forked from apluslms/a-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewbase.py
309 lines (251 loc) · 10.6 KB
/
viewbase.py
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
from typing import Callable, List, Optional, Tuple, Union
from django.contrib.auth.models import User
from django.db import models
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.formats import date_format
from django.utils.functional import cached_property
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
from course.viewbase import CourseModuleMixin
from lib.viewbase import BaseTemplateView, BaseView
from userprofile.models import UserProfile
from userprofile.pseudonymize import format_user
from .cache.content import LearningObjectContent, ModuleContent
from .cache.hierarchy import NoSuchContent
from .cache.points import LearningObjectPoints, SubmissionEntry, ExercisePoints
from .permissions import (
ExerciseVisiblePermission,
BaseExerciseAssistantPermission,
SubmissionVisiblePermission,
ModelVisiblePermission,
)
from .models import (
LearningObject,
BaseExercise,
Submission,
RevealRule,
)
from .exercise_models import ExerciseTask
from .reveal_states import ExerciseRevealState
from .tasks import regrade_exercises
class ExerciseBaseMixin:
context_properties = ["exercise"]
exercise_kw = "exercise_path"
exercise_permission_classes = (
ExerciseVisiblePermission,
)
def get_permissions(self):
perms = super().get_permissions()
perms.extend((Perm() for Perm in self.exercise_permission_classes))
return perms
# get_exercise_object
@cached_property
def exercise(self) -> LearningObject:
return self.get_exercise_object()
class ExerciseRevealRuleMixin:
context_properties = ["feedback_revealed", "feedback_hidden_description", "model_revealed"]
@cached_property
def feedback_reveal_info(self) -> Tuple[bool, Union[str, Callable[[], str]]]:
feedback_revealed = True
feedback_hidden_description = None
if (
not self.is_course_staff
and isinstance(self.exercise, BaseExercise)
and isinstance(self.request.user, User)
):
rule = self.exercise.active_submission_feedback_reveal_rule
state = ExerciseRevealState(self.exercise, self.request.user)
feedback_revealed = rule.is_revealed(state)
if rule.trigger in (
RevealRule.TRIGGER.TIME,
RevealRule.TRIGGER.DEADLINE,
RevealRule.TRIGGER.DEADLINE_ALL,
RevealRule.TRIGGER.DEADLINE_OR_FULL_POINTS,
):
reveal_time = rule.get_reveal_time(state)
formatted_time = date_format(timezone.localtime(reveal_time), "DATETIME_FORMAT")
feedback_hidden_description = format_lazy(
_('RESULTS_WILL_BE_REVEALED -- {time}'),
time=formatted_time,
)
else:
feedback_hidden_description = _('RESULTS_ARE_CURRENTLY_HIDDEN')
return (feedback_revealed, feedback_hidden_description)
@cached_property
def feedback_revealed(self):
return self.feedback_reveal_info[0]
@cached_property
def feedback_hidden_description(self) -> str:
if callable(self.feedback_reveal_info[1]):
return self.feedback_reveal_info[1]()
return self.feedback_reveal_info[1]
@cached_property
def model_revealed(self) -> bool:
model_revealed = True
if (
not self.is_course_staff
and isinstance(self.exercise, BaseExercise)
and isinstance(self.request.user, User)
):
model_revealed = self.exercise.can_show_model_solutions_to_student(self.request.user)
return model_revealed
class ExerciseMixin(ExerciseRevealRuleMixin, ExerciseBaseMixin, CourseModuleMixin):
exercise_permission_classes = ExerciseBaseMixin.exercise_permission_classes + (
BaseExerciseAssistantPermission,
)
submission_url_name = 'submission'
exercise_url_name = 'exercise'
context_properties = ["summary", "submissions", "previous", "current", "next", "breadcrumb"]
def get_exercise_object(self):
try:
exercise_id = self.content_bare.find_path(
self.module.id,
self.kwargs[self.exercise_kw]
)
return LearningObject.objects.get(id=exercise_id)
except (NoSuchContent, LearningObject.DoesNotExist) as exc:
raise Http404("Learning object not found") from exc
def get_common_objects(self) -> None:
super().get_common_objects()
self.now = timezone.now()
self.pseudonymize = self.request.session.get("pseudonymize", False)
self.note("now", "submission_url_name", "exercise_url_name", "pseudonymize")
def get_summary_user(self) -> Optional[User]:
return self.request.user
@cached_property
def exercise_info(self) -> Tuple[
LearningObjectContent,
List[Union[ModuleContent, LearningObjectContent]],
Optional[Union[ModuleContent, LearningObjectContent]],
Optional[Union[ModuleContent, LearningObjectContent]]
]:
return self.points.find(self.exercise)
@cached_property
def current(self) -> LearningObjectContent:
if "exercise_info" in self.__dict__ or "content" in self.__dict__:
return self.exercise_info[0]
return LearningObjectContent.get(self.exercise)
@cached_property
def breadcrumb(self):
return self.exercise_info[1][1:-1]
@cached_property
def previous(self):
return self.exercise_info[2]
@cached_property
def next(self):
return self.exercise_info[3]
@cached_property
def summary(self) -> ExercisePoints:
"""Cached points for a submittable exercise. Raises AttributeError (i.e. signal to python that
the attribute doesn't exist) if the exercise is not submittable"""
entry = LearningObjectPoints.get(
self.exercise, self.get_summary_user(), self.is_course_staff
)
if not isinstance(entry, ExercisePoints):
raise AttributeError(f"LearningObject '{self.exercise}' is not submittable")
return entry
@cached_property
def submissions(self) -> List[SubmissionEntry]:
return self.summary.submissions
class ExerciseBaseView(ExerciseMixin, BaseTemplateView):
pass
class ExerciseTemplateBaseView(ExerciseMixin, BaseTemplateView):
pass
class ExerciseModelMixin(ExerciseMixin):
model_permission_classes = (
ModelVisiblePermission,
)
def get_permissions(self):
perms = super().get_permissions()
perms.extend((Perm() for Perm in self.model_permission_classes))
return perms
def get_exercise_object(self):
exercise = super().get_exercise_object()
if not exercise.is_submittable:
raise Http404("This learning object does not have a model answer.")
return exercise
class ExerciseModelBaseView(ExerciseModelMixin, BaseTemplateView):
pass
class SubmissionBaseMixin:
submission_kw = "submission_id"
submission_permission_classes = (
SubmissionVisiblePermission,
)
submitter: UserProfile
submission: Submission
def get_permissions(self):
perms = super().get_permissions()
perms.extend((Perm() for Perm in self.submission_permission_classes))
return perms
# get_submission_object
def get_resource_objects(self) -> None:
super().get_resource_objects()
self.submission = self.get_submission_object()
if self.submission.is_submitter(self.request.user):
self.submitter = self.request.user.userprofile
else:
self.submitter = self.submission.submitters.first()
self.note("submission", "submitter")
class SubmissionMixin(SubmissionBaseMixin, ExerciseMixin):
context_properties = ["index", "submission_entry"]
def get_submission_object(self) -> Submission:
return get_object_or_404(
Submission.objects.prefetch_related(None).prefetch_related(
models.Prefetch('submitters', UserProfile.objects.prefetch_tags(self.instance))
),
id=self.kwargs[self.submission_kw],
exercise=self.exercise
)
def get_summary_user(self) -> Optional[User]:
if not self.submitter:
# The submission has no submitters.
# Use None (AnonymousUser) in the ExercisePoints
# so that it does not pick submissions from request.user (the teacher).
return None
format_user(self.submitter.user, self.pseudonymize)
return self.submitter.user
@cached_property
def submission_entry(self) -> int:
return next(s for s in self.submissions if s.id == self.submission.id)
@cached_property
def index(self) -> int:
return len(self.submissions) - list(s.id for s in self.submissions).index(self.submission.id)
class SubmissionBaseView(SubmissionMixin, BaseTemplateView):
pass
class SubmissionDraftBaseView(ExerciseMixin, BaseView):
pass
class ExerciseListBaseView(ExerciseBaseView):
'''
Common base class for ListSubmissionView and ListSubmittersView.
Presently just for common mass regrade implementation.
'''
def get_common_objects(self):
super().get_common_objects()
# Regrade button text changes dynamically if regrade is ongoing.
# For now only teachers (and admins) can start mass regrade.
self.regrade_button = _('REGRADE')
self.resultinfo = ""
self.allow_regrade = self.instance.is_teacher(self.request.user)
try:
task = ExerciseTask.objects.get(
exercise=self.exercise,
task_type=ExerciseTask.TASK_TYPE.REGRADE
)
result = regrade_exercises.AsyncResult(task.task_id)
if result.state == 'PROGRESS':
self.regrade_button = format_lazy(_('REGRADING_PCT -- {percent}'),
percent=int(result.info.get('current') * 100 / result.info.get('total')))
self.resultinfo = format_lazy(_('REGRADING_PROGRESS -- {current}, {total}'),
current=result.info.get('current'), total=result.info.get('total'))
elif result.state == 'PENDING':
self.regrade_button = _('REGRADING')
self.resultinfo = _('STARTING_REGRADE')
else:
# Ensure that database does not have reference to stale Celery task
task.delete()
result.forget()
except ExerciseTask.DoesNotExist:
pass
self.note("regrade_button", "allow_regrade", "resultinfo")