2 from string import lower
4 from django.core.exceptions import MultipleObjectsReturned
5 from django.db.models.signals import post_save
7 from forum.models import Badge, Node, Action
8 from forum.actions import AwardAction
12 installed = dict([(b.cls, b) for b in Badge.objects.all()])
14 class BadgesMeta(type):
18 def __new__(mcs, name, bases, dic):
19 badge = type.__new__(mcs, name, bases, dic)
21 if not dic.get('abstract', False):
22 if not name in installed:
23 badge.ondb = Badge(cls=name, type=dic.get('type', Badge.BRONZE))
26 badge.ondb = installed[name]
30 def hook(action, new):
31 user = inst.award_to(action)
34 badge.award(user, action, badge.award_once)
36 for action in badge.listen_to:
39 BadgesMeta.by_class[name] = badge
40 badge.ondb.__dict__['_class'] = inst
41 BadgesMeta.by_id[badge.ondb.id] = badge
45 class AbstractBadge(object):
46 __metaclass__ = BadgesMeta
53 raise NotImplementedError
56 def description(self):
57 raise NotImplementedError
60 def award(cls, user, action, once=False):
64 awarded = AwardAction.get_for(user, cls.ondb)
67 awarded = AwardAction.get_for(user, cls.ondb, node)
69 trigger = isinstance(action, Action) and action or None
72 AwardAction(user=user, node=node).save(data=dict(badge=cls.ondb, trigger=trigger))
73 except MultipleObjectsReturned:
75 logging.error('Found multiple %s badges awarded for user %s (%s)' % (self.name, user.username, user.id))
77 logging.error('Found multiple %s badges awarded for user %s (%s) and node %s' % (self.name, user.username, user.id, node.id))