This repository was archived by the owner on Dec 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathmodels.py
1328 lines (1075 loc) · 47.7 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 logging
import re
import random
import hashlib
from datetime import datetime, timedelta, tzinfo
from time import time, gmtime, strftime
import calendar
import os.path
from os.path import dirname
from urlparse import urljoin
from django.conf import settings
from django.db import models
from django.db.models import signals, Q, Count, Max
from django.db.models.fields.files import FieldFile, ImageFieldFile
from django.core.mail import send_mail
from django.core.exceptions import ValidationError
from django.core.files.storage import FileSystemStorage
from django.core.files.base import ContentFile
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.sites.models import Site
from django.contrib.contenttypes.models import ContentType
from django.template import Context, TemplateDoesNotExist
from django.template.loader import render_to_string
from django.core.serializers.json import DjangoJSONEncoder
import json
# HACK: Django 1.2 is missing receiver and user_logged_in
try:
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
except ImportError:
receiver = False
user_logged_in = False
try:
from tower import ugettext_lazy as _
except ImportError:
from django.utils.translation import ugettext_lazy as _
try:
from funfactory.urlresolvers import reverse
except ImportError:
from django.core.urlresolvers import reverse
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
from PIL import Image
except ImportError:
import Image
try:
import taggit
from taggit.managers import TaggableManager
from taggit.models import Tag, TaggedItem
except ImportError:
taggit = None
if "notification" in settings.INSTALLED_APPS:
from notification import models as notification
else:
notification = None
import badger
from .signals import (badge_will_be_awarded, badge_was_awarded,
nomination_will_be_approved, nomination_was_approved,
nomination_will_be_accepted, nomination_was_accepted,
nomination_will_be_rejected, nomination_was_rejected,
user_will_be_nominated, user_was_nominated)
OBI_VERSION = "0.5.0"
IMG_MAX_SIZE = getattr(settings, "BADGER_IMG_MAX_SIZE", (256, 256))
SITE_ISSUER = getattr(settings, 'BADGER_SITE_ISSUER', {
"name": "Example",
"url": "http://example.com",
"description": "This is an example organization",
"email": "[email protected]"
})
# Set up a file system for badge uploads that can be kept separate from the
# rest of /media if necessary. Lots of hackery to ensure sensible defaults.
UPLOADS_ROOT = getattr(settings, 'BADGER_MEDIA_ROOT',
os.path.join(getattr(settings, 'MEDIA_ROOT', 'media/'), 'uploads'))
UPLOADS_URL = getattr(settings, 'BADGER_MEDIA_URL',
urljoin(getattr(settings, 'MEDIA_URL', '/media/'), 'uploads/'))
BADGE_UPLOADS_FS = FileSystemStorage(location=UPLOADS_ROOT,
base_url=UPLOADS_URL)
DEFAULT_BADGE_IMAGE = getattr(settings, 'BADGER_DEFAULT_BADGE_IMAGE',
"%s/fixtures/default-badge.png" % dirname(__file__))
DEFAULT_BADGE_IMAGE_URL = getattr(settings, 'BADGER_DEFAULT_BADGE_IMAGE_URL',
urljoin(getattr(settings, 'MEDIA_URL', '/media/'), 'img/default-badge.png'))
TIME_ZONE_OFFSET = getattr(settings, "TIME_ZONE_OFFSET", timedelta(0))
MK_UPLOAD_TMPL = '%(base)s/%(h1)s/%(h2)s/%(hash)s_%(field_fn)s_%(now)s_%(rand)04d.%(ext)s'
DEFAULT_HTTP_PROTOCOL = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
CLAIM_CODE_LENGTH = getattr(settings, "CLAIM_CODE_LENGTH", 6)
def _document_django_model(cls):
"""Adds meta fields to the docstring for better autodoccing"""
fields = cls._meta.fields
doc = cls.__doc__
if not doc.endswith('\n\n'):
doc = doc + '\n\n'
for f in fields:
doc = doc + ' :arg {0}:\n'.format(f.name)
cls.__doc__ = doc
return cls
def scale_image(img_upload, img_max_size):
"""Crop and scale an image file."""
try:
img = Image.open(img_upload)
except IOError:
return None
src_width, src_height = img.size
src_ratio = float(src_width) / float(src_height)
dst_width, dst_height = img_max_size
dst_ratio = float(dst_width) / float(dst_height)
if dst_ratio < src_ratio:
crop_height = src_height
crop_width = crop_height * dst_ratio
x_offset = int(float(src_width - crop_width) / 2)
y_offset = 0
else:
crop_width = src_width
crop_height = crop_width / dst_ratio
x_offset = 0
y_offset = int(float(src_height - crop_height) / 2)
img = img.crop((x_offset, y_offset,
x_offset + int(crop_width), y_offset + int(crop_height)))
img = img.resize((dst_width, dst_height), Image.ANTIALIAS)
# If the mode isn't RGB or RGBA we convert it. If it's not one
# of those modes, then we don't know what the alpha channel should
# be so we convert it to "RGB".
if img.mode not in ("RGB", "RGBA"):
img = img.convert("RGB")
new_img = StringIO()
img.save(new_img, "PNG")
img_data = new_img.getvalue()
return ContentFile(img_data)
# Taken from http://stackoverflow.com/a/4019144
def slugify(txt):
"""A custom version of slugify that retains non-ascii characters. The
purpose of this function in the application is to make URLs more readable
in a browser, so there are some added heuristics to retain as much of the
title meaning as possible while excluding characters that are troublesome
to read in URLs. For example, question marks will be seen in the browser
URL as %3F and are thereful unreadable. Although non-ascii characters will
also be hex-encoded in the raw URL, most browsers will display them as
human-readable glyphs in the address bar -- those should be kept in the
slug."""
# remove trailing whitespace
txt = txt.strip()
# remove spaces before and after dashes
txt = re.sub('\s*-\s*', '-', txt, re.UNICODE)
# replace remaining spaces with dashes
txt = re.sub('[\s/]', '-', txt, re.UNICODE)
# replace colons between numbers with dashes
txt = re.sub('(\d):(\d)', r'\1-\2', txt, re.UNICODE)
# replace double quotes with single quotes
txt = re.sub('"', "'", txt, re.UNICODE)
# remove some characters altogether
txt = re.sub(r'[?,:!@#~`+=$%^&\\*()\[\]{}<>]', '', txt, re.UNICODE)
return txt
def get_permissions_for(self, user):
"""Mixin method to collect permissions for a model instance"""
pre = 'allows_'
pre_len = len(pre)
methods = (m for m in dir(self) if m.startswith(pre))
perms = dict(
(m[pre_len:], getattr(self, m)(user))
for m in methods
)
return perms
def mk_upload_to(field_fn, ext, tmpl=MK_UPLOAD_TMPL):
"""upload_to builder for file upload fields"""
def upload_to(instance, filename):
base, slug = instance.get_upload_meta()
slug_hash = (hashlib.md5(slug.encode('utf-8', 'ignore'))
.hexdigest())
return tmpl % dict(now=int(time()), rand=random.randint(0, 1000),
slug=slug[:50], base=base, field_fn=field_fn,
pk=instance.pk,
hash=slug_hash, h1=slug_hash[0], h2=slug_hash[1],
ext=ext)
return upload_to
class JSONField(models.TextField):
"""JSONField is a generic textfield that neatly serializes/unserializes
JSON objects seamlessly
see: http://djangosnippets.org/snippets/1478/
"""
# Used so to_python() is called
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""Convert our string value to JSON after we load it from the DB"""
if not value:
return dict()
try:
if (isinstance(value, basestring) or
type(value) is unicode):
return json.loads(value)
except ValueError:
return dict()
return value
def get_db_prep_save(self, value, connection):
"""Convert our JSON object to a string before we save"""
if not value:
return '{}'
if isinstance(value, dict):
value = json.dumps(value, cls=DjangoJSONEncoder)
if isinstance(value, basestring) or value is None:
return value
return smart_unicode(value)
# Tell South that this field isn't all that special
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^badger.models.JSONField"])
except ImportError:
pass
class SearchManagerMixin(object):
"""Quick & dirty manager mixin for search"""
# See: http://www.julienphalip.com/blog/2008/08/16/adding-search-django-site-snap/
def _normalize_query(self, query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub):
"""
Splits the query string in invidual keywords, getting rid of unecessary spaces
and grouping quoted words together.
Example::
foo._normalize_query(' some random words "with quotes " and spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces']
"""
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]
# See: http://www.julienphalip.com/blog/2008/08/16/adding-search-django-site-snap/
def _get_query(self, query_string, search_fields):
"""
Returns a query, that is a combination of Q objects. That
combination aims to search keywords within a model by testing
the given search fields.
"""
query = None # Query to search for every search term
terms = self._normalize_query(query_string)
for term in terms:
or_query = None # Query to search for a given term in each field
for field_name in search_fields:
q = Q(**{"%s__icontains" % field_name: term})
if or_query is None:
or_query = q
else:
or_query = or_query | q
if query is None:
query = or_query
else:
query = query & or_query
return query
def search(self, query_string, sort='title'):
"""Quick and dirty keyword search on submissions"""
# TODO: Someday, replace this with something like Sphinx or another real
# search engine
strip_qs = query_string.strip()
if not strip_qs:
return self.all_sorted(sort).order_by('-modified')
else:
query = self._get_query(strip_qs, self.search_fields)
return self.all_sorted(sort).filter(query).order_by('-modified')
def all_sorted(self, sort=None):
"""Apply to .all() one of the sort orders supported for views"""
queryset = self.all()
if sort == 'title':
return queryset.order_by('title')
else:
return queryset.order_by('-created')
class BadgerException(Exception):
"""General Badger model exception"""
class BadgeException(BadgerException):
"""Badge model exception"""
class BadgeAwardNotAllowedException(BadgeException):
"""Attempt to award a badge not allowed."""
class BadgeAlreadyAwardedException(BadgeException):
"""Attempt to award a unique badge twice."""
class BadgeDeferredAwardManagementNotAllowedException(BadgeException):
"""Attempt to manage deferred awards not allowed."""
class BadgeManager(models.Manager, SearchManagerMixin):
"""Manager for Badge model objects"""
search_fields = ('title', 'slug', 'description', )
def allows_add_by(self, user):
if user.is_anonymous():
return False
if getattr(settings, "BADGER_ALLOW_ADD_BY_ANYONE", False):
return True
if user.has_perm('badger.add_badge'):
return True
return False
def allows_grant_by(self, user):
if user.is_anonymous():
return False
if user.has_perm('badger.grant_deferredaward'):
return True
return False
def top_tags(self, min_count=2, limit=20):
"""Assemble list of top-used tags"""
if not taggit:
return []
# TODO: There has got to be a better way to do this. I got lost in
# Django model bits, though.
# Gather list of tags sorted by use frequency
ct = ContentType.objects.get_for_model(Badge)
tag_counts = (TaggedItem.objects
.values('tag')
.annotate(count=Count('id'))
.filter(content_type=ct, count__gte=min_count)
.order_by('-count'))[:limit]
# Gather set of tag IDs from list
tag_ids = set(x['tag'] for x in tag_counts)
# Gather and map tag objects to IDs
tags_by_id = dict((x.pk, x)
for x in Tag.objects.filter(pk__in=tag_ids))
# Join tag objects up with counts
tags_with_counts = [
dict(count=x['count'], tag=tags_by_id[x['tag']])
for x in tag_counts]
return tags_with_counts
@_document_django_model
class Badge(models.Model):
"""Representation of a badge"""
objects = BadgeManager()
title = models.CharField(max_length=255, blank=False, unique=True,
help_text='Short, descriptive title')
slug = models.SlugField(blank=False, unique=True,
help_text='Very short name, for use in URLs and links')
description = models.TextField(blank=True,
help_text='Longer description of the badge and its criteria')
image = models.ImageField(blank=True, null=True,
storage=BADGE_UPLOADS_FS, upload_to=mk_upload_to('image', 'png'),
help_text='Upload an image to represent the badge')
prerequisites = models.ManyToManyField('self', symmetrical=False,
blank=True, null=True,
help_text=('When all of the selected badges have been awarded, this '
'badge will be automatically awarded.'))
# TODO: Rename? Eventually we'll want a globally-unique badge. That is, one
# unique award for one person for the whole site.
unique = models.BooleanField(default=True,
help_text=('Should awards of this badge be limited to '
'one-per-person?'))
nominations_accepted = models.BooleanField(default=True, blank=True,
help_text=('Should this badge accept nominations from '
'other users?'))
nominations_autoapproved = models.BooleanField(default=False, blank=True,
help_text='Should all nominations be automatically approved?')
if taggit:
tags = TaggableManager(blank=True)
creator = models.ForeignKey(User, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True, blank=False)
modified = models.DateTimeField(auto_now=True, blank=False)
class Meta:
unique_together = ('title', 'slug')
ordering = ['-modified', '-created']
permissions = (
('manage_deferredawards',
_(u'Can manage deferred awards for this badge')),
)
get_permissions_for = get_permissions_for
def __unicode__(self):
return self.title
def get_absolute_url(self, format='html'):
if format == 'json':
return reverse('badger.detail_json', args=(self.slug,))
return reverse('badger.views.detail', args=(self.slug,))
def get_upload_meta(self):
return ("badge", self.slug)
def clean(self):
if self.image:
scaled_file = scale_image(self.image.file, IMG_MAX_SIZE)
if not scaled_file:
raise ValidationError(_(u'Cannot process image'))
self.image.file = scaled_file
def save(self, **kwargs):
"""Save the submission, updating slug and screenshot thumbnails"""
if not self.slug:
self.slug = slugify(self.title)
super(Badge, self).save(**kwargs)
if notification:
if self.creator:
notification.send([self.creator], 'badge_edited',
dict(badge=self,
protocol=DEFAULT_HTTP_PROTOCOL))
def delete(self, **kwargs):
"""Make sure deletes cascade to awards"""
self.award_set.all().delete()
super(Badge, self).delete(**kwargs)
def allows_detail_by(self, user):
# TODO: Need some logic here, someday.
return True
def allows_edit_by(self, user):
if user.is_anonymous():
return False
if user.has_perm('badger.change_badge'):
return True
if user == self.creator:
return True
return False
def allows_delete_by(self, user):
if user.is_anonymous():
return False
if user.has_perm('badger.change_badge'):
return True
if user == self.creator:
return True
return False
def allows_award_to(self, user):
"""Is award_to() allowed for this user?"""
if None == user:
return True
if user.is_anonymous():
return False
if user.is_staff or user.is_superuser:
return True
if user == self.creator:
return True
# TODO: List of delegates for whom awarding is allowed
return False
def allows_manage_deferred_awards_by(self, user):
"""Can this user manage deferred awards"""
if user.is_anonymous():
return False
if user.has_perm('badger.manage_deferredawards'):
return True
if user == self.creator:
return True
return False
def generate_deferred_awards(self, user, amount=10, reusable=False):
"""Generate a number of deferred awards with a claim group code"""
if not self.allows_manage_deferred_awards_by(user):
raise BadgeDeferredAwardManagementNotAllowedException()
return (DeferredAward.objects.generate(self, user, amount, reusable))
def get_claim_group(self, claim_group):
"""Get all the deferred awards for a claim group code"""
return DeferredAward.objects.filter(claim_group=claim_group)
def delete_claim_group(self, user, claim_group):
"""Delete all the deferred awards for a claim group code"""
if not self.allows_manage_deferred_awards_by(user):
raise BadgeDeferredAwardManagementNotAllowedException()
self.get_claim_group(claim_group).delete()
@property
def claim_groups(self):
"""Produce a list of claim group IDs available"""
return DeferredAward.objects.get_claim_groups(badge=self)
def award_to(self, awardee=None, email=None, awarder=None,
description='', raise_already_awarded=False):
"""Award this badge to the awardee on the awarder's behalf"""
# If no awarder given, assume this is on the badge creator's behalf.
if not awarder:
awarder = self.creator
if not self.allows_award_to(awarder):
raise BadgeAwardNotAllowedException()
# If we have an email, but no awardee, try looking up the user.
if email and not awardee:
qs = User.objects.filter(email=email)
if not qs:
# If there's no user for this email address, create a
# DeferredAward for future claiming.
if self.unique and DeferredAward.objects.filter(
badge=self, email=email).exists():
raise BadgeAlreadyAwardedException()
da = DeferredAward(badge=self, email=email)
da.save()
return da
# Otherwise, we'll use the most recently created user
awardee = qs.latest('date_joined')
if self.unique and self.is_awarded_to(awardee):
if raise_already_awarded:
raise BadgeAlreadyAwardedException()
else:
return Award.objects.filter(user=awardee, badge=self)[0]
return Award.objects.create(user=awardee, badge=self,
creator=awarder,
description=description)
def check_prerequisites(self, awardee, dep_badge, award):
"""Check the prerequisites for this badge. If they're all met, award
this badge to the user."""
if self.is_awarded_to(awardee):
# Not unique, but badge auto-award from prerequisites should only
# happen once.
return None
for badge in self.prerequisites.all():
if not badge.is_awarded_to(awardee):
# Bail on the first unmet prerequisites
return None
return self.award_to(awardee)
def is_awarded_to(self, user):
"""Has this badge been awarded to the user?"""
return Award.objects.filter(user=user, badge=self).count() > 0
def progress_for(self, user):
"""Get or create (but not save) a progress record for a user"""
try:
# Look for an existing progress record...
p = Progress.objects.get(user=user, badge=self)
except Progress.DoesNotExist:
# If none found, create a new one but don't save it yet.
p = Progress(user=user, badge=self)
return p
def allows_nominate_for(self, user):
"""Is nominate_for() allowed for this user?"""
if not self.nominations_accepted:
return False
if None == user:
return True
if user.is_anonymous():
return False
if user.is_staff or user.is_superuser:
return True
if user == self.creator:
return True
# TODO: Flag to enable / disable nominations from anyone
# TODO: List of delegates from whom nominations are accepted
return True
def nominate_for(self, nominee, nominator=None):
"""Nominate a nominee for this badge on the nominator's behalf"""
nomination = Nomination.objects.create(badge=self, creator=nominator,
nominee=nominee)
if notification:
if self.creator:
notification.send([self.creator], 'nomination_submitted',
dict(nomination=nomination,
protocol=DEFAULT_HTTP_PROTOCOL))
if self.nominations_autoapproved:
nomination.approve_by(self.creator)
return nomination
def is_nominated_for(self, user):
return Nomination.objects.filter(nominee=user, badge=self).count() > 0
def as_obi_serialization(self, request=None):
"""Produce an Open Badge Infrastructure serialization of this badge"""
if request:
base_url = request.build_absolute_uri('/')[:-1]
else:
base_url = 'http://%s' % (Site.objects.get_current().domain,)
data = {
# TODO: truncate more intelligently
"name": self.title[:128],
# TODO: truncate more intelligently
"description": self.description[:128] or self.title[:128],
"criteria": urljoin(base_url, self.get_absolute_url()),
"issuer": urljoin(base_url, reverse('badger.site_issuer'))
}
image_url = self.image and self.image.url or DEFAULT_BADGE_IMAGE_URL
data['image'] = urljoin(base_url, image_url)
# TODO: tags
# TODO: alignment
return data
class AwardManager(models.Manager):
def get_query_set(self):
return super(AwardManager, self).get_query_set().exclude(hidden=True)
@_document_django_model
class Award(models.Model):
"""Representation of a badge awarded to a user"""
admin_objects = models.Manager()
objects = AwardManager()
description = models.TextField(blank=True,
help_text='Explanation and evidence for the badge award')
badge = models.ForeignKey(Badge)
image = models.ImageField(blank=True, null=True,
storage=BADGE_UPLOADS_FS,
upload_to=mk_upload_to('image', 'png'))
claim_code = models.CharField(max_length=32, blank=True,
default='', unique=False, db_index=True,
help_text='Code used to claim this award')
user = models.ForeignKey(User, related_name="award_user")
creator = models.ForeignKey(User, related_name="award_creator",
blank=True, null=True)
hidden = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True, blank=False)
modified = models.DateTimeField(auto_now=True, blank=False)
get_permissions_for = get_permissions_for
class Meta:
ordering = ['-modified', '-created']
def __unicode__(self):
by = self.creator and (u' by %s' % self.creator) or u''
return u'Award of %s to %s%s' % (self.badge, self.user, by)
@models.permalink
def get_absolute_url(self, format='html'):
if format == 'json':
return ('badger.award_detail_json', (self.badge.slug, self.pk))
return ('badger.views.award_detail', (self.badge.slug, self.pk))
def get_upload_meta(self):
u = self.user.username
return ("award/%s/%s/%s" % (u[0], u[1], u), self.badge.slug)
def allows_detail_by(self, user):
# TODO: Need some logic here, someday.
return True
def allows_delete_by(self, user):
if user.is_anonymous():
return False
if user == self.user:
return True
if user == self.creator:
return True
if user.has_perm('badger.change_award'):
return True
return False
def save(self, *args, **kwargs):
# Signals and some bits of logic only happen on a new award.
is_new = not self.pk
if is_new:
# Bail if this is an attempt to double-award a unique badge
if self.badge.unique and self.badge.is_awarded_to(self.user):
raise BadgeAlreadyAwardedException()
# Only fire will-be-awarded signal on a new award.
badge_will_be_awarded.send(sender=self.__class__, award=self)
super(Award, self).save(*args, **kwargs)
# Called after super.save(), so we have some auto-gen fields
if badger.settings.BAKE_AWARD_IMAGES:
self.bake_obi_image()
if is_new:
# Only fire was-awarded signal on a new award.
badge_was_awarded.send(sender=self.__class__, award=self)
if notification:
if self.creator:
notification.send([self.badge.creator], 'badge_awarded',
dict(award=self,
protocol=DEFAULT_HTTP_PROTOCOL))
notification.send([self.user], 'award_received',
dict(award=self,
protocol=DEFAULT_HTTP_PROTOCOL))
# Since this badge was just awarded, check the prerequisites on all
# badges that count this as one.
for dep_badge in self.badge.badge_set.all():
dep_badge.check_prerequisites(self.user, self.badge, self)
# Reset any progress for this user & badge upon award.
Progress.objects.filter(user=self.user, badge=self.badge).delete()
def delete(self):
"""Make sure nominations get deleted along with awards"""
Nomination.objects.filter(award=self).delete()
super(Award, self).delete()
def as_obi_assertion(self, request=None):
"""Build a representation of this award as an OBI assertion"""
if request:
base_url = request.build_absolute_uri('/')[:-1]
else:
base_url = 'http://%s' % (Site.objects.get_current().domain,)
hash_salt = (hashlib.md5('%s-%s-%s' % (self.badge.pk,
self.pk,
settings.SECRET_KEY))
.hexdigest())
recipient_text = '%s%s' % (self.user.email, hash_salt)
recipient_hash = ('sha256$%s' % hashlib.sha256(recipient_text)
.hexdigest())
assertion = {
"uid": '%s' % self.id,
"recipient": {
"type": "email",
"hashed": True,
"salt": hash_salt,
"identity": recipient_hash
},
"badge": urljoin(base_url,
self.badge.get_absolute_url(format='json')),
"verify": {
"type": "hosted",
"url": urljoin(base_url,
self.get_absolute_url(format='json'))
},
"evidence": urljoin(base_url, self.get_absolute_url()),
"issuedOn": calendar.timegm(self.created.utctimetuple()),
# TODO: implement award expiration
# "expires": calendar.timegm(self.expires.utctimetuple()),
}
return assertion
def bake_obi_image(self, request=None):
"""Bake the OBI JSON badge award assertion into a copy of the original
badge's image, if one exists."""
if request:
base_url = request.build_absolute_uri('/')
else:
base_url = 'http://%s' % (Site.objects.get_current().domain,)
if self.badge.image:
# Make a duplicate of the badge image
self.badge.image.open()
img_copy_fh = StringIO(self.badge.image.file.read())
else:
# Make a copy of the default badge image
img_copy_fh = StringIO(open(DEFAULT_BADGE_IMAGE, 'rb').read())
try:
# Try processing the image copy, bail if the image is bad.
img = Image.open(img_copy_fh)
except IOError:
return False
# Here's where the baking gets done. JSON representation of the OBI
# assertion gets written into the "openbadges" metadata field
# see: http://blog.client9.com/2007/08/python-pil-and-png-metadata-take-2.html
# see: https://github.com/mozilla/openbadges/blob/development/lib/baker.js
# see: https://github.com/mozilla/openbadges/blob/development/controllers/baker.js
try:
from PIL import PngImagePlugin
except ImportError:
import PngImagePlugin
meta = PngImagePlugin.PngInfo()
# TODO: Will need this, if we stop doing hosted assertions
# assertion = self.as_obi_assertion(request)
# meta.add_text('openbadges', json.dumps(assertion))
hosted_assertion_url = '%s%s' % (
base_url, reverse('badger.award_detail_json',
args=(self.badge.slug, self.id)))
meta.add_text('openbadges', hosted_assertion_url)
# And, finally save out the baked image.
new_img = StringIO()
img.save(new_img, "PNG", pnginfo=meta)
img_data = new_img.getvalue()
name_before = self.image.name
self.image.save('', ContentFile(img_data), False)
if (self.image.storage.exists(name_before)):
self.image.storage.delete(name_before)
# Update the image field with the new image name
# NOTE: Can't do a full save(), because this gets called in save()
Award.objects.filter(pk=self.pk).update(image=self.image)
return True
@property
def nomination(self):
"""Find the nomination behind this award, if any."""
# TODO: This should really be a foreign key relation, someday.
try:
return Nomination.objects.get(award=self)
except Nomination.DoesNotExist:
return None
class ProgressManager(models.Manager):
pass
class Progress(models.Model):
"""Record tracking progress toward auto-award of a badge"""
badge = models.ForeignKey(Badge)
user = models.ForeignKey(User, related_name="progress_user")
percent = models.FloatField(default=0)
counter = models.FloatField(default=0, blank=True, null=True)
notes = JSONField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True, blank=False)
modified = models.DateTimeField(auto_now=True, blank=False)
class Meta:
unique_together = ('badge', 'user')
verbose_name_plural = "Progresses"
get_permissions_for = get_permissions_for
def __unicode__(self):
perc = self.percent and (' (%s%s)' % (self.percent, '%')) or ''
return u'Progress toward %s by %s%s' % (self.badge, self.user, perc)
def save(self, *args, **kwargs):
"""Save the progress record, with before and after signals"""
# Signals and some bits of logic only happen on a new award.
is_new = not self.pk
# Bail if this is an attempt to double-award a unique badge
if (is_new and self.badge.unique and
self.badge.is_awarded_to(self.user)):
raise BadgeAlreadyAwardedException()
super(Progress, self).save(*args, **kwargs)
# If the percent is over/equal to 1.0, auto-award on save.
if self.percent >= 100:
self.badge.award_to(self.user)
def _quiet_save(self, raise_exception=False):
try:
self.save()
except BadgeAlreadyAwardedException as e:
if raise_exception:
raise e
def update_percent(self, current, total=None, raise_exception=False):
"""Update the percent completion value."""
if total is None:
value = current
else:
value = (float(current) / float(total)) * 100.0
self.percent = value
self._quiet_save(raise_exception)
def increment_by(self, amount, raise_exception=False):
# TODO: Do this with an UPDATE counter+amount in DB
self.counter += amount
self._quiet_save(raise_exception)
return self
def decrement_by(self, amount, raise_exception=False):
# TODO: Do this with an UPDATE counter-amount in DB
self.counter -= amount
self._quiet_save(raise_exception)
return self
class DeferredAwardManager(models.Manager):
def get_claim_groups(self, badge):
"""Build a list of all known claim group IDs for a badge"""
qs = (self.filter(badge=badge)
.values('claim_group').distinct().all()
.annotate(modified=Max('modified'), count=Count('id')))
return [x
for x in qs
if x['claim_group']]
def generate(self, badge, user=None, amount=10, reusable=False):
"""Generate a number of deferred awards for a badge"""
claim_group = '%s-%s' % (time(), random.randint(0, 10000))
for i in range(0, amount):
(DeferredAward(badge=badge, creator=user, reusable=reusable,
claim_group=claim_group).save())
return claim_group
def claim_by_email(self, awardee):
"""Claim all deferred awards that match the awardee's email"""
return self._claim_qs(awardee, self.filter(email=awardee.email))
def claim_by_code(self, awardee, code):
"""Claim a deferred award by code for the awardee"""
return self._claim_qs(awardee, self.filter(claim_code=code))
def _claim_qs(self, awardee, qs):
"""Claim all the deferred awards that match the queryset"""
for da in qs:
da.claim(awardee)
def make_random_code():
"""Generare a random code, using a set of alphanumeric characters that
attempts to avoid ambiguously similar shapes."""
s = '3479acefhjkmnprtuvwxy'
return ''.join([random.choice(s) for x in range(CLAIM_CODE_LENGTH)])
class DeferredAwardGrantNotAllowedException(BadgerException):
"""Attempt to grant a DeferredAward not allowed"""
@_document_django_model
class DeferredAward(models.Model):
"""Deferred award, can be converted into into a real award."""
objects = DeferredAwardManager()