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