Merge branch 'master' of github.com:FinalsClub/karmaworld
[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 a url ending in slug
75             return u"/{0}/{1}/{2}".format(self.course.school.slug, self.course.slug, self.slug)
76         else:
77             # return a url ending in id
78             return u"/{0}/{1}/{2}".format(self.course.school.slug, self.course.slug, self.id)
79
80
81 class DriveAuth(models.Model):
82     """ stored google drive authentication and refresh token
83         used for interacting with google drive """
84
85     email = models.EmailField(default=GOOGLE_USER)
86     credentials = models.TextField() # JSON of Oauth2Credential object
87     stored_at = models.DateTimeField(auto_now=True)
88
89
90     @staticmethod
91     def get(email=GOOGLE_USER):
92         """ Staticmethod for getting the singleton DriveAuth object """
93         # FIXME: this is untested
94         return DriveAuth.objects.filter(email=email).reverse()[0]
95
96
97     def store(self, creds):
98         """ Transform an existing credentials object to a db serialized """
99         self.email = creds.id_token['email']
100         self.credentials = creds.to_json()
101         self.save()
102
103
104     def transform_to_cred(self):
105         """ take stored credentials and produce a Credentials object """
106         return Credentials.new_from_json(self.credentials)
107
108
109     def __unicode__(self):
110         return u'Gdrive auth for %s created/updated at %s' % \
111                     (self.email, self.stored_at)