yandex_metric 0.1

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ source "http://rubygems.org"
2
+ # Add dependencies required to use your gem here.
3
+ # Example:
4
+ # gem "activesupport", ">= 2.3.5"
5
+
6
+ # Add dependencies to develop your gem here.
7
+ # Include everything needed to run rake, tests, features, etc.
8
+ group :development do
9
+ gem "shoulda", ">= 0"
10
+ gem "bundler", "~> 1.0.0"
11
+ gem "jeweler", "~> 1.6.4"
12
+ gem "rcov", ">= 0"
13
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2011 bskaplou
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,53 @@
1
+ = yandex_metric
2
+
3
+ Simple wrapper over Yandex Metric REST API.
4
+
5
+ == Methods
6
+
7
+ Yandex Metric API => Ruby
8
+
9
+ GET /counters => get_counters
10
+
11
+ POST /counter/{id}/filters => post_counter_filters
12
+
13
+ DELETE /counter/{id}/grant/{user_login} => delete_counter_grant
14
+
15
+ All methods are taking the only argument which is hash.
16
+ {something} in request path will be raplaced with args['something'].
17
+
18
+ == Examples
19
+
20
+ ym = YM::YandexMetric.new({
21
+ :username => username,
22
+ :password => password,
23
+ :client_id => client_id,
24
+ :client_secret => client_secret,
25
+ })
26
+
27
+ cid = ym.get_counters['counters'][0]['id']
28
+ puts ym.get_counter_goals({'id' => cid})
29
+ yesterday = (Time.new - 86400).strftime '%Y%m%d'
30
+ today = Time.new.strftime '%Y%m%d'
31
+ p = {
32
+ 'id' => cid,
33
+ 'date1' => yesterday,
34
+ 'date2' => today,
35
+ 'group' => 'day'
36
+ }
37
+ puts ym.get_stat_traffic_summary(p)
38
+
39
+ == Contributing to yandex_metric
40
+
41
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
42
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
43
+ * Fork the project
44
+ * Start a feature/bugfix branch
45
+ * Commit and push until you are happy with your contribution
46
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
47
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
48
+
49
+ == Copyright
50
+
51
+ Copyright (c) 2011 bskaplou. See LICENSE.txt for
52
+ further details.
53
+
data/Rakefile ADDED
@@ -0,0 +1,54 @@
1
+ # encoding: utf-8
2
+
3
+ require 'rubygems'
4
+ require 'bundler'
5
+ begin
6
+ Bundler.setup(:default, :development)
7
+ rescue Bundler::BundlerError => e
8
+ $stderr.puts e.message
9
+ $stderr.puts "Run `bundle install` to install missing gems"
10
+ exit e.status_code
11
+ end
12
+ require 'rake'
13
+
14
+ require 'jeweler'
15
+ Jeweler::Tasks.new do |gem|
16
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
17
+ gem.name = "yandex_metric"
18
+ gem.homepage = "http://github.com/bskaplou/yandex_metric"
19
+ gem.license = "MIT"
20
+ gem.summary = %Q{Simple API for Yandex Metric manipulations through Yandex Metric API}
21
+ gem.description = %Q{YandexMetric hides OAuth from user and converts Yandex Metric REST methods into ruby methods}
22
+ gem.email = "bskaplou@gmail.com"
23
+ gem.authors = ["bskaplou"]
24
+ gem.version = File.read 'VERSION'
25
+ # dependencies defined in Gemfile
26
+ end
27
+ Jeweler::RubygemsDotOrgTasks.new
28
+
29
+ require 'rake/testtask'
30
+ Rake::TestTask.new(:test) do |test|
31
+ test.libs << 'lib' << 'test'
32
+ test.pattern = 'test/**/test_*.rb'
33
+ test.verbose = true
34
+ end
35
+
36
+ require 'rcov/rcovtask'
37
+ Rcov::RcovTask.new do |test|
38
+ test.libs << 'test'
39
+ test.pattern = 'test/**/test_*.rb'
40
+ test.verbose = true
41
+ test.rcov_opts << '--exclude "gems/*"'
42
+ end
43
+
44
+ task :default => :test
45
+
46
+ require 'rdoc/task'
47
+ Rake::RDocTask.new do |rdoc|
48
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
49
+
50
+ rdoc.rdoc_dir = 'rdoc'
51
+ rdoc.title = "yandex_metric #{version}"
52
+ rdoc.rdoc_files.include('README*')
53
+ rdoc.rdoc_files.include('lib/**/*.rb')
54
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1
@@ -0,0 +1,134 @@
1
+ require 'net/https'
2
+ require 'net/http'
3
+ require 'cgi'
4
+ require 'json'
5
+
6
+ module YM
7
+ SSL_PORT = 443
8
+ TIMEOUT = 50
9
+
10
+ class Client
11
+ def self.encode_params prms
12
+ prms.inject ('') { |acc, (k, v)|
13
+ acc + CGI::escape(k) + '=' + CGI::escape(v.to_s) + '&'
14
+ }
15
+ end
16
+
17
+ def self.default_args
18
+ {:port => SSL_PORT,
19
+ :ssl => true,
20
+ :timeout => TIMEOUT}
21
+ end
22
+
23
+ def self.client args = {}
24
+ args = default_args.merge args
25
+ cli = Net::HTTP.new args[:host], args[:port]
26
+ cli.use_ssl = args[:ssl]
27
+ #Not enough percise timeout but will not block execution
28
+ cli.read_timeout = cli.open_timeout = cli.ssl_timeout = args[:timeout]
29
+ cli
30
+ end
31
+
32
+ def self.result res
33
+ raise res.value unless res.instance_of? Net::HTTPOK
34
+ res.body
35
+ end
36
+
37
+ def self.get args = {}
38
+ qpath = args[:path] + '?' + encode_params(args[:params])
39
+ result(client(args).get2 qpath, args[:headers])
40
+ end
41
+
42
+ def self.post args = {}
43
+ result(client(args).post2 args[:path], encode_params(args[:params]))
44
+ end
45
+
46
+ def self.put args = {}
47
+ '{"error" : "not implemented yet"}'
48
+ end
49
+
50
+ def self.delete args = {}
51
+ '{"error" : "not implemented yet"}'
52
+ end
53
+ end
54
+
55
+ class YandexMetric
56
+ OAUTH_HOST = 'oauth.yandex.ru'
57
+ OAUTH_PORT = SSL_PORT
58
+ OAUTH_PATH = '/token'
59
+ API_HOST = 'api-metrika.yandex.ru'
60
+ API_PORT = SSL_PORT
61
+ SSL = true
62
+
63
+ def default_options
64
+ {:timeout => TIMEOUT}
65
+ end
66
+
67
+ def default_headers
68
+ {'Accept' => 'application/x-yametrika+json'}
69
+ end
70
+
71
+ attr_reader :options
72
+ def initialize options = {}
73
+ @options = default_options.merge options
74
+ end
75
+
76
+ def init_token
77
+ params = {'grant_type' => 'password'}
78
+ [:username, :password, :client_id, :client_secret].each do |key|
79
+ options.has_key? key or raise "#{key} is not defined"
80
+ params[key.to_s] = options[key]
81
+ end
82
+ args = {
83
+ :host => OAUTH_HOST,
84
+ :port => OAUTH_PORT,
85
+ :ssl => SSL,
86
+ :path => OAUTH_PATH,
87
+ :params => params,
88
+ :timeout => options[:timeout]
89
+ }
90
+ JSON.parse(Client.post args)['access_token']
91
+ end
92
+
93
+ def get_token
94
+ @token ||= init_token
95
+ end
96
+
97
+ def generic_method method, path, params
98
+ headers = default_headers.merge({'Authorization' => ("OAuth " + get_token)})
99
+ args = {
100
+ :host => API_HOST,
101
+ :port => API_PORT,
102
+ :ssl => SSL,
103
+ :path => path,
104
+ :params => params,
105
+ :headers => headers,
106
+ :timeout => options[:timeout]
107
+ }
108
+ JSON.parse(Client.send method, args)
109
+ end
110
+
111
+ def self.method_name method, path
112
+ #/path/{id}/param => path_param
113
+ method_tail = path[1..-1].gsub(/\/{[a-zA-Z0-9_]+}/, '').gsub(/\//, '_')
114
+ #'GET /path/{id}/param' => 'get_path_param'
115
+ method.downcase + '_' + method_tail
116
+ end
117
+
118
+ def self.api_method description, path, methods, param_desc = ''
119
+ #path sometimes starts with '/' but not always
120
+ path = '/' + path unless path[0] == '/'
121
+ methods.split(' ').each do |m|
122
+ define_method method_name(m, path) do |args = {}|
123
+ #/path/{id}/param => /path/id_value/param
124
+ real_path = path.gsub(/\{[a-zA-Z0-9_]+\}/) {|id|
125
+ args.delete(id[1..-2])
126
+ }
127
+ generic_method m.downcase.to_sym, real_path, args
128
+ end
129
+ end
130
+ end
131
+ end
132
+ end
133
+
134
+ load 'yandex_metric_methods.rb'
@@ -0,0 +1,46 @@
1
+ module YM
2
+ YandexMetric.api_method 'Список счетчиков','/counters','GET POST','-'
3
+ YandexMetric.api_method 'Счетчик','/counter/{id}','GET PUT DELETE','id ― числовой идентификатор счетчика.'
4
+ YandexMetric.api_method 'Список целей счетчика','/counter/{id}/goals','GET POST','-'
5
+ YandexMetric.api_method 'Цель счетчика','/counter/{id}/goal/{goal_id}','GET PUT DELETE','goal_id ― числовой идентификатор цели.'
6
+ YandexMetric.api_method 'Список фильтров счетчика','/counter/{id}/filters','GET POST','filter_id ― числовой идентификатор фильтра.'
7
+ YandexMetric.api_method 'Фильтр счетчика','/counter/{id}/filter/{filter_id}','GET PUT DELETE','filter_id ― числовой идентификатор фильтра.'
8
+ YandexMetric.api_method 'Список операций счетчика','/counter/{id}/operations','GET POST','-'
9
+ YandexMetric.api_method 'Операция счетчика','/counter/{id}/operation/{operation_id}','GET PUT DELETE','operation_id ― числовой идентификатор операции.'
10
+ YandexMetric.api_method 'Список гостевых доступов счетчика','/counter/{id}/grants','GET POST','-'
11
+ YandexMetric.api_method 'Право доступа к счетчику','/counter/{id}/grant/{user_login}','GET PUT DELETE','user_login ― логин пользователя, которому выдан гостевой доступ. Для публичной статистики вместо логина пользователя указывается «0».'
12
+ YandexMetric.api_method 'Список собственных представителей','/delegates','GET PUT POST','-'
13
+ YandexMetric.api_method 'Представитель','/delegate/{user_login}','DELETE','user_login ― логин пользователя, которому выдан полный доступ.'
14
+ YandexMetric.api_method 'Список аккаунтов (прав на представительство)','/accounts','GET PUT','-'
15
+ YandexMetric.api_method 'Аккаунт','/account/{user_login}','DELETE','user_login ― логин владельца аккаунта.'
16
+ YandexMetric.api_method 'Посещаемость','stat/traffic/summary','GET'
17
+ YandexMetric.api_method 'Вовлечение','stat/traffic/deepness','GET'
18
+ YandexMetric.api_method 'По времени суток','stat/traffic/hourly','GET'
19
+ YandexMetric.api_method 'Нагрузка на сайт','stat/traffic/load','GET'
20
+ YandexMetric.api_method 'Сводка','stat/sources/summary','GET'
21
+ YandexMetric.api_method 'Сайты','stat/sources/sites','GET'
22
+ YandexMetric.api_method 'Поисковые системы','stat/sources/search_engines','GET'
23
+ YandexMetric.api_method 'Поисковые фразы','stat/sources/phrases','GET'
24
+ YandexMetric.api_method 'Рекламные системы','stat/sources/marketing','GET'
25
+ YandexMetric.api_method 'Директ ― сводка','stat/sources/direct/summary','GET'
26
+ YandexMetric.api_method 'Директ ― площадки','stat/sources/direct/platforms','GET'
27
+ YandexMetric.api_method 'Директ ― регионы','stat/sources/direct/regions','GET'
28
+ YandexMetric.api_method 'Метки','stat/sources/tags','GET'
29
+ YandexMetric.api_method 'Популярное содержание','stat/content/popular','GET'
30
+ YandexMetric.api_method 'Страницы входа','stat/content/entrance','GET'
31
+ YandexMetric.api_method 'Страницы выхода','stat/content/exit','GET'
32
+ YandexMetric.api_method 'Заголовки страниц','stat/content/titles','GET'
33
+ YandexMetric.api_method 'Параметры URL','stat/content/url_param','GET'
34
+ YandexMetric.api_method 'Отчет по Странам мира','stat/geo','GET'
35
+ YandexMetric.api_method 'Пол и возраст','stat/demography/age_gender','GET'
36
+ YandexMetric.api_method 'Половозрастная структура','stat/demography/structure','GET'
37
+ YandexMetric.api_method 'Браузеры','stat/tech/browsers','GET'
38
+ YandexMetric.api_method 'Операционные системы','stat/tech/os','GET'
39
+ YandexMetric.api_method 'Разрешения дисплеев','stat/tech/display','GET'
40
+ YandexMetric.api_method 'Мобильные устройства','stat/tech/mobile','GET'
41
+ YandexMetric.api_method 'Версии Flash','stat/tech/flash','GET'
42
+ YandexMetric.api_method 'Версии Silverlight','stat/tech/silverlight','GET'
43
+ YandexMetric.api_method 'Версии .NET','stat/tech/dotnet','GET'
44
+ YandexMetric.api_method 'Наличие Java','stat/tech/java','GET'
45
+ YandexMetric.api_method 'Наличие Cookies','stat/tech/cookies','GET'
46
+ end
data/test/helper.rb ADDED
@@ -0,0 +1,18 @@
1
+ require 'rubygems'
2
+ require 'bundler'
3
+ begin
4
+ Bundler.setup(:default, :development)
5
+ rescue Bundler::BundlerError => e
6
+ $stderr.puts e.message
7
+ $stderr.puts "Run `bundle install` to install missing gems"
8
+ exit e.status_code
9
+ end
10
+ require 'test/unit'
11
+ require 'shoulda'
12
+
13
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
14
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
15
+ require 'yandex_metric'
16
+
17
+ class Test::Unit::TestCase
18
+ end
@@ -0,0 +1,7 @@
1
+ require 'helper'
2
+
3
+ class TestYandexMetric < Test::Unit::TestCase
4
+ should "probably rename this file and start testing for real" do
5
+ #flunk "hey buddy, you should probably rename this file and start testing for real"
6
+ end
7
+ end
@@ -0,0 +1,59 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = "yandex_metric"
8
+ s.version = "0.1"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["bskaplou"]
12
+ s.date = "2011-11-14"
13
+ s.description = "YandexMetric hides OAuth from user and converts Yandex Metric REST methods into ruby methods"
14
+ s.email = "bskaplou@gmail.com"
15
+ s.extra_rdoc_files = [
16
+ "LICENSE.txt",
17
+ "README.rdoc"
18
+ ]
19
+ s.files = [
20
+ ".document",
21
+ "Gemfile",
22
+ "LICENSE.txt",
23
+ "README.rdoc",
24
+ "Rakefile",
25
+ "VERSION",
26
+ "lib/yandex_metric.rb",
27
+ "lib/yandex_metric_methods.rb",
28
+ "test/helper.rb",
29
+ "test/test_yandex_metric.rb",
30
+ "yandex_metric.gemspec"
31
+ ]
32
+ s.homepage = "http://github.com/bskaplou/yandex_metric"
33
+ s.licenses = ["MIT"]
34
+ s.require_paths = ["lib"]
35
+ s.rubygems_version = "1.8.10"
36
+ s.summary = "Simple API for Yandex Metric manipulations through Yandex Metric API"
37
+
38
+ if s.respond_to? :specification_version then
39
+ s.specification_version = 3
40
+
41
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
42
+ s.add_development_dependency(%q<shoulda>, [">= 0"])
43
+ s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
44
+ s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"])
45
+ s.add_development_dependency(%q<rcov>, [">= 0"])
46
+ else
47
+ s.add_dependency(%q<shoulda>, [">= 0"])
48
+ s.add_dependency(%q<bundler>, ["~> 1.0.0"])
49
+ s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
50
+ s.add_dependency(%q<rcov>, [">= 0"])
51
+ end
52
+ else
53
+ s.add_dependency(%q<shoulda>, [">= 0"])
54
+ s.add_dependency(%q<bundler>, ["~> 1.0.0"])
55
+ s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
56
+ s.add_dependency(%q<rcov>, [">= 0"])
57
+ end
58
+ end
59
+
metadata ADDED
@@ -0,0 +1,111 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yandex_metric
3
+ version: !ruby/object:Gem::Version
4
+ prerelease:
5
+ version: "0.1"
6
+ platform: ruby
7
+ authors:
8
+ - bskaplou
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+
13
+ date: 2011-11-14 00:00:00 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: shoulda
17
+ requirement: &id001 !ruby/object:Gem::Requirement
18
+ none: false
19
+ requirements:
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: "0"
23
+ type: :development
24
+ prerelease: false
25
+ version_requirements: *id001
26
+ - !ruby/object:Gem::Dependency
27
+ name: bundler
28
+ requirement: &id002 !ruby/object:Gem::Requirement
29
+ none: false
30
+ requirements:
31
+ - - ~>
32
+ - !ruby/object:Gem::Version
33
+ version: 1.0.0
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: *id002
37
+ - !ruby/object:Gem::Dependency
38
+ name: jeweler
39
+ requirement: &id003 !ruby/object:Gem::Requirement
40
+ none: false
41
+ requirements:
42
+ - - ~>
43
+ - !ruby/object:Gem::Version
44
+ version: 1.6.4
45
+ type: :development
46
+ prerelease: false
47
+ version_requirements: *id003
48
+ - !ruby/object:Gem::Dependency
49
+ name: rcov
50
+ requirement: &id004 !ruby/object:Gem::Requirement
51
+ none: false
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: "0"
56
+ type: :development
57
+ prerelease: false
58
+ version_requirements: *id004
59
+ description: YandexMetric hides OAuth from user and converts Yandex Metric REST methods into ruby methods
60
+ email: bskaplou@gmail.com
61
+ executables: []
62
+
63
+ extensions: []
64
+
65
+ extra_rdoc_files:
66
+ - LICENSE.txt
67
+ - README.rdoc
68
+ files:
69
+ - .document
70
+ - Gemfile
71
+ - LICENSE.txt
72
+ - README.rdoc
73
+ - Rakefile
74
+ - VERSION
75
+ - lib/yandex_metric.rb
76
+ - lib/yandex_metric_methods.rb
77
+ - test/helper.rb
78
+ - test/test_yandex_metric.rb
79
+ - yandex_metric.gemspec
80
+ homepage: http://github.com/bskaplou/yandex_metric
81
+ licenses:
82
+ - MIT
83
+ post_install_message:
84
+ rdoc_options: []
85
+
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ none: false
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ hash: 664816113
94
+ segments:
95
+ - 0
96
+ version: "0"
97
+ required_rubygems_version: !ruby/object:Gem::Requirement
98
+ none: false
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: "0"
103
+ requirements: []
104
+
105
+ rubyforge_project:
106
+ rubygems_version: 1.8.10
107
+ signing_key:
108
+ specification_version: 3
109
+ summary: Simple API for Yandex Metric manipulations through Yandex Metric API
110
+ test_files: []
111
+