forked from instructure/canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_outcomes.rb
More file actions
401 lines (345 loc) · 14.5 KB
/
Copy pathbasic_outcomes.rb
File metadata and controls
401 lines (345 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
234
235
236
237
238
239
240
241
242
243
244
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#
# Copyright (C) 2013 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
require 'nokogiri'
module BasicLTI
module BasicOutcomes
class Unauthorized < StandardError
def response_status
401
end
end
class InvalidRequest < StandardError
def response_status
415
end
end
class InvalidSourceId < StandardError
end
SOURCE_ID_REGEX = %r{^(\d+)-(\d+)-(\d+)-(\d+)-(\w+)$}
def self.decode_source_id(tool, sourceid)
tool.shard.activate do
raise InvalidSourceId, 'Invalid sourcedid' if sourceid.blank?
md = sourceid.match(SOURCE_ID_REGEX)
raise InvalidSourceId, 'Invalid sourcedid' unless md
new_encoding = [md[1], md[2], md[3], md[4]].join('-')
raise InvalidSourceId, 'Invalid signature' unless Canvas::Security.
verify_hmac_sha1(md[5], new_encoding, key: tool.shard.settings[:encryption_key])
raise InvalidSourceId, 'Tool is invalid' unless tool.id == md[1].to_i
course = Course.active.where(id: md[2]).first
raise InvalidSourceId, 'Course is invalid' unless course
user = course.student_enrollments.active.where(user_id: md[4]).first.try(:user)
raise InvalidSourceId, 'User is no longer in course' unless user
assignment = course.assignments.active.where(id: md[3]).first
raise InvalidSourceId, 'Assignment is invalid' unless assignment
tag = assignment.external_tool_tag if assignment
raise InvalidSourceId, 'Assignment is no longer associated with this tool' unless tag and tool.
matches_url?(tag.url, false) and tool.workflow_state != 'deleted'
return course, assignment, user
end
end
def self.process_request(tool, xml)
res = LtiResponse.new(xml)
unless res.handle_request(tool)
res.code_major = 'unsupported'
res.description = 'Request could not be handled. ¯\_(ツ)_/¯'
end
return res
end
def self.process_legacy_request(tool, params)
res = LtiResponse::Legacy.new(params)
unless res.handle_request(tool)
res.code_major = 'unsupported'
res.description = 'Legacy request could not be handled. ¯\_(ツ)_/¯'
end
return res
end
class LtiResponse
include TextHelper
attr_accessor :code_major, :severity, :description, :body
def initialize(lti_request)
@lti_request = lti_request
self.code_major = 'success'
self.severity = 'status'
end
def sourcedid
@lti_request.at_css('imsx_POXBody sourcedGUID > sourcedId').try(:content)
end
def message_ref_identifier
@lti_request.at_css('imsx_POXHeader imsx_messageIdentifier').try(:content)
end
def operation_ref_identifier
tag = @lti_request.at_css('imsx_POXBody *:first').try(:name)
tag && tag.sub(%r{Request$}, '')
end
def result_score
@lti_request.at_css('imsx_POXBody > replaceResultRequest > resultRecord > result > resultScore > textString').try(:content)
end
def result_total_score
@lti_request.at_css('imsx_POXBody > replaceResultRequest > resultRecord > result > resultTotalScore > textString').try(:content)
end
def result_data_text
@lti_request && @lti_request.at_css('imsx_POXBody > replaceResultRequest > resultRecord > result > resultData > text').try(:content)
end
def result_data_url
@lti_request && @lti_request.at_css('imsx_POXBody > replaceResultRequest > resultRecord > result > resultData > url').try(:content)
end
def result_data_download_url
url = @lti_request && @lti_request.at_css('imsx_POXBody > replaceResultRequest > resultRecord > result > resultData > downloadUrl').try(:content)
name = @lti_request && @lti_request.at_css('imsx_POXBody > replaceResultRequest > resultRecord > result > resultData > documentName').try(:content)
return {
url: url,
name: name
} if url && name
end
def result_data_launch_url
@lti_request && @lti_request.at_css('imsx_POXBody > replaceResultRequest > resultRecord > result > resultData > ltiLaunchUrl').try(:content)
end
def to_xml
xml = LtiResponse.envelope.dup
xml.at_css('imsx_POXHeader imsx_statusInfo imsx_codeMajor').content = code_major
xml.at_css('imsx_POXHeader imsx_statusInfo imsx_severity').content = severity
xml.at_css('imsx_POXHeader imsx_statusInfo imsx_description').content = description
xml.at_css('imsx_POXHeader imsx_statusInfo imsx_messageRefIdentifier').content = message_ref_identifier
xml.at_css('imsx_POXHeader imsx_statusInfo imsx_operationRefIdentifier').content = operation_ref_identifier
xml.at_css('imsx_POXBody').inner_html = body if body.present?
xml.to_s
end
def self.envelope
return @envelope if @envelope
@envelope = Nokogiri::XML.parse <<-XML
<imsx_POXEnvelopeResponse xmlns = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
<imsx_POXHeader>
<imsx_POXResponseHeaderInfo>
<imsx_version>V1.0</imsx_version>
<imsx_messageIdentifier></imsx_messageIdentifier>
<imsx_statusInfo>
<imsx_codeMajor></imsx_codeMajor>
<imsx_severity>status</imsx_severity>
<imsx_description></imsx_description>
<imsx_messageRefIdentifier></imsx_messageRefIdentifier>
<imsx_operationRefIdentifier></imsx_operationRefIdentifier>
</imsx_statusInfo>
</imsx_POXResponseHeaderInfo>
</imsx_POXHeader>
<imsx_POXBody>
</imsx_POXBody>
</imsx_POXEnvelopeResponse>
XML
@envelope.encoding = 'UTF-8'
@envelope
end
def handle_request(tool)
#check if we recognize the xml structure
return false unless operation_ref_identifier
# verify the lis_result_sourcedid param, which will be a canvas-signed
# tuple of (course, assignment, user) to ensure that only this launch of
# the tool is attempting to modify this data.
source_id = self.sourcedid
begin
course, assignment, user = BasicLTI::BasicOutcomes.decode_source_id(tool, source_id)
rescue InvalidSourceId => e
self.code_major = 'failure'
self.description = e.to_s
self.body = "<#{operation_ref_identifier}Response />"
return true
end
op = self.operation_ref_identifier
if self.respond_to?("handle_#{op}", true)
return self.send("handle_#{op}", tool, course, assignment, user)
end
false
end
protected
def handle_replaceResult(_tool, _course, assignment, user)
text_value = self.result_score
new_score = Float(text_value) rescue false
raw_score = Float(self.result_total_score) rescue false
error_message = nil
submission_hash = {}
existing_submission = assignment.submissions.where(user_id: user.id).first
if (text = result_data_text)
submission_hash[:body] = text
submission_hash[:submission_type] = 'online_text_entry'
elsif (url = result_data_url)
submission_hash[:url] = url
submission_hash[:submission_type] = 'online_url'
elsif (result_data = result_data_download_url)
url = result_data[:url]
attachment = Attachment.create!(
shard: user.shard,
context: user,
file_state: 'deleted',
workflow_state: 'unattached',
filename: result_data[:name],
display_name: result_data[:name],
user: user
)
submission_hash[:attachments] = [attachment]
submission_hash[:submission_type] = 'online_upload'
elsif (launch_url = result_data_launch_url)
submission_hash[:url] = launch_url
submission_hash[:submission_type] = 'basic_lti_launch'
elsif !existing_submission || existing_submission.submission_type.blank?
submission_hash[:submission_type] = 'external_tool'
end
if raw_score
submission_hash[:grade] = raw_score
submission_hash[:grader_id] = -_tool.id
elsif new_score
if (0.0 .. 1.0).include?(new_score)
submission_hash[:grade] = "#{round_if_whole(new_score * 100)}%"
submission_hash[:grader_id] = -_tool.id
else
error_message = I18n.t('lib.basic_lti.bad_score', "Score is not between 0 and 1")
end
elsif !text && !url && !launch_url
error_message = I18n.t('lib.basic_lti.no_score', "No score given")
end
if error_message
self.code_major = 'failure'
self.description = error_message
elsif assignment.grading_type != "pass_fail" && (assignment.points_possible.nil?)
unless submission = Submission.where(user_id: user.id, assignment_id: assignment).first
submission = Submission.create!(submission_hash.merge(:user => user,
:assignment => assignment))
end
submission.submission_comments.create!(:comment => I18n.t('lib.basic_lti.no_points_comment', <<-NO_POINTS, :grade => submission_hash[:grade]))
An external tool attempted to grade this assignment as %{grade}, but was unable
to because the assignment has no points possible.
NO_POINTS
self.code_major = 'failure'
self.description = I18n.t('lib.basic_lti.no_points_possible', 'Assignment has no points possible.')
else
if attachment
job_options = {
:priority => Delayed::LOW_PRIORITY,
:max_attempts => 1,
:n_strand => 'file_download'
}
send_later_enqueue_args(:fetch_attachment_and_save_submission, job_options, url, attachment, _tool, submission_hash, assignment, user, new_score, raw_score)
else
create_homework_submission _tool, submission_hash, assignment, user, new_score, raw_score
end
end
self.body = "<replaceResultResponse />"
true
end
def create_homework_submission(_tool, submission_hash, assignment, user, new_score, raw_score)
if submission_hash[:submission_type].present? && submission_hash[:submission_type] != 'external_tool'
@submission = assignment.submit_homework(user, submission_hash.clone)
end
if new_score || raw_score
submission_hash[:grade] = (new_score >= 1 ? "pass" : "fail") if assignment.grading_type == "pass_fail"
submission_hash[:grader_id] = -_tool.id
@submission = assignment.grade_student(user, submission_hash).first
end
if @submission
@submission.save
else
self.code_major = 'failure'
self.description = I18n.t('lib.basic_lti.no_submission_created', 'This outcome request failed to create a new homework submission.')
end
end
def handle_deleteResult(tool, _course, assignment, user)
assignment.grade_student(user, :grade => nil, grader_id: -tool.id)
self.body = "<deleteResultResponse />"
true
end
def handle_readResult(tool, course, assignment, user)
@submission = assignment.submission_for_student(user)
self.body = %{
<readResultResponse>
<result>
<resultScore>
<language>en</language>
<textString>#{submission_score}</textString>
</resultScore>
</result>
</readResultResponse>
}
true
end
def fetch_attachment_and_save_submission(url, attachment, _tool, submission_hash, assignment, user, new_score, raw_score)
attachment.clone_url(url, 'rename', true)
create_homework_submission _tool, submission_hash, assignment, user, new_score, raw_score
end
def submission_score
if @submission.try(:graded?)
raw_score = @submission.assignment.score_to_grade_percent(@submission.score)
raw_score / 100.0
end
end
class Legacy < LtiResponse
def initialize(params)
super(nil)
@params = params
end
def sourcedid
@params[:sourcedid]
end
def result_score
@params[:result_resultscore_textstring]
end
def operation_ref_identifier
case @params[:lti_message_type].try(:downcase)
when 'basic-lis-updateresult'
'replaceResult'
when 'basic-lis-readresult'
'readResult'
when 'basic-lis-deleteresult'
'deleteResult'
end
end
def to_xml
xml = LtiResponse::Legacy.envelope.dup
xml.at_css('message_response > statusinfo > codemajor').content = code_major.capitalize
if score = submission_score
xml.at_css('message_response > result > sourcedid').content = sourcedid
xml.at_css('message_response > result > resultscore > textstring').content = score
else
xml.at_css('message_response > result').remove
end
xml.to_s
end
def self.envelope
return @envelope if @envelope
@envelope = Nokogiri::XML.parse <<-XML
<message_response>
<lti_message_type></lti_message_type>
<statusinfo>
<codemajor></codemajor>
<severity>Status</severity>
<codeminor>fullsuccess</codeminor>
</statusinfo>
<result>
<sourcedid></sourcedid>
<resultscore>
<resultvaluesourcedid>decimal</resultvaluesourdedid>
<textstring></textstring>
<language>en-US</language>
</resultscore>
</result>
</message_response>
XML
@envelope.encoding = 'UTF-8'
@envelope
end
end
end
end
end