forked from openedx/edx-proctoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
2603 lines (2203 loc) · 102 KB
/
Copy pathapi.py
File metadata and controls
2603 lines (2203 loc) · 102 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=too-many-branches, too-many-lines, too-many-statements
"""
In-Proc API (aka Library) for the edx_proctoring subsystem. This is not to be confused with a HTTP REST
API which is in the views.py file, per edX coding standards
"""
import logging
import uuid
from datetime import datetime, timedelta
import pytz
from opaque_keys import InvalidKeyError
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.core.mail.message import EmailMessage
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop
from edx_proctoring import constants
from edx_proctoring.backends import get_backend_provider
from edx_proctoring.exceptions import (
BackendProviderCannotRegisterAttempt,
BackendProviderOnboardingException,
BackendProviderSentNoAttemptID,
ProctoredExamAlreadyExists,
ProctoredExamIllegalStatusTransition,
ProctoredExamNotActiveException,
ProctoredExamNotFoundException,
ProctoredExamPermissionDenied,
ProctoredExamReviewPolicyAlreadyExists,
ProctoredExamReviewPolicyNotFoundException,
StudentExamAttemptAlreadyExistsException,
StudentExamAttemptDoesNotExistsException,
StudentExamAttemptedAlreadyStarted,
StudentExamAttemptOnPastDueProctoredExam
)
from edx_proctoring.models import (
ProctoredExam,
ProctoredExamReviewPolicy,
ProctoredExamSoftwareSecureReview,
ProctoredExamStudentAllowance,
ProctoredExamStudentAttempt
)
from edx_proctoring.runtime import get_runtime_service
from edx_proctoring.serializers import (
ProctoredExamReviewPolicySerializer,
ProctoredExamSerializer,
ProctoredExamStudentAllowanceSerializer,
ProctoredExamStudentAttemptSerializer
)
from edx_proctoring.statuses import ProctoredExamStudentAttemptStatus
from edx_proctoring.utils import (
emit_event,
get_exam_due_date,
has_due_date_passed,
humanized_time,
is_reattempting_exam,
obscured_user_id,
verify_and_add_wait_deadline
)
log = logging.getLogger(__name__)
SHOW_EXPIRY_MESSAGE_DURATION = 1 * 60 # duration within which expiry message is shown for a timed-out exam
APPROVED_STATUS = 'approved'
REJECTED_GRADE_OVERRIDE_EARNED = 0.0
USER_MODEL = get_user_model()
def create_exam(course_id, content_id, exam_name, time_limit_mins, due_date=None,
is_proctored=True, is_practice_exam=False, external_id=None, is_active=True, hide_after_due=False,
backend=None):
"""
Creates a new ProctoredExam entity, if the course_id/content_id pair do not already exist.
If that pair already exists, then raise exception.
Returns: id (PK)
"""
if ProctoredExam.get_exam_by_content_id(course_id, content_id) is not None:
err_msg = (
'Attempted to create proctored exam with course_id={course_id} and content_id={content_id}, '
'but this exam already exists.'.format(course_id=course_id, content_id=content_id)
)
raise ProctoredExamAlreadyExists(err_msg)
proctored_exam = ProctoredExam.objects.create(
course_id=course_id,
content_id=content_id,
external_id=external_id,
exam_name=exam_name,
time_limit_mins=time_limit_mins,
due_date=due_date,
is_proctored=is_proctored,
is_practice_exam=is_practice_exam,
is_active=is_active,
hide_after_due=hide_after_due,
backend=backend or settings.PROCTORING_BACKENDS.get('DEFAULT', None),
)
log_msg = (
'Created exam (exam_id={exam_id}) with parameters: course_id={course_id}, '
'content_id={content_id}, exam_name={exam_name}, time_limit_mins={time_limit_mins}, '
'is_proctored={is_proctored}, is_practice_exam={is_practice_exam}, '
'external_id={external_id}, is_active={is_active}, hide_after_due={hide_after_due}'.format(
exam_id=proctored_exam.id,
course_id=course_id, content_id=content_id,
exam_name=exam_name, time_limit_mins=time_limit_mins,
is_proctored=is_proctored, is_practice_exam=is_practice_exam,
external_id=external_id, is_active=is_active, hide_after_due=hide_after_due
)
)
log.info(log_msg)
# read back exam so we can emit an event on it
exam = get_exam_by_id(proctored_exam.id)
emit_event(exam, 'created')
return proctored_exam.id
def create_exam_review_policy(exam_id, set_by_user_id, review_policy):
"""
Creates a new exam_review_policy entity, if the review_policy
for exam_id does not already exist. If it exists, then raise exception.
Arguments:
exam_id: the ID of the exam with which the review policy is to be associated
set_by_user_id: the ID of the user setting this review policy
review_policy: the review policy for the exam
Returns: id (PK)
"""
exam_review_policy = ProctoredExamReviewPolicy.get_review_policy_for_exam(exam_id)
if exam_review_policy is not None:
err_msg = (
'user_id={user_id} attempted to create an exam review policy for '
'exam_id={exam_id}, but a review policy for this exam already exists.'.format(
user_id=set_by_user_id,
exam_id=exam_id,
)
)
raise ProctoredExamReviewPolicyAlreadyExists(err_msg)
exam_review_policy = ProctoredExamReviewPolicy.objects.create(
proctored_exam_id=exam_id,
set_by_user_id=set_by_user_id,
review_policy=review_policy,
)
log_msg = (
'Created ProctoredExamReviewPolicy (review_policy={review_policy}) '
'with parameters: exam_id={exam_id}, set_by_user_id={set_by_user_id}'.format(
exam_id=exam_id,
review_policy=review_policy,
set_by_user_id=set_by_user_id,
)
)
log.info(log_msg)
return exam_review_policy.id
def update_review_policy(exam_id, set_by_user_id, review_policy):
"""
Given a exam id, update/remove the existing record, otherwise raise exception if not found.
Arguments:
exam_id: the ID of the exam whose review policy is being updated
set_by_user_id: the ID of the user updating this review policy
review_policy: the review policy for the exam
Returns: review_policy_id
"""
log_msg = (
'Updating exam review policy with exam_id={exam_id} '
'set_by_user_id={set_by_user_id}, review_policy={review_policy} '
.format(
exam_id=exam_id, set_by_user_id=set_by_user_id, review_policy=review_policy
)
)
log.info(log_msg)
exam_review_policy = ProctoredExamReviewPolicy.get_review_policy_for_exam(exam_id)
if exam_review_policy is None:
err_msg = (
'user_id={user_id} attempted to update exam review policy for '
'exam_id={exam_id}, but this exam does not have a review policy.'.format(
user_id=set_by_user_id,
exam_id=exam_id,
)
)
raise ProctoredExamReviewPolicyNotFoundException(err_msg)
if review_policy:
exam_review_policy.set_by_user_id = set_by_user_id
exam_review_policy.review_policy = review_policy
exam_review_policy.save()
msg = (
'Updated exam review policy for exam_id={exam_id}, set_by_user_id={set_by_user_id}'.format(
set_by_user_id=set_by_user_id,
exam_id=exam_id,
)
)
log.info(msg)
else:
exam_review_policy.delete()
msg = (
'Removed exam review policy for exam_id={exam_id}, set_by_user_id={set_by_user_id}'.format(
set_by_user_id=set_by_user_id,
exam_id=exam_id,
)
)
log.info(msg)
def remove_review_policy(exam_id):
"""
Given a exam id, remove the existing record, otherwise raise exception if not found.
"""
log_msg = 'Removing exam review policy for exam_id={exam_id}'.format(exam_id=exam_id)
log.info(log_msg)
exam_review_policy = ProctoredExamReviewPolicy.get_review_policy_for_exam(exam_id)
if exam_review_policy is None:
err_msg = (
'Attempted to remove exam remove policy for exam_id={exam_id}, but this '
'exam does not have a review policy.'.format(exam_id=exam_id)
)
raise ProctoredExamReviewPolicyNotFoundException(err_msg)
exam_review_policy.delete()
def get_review_policy_by_exam_id(exam_id):
"""
Looks up exam by the Primary Key. Raises exception if not found.
Returns dictionary version of the Django ORM object
e.g.
{
"id": 1
"proctored_exam": "{object}",
"set_by_user": "{object}",
"exam_review_rules": "review rules value"
"created": "datetime",
"modified": "datetime"
}
"""
exam_review_policy = ProctoredExamReviewPolicy.get_review_policy_for_exam(exam_id)
if exam_review_policy is None:
err_msg = (
'Attempted to get exam review policy for exam_id={exam_id}, but this review '
'policy does not exist.'.format(exam_id=exam_id)
)
raise ProctoredExamReviewPolicyNotFoundException(err_msg)
return ProctoredExamReviewPolicySerializer(exam_review_policy).data
def _get_review_policy_by_exam_id(exam_id):
"""
Looks up exam by the primary key. Returns None if not found
Returns review_policy field of the Django ORM object
"""
try:
exam_review_policy = get_review_policy_by_exam_id(exam_id)
return ProctoredExamReviewPolicySerializer(exam_review_policy).data['review_policy']
except ProctoredExamReviewPolicyNotFoundException:
return None
def update_exam(exam_id, exam_name=None, time_limit_mins=None, due_date=constants.MINIMUM_TIME,
is_proctored=None, is_practice_exam=None, external_id=None, is_active=None,
hide_after_due=None, backend=None):
"""
Given a Django ORM id, update the existing record, otherwise raise exception if not found.
If an argument is not passed in, then do not change it's current value.
Returns: id
"""
log_msg = (
'Updating exam_id={exam_id} with parameters '
'exam_name={exam_name}, time_limit_mins={time_limit_mins}, due_date={due_date}'
'is_proctored={is_proctored}, is_practice_exam={is_practice_exam}, '
'external_id={external_id}, is_active={is_active}, hide_after_due={hide_after_due}, '
'backend={backend}'.format(
exam_id=exam_id, exam_name=exam_name, time_limit_mins=time_limit_mins,
due_date=due_date, is_proctored=is_proctored, is_practice_exam=is_practice_exam,
external_id=external_id, is_active=is_active, hide_after_due=hide_after_due, backend=backend
)
)
log.info(log_msg)
proctored_exam = ProctoredExam.get_exam_by_id(exam_id)
if proctored_exam is None:
err_msg = (
'Attempted to update exam_id={exam_id}, but this exam does not exist.'.format(exam_id=exam_id)
)
raise ProctoredExamNotFoundException(err_msg)
if exam_name is not None:
proctored_exam.exam_name = exam_name
if time_limit_mins is not None:
proctored_exam.time_limit_mins = time_limit_mins
if due_date is not constants.MINIMUM_TIME:
proctored_exam.due_date = due_date
if is_proctored is not None:
proctored_exam.is_proctored = is_proctored
if is_practice_exam is not None:
proctored_exam.is_practice_exam = is_practice_exam
if external_id is not None:
proctored_exam.external_id = external_id
if is_active is not None:
proctored_exam.is_active = is_active
if hide_after_due is not None:
proctored_exam.hide_after_due = hide_after_due
if backend is not None:
proctored_exam.backend = backend
proctored_exam.save()
# read back exam so we can emit an event on it
exam = get_exam_by_id(proctored_exam.id)
emit_event(exam, 'updated')
return proctored_exam.id
def get_exam_by_id(exam_id):
"""
Looks up exam by the Primary Key. Raises exception if not found.
Returns dictionary version of the Django ORM object
e.g.
{
"course_id": "edX/DemoX/Demo_Course",
"content_id": "123",
"external_id": "",
"exam_name": "Midterm",
"time_limit_mins": 90,
"is_proctored": true,
"is_active": true
}
"""
proctored_exam = ProctoredExam.get_exam_by_id(exam_id)
if proctored_exam is None:
err_msg = (
'Attempted to get exam_id={exam_id}, but this exam does not exist.'.format(exam_id=exam_id)
)
raise ProctoredExamNotFoundException(err_msg)
serialized_exam_object = ProctoredExamSerializer(proctored_exam)
return serialized_exam_object.data
def get_exam_by_content_id(course_id, content_id):
"""
Looks up exam by the course_id/content_id pair. Raises exception if not found.
Returns dictionary version of the Django ORM object
e.g.
{
"course_id": "edX/DemoX/Demo_Course",
"content_id": "123",
"external_id": "",
"exam_name": "Midterm",
"time_limit_mins": 90,
"is_proctored": true,
"is_active": true
}
"""
proctored_exam = ProctoredExam.get_exam_by_content_id(course_id, content_id)
if proctored_exam is None:
err_msg = (
'Cannot find proctored exam in course_id={course_id} with content_id={content_id}'.format(
course_id=course_id, content_id=content_id
)
)
raise ProctoredExamNotFoundException(err_msg)
serialized_exam_object = ProctoredExamSerializer(proctored_exam)
return serialized_exam_object.data
def add_allowance_for_user(exam_id, user_info, key, value):
"""
Adds (or updates) an allowance for a user within a given exam
"""
log_msg = (
'Adding allowance key={key} with value={value} for exam_id={exam_id} '
'for user={user_info} '.format(
key=key, value=value, exam_id=exam_id, user_info=user_info
)
)
log.info(log_msg)
try:
student_allowance, action = ProctoredExamStudentAllowance.add_allowance_for_user(exam_id, user_info, key, value)
except ProctoredExamNotActiveException as error:
# let this exception raised so that we get 400 in case of inactive exam
raise ProctoredExamNotActiveException from error
if student_allowance is not None:
# emit an event for 'allowance.created|updated'
data = {
'allowance_user_id': student_allowance.user.id,
'allowance_key': student_allowance.key,
'allowance_value': student_allowance.value
}
exam = get_exam_by_id(exam_id)
emit_event(exam, 'allowance.{action}'.format(action=action), override_data=data)
def get_allowances_for_course(course_id):
"""
Get all the allowances for the course.
"""
student_allowances = ProctoredExamStudentAllowance.get_allowances_for_course(
course_id
)
return [ProctoredExamStudentAllowanceSerializer(allowance).data for allowance in student_allowances]
def remove_allowance_for_user(exam_id, user_id, key):
"""
Deletes an allowance for a user within a given exam.
"""
log_msg = (
'Removing allowance key={key} for exam_id={exam_id} for user_id={user_id}'.format(
key=key, exam_id=exam_id, user_id=user_id
)
)
log.info(log_msg)
student_allowance = ProctoredExamStudentAllowance.get_allowance_for_user(exam_id, user_id, key)
if student_allowance is not None:
student_allowance.delete()
# emit an event for 'allowance.deleted'
data = {
'allowance_user_id': student_allowance.user.id,
'allowance_key': student_allowance.key,
'allowance_value': student_allowance.value
}
exam = get_exam_by_id(exam_id)
emit_event(exam, 'allowance.deleted', override_data=data)
def _check_for_attempt_timeout(attempt):
"""
Helper method to see if the status of an
exam needs to be updated, e.g. timeout
"""
if not attempt:
return attempt
# right now the only adjustment to
# status is transitioning to timeout
has_started_exam = (
attempt and
attempt.get('started_at') and
ProctoredExamStudentAttemptStatus.is_incomplete_status(attempt.get('status'))
)
if has_started_exam:
now_utc = datetime.now(pytz.UTC)
expires_at = attempt['started_at'] + timedelta(minutes=attempt['allowed_time_limit_mins'])
has_time_expired = now_utc > expires_at
if has_time_expired:
update_attempt_status(
attempt['id'],
ProctoredExamStudentAttemptStatus.timed_out,
timeout_timestamp=expires_at
)
attempt = get_exam_attempt_by_id(attempt['id'])
return attempt
def _get_exam_attempt(exam_attempt_obj):
"""
Helper method to commonalize all query patterns
"""
if not exam_attempt_obj:
return None
serialized_attempt_obj = ProctoredExamStudentAttemptSerializer(exam_attempt_obj)
attempt = serialized_attempt_obj.data
attempt = _check_for_attempt_timeout(attempt)
return attempt
def get_current_exam_attempt(exam_id, user_id):
"""
Args:
int: exam id
int: user_id
Returns:
dict: our exam attempt
"""
exam_attempt_obj = ProctoredExamStudentAttempt.objects.get_current_exam_attempt(exam_id, user_id)
return _get_exam_attempt(exam_attempt_obj)
def get_exam_attempt_by_id(attempt_id):
"""
Args:
int: exam attempt id
Returns:
dict: our exam attempt
"""
exam_attempt_obj = ProctoredExamStudentAttempt.objects.get_exam_attempt_by_id(attempt_id)
return _get_exam_attempt(exam_attempt_obj)
def get_exam_attempt_by_external_id(external_id):
"""
Args:
str: exam attempt external_id
Returns:
dict: our exam attempt
"""
exam_attempt_obj = ProctoredExamStudentAttempt.objects.get_exam_attempt_by_external_id(external_id)
return _get_exam_attempt(exam_attempt_obj)
def get_exam_attempt_by_code(attempt_code):
"""
Args:
str: exam attempt attempt_code
Returns:
dict: our exam attempt
"""
exam_attempt_obj = ProctoredExamStudentAttempt.objects.get_exam_attempt_by_code(attempt_code)
return _get_exam_attempt(exam_attempt_obj)
def update_exam_attempt(attempt_id, **kwargs):
"""
Update exam_attempt
"""
exam_attempt_obj = ProctoredExamStudentAttempt.objects.get_exam_attempt_by_id(attempt_id)
if not exam_attempt_obj:
err_msg = (
'Attempted to update exam attempt with attempt_id={attempt_id} but '
'this attempt does not exist.'.format(attempt_id=attempt_id)
)
raise StudentExamAttemptDoesNotExistsException(err_msg)
for key, value in kwargs.items():
# only allow a limit set of fields to update
# namely because status transitions can trigger workflow
if key not in [
'last_poll_timestamp',
'last_poll_ipaddr',
'is_status_acknowledged',
'time_remaining_seconds',
]:
err_msg = (
'You cannot call into update_exam_attempt to change '
'field={key}. (attempt_id={attempt_id})'.format(key=key, attempt_id=attempt_id)
)
raise ProctoredExamPermissionDenied(err_msg)
setattr(exam_attempt_obj, key, value)
exam_attempt_obj.save()
def is_exam_passed_due(exam, user=None):
"""
Return whether the due date has passed.
Uses edx_when to lookup the date for the subsection.
"""
return has_due_date_passed(get_exam_due_date(exam, user=user))
def _was_review_status_acknowledged(is_status_acknowledged, exam):
"""
Return True if review status has been acknowledged and due date has been passed
"""
return is_status_acknowledged and is_exam_passed_due(exam)
def _create_and_decline_attempt(exam_id, user_id):
"""
It will create the exam attempt and change the attempt's status to decline.
it will auto-decline further exams too
"""
attempt_id = create_exam_attempt(exam_id, user_id)
update_attempt_status(
attempt_id,
ProctoredExamStudentAttemptStatus.declined,
raise_if_not_found=False
)
def _register_proctored_exam_attempt(user_id, exam_id, exam, attempt_code, review_policy):
"""
Call the proctoring backend to register the exam attempt. If there are exceptions
the external_id returned might be None. If the backend have onboarding status errors,
it will be returned with force_status
"""
scheme = 'https' if getattr(settings, 'HTTPS', 'on') == 'on' else 'http'
lms_host = '{scheme}://{hostname}'.format(scheme=scheme, hostname=settings.SITE_NAME)
obs_user_id = obscured_user_id(user_id, exam['backend'])
allowed_time_limit_mins = _calculate_allowed_mins(exam, user_id)
review_policy_exception = ProctoredExamStudentAllowance.get_review_policy_exception(exam_id, user_id)
# get the name of the user, if the service is available
full_name = ''
email = None
external_id = None
force_status = None
credit_service = get_runtime_service('credit')
if credit_service:
credit_state = credit_service.get_credit_state(user_id, exam['course_id'])
if credit_state:
full_name = credit_state['profile_fullname']
email = credit_state['student_email']
context = {
'lms_host': lms_host,
'time_limit_mins': allowed_time_limit_mins,
'attempt_code': attempt_code,
'is_sample_attempt': exam['is_practice_exam'],
'user_id': obs_user_id,
'full_name': full_name,
'email': email
}
# see if there is an exam review policy for this exam
# if so, then pass it into the provider
if review_policy:
context.update({
'review_policy': review_policy.review_policy
})
# see if there is a review policy exception for this *user*
# exceptions are granted on a individual basis as an
# allowance
if review_policy_exception:
context.update({
'review_policy_exception': review_policy_exception
})
# now call into the backend provider to register exam attempt
try:
external_id = get_backend_provider(exam).register_exam_attempt(
exam,
context=context,
)
except BackendProviderSentNoAttemptID as ex:
log_message = (
'Failed to get the attempt ID for user_id={user_id} '
'for exam_id={exam_id} in course_id={course_id} from the '
'backend because the backend did not provide the id in API '
'response, even when the HTTP response status is {status}, '
'Response: {response}'.format(
user_id=user_id,
exam_id=exam_id,
course_id=exam['course_id'],
response=str(ex),
status=ex.http_status
)
)
log.error(log_message)
raise ex
except BackendProviderCannotRegisterAttempt as ex:
log_message = (
'Failed to create attempt for user_id={user_id} '
'for exam_id={exam_id} in course_id={course_id} '
'because backend was unable to register the attempt. '
'Status: {status}, Response: {response}'.format(
user_id=user_id,
exam_id=exam_id,
course_id=exam['course_id'],
response=str(ex),
status=ex.http_status,
)
)
log.error(log_message)
raise ex
except BackendProviderOnboardingException as ex:
force_status = ex.status
log_msg = (
'Failed to create attempt for user_id={user_id} '
'for exam_id={exam_id} in course_id={course_id} '
'because of onboarding failure: {force_status}'.format(
user_id=user_id,
exam_id=exam_id,
course_id=exam['course_id'],
force_status=force_status
)
)
log.error(log_msg)
return external_id, force_status
def create_exam_attempt(exam_id, user_id, taking_as_proctored=False):
"""
Creates an exam attempt for user_id against exam_id. There should only
be one exam_attempt per user per exam, with one exception described below.
Multiple attempts by user will be archived in a separate table.
If the attempt enters an error state, it must be marked as ready to resume,
and another attempt must be made in order to resume the exam. This is the
only case where multiple attempts for the same exam should exist.
"""
# for now the student is allowed the exam default
exam = get_exam_by_id(exam_id)
log_msg = (
'Creating exam attempt for exam_id={exam_id} for user_id={user_id} '
'in course_id={course_id} with taking_as_proctored={taking_as_proctored}'.format(
exam_id=exam_id,
user_id=user_id,
course_id=exam['course_id'],
taking_as_proctored=taking_as_proctored,
)
)
log.info(log_msg)
existing_attempt = ProctoredExamStudentAttempt.objects.get_current_exam_attempt(exam_id, user_id)
time_remaining_seconds = None
# only practice exams and exams with resume states may have multiple attempts
if existing_attempt:
if ProctoredExamStudentAttemptStatus.is_resume_status(existing_attempt.status):
# save remaining time and mark the most recent attempt as resumed, if it isn't already
time_remaining_seconds = existing_attempt.time_remaining_seconds
mark_exam_attempt_as_resumed(existing_attempt.id)
elif not existing_attempt.is_sample_attempt:
err_msg = (
'Cannot create new exam attempt for exam_id={exam_id} and '
'user_id={user_id} in course_id={course_id} because it already exists!'
).format(exam_id=exam_id, user_id=user_id, course_id=exam['course_id'])
raise StudentExamAttemptAlreadyExistsException(err_msg)
attempt_code = str(uuid.uuid4()).upper()
review_policy = ProctoredExamReviewPolicy.get_review_policy_for_exam(exam_id)
external_id = None
force_status = None
if is_exam_passed_due(exam, user=user_id) and taking_as_proctored:
err_msg = (
'user_id={user_id} trying to create exam attempt for past due proctored '
'exam_id={exam_id} in course_id={course_id}. Do not register an exam attempt!'.format(
exam_id=exam_id, user_id=user_id, course_id=exam['course_id']
)
)
raise StudentExamAttemptOnPastDueProctoredExam(err_msg)
if taking_as_proctored:
external_id, force_status = _register_proctored_exam_attempt(
user_id, exam_id, exam, attempt_code, review_policy
)
attempt = ProctoredExamStudentAttempt.create_exam_attempt(
exam_id,
user_id,
'', # student name is TBD
attempt_code,
taking_as_proctored,
exam['is_practice_exam'],
external_id,
review_policy_id=review_policy.id if review_policy else None,
status=force_status,
time_remaining_seconds=time_remaining_seconds,
)
# Emit event when exam attempt created
emit_event(exam, attempt.status, attempt=_get_exam_attempt(attempt))
log_msg = (
'Created exam attempt_id={attempt_id} for exam_id={exam_id} for '
'user_id={user_id} with taking as proctored={taking_as_proctored}. '
'attempt_code={attempt_code} was generated which has an '
'external_id={external_id}'.format(
attempt_id=attempt.id, exam_id=exam_id, user_id=user_id,
taking_as_proctored=taking_as_proctored,
attempt_code=attempt_code,
external_id=external_id
)
)
log.info(log_msg)
return attempt.id
def start_exam_attempt(exam_id, user_id):
"""
Signals the beginning of an exam attempt for a given
exam_id. If one already exists, then an exception should be thrown.
Returns: exam_attempt_id (PK)
"""
existing_attempt = ProctoredExamStudentAttempt.objects.get_current_exam_attempt(exam_id, user_id)
if not existing_attempt:
err_msg = (
'Cannot start exam attempt for exam_id={exam_id} '
'and user_id={user_id} because it does not exist!'
).format(exam_id=exam_id, user_id=user_id)
raise StudentExamAttemptDoesNotExistsException(err_msg)
return _start_exam_attempt(existing_attempt)
def start_exam_attempt_by_code(attempt_code):
"""
Signals the beginning of an exam attempt when we only have
an attempt code
"""
existing_attempt = ProctoredExamStudentAttempt.objects.get_exam_attempt_by_code(attempt_code)
if not existing_attempt:
err_msg = (
'Cannot start exam attempt for attempt_code={attempt_code} '
'because it does not exist!'
).format(attempt_code=attempt_code)
raise StudentExamAttemptDoesNotExistsException(err_msg)
return _start_exam_attempt(existing_attempt)
def _start_exam_attempt(existing_attempt):
"""
Helper method
"""
if existing_attempt.started_at and existing_attempt.status == ProctoredExamStudentAttemptStatus.started:
# cannot restart an attempt
err_msg = (
'Cannot start exam attempt for exam_id={exam_id} '
'and user_id={user_id} because it has already started!'
).format(exam_id=existing_attempt.proctored_exam.id, user_id=existing_attempt.user_id)
raise StudentExamAttemptedAlreadyStarted(err_msg)
update_attempt_status(
existing_attempt.id,
ProctoredExamStudentAttemptStatus.started
)
return existing_attempt.id
def stop_exam_attempt(attempt_id):
"""
Marks the exam attempt as completed (sets the completed_at field and updates the record)
"""
return update_attempt_status(attempt_id, ProctoredExamStudentAttemptStatus.ready_to_submit)
def mark_exam_attempt_timeout(attempt_id):
"""
Marks the exam attempt as timed_out
"""
return update_attempt_status(attempt_id, ProctoredExamStudentAttemptStatus.timed_out)
def mark_exam_attempt_as_ready(attempt_id):
"""
Marks the exam attemp as ready to start
"""
return update_attempt_status(attempt_id, ProctoredExamStudentAttemptStatus.ready_to_start)
def mark_exam_attempt_as_resumed(attempt_id):
"""
Marks the current exam attempt as resumed
"""
return update_attempt_status(attempt_id, ProctoredExamStudentAttemptStatus.resumed)
def is_state_transition_legal(from_status, to_status):
"""
Determine and return as a boolean whether a proctored exam attempt state transition
from from_status to to_status is an allowed state transition.
Arguments:
from_status: original status of a proctored exam attempt
to_status: future status of a proctored exam attempt
"""
in_completed_status = ProctoredExamStudentAttemptStatus.is_completed_status(from_status)
to_incompleted_status = ProctoredExamStudentAttemptStatus.is_incomplete_status(to_status)
# don't allow state transitions from a completed state to an incomplete state
# if a re-attempt is desired then the current attempt must be deleted
if in_completed_status and to_incompleted_status:
return False
# only allow a state transition to the ready_to_resume state from an error state
if (to_status == ProctoredExamStudentAttemptStatus.ready_to_resume and
from_status != ProctoredExamStudentAttemptStatus.error):
return False
# only allowed state transition to the resumed state from ready_to_resume (or resumed).
# this accounts for cases where the previous attempt was marked as resumed, but a new
# attempt failed to be created.
if (to_status == ProctoredExamStudentAttemptStatus.resumed and
not ProctoredExamStudentAttemptStatus.is_resume_status(from_status)):
return False
return True
def can_update_credit_grades_and_email(attempts, to_status):
"""
Determine and return as a boolean whether an attempt should trigger an update to credit and grades
Arguments:
attempts: a list of all currently active attempts for a given user_id and exam_id
to_status: future status of a proctored exam attempt
"""
statuses = [attempt['status'] for attempt in attempts]
if len(statuses) == 1:
# if there is only one attempt for a user in an exam, it can be responsible for updates to credits and grades
return True
if to_status in [ProctoredExamStudentAttemptStatus.declined, ProctoredExamStudentAttemptStatus.error]:
# can only decline/error the most recent attempt, so return true
# these should not send emails but will update credits and grades
return True
if to_status == ProctoredExamStudentAttemptStatus.submitted:
# we only want to update a submitted status if there are no rejected past attempts
for status in statuses:
if status == ProctoredExamStudentAttemptStatus.rejected:
return False
return True
if to_status == ProctoredExamStudentAttemptStatus.verified:
# if we are updating an attempt to verified, we can only return true if all other attempts are verified
for status in statuses:
if status != ProctoredExamStudentAttemptStatus.verified:
return False
return True
if to_status == ProctoredExamStudentAttemptStatus.rejected:
if (
statuses.count(ProctoredExamStudentAttemptStatus.rejected) > 1 or
ProctoredExamStudentAttemptStatus.declined in statuses
):
# if there is more than one rejection, do not update grades/certificate/email again
# or if there is a declined status, do not update grades/certificate/email again
return False
return True
return False
# pylint: disable=inconsistent-return-statements
def update_attempt_status(attempt_id, to_status,
raise_if_not_found=True, cascade_effects=True, timeout_timestamp=None,
update_attributable_to=None):
"""
Internal helper to handle state transitions of attempt status
"""
exam_attempt_obj = ProctoredExamStudentAttempt.objects.get_exam_attempt_by_id(attempt_id)
if exam_attempt_obj is None:
if raise_if_not_found:
raise StudentExamAttemptDoesNotExistsException(
'Tried to look up exam by attempt_id={attempt_id}, '
'but this attempt does not exist.'.format(attempt_id=attempt_id)
)
return
exam_id = exam_attempt_obj.proctored_exam.id
user_id = exam_attempt_obj.user.id
from_status = exam_attempt_obj.status
log_msg = (
'Updating attempt status for exam_id={exam_id} '
'for user_id={user_id} from status "{from_status}" to "{to_status}"'.format(
exam_id=exam_id, user_id=user_id, from_status=from_status, to_status=to_status
)
)
log.info(log_msg)
# In some configuration we may treat timeouts the same
# as the user saying he/she wishes to submit the exam
allow_timeout_state = settings.PROCTORING_SETTINGS.get('ALLOW_TIMED_OUT_STATE', False)