fixing note url generation when there is no slug set
[oweals/karmaworld.git] / karmaworld / apps / notes / models.py
1 #!/usr/bin/env python
2 # -*- coding:utf8 -*-
3 # Copyright (C) 2012  FinalsClub Foundation
4
5 """
6     Models for the notes django app.
7     Contains only the minimum for handling files and their representation
8 """
9 import datetime
10
11 from django.template import defaultfilters
12 from django.db import models
13 from taggit.managers import TaggableManager
14 from oauth2client.client import Credentials
15
16 from karmaworld.apps.courses.models import Course
17
18 class Note(models.Model):
19     """ A django model representing an uploaded file and associated metadata.
20     """
21     UNKNOWN_FILE = '???'
22     FILE_TYPE_CHOICES = (
23         ('doc', 'MS Word compatible file (.doc, .docx, .rtf, .odf)'),
24         ('img', 'Scan or picture of notes'),
25         ('pdf', 'PDF file'),
26         (UNKNOWN_FILE, 'Unknown file'),
27     )
28
29     course          = models.ForeignKey(Course)
30     # Tagging system
31     tags            = TaggableManager(blank=True)
32
33     name            = models.CharField(max_length=255, blank=True, null=True)
34     slug            = models.SlugField(null=True)
35     desc            = models.TextField(max_length=511, blank=True, null=True)
36     uploaded_at     = models.DateTimeField(null=True, default=datetime.datetime.utcnow)
37
38     file_type   = models.CharField(max_length=15, blank=True, null=True, choices=FILE_TYPE_CHOICES, default=UNKNOWN_FILE)
39     # Upload files to MEDIA_ROOT/notes/YEAR/MONTH/DAY, 2012/10/30/filename
40     note_file   = models.FileField(upload_to="notes/%Y/%m/%j/", blank=True, null=True)
41
42     ## post gdrive conversion data
43     embed_url   = models.URLField(max_length=1024, blank=True, null=True)
44     download_url = models.URLField(max_length=1024, blank=True, null=True)
45     # for word processor documents
46     html        = models.TextField(blank=True, null=True)
47     text        = models.TextField(blank=True, null=True)
48
49     # FIXME: Not Implemented
50     #uploader    = models.ForeignKey(User, blank=True, null=True, related_name='notes')
51     #course      = models.ForeignKey(Course, blank=True, null=True, related_name="files")
52     #school      = models.ForeignKey(School, blank=True, null=True)
53
54
55     def __unicode__(self):
56         return u"{0}: {1} -- {2}".format(self.file_type, self.name, self.uploaded_at)
57
58
59     def save(self, *args, **kwargs):
60         """ override built-in save to ensure contextual self.name """
61         # TODO: If self.name isn't set, generate one based on uploaded_name
62         # if we fail to set the Note.name earlier than this, use the saved filename
63
64         if not self.slug:
65             self.slug = defaultfilters.slugify(self.name)
66         super(Note, self).save(*args, **kwargs)
67
68
69     def get_absolute_url(self):
70         """ Resolve note url, use 'note' route and slug if slug
71             otherwise use note.id
72         """
73         if self.slug == None:
74             return u"/{0}/{1}/{2}".format(self.course.school.slug, self.course.slug, self.slug)
75         else:
76             return u"/{0}/{1}/{2}".format(self.course.school.slug, self.course.slug, self.id)
77
78
79 # FIXME: replace the following GOOGLE_USER in a settings.py
80 GOOGLE_USER = 'seth.woodworth@gmail.com'
81
82 class DriveAuth(models.Model):
83     """ stored google drive authentication and refresh token
84         used for interacting with google drive """
85
86     email = models.EmailField(default=GOOGLE_USER)
87     credentials = models.TextField() # JSON of Oauth2Credential object
88     stored_at = models.DateTimeField(auto_now=True)
89
90
91     @staticmethod
92     def get(email=GOOGLE_USER):
93         """ Staticmethod for getting the singleton DriveAuth object """
94         # FIXME: this is untested
95         return DriveAuth.objects.filter(email=email).reverse()[0]
96
97
98     def store(self, creds):
99         """ Transform an existing credentials object to a db serialized """
100         self.email = creds.id_token['email']
101         self.credentials = creds.to_json()
102         self.save()
103
104
105     def transform_to_cred(self):
106         """ take stored credentials and produce a Credentials object """
107         return Credentials.new_from_json(self.credentials)
108
109
110     def __unicode__(self):
111         return u'Gdrive auth for %s created/updated at %s' % \
112                     (self.email, self.stored_at)