telphin_api 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: c44141d306d2360eee15812c692ee1a45be00527
4
+ data.tar.gz: 1a8daf10b99b12993a9c8123af8e0f3cd7809fcd
5
+ SHA512:
6
+ metadata.gz: 93962713545230f25507ebcc1e5bd7539d969d26e589203c5acbb43699018815d9f51a1018b07a8eec43a3449466b27465b7aed72bec868023660259cdbfbe0f
7
+ data.tar.gz: 5b0f68ef059f86a7dee318fccfd04e46d783b9cd5f37c906b1c6c8599c42fe6065e2fad416afb327286342651ca791de503789bd0734cc16a930514bad8be049
@@ -0,0 +1,10 @@
1
+ *.gem
2
+ .bundle
3
+ Gemfile.lock
4
+ pkg/*
5
+ tmp/*
6
+ .yardoc/*
7
+ .idea
8
+ spec/support/credentials.yml
9
+ doc/
10
+ *.iml
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --color --format=documentation
@@ -0,0 +1,19 @@
1
+ language: ruby
2
+
3
+ rvm:
4
+ - 1.9.3
5
+ - 2.0
6
+ - 2.1
7
+ - 2.2
8
+ - ruby-head
9
+ - jruby-19mode
10
+ - jruby-9.0.0.0
11
+ - jruby-head
12
+
13
+ jdk:
14
+ - oraclejdk8
15
+
16
+ matrix:
17
+ allow_failures:
18
+ - rvm: ruby-head
19
+ - rvm: jruby-head
@@ -0,0 +1,3 @@
1
+ --files README.md,CHANGELOG.md
2
+ --markup markdown
3
+ --markup-provider redcarpet
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in telphin_api.gemspec
4
+ gemspec
@@ -0,0 +1,14 @@
1
+ guard 'rspec', all_on_start: true, all_after_pass: true, cmd: 'bin/rspec' do
2
+ watch(%r{^spec/.+_spec\.rb$})
3
+ watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
4
+ watch('spec/spec_helper.rb') { 'spec' }
5
+
6
+ watch('spec/support/mechanized_authorization.rb') { 'spec/integration_spec.rb' }
7
+ end
8
+
9
+
10
+ guard 'yard' do
11
+ watch(%r{lib/.+\.rb})
12
+ end unless defined?(JRUBY_VERSION)
13
+
14
+ notification :terminal_notifier, activate: 'com.googlecode.iTerm2'
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2015 Konstantin Tyutyunnikov
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.
@@ -0,0 +1,197 @@
1
+ ## telphin_api [![Build Status](https://secure.travis-ci.org/rootooz/telphin_api.png)](http://travis-ci.org/rootooz/telphin_api) [![Gem Version](https://badge.fury.io/rb/telphin_api.png)](http://badge.fury.io/rb/telphin_api) [![Dependency Status](https://gemnasium.com/7even/telphin_api.png)](https://gemnasium.com/7even/telphin_api) [![Code Climate](https://codeclimate.com/github/7even/telphin_api.png)](https://codeclimate.com/github/7even/telphin_api)
2
+
3
+ `telphin_api` — ruby-адаптер для Телфин. Он позволяет вызывать методы API, а также поддерживает получение токена для работы с API.
4
+
5
+ ## Установка
6
+
7
+ ``` ruby
8
+ # Gemfile
9
+ gem 'telphin_api'
10
+ ```
11
+
12
+ или просто
13
+
14
+ ``` sh
15
+ $ gem install telphin_api
16
+ ```
17
+
18
+ ## Использование
19
+
20
+ ### Вызов методов
21
+
22
+ ``` ruby
23
+ # создаем клиент
24
+ @tph = TelphinApi::Client.new
25
+ # и вызываем методы API
26
+ @tph.extensions.phone_call_events(:user_id => '@me', :extension_number => '00000*101', :method => :get)
27
+
28
+ # в ruby принято использовать snake_case в названиях методов,
29
+ # поэтому extensions.phoneCallEvents становится extensions.phone_call_events
30
+ @tph.extensions.phone_call_events
31
+
32
+ # большинство методов возвращает структуры Hashie::Mash
33
+ # и массивы из них
34
+ call_events.first.id # => bMf0iCJneuA0YWawjUOjVTzAGn
35
+ call_events.first.url # => https://site/api/telphin/call/out
36
+ call_events.first.method # => 0
37
+ call_events.first.status # => 1
38
+ call_events.first.type # => 1
39
+
40
+ # если метод, возвращающий массив, вызывается с блоком,
41
+ # то блок будет выполнен для каждого элемента,
42
+ # и метод вернет обработанный массив
43
+ @tph.extensions.phone_call_events(:user_id => '@me', :extension_number => '00000*101', :method => :get) do |event|
44
+ "#{event.id} '#{event.url}' #{event.method}"
45
+ end
46
+ # => ["bMf0iCJneuA0YWawjUOjVTzAGn 'https://site/api/telphin/call/out' 0"]
47
+ ```
48
+
49
+ ### Авторизация
50
+
51
+ Для авторизации необходимо задать параметры `app_key` (Ключ клиента), `app_secret` (Секрет клиента) и `site` (адрес вашего API сервера, полученного при заключении договора) в настройках `TelphinApi.configure`. Более подробно о конфигурировании `telphin_api` см. далее в соответствующем разделе.
52
+
53
+ `telphin_api` предоставляет метод `TelphinApi.authorize`, который делает запрос к Телфин, получает токен и создает клиент:
54
+
55
+ ``` ruby
56
+ @tph = TelphinApi.authorize
57
+ # и теперь можно вызывать методы API на объекте @tph
58
+ @tph.token
59
+ ```
60
+
61
+ Клиент будет содержать token пользователя, авторизовавшего приложение
62
+ Также в этот момент полезно сохранить полученный токен в БД либо в сессии, чтобы использовать их повторно:
63
+
64
+ ``` ruby
65
+ current_user.token = @vk.token
66
+ current_user.save
67
+ # позже
68
+ @tph = TelphinApi::Client.new(current_user.token)
69
+ ```
70
+
71
+ ### Прочее
72
+
73
+ Если клиент API (объект класса `TelphinApi::Client`) был создан с помощью метода `TelphinApi.authorize`, он будет содержать информацию о времени истечения токена (`expires_at`). Получить их можно с помощью соответствующих методов:
74
+
75
+ ``` ruby
76
+ @tph = TelphinApi.authorize
77
+ # => #<TelphinApi::Client:0x007fa578f00ad0>
78
+ tph.expires_at # => 2015-12-18 23:22:55 +0400
79
+ # можно проверить, истекло ли время жизни токена
80
+ tph.expired? # => false
81
+ ```
82
+
83
+ Чтобы создать короткий синоним `TPH` для модуля `TelphinApi`, достаточно вызвать метод `TelphinApi.register_alias`:
84
+
85
+ ``` ruby
86
+ TelphinApi.register_alias
87
+ TPH::Client.new # => #<TelphinApi::Client:0x007fa578d6d948>
88
+ ```
89
+
90
+ При необходимости можно удалить синоним методом `TelphinApi.unregister_alias`:
91
+
92
+ ``` ruby
93
+ TPH.unregister_alias
94
+ TPH # => NameError: uninitialized constant VK
95
+ ```
96
+
97
+ ### Обработка ошибок
98
+
99
+ Если Телфин API возвращает ошибку, выбрасывается исключение класса `TelphinApi::Error`.
100
+
101
+ ``` ruby
102
+ tph = TPH::Client.new
103
+ @tph.extensions.phone_call_events
104
+ # TelphinApi::Error: Telphin returned an error extension_invalid: 'Value supplied in the URI-Fragment as extension is invalid. The parameter must reference the number of an existing extension and cannot be set to @self.'
105
+ ```
106
+
107
+ ### Логгирование
108
+
109
+ `telphin_api` логгирует служебную информацию о запросах при вызове методов.
110
+ По умолчанию все пишется в `STDOUT`, но в настройке можно указать
111
+ любой другой совместимый логгер, например `Rails.logger`.
112
+
113
+ Есть возможность логгирования 3 типов информации,
114
+ каждому соответствует ключ в глобальных настройках.
115
+
116
+ | | ключ настройки | по умолчанию | уровень логгирования |
117
+ | ---------------------- | --------------- | ------------ | -------------------- |
118
+ | URL запроса | `log_requests` | `true` | `debug` |
119
+ | JSON ответа при ошибке | `log_errors` | `true` | `warn` |
120
+ | JSON удачного ответа | `log_responses` | `false` | `debug` |
121
+
122
+ Таким образом, в rails-приложении с настройками по умолчанию в production
123
+ записываются только ответы сервера при ошибках;
124
+ в development также логгируются URL-ы запросов.
125
+
126
+
127
+ ## Настройка
128
+
129
+ Глобальные параметры `telphin_api` задаются в блоке `TelphinApi.configure` следующим образом:
130
+
131
+ ``` ruby
132
+ TelphinApi.configure do |config|
133
+ # параметры, необходимые для авторизации средствами telphin_api
134
+ # (не нужны при использовании сторонней авторизации)
135
+ config.app_key = '123'
136
+ config.app_secret = 'AbCdE654'
137
+ config.site = 'https://pbx.telphin.ru/uapi' # По умолчанию https://pbx.telphin.ru/uapi
138
+
139
+ # faraday-адаптер для сетевых запросов
140
+ config.adapter = :net_http
141
+
142
+ # параметры для faraday-соединения
143
+ config.faraday_options = {
144
+ ssl: {
145
+ ca_path: '/usr/lib/ssl/certs'
146
+ },
147
+ proxy: {
148
+ uri: 'http://proxy.example.com',
149
+ user: 'foo',
150
+ password: 'bar'
151
+ }
152
+ }
153
+ # максимальное количество повторов запроса при ошибках
154
+ config.max_retries = 2
155
+
156
+ # логгер
157
+ config.logger = Rails.logger
158
+ config.log_requests = true # URL-ы запросов
159
+ config.log_errors = true # ошибки
160
+ config.log_responses = false # удачные ответы
161
+ end
162
+ ```
163
+
164
+ По умолчанию для HTTP-запросов используется `Net::HTTP`; можно выбрать
165
+ [любой другой адаптер](https://github.com/technoweenie/faraday/blob/master/lib/faraday/adapter.rb),
166
+ поддерживаемый `faraday`.
167
+
168
+ При необходимости можно указать параметры для faraday-соединения &mdash; например,
169
+ параметры прокси-сервера или путь к SSL-сертификатам.
170
+
171
+ Чтобы сгенерировать файл с настройками по умолчанию в rails-приложении,
172
+ можно воспользоваться генератором `telphin_api:install`:
173
+
174
+ ``` sh
175
+ $ cd /path/to/app
176
+ $ rails generate telphin_api:install
177
+ ```
178
+
179
+ ## JSON-парсер
180
+
181
+ `telphin_api` использует парсер [Oj](https://github.com/ohler55/oj)
182
+
183
+ Также в библиотеке `multi_json` (обертка для различных JSON-парсеров,
184
+ которая выбирает самый быстрый из установленных в системе и парсит им)
185
+ `Oj` поддерживается и имеет наивысший приоритет; поэтому если он установлен
186
+ в системе, `multi_json` будет использовать именно его.
187
+
188
+ ## Участие в разработке
189
+
190
+ Если вы хотите поучаствовать в разработке проекта, форкните репозиторий,
191
+ положите свои изменения в отдельную ветку, покройте их спеками
192
+ и отправьте мне pull request.
193
+
194
+ `telphin_api` тестируется под MRI `2.1.2`.
195
+ Если что-то работает неправильно, либо вообще не работает,
196
+ то это следует считать багом, и написать об этом
197
+ в [issues на Github](https://github.com/rootooz/telphin_api/issues).
@@ -0,0 +1,13 @@
1
+ require 'bundler/gem_tasks'
2
+
3
+ desc 'Fires up the console with preloaded telphin_api'
4
+ task :console do
5
+ sh 'pry -I ./lib -r ./lib/telphin_api'
6
+ end
7
+
8
+ require 'rspec/core/rake_task'
9
+ RSpec::Core::RakeTask.new do |t|
10
+ t.rspec_opts = '--color --format doc'
11
+ end
12
+
13
+ task default: :spec
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ #
3
+ # This file was generated by Bundler.
4
+ #
5
+ # The application 'rspec' is installed as part of a gem, and
6
+ # this file is here to facilitate running it.
7
+ #
8
+
9
+ require 'pathname'
10
+ ENV['BUNDLE_GEMFILE'] ||= Pathname.new(__FILE__).expand_path.join('../../Gemfile').to_s
11
+
12
+ require 'rubygems'
13
+ require 'bundler/setup'
14
+
15
+ load Gem.bin_path('rspec-core', 'rspec')
@@ -0,0 +1,7 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gem 'sinatra'
4
+ gem 'sinatra-reloader'
5
+ gem 'telphin_api', :path => '../'
6
+
7
+
@@ -0,0 +1,23 @@
1
+ require 'bundler/setup'
2
+ require 'sinatra'
3
+ require 'telphin_api'
4
+
5
+ class OmniTelphinDemo < Sinatra::Base
6
+ use Rack::Session::Cookie
7
+
8
+ TelphinApi.configure do |config|
9
+ # Authorization parameters (not needed when using an external authorization):
10
+ config.app_key = 'F~PUJXc8X5_2vUy7W5B~IBjXm6Hv~dRT'
11
+ config.app_secret = 'x~X1r206MB~ckpYhb6c.W4ch4OLx_9If'
12
+ end
13
+
14
+ get '/' do
15
+ @tph = TelphinApi.authorize
16
+ ar = @tph.extensions.phone_call_events(:user_id => '@me', :extension_number => '17608s*101', :method => :get)
17
+
18
+ abort ar.inspect
19
+ end
20
+
21
+ end
22
+
23
+ OmniTelphinDemo.run!
@@ -0,0 +1,2 @@
1
+ Description:
2
+ Create a telphin_api config file in config/initializers/telphin_api.rb.
@@ -0,0 +1,10 @@
1
+ # A rails generator `telphin_api:install`.
2
+ # It creates a config file in `config/initializers/telphin_api.rb`.
3
+ class TelphinApi::InstallGenerator < Rails::Generators::Base
4
+ source_root File.expand_path('../templates', __FILE__)
5
+
6
+ # Creates the config file.
7
+ def create_initializer
8
+ copy_file 'initializer.rb', 'config/initializers/telphin_api.rb'
9
+ end
10
+ end
@@ -0,0 +1,25 @@
1
+ TelphinApi.configure do |config|
2
+ # Authorization parameters (not needed when using an external authorization):
3
+ # config.app_key = '123'
4
+ # config.app_secret = 'AbCdE654'
5
+ # config.site = 'https://pbx.telphin.ru/uapi'
6
+
7
+ # Faraday adapter to make requests with:
8
+ # config.adapter = :net_http
9
+
10
+ # Logging parameters:
11
+ # log everything through the rails logger
12
+ config.logger = Rails.logger
13
+
14
+ # log requests' URLs
15
+ # config.log_requests = true
16
+
17
+ # log response JSON after errors
18
+ # config.log_errors = true
19
+
20
+ # log response JSON after successful responses
21
+ # config.log_responses = false
22
+ end
23
+
24
+ # create a short alias TPH for TelphinApi module
25
+ # TelphinApi.register_alias
@@ -0,0 +1,39 @@
1
+ require 'faraday'
2
+ require 'faraday_middleware'
3
+ require 'oj' unless defined?(JRUBY_VERSION)
4
+ require 'faraday_middleware/multi_json'
5
+ require 'oauth2'
6
+ require 'yaml'
7
+ require 'hashie'
8
+
9
+ require 'telphin_api/version'
10
+ require 'telphin_api/error'
11
+ require 'telphin_api/configuration'
12
+ require 'telphin_api/authorization'
13
+ require 'telphin_api/utils'
14
+ require 'telphin_api/api'
15
+ require 'telphin_api/resolver'
16
+ require 'telphin_api/resolvable'
17
+ require 'telphin_api/client'
18
+ require 'telphin_api/namespace'
19
+ require 'telphin_api/method'
20
+ require 'telphin_api/result'
21
+ require 'telphin_api/logger'
22
+
23
+ # Main module.
24
+ module TelphinApi
25
+ extend TelphinApi::Configuration
26
+ extend TelphinApi::Authorization
27
+
28
+ class << self
29
+ # Creates a short alias `TPH` for `TelphinApi` module.
30
+ def register_alias
31
+ Object.const_set(:TPH, TelphinApi)
32
+ end
33
+
34
+ # Removes the `TPH` alias.
35
+ def unregister_alias
36
+ Object.send(:remove_const, :TPH) if defined?(TPH)
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,59 @@
1
+ module TelphinApi
2
+ # A low-level module which handles the requests to Telphin API and returns their results as mashes.
3
+ #
4
+ # It uses Faraday with middleware underneath the hood.
5
+ module API
6
+ class << self
7
+ # API method call.
8
+ # @param [String] full_method A full name of the method.
9
+ # @param [Hash] args Method arguments.
10
+ # @param [String] token The access token.
11
+ # @return [Hashie::Mash] Mashed server response.
12
+ def call(full_method, args = {}, token = nil)
13
+ namespace = full_method.first
14
+ action = full_method.last
15
+
16
+ http_method = args.delete(:method)
17
+ http_method ||= :get
18
+
19
+ user_id = args.delete(:user_id)
20
+ extension_number = args.delete(:extension_number)
21
+ id = args.delete(:id)
22
+
23
+ flat_arguments = Utils.flatten_arguments(args)
24
+ url = [TelphinApi.site, namespace, user_id, extension_number, action].join('/')
25
+ url = url + '/' + id unless id.nil?
26
+ connection = connection(url: url, token: token)
27
+
28
+ if flat_arguments.empty?
29
+ connection.send(http_method).body
30
+ else
31
+ connection.send(http_method, flat_arguments).body
32
+ end
33
+ end
34
+
35
+ # Faraday connection.
36
+ # @param [Hash] options Connection options.
37
+ # @option options [String] :url Connection URL (either full or just prefix).
38
+ # @option options [String] :token OAuth2 access token (not used if omitted).
39
+ # @return [Faraday::Connection] Created connection.
40
+ def connection(options = {})
41
+ url = options.delete(:url)
42
+ token = options.delete(:token)
43
+ url = url + '?accessRequestToken=' + token
44
+
45
+ Faraday.new(url, TelphinApi.faraday_options) do |builder|
46
+ builder.request :multipart
47
+ builder.request :url_encoded
48
+ builder.request :retry, TelphinApi.max_retries
49
+
50
+ builder.response :telphin_logger
51
+ builder.response :mashify
52
+ builder.response :multi_json, preserve_raw: true
53
+
54
+ builder.adapter TelphinApi.adapter
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end