bgneal@51: """
bgneal@51: Models for the email_list application.
bgneal@51: 
bgneal@51: """
bgneal@51: import base64
bgneal@51: import datetime
bgneal@51: import hashlib
bgneal@51: 
bgneal@51: from django.db import models
bgneal@51: from django.conf import settings
bgneal@51: 
bgneal@51: 
bgneal@51: class Subscriber(models.Model):
bgneal@51:     status_codes = [('P', 'Pending'), ('A', 'Active'), ('L', 'Leaving')]
bgneal@51:     key_length = 28
bgneal@51: 
bgneal@51:     name = models.CharField(max_length=64, blank=True)
bgneal@51:     email = models.EmailField(db_index=True)
bgneal@51:     location = models.CharField(max_length=64, blank=True)
bgneal@51:     status = models.CharField(max_length=1, choices=status_codes, default='A')
bgneal@51:     key = models.CharField(max_length=key_length, editable=False, blank=True,
bgneal@51:             db_index=True)
bgneal@51:     status_date = models.DateTimeField(editable=False)
bgneal@51: 
bgneal@51:     class Meta:
bgneal@51:         ordering = ['name', 'email']
bgneal@51: 
bgneal@51:     def __unicode__(self):
bgneal@51:         if self.name:
bgneal@51:             return u'%s <%s>' % (self.name, self.email)
bgneal@51:         return self.email
bgneal@51: 
bgneal@51:     def save(self, *args, **kwargs):
bgneal@51:         if not self.pk and not self.status_date:
bgneal@51:             self.status_date = datetime.datetime.now()
bgneal@51: 
bgneal@51:         super(Subscriber, self).save(*args, **kwargs)
bgneal@51: 
bgneal@51:     def set_pending(self):
bgneal@51:         self.status = 'P'
bgneal@51:         self.status_date = datetime.datetime.now()
bgneal@51:         self.gen_key()
bgneal@51: 
bgneal@51:     def set_active(self):
bgneal@51:         self.status = 'A'
bgneal@51:         self.status_date = datetime.datetime.now()
bgneal@51:         self.key = ''
bgneal@51: 
bgneal@51:     def set_leaving(self):
bgneal@51:         self.status = 'L'
bgneal@51:         self.status_date = datetime.datetime.now()
bgneal@51:         self.gen_key()
bgneal@51: 
bgneal@51:     def is_pending(self):
bgneal@51:         return self.status == 'P'
bgneal@51: 
bgneal@51:     def is_leaving(self):
bgneal@51:         return self.status == 'L'
bgneal@51: 
bgneal@51:     def is_active(self):
bgneal@51:         return self.status == 'A'
bgneal@51: 
bgneal@51:     def gen_key(self):
bgneal@51:         source = (settings.SECRET_KEY + self.email + self.name + self.location +
bgneal@51:                 self.status + self.status_date.isoformat())
bgneal@51: 
bgneal@51:         sha = hashlib.sha1()
bgneal@51:         sha.update(source)
bgneal@51:         self.key = base64.urlsafe_b64encode(sha.digest())