Commits

Dan Carroll committed 1cfadf8

Add Provider model to activitysync. Add migrations to create Provider data from existing activities.

Comments (0)

Files changed (8)

mysite/activitysync/admin.py

 # Activity admin page
-from activitysync.models import Activity
+from activitysync.models import Provider, Activity
 from django.contrib import admin
 
+admin.site.register(Provider)
+
 class ActivityAdmin(admin.ModelAdmin):
-    list_display = ('source', 'title', 'published', 'link', 'pub_date')
-    list_filter = ['pub_date', 'source', 'username', 'published']
+    list_display = ('title', 'provider', 'published', 'link', 'pub_date')
+    list_filter = ['pub_date', 'provider', 'username', 'published']
     search_fields = ['title', 'comments']
     date_hierarchy = 'pub_date'
 

mysite/activitysync/management/commands/updatetest.py

 from django.conf import settings
 from django.core import exceptions
-from django.core.management.base import NoArgsCommand
+from django.core.management.base import BaseCommand, CommandError
 from django.core.management.color import no_style
 from django.core.mail import mail_admins
 from optparse import make_option
 import os
 import sys
 import time
-import socket
 import datetime
 import feedparser
 import twitter
 
-class Command(NoArgsCommand):
+class Command(BaseCommand):
+    option_list = BaseCommand.option_list + (
+        make_option('--send-result', '-s', default=False, action='store_true', dest='sendmail',
+            help='Send email with new activities to site admins'),
+        make_option('--dry-run', '-d', default=False, action='store_true', dest='dryrun',
+            help='Gather activities, but do not create items in database'),
+    )
     help = "Update activities by depositing them into the blog database."
 
-    def handle_noargs(self, **options): 
+    def handle(self, *args, **options): 
         self.style = no_style()
-        
+        if len(args) != 0:
+            raise CommandError("Command does not accept any arguments")
+
+        send_email = options.get('sendmail')
+        dry_run = options.get('dryrun')
+
         email_status_info = []
         items_added = False
         try:
                         print "Created item: %s (%s)" % (activity_item.title, activity_item.link)
                         email_status_info.append("Created item: %s (%s)\n" % (activity_item.title, activity_item.link))
                         items_added = True
-
-                        #Activity.objects.create(title=activity_item.title, link=activity_item.link, source=provider_instance.sourceid(), username=activity_item.username, author=activity_item.author, comments=activity_item.comments, pub_date=activity_item.pub_date, published=activity_item.published, guid=activity_item.guid)
+                        
+                        if dry_run:
+                            print 'Dry run, not creating item'
+                            #Activity.objects.create(title=activity_item.title, link=activity_item.link, source=provider_instance.sourceid(), username=activity_item.username, author=activity_item.author, comments=activity_item.comments, pub_date=activity_item.pub_date, published=activity_item.published, guid=activity_item.guid)
 
         except:
             ### DEBUGGING CODE
                         mailBody = mailBody.encode('utf-8') + itemString.encode('utf-8')
                     except UnicodeDecodeError:
                         mailBody = mailBody + "\n\nFAILED TO PARSE ACTIVITY\n\n"
-                ### DISABLED TEMPORARILY FOR DEBUGGING
-                #mail_admins('Update Activities command completed', mailBody, fail_silently=False)
-                #print 'Mail sent to admins'
-                ### END DISABLE
+                if send_email:
+                    mail_admins('Update Activities command completed', mailBody, fail_silently=False)
+                    print 'Mail sent to admins'
+

mysite/activitysync/managers.py

 from django.db.models import Manager
 import datetime
 
-class PublishedManager(Manager):
-    """Returns published posts that are not in the future."""
+class ActivityManager(Manager):
+    def get_query_set(self):
+        return super(ActivityManager, self).get_query_set().select_related('provider')
    
     def published(self):
+        """Returns published posts that are not in the future."""
         return self.get_query_set().filter(published=True, pub_date__lte=datetime.datetime.now())
 

mysite/activitysync/migrations/0002_auto__add_provider__add_field_activity_provider.py

+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        
+        # Adding model 'Provider'
+        db.create_table('activitysync_provider', (
+            ('name', self.gf('django.db.models.fields.CharField')(max_length=50)),
+            ('prefix', self.gf('django.db.models.fields.CharField')(max_length=50)),
+            ('link', self.gf('django.db.models.fields.URLField')(max_length=500)),
+            ('sourceid', self.gf('django.db.models.fields.CharField')(unique=True, max_length=20, primary_key=True, db_index=True)),
+        ))
+        db.send_create_signal('activitysync', ['Provider'])
+
+        # Adding field 'Activity.provider'
+        db.add_column('activitysync_activity', 'provider', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['activitysync.Provider'], null=True), keep_default=False)
+
+
+    def backwards(self, orm):
+        
+        # Deleting model 'Provider'
+        db.delete_table('activitysync_provider')
+
+        # Deleting field 'Activity.provider'
+        db.delete_column('activitysync_activity', 'provider_id')
+
+
+    models = {
+        'activitysync.activity': {
+            'Meta': {'ordering': "('-pub_date',)", 'object_name': 'Activity'},
+            'author': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
+            'comments': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
+            'guid': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'link': ('django.db.models.fields.URLField', [], {'max_length': '500'}),
+            'provider': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['activitysync.Provider']", 'null': 'True'}),
+            'pub_date': ('django.db.models.fields.DateTimeField', [], {}),
+            'published': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'source': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
+            'username': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'})
+        },
+        'activitysync.provider': {
+            'Meta': {'ordering': "('name',)", 'object_name': 'Provider'},
+            'link': ('django.db.models.fields.URLField', [], {'max_length': '500'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
+            'prefix': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
+            'sourceid': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20', 'primary_key': 'True', 'db_index': 'True'})
+        }
+    }
+
+    complete_apps = ['activitysync']

mysite/activitysync/migrations/0003_convert_to_provider_objects.py

+# encoding: utf-8
+import datetime
+from south.db import db
+from south.v2 import DataMigration
+from django.db import models
+
+class Migration(DataMigration):
+
+    def forwards(self, orm):
+        for activity in orm.Activity.objects.all():
+            print "Activity: %s" % activity.title
+            provider = self.get_or_create_provider(orm, activity)
+            print "   - Has provider: %s" % provider.name
+            activity.provider = provider
+            activity.save()
+
+    def backwards(self, orm):
+        for activity in orm.Activity.objects.all():
+            provider = activity.provider
+            print 'Activity: %s' % activity.title
+            print '   - Has source: %s' % self.sourceid_to_sourcechoice(provider)
+            activity.source = self.sourceid_to_sourcechoice(provider)
+            activity.save()   
+
+    def get_or_create_provider(self, orm, activity):
+        sourceid = self.get_provider_sourceid(activity)
+
+        try:
+            provider = orm.Provider.objects.get(sourceid=sourceid)
+            return provider
+        except orm.Provider.DoesNotExist:
+            name = self.get_provider_name(activity)
+            prefix = self.get_activity_prefix(activity)
+            link = self.get_network_link(activity)
+
+            provider = orm.Provider.objects.create(name=name, prefix=prefix, link=link, sourceid=sourceid)
+            return provider
+
+    def get_provider_sourceid(self, activity):
+        if activity.source == 'T':
+            return u"twitter"
+        elif activity.source == 'DL':
+            return u"delicious"
+        elif activity.source == 'FB':
+            return u"facebook"
+        elif activity.source == 'HU':
+            return u"hulu"
+        elif activity.source == 'RD':
+            return u"reddit"
+        elif activity.source == 'GR':
+            return u"googlereader"
+
+    def get_provider_name(self, activity):
+        if activity.source == 'T':
+            return u"Twitter"
+        elif activity.source == 'DL':
+            return u"Delicious"
+        elif activity.source == 'FB':
+            return u"Facebook"
+        elif activity.source == 'HU':
+            return u"Hulu"
+        elif activity.source == 'RD':
+            return u"Reddit"
+        elif activity.source == 'GR':
+            return u"Google Reader"
+ 
+    def get_activity_prefix(self, activity):
+        if activity.source == 'DL':
+            return u'Bookmarked '
+        elif activity.source == 'HU':
+            return u'Watched '
+        elif activity.source == 'RD':
+            return u'Liked '
+        elif activity.source == 'GR':
+            return u'Shared '
+        else:
+            return u''
+    
+    def get_network_link(self, activity):
+        if activity.source == 'T':
+            return u"http://twitter.com/erunama"
+        elif activity.source == 'DL':
+            return u"http://delicious.com/erunama"
+        elif activity.source == 'FB':
+            return u"http://www.facebook.com/people/Dan-Carroll/401024"
+        elif activity.source == 'HU':
+            return u"http://www.hulu.com/profiles/erunama/"
+        elif activity.source == 'RD':
+            return u"http://www.reddit.com/user/erunama/"
+        elif activity.source == 'GR':
+            return u"http://www.google.com/reader/shared/dancarroll"
+
+# HELPER METHODS FOR BACKWARDS MIGRATION
+    def sourceid_to_sourcechoice(self, provider):
+        if provider.sourceid == 'twitter':
+            return u"T"
+        elif provider.sourceid == 'delicious':
+            return u"DL"
+        elif provider.sourceid == 'facebook':
+            return u"FB"
+        elif provider.sourceid == 'hulu':
+            return u"HU"
+        elif provider.sourceid == 'reddit':
+            return u"RD"
+        elif provider.sourceid == 'googlereader':
+            return u"GR"
+
+
+    models = {
+        'activitysync.activity': {
+            'Meta': {'ordering': "('-pub_date',)", 'object_name': 'Activity'},
+            'author': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
+            'comments': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
+            'guid': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'link': ('django.db.models.fields.URLField', [], {'max_length': '500'}),
+            'provider': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['activitysync.Provider']", 'null': 'True'}),
+            'pub_date': ('django.db.models.fields.DateTimeField', [], {}),
+            'published': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'source': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
+            'username': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'})
+        },
+        'activitysync.provider': {
+            'Meta': {'ordering': "('name',)", 'object_name': 'Provider'},
+            'link': ('django.db.models.fields.URLField', [], {'max_length': '500'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
+            'prefix': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
+            'sourceid': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20', 'primary_key': 'True', 'db_index': 'True'})
+        }
+    }
+
+    complete_apps = ['activitysync']

mysite/activitysync/models.py

 from django.db import models
-from activitysync.managers import PublishedManager
+from activitysync.managers import ActivityManager
 import datetime
 
+class Provider(models.Model):
+    """Provider represents a particular social network"""
+    name = models.CharField(max_length=50)
+    prefix = models.CharField(max_length=50, blank=True)
+    link = models.URLField(max_length=500)
+    sourceid = models.CharField(max_length=20, primary_key=True, unique=True, db_index=True)
+
+    class Meta:
+        verbose_name = 'provider'
+        verbose_name_plural = 'providers'
+        ordering = ('name',)
+    
+    def __unicode__(self):
+        return u'%s' % self.name
+
+
 class Activity(models.Model):
     """Activity from social network (Twitter, Flickr, etc)."""
     SOURCE_CHOICES = (
     pub_date = models.DateTimeField('Date published')
     published = models.BooleanField(default=True)
     guid = models.CharField(max_length=255, unique=True, db_index=True)
-    objects = PublishedManager()
+
+    provider = models.ForeignKey(Provider, null=True)
+
+    objects = ActivityManager()
     
     class Meta:
         verbose_name = 'activity'

mysite/templates/activity.html

             <div id="activity-list"><ul>
         {% endifchanged %}
         
-        <li><a href="{{ activity.get_network_link }}"><img src="{{ MEDIA_URL }}networks/{{ activity.get_source_display }}_16.png" alt="{{ activity.get_source_display }}" /></a>{{ activity.get_activity_prefix}} <a href="{{ activity.link }}">{{ activity.title }}</a>
+        <li><a href="{{ activity.provider.link }}"><img src="{{ MEDIA_URL }}networks/{{ activity.provider.sourceid }}_16.png" alt="{{ activity.provider.name }}" /></a>{{ activity.provider.prefix }} <a href="{{ activity.link }}">{{ activity.title }}</a>
         <span class="time">{{ activity.pub_date|timesince|upper }} AGO</span></li>
     
     {% endfor %}

mysite/templates/index.html

         <div id="activity-list">
             <ul>
             {% for activity in activities %}
-                <li><a href="{{ activity.get_network_link }}"><img src="{{ MEDIA_URL }}networks/{{ activity.get_source_display }}_16.png" alt="{{ activity.get_source_display }}" /></a>{{ activity.get_activity_prefix}} <a href="{{ activity.link }}">{{ activity.title }}</a>
+                <li><a href="{{ activity.provider.link }}"><img src="{{ MEDIA_URL }}networks/{{ activity.provider.sourceid }}_16.png" alt="{{ activity.provider.name }}" /></a>{{ activity.provider.prefix }} <a href="{{ activity.link }}">{{ activity.title }}</a>
                     <span class="time">{{ activity.pub_date|timesince|upper }} AGO</span></li>
             {% endfor %}
             </ul>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.