ohmage 0.0.1

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
+ SHA1:
3
+ metadata.gz: 4bb1f2b405dcf481e20c0fb439eb0853da169fb4
4
+ data.tar.gz: f0e3544e9057623c8f89f4cc27ef4d3291b7ca7f
5
+ SHA512:
6
+ metadata.gz: 00103e4c52f43a0fd5a91acd10f568cd0f30d084f0d525118eb6c2c1d09e155604f2a67aa926a555426011d48cfbda6819ae4464be80c1360a80d62be56a8d43
7
+ data.tar.gz: 413e3ee2df7afdf4285c30710b143b43595532ce135718f2294e58f17fb4cd25dc8c84863305eae5ee22aca9b8fc9d2eda127c4017653e934417ad20ef0f9526
data/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2015 Steve Nolen
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/bin/ohmage ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
4
+
5
+ require 'ohmage/cli'
6
+
7
+ Ohmage::CLI.start(ARGV)
data/lib/ohmage/api.rb ADDED
@@ -0,0 +1,11 @@
1
+ require 'ohmage/user'
2
+ require 'ohmage/campaign'
3
+ require 'ohmage/clazz'
4
+
5
+ module Ohmage
6
+ module API
7
+ include Ohmage::API::User
8
+ include Ohmage::API::Clazz
9
+ include Ohmage::API::Campaign
10
+ end
11
+ end
@@ -0,0 +1,19 @@
1
+ module Ohmage
2
+ module API
3
+ module Campaign
4
+ #
5
+ # ohmage campaign/read call
6
+ # @see https://github.com/ohmage/server/wiki/Campaign-Manipulation#campaignRead
7
+ # @returns [Array: Ohmage::Campaign objects] matching criteria and output format
8
+ def campaign_read(params = {})
9
+ request = Ohmage::Request.new(self, :post, 'campaign/read', params)
10
+ # TODO: make a utility to abstract creation of array of base objects
11
+ t = []
12
+ request.perform[:data].each do |k, v|
13
+ t << Ohmage::Campaign.new(k => v)
14
+ end
15
+ t
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,31 @@
1
+ module Ohmage
2
+ module API
3
+ module Clazz
4
+ #
5
+ # ohmage class/read call
6
+ # @see https://github.com/ohmage/server/wiki/Class-Manipulation#classRead
7
+ # @returns [Array: Ohmage::Class objects] matching criteria
8
+ #
9
+ def class_read(params = {})
10
+ request = Ohmage::Request.new(self, :post, 'class/read', params)
11
+ # TODO: make a utility to abstract creation of array of base objects
12
+ t = []
13
+ request.perform[:data].each do |k, v|
14
+ t << Ohmage::Clazz.new(k => v)
15
+ end
16
+ t
17
+ end
18
+
19
+ def class_create(params = {})
20
+ request = Ohmage::Request.new(self, :post, 'class/create', params)
21
+ request.perform
22
+ class_read(class_urn_list: params[:class_urn])
23
+ end
24
+
25
+ def class_delete(params = {})
26
+ request = Ohmage::Request.new(self, :post, 'class/delete', params)
27
+ request.perform
28
+ end
29
+ end
30
+ end
31
+ end
data/lib/ohmage/cli.rb ADDED
@@ -0,0 +1,114 @@
1
+ require 'thor'
2
+ require 'ohmage'
3
+ require 'ohmage/cli_helpers'
4
+
5
+ module Ohmage
6
+ class CLI < Thor
7
+ include Ohmage::CliHelpers
8
+
9
+ class List < Thor
10
+ class_option :table, aliases: :t, type: :boolean, desc: 'formats output as table'
11
+
12
+ desc 'ls campaign <options>', 'Lists campaigns current user has access to'
13
+ option :search, aliases: :s, desc: 'a search string to limit the returned campaign list'
14
+ def campaign
15
+ ls = Ohmage.campaign_read(campaign_name_search: options[:search], output_format: 'short')
16
+ Ohmage::CLI_Helpers.format_output(ls, options[:table], [:name, :urn, :description], :urn)
17
+ end
18
+
19
+ desc 'ls class <options>', 'Lists classes current user has access to'
20
+ def clazz(urn_list = nil)
21
+ ls = Ohmage.class_read(class_urn_list: urn_list)
22
+ Ohmage::CLI_Helpers.format_output(ls, options[:table], [:name, :urn, :description, :role, :users], :urn)
23
+ end
24
+
25
+ desc 'ls user <options>', 'Lists users that match criteria of search, all viewable if no search'
26
+ option :search, aliases: :s, desc: 'a search string to limit the returned user list'
27
+ def user(username = nil)
28
+ ls = Ohmage.user_read(user_list: username, username_search: options[:search])
29
+ Ohmage::CLI_Helpers.format_output(ls, options[:table], [:username, :email_address, :enabled, :admin, :new_account], :username)
30
+ end
31
+ end
32
+
33
+ class Create < Thor
34
+ class_option :table, aliases: :t, type: :boolean, desc: 'formats output as table'
35
+
36
+ desc 'create user <username> <options>', 'creates a new ohmage user with parameters'
37
+ option :password, required: true, aliases: :p, desc: 'value for new user password'
38
+ option :admin, type: :boolean, default: false, desc: 'is user admin?'
39
+ option :enabled, type: :boolean, default: true, desc: 'is user enabled?'
40
+ option :new, type: :boolean, aliases: :first_login, default: true, desc: 'force password reset on first login?'
41
+ def user(username)
42
+ new_user = Ohmage.user_create(username: username,
43
+ password: options[:password],
44
+ admin: options[:admin],
45
+ enabled: options[:enabled],
46
+ new_account: options[:new])
47
+ Ohmage::CLI_Helpers.format_output(new_user, options[:table], [:username], :username)
48
+ end
49
+
50
+ desc 'create class <class_urn> <class_name> <options>', 'creates a new ohmage class with parameters'
51
+ option :description, aliases: :d, type: :string, desc: 'description of class'
52
+ def clazz(urn, name)
53
+ new_class = Ohmage.class_create(class_urn: urn,
54
+ class_name: name,
55
+ description: options[:description])
56
+ Ohmage::CLI_Helpers.format_output(new_class, options[:table], [:urn, :name, :description], :urn)
57
+ end
58
+ end
59
+
60
+ class Delete < Thor
61
+ desc 'delete clazz <class_urn>', 'deletes an existing ohmage class'
62
+ def clazz(urn)
63
+ Ohmage.class_delete(class_urn: urn)
64
+ end
65
+ end
66
+
67
+ class Update < Thor
68
+ class_option :table, aliases: :t, type: :boolean, default: true, desc: 'formats output as table'
69
+
70
+ desc 'update user <username> <options>', 'updates provided values for a given username'
71
+ option :admin, type: :boolean, desc: 'is user admin?'
72
+ option :new, type: :boolean, desc: 'force pw reset on login?'
73
+ def user(username)
74
+ updated_user = Ohmage.user_update(username: username,
75
+ admin: options[:admin],
76
+ enabled: options[:enabled],
77
+ new_account: options[:new])
78
+ Ohmage::CLI_Helpers.format_output(updated_user, options[:table], [:username, :admin, :enabled, :new_account], :username)
79
+ end
80
+
81
+ desc 'update password <username> <options>', "updates provided user's password"
82
+ option :password, required: true, aliases: :p, desc: 'new password for user'
83
+ def password(username)
84
+ Ohmage.user_password(username: username, new_password: options[:password])
85
+ end
86
+ end
87
+
88
+ desc 'hi', 'returns current config'
89
+ def hi
90
+ conf = Ohmage.client
91
+ puts 'Server: ' + conf.host
92
+ puts 'Current User: ' + conf.user
93
+ conf.server_config.each do |k, v|
94
+ puts k.to_s + ': ' + v.to_s
95
+ end
96
+ end
97
+
98
+ # Allow use of either ls or list. I don't see any reference to aliasing subcommands
99
+ # so i'll just do this for now!
100
+ %w(ls list).each do |l|
101
+ desc "#{l} <entity>", 'lists specified entity current user has access to'
102
+ subcommand l, List
103
+ end
104
+
105
+ desc 'create <entity>', 'creates an entity matching the required info.'
106
+ subcommand 'create', Create
107
+
108
+ desc 'delete <entity>', 'deletes an entity matching required info'
109
+ subcommand 'delete', Delete
110
+
111
+ desc 'update <entity>', 'updates an entity matching info'
112
+ subcommand 'update', Update
113
+ end
114
+ end
@@ -0,0 +1,24 @@
1
+ require 'formatador'
2
+
3
+ module Ohmage
4
+ module CliHelpers
5
+ def self.format_output(d, table, fields, no_table_field) # rubocop:disable MethodLength
6
+ # accepts an ohmage entity array and returns output (table or newline given table boolean)
7
+ output = []
8
+ d.each do |i|
9
+ @line = {}
10
+ fields.each do |f|
11
+ @line.merge!(f.to_sym => i.send(f).to_s)
12
+ end
13
+ output << @line
14
+ end
15
+ if table
16
+ Formatador.display_compact_table(output, fields)
17
+ else
18
+ output.each do |v|
19
+ Formatador.display_line(v[no_table_field])
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,46 @@
1
+ require 'ohmage/api'
2
+ require 'ohmage/request'
3
+
4
+ module Ohmage
5
+ class Client
6
+ include Ohmage::API
7
+ attr_accessor :host, :port, :path, :client_string, :user, :password, :token, :server_config
8
+ def initialize(options = {}) # rubocop:disable MethodLength
9
+ self.server_url = ENV['OHMAGE_SERVER_URL']
10
+ self.user = ENV['OHMAGE_USER']
11
+ self.password = ENV['OHMAGE_PASSWORD']
12
+ self.client_string = 'ruby-ohmage'
13
+ self.path = 'app/'
14
+ self.port = 443
15
+ options.each do |k, v|
16
+ instance_variable_set("@#{k}", v)
17
+ end
18
+ yield(self) if block_given?
19
+ server_config_read
20
+ self
21
+ end
22
+ #
23
+ # ohmage config/read call
24
+ # @returns [Hash] of server config details
25
+ def server_config_read
26
+ request = Ohmage::Request.new(self, :get, 'config/read', {})
27
+ resp = request.perform
28
+ self.server_config = resp[:data]
29
+ end
30
+ #
31
+ # ohmage user/auth_token call
32
+ # @see https://github.com/ohmage/server/wiki/User-Authentication#statefulAuthentication
33
+ # @returns String: auth_token valid for server's auth_token_lifetime param
34
+ #
35
+ def auth_token
36
+ params = {}
37
+ params['user'] = user
38
+ params['password'] = password
39
+ request = Ohmage::Request.new(self, :post, 'user/auth_token', params)
40
+ resp = request.perform
41
+ self.token = resp[:token]
42
+ resp[:token]
43
+ end
44
+ alias_method :auth, :auth_token
45
+ end
46
+ end
@@ -0,0 +1,19 @@
1
+ module Ohmage
2
+ class Campaign
3
+ # @return [String]
4
+ attr_reader :urn, :name, :icon_url, :authored_by, :running_state, :privacy_state, :creation_timestamp, :description, :xml
5
+ alias_method :author, :authored_by
6
+ # @return [Array]
7
+ attr_reader :user_roles, :classes
8
+ alias_method :roles, :user_roles
9
+ # @return [Hash]
10
+ attr_reader :user_role_campaign
11
+
12
+ def initialize(attrs = {})
13
+ @urn = attrs.keys[0].to_s
14
+ attrs.values[0].each do |k, v|
15
+ instance_variable_set("@#{k}", v)
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,16 @@
1
+ module Ohmage
2
+ class Clazz
3
+ # @return [String]
4
+ attr_reader :urn, :name, :description, :role
5
+ attr_reader :my_role, :role
6
+ # @return [Hash]
7
+ attr_reader :users
8
+
9
+ def initialize(attrs = {})
10
+ @urn = attrs.keys[0].to_s
11
+ attrs.values[0].each do |k, v|
12
+ instance_variable_set("@#{k}", v)
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,22 @@
1
+ module Ohmage
2
+ class User
3
+ # #return [String]
4
+ attr_reader :username, :first_name, :last_name, :organization, :personal_id, :email_address
5
+ alias_method :id, :username
6
+ alias_method :user, :username
7
+ alias_method :org, :organization
8
+ alias_method :email, :email_address
9
+ # @return [Object]
10
+ attr_reader :permissions, :classes, :campaigns
11
+ # @return [TrueClass, FalseClass]
12
+ attr_reader :enabled, :can_setup_users, :new_account, :can_create_classes, :can_create_campaigns, :admin, :is_admin
13
+
14
+ def initialize(attrs = {})
15
+ @username = attrs.keys[0].to_s
16
+ attrs.values[0].each do |k, v|
17
+ instance_variable_set("@#{k}", v)
18
+ end
19
+ @permissions.each { |k, v| instance_variable_set("@#{k}", v) }
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,111 @@
1
+ module Ohmage
2
+ class Error < StandardError
3
+ ClientError = Class.new(self)
4
+ BadRequest = Class.new(ClientError)
5
+ Unauthorized = Class.new(ClientError)
6
+ NotFound = Class.new(ClientError)
7
+ NotAcceptable = Class.new(ClientError)
8
+ InvalidToken = Class.new(ClientError)
9
+ InvalidParameter = Class.new(ClientError)
10
+ MobilityException = Class.new(ClientError)
11
+ SurveyException = Class.new(ClientError)
12
+ CampaignException = Class.new(ClientError)
13
+ ImageException = Class.new(ClientError)
14
+ ClassException = Class.new(ClientError)
15
+ UserException = Class.new(ClientError)
16
+ CatchAll = Class.new(ClientError)
17
+
18
+ ServerError = Class.new(self)
19
+ InternalServerError = Class.new(ServerError)
20
+ BadGateway = Class.new(ServerError)
21
+ ServiceUnavailable = Class.new(ServerError)
22
+ GatewayTimeout = Class.new(ServerError)
23
+
24
+ ERRORS = {
25
+ 888 => Ohmage::Error::CatchAll, # just, i don't know, catch 'em all.
26
+ 400 => Ohmage::Error::BadRequest,
27
+ 401 => Ohmage::Error::Unauthorized,
28
+ 404 => Ohmage::Error::NotFound,
29
+ 405 => Ohmage::Error::Unauthorized,
30
+ 406 => Ohmage::Error::NotAcceptable,
31
+ 500 => Ohmage::Error::InternalServerError,
32
+ 502 => Ohmage::Error::BadGateway,
33
+ 503 => Ohmage::Error::ServiceUnavailable,
34
+ 504 => Ohmage::Error::GatewayTimeout,
35
+ }
36
+ # How ugly is this??
37
+ STRING_ERRORS = {
38
+ '0100' => Ohmage::Error::InternalServerError,
39
+ '0101' => Ohmage::Error::InternalServerError,
40
+ # Auth
41
+ '0200' => Ohmage::Error::Unauthorized,
42
+ '0201' => Ohmage::Error::Unauthorized,
43
+ '0202' => Ohmage::Error::Unauthorized,
44
+ '0203' => Ohmage::Error::InvalidToken,
45
+ }
46
+ ('0300'..'0312').to_a.each do |e|
47
+ STRING_ERRORS[e] = Ohmage::Error::InvalidParameter
48
+ end
49
+ ('0500'..'0503').to_a.each do |e|
50
+ STRING_ERRORS[e] = Ohmage::Error::MobilityException
51
+ end
52
+ ('0600'..'0630').to_a.each do |e|
53
+ STRING_ERRORS[e] = Ohmage::Error::SurveyException
54
+ end
55
+ ('0700'..'0713').to_a.each do |e|
56
+ STRING_ERRORS[e] = Ohmage::Error::CampaignException
57
+ end
58
+ ('0800'..'0803').to_a.each do |e|
59
+ STRING_ERRORS[e] = Ohmage::Error::ImageException
60
+ end
61
+ ('0900'..'0906').to_a.each do |e|
62
+ STRING_ERRORS[e] = Ohmage::Error::ClassException
63
+ end
64
+ ('1000'..'1017').to_a.each do |e|
65
+ STRING_ERRORS[e] = Ohmage::Error::UserException
66
+ end
67
+ ('1100'..'1803').to_a.each do |e|
68
+ STRING_ERRORS[e] = Ohmage::Error::CatchAll
69
+ end
70
+ class << self
71
+ # Create a new error from an HTTP response
72
+ #
73
+ # @param body [String]
74
+ # @return [Ohmage::Error]
75
+ def from_response(body)
76
+ message, code = parse_error(body)
77
+ # ohmage returns own error codes in body and as strings.
78
+ if code.is_a? String
79
+ new(message, 888)
80
+ else
81
+ new(message, code)
82
+ end
83
+ end
84
+
85
+ private
86
+
87
+ def parse_error(body)
88
+ if body.nil? || body.empty?
89
+ ['', nil]
90
+ elsif body[:errors]
91
+ extract_message_from_errors(body)
92
+ end
93
+ end
94
+
95
+ def extract_message_from_errors(body)
96
+ first = Array(body[:errors]).first
97
+ [first[:text], first[:code]]
98
+ end
99
+ end
100
+ # Initializes a new Error object
101
+ #
102
+ # @param message [Exception, String]
103
+ # @param rate_limit [Hash]
104
+ # @param code [Integer]
105
+ # @return [Ohmage::Error]
106
+ def initialize(message = '', code = nil)
107
+ super(message)
108
+ @code = code
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,81 @@
1
+ module Ohmage
2
+ class Request
3
+ def initialize(client, request_method, api, options = {}) # rubocop:disable MethodLength
4
+ @client = client
5
+ @uri = Addressable::URI.parse(@client.server_url + @client.path + api)
6
+ @options = options
7
+ @options['client'] = @client.client_string
8
+ case api
9
+ when 'config/read', 'user/auth_token', 'user/auth'
10
+ # these calls don't need auth
11
+ else
12
+ @client.auth if @client.token.nil?
13
+ @options['auth_token'] = @client.token
14
+ end
15
+
16
+ @request_method = request_method
17
+ end
18
+ def perform # rubocop:disable all
19
+ response = HTTP.public_send(@request_method, @uri.to_s, params: @options)
20
+ response_body = symbolize_keys!(response.parse)
21
+ response_headers = response.headers
22
+ begin
23
+ fail_or_return_response_body(response.status, response_body, response_headers)
24
+ rescue Ohmage::Error::InvalidToken
25
+ @client.auth
26
+ # refactor this, essentially recursively performs the request if it token failed
27
+ # on the first try. bad, bad, bad.
28
+ @options['auth_token'] = @client.token
29
+ response = HTTP.public_send(@request_method, @uri.to_s, params: @options)
30
+ response_body = symbolize_keys!(response.parse)
31
+ response_headers = response.headers
32
+ fail_or_return_response_body(response.status, response_body, response_headers)
33
+ end
34
+ end
35
+
36
+ def symbolize_keys!(object)
37
+ if object.is_a?(Array)
38
+ object.each_with_index do |val, index|
39
+ object[index] = symbolize_keys!(val)
40
+ end
41
+ elsif object.is_a?(Hash)
42
+ object.keys.each do |key|
43
+ object[key.to_sym] = symbolize_keys!(object.delete(key))
44
+ end
45
+ end
46
+ object
47
+ end
48
+
49
+ def fail_or_return_response_body(code, body, headers)
50
+ error = error(code, body, headers)
51
+ fail(error) if error
52
+ body
53
+ end
54
+
55
+ def error(code, body, _headers) # rubocop:disable all
56
+ # ohmage doesn't really return HTTP error codes
57
+ # so we're going to catch the real ones first, assuming
58
+ # they are sent from the web server (like 502 or 404)
59
+ klass = Ohmage::Error::ERRORS[code]
60
+ if klass.nil?
61
+ # we're not necessarily sure that this really isn't an error
62
+ # so we have to inspect the response body to look for result:failure
63
+ if body[:result] == 'failure'
64
+ # then ohmage also considers this a failure. weird, but let's try a new way to handle this
65
+ # we also want to smartly handle auth token errors, since we ohmage does not currently have
66
+ # persistent tokens
67
+ @code = body[:errors].first[:code]
68
+ @message = body[:errors].first[:text]
69
+ if @message =~ /token/ # rubocop:disable Metrics/BlockNesting
70
+ @code = '0203' # a new fake error code for catching token errors
71
+ end
72
+ klass = Ohmage::Error::STRING_ERRORS[@code]
73
+ klass.from_response(body) # refactor this.
74
+ end # body has { "result": "success" }, so let's assume it isn't a failure.
75
+ else
76
+ # return the base error
77
+ klass.from_response(body)
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,59 @@
1
+ module Ohmage
2
+ module API
3
+ module User
4
+ #
5
+ # ohmage user/read call
6
+ # @see https://github.com/ohmage/server/wiki/User-Manipulation#userRead
7
+ # @returns [Array: Ohmage::User objects] that match param criteria
8
+ #
9
+ def user_read(params = {})
10
+ request = Ohmage::Request.new(self, :post, 'user/read', params)
11
+ t = []
12
+ request.perform[:data].each do |k, v|
13
+ t << Ohmage::User.new(k => v)
14
+ end
15
+ t
16
+ end
17
+
18
+ #
19
+ # ohmage user_info/read call
20
+ # @see https://github.com/ohmage/server/wiki/User-Manipulation#userInfoRead
21
+ # @returns Object: detailed list of classes/campaign current user can access
22
+ #
23
+ def user_info_read
24
+ request = Ohmage::Request.new(self, :post, 'user_info/read', {})
25
+ Ohmage::User.new(request.perform[:data])
26
+ end
27
+
28
+ #
29
+ # ohmage user/create call
30
+ # @see https://github.com/ohmage/server/wiki/User-Manipulation#userCreate
31
+ # @returns [Object: Ohmage::User]
32
+ #
33
+ def user_create(params = {})
34
+ request = Ohmage::Request.new(self, :post, 'user/create', params)
35
+ request.perform
36
+ user_read(user_list: params[:username])
37
+ end
38
+
39
+ #
40
+ # ohmage user/update call
41
+ # @see https://github.com/ohmage/server/wiki/User-Manipulation#userUpdate
42
+ # @returns [Object: Ohmage::User]
43
+ #
44
+ def user_update(params = {})
45
+ request = Ohmage::Request.new(self, :post, 'user/update', params)
46
+ request.perform
47
+ user_read(user_list: params[:username])
48
+ end
49
+
50
+ def user_password(params = {}) # is this method name odd?
51
+ # this api call demands current user's info.
52
+ params[:user] = user
53
+ params[:password] = password
54
+ request = Ohmage::Request.new(self, :post, 'user/change_password', params)
55
+ request.perform
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,45 @@
1
+ module Ohmage
2
+ module Version
3
+ module_function
4
+
5
+ # @return [Integer]
6
+ def major
7
+ 0
8
+ end
9
+
10
+ # @return [Integer]
11
+ def minor
12
+ 0
13
+ end
14
+
15
+ # @return [Integer]
16
+ def patch
17
+ 1
18
+ end
19
+
20
+ # @return [Integer, NilClass]
21
+ def pre
22
+ nil
23
+ end
24
+
25
+ # @return [Hash]
26
+ def to_h
27
+ {
28
+ major: major,
29
+ minor: minor,
30
+ patch: patch,
31
+ pre: pre,
32
+ }
33
+ end
34
+
35
+ # @return [Array]
36
+ def to_a
37
+ to_h.values.compact
38
+ end
39
+
40
+ # @return [String]
41
+ def to_s
42
+ to_a.join('.')
43
+ end
44
+ end
45
+ end
data/lib/ohmage.rb ADDED
@@ -0,0 +1,28 @@
1
+ require 'http'
2
+ require 'addressable/uri'
3
+ require 'ohmage/error'
4
+ require 'ohmage/client'
5
+ require 'ohmage/user'
6
+ require 'ohmage/request'
7
+ require 'ohmage/entity/user'
8
+ require 'ohmage/entity/clazz'
9
+ require 'ohmage/entity/campaign'
10
+ require 'ohmage/version'
11
+
12
+ module Ohmage
13
+ # @return [Ohmage::Client]
14
+ def self.client(options = {})
15
+ Ohmage::Client.new(options)
16
+ end
17
+
18
+ # Delegate to Ohmage::Client
19
+ def self.method_missing(method, *args, &block)
20
+ return super unless client.respond_to?(method)
21
+ client.send(method, *args, &block)
22
+ end
23
+
24
+ # Delegate to Ohmage::Client
25
+ def self.respond_to?(method)
26
+ client.respond_to?(method) || super
27
+ end
28
+ end
data/ohmage.gemspec ADDED
@@ -0,0 +1,23 @@
1
+ lib = File.expand_path('../lib', __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'ohmage/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.add_dependency 'addressable'
7
+ spec.add_dependency 'http', '~> 0.7.3'
8
+ spec.add_dependency 'thor', '~> 0.19.1'
9
+ spec.add_dependency 'formatador', '~> 0.2.5'
10
+ spec.authors = ['Steve Nolen']
11
+ spec.description = 'A Ruby interface for the ohmage 2.x API.'
12
+ spec.email = %w(technolengy@gmail.com)
13
+ spec.files = %w(LICENSE.txt ohmage.gemspec bin/ohmage) + Dir['lib/**/*.rb']
14
+ spec.homepage = 'https://github.com/ohmage/gem'
15
+ spec.licenses = %w(Apache 2)
16
+ spec.name = 'ohmage'
17
+ spec.executables = 'ohmage'
18
+ spec.require_paths = %w(lib)
19
+ spec.required_ruby_version = '>= 1.9.3'
20
+ spec.required_rubygems_version = '>= 1.3.5'
21
+ spec.summary = spec.description
22
+ spec.version = Ohmage::Version
23
+ end
metadata ADDED
@@ -0,0 +1,120 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ohmage
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Steve Nolen
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-03-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: addressable
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: http
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.7.3
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.7.3
41
+ - !ruby/object:Gem::Dependency
42
+ name: thor
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 0.19.1
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 0.19.1
55
+ - !ruby/object:Gem::Dependency
56
+ name: formatador
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 0.2.5
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 0.2.5
69
+ description: A Ruby interface for the ohmage 2.x API.
70
+ email:
71
+ - technolengy@gmail.com
72
+ executables:
73
+ - ohmage
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - LICENSE.txt
78
+ - bin/ohmage
79
+ - lib/ohmage.rb
80
+ - lib/ohmage/api.rb
81
+ - lib/ohmage/campaign.rb
82
+ - lib/ohmage/clazz.rb
83
+ - lib/ohmage/cli.rb
84
+ - lib/ohmage/cli_helpers.rb
85
+ - lib/ohmage/client.rb
86
+ - lib/ohmage/entity/campaign.rb
87
+ - lib/ohmage/entity/clazz.rb
88
+ - lib/ohmage/entity/user.rb
89
+ - lib/ohmage/error.rb
90
+ - lib/ohmage/request.rb
91
+ - lib/ohmage/user.rb
92
+ - lib/ohmage/version.rb
93
+ - ohmage.gemspec
94
+ homepage: https://github.com/ohmage/gem
95
+ licenses:
96
+ - Apache
97
+ - '2'
98
+ metadata: {}
99
+ post_install_message:
100
+ rdoc_options: []
101
+ require_paths:
102
+ - lib
103
+ required_ruby_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: 1.9.3
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: 1.3.5
113
+ requirements: []
114
+ rubyforge_project:
115
+ rubygems_version: 2.4.1
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: A Ruby interface for the ohmage 2.x API.
119
+ test_files: []
120
+ has_rdoc: