/
models.py
1965 lines (1667 loc) · 71.3 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
# TODO: Split models into distinct .py files
from werkzeug.exceptions import BadRequest
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from sqlalchemy import PrimaryKeyConstraint, UniqueConstraint, MetaData, types
from sqlalchemy.dialects import mysql
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import aliased, backref
from sqlalchemy.sql import text
from markdown import markdown
import pytz
import functools
from collections import namedtuple, Counter
import contextlib
import csv
import datetime as dt
import json
import os
import logging
import shlex
import urllib.parse
import mimetypes
from server.constants import (VALID_ROLES, STUDENT_ROLE, STAFF_ROLES, TIMEZONE,
SCORE_KINDS, OAUTH_OUT_OF_BAND_URI,
INSTRUCTOR_ROLE, ROLE_DISPLAY_NAMES, AUTOGRADER_URL)
from server.extensions import cache, storage
from server.utils import (encode_id, chunks, generate_number_table,
humanize_name)
logger = logging.getLogger(__name__)
convention = {
"ix": 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
}
metadata = MetaData(naming_convention=convention)
db = SQLAlchemy(metadata=metadata)
def transaction(f):
""" Decorator for database (session) transactions."""
@functools.wraps(f)
def wrapper(*args, **kwds):
try:
value = f(*args, **kwds)
db.session.commit()
return value
except:
db.session.rollback()
raise
return wrapper
class Json(types.TypeDecorator):
impl = types.Text
def process_bind_param(self, value, dialect):
# Python -> SQL
return json.dumps(value)
def process_result_value(self, value, dialect):
# SQL -> Python
return json.loads(value)
@compiles(mysql.MEDIUMBLOB, 'sqlite')
def ok_blob(element, compiler, **kw):
return "BLOB"
@compiles(mysql.MEDIUMTEXT, 'sqlite')
def ok_text(element, compiler, **kw):
return "TEXT"
class JsonBlob(types.TypeDecorator):
impl = mysql.MEDIUMBLOB
def process_bind_param(self, value, dialect):
# Python -> SQL
return json.dumps(value).encode('utf-8')
def process_result_value(self, value, dialect):
# SQL -> Python
return json.loads(value.decode('utf-8'))
class Timezone(types.TypeDecorator):
impl = types.String(255)
def process_bind_param(self, value, dialect):
# Python -> SQL
if not hasattr(value, 'zone'):
if value not in pytz.common_timezones_set:
logger.warning('Unknown TZ: {}'.format(value))
# Unknown TZ, use default instead
return TIMEZONE
return value
return value.zone
def process_result_value(self, value, dialect):
# SQL -> Python
return pytz.timezone(value)
class StringList(types.TypeDecorator):
impl = types.Text
def process_bind_param(self, string_list, dialect):
# Python -> SQL
items = []
for item in string_list:
if " " in item or not item:
items.append('"{}"'.format(item))
else:
items.append(item)
return ' '.join(items)
def process_result_value(self, value, dialect):
""" SQL -> Python
Uses shlex.split to handle values with spaces.
It's a fragile solution since it will break in some cases.
For example if the last character is a backslash or otherwise meaningful
to a shell.
"""
values = []
for val in shlex.split(value):
if " " in val and '"' in val:
values.append(val[1:-1])
else:
values.append(val)
return values
class Model(db.Model):
""" Timestamps all models, and serializes model objects."""
__abstract__ = True
created = db.Column(db.DateTime(timezone=True),
server_default=db.func.now(), nullable=False)
def __repr__(self):
if hasattr(self, 'id'):
key_val = self.id
else:
pk = self.__mapper__.primary_key
if type(pk) == tuple:
key_val = pk[0].name
else:
key_val = self.__mapper__.primary_key._list[0].name
return '<{0} {1}>'.format(self.__class__.__name__, key_val)
@classmethod
def can(cls, obj, user, action):
if user.is_admin:
return True
return False
@hybrid_property
def export(self):
""" CSV export data. """
if not hasattr(self, 'export_items'):
return {}
return {k: v for k, v in self.as_dict().items() if k in self.export_items}
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
def from_dict(self, dict):
for c in self.__table__.columns:
if c.name in dict:
setattr(self, c.name, dict[c.name])
return self
class User(Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
email = db.Column(db.String(255), unique=True, nullable=False, index=True)
is_admin = db.Column(db.Boolean(), default=False)
export_items = ('email', 'name')
def __repr__(self):
return '<User {0}>'.format(self.email)
def enrollments(self, roles=None):
if roles is None:
roles = [STUDENT_ROLE]
query = (Enrollment.query.join(Enrollment.course)
.options(db.contains_eager(Enrollment.course))
.filter(Enrollment.user_id == self.id)
.filter(Enrollment.role.in_(roles))
.order_by(Course.created.desc()))
return query.all()
@cache.memoize(120)
def is_enrolled(self, course_id, roles=VALID_ROLES):
for enroll in self.participations:
if enroll.course_id == course_id and enroll.role in roles:
return enroll
return False
@hybrid_property
def identifier(self):
return humanize_name(self.name) or self.email
@cache.memoize(3600)
def num_grading_tasks(self):
# TODO: Pass in assignment_id (Useful for course dashboard)
return GradingTask.query.filter_by(grader=self, score_id=None).count()
def is_staff(self):
""" Return True if the user is a staff member in any course. """
if self.is_admin:
return True
query = (Enrollment.query.filter(Enrollment.user_id == self.id)
.filter(Enrollment.role.in_(STAFF_ROLES)))
return query.count() > 0
@staticmethod
def get_by_id(uid):
""" Performs .query.get; potentially can be cached."""
return User.query.get(uid)
@staticmethod
@cache.memoize(240)
def email_by_id(uid):
user = User.query.get(uid)
if user:
return user.email
@staticmethod
def lookup(email):
""" Get a User with the given email address, or None."""
return User.query.filter_by(email=email).one_or_none()
class Course(Model):
id = db.Column(db.Integer, primary_key=True)
# offering - E.g., 'cal/cs61a/fa14'
offering = db.Column(db.String(255), nullable=False, unique=True, index=True)
institution = db.Column(db.String(255), nullable=False) # E.g., 'UC Berkeley'
display_name = db.Column(db.String(255), nullable=False)
website = db.Column(db.String(255))
active = db.Column(db.Boolean(), nullable=False, default=True)
timezone = db.Column(Timezone, nullable=False, default=pytz.timezone(TIMEZONE))
autograder_url = db.Column(db.String(255), server_default=AUTOGRADER_URL)
@classmethod
def can(cls, obj, user, action):
if user.is_admin:
return True
if not obj:
return False
if action == "view":
return user.is_authenticated
return user.is_enrolled(obj.id, STAFF_ROLES)
def __repr__(self):
return '<Course {0!r}>'.format(self.offering)
@staticmethod
def by_name(name):
return Course.query.filter_by(offering=name).one_or_none()
@property
def display_name_with_semester(self):
year = self.offering[-2:]
if "fa" in self.offering[-4:]:
semester = "Fall"
elif "sp" in self.offering[-4:]:
semester = "Spring"
elif "wi" in self.offering[-4:]:
semester = "Winter"
elif "au" in self.offering[-4:]:
semester = "Autumn"
elif "su" in self.offering[-4:]:
semester = "Summer"
else:
return self.display_name + " (20{0})".format(year)
return self.display_name + " ({0} 20{1})".format(semester, year)
def statistics(self):
assignments = self.assignments
active_assignments = [x for x in assignments if x.active]
inactive_assignments = [x for x in assignments if not x.active]
backup_count_query = (Backup.query.join(Backup.assignment)
.filter(Assignment.course == self))
count_by_role = dict(Counter([x.role for x in self.participations]))
count_by_role['all_staff'] = sum(count_by_role.get(x, 0) for x in STAFF_ROLES)
return {
'active_assignments': len(active_assignments),
'inactive_assignments': len(inactive_assignments),
'backup_count': backup_count_query.count(),
'submit_count': backup_count_query.filter(Backup.submit == True).count(),
'enrollment_counts': count_by_role
}
def is_enrolled(self, user):
return Enrollment.query.filter_by(
user=user,
course=self
).count() > 0
def get_participants(self, roles):
return (Enrollment.query
.options(db.joinedload('user'))
.filter(Enrollment.role.in_(roles),
Enrollment.course == self)
.all())
def get_staff(self):
return self.get_participants(STAFF_ROLES)
def get_students(self):
return self.get_participants([STUDENT_ROLE])
def initialize_content(self, user):
""" When a course is created, add the creating user as an instructor
and then create an example assignment.
"""
enroll = Enrollment(course=self, user_id=user.id, role=INSTRUCTOR_ROLE)
assign = Assignment(course=self, display_name="Example",
name=self.offering + '/example',
max_group_size=2, uploads_enabled=True,
due_date=dt.datetime.now() + dt.timedelta(days=7),
lock_date=dt.datetime.now() + dt.timedelta(days=8))
db.session.add_all([enroll, assign])
db.session.commit()
class Assignment(Model):
""" Assignments are particular to courses and have unique names.
name - cal/cs61a/fa14/proj1
display_name - Hog
due_date - DEADLINE (Publically displayed)
lock_date - DEADLINE+1 (Hard Deadline for submissions)
url - cs61a.org/proj/hog/hog.zip
flagged - User has indicated this one should be graded and not others
published_scores - list of grade tags that are published to students
"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), index=True, nullable=False, unique=True)
course_id = db.Column(db.ForeignKey("course.id"), index=True,
nullable=False)
display_name = db.Column(db.String(255), nullable=False)
due_date = db.Column(db.DateTime(timezone=True), nullable=False)
lock_date = db.Column(db.DateTime(timezone=True), nullable=False)
visible = db.Column(db.Boolean(), default=True)
creator_id = db.Column(db.ForeignKey("user.id"))
url = db.Column(db.Text)
max_group_size = db.Column(db.Integer(), nullable=False, default=1)
revisions_allowed = db.Column(db.Boolean(), nullable=False, default=False)
autograding_key = db.Column(db.String(255))
continuous_autograding = db.Column(db.Boolean(), default=False)
uploads_enabled = db.Column(db.Boolean(), nullable=False, default=False)
upload_info = db.Column(db.Text)
published_scores = db.Column(StringList, nullable=False, default=[])
files = db.Column(JsonBlob) # JSON object mapping filenames to contents
course = db.relationship("Course", backref="assignments")
user_assignment = namedtuple('UserAssignment',
['assignment', 'subm_time', 'group',
'final_subm', 'scores'])
@hybrid_property
def active(self):
return dt.datetime.utcnow() <= self.lock_date
@classmethod
def can(cls, obj, user, action):
if not obj:
if action == "create":
return (user.enrollments(roles=STAFF_ROLES) or
user.is_admin)
return False
if user.is_admin:
return True
is_staff = user.is_enrolled(obj.course.id, STAFF_ROLES)
if action == "view":
return is_staff or obj.visible
if action == "publish_scores":
return is_staff
return is_staff
@staticmethod
@cache.memoize(180)
def assignment_stats(assign_id, detailed=True):
assignment = Assignment.query.get(assign_id)
base_query = Backup.query.filter_by(assignment=assignment)
stats = {
'submissions': base_query.filter_by(submit=True).count(),
'backups': base_query.count(),
'groups': Group.query.filter_by(assignment=assignment).count(),
}
data = assignment.course_submissions()
submissions = [fs['backup'] for fs in data if fs['backup']]
submissions_id = set(fs['id'] for fs in submissions)
students_with_subms = set(s['user']['id'] for s in data
if s['backup'] and s['backup']['submit'])
students_with_backup = set(s['user']['id'] for s in data
if s['backup'] and not s['backup']['submit'])
students_without_subms = set(s['user']['id'] for s in data
if not s['backup'])
groups = [g['group'] for g in data if g['group']]
total_students = len(data)
percent_started = ((len(students_with_subms) + len(students_with_backup)) /
(total_students or 1)) * 100
percent_finished = (len(students_with_subms) / (total_students or 1)) * 100
active_groups = len({g['group_id'] for g in groups if ',' in g['group_member']})
stats.update({
'unique_submissions': len(submissions_id),
'students_with_subm': len(students_with_subms),
'students_with_backup': len(students_with_backup),
'students_no_backup': len(students_without_subms),
'percent_started': percent_started,
'percent_finished': percent_finished,
'active_groups': active_groups,
'percent_groups_active': active_groups/(stats['groups'] or 1)
})
if detailed:
stats.update({
'raw_data': data
})
return stats
@staticmethod
@cache.memoize(1000)
def name_to_assign_info(name):
assign = Assignment.query.filter_by(name=name).one_or_none()
if assign:
info = assign.as_dict()
info['active'] = assign.active
return info
@staticmethod
def by_name(name):
""" Return assignment object when given a name."""
return Assignment.query.filter_by(name=name).one_or_none()
def user_timeline(self, user_id, current_backup_id=None):
""" Timeline of user submissions. Returns a dictionary
with timeline contents from most recent to oldest.
Example Return:
{'submitters': {'a@example.com': 40},
'timeline': [{
'event': "(Unlock|Started|Switched|Submitted|Later|Solved)"
'attempt': 20,
'title': "Started unlocking"
'backup': Backup(...)
}]
}
"""
user_ids = self.active_user_ids(user_id)
analytics = (db.session.query(Backup, Message)
.outerjoin(Message)
.filter(Backup.submitter_id.in_(user_ids),
Backup.assignment_id == self.id,
Message.kind == "analytics")
.order_by(Backup.created.asc())
.all())
unlock_started_q, started_questions, solved_questions = {}, {}, {}
history, timeline, submitters = [], [], []
# TODO: Make timeline a namedtuple
last_q = (None, False, 0) # current_question, is_solved, count
for backup, message in analytics:
contents = message.contents
working_q = contents.get('question')
if not working_q:
continue
curr_q = working_q[0]
if ('history' not in contents or 'questions' not in contents['history'] or
not isinstance(contents['history']['questions'], dict)):
continue
submitters.append(backup.submitter.email)
curr_q_stats = message.contents['history']['questions'].get(curr_q)
total_attempt_count = message.contents['history'].get('all_attempts')
is_solved = curr_q_stats.get('solved')
if current_backup_id and current_backup_id == backup.hashid:
current_backup_event = {"event": "Current",
"attempt": total_attempt_count,
"title": "Current Backup Queried".format(curr_q),
"backup": backup}
timeline.append(current_backup_event)
continue
if contents.get('unlock'):
# Is unlocking.
if curr_q not in unlock_started_q:
unlock_started_q[curr_q] = backup.hashid
timeline.append({"event": "Unlock",
"attempt": total_attempt_count,
"title": "Started unlocking {}".format(curr_q),
"backup": backup})
if curr_q != last_q[0]:
last_q = (curr_q, is_solved, 0)
else:
last_q = (curr_q, is_solved, last_q[2]+1)
elif curr_q not in started_questions:
started_questions[curr_q] = backup.hashid
timeline.append({"event": "Started",
"title": "Started {}".format(curr_q),
"attempt": total_attempt_count,
"backup": backup})
last_q = (curr_q, is_solved, 1)
elif last_q[0] != curr_q and last_q[0] is not None:
# Didn't just start it but did switch questions.
timeline.append({"event": "Switched",
"title": "Switched to {}".format(curr_q),
"attempt": total_attempt_count,
"body": "{} Backups Later".format(last_q[2]),
"backup": backup, "date": backup.created})
last_q = (curr_q, is_solved, 1)
if is_solved and curr_q not in solved_questions:
# Just solved a question
solved_questions[curr_q] = backup.hashid
attempts_later = last_q[2] - 1
if attempts_later > 10:
timeline.append({"event": "Later",
"title": ("{} attempts on {} after starting"
.format(attempts_later, curr_q)),
"attempt": total_attempt_count,
"backup": backup})
timeline.append({"event": "Solved",
"title": "Solved {}".format(curr_q),
"attempt": total_attempt_count,
"backup": backup})
else:
last_q = (curr_q, is_solved, last_q[2]+1)
if backup.submit:
timeline.append({"event": "Submitted",
"attempt": total_attempt_count,
"title": "Submitted ({})".format(backup.hashid),
"backup": backup})
history.append(message.contents)
return {'submitters': dict(Counter(submitters)),
'timeline': timeline}
def user_status(self, user, staff_view=False):
"""Return a summary of an assignment for a user. If STAFF_VIEW is True,
return more information that staff can see also.
"""
user_ids = self.active_user_ids(user.id)
final_submission = self.final_submission(user_ids)
submission_time = final_submission and final_submission.created
group = Group.lookup(user, self)
scores = self.scores(user_ids, only_published=not staff_view)
return self.user_assignment(
assignment=self,
subm_time=submission_time,
group=group,
final_subm=final_submission,
scores=scores,
)
def course_submissions(self, include_empty=True):
""" Return data on all course submissions for all enrolled users
List of dictionaries with user, group, backup dictionaries.
Sample [ {'user': {}, 'group': {}, 'backup': {} }]
"""
current_db = db.engine.name
if current_db != 'mysql':
return self.course_submissions_slow(include_empty=include_empty)
# Can only run the fast query on MySQL
submissions = []
stats = self.mysql_course_submissions_query()
keys = stats.keys()
for r in stats:
user_info = {k: v for k, v in zip(keys[:3], r[:3])}
group_info = {k: v for k, v in zip(keys[3:6], r[3:6])}
if group_info['group_member_emails']:
group_info['group_member_emails'] = group_info['group_member_emails'].split(',')
backup_info = {k: v for k, v in zip(keys[6:], r[6:])}
if not include_empty and backup_info['id'] is None:
continue
data = {'user': user_info,
'group': group_info if group_info.get('group_id') else None,
'backup': backup_info if backup_info.get('id') else None}
submissions.append(data)
return submissions
def mysql_course_submissions_query(self):
""" For MySQL Clients only. Returns a SQLAlchemy result proxy object
Contains all of the following fields.
id email name group_id group_member group_member_emails
5 dschmidt1@gmail.com 'david s' 3 5,15 dschmidt1@gmail.com, foo@bar.com
created id id submitter_id assignment_id submit flagged
2016-09-07 20:22:04 4790 15 1 1 1
"""
giant_query = """SELECT * FROM
(SELECT u.id,
u.email,
u.name,
gm.group_id,
GROUP_CONCAT(IFNULL(gm2.user_id, u.id)) AS group_member,
GROUP_CONCAT((SELECT partners.email from user as partners
where id = gm2.user_id AND partners.id != u.id)) AS group_member_emails
FROM
(SELECT u.id,
u.email,
u.name
FROM user AS u,
enrollment AS e
WHERE e.course_id = :course_id
AND e.user_id = u.id
AND e.role='student') AS u
LEFT JOIN
(SELECT *
FROM group_member
WHERE status = 'active'
AND assignment_id = :assign_id) AS gm ON u.id = gm.user_id
LEFT JOIN group_member AS gm2 ON gm2.group_id = gm.group_id
AND gm2.status = 'active'
GROUP BY u.id) AS members
LEFT JOIN backup AS b2 ON b2.id=
(SELECT id
FROM backup AS b3,
({group_number_table}) AS member_index_counter
WHERE assignment_id=:assign_id
AND b3.submitter_id = CAST(NULLIF(SUBSTRING_INDEX(members.group_member, ',', -pos),
SUBSTRING_INDEX(members.group_member, ',', 1 - pos))
AS UNSIGNED)
ORDER BY flagged DESC, submit DESC, created DESC LIMIT 1)
ORDER BY group_id DESC;
""".format(group_number_table=generate_number_table(self.max_group_size))
giant_query = text(giant_query)
giant_query = giant_query.bindparams(db.bindparam("course_id", db.Integer),
db.bindparam("assign_id", db.Integer))
result = db.session.execute(giant_query, {'course_id': self.course.id,
'assign_id': self.id})
return result
def course_submissions_slow(self, include_empty=True):
""" Return course submissions info with a slow set of queries."""
seen = set()
submissions = []
for student in self.course.participations:
if student.role == STUDENT_ROLE and student.user_id not in seen:
student_user = student.user
group_ids = self.active_user_ids(student.user_id)
group_obj = Group.lookup(student_user, self)
if group_obj:
group_members = [m.user for m in group_obj.members]
else:
group_members = [student_user]
group_emails = [u.email for u in group_members]
group_member_ids = ','.join([str(u_id) for u_id in group_ids])
fs = self.final_submission(group_ids)
if not fs:
fs = self.backups(group_ids).first()
for member in group_members:
if not fs and not include_empty:
continue
data = {
'user': {
'id': member.id,
'name': member.name,
'email': member.email,
},
'group': {
'group_id': group_obj.id,
'group_member': group_member_ids,
'group_member_emails': group_emails
} if group_obj else None,
'backup': fs.as_dict() if fs else None
}
submissions.append(data)
seen |= group_ids # Perform union of two sets
return submissions
def active_user_ids(self, user_id):
""" Return a set of the ids of all users that are active in the same group
that our user is active in. If the user is not in a group, return just
that user's id (i.e. as if they were in a 1-person group).
"""
user_member = aliased(GroupMember)
members = GroupMember.query.join(
user_member, GroupMember.group_id == user_member.group_id
).filter(
user_member.user_id == user_id,
user_member.assignment_id == self.id,
user_member.status == 'active',
GroupMember.status == 'active'
).all()
if not members:
return {user_id}
else:
return {member.user_id for member in members}
def backups(self, user_ids):
""" Return a query for the backups that the list of users has for this
assignment.
"""
return Backup.query.filter(
Backup.submitter_id.in_(user_ids),
Backup.assignment_id == self.id,
Backup.submit == False
).order_by(Backup.created.desc())
def submissions(self, user_ids):
""" Return a query for the submissions that the list of users has for this
assignment.
"""
return Backup.query.filter(
Backup.submitter_id.in_(user_ids),
Backup.assignment_id == self.id,
Backup.submit == True
).order_by(Backup.created.desc())
def final_submission(self, user_ids):
""" Return a final submission for a user, or None."""
return (Backup.query
.options(db.joinedload(Backup.scores))
.filter(Backup.submitter_id.in_(user_ids),
Backup.assignment_id == self.id,
Backup.submit == True)
.order_by(Backup.flagged.desc(),
Backup.created.desc())
.first())
def revision(self, user_ids):
""" Return the revision backup for a user, or None."""
revision_score = Score.query.filter(
Score.user_id.in_(user_ids),
Score.assignment_id == self.id,
Score.kind == "revision",
Score.archived == False,
).order_by(Score.created.desc()).first()
if revision_score:
return revision_score.backup
def scores(self, user_ids, only_published=True):
"""Return a list of Scores for this assignment and a group. Only the
maximum score for each kind is returned. If there is a tie, the more
recent score is preferred.
"""
scores = Score.query.filter(
Score.user_id.in_(user_ids),
Score.assignment_id == self.id,
Score.archived == False,
).order_by(Score.score.desc(), Score.created.desc()).all()
scores_by_kind = {}
# keep only first score for each kind
for score in scores:
if score.kind not in scores_by_kind:
scores_by_kind[score.kind] = score
max_scores = list(scores_by_kind.values())
if only_published:
return [
score for score in max_scores
if score.kind in self.published_scores
]
else:
return max_scores
@transaction
def flag(self, backup_id, member_ids):
""" Flag a submission. First unflags any submissions by one of
MEMBER_IDS, which is a list of group member user IDs.
"""
self._unflag_all(member_ids)
backup = Backup.query.filter(
Backup.id == backup_id,
Backup.submitter_id.in_(member_ids),
Backup.flagged == False
).one_or_none()
if not backup:
raise BadRequest('Could not find backup')
if not backup.submit:
backup.submit = True
backup.flagged = True
return backup
@transaction
def unflag(self, backup_id, member_ids):
""" Unflag a submission."""
backup = Backup.query.filter(
Backup.id == backup_id,
Backup.submitter_id.in_(member_ids),
Backup.flagged == True
).one_or_none()
if not backup:
raise BadRequest('Could not find backup')
backup.flagged = False
return backup
def _unflag_all(self, member_ids):
""" Unflag all submissions by members of MEMBER_IDS for
this assignment (SELF)
"""
# There should only ever be one flagged submission
backup = Backup.query.filter(
Backup.submitter_id.in_(member_ids),
Backup.assignment_id == self.id,
Backup.flagged == True
).one_or_none()
if backup:
backup.flagged = False
@transaction
def publish_score(self, tag):
"""Publish student score for the assignment."""
self.published_scores = self.published_scores + [tag]
@transaction
def hide_score(self, tag):
"""Hide student score for the assignment."""
self.published_scores = [t for t in self.published_scores if t != tag]
class Enrollment(Model):
__tablename__ = 'enrollment'
__table_args__ = (
PrimaryKeyConstraint('user_id', 'course_id'),
)
user_id = db.Column(db.ForeignKey("user.id"), index=True, nullable=False)
course_id = db.Column(db.ForeignKey("course.id"), index=True,
nullable=False)
role = db.Column(db.Enum(*VALID_ROLES, name='role'),
default=STUDENT_ROLE, nullable=False, index=True)
sid = db.Column(db.String(255))
class_account = db.Column(db.String(255))
section = db.Column(db.String(255))
user = db.relationship("User", backref="participations")
course = db.relationship("Course", backref="participations")
export_items = ('sid', 'class_account', 'section', 'role')
@hybrid_property
def export(self):
""" CSV export data. Overrides Model.export."""
data = self.as_dict()
data['role'] = ROLE_DISPLAY_NAMES[self.role]
return {k: v for k, v in data.items() if k in self.export_items}
def has_role(self, course, role):
if self.course != course:
return False
return self.role == role
def is_staff(self, course):
return self.course == course and self.role in STAFF_ROLES
@classmethod
def can(cls, obj, user, action):
if user.is_admin:
return True
return user.is_enrolled(obj.course.id, STAFF_ROLES)
@staticmethod
@transaction
def enroll_from_form(cid, form):
role = form.role.data
info = {
'email': form.email.data,
'name': form.name.data,
'sid': form.sid.data,
'class_account': form.secondary.data,
'section': form.section.data
}
Enrollment.create(cid, [info], role)
@transaction
def unenroll(self):
cache.delete_memoized(User.is_enrolled)
db.session.delete(self)
@staticmethod
@transaction
def enroll_from_csv(cid, form):
enrollment_info = []
rows = form.csv.data.splitlines()
role = form.role.data
for entry in csv.reader(rows):
entry = [x.strip() for x in entry]
enrollment_info.append({
'email': entry[0],
'name': entry[1],
'sid': entry[2],
'class_account': entry[3],
'section': entry[4],
})
return Enrollment.create(cid, enrollment_info, role)
@staticmethod
@transaction
def create(cid, enrollment_info, role=STUDENT_ROLE):
"""ENROLLMENT_INFO is a sequence of dictionaries with the keys
'email', 'name', 'sid', 'class_account', and 'section'.
Returns two integers, the number of enrollments created and the number
of enrollments updated.
"""
created = 0
updated = 0
for info in enrollment_info:
email, name = info['email'], info['name']
user = User.lookup(email)
if user:
user.name = name
else:
user = User(name=name, email=email)
db.session.add(user)
record = Enrollment.query.filter_by(user_id=user.id,
course_id=cid).one_or_none()
if not record:
record = Enrollment(course_id=cid, user_id=user.id)
created += 1
else:
updated += 1
record.role = role
record.sid = info['sid']
record.class_account = info['class_account']
record.section = info['section']
db.session.add(record)
cache.delete_memoized(User.is_enrolled)
return created, updated
class Message(Model):
__tablename__ = 'message'
__table_args__ = {'mysql_row_format': os.getenv('DB_ROW_FORMAT', 'COMPRESSED')}
id = db.Column(db.Integer, primary_key=True)
backup_id = db.Column(db.ForeignKey("backup.id"), nullable=False,
index=True)
contents = db.Column(JsonBlob, nullable=False)
kind = db.Column(db.String(255), nullable=False, index=True)
backup = db.relationship("Backup")
class Backup(Model):
id = db.Column(db.Integer, primary_key=True)
submitter_id = db.Column(db.ForeignKey("user.id"), nullable=False)
# NULL if same as submitter
creator_id = db.Column(db.ForeignKey("user.id"), nullable=True)
assignment_id = db.Column(db.ForeignKey("assignment.id"), nullable=False)
submit = db.Column(db.Boolean(), nullable=False, default=False, index=True)
flagged = db.Column(db.Boolean(), nullable=False, default=False, index=True)
# The time we should treat this backup as being submitted. If NULL, use
# the `created` timestamp instead.
custom_submission_time = db.Column(db.DateTime(timezone=True), nullable=True)
submitter = db.relationship("User", foreign_keys='Backup.submitter_id')
creator = db.relationship("User", foreign_keys='Backup.creator_id')
assignment = db.relationship("Assignment")
messages = db.relationship("Message")
scores = db.relationship("Score")
comments = db.relationship("Comment", order_by="Comment.created")
external_files = db.relationship("ExternalFile")
# Already have indexes for submitter_id and assignment_id due to FK
db.Index('idx_backupCreated', 'created')
@classmethod
def create(cls, submitter, assignment_id=None, assignment=None, submit=False,
creator=None, created=None, custom_submission_time=None):
created = created or db.func.now()