making assorted changes for ppt file_type marking on the Note model
[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 lxml.html import fromstring, tostring
16 from oauth2client.client import Credentials
17 from taggit.managers import TaggableManager
18
19 from karmaworld.apps.courses.models import Course
20
21 try:
22     from secrets.drive import GOOGLE_USER
23 except:
24     GOOGLE_USER = u'admin@karmanotes.org'
25
26 fs = FileSystemStorage(location=settings.MEDIA_ROOT)
27
28 class Note(models.Model):
29     """ A django model representing an uploaded file and associated metadata.
30     """
31     UNKNOWN_FILE = '???'
32     FILE_TYPE_CHOICES = (
33         ('doc', 'MS Word compatible file (.doc, .docx, .rtf, .odf)'),
34         ('img', 'Scan or picture of notes'),
35         ('pdf', 'PDF file'),
36         ('ppt', 'Powerpoint'),
37         (UNKNOWN_FILE, 'Unknown file'),
38     )
39
40     course          = models.ForeignKey(Course)
41     # Tagging system
42     tags            = TaggableManager(blank=True)
43
44     name            = models.CharField(max_length=255, blank=True, null=True)
45     slug            = models.SlugField(max_length=255, null=True)
46     year            = models.IntegerField(blank=True, null=True, 
47                         default=datetime.datetime.utcnow().year)
48     desc            = models.TextField(max_length=511, blank=True, null=True)
49     uploaded_at     = models.DateTimeField(null=True, default=datetime.datetime.utcnow)
50
51     file_type       = models.CharField(max_length=15,
52                             choices=FILE_TYPE_CHOICES,
53                             default=UNKNOWN_FILE,
54                             blank=True, null=True)
55
56     # Upload files to MEDIA_ROOT/notes/YEAR/MONTH/DAY, 2012/10/30/filename
57     # FIXME: because we are adding files by hand in tasks.py, upload_to is being ignored for media files
58     note_file       = models.FileField(
59                             storage=fs,
60                             upload_to="notes/%Y/%m/%j/",
61                             blank=True, null=True)
62     pdf_file       = models.FileField(
63                             storage=fs,
64                             upload_to="notes/%Y/%m/%j/",
65                             blank=True, null=True)
66
67     ## post gdrive conversion data
68     embed_url       = models.URLField(max_length=1024, blank=True, null=True)
69     download_url    = models.URLField(max_length=1024, blank=True, null=True)
70     # for word processor documents
71     html            = models.TextField(blank=True, null=True)
72     text            = models.TextField(blank=True, null=True)
73
74
75     class Meta:
76         """ Sort files by most recent first """
77         ordering = ['-uploaded_at']
78
79
80     def __unicode__(self):
81         return u"{0}: {1} -- {2}".format(self.file_type, self.name, self.uploaded_at)
82
83     def save(self, *args, **kwargs):
84         """ override built-in save to ensure contextual self.name """
85         # TODO: If self.name isn't set, generate one based on uploaded_name
86         # if we fail to set the Note.name earlier than this, use the saved filename
87
88         # only generate a slug if the name has been set, and slug hasn't
89         if not self.slug and self.name:
90             slug = defaultfilters.slugify(self.name)
91             cursor = Note.objects.filter(slug=slug)
92             # If there are no other notes with this slug, then the slug does not need an id
93             if cursor.count() == 0:
94                 self.slug = slug
95             else:
96                 super(Note, self).save(*args, **kwargs) # generate self.id
97                 self.slug = defaultfilters.slugify("%s %s" % (self.name, self.id))
98             super(Note, self).save(*args, **kwargs)
99
100         # Check if Note.uploaded_at is after Course.updated_at
101         if self.uploaded_at and self.uploaded_at > self.course.updated_at:
102             self.course.updated_at = self.uploaded_at
103             # if it is, update Course.updated_at
104             self.course.save()
105
106         super(Note, self).save(*args, **kwargs)
107
108     def get_absolute_url(self):
109         """ Resolve note url, use 'note' route and slug if slug
110             otherwise use note.id
111         """
112         if self.slug is not None:
113             # return a url ending in slug
114             return u"/{0}/{1}/{2}".format(self.course.school.slug, self.course.slug, self.slug)
115         else:
116             # return a url ending in id
117             return u"/{0}/{1}/{2}".format(self.course.school.slug, self.course.slug, self.id)
118
119     def sanitize_html(self, save=True):
120         """ if self contains html, find all <a> tags and add target=_blank 
121             takes self
122             returns True/False on succ/fail and error or count
123         """
124         # build a tag sanitizer
125         def add_attribute_target(tag):
126             tag.attrib['target'] = '_blank'
127
128         # if no html, return false
129         if not self.html:
130             return False, "Note has no html"
131
132         _html = fromstring(self.html)
133         a_tags = _html.findall('.//a') # recursively find all a tags in document tree
134         # if there are a tags
135         if a_tags > 1:
136             #apply the add attribute function
137             map(add_attribute_target, a_tags)
138             self.html = _html
139             if save:
140                 self.save()
141             return True, len(a_tags)
142
143
144
145 class DriveAuth(models.Model):
146     """ stored google drive authentication and refresh token
147         used for interacting with google drive """
148
149     email = models.EmailField(default=GOOGLE_USER)
150     credentials = models.TextField() # JSON of Oauth2Credential object
151     stored_at = models.DateTimeField(auto_now=True)
152
153
154     @staticmethod
155     def get(email=GOOGLE_USER):
156         """ Staticmethod for getting the singleton DriveAuth object """
157         # FIXME: this is untested
158         return DriveAuth.objects.filter(email=email).reverse()[0]
159
160
161     def store(self, creds):
162         """ Transform an existing credentials object to a db serialized """
163         self.email = creds.id_token['email']
164         self.credentials = creds.to_json()
165         self.save()
166
167
168     def transform_to_cred(self):
169         """ take stored credentials and produce a Credentials object """
170         return Credentials.new_from_json(self.credentials)
171
172
173     def __unicode__(self):
174         return u'Gdrive auth for %s created/updated at %s' % \
175                     (self.email, self.stored_at)