Drop pre-rendered html: User.bio_html
[mediagoblin.git] / mediagoblin / db / mongo / models.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import datetime
18
19 from mongokit import Document
20
21 from mediagoblin import mg_globals
22 from mediagoblin.db.mongo import migrations
23 from mediagoblin.db.mongo.util import ASCENDING, DESCENDING, ObjectId
24 from mediagoblin.tools.pagination import Pagination
25 from mediagoblin.tools import url
26 from mediagoblin.db.mixin import UserMixin, MediaEntryMixin
27
28 ###################
29 # Custom validators
30 ###################
31
32 ########
33 # Models
34 ########
35
36
37 class User(Document, UserMixin):
38 """
39 A user of MediaGoblin.
40
41 Structure:
42 - username: The username of this user, should be unique to this instance.
43 - email: Email address of this user
44 - created: When the user was created
45 - plugin_data: a mapping of extra plugin information for this User.
46 Nothing uses this yet as we don't have plugins, but someday we
47 might... :)
48 - pw_hash: Hashed version of user's password.
49 - email_verified: Whether or not the user has verified their email or not.
50 Most parts of the site are disabled for users who haven't yet.
51 - status: whether or not the user is active, etc. Currently only has two
52 values, 'needs_email_verification' or 'active'. (In the future, maybe
53 we'll change this to a boolean with a key of 'active' and have a
54 separate field for a reason the user's been disabled if that's
55 appropriate... email_verified is already separate, after all.)
56 - verification_key: If the user is awaiting email verification, the user
57 will have to provide this key (which will be encoded in the presented
58 URL) in order to confirm their email as active.
59 - is_admin: Whether or not this user is an administrator or not.
60 - url: this user's personal webpage/website, if appropriate.
61 - bio: biography of this user (plaintext, in markdown)
62 """
63 __collection__ = 'users'
64 use_dot_notation = True
65
66 structure = {
67 'username': unicode,
68 'email': unicode,
69 'created': datetime.datetime,
70 'plugin_data': dict, # plugins can dump stuff here.
71 'pw_hash': unicode,
72 'email_verified': bool,
73 'status': unicode,
74 'verification_key': unicode,
75 'is_admin': bool,
76 'url': unicode,
77 'bio': unicode, # May contain markdown
78 'fp_verification_key': unicode, # forgotten password verification key
79 'fp_token_expire': datetime.datetime,
80 }
81
82 required_fields = ['username', 'created', 'pw_hash', 'email']
83
84 default_values = {
85 'created': datetime.datetime.utcnow,
86 'email_verified': False,
87 'status': u'needs_email_verification',
88 'is_admin': False}
89
90
91 class MediaEntry(Document, MediaEntryMixin):
92 """
93 Record of a piece of media.
94
95 Structure:
96 - uploader: A reference to a User who uploaded this.
97
98 - title: Title of this work
99
100 - slug: A normalized "slug" which can be used as part of a URL to retrieve
101 this work, such as 'my-works-name-in-slug-form' may be viewable by
102 'http://mg.example.org/u/username/m/my-works-name-in-slug-form/'
103 Note that since URLs are constructed this way, slugs must be unique
104 per-uploader. (An index is provided to enforce that but code should be
105 written on the python side to ensure this as well.)
106
107 - created: Date and time of when this piece of work was uploaded.
108
109 - description: Uploader-set description of this work. This can be marked
110 up with MarkDown for slight fanciness (links, boldness, italics,
111 paragraphs...)
112
113 - description_html: Rendered version of the description, run through
114 Markdown and cleaned with our cleaning tool.
115
116 - media_type: What type of media is this? Currently we only support
117 'image' ;)
118
119 - media_data: Extra information that's media-format-dependent.
120 For example, images might contain some EXIF data that's not appropriate
121 to other formats. You might store it like:
122
123 mediaentry.media_data['exif'] = {
124 'manufacturer': 'CASIO',
125 'model': 'QV-4000',
126 'exposure_time': .659}
127
128 Alternately for video you might store:
129
130 # play length in seconds
131 mediaentry.media_data['play_length'] = 340
132
133 ... so what's appropriate here really depends on the media type.
134
135 - plugin_data: a mapping of extra plugin information for this User.
136 Nothing uses this yet as we don't have plugins, but someday we
137 might... :)
138
139 - tags: A list of tags. Each tag is stored as a dictionary that has a key
140 for the actual name and the normalized name-as-slug, so ultimately this
141 looks like:
142 [{'name': 'Gully Gardens',
143 'slug': 'gully-gardens'},
144 {'name': 'Castle Adventure Time?!",
145 'slug': 'castle-adventure-time'}]
146
147 - state: What's the state of this file? Active, inactive, disabled, etc...
148 But really for now there are only two states:
149 "unprocessed": uploaded but needs to go through processing for display
150 "processed": processed and able to be displayed
151
152 - license: URI for media's license.
153
154 - queued_media_file: storage interface style filepath describing a file
155 queued for processing. This is stored in the mg_globals.queue_store
156 storage system.
157
158 - queued_task_id: celery task id. Use this to fetch the task state.
159
160 - media_files: Files relevant to this that have actually been processed
161 and are available for various types of display. Stored like:
162 {'thumb': ['dir1', 'dir2', 'pic.png'}
163
164 - attachment_files: A list of "attachment" files, ones that aren't
165 critical to this piece of media but may be usefully relevant to people
166 viewing the work. (currently unused.)
167
168 - fail_error: path to the exception raised
169 - fail_metadata:
170 """
171 __collection__ = 'media_entries'
172 use_dot_notation = True
173
174 structure = {
175 'uploader': ObjectId,
176 'title': unicode,
177 'slug': unicode,
178 'created': datetime.datetime,
179 'description': unicode, # May contain markdown/up
180 'description_html': unicode, # May contain plaintext, or HTML
181 'media_type': unicode,
182 'media_data': dict, # extra data relevant to this media_type
183 'plugin_data': dict, # plugins can dump stuff here.
184 'tags': [dict],
185 'state': unicode,
186 'license': unicode,
187
188 # For now let's assume there can only be one main file queued
189 # at a time
190 'queued_media_file': [unicode],
191 'queued_task_id': unicode,
192
193 # A dictionary of logical names to filepaths
194 'media_files': dict,
195
196 # The following should be lists of lists, in appropriate file
197 # record form
198 'attachment_files': list,
199
200 # If things go badly in processing things, we'll store that
201 # data here
202 'fail_error': unicode,
203 'fail_metadata': dict}
204
205 required_fields = [
206 'uploader', 'created', 'media_type', 'slug']
207
208 default_values = {
209 'created': datetime.datetime.utcnow,
210 'state': u'unprocessed'}
211
212 def get_comments(self, ascending=False):
213 if ascending:
214 order = ASCENDING
215 else:
216 order = DESCENDING
217
218 return self.db.MediaComment.find({
219 'media_entry': self._id}).sort('created', order)
220
221 def generate_slug(self):
222 self.slug = url.slugify(self.title)
223
224 duplicate = mg_globals.database.media_entries.find_one(
225 {'slug': self.slug})
226
227 if duplicate:
228 self.slug = "%s-%s" % (self._id, self.slug)
229
230 def url_to_prev(self, urlgen):
231 """
232 Provide a url to the previous entry from this user, if there is one
233 """
234 cursor = self.db.MediaEntry.find({'_id': {"$gt": self._id},
235 'uploader': self.uploader,
236 'state': 'processed'}).sort(
237 '_id', ASCENDING).limit(1)
238 for media in cursor:
239 return media.url_for_self(urlgen)
240
241 def url_to_next(self, urlgen):
242 """
243 Provide a url to the next entry from this user, if there is one
244 """
245 cursor = self.db.MediaEntry.find({'_id': {"$lt": self._id},
246 'uploader': self.uploader,
247 'state': 'processed'}).sort(
248 '_id', DESCENDING).limit(1)
249
250 for media in cursor:
251 return media.url_for_self(urlgen)
252
253 @property
254 def get_uploader(self):
255 return self.db.User.find_one({'_id': self.uploader})
256
257
258 class MediaComment(Document):
259 """
260 A comment on a MediaEntry.
261
262 Structure:
263 - media_entry: The media entry this comment is attached to
264 - author: user who posted this comment
265 - created: when the comment was created
266 - content: plaintext (but markdown'able) version of the comment's content.
267 - content_html: the actual html-rendered version of the comment displayed.
268 Run through Markdown and the HTML cleaner.
269 """
270
271 __collection__ = 'media_comments'
272 use_dot_notation = True
273
274 structure = {
275 'media_entry': ObjectId,
276 'author': ObjectId,
277 'created': datetime.datetime,
278 'content': unicode,
279 'content_html': unicode}
280
281 required_fields = [
282 'media_entry', 'author', 'created', 'content']
283
284 default_values = {
285 'created': datetime.datetime.utcnow}
286
287 def media_entry(self):
288 return self.db.MediaEntry.find_one({'_id': self['media_entry']})
289
290 @property
291 def get_author(self):
292 return self.db.User.find_one({'_id': self['author']})
293
294
295 REGISTER_MODELS = [
296 MediaEntry,
297 User,
298 MediaComment]
299
300
301 def register_models(connection):
302 """
303 Register all models in REGISTER_MODELS with this connection.
304 """
305 connection.register(REGISTER_MODELS)