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