Class: LMS::API
- Inherits:
-
Object
show all
- Defined in:
- lib/lms/canvas.rb
Defined Under Namespace
Classes: Exception, InvalidAPIMethodRequestException, InvalidAPIRequestException, InvalidAPIRequestFailedException, InvalidRefreshOptionsException, MissingRequiredParameterException, RefreshTokenFailedException, RefreshTokenRequired
Class Attribute Summary collapse
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
-
#all_accounts ⇒ Object
Get all accounts including sub accounts.
-
#api_delete_request(api_url, additional_headers = {}) ⇒ Object
-
#api_error(result) ⇒ Object
-
#api_get_all_request(api_url, additional_headers = {}) ⇒ Object
-
#api_get_blocks_request(api_url, additional_headers = {}) ⇒ Object
-
#api_get_request(api_url, additional_headers = {}) ⇒ Object
-
#api_post_request(api_url, payload, additional_headers = {}) ⇒ Object
-
#api_put_request(api_url, payload, additional_headers = {}) ⇒ Object
-
#auth_state_model ⇒ Object
instance accessor, for convenience.
-
#check_result(result) ⇒ Object
-
#full_url(api_url, use_api_prefix = true) ⇒ Object
-
#get_next_url(link) ⇒ Object
-
#headers(additional_headers = {}) ⇒ Object
-
#initialize(lms_uri, authentication, refresh_token_options = nil) ⇒ API
constructor
The authentication parameter must be either a string (indicating a token), or an object that responds to: - #id - #token - #update(hash) – which should update #token with hash:noh.
-
#lock ⇒ Object
Obtains a lock (via the API.auth_state_model interface) and yields an authentication object corresponding to self.authentication.id.
-
#proxy(type, params, payload = nil, get_all = false) ⇒ Object
-
#refresh_token ⇒ Object
-
#refreshably ⇒ Object
Constructor Details
#initialize(lms_uri, authentication, refresh_token_options = nil) ⇒ API
The authentication parameter must be either a string (indicating a token), or an object that responds to:
-
-
-
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
# File 'lib/lms/canvas.rb', line 51
def initialize(lms_uri, authentication, refresh_token_options = nil)
@per_page = 100
@lms_uri = lms_uri
@refresh_token_options = refresh_token_options
if authentication.is_a?(String)
@authentication = OpenStruct.new(token: authentication)
else
@authentication = authentication
end
if refresh_token_options.present?
required_options = [:client_id, :client_secret, :redirect_uri, :refresh_token]
= @refresh_token_options.keys - required_options
raise InvalidRefreshOptionsException, "Invalid option(s) provided: #{extra_options.join(', ')}" unless .length == 0
missing_options = required_options - @refresh_token_options.keys
raise InvalidRefreshOptionsException, "Missing required option(s): #{missing_options.join(', ')}" unless missing_options.length == 0
end
end
|
Class Attribute Details
.auth_state_model ⇒ Object
Returns the value of attribute auth_state_model.
19
20
21
|
# File 'lib/lms/canvas.rb', line 19
def auth_state_model
@auth_state_model
end
|
Instance Attribute Details
#authentication ⇒ Object
Returns the value of attribute authentication.
44
45
46
|
# File 'lib/lms/canvas.rb', line 44
def authentication
@authentication
end
|
Class Method Details
.ignore_required(type) ⇒ Object
Ignore required params for specific calls. For example, the external tool calls have required params “name, privacy_level, consumer_key, shared_secret”. However, those params are not required if the call specifies config_type: “by_xml”.
238
239
240
241
242
243
|
# File 'lib/lms/canvas.rb', line 238
def self.ignore_required(type)
[
"CREATE_EXTERNAL_TOOL_COURSES",
"CREATE_EXTERNAL_TOOL_ACCOUNTS"
].include?(type)
end
|
.lms_url(type, params, payload = nil) ⇒ Object
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
|
# File 'lib/lms/canvas.rb', line 245
def self.lms_url(type, params, payload = nil)
endpoint = LMS::CANVAS_URLs[type]
parameters = endpoint[:parameters]
missing = []
if !self.ignore_required(type)
parameters.find_all{|p| p["required"]}.map{|p| p["name"]}.each do |p|
if p.include?("[") && p.include?("]")
parts = p.split('[')
parent = parts[0].to_sym
child = parts[1].gsub("]", "").to_sym
missing << p unless (params[parent].present? && params[parent][child].present?) ||
(payload.present? && payload[parent].present? && payload[parent][child].present?)
else
missing << p unless params[p.to_sym].present? || (payload.present? && !payload.is_a?(String) && payload[p.to_sym].present?)
end
end
end
if missing.length > 0
raise LMS::API::MissingRequiredParameterException, "Missing required parameter(s): #{missing.join(', ')}"
end
uri_proc = endpoint[:uri]
path_parameters = parameters.find_all{|p| p["paramType"] == "path"}.map{|p| p["name"].to_sym}
args = params.slice(*path_parameters).symbolize_keys
uri = args.blank? ? uri_proc.call : uri_proc.call(**args)
query_parameters = parameters.find_all{ |p| p["paramType"] == "query" }.map{ |p| p["name"].to_sym }
query_parameters << :per_page
query_parameters << :page
allowed_params = params.slice(*query_parameters)
if allowed_params.present?
"#{uri}?#{allowed_params.to_query}"
else
uri
end
end
|
.on_auth(callback = nil, &block) ⇒ Object
callback must accept a single parameter (the API object itself) and return the new authentication object.
29
30
31
|
# File 'lib/lms/canvas.rb', line 29
def self.on_auth(callback = nil, &block)
@@on_auth = callback || block
end
|
Instance Method Details
#all_accounts ⇒ Object
Get all accounts including sub accounts
296
297
298
299
300
301
302
303
304
|
# File 'lib/lms/canvas.rb', line 296
def all_accounts
all = []
self.proxy("LIST_ACCOUNTS", {}, nil, true).each do |account|
all << account
sub_accounts = self.proxy("GET_SUB_ACCOUNTS_OF_ACCOUNT", {account_id: account['id']}, nil, true)
all = all.concat(sub_accounts)
end
all
end
|
#api_delete_request(api_url, additional_headers = {}) ⇒ Object
126
127
128
129
130
131
|
# File 'lib/lms/canvas.rb', line 126
def api_delete_request(api_url, = {})
url = full_url(api_url)
refreshably do
HTTParty.delete(url, headers: ())
end
end
|
#api_error(result) ⇒ Object
182
183
184
185
186
|
# File 'lib/lms/canvas.rb', line 182
def api_error(result)
error = "Status: #{result.headers['status']} \n"
error << "Http Response: #{result.response.code} \n"
error << "Error: #{result['errors'] || result.response.message} \n"
end
|
#api_get_all_request(api_url, additional_headers = {}) ⇒ Object
133
134
135
136
137
138
139
|
# File 'lib/lms/canvas.rb', line 133
def api_get_all_request(api_url, = {})
[].tap do |results|
api_get_blocks_request(api_url, ) do |result|
results.concat(result)
end
end
end
|
#api_get_blocks_request(api_url, additional_headers = {}) ⇒ Object
141
142
143
144
145
146
147
148
149
|
# File 'lib/lms/canvas.rb', line 141
def api_get_blocks_request(api_url, = {})
connector = api_url.include?("?") ? "&" : "?"
next_url = "#{api_url}#{connector}per_page=#{@per_page}"
while next_url do
result = api_get_request(next_url, )
yield result
next_url = get_next_url(result.["link"])
end
end
|
#api_get_request(api_url, additional_headers = {}) ⇒ Object
119
120
121
122
123
124
|
# File 'lib/lms/canvas.rb', line 119
def api_get_request(api_url, = {})
url = full_url(api_url)
refreshably do
HTTParty.get(url, headers: ())
end
end
|
#api_post_request(api_url, payload, additional_headers = {}) ⇒ Object
112
113
114
115
116
117
|
# File 'lib/lms/canvas.rb', line 112
def api_post_request(api_url, payload, = {})
url = full_url(api_url)
refreshably do
HTTParty.post(url, headers: (), body: payload)
end
end
|
#api_put_request(api_url, payload, additional_headers = {}) ⇒ Object
105
106
107
108
109
110
|
# File 'lib/lms/canvas.rb', line 105
def api_put_request(api_url, payload, = {})
url = full_url(api_url)
refreshably do
HTTParty.put(url, headers: (), body: payload)
end
end
|
#auth_state_model ⇒ Object
instance accessor, for convenience
23
24
25
|
# File 'lib/lms/canvas.rb', line 23
def auth_state_model
self.class.auth_state_model
end
|
#check_result(result) ⇒ Object
170
171
172
173
174
175
176
177
178
179
180
|
# File 'lib/lms/canvas.rb', line 170
def check_result(result)
code = result.response.code.to_i
return result if [200, 201].include?(code)
if code == 401 && result.["www-authenticate"] == 'Bearer realm="canvas-lms"'
raise LMS::API::RefreshTokenRequired
end
raise LMS::API::InvalidAPIRequestException, api_error(result)
end
|
#full_url(api_url, use_api_prefix = true) ⇒ Object
93
94
95
96
97
98
99
100
101
102
103
|
# File 'lib/lms/canvas.rb', line 93
def full_url(api_url, use_api_prefix = true)
if api_url[0...4] == "http"
api_url
else
if use_api_prefix
"#{@lms_uri}/api/v1/#{api_url}"
else
"#{@lms_uri}/#{api_url}"
end
end
end
|
#get_next_url(link) ⇒ Object
188
189
190
191
192
193
|
# File 'lib/lms/canvas.rb', line 188
def get_next_url(link)
return nil if link.blank?
if url = link.split(",").find{ |l| l.split(";")[1].strip == 'rel="next"' }
url.split(";")[0].gsub(/[\<\>\s]/, "")
end
end
|
86
87
88
89
90
91
|
# File 'lib/lms/canvas.rb', line 86
def ( = {})
{
"Authorization" => "Bearer #{@authentication.token}",
"User-Agent" => "LMS-API Ruby"
}.merge()
end
|
#lock ⇒ Object
Obtains a lock (via the API.auth_state_model interface) and yields an authentication object corresponding to self.authentication.id. The object is returned when the block finishes.
74
75
76
77
78
79
80
81
82
83
84
|
# File 'lib/lms/canvas.rb', line 74
def lock
auth_state_model.transaction do
record = auth_state_model.
lock(true).
find(authentication.id)
yield record
record
end
end
|
#proxy(type, params, payload = nil, get_all = false) ⇒ Object
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
|
# File 'lib/lms/canvas.rb', line 195
def proxy(type, params, payload = nil, get_all = false)
= {
"Content-Type" => "application/json"
}
method = LMS::CANVAS_URLs[type][:method]
url = LMS::API.lms_url(type, params, payload)
payload_json = payload.to_json
case method
when "GET"
if block_given?
api_get_blocks_request(url, ) do |result|
yield result
end
elsif get_all
api_get_all_request(url, )
else
api_get_request(url, )
end
when "POST"
api_post_request(url, payload_json, )
when "PUT"
api_put_request(url, payload_json, )
when "DELETE"
api_delete_request(url, )
else
raise LMS::API::InvalidAPIMethodRequestException "Invalid method type: #{method}"
end
rescue LMS::API::InvalidAPIRequestException => ex
error = ex.to_s
error << "API Request Url: #{url} \n"
error << "API Request Params: #{params} \n"
error << "API Request Payload: #{payload} \n"
new_ex = LMS::API::InvalidAPIRequestFailedException.new(error)
new_ex.set_backtrace(ex.backtrace)
raise new_ex
end
|
#refresh_token ⇒ Object
160
161
162
163
164
165
166
167
168
|
# File 'lib/lms/canvas.rb', line 160
def refresh_token
payload = {
grant_type: "refresh_token"
}.merge(@refresh_token_options)
url = full_url("login/oauth2/token", false)
result = HTTParty.post(url, headers: , body: payload)
raise LMS::API::RefreshTokenFailedException, api_error(result) unless [200, 201].include?(result.response.code.to_i)
result["access_token"]
end
|
#refreshably ⇒ Object
151
152
153
154
155
156
157
158
|
# File 'lib/lms/canvas.rb', line 151
def refreshably
result = yield
check_result(result)
rescue LMS::API::RefreshTokenRequired => ex
raise ex if @refresh_token_options.blank?
@authentication = @@on_auth.call(self)
retry
end
|