Serotonin Storm

source>elsewhere>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
from datetime import datetime

from django import forms
from django.db import models
from django.core.cache import cache
from django.contrib import admin
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse

GOOGLE_PROFILE_URL = 'http://www.google.com/s2/favicons?domain_url=%s'
SN_CACHE_KEY = 'elsewhere_sn_data'
IM_CACHE_KEY = 'elsewhere_im_data'


class Network(models.Model):
    """ Model for storing networks. """

    name = models.CharField(max_length=100)
    url = models.URLField(verify_exists=False)
    identifier = models.CharField(max_length=100)
    icon = models.CharField(max_length=100, blank=True)

    class Meta:
        abstract = True

    def __unicode__(self):
        return self.name

class SocialNetwork(Network):
    class Meta:
        verbose_name_plural = 'social networks'

    def save(self, *args, **kwargs):
        cache.delete(SN_CACHE_KEY)
        super(SocialNetwork, self).save(*args, **kwargs)

class InstantMessenger(Network):
    class Meta:
        verbose_name_plural = 'instant messanger networks'

    def save(self, *args, **kwargs):
        cache.delete(IM_CACHE_KEY)
        super(InstantMessenger, self).save(*args, **kwargs)

# the following makes the social / IM networks data act as lists.

def SocialNetworkData():
    cache_key = SN_CACHE_KEY
    data = cache.get(cache_key)

    if not data:
        data = []

        try:
            for network in SocialNetwork.objects.all():
                data.append({
                    'id': slugify(network.name),
                    'name': network.name,
                    'url': network.url,
                    'identifier': network.identifier,
                    'icon': network.icon
                })
            cache.set(cache_key, data, 60*60*24)
        except:
            # if we haven't yet synced the database, don't worry about this yet
            pass

    return data

def InstantMessengerData():
    cache_key = IM_CACHE_KEY
    data = cache.get(cache_key)

    if not data:
        data = []
        try:
            for network in InstantMessenger.objects.all():
                data.append({
                    'id': slugify(network.name),
                    'name': network.name,
                    'url': network.url,
                    'icon': network.icon
                })
            cache.set(cache_key, data, 60*60*24)
        except:
            # if we haven't yet synced the database, don't worry about this yet
            pass

    return data

class ProfileManager:
    """ Handle raw data for lists of profiles."""
    data = {}

    def _get_choices(self):
        """ List of choices for profile select fields. """
        return [(props['id'], props['name']) for props in self.data]
    choices = property(_get_choices)

class SocialNetworkManager(ProfileManager):
    data = SocialNetworkData()
sn_manager = SocialNetworkManager()

class InstantMessengerManager(ProfileManager):
    data = InstantMessengerData()
im_manager = InstantMessengerManager()

class Profile(models.Model):
    """ Common profile model pieces. """
    data_manager = None

    date_added = models.DateTimeField(_('date added'), auto_now_add=True)
    date_verified = models.DateTimeField(_('date verified'), default=datetime.now)
    is_verified = models.BooleanField(default=False)

    class Meta:
        abstract = True

    def _get_data_item(self):
        # Find profile data for this profile id
        for network in self.data_manager.data:
            if network['id'] == self.network_id:
                return network
        return None
    data_item = property(_get_data_item)

    def _get_name(self):
        # Profile display name
        return self.data_item['name']
    name = property(_get_name)
 
    def _get_url(self):
        # Profile URL with username
        return self.data_item['url'] % self.username
    url = property(_get_url)
    
    def _get_icon_name(self):
        # Icon name
        return self.data_item['icon']
    icon_name = property(_get_icon_name)
 
    def _get_icon(self):
        # Icon URL or link to Google icon service
        if self.icon_name:
            print reverse('elsewhere_img', args=[self.icon_name])
            print self.icon_name
            return reverse('elsewhere_img', args=[self.icon_name])
        return GOOGLE_PROFILE_URL % self.url
    icon = property(_get_icon)

class SocialNetworkProfile(Profile):
    data_manager = sn_manager

    user = models.ForeignKey(User, db_index=True, related_name='social_network_profiles')
    network_id = models.CharField(max_length=16, choices=data_manager.choices, db_index=True)
    username = models.CharField(max_length=64)
    
    def __unicode__(self):
        return self.network_id

class SocialNetworkForm(forms.ModelForm):

    class Meta:
        model = SocialNetworkProfile
        fields = ('network_id', 'username')


class InstantMessengerProfile(Profile):
    data_manager = im_manager

    user = models.ForeignKey(User, db_index=True, related_name='instant_messenger_profiles')
    network_id = models.CharField(max_length=16, choices=data_manager.choices, db_index=True)
    username = models.CharField(max_length=64)

    def __unicode__(self):
        return self.username

class InstantMessengerForm(forms.ModelForm):

    class Meta:
        model = InstantMessengerProfile
        fields = ('network_id', 'username')


class WebsiteProfile(models.Model):
    user = models.ForeignKey(User, db_index=True, related_name='website_profiles')
    name = models.CharField(max_length=64)
    url = models.URLField(verify_exists=True)

    def __unicode__(self):
        return self.url

    def _get_icon(self):
        # No known icons! Just return the Google service URL.
        return GOOGLE_PROFILE_URL % self.url
    icon = property(_get_icon)


class WebsiteForm(forms.ModelForm):

    class Meta:
        model = WebsiteProfile
        fields = ('name', 'url')