domoscio_admin 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a790c17d0b0a88271416a5f4a7fa5f2a06e4bb5b0a751b9d1e91483bc006d864
4
+ data.tar.gz: bbd25ad9fb705fbea08d2e6099355c31e39c6cece6b3c07d0673d75f6887a422
5
+ SHA512:
6
+ metadata.gz: a7f80348978cb8817f9b4bdbea72d96108226bd76090a2cf5181054f364ce010f1ef6fcc8e55c15f3c2f0601fd152e2717f8c674a7480abca0cb75e8296b3eee
7
+ data.tar.gz: edf7e8648248865b3e5a96aa704f896ceb786b073aa906b507b7b92f0ab1a1a1d8124264a0bc537aedaa6804aa01af3a8f331fd85ca7abd2da0bacb91822b28b
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2014 YOURNAME
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.md ADDED
@@ -0,0 +1,69 @@
1
+ # DomoscioAdmin
2
+
3
+ This README would document whatever steps are necessary to get the DomoscioAdmin Ruby SDK up and running.
4
+
5
+ ## Getting Started
6
+
7
+ These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
8
+
9
+ ### Prerequisites
10
+
11
+ DomoscioAdmin works with Rails 3.2 onwards.
12
+
13
+ ### Installing
14
+
15
+ Add it to your Gemfile with:
16
+
17
+ ```ruby
18
+ gem 'domoscio_admin', '0.1.0', git: 'git://github.com/Celumproject/domoscio-admin-sdk-ruby', branch: 'master'
19
+ ```
20
+
21
+ Then run `bundle install`
22
+
23
+ Next, you need to run the generator:
24
+
25
+ ```console
26
+ $ rails generate domoscio_admin:install
27
+ ```
28
+
29
+ Then you have to configure the `ENV['DOMOSCIO_ID']` and `ENV['DOMOSCIO_PASSWORD']` with your credentials to access your enabled APIs. Refer to the API documentation for details:
30
+ https://domoscio.com/wiki/doku.php?id=api2:start
31
+
32
+ ```ruby
33
+ DomoscioAdmin.configure do |c|
34
+ c.client_id = ENV['DOMOSCIO_ID']
35
+ c.client_passphrase = ENV['DOMOSCIO_PASSWORD']
36
+ c.temp_dir = File.expand_path('../tmp', __FILE__)
37
+ FileUtils.mkdir_p(c.temp_dir) unless File.directory?(c.temp_dir)
38
+ end
39
+ ```
40
+
41
+ | Key | Type | Description |
42
+ | ------------- | ------------- | ------------- |
43
+ | client_id | `integer` | this is your instance_id, required for access to your data |
44
+ | client_passphrase | `string` | client_passphrase is your secret key, this token is paired with your client_id |
45
+
46
+ ## Basic DomoscioAdmin use
47
+
48
+ ### Get Url
49
+
50
+ Server request need 2 parameters :
51
+ - First argument is the client_id.
52
+ - Second argument is the request body.
53
+
54
+ In `your controller`:
55
+
56
+ ```ruby
57
+ @chart_url = DomoscioAdmin::InstanceParam.update(client_id, {param_1: "param_value"})
58
+ ```
59
+
60
+
61
+ ## Versioning
62
+
63
+ Currently v0.2.0
64
+
65
+ ## Authors
66
+
67
+ See the list of contributors (https://github.com/Celumproject/domoscio_js/contributors)
68
+
69
+ This project rocks and uses MIT-LICENSE.
data/Rakefile ADDED
@@ -0,0 +1,28 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+
9
+ RDoc::Task.new(:rdoc) do |rdoc|
10
+ rdoc.rdoc_dir = 'rdoc'
11
+ rdoc.title = 'DomoscioAdmin'
12
+ rdoc.options << '--line-numbers'
13
+ rdoc.rdoc_files.include('README.rdoc')
14
+ rdoc.rdoc_files.include('lib/**/*.rb')
15
+ end
16
+
17
+ Bundler::GemHelper.install_tasks
18
+
19
+ require 'rake/testtask'
20
+
21
+ Rake::TestTask.new(:test) do |t|
22
+ t.libs << 'lib'
23
+ t.libs << 'test'
24
+ t.pattern = 'test/**/*_test.rb'
25
+ t.verbose = false
26
+ end
27
+
28
+ task default: :test
@@ -0,0 +1,64 @@
1
+ module DomoscioAdmin
2
+ module AuthorizationToken
3
+ class Manager
4
+ class << self
5
+ def storage
6
+ @@storage ||= FileStorage.new
7
+ end
8
+
9
+ def storage=(storage)
10
+ @@storage = storage
11
+ end
12
+
13
+ def get_token
14
+ storage.get
15
+ end
16
+ end
17
+ end
18
+
19
+ class StaticStorage
20
+ def get
21
+ @@token ||= nil
22
+ end
23
+
24
+ def store(token)
25
+ @@token = token
26
+ end
27
+ end
28
+
29
+ class FileStorage
30
+ require 'yaml'
31
+ @temp_dir
32
+
33
+ def initialize(temp_dir = nil)
34
+ @temp_dir = temp_dir || DomoscioAdmin.configuration.temp_dir
35
+ raise "Path to temporary folder is not defined" unless @temp_dir
36
+ end
37
+
38
+ def get
39
+ begin
40
+ f = File.open(file_path, File::RDONLY)
41
+ f.flock(File::LOCK_SH)
42
+ txt = f.read
43
+ f.close
44
+ YAML.load(txt) || nil
45
+ rescue Errno::ENOENT
46
+ nil
47
+ end
48
+ end
49
+
50
+ def store(token)
51
+ File.open(file_path, File::RDWR | File::CREAT, 0644) do |f|
52
+ f.flock(File::LOCK_EX)
53
+ f.truncate(0)
54
+ f.rewind
55
+ f.puts(YAML.dump(token))
56
+ end
57
+ end
58
+
59
+ def file_path
60
+ File.join(@temp_dir, "DomoscioAdmin.AuthorizationToken.FileStore.tmp")
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,31 @@
1
+ module DomoscioAdmin
2
+ # Generic error superclass for MangoPay specific errors.
3
+ # Currently never instantiated directly.
4
+ # Currently only single subclass used.
5
+ class Error < StandardError
6
+ end
7
+
8
+ # ResponseError from DomoscioAdmin
9
+ class ResponseError < Error
10
+ attr_reader :request_url, :code, :details, :body, :request_params
11
+
12
+ def initialize(request_url, code, details = {}, body = nil, request_params = {})
13
+ @request_url, @code, @details, @body, @request_params = request_url, code, details, body, request_params
14
+ super(message) if message
15
+ end
16
+
17
+ def message; @details.is_a?(Hash) ? @details.dig(:error, :message) : @details; end
18
+ end
19
+
20
+ # ProcessingError from DomoscioAdmin
21
+ class ProcessingError < Error
22
+ attr_reader :request_url, :code, :details, :body, :request_params
23
+
24
+ def initialize(request_url, code, details = {}, body = nil, request_params = {})
25
+ @request_url, @code, @details, @body, @request_params = request_url, code, details, body, request_params
26
+ super(message) if message
27
+ end
28
+
29
+ def message; @details.message; end
30
+ end
31
+ end
@@ -0,0 +1,10 @@
1
+ require 'rails/generators'
2
+ module DomoscioAdmin
3
+ class InstallGenerator < ::Rails::Generators::Base
4
+ source_root File.expand_path('../templates', __FILE__)
5
+ desc "Generate config file for DomoscioAdmin configuration"
6
+ def install
7
+ copy_file "install.rb", "config/initializers/domoscio_admin.rb"
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,6 @@
1
+ DomoscioAdmin.configure do |c|
2
+ c.client_id = ENV['DOMOSCIO_ID']
3
+ c.client_passphrase = ENV['DOMOSCIO_PASSWORD']
4
+ c.temp_dir = File.expand_path('../tmp', __FILE__)
5
+ FileUtils.mkdir_p(c.temp_dir) unless File.directory?(c.temp_dir)
6
+ end
@@ -0,0 +1,52 @@
1
+ module DomoscioAdmin
2
+ module HTTPCalls
3
+ module Create
4
+ module ClassMethods
5
+ def create(*id, params)
6
+ id = id.empty? ? nil : id[0]
7
+ DomoscioAdmin.request(:post, url(id), params)
8
+ end
9
+ end
10
+
11
+ def self.included(base)
12
+ base.extend(ClassMethods)
13
+ end
14
+ end
15
+
16
+ module Update
17
+ module ClassMethods
18
+ def update(id = nil, params = {})
19
+ DomoscioAdmin.request(:put, url(id), params)
20
+ end
21
+ end
22
+
23
+ def self.included(base)
24
+ base.extend(ClassMethods)
25
+ end
26
+ end
27
+
28
+ module Fetch
29
+ module ClassMethods
30
+ def fetch(id = nil, params = {})
31
+ DomoscioAdmin.request(:get, url(id), params)
32
+ end
33
+ end
34
+
35
+ def self.included(base)
36
+ base.extend(ClassMethods)
37
+ end
38
+ end
39
+
40
+ module Destroy
41
+ module ClassMethods
42
+ def destroy(id = nil, params = {})
43
+ DomoscioAdmin.request(:delete, url(id), params)
44
+ end
45
+ end
46
+
47
+ def self.included(base)
48
+ base.extend(ClassMethods)
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,6 @@
1
+ module DomoscioAdmin
2
+ class InstanceParameter < Resource
3
+ include DomoscioAdmin::HTTPCalls::Fetch
4
+ include DomoscioAdmin::HTTPCalls::Update
5
+ end
6
+ end
@@ -0,0 +1,23 @@
1
+ module DomoscioAdmin
2
+ module JSON
3
+ class << self
4
+ if MultiJson.respond_to?(:dump)
5
+ def dump(*args)
6
+ MultiJson.dump(*args)
7
+ end
8
+
9
+ def load(*args)
10
+ MultiJson.load(*args)
11
+ end
12
+ else
13
+ def dump(*args)
14
+ MultiJson.encode(*args)
15
+ end
16
+
17
+ def load(*args)
18
+ MultiJson.decode(*args)
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,19 @@
1
+ module DomoscioAdmin
2
+ class Resource
3
+ class << self
4
+ def class_name
5
+ name.split('::')[-1]
6
+ end
7
+
8
+ def url(id = nil)
9
+ if self == Resource
10
+ raise NotImplementedError.new('Resource is an abstract class. Do not use it directly.')
11
+ end
12
+
13
+ build_url = "/instances/#{DomoscioAdmin.configuration.client_id}/#{class_name.underscore}s"
14
+ build_url << "/#{CGI.escape(id.to_s)}" if id
15
+ return build_url
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,3 @@
1
+ module DomoscioAdmin
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,175 @@
1
+ require 'net/https'
2
+ require 'cgi/util'
3
+ require 'multi_json'
4
+ # helpers
5
+ require 'domoscio_admin/version'
6
+ require 'domoscio_admin/json'
7
+ require 'domoscio_admin/errors'
8
+ require 'domoscio_admin/authorization_token'
9
+ # generators
10
+ require 'domoscio_admin/generators/install_generator'
11
+ # resources
12
+ require 'domoscio_admin/http_calls'
13
+ require 'domoscio_admin/resource'
14
+ require 'domoscio_admin/instance/instance_parameter'
15
+
16
+ module DomoscioAdmin
17
+ class Configuration
18
+ attr_accessor :root_url, :client_id, :client_passphrase, :temp_dir
19
+
20
+ def root_url
21
+ @root_url ||= ""
22
+ end
23
+ end
24
+
25
+ class << self
26
+ attr_accessor :configuration
27
+ end
28
+
29
+ def self.configure
30
+ self.configuration ||= Configuration.new
31
+ yield configuration
32
+ end
33
+
34
+ def self.api_uri(url = '')
35
+ URI(configuration.root_url + url)
36
+ end
37
+
38
+ #
39
+ # - +method+: HTTP method; lowercase symbol, e.g. :get, :post etc.
40
+ # - +url+: the part after Configuration#root_url
41
+ # - +params+: hash; entity data for creation, update etc.; will dump it by JSON and assign to Net::HTTPRequest#body
42
+ #
43
+ # Performs HTTP requests to Adaptive Engine
44
+ # On token issues, will try once to get a new token then will output a DomoscioAdmin::ReponseError with details
45
+ #
46
+ # Raises DomoscioAdmin::ResponseError on Adaptive Error Status
47
+ # Raises DomoscioAdmin::ProcessingError on Internal Error
48
+ #
49
+ def self.request(method, url, params = {})
50
+ store_tokens, headers = request_headers
51
+ uri = api_uri(url)
52
+
53
+ response = DomoscioAdmin.send_request(uri, method, params, headers)
54
+ return response if response.kind_of? DomoscioAdmin::ProcessingError
55
+
56
+ begin
57
+ raise_http_failure(uri, response, params)
58
+ data = DomoscioAdmin::JSON.load(response.body.nil? ? '' : response.body)
59
+ DomoscioAdmin::AuthorizationToken::Manager.storage.store({ access_token: response['Accesstoken'], refresh_token: response['Refreshtoken'] }) if store_tokens
60
+ rescue MultiJson::LoadError => exception
61
+ data = ProcessingError.new(uri, 500, exception, response.body, params)
62
+ rescue ResponseError => exception
63
+ data = exception
64
+ end
65
+
66
+ data
67
+ end
68
+
69
+ private
70
+
71
+ # This function catches usual Http errors during calls
72
+ #
73
+ def self.send_request(uri, method, params, headers)
74
+ begin
75
+ response = perform_call(uri, method, params, headers)
76
+ response = retry_call_and_store_tokens(uri, method, params, headers) if ['401', '403'].include? response.code
77
+ response
78
+ rescue Timeout::Error, Errno::EINVAL, HTTP::ConnectionError, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => exception
79
+ ProcessingError.new(uri, 500, exception, response, params)
80
+ end
81
+ end
82
+
83
+ # This helper will check the response status and build the correcponding DomoscioAdmin::ResponseError
84
+ #
85
+ def self.raise_http_failure(uri, response, params)
86
+ unless response.kind_of? Net::HTTPSuccess
87
+ if response.blank?
88
+ raise ResponseError.new(uri, 500, { error: { status: 500, message: 'DomoscioAdmin not available' } }, {}, params)
89
+ else
90
+ raise ResponseError.new(uri, response.code.to_i, DomoscioAdmin::JSON.load((response.body.nil? ? '' : response.body), :symbolize_keys => true), response.body, params)
91
+ end
92
+ end
93
+ end
94
+
95
+ # Actual HTTP call is performed here
96
+ #
97
+ def self.perform_call(uri, method, params, headers)
98
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
99
+ req = Net::HTTP::const_get(method.capitalize).new(uri.request_uri, headers)
100
+ req.body = DomoscioAdmin::JSON.dump(params)
101
+ http.request req
102
+ end
103
+ end
104
+
105
+ # This method is called when AdaptiveEngine returns tokens errors
106
+ # Action on those errors is to retry and request new tokens, those new token are then stored
107
+ def self.retry_call_and_store_tokens(uri, method, params, headers)
108
+ headers = request_new_tokens
109
+ response = perform_call(uri, method, params, headers)
110
+ DomoscioAdmin::AuthorizationToken::Manager.storage.store({ access_token: response['Accesstoken'], refresh_token: response['Refreshtoken'] })
111
+ response
112
+ end
113
+
114
+ def self.user_agent
115
+ @uname ||= get_uname
116
+ {
117
+ bindings_version: DomoscioAdmin::VERSION,
118
+ lang: 'ruby',
119
+ lang_version: "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})",
120
+ platform: RUBY_PLATFORM,
121
+ uname: @uname
122
+ }
123
+ end
124
+
125
+ def self.get_uname
126
+ `uname -a 2>/dev/null`.strip if RUBY_PLATFORM =~ /linux|darwin/i
127
+ rescue Errno::ENOMEM
128
+ 'uname lookup failed'
129
+ end
130
+
131
+ # Process the token loading and analyze
132
+ # will return the processed headers and a token store flag
133
+ #
134
+ def self.request_headers
135
+ begin
136
+ auth_token = DomoscioAdmin::AuthorizationToken::Manager.get_token
137
+ if auth_token && auth_token[:access_token] && auth_token[:refresh_token]
138
+ [false, send_current_tokens(auth_token)]
139
+ else
140
+ [true, request_new_tokens]
141
+ end
142
+ rescue SyntaxError, StandardError
143
+ [true, request_new_tokens]
144
+ end
145
+ end
146
+
147
+ # If stored token successfully loaded we build the header with them
148
+ #
149
+ def self.send_current_tokens(auth_token)
150
+ {
151
+ 'user_agent' => "#{DomoscioAdmin.user_agent}",
152
+ 'ClientId' => "#{DomoscioAdmin.configuration.client_id}",
153
+ 'AccessToken' => "#{auth_token[:access_token]}",
154
+ 'RefreshToken' => "#{auth_token[:refresh_token]}",
155
+ 'Content-Type' => 'application/json'
156
+ }
157
+ end
158
+
159
+ # If we cant find tokens of they are corrupted / expired, then we set headers to request new ones
160
+ def self.request_new_tokens
161
+ {
162
+ 'user_agent' => "#{DomoscioAdmin.user_agent}",
163
+ 'ClientId' => "#{DomoscioAdmin.configuration.client_id}",
164
+ 'Authorization' => "Token token=#{DomoscioAdmin.configuration.client_passphrase}",
165
+ 'Content-Type' => 'application/json'
166
+ }
167
+ end
168
+
169
+ DomoscioAdmin.configure do |c|
170
+ c.client_id = nil
171
+ c.client_passphrase = nil
172
+ c.temp_dir = File.expand_path('../tmp', __FILE__)
173
+ FileUtils.mkdir_p(c.temp_dir) unless File.directory?(c.temp_dir)
174
+ end
175
+ end
@@ -0,0 +1,19 @@
1
+ # require_relative '../lib/domoscio_admin'
2
+ # require_relative './lib/domoscio_admin/shared_resources'
3
+
4
+ require 'capybara/rspec'
5
+ require 'capybara-webkit'
6
+ require 'fileutils'
7
+ require 'active_support/all'
8
+
9
+ Capybara.default_driver = :webkit
10
+
11
+ def reset_domoscio_admin_configuration
12
+ DomoscioAdmin.configure do |c|
13
+ c.client_id = 14
14
+ c.client_passphrase = '748add958564718f6d7add299655f95c'
15
+ c.temp_dir = File.expand_path('../tmp', __FILE__)
16
+ FileUtils.mkdir_p(c.temp_dir) unless File.directory?(c.temp_dir)
17
+ end
18
+ end
19
+ reset_domoscio_admin_configuration
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: domoscio_admin
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Pascal Lim
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-12-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '3.2'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '3.2'
27
+ description: Ruby client to interact with Domoscio Admin.
28
+ email:
29
+ - pascal.lim@domoscio.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - MIT-LICENSE
35
+ - README.md
36
+ - Rakefile
37
+ - lib/domoscio_admin.rb
38
+ - lib/domoscio_admin/authorization_token.rb
39
+ - lib/domoscio_admin/errors.rb
40
+ - lib/domoscio_admin/generators/install_generator.rb
41
+ - lib/domoscio_admin/generators/templates/install.rb
42
+ - lib/domoscio_admin/http_calls.rb
43
+ - lib/domoscio_admin/instance/instance_parameter.rb
44
+ - lib/domoscio_admin/json.rb
45
+ - lib/domoscio_admin/resource.rb
46
+ - lib/domoscio_admin/version.rb
47
+ - spec/spec_helper.rb
48
+ homepage: https://www.domoscio.com
49
+ licenses:
50
+ - MIT
51
+ metadata: {}
52
+ post_install_message:
53
+ rdoc_options: []
54
+ require_paths:
55
+ - lib
56
+ required_ruby_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ requirements: []
67
+ rubygems_version: 3.0.8
68
+ signing_key:
69
+ specification_version: 4
70
+ summary: Summary of DomoscioAdmin.
71
+ test_files:
72
+ - spec/spec_helper.rb