Permalink
Browse files

Initial checkin.

  • Loading branch information...
0 parents commit bdc7eb02e6dca553588de25584cf23ed6099e72b @alex alex committed Jan 26, 2010
Showing with 78 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. 0 LICENSE
  3. 0 README
  4. 0 brabeion/__init__.py
  5. +66 −0 brabeion/badges.py
  6. +11 −0 brabeion/models.py
  7. 0 setup.py
1 .gitignore
@@ -0,0 +1 @@
+*.py[co]
0 LICENSE
No changes.
0 README
No changes.
0 brabeion/__init__.py
No changes.
66 brabeion/badges.py
@@ -0,0 +1,66 @@
+from collections import defaultdict
+
+from brabeion.models import BadgeAward
+
+
+class BadgeCache(object):
+ """
+ This is responsible for storing all badges that have been registered, as
+ well as providing the pulic API for awarding badges.
+
+ This class should not be instantiated multiple times, if you do it's your
+ fault when things break, and you get to pick up all the pieces.
+ """
+ def __init__(self):
+ self._event_registry = defaultdict(list)
+ self._registry = {}
+
+ def register(self, badge):
+ # We should probably duck-type this, but for now it's a decent sanity
+ # check.
+ assert issubclass(badge, Badge)
+ badge = Badge()
+ self._registry[badge.name] = name
+ for event in badge.events:
+ self._event_registry[event].append(badge)
+
+ def possibly_award_badge(event, **state):
+ for badge in self._registry[event]:
+ badge.possibly_award(**state)
+
+
+class BadgeAwarded(object):
+ def __init__(self, level=None):
+ self.level = level
+
+class BadgeDetail(object):
+ def __init__(self, name=None, description=None):
+ self.name = name
+ self.description = description
+
+
+class Badge(object):
+ def __init__(self):
+ assert not (self.multiple and len(self.levels) > 1)
+
+ def possibly_award(self, **state):
+ assert "user" in state
+ if (not self.multiple and
+ BadgeAward.objects.filter(user=state["user"]).exists()):
+ # if the user has this badge, and they can't get it more than once
+ # bail early
+ return
+ if self.async:
+ raise NotImplementedError("I haven't implemented async Badge's yet")
+
+ awarded = self.award(**state)
+ if awarded is None:
+ return
+ if awarded.level is None:
+ assert len(self.levels) == 1
+ awarded.level = 1
+ # awarded levels are 1 indexed, for conveineince
+ awarded = awarded.level - 1
+ assert awarded < len(self.levels)
+ BadgeAward.objects.create(user=state["user"], codename=self.name,
+ level=awarded)
11 brabeion/models.py
@@ -0,0 +1,11 @@
+from datetime import datetime
+
+from django.contrib.auth.models import User
+from django.db import models
+
+
+class BadgeAwarded(models.Model):
+ user = models.ForeignKey(User, related_name="badges_earned")
+ awarded_at = models.DateTimeField(default=datetime.now)
+ codename = models.CharField(max_length=255)
+ level = models.IntegerField()
0 setup.py
No changes.

0 comments on commit bdc7eb0

Please sign in to comment.