models.py 23.2 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
from math import log1p
from math import exp
from datetime import timedelta
from gcm import gcm
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.auth.tokens import default_token_generator
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail
from django.core.validators import MinLengthValidator
from django.db import IntegrityError
from django.db.models import *
from django.utils.timezone import now, make_aware
from flashy.settings import QUARTER_START, ABSOLUTE_URL_ROOT, IN_PRODUCTION, GCM_API_KEY
from simple_email_confirmation import SimpleEmailConfirmationUserMixin, EmailAddress
from fields import MaskField
from cached_property import cached_property
# Hack to fix AbstractUser before subclassing it
AbstractUser._meta.get_field('email')._unique = True
AbstractUser._meta.get_field('username')._unique = False
class EmailOnlyUserManager(UserManager):
"""
A tiny extension of Django's UserManager which correctly creates users
without usernames (using emails instead).
"""
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
email = self.normalize_email(email)
user = self.model(email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser,
date_joined=now(), **extra_fields)
user.set_password(password)
user.save(using=self._db)
user.send_confirmation_email()
return user
def create_user(self, email, password=None, **extra_fields):
user = self._create_user(email, password, False, False, **extra_fields)
return user
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
class FlashcardAlreadyPulledException(Exception):
pass
class FlashcardNotInDeckException(Exception):
pass
class FlashcardNotHiddenException(Exception):
pass
class FlashcardAlreadyHiddenException(Exception):
pass
class User(AbstractUser, SimpleEmailConfirmationUserMixin):
"""
An extension of Django's default user model.
We use email as the username field, and include enrolled sections here
"""
objects = EmailOnlyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
sections = ManyToManyField('Section', help_text="The sections which the user is enrolled in")
confirmed_email = BooleanField(default=False)
registration_id = CharField(null=True, default=None, max_length=4096)
last_notified = DateTimeField(null=True, default=None)
@property
def locked(self):
if self.confirmed_email: return False
return (now() - self.date_joined).days > 0
def send_confirmation_email(self):
body = '''
Visit the following link to confirm your email address:
%sapp/verifyemail/%s
If you did not register for Flashy, no action is required.
'''
send_mail("Flashy email verification", body % (ABSOLUTE_URL_ROOT, self.confirmation_key),
"noreply@flashy.cards", [self.email])
def notify(self):
if self.registration_id is None:
raise ValueError("user's registration_id is null")
gcm_ctx = gcm.GCM(GCM_API_KEY)
try:
gcm_ctx.plaintext_request(
registration_id=self.registration_id,
data={'poop': 'data'}
)
except (gcm.GCMInvalidRegistrationException, gcm.GCMMissingRegistrationException):
self.registration_id = None
self.last_notified = now()
self.save()
def set_registration_id(self, token):
self.registration_id = token
self.save()
def is_in_section(self, section):
return self.sections.filter(pk=section.pk).exists()
def pull(self, flashcard):
if not self.is_in_section(flashcard.section):
raise ValueError("User not in the section this flashcard belongs to")
try:
user_card = UserFlashcard.objects.create(user=self, flashcard=flashcard)
except IntegrityError:
raise FlashcardAlreadyPulledException()
flashcard.refresh_score()
import flashcards.pushes
flashcards.pushes.push_feed_event('score_change', flashcard)
flashcards.pushes.push_deck_event('card_pulled', flashcard, self)
def unpull(self, flashcard):
if not self.is_in_section(flashcard.section):
raise ValueError("User not in the section this flashcard belongs to")
try:
user_card = UserFlashcard.objects.get(user=self, flashcard=flashcard)
except UserFlashcard.DoesNotExist:
raise FlashcardNotInDeckException()
user_card.delete()
flashcard.refresh_score()
import flashcards.pushes
flashcards.pushes.push_feed_event('score_change', flashcard)
flashcards.pushes.push_deck_event('card_unpulled', flashcard, self)
def get_deck(self, section):
if not self.is_in_section(section):
raise ObjectDoesNotExist("User not enrolled in section")
return Flashcard.objects.all().filter(userflashcard__user=self).filter(section=section)
def request_password_reset(self):
token = default_token_generator.make_token(self)
body = '''
Visit the following link to reset your password:
%sapp/resetpassword/%d/%s
If you did not request a password reset, no action is required.
'''
send_mail("Flashy password reset",
body % (ABSOLUTE_URL_ROOT, self.pk, token),
"noreply@flashy.cards",
[self.email])
@classmethod
def confirm_email(cls, confirmation_key):
# This will raise an exception if the email address is invalid
address = EmailAddress.objects.confirm(confirmation_key, save=True).email
user = cls.objects.get(email=address)
user.confirmed_email = True
user.save()
return address
def by_retention(self, sections, material_date_begin, material_date_end):
user_flashcard_filter = UserFlashcard.objects.filter(
user=self, flashcard__section__pk__in=sections,
flashcard__material_date__gte=material_date_begin,
flashcard__material_date__lte=material_date_end
)
if not user_flashcard_filter.exists():
raise ValidationError("No matching flashcard found in your decks")
return user_flashcard_filter.order_by('next_review')
class UserFlashcard(Model):
"""
Represents the relationship between a user and a flashcard by:
1. A user has a flashcard in their deck
2. A user used to have a flashcard in their deck
3. A user has a flashcard hidden from them
"""
user = ForeignKey('User')
mask = MaskField(null=True, blank=True, default=None, help_text="The user-specific mask on the card")
pulled = DateTimeField(auto_now_add=True, help_text="When the user pulled the card")
flashcard = ForeignKey('Flashcard')
next_review = DateTimeField(null=True)
last_interval = IntegerField(default=1)
last_response_factor = FloatField(default=2.5)
q_dict = {(False, False): 0, (False, True): 1, (False, None): 2,
(True, False): 3, (True, None): 4, (True, True): 5}
def get_mask(self):
if self.mask is None:
return self.flashcard.mask
return self.mask
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if self.pk is None:
self.next_review = now() + timedelta(days=1)
super(UserFlashcard, self).save(force_insert=force_insert, force_update=force_update,
using=using, update_fields=update_fields)
def review(self, user_flashcard_quiz):
q = self.q_dict[(user_flashcard_quiz.response == user_flashcard_quiz.blanked_word), user_flashcard_quiz.correct]
if self.last_interval == 1:
self.last_interval = 6
else:
self.last_response_factor = max(1.3, self.last_response_factor + (0.1 - (5 - q) * (0.08 + (5 - q) * 0.02)))
# self.last_interval = max(1, self.last_interval + (now() - self.next_review).days)
self.last_interval = int(round(self.last_interval * self.last_response_factor))
self.next_review = now() + timedelta(days=self.last_interval)
self.save()
class Meta:
# There can be at most one UserFlashcard for each User and Flashcard
unique_together = (('user', 'flashcard'),)
index_together = ["user", "flashcard"]
# By default, order by most recently pulled
ordering = ['-pulled']
def __unicode__(self):
return '%s has %s' % (str(self.user), str(self.flashcard))
class FlashcardHide(Model):
"""
Represents the property of a flashcard being hidden by a user.
Each instance of this class represents a single user hiding a single flashcard.
If reason is null, the flashcard was just hidden.
If reason is not null, the flashcard was reported, and reason is the reason why it was reported.
"""
user = ForeignKey('User')
flashcard = ForeignKey('Flashcard')
reason = CharField(max_length=255, blank=True, null=True)
hidden = DateTimeField(auto_now_add=True)
class Meta:
# There can only be one FlashcardHide object for each User and Flashcard
unique_together = (('user', 'flashcard'),)
index_together = ["user", "flashcard"]
def __unicode__(self):
return u'%s hid %s' % (unicode(self.user), unicode(self.flashcard))
class Flashcard(Model):
text = CharField(max_length=180, help_text='The text on the card', validators=[MinLengthValidator(5)])
section = ForeignKey('Section', help_text='The section with which the card is associated')
pushed = DateTimeField(auto_now_add=True, help_text="When the card was first pushed")
material_date = DateTimeField(default=now, help_text="The date with which the card is associated")
previous = ForeignKey('Flashcard', null=True, blank=True, default=None,
help_text="The previous version of this card, if one exists")
score = FloatField(default=0)
author = ForeignKey(User)
is_hidden = BooleanField(default=False)
hide_reason = CharField(blank=True, null=True, max_length=255, default='',
help_text="Reason for hiding this card")
mask = MaskField(null=True, blank=True, help_text="The mask on the card")
class Meta:
# By default, order by most recently pushed
ordering = ['-pushed']
def __unicode__(self):
return u'<flashcard: %s>' % self.text
def refresh_score(self):
self.score = self.calculate_score
self.save()
@classmethod
def push(cls, **kwargs):
card = cls(**kwargs)
card.save()
card.author.pull(card)
import flashcards.pushes
flashcards.pushes.push_feed_event('new_card', card)
return card
@property
def material_week_num(self):
return (self.material_date - QUARTER_START).days / 7 + 1
def is_hidden_from(self, user):
"""
A card can be hidden globally, but if a user has the card in their deck,
this visibility overrides a global hide.
:param user:
:return: Whether the card is hidden from the user.
"""
# if hasattr(self, 'is_not_hidden') and self.is_not_hidden: return False
return self.is_hidden or self.flashcardhide_set.filter(user=user).exists()
def is_in_deck(self, user):
if hasattr(self, 'userflashcard_id'): return self.userflashcard_id
return self.userflashcard_set.filter(user=user).exists()
def edit(self, user, new_data):
"""
Creates a new flashcard if a new flashcard should be created when the given user edits this flashcard.
Sets up everything correctly so this object, when saved, will result in the appropriate changes.
:param user: The user editing this card.
:param new_data: The new information, namely a dict containg 'material_date', 'text', and 'mask' keys.
"""
# content_changed is True iff either material_date or text were changed
content_changed = False
# create_new is True iff the user editing this card is the author of this card
# and there are no other users with this card in their decks
create_new = user != self.author or \
UserFlashcard.objects.filter(flashcard=self).exclude(user=user).exists()
if 'material_date' in new_data and self.material_date != new_data['material_date']:
content_changed = True
self.material_date = new_data['material_date']
if 'text' in new_data and self.text != new_data['text']:
content_changed = True
self.text = new_data['text']
if create_new and content_changed:
if self.is_in_deck(user): user.unpull(self)
self.previous_id = self.pk
self.pk = None
self.mask = new_data.get('mask', self.mask)
self.save()
user.hide(Flashcard.objects.get(pk=self.previous_id))
user.pull(self)
else:
user_card, created = UserFlashcard.objects.get_or_create(user=user, flashcard=self)
user_card.mask = new_data.get('mask', user_card.mask)
user_card.save()
if not create_new:
self.save()
import flashcards.pushes
flashcards.pushes.push_deck_event('card_fixed', self, user)
return self
def hide_by_user(self, user, reason=None):
import flashcards.pushes
flashcards.pushes.push_deck_event('card_hidden', self, user)
if self.is_in_deck(user): user.unpull(self)
hide, created = FlashcardHide.objects.get_or_create(user=user, flashcard=self)
hide.reason = reason
hide.save()
def unhide_by_user(self, user, reason=None):
import flashcards.pushes
flashcards.pushes.push_deck_event('card_unhidden', self, user)
hide = self.flashcardhide_set.get(user=user)
hide.delete()
@cached_property
def calculate_score(self):
def seconds_since_epoch(dt):
from datetime import datetime
epoch = make_aware(datetime.utcfromtimestamp(0))
delta = dt - epoch
return delta.total_seconds()
z = 0
rate = 1.0 / 120
for vote in self.userflashcard_set.iterator():
t = seconds_since_epoch(vote.pulled)
u = max(z, rate * t)
v = min(z, rate * t)
z = u + log1p(exp(v - u))
return z
@classmethod
def cards_visible_to(cls, user):
"""
:param user:
:return: A queryset with all cards that should be visible to a user.
"""
# All flashcards where the author is either confirmed, or the user
rqs = cls.objects.filter(Q(author__confirmed_email=True) | Q(author=user))
# Exclude hidden cards
rqs = rqs.exclude(Q(is_hidden=True) | Q(flashcardhide__user=user))
# rqs = rqs.prefetch_related('userflashcard_set')
# rqs = rqs.aggregate(Count(userflashcard__user=user))
# Annotate the cards so we don't have to check if they're hidden in the future
return rqs.annotate(is_not_hidden=Value(True, output_field=BooleanField()))
@classmethod
def cards_hidden_by(cls, user):
return cls.objects.filter(flashcardhide__user=user)
class UserFlashcardQuiz(Model):
"""
An event of a user being quizzed on a flashcard.
"""
user_flashcard = ForeignKey(UserFlashcard)
when = DateTimeField(auto_now=True)
blanked_word = CharField(max_length=255, blank=True, help_text="The character range which was blanked")
response = CharField(max_length=255, blank=True, null=True, default=None, help_text="The user's response")
correct = NullBooleanField(help_text="The user's self-evaluation of their response")
def __unicode__(self):
return '%s reviewed %s' % (str(self.user_flashcard.user), str(self.user_flashcard.flashcard))
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
super(UserFlashcardQuiz, self).save(force_insert=force_insert, force_update=force_update,
using=using, update_fields=update_fields)
self.user_flashcard.review(self)
def status(self):
"""
There are three stages of a quiz object:
1. the user has been shown the card
2. the user has answered the card
3. the user has self-evaluated their response's correctness
:return: string (evaluated, answered, viewed)
"""
if self.correct is not None: return "evaluated"
if self.response: return "answered"
return "viewed"
class Section(Model):
"""
A UCSD course taught by an instructor during a quarter.
We use the term "section" to avoid collision with the builtin keyword "class"
We index gratuitously to support autofill and because this is primarily read-only
"""
department = CharField(db_index=True, max_length=50)
department_abbreviation = CharField(db_index=True, max_length=10)
course_num = CharField(db_index=True, max_length=6)
course_title = CharField(db_index=True, max_length=50)
instructor = CharField(db_index=True, max_length=100)
quarter = CharField(db_index=True, max_length=4)
PAGE_SIZE = 40
@classmethod
def search(cls, terms):
"""
Search all fields of all sections for a particular set of terms
A matching section must match at least one field on each term
:param terms:iterable
:return: Matching QuerySet ordered by department and course number
"""
final_q = Q()
for term in terms:
q = Q(department__icontains=term)
q |= Q(department_abbreviation__icontains=term)
q |= Q(course_title__icontains=term)
q |= Q(course_num__icontains=term)
q |= Q(instructor__icontains=term)
final_q &= q
qs = cls.objects.filter(final_q).prefetch_related('whitelist')
# Have the database cast the course number to an integer so it will sort properly
# ECE 35 should rank before ECE 135 even though '135' < '35' lexicographically
qs = qs.extra(select={'course_num_int': "CAST(rtrim(course_num, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') AS INTEGER)"})
qs = qs.order_by('department_abbreviation', 'course_num_int')
return qs
@property
def is_whitelisted(self):
"""
:return: whether a whitelist exists for this section
"""
data = cache.get("section_%d_is_whitelisted" % self.pk)
if data is None:
data = self.whitelist.exists()
cache.set("section_%d_is_whitelisted" % self.pk, data, 24 * 60 * 60)
return data
def is_user_on_whitelist(self, user):
"""
:return: whether the user is on the waitlist for this section
"""
return self.whitelist.filter(email=user.email).exists()
def is_user_enrolled(self, user):
return self.user_set.filter(pk=user.pk).exists()
def enroll(self, user):
if user.sections.filter(pk=self.pk).exists():
raise ValidationError('User is already enrolled in this section')
if self.is_whitelisted and not self.is_user_on_whitelist(user):
raise PermissionDenied("User must be on the whitelist to add this section.")
self.user_set.add(user)
def drop(self, user):
if not user.sections.filter(pk=self.pk).exists():
raise ValidationError("User is not enrolled in the section.")
self.user_set.remove(user)
class Meta:
ordering = ['department_abbreviation', 'course_num']
@property
def lecture_times(self):
data = cache.get("section_%d_lecture_times" % self.pk)
if not data:
lecture_periods = self.lectureperiod_set.all()
if lecture_periods.exists():
data = ''.join(map(lambda x: x.weekday_letter, lecture_periods)) + ' ' + lecture_periods[
0].short_start_time
else:
data = ''
cache.set("section_%d_lecture_times" % self.pk, data, 24 * 60 * 60)
return data
@property
def long_name(self):
return '%s %s (%s)' % (self.course_title, self.lecture_times, self.instructor)
@property
def short_name(self):
return '%s %s' % (self.department_abbreviation, self.course_num)
def get_feed_for_user(self, user):
cards = self.get_cards_for_user(user).order_by('-score')
return cards
def get_cards_for_user(self, user):
return Flashcard.cards_visible_to(user).filter(section=self)
def __unicode__(self):
return '%s %s: %s (%s %s)' % (
self.department_abbreviation, self.course_num, self.course_title, self.instructor, self.quarter)
class LecturePeriod(Model):
"""
A lecture period for a section
"""
section = ForeignKey(Section)
week_day = IntegerField(help_text="1-indexed day of week, starting at Sunday")
start_time = TimeField()
end_time = TimeField()
@property
def weekday_letter(self):
return ['?', 'S', 'M', 'T', 'W', 'Th', 'F', 'S', 'S'][self.week_day]
@property
def short_start_time(self):
# lstrip 0 because windows doesn't support %-I
return self.start_time.strftime('%I %p').lstrip('0')
class Meta:
unique_together = (('section', 'start_time', 'week_day'),)
ordering = ['section', 'week_day']
def __unicode__(self):
return self.weekday_letter + ' ' + self.short_start_time
class WhitelistedAddress(Model):
"""
An email address that has been whitelisted for a section at an instructor's request
"""
email = EmailField()
section = ForeignKey(Section, related_name='whitelist')
def __unicode__(self):
return '%s whitelisted for %s' % (str(self.email), str(self.section))
class Now(Func):
template = 'CURRENT_TIMESTAMP'
def __init__(self, output_field=DateTimeField(), **extra):
self.source_expressions = []
self.extra = {}
super(Func, self).__init__(output_field=output_field, **extra)
def copy(self):
return super(Func, self).copy()
class JulianDay(Func):
function = 'julianday'
template = '%(function)s(%(expressions)s)'
def __init__(self, expression, **extra):
output = extra.pop('output_field', FloatField())
super(JulianDay, self).__init__(expression, output_field=output, **extra)
class PostgresIntervalDay(Func):
function = 'EXTRACT'
template = "(((%(function)s(EPOCH FROM %(expressions)s) / 60) / 60) / 24)::integer"
arg_joiner = ' - '
def __init__(self, *expression, **extra):
output = extra.pop('output_field', FloatField())
super(PostgresIntervalDay, self).__init__(*expression, output_field=output, **extra)
def interval_days(expression1, expression2):
if IN_PRODUCTION:
return PostgresIntervalDay(expression1, expression2)
return JulianDay(expression1) - JulianDay(expression2)