-
Notifications
You must be signed in to change notification settings - Fork 73
/
models.py
1549 lines (1341 loc) · 54.9 KB
/
models.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
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
import datetime
import json
import logging
import string
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, TYPE_CHECKING
import urllib.request
import urllib.parse
from random import choice
from aplus_auth.payload import Payload, Permission
from aplus_auth import settings as auth_settings
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.staticfiles import finders
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import F, Q
from django.db.models.base import DEFERRED
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
from django_colortag.models import ColorTag
from requests.exceptions import HTTPError
from apps.models import BaseTab, BasePlugin
from authorization.models import JWTAccessible
from authorization.object_permissions import register_jwt_accessible_class
from lib.fields import PercentField, DefaultOneToOneField, DefaultForeignKey
from lib.helpers import (
Enum,
get_random_string,
resize_image,
roman_numeral,
safe_file_name,
url_with_query_in_data
)
from lib.models import UrlMixin
from lib.typing import AnyUser
from lib.validators import generate_url_key_validator
from userprofile.models import User, UserProfile, GraderUser
from .sis import get_sis_configuration, StudentInfoSystem
if TYPE_CHECKING:
from django.db.models.manager import RelatedManager
from edit_course.operations.configure import ConfigParts
from exercise.exercise_models import LearningObject
from threshold.models import CourseModuleRequirement
logger = logging.getLogger('aplus.course')
# Read pseudonymization data from file
with open(finders.find('pseudonym.json'), encoding='utf-8') as json_file:
DATA = json.load(json_file)
class CourseManager(JWTAccessible["Course"], models.Manager): ...
@register_jwt_accessible_class("course")
class Course(UrlMixin, models.Model):
"""
Course model represents a course in a university. A course has a name and an
identification number. It also has a URL which is included in the addresses
of pages under the course.
"""
name = models.CharField(
verbose_name=_('LABEL_NAME'),
max_length=255,
)
code = models.CharField(
verbose_name=_('LABEL_CODE'),
max_length=255,
)
url = models.CharField(
verbose_name=_('LABEL_URL'),
unique=True,
max_length=255,
blank=False,
help_text=_('COURSE_URL_IDENTIFIER_HELPTEXT'),
validators=[generate_url_key_validator()],
)
objects = CourseManager()
class Meta:
verbose_name = _('MODEL_NAME_COURSE')
verbose_name_plural = _('MODEL_NAME_COURSE_PLURAL')
def __str__(self):
return "{} {}".format(self.code, self.name)
def clean(self):
super().clean()
RESERVED = ("admin", "accounts", "shibboleth", "api",
"archive", "course", "exercise", "diploma")
if self.url in RESERVED:
raise ValidationError({
'url': format_lazy(
_('TAKEN_WORDS_INCLUDE -- {}'),
", ".join(RESERVED)
)
})
ABSOLUTE_URL_NAME = "course-instances"
def get_url_kwargs(self):
return dict(course_slug=self.url) # pylint: disable=use-dict-literal
class StudentGroupManager(models.Manager):
def get_queryset(self) -> models.QuerySet['StudentGroup']:
return super().get_queryset().prefetch_related('members')
class StudentGroup(models.Model):
"""
Stores a user group for a course instance.
"""
course_instance = models.ForeignKey('CourseInstance',
verbose_name=_('LABEL_COURSE_INSTANCE'),
on_delete=models.CASCADE,
related_name='groups',
)
members = models.ManyToManyField(UserProfile,
verbose_name=_('LABEL_MEMBERS'),
related_name='groups',
)
timestamp = models.DateTimeField(
verbose_name=_('LABEL_TIMESTAMP'),
auto_now_add=True,
)
objects = StudentGroupManager()
class Meta:
verbose_name = _('MODEL_NAME_STUDENT_GROUP')
verbose_name_plural = _('MODEL_NAME_STUDENT_GROUP_PLURAL')
ordering = ['course_instance','timestamp']
@classmethod
def get_exact_from(
cls,
search_from: Iterable['StudentGroup'],
member_profiles: Sequence[UserProfile],
) -> Optional['StudentGroup']:
for group in search_from:
if group.equals(member_profiles):
return group
return None
@classmethod
def get_exact(
cls,
course_instance: Optional['CourseInstance'],
member_profiles: Sequence[UserProfile],
) -> Optional['StudentGroup']:
return cls.get_exact_from(
cls.objects.filter(
course_instance=course_instance,
members=member_profiles[0],
),
member_profiles,
)
@classmethod
def filter_collaborators_of(cls, members, profile):
return [p for p in members if p != profile]
@classmethod
def format_collaborator_names(cls, members, profile):
return ", ".join(p.user.get_full_name()
for p in cls.filter_collaborators_of(members, profile))
def equals(self, profiles):
return set(self.members.all()) == set(profiles)
def collaborators_of(self, profile):
return self.filter_collaborators_of(self.members.all(), profile)
def collaborator_names(self, profile):
return self.format_collaborator_names(self.members.all(), profile)
class Enrollment(models.Model):
"""
Maps an enrolled student in a course instance.
"""
ENROLLMENT_ROLE = Enum([
('STUDENT', 1, _('STUDENT')),
('ASSISTANT', 2, _('ASSISTANT')),
('TEACHER', 3, _('TEACHER')),
])
ENROLLMENT_STATUS = Enum([
('ACTIVE', 1, _('ACTIVE')),
('REMOVED', 2, _('REMOVED')),
('BANNED', 3, _('BANNED')),
('PENDING', 4, _('PENDING')),
])
course_instance = models.ForeignKey('CourseInstance',
verbose_name=_('LABEL_COURSE_INSTANCE'),
on_delete=models.CASCADE,
)
user_profile = models.ForeignKey(UserProfile,
verbose_name=_('LABEL_USER_PROFILE'),
on_delete=models.CASCADE,
)
language = models.CharField(
verbose_name=_('LABEL_LANGUAGE'),
max_length=5,
blank=True,
default="",
)
timestamp = models.DateTimeField(
verbose_name=_('LABEL_TIMESTAMP'),
auto_now_add=True,
)
personal_code = models.CharField(
verbose_name=_('LABEL_PERSONAL_CODE'),
max_length=10,
blank=True,
default='',
)
selected_group = models.ForeignKey(StudentGroup,
verbose_name=_('LABEL_SELECTED_GROUP'),
on_delete=models.SET_NULL,
blank=True, null=True, default=None,
)
anon_name = models.CharField(
verbose_name=_('LABEL_ANON_NAME'),
max_length=50,
blank=True,
default='',
)
anon_id = models.CharField(
verbose_name=_('LABEL_ANON_ID'),
max_length=50,
unique=True,
blank=True,
null=True,
)
role = models.IntegerField(
verbose_name=_('LABEL_ROLE'),
choices=ENROLLMENT_ROLE.choices,
default=ENROLLMENT_ROLE.STUDENT,
)
status = models.IntegerField(
verbose_name=_('LABEL_STATUS'),
choices=ENROLLMENT_STATUS.choices,
default=ENROLLMENT_STATUS.ACTIVE,
)
from_sis = models.BooleanField(
verbose_name=_('LABEL_FROM_SIS'),
default=False,
)
class Meta:
verbose_name = _('MODEL_NAME_ENROLLMENT')
verbose_name_plural = _('MODEL_NAME_ENROLLMENT_PLURAL')
unique_together = ("course_instance", "user_profile")
def create_enrollment_code(sender, instance, created, **kwargs): # pylint: disable=unused-argument
if created:
easychars = '0123456789ABCDEFGHJKLMNPQRSTUVXYZ'
code = get_random_string(6, easychars)
while Enrollment.objects.filter(course_instance=instance.course_instance, personal_code=code).exists():
code = get_random_string(6, easychars)
instance.personal_code = code
instance.save()
def create_anon_id(sender, instance, created, **kwargs): # pylint: disable=unused-argument
if created or not instance.anon_id:
nums = string.digits + string.ascii_lowercase
code = get_random_string(16, nums)
i = 0
while Enrollment.objects.filter(anon_id=code).exists():
code = get_random_string(16, nums)
i += 1
if i > 10000:
raise RuntimeError("No anonymous user ids available")
instance.anon_id = code
instance.save(update_fields=['anon_id'])
def pseudonymize(sender, instance, created, **kwargs): # pylint: disable=unused-argument
if created or not instance.anon_name:
def namegen():
'''
If the color-animal pairs are starting to run out, add another color.
This is highly unlikely, as there are roughly 140*68=9520 possible combinations
'''
second_name = ""
if Enrollment.objects.filter(
course_instance=instance.course_instance
).count() > len(DATA["colors"]) * len(DATA["animals"]) * 0.75:
second_name = choice(DATA["colors"])["name"]
return choice(DATA["colors"])["name"] + second_name + " " + choice(DATA["animals"])
codename = namegen()
i = 0
while Enrollment.objects.filter(course_instance=instance.course_instance, anon_name=codename).exists():
codename = namegen()
i += 1
if i > 10000:
raise RuntimeError("No anonymous usernames available")
instance.anon_name = codename
instance.save(update_fields=['anon_name'])
post_save.connect(create_enrollment_code, sender=Enrollment)
post_save.connect(create_anon_id, sender=Enrollment)
post_save.connect(pseudonymize, sender=Enrollment)
class UserTag(UrlMixin, ColorTag):
course_instance = models.ForeignKey('CourseInstance',
verbose_name=_('LABEL_COURSE_INSTANCE'),
on_delete=models.CASCADE,
related_name="usertags",
)
visible_to_students = models.BooleanField(
verbose_name=_('LABEL_VISIBLE_TO_STUDENTS'),
default=False,
)
class Meta:
verbose_name = _('MODEL_NAME_USER_TAG')
verbose_name_plural = _('MODEL_NAME_USER_TAG_PLURAL')
ordering = ['course_instance', 'name']
def get_url_kwargs(self):
return dict(tag_id=self.id, **self.course_instance.get_url_kwargs()) # pylint: disable=use-dict-literal
def is_valid_slug(self, slug_candidate): # pylint: disable=arguments-renamed
assert self.course_instance
if not slug_candidate:
return False
qs = self.__class__.objects.filter(
course_instance=self.course_instance, slug=slug_candidate)
if self.pk is not None:
qs = qs.exclude(pk=self.pk)
return not qs.exists()
class SubmissionTag(UrlMixin, ColorTag):
course_instance = models.ForeignKey('CourseInstance',
verbose_name=_('LABEL_COURSE_INSTANCE'),
on_delete=models.CASCADE,
related_name="submissiontags",
)
visible_to_students = models.BooleanField(
verbose_name=_('LABEL_VISIBLE_TO_STUDENTS'),
default=False,
)
class Meta:
verbose_name = _('MODEL_NAME_SUBMISSION_TAG')
verbose_name_plural = _('MODEL_NAME_SUBMISSION_TAG_PLURAL')
ordering = ['id']
def get_url_kwargs(self):
return dict(tag_id=self.id, **self.course_instance.get_url_kwargs()) # pylint: disable=use-dict-literal
def is_valid_slug(self, slug_candidate): # pylint: disable=arguments-renamed
assert self.course_instance
if not slug_candidate:
return False
qs = self.__class__.objects.filter(
course_instance=self.course_instance, slug=slug_candidate)
if self.pk is not None:
qs = qs.exclude(pk=self.pk)
return not qs.exists()
class HardcodedUserTag(UserTag):
class Meta:
verbose_name = _('MODEL_NAME_HARDCODED_USER_TAG')
verbose_name_plural = _('MODEL_NAME_HARDCODED_USER_TAG_PLURAL')
proxy = True
data_attrs = {
'-removable': 'false'
}
def __init__(self, **kwargs):
kwargs.setdefault('course_instance', DEFERRED)
kwargs.setdefault('visible_to_students', True)
super().__init__(**kwargs)
def save(self, *args, **kwargs):
raise RuntimeError("Hardcoded tags can not be saved!")
USERTAG_INTERNAL = HardcodedUserTag(
name=getattr(settings, 'INTERNAL_USER_LABEL', _('INTERNAL')),
slug='user-internal',
description=_('INTERNAL_USER_DESCRIPTION'),
color='#006cb4',
)
USERTAG_EXTERNAL = HardcodedUserTag(
name=getattr(settings, 'EXTERNAL_USER_LABEL', _('EXTERNAL')),
slug='user-external',
description=_('EXTERNAL_USER_DESCRIPTION'),
color='#545454',
)
class UserTaggingManager(models.Manager):
def tags_for_instance(self, course_instance):
ts = self.filter(course_instance=course_instance)\
.select_related('tag')
return [t.tag for t in ts]
def get_all(self, profile: UserProfile, course_instance: 'CourseInstance') -> List[UserTag]:
# Check if taggings for the course instance were prefetched
if hasattr(profile, 'instance_taggings'):
taggings = profile.instance_taggings
else:
taggings = (
self.filter(
user=profile,
course_instance=course_instance
)
.select_related('tag')
)
tags = [USERTAG_EXTERNAL if profile.is_external else USERTAG_INTERNAL]
tags.extend(t.tag for t in taggings)
return tags
def set(self, profile, tag):
return self.get_or_create(
tag=tag,
user=profile,
course_instance=tag.course_instance,
)
def unset(self, profile, tag):
self.filter(
tag=tag,
user=profile,
).delete()
class UserTagging(models.Model):
tag = models.ForeignKey(UserTag,
verbose_name=_('LABEL_TAG'),
on_delete=models.CASCADE,
related_name="taggings",
)
user = models.ForeignKey(UserProfile,
verbose_name=_('LABEL_USER'),
on_delete=models.CASCADE,
related_name="taggings",
db_index=True,
)
course_instance = models.ForeignKey('CourseInstance',
verbose_name=_('LABEL_COURSE_INSTANCE'),
on_delete=models.CASCADE,
related_name="taggings",
db_index=True,
)
objects = UserTaggingManager()
def __str__(self):
return 'tag: {tag}, user: {user}'.format(
tag=self.tag.name,
user=self.user.user.username
)
class Meta:
verbose_name = _('MODEL_NAME_USER_TAGGING')
verbose_name_plural = _('MODEL_NAME_USER_TAGGING_PLURAL')
unique_together = ('tag', 'user', 'course_instance')
indexes = [models.Index(fields=['user', 'course_instance'])]
ordering = ['tag']
def get_course_staff_visibility_filter(user, prefix=None):
if prefix is None:
prefix = ''
filter = Q() # pylint: disable=redefined-builtin
if isinstance(user, User):
user = user.userprofile
filter = (
(Q(**{f'{prefix}enrollment__role': Enrollment.ENROLLMENT_ROLE.TEACHER})
| Q(**{f'{prefix}enrollment__role': Enrollment.ENROLLMENT_ROLE.ASSISTANT}))
& Q(**{f'{prefix}enrollment__status': Enrollment.ENROLLMENT_STATUS.ACTIVE})
& Q(**{f'{prefix}enrollment__user_profile': user})
)
elif isinstance(user, GraderUser):
courses = [o for _, o in user.permissions.courses]
instances = [o for _, o in user.permissions.instances]
filter = Q(**{f'{prefix}course__in': courses}) | Q(**{f'{prefix}id__in': instances})
return filter
class CourseInstanceManager(JWTAccessible["CourseInstance"], models.Manager):
"""
Helpers in CourseInstance.objects
"""
def get_queryset(self):
return super().get_queryset().select_related('course').order_by('-starting_time')
def get_visible(self, user=None):
if not user or not user.is_authenticated:
return self.filter(visible_to_students=True)
if not user.is_superuser:
return self.filter(
get_course_staff_visibility_filter(user)
| Q(visible_to_students=True),
).distinct()
return self.all()
def get_enrolled(self, user):
# Also "PENDING" enrollments should show as own courses (e.g. in front page, course menu)
return self.filter(
Q(enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE)
| Q(enrollment__status=Enrollment.ENROLLMENT_STATUS.PENDING),
enrollment__role=Enrollment.ENROLLMENT_ROLE.STUDENT,
enrollment__user_profile=user)
def get_assisting(self, user):
return self.filter(
enrollment__role=Enrollment.ENROLLMENT_ROLE.ASSISTANT,
enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE,
enrollment__user_profile=user)
def get_teaching(self, user):
return self.filter(
enrollment__role=Enrollment.ENROLLMENT_ROLE.TEACHER,
enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE,
enrollment__user_profile=user)
def get_active(self, user):
return self.filter(
enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE,
enrollment__user_profile=user)
def has_access(self, user: AnyUser, payload: Payload, permission: Permission, instance: "CourseInstance") -> bool:
# a normal user
if user.is_authenticated and not user.is_anonymous:
return instance.is_teacher(user)
# a grader user
if user.is_authenticated and user.is_anonymous:
config_uid = auth_settings().get_uid_for_url(instance.configure_url)
if config_uid is None:
logger.warning( # pylint: disable=logging-fstring-interpolation
f"Could not find public key for configure_url {instance.configure_url}. "
f"Cannot authorize JWT instance access"
)
return False
return config_uid == user.username
return False
def has_create_access(self, payload: Payload, kwargs: Dict[str, Any]) -> bool: # pylint: disable=arguments-differ
return False
def build_upload_dir(instance, filename):
"""
Returns the path to a directory where the instance image should be saved.
"""
return "public/course_instance_{:d}/{}".format(
instance.id,
safe_file_name(filename)
)
class CourseInstanceProto(UrlMixin):
ABSOLUTE_URL_NAME = "course"
EDIT_URL_NAME = "course-edit"
url: str
def get_url_kwargs(self):
return {"instance_slug": self.url, **self.get_course_url_kwargs()}
def get_course_url_kwargs(self):
raise NotImplementedError(f"{self.__class__} must implement get_course_url_kwargs")
@register_jwt_accessible_class("instance")
class CourseInstance(CourseInstanceProto, models.Model):
"""
CourseInstance class represent an instance of a course. A single course may have
several instances either at the same time or during different years.
Teachers, assistants, and students are set to each instance separately via Enrollments.
Each instance may have different teachers and assistants.
(Before A+ v1.10, teachers were set for Courses and shared
for all CourseInstances of the Course.)
"""
ENROLLMENT_AUDIENCE = Enum([
('INTERNAL_USERS', 1, _('INTERNAL_USERS')),
('EXTERNAL_USERS', 2, _('EXTERNAL_USERS')),
('ALL_USERS', 3, _('ALL_USERS')),
])
VIEW_ACCESS = Enum([
('ENROLLED', 1, _('ENROLLED_STUDENTS')),
('ENROLLMENT_AUDIENCE', 2, _('ENROLLMENT_AUDIENCE')),
('ALL_REGISTERED', 3, _('ALL_REGISTERED_USERS')),
('PUBLIC', 4, _('PUBLIC')),
])
INDEX_TYPE = Enum([
('RESULTS', 0, _('USER_RESULTS')),
('TOC', 1, _('TABLE_OF_CONTENTS')),
('LAST', 2, _('LAST_VISITED_LINK')),
('EXPERIMENT', 10, _('EXPERIMENTAL_SETUP')),
])
CONTENT_NUMBERING = Enum([
('NONE', 0, _('NUMBERING_NONE')),
('ARABIC', 1, _('NUMBERING_ARABIC')),
('ROMAN', 2, _('NUMBERING_ROMAN')),
('HIDDEN', 3, _('NUMBERING_HIDDEN_ARABIC')),
])
RESERVED_URLS = ("instances",) # strings which cannot be used as course instance URL identifiers
course = models.ForeignKey(Course,
verbose_name=_('LABEL_COURSE'),
on_delete=models.CASCADE,
related_name="instances",
)
instance_name = models.CharField(
verbose_name=_('LABEL_INSTANCE_NAME'),
max_length=255,
)
url: str = models.CharField( # type: ignore
verbose_name=_('LABEL_URL'),
max_length=255,
blank=False,
help_text=_('COURSE_INSTANCE_URL_IDENTIFIER_HELPTEXT'),
validators=[generate_url_key_validator()],
)
visible_to_students = models.BooleanField(
verbose_name=_('LABEL_VISIBLE_TO_STUDENTS'),
default=True,
)
enrollment_audience = models.IntegerField(
verbose_name=_('LABEL_ENROLLMENT_AUDIENCE'),
choices=ENROLLMENT_AUDIENCE.choices,
default=ENROLLMENT_AUDIENCE.INTERNAL_USERS,
)
view_content_to = models.IntegerField(
verbose_name=_('LABEL_VIEW_CONTENT_TO'),
choices=VIEW_ACCESS.choices,
default=VIEW_ACCESS.ENROLLED,
)
starting_time = models.DateTimeField(
verbose_name=_('LABEL_STARTING_TIME'),
)
ending_time = models.DateTimeField(
verbose_name=_('LABEL_ENDING_TIME'),
)
lifesupport_time = models.DateTimeField(
verbose_name=_('LABEL_LIFESUPPORT_TIME'),
blank=True, null=True,
)
archive_time = models.DateTimeField(
verbose_name=_('LABEL_ARCHIVE_TIME'),
blank=True, null=True,
)
enrollment_starting_time = models.DateTimeField(
verbose_name=_('LABEL_ENROLLMENT_STARTING_TIME'),
blank=True, null=True,
help_text=_('COURSE_INSTANCE_ENROLLMENT_TIME_HELPTEXT'),
)
enrollment_ending_time = models.DateTimeField(
verbose_name=_('LABEL_ENROLLMENT_ENDING_TIME'),
blank=True, null=True,
help_text=_('COURSE_INSTANCE_ENROLLMENT_TIME_HELPTEXT'),
)
image = models.ImageField(
verbose_name=_('LABEL_IMAGE'),
blank=True, null=True,
upload_to=build_upload_dir,
)
language = models.CharField(
verbose_name=_('LABEL_LANGUAGE'),
max_length=255,
blank=True,
default="",
)
description = models.TextField(
verbose_name=_('LABEL_DESCRIPTION'),
blank=True,
)
footer = models.TextField(
verbose_name=_('LABEL_FOOTER'),
blank=True,
)
index_mode = models.IntegerField(
verbose_name=_('LABEL_INDEX_MODE'),
choices=INDEX_TYPE.choices, default=INDEX_TYPE.RESULTS,
help_text=_('COURSE_INSTANCE_INDEX_CONTENT_SELECTION_HELPTEXT'),
)
module_numbering = models.IntegerField(
verbose_name=_('LABEL_MODULE_NUMBERING'),
choices=CONTENT_NUMBERING.choices,
default=CONTENT_NUMBERING.ARABIC,
)
content_numbering = models.IntegerField(
verbose_name=_('LABEL_CONTENT_NUMBERING'),
choices=CONTENT_NUMBERING.choices,
default=CONTENT_NUMBERING.ARABIC,
)
head_urls = models.TextField(
verbose_name=_('LABEL_HEAD_URLS'),
blank=True,
help_text=_('COURSE_INSTANCE_EXTERNAL_CSS_AND_JS_FOR_ALL_PAGES_HELPTEXT'),
)
configure_url = models.URLField(blank=True)
build_log_url = models.URLField(blank=True)
last_modified = models.DateTimeField(auto_now=True, blank=True, null=True)
technical_error_emails = models.CharField(
verbose_name=_('LABEL_TECHNICAL_ERROR_EMAILS'),
max_length=255,
blank=True,
help_text=_('COURSE_INSTANCE_EXERCISE_ERROR_EMAIL_RECIPIENT_OVERRIDE_HELPTEXT'),
)
plugins = GenericRelation(BasePlugin, object_id_field="container_pk",
content_type_field="container_type")
tabs = GenericRelation(BaseTab, object_id_field="container_pk",
content_type_field="container_type")
sis_id = models.CharField(
verbose_name=_('LABEL_SIS_IDENTIFIER'),
max_length=255,
blank=True,
default="",
)
sis_enroll = models.BooleanField(
verbose_name=_('LABEL_SIS_ENROLL'),
default=False,
help_text=_('COURSE_INSTANCE_SIS_ENROLL_HELP')
)
# usertags from course.models.UserTag
# taggings from course.models.UserTagging
# categories from course.models.LearningObjectCategory
# course_modules from course.models.CourseModule
objects = CourseInstanceManager()
if TYPE_CHECKING:
id: int
course_modules: RelatedManager["CourseModule"]
class Meta:
verbose_name = _('MODEL_NAME_COURSE_INSTANCE')
verbose_name_plural = _('MODEL_NAME_COURSE_INSTANCE_PLURAL')
unique_together = ("course", "url")
def __str__(self):
return "{}: {}".format(str(self.course), self.instance_name)
def clean(self):
super().clean()
errors = {}
if self.instance_name in self.RESERVED_URLS:
errors['instance_name'] = format_lazy(_('COURSE_INSTANCE_ERROR_INSTANCE_NAME -- {}'), self.instance_name)
if self.url in self.RESERVED_URLS:
errors['url'] = format_lazy(_('COURSE_INSTANCE_ERROR_URL -- {}'), self.url)
if self.ending_time and self.starting_time and self.ending_time <= self.starting_time:
errors['ending_time'] = _('COURSE_INSTANCE_ERROR_ENDING_TIME_BEFORE_STARTING')
if self.lifesupport_time and self.lifesupport_time < self.ending_time:
errors['lifesupport_time'] = _('COURSE_INSTANCE_ERROR_LIFESUPPORT_TIME_BEFORE_ENDING')
if (self.archive_time and not self.lifesupport_time) \
or (self.lifesupport_time and not self.archive_time):
# Must not set only one of lifesupport and archive time since their
# default values could change their order. Lifesupport time must not
# be earlier than archive time.
errors['archive_time'] = _('COURSE_INSTANCE_ERROR_ARCHIVE_TIME_AND_LIFESUPPORT_ONLY_ONE_SET')
elif self.archive_time and self.archive_time < self.lifesupport_time:
errors['archive_time'] = _('COURSE_INSTANCE_ERROR_ARCHIVE_TIME_BEFORE_LIFESUPPORT')
if self.language.startswith("|"):
langs = list(filter(None, self.language.split("|"))) # remove pipes & empty strings
for lang in langs:
if not self.is_valid_language(lang):
if "language" in errors:
errors['language'] += (", " + lang)
else:
errors['language'] = _('COURSE_INSTANCE_ERROR_LANGUAGE(S)_MISSING_FROM_SETTINGS') + lang
elif not self.is_valid_language(self.language):
errors['language'] = _('COURSE_INSTANCE_ERROR_LANGUAGE_MISSING_FROM_SETTINGS')
if errors:
raise ValidationError(errors)
def is_valid_language(self, lang):
return lang == "" or lang in [key for key,name in settings.LANGUAGES]
@property
def languages(self):
return self.language.strip('|').split('|')
@property
def default_language(self):
language = self.language
language_code = language.lstrip('|').split('|', 1)[0]
if language_code:
return language_code
return settings.LANGUAGE_CODE.split('-', 1)[0]
@property
def students(self):
return UserProfile.objects.filter(
enrollment__role=Enrollment.ENROLLMENT_ROLE.STUDENT,
enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE,
enrollment__course_instance=self
)
@property
def all_students(self):
return UserProfile.objects.filter(
enrollment__role=Enrollment.ENROLLMENT_ROLE.STUDENT,
enrollment__course_instance=self
).annotate(enrollment_status=F('enrollment__status'))
@property
def assistants(self):
return UserProfile.objects.filter(
enrollment__role=Enrollment.ENROLLMENT_ROLE.ASSISTANT,
enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE,
enrollment__course_instance=self)
@property
def teachers(self):
return UserProfile.objects.filter(
enrollment__role=Enrollment.ENROLLMENT_ROLE.TEACHER,
enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE,
enrollment__course_instance=self)
@property
def course_staff(self):
return UserProfile.objects.filter(
Q(enrollment__role=Enrollment.ENROLLMENT_ROLE.TEACHER)
| Q(enrollment__role=Enrollment.ENROLLMENT_ROLE.ASSISTANT),
enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE,
enrollment__course_instance=self)
@property
def course_staff_and_students(self):
return UserProfile.objects.filter(
enrollment__status=Enrollment.ENROLLMENT_STATUS.ACTIVE,
enrollment__course_instance=self
)
@cached_property
def later_instance(self):
later_instance = None
if self.is_past: # pylint: disable=using-constant-test
try:
later_instance = (
CourseInstance.objects.filter(
course=self.course,
ending_time__gte=timezone.now()
).latest('starting_time')
)
except CourseInstance.DoesNotExist:
pass
return later_instance
def save(self, *args, **kwargs):
"""
Saves the model.
"""
super().save(*args, **kwargs)
if self.image:
resize_image(self.image.path, (800,600))
def is_assistant(self, user):
return (
user and
user.is_authenticated and
isinstance(user, User) and
self.assistants.filter(id=user.userprofile.id).exists()
)
def is_teacher(self, user):
return (
user and
user.is_authenticated and (
user.is_superuser or (
isinstance(user, User) and
self.teachers.filter(id=user.userprofile.id).exists()
) or (
isinstance(user, GraderUser) and
(Permission.WRITE, self.course) in user.permissions.courses
)
)
)
def is_course_staff(self, user):
return self.is_teacher(user) or self.is_assistant(user)
def is_student(self, user):
return (
user and
user.is_authenticated and
isinstance(user, User) and
self.students.filter(id=user.userprofile.id).exists()
)
def is_banned(self, user):
return (
user and
user.is_authenticated and
isinstance(user, User) and
self.all_students.filter(
enrollment__status=Enrollment.ENROLLMENT_STATUS.BANNED,
id=user.userprofile.id,
).exists()
)
def is_enrollable(self, user):
if self.is_course_staff(user):
# Allow course staff to enroll even if the course instance is hidden
# or the user does not belong to the enrollment audience.
return True
enrollment = self.get_enrollment_for(user)
if enrollment and enrollment.status == Enrollment.ENROLLMENT_STATUS.BANNED:
return False
if user and user.is_authenticated and self.visible_to_students:
if self.enrollment_audience == self.ENROLLMENT_AUDIENCE.INTERNAL_USERS:
return not user.userprofile.is_external
if self.enrollment_audience == self.ENROLLMENT_AUDIENCE.EXTERNAL_USERS:
return user.userprofile.is_external
return True
return False
def enroll_student(self, user, from_sis=False, use_pending=False):
# Return value False indicates whether that the user was already enrolled.
if use_pending:
status = Enrollment.ENROLLMENT_STATUS.PENDING
else:
status = Enrollment.ENROLLMENT_STATUS.ACTIVE
if user and user.is_authenticated:
try:
enrollment = Enrollment.objects.get(
course_instance=self,
user_profile=user.userprofile,
)
if (
enrollment.status in (
Enrollment.ENROLLMENT_STATUS.ACTIVE,
Enrollment.ENROLLMENT_STATUS.PENDING,
)
):
if (enrollment.status == Enrollment.ENROLLMENT_STATUS.PENDING and not use_pending):
enrollment.status = Enrollment.ENROLLMENT_STATUS.ACTIVE
enrollment.save()
if not enrollment.from_sis and from_sis and enrollment.role == Enrollment.ENROLLMENT_ROLE.STUDENT:
enrollment.from_sis = from_sis
enrollment.save()
return False
enrollment.role = Enrollment.ENROLLMENT_ROLE.STUDENT
enrollment.status = status
enrollment.from_sis = from_sis
enrollment.save()
return True
except Enrollment.DoesNotExist:
Enrollment.objects.create(
course_instance=self,
user_profile=user.userprofile,
role=Enrollment.ENROLLMENT_ROLE.STUDENT,
status=status,
from_sis=from_sis,
)
return True
return False
def enroll_from_sis(self) -> Tuple[int, int]:
"""
Enroll students based on the participants information in Student Info System.
If student has removed herself in SIS, she will also be marked as removed in A+.
Returns
-------
Number of enrolled and removed students based on this call.
-1 if there was problem accessing SIS.
"""
from .cache.menu import invalidate_content # pylint: disable=import-outside-toplevel
sis: StudentInfoSystem = get_sis_configuration()
if not sis:
return -1, -1
addcount = 0