Add a license preference field
[mediagoblin.git] / mediagoblin / db / 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 """
18 TODO: indexes on foreignkeys, where useful.
19 """
20
21 import logging
22 import datetime
23 import sys
24
25 from sqlalchemy import Column, Integer, Unicode, UnicodeText, DateTime, \
26 Boolean, ForeignKey, UniqueConstraint, PrimaryKeyConstraint, \
27 SmallInteger
28 from sqlalchemy.orm import relationship, backref
29 from sqlalchemy.orm.collections import attribute_mapped_collection
30 from sqlalchemy.sql.expression import desc
31 from sqlalchemy.ext.associationproxy import association_proxy
32 from sqlalchemy.util import memoized_property
33
34 from mediagoblin.db.extratypes import PathTupleWithSlashes, JSONEncoded
35 from mediagoblin.db.base import Base, DictReadAttrProxy, Session
36 from mediagoblin.db.mixin import UserMixin, MediaEntryMixin, MediaCommentMixin, CollectionMixin, CollectionItemMixin
37 from mediagoblin.tools.files import delete_media_files
38
39 # It's actually kind of annoying how sqlalchemy-migrate does this, if
40 # I understand it right, but whatever. Anyway, don't remove this :P
41 #
42 # We could do migration calls more manually instead of relying on
43 # this import-based meddling...
44 from migrate import changeset
45
46 _log = logging.getLogger(__name__)
47
48
49 class User(Base, UserMixin):
50 """
51 TODO: We should consider moving some rarely used fields
52 into some sort of "shadow" table.
53 """
54 __tablename__ = "core__users"
55
56 id = Column(Integer, primary_key=True)
57 username = Column(Unicode, nullable=False, unique=True)
58 email = Column(Unicode, nullable=False)
59 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
60 pw_hash = Column(Unicode, nullable=False)
61 email_verified = Column(Boolean, default=False)
62 status = Column(Unicode, default=u"needs_email_verification", nullable=False)
63 # Intented to be nullable=False, but migrations would not work for it
64 # set to nullable=True implicitly.
65 wants_comment_notification = Column(Boolean, default=True)
66 license_preference = Column(Unicode)
67 verification_key = Column(Unicode)
68 is_admin = Column(Boolean, default=False, nullable=False)
69 url = Column(Unicode)
70 bio = Column(UnicodeText) # ??
71 fp_verification_key = Column(Unicode)
72 fp_token_expire = Column(DateTime)
73
74 ## TODO
75 # plugin data would be in a separate model
76
77 def __repr__(self):
78 return '<{0} #{1} {2} {3} "{4}">'.format(
79 self.__class__.__name__,
80 self.id,
81 'verified' if self.email_verified else 'non-verified',
82 'admin' if self.is_admin else 'user',
83 self.username)
84
85 def delete(self, **kwargs):
86 """Deletes a User and all related entries/comments/files/..."""
87 # Delete this user's Collections and all contained CollectionItems
88 for collection in self.collections:
89 collection.delete(commit=False)
90
91 media_entries = MediaEntry.query.filter(MediaEntry.uploader == self.id)
92 for media in media_entries:
93 # TODO: Make sure that "MediaEntry.delete()" also deletes
94 # all related files/Comments
95 media.delete(del_orphan_tags=False, commit=False)
96
97 # Delete now unused tags
98 # TODO: import here due to cyclic imports!!! This cries for refactoring
99 from mediagoblin.db.util import clean_orphan_tags
100 clean_orphan_tags(commit=False)
101
102 # Delete user, pass through commit=False/True in kwargs
103 super(User, self).delete(**kwargs)
104 _log.info('Deleted user "{0}" account'.format(self.username))
105
106
107 class MediaEntry(Base, MediaEntryMixin):
108 """
109 TODO: Consider fetching the media_files using join
110 """
111 __tablename__ = "core__media_entries"
112
113 id = Column(Integer, primary_key=True)
114 uploader = Column(Integer, ForeignKey(User.id), nullable=False, index=True)
115 title = Column(Unicode, nullable=False)
116 slug = Column(Unicode)
117 created = Column(DateTime, nullable=False, default=datetime.datetime.now,
118 index=True)
119 description = Column(UnicodeText) # ??
120 media_type = Column(Unicode, nullable=False)
121 state = Column(Unicode, default=u'unprocessed', nullable=False)
122 # or use sqlalchemy.types.Enum?
123 license = Column(Unicode)
124 collected = Column(Integer, default=0)
125
126 fail_error = Column(Unicode)
127 fail_metadata = Column(JSONEncoded)
128
129 transcoding_progress = Column(SmallInteger)
130
131 queued_media_file = Column(PathTupleWithSlashes)
132
133 queued_task_id = Column(Unicode)
134
135 __table_args__ = (
136 UniqueConstraint('uploader', 'slug'),
137 {})
138
139 get_uploader = relationship(User)
140
141 media_files_helper = relationship("MediaFile",
142 collection_class=attribute_mapped_collection("name"),
143 cascade="all, delete-orphan"
144 )
145 media_files = association_proxy('media_files_helper', 'file_path',
146 creator=lambda k, v: MediaFile(name=k, file_path=v)
147 )
148
149 attachment_files_helper = relationship("MediaAttachmentFile",
150 order_by="MediaAttachmentFile.created"
151 )
152 attachment_files = association_proxy("attachment_files_helper", "dict_view",
153 creator=lambda v: MediaAttachmentFile(
154 name=v["name"], filepath=v["filepath"])
155 )
156
157 tags_helper = relationship("MediaTag",
158 cascade="all, delete-orphan" # should be automatically deleted
159 )
160 tags = association_proxy("tags_helper", "dict_view",
161 creator=lambda v: MediaTag(name=v["name"], slug=v["slug"])
162 )
163
164 collections_helper = relationship("CollectionItem",
165 cascade="all, delete-orphan"
166 )
167 collections = association_proxy("collections_helper", "in_collection")
168
169 ## TODO
170 # media_data
171 # fail_error
172
173 def get_comments(self, ascending=False):
174 order_col = MediaComment.created
175 if not ascending:
176 order_col = desc(order_col)
177 return MediaComment.query.filter_by(
178 media_entry=self.id).order_by(order_col)
179
180 def url_to_prev(self, urlgen):
181 """get the next 'newer' entry by this user"""
182 media = MediaEntry.query.filter(
183 (MediaEntry.uploader == self.uploader)
184 & (MediaEntry.state == u'processed')
185 & (MediaEntry.id > self.id)).order_by(MediaEntry.id).first()
186
187 if media is not None:
188 return media.url_for_self(urlgen)
189
190 def url_to_next(self, urlgen):
191 """get the next 'older' entry by this user"""
192 media = MediaEntry.query.filter(
193 (MediaEntry.uploader == self.uploader)
194 & (MediaEntry.state == u'processed')
195 & (MediaEntry.id < self.id)).order_by(desc(MediaEntry.id)).first()
196
197 if media is not None:
198 return media.url_for_self(urlgen)
199
200 #@memoized_property
201 @property
202 def media_data(self):
203 session = Session()
204
205 return session.query(self.media_data_table).filter_by(
206 media_entry=self.id).first()
207
208 def media_data_init(self, **kwargs):
209 """
210 Initialize or update the contents of a media entry's media_data row
211 """
212 session = Session()
213
214 media_data = session.query(self.media_data_table).filter_by(
215 media_entry=self.id).first()
216
217 # No media data, so actually add a new one
218 if media_data is None:
219 media_data = self.media_data_table(
220 media_entry=self.id,
221 **kwargs)
222 session.add(media_data)
223 # Update old media data
224 else:
225 for field, value in kwargs.iteritems():
226 setattr(media_data, field, value)
227
228 @memoized_property
229 def media_data_table(self):
230 # TODO: memoize this
231 models_module = self.media_type + '.models'
232 __import__(models_module)
233 return sys.modules[models_module].DATA_MODEL
234
235 def __repr__(self):
236 safe_title = self.title.encode('ascii', 'replace')
237
238 return '<{classname} {id}: {title}>'.format(
239 classname=self.__class__.__name__,
240 id=self.id,
241 title=safe_title)
242
243 def delete(self, del_orphan_tags=True, **kwargs):
244 """Delete MediaEntry and all related files/attachments/comments
245
246 This will *not* automatically delete unused collections, which
247 can remain empty...
248
249 :param del_orphan_tags: True/false if we delete unused Tags too
250 :param commit: True/False if this should end the db transaction"""
251 # User's CollectionItems are automatically deleted via "cascade".
252 # Delete all the associated comments
253 for comment in self.get_comments():
254 comment.delete(commit=False)
255
256 # Delete all related files/attachments
257 try:
258 delete_media_files(self)
259 except OSError, error:
260 # Returns list of files we failed to delete
261 _log.error('No such files from the user "{1}" to delete: '
262 '{0}'.format(str(error), self.get_uploader))
263 _log.info('Deleted Media entry id "{0}"'.format(self.id))
264 # Related MediaTag's are automatically cleaned, but we might
265 # want to clean out unused Tag's too.
266 if del_orphan_tags:
267 # TODO: Import here due to cyclic imports!!!
268 # This cries for refactoring
269 from mediagoblin.db.util import clean_orphan_tags
270 clean_orphan_tags(commit=False)
271 # pass through commit=False/True in kwargs
272 super(MediaEntry, self).delete(**kwargs)
273
274
275 class FileKeynames(Base):
276 """
277 keywords for various places.
278 currently the MediaFile keys
279 """
280 __tablename__ = "core__file_keynames"
281 id = Column(Integer, primary_key=True)
282 name = Column(Unicode, unique=True)
283
284 def __repr__(self):
285 return "<FileKeyname %r: %r>" % (self.id, self.name)
286
287 @classmethod
288 def find_or_new(cls, name):
289 t = cls.query.filter_by(name=name).first()
290 if t is not None:
291 return t
292 return cls(name=name)
293
294
295 class MediaFile(Base):
296 """
297 TODO: Highly consider moving "name" into a new table.
298 TODO: Consider preloading said table in software
299 """
300 __tablename__ = "core__mediafiles"
301
302 media_entry = Column(
303 Integer, ForeignKey(MediaEntry.id),
304 nullable=False)
305 name_id = Column(SmallInteger, ForeignKey(FileKeynames.id), nullable=False)
306 file_path = Column(PathTupleWithSlashes)
307
308 __table_args__ = (
309 PrimaryKeyConstraint('media_entry', 'name_id'),
310 {})
311
312 def __repr__(self):
313 return "<MediaFile %s: %r>" % (self.name, self.file_path)
314
315 name_helper = relationship(FileKeynames, lazy="joined", innerjoin=True)
316 name = association_proxy('name_helper', 'name',
317 creator=FileKeynames.find_or_new
318 )
319
320
321 class MediaAttachmentFile(Base):
322 __tablename__ = "core__attachment_files"
323
324 id = Column(Integer, primary_key=True)
325 media_entry = Column(
326 Integer, ForeignKey(MediaEntry.id),
327 nullable=False)
328 name = Column(Unicode, nullable=False)
329 filepath = Column(PathTupleWithSlashes)
330 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
331
332 @property
333 def dict_view(self):
334 """A dict like view on this object"""
335 return DictReadAttrProxy(self)
336
337
338 class Tag(Base):
339 __tablename__ = "core__tags"
340
341 id = Column(Integer, primary_key=True)
342 slug = Column(Unicode, nullable=False, unique=True)
343
344 def __repr__(self):
345 return "<Tag %r: %r>" % (self.id, self.slug)
346
347 @classmethod
348 def find_or_new(cls, slug):
349 t = cls.query.filter_by(slug=slug).first()
350 if t is not None:
351 return t
352 return cls(slug=slug)
353
354
355 class MediaTag(Base):
356 __tablename__ = "core__media_tags"
357
358 id = Column(Integer, primary_key=True)
359 media_entry = Column(
360 Integer, ForeignKey(MediaEntry.id),
361 nullable=False, index=True)
362 tag = Column(Integer, ForeignKey(Tag.id), nullable=False, index=True)
363 name = Column(Unicode)
364 # created = Column(DateTime, nullable=False, default=datetime.datetime.now)
365
366 __table_args__ = (
367 UniqueConstraint('tag', 'media_entry'),
368 {})
369
370 tag_helper = relationship(Tag)
371 slug = association_proxy('tag_helper', 'slug',
372 creator=Tag.find_or_new
373 )
374
375 def __init__(self, name=None, slug=None):
376 Base.__init__(self)
377 if name is not None:
378 self.name = name
379 if slug is not None:
380 self.tag_helper = Tag.find_or_new(slug)
381
382 @property
383 def dict_view(self):
384 """A dict like view on this object"""
385 return DictReadAttrProxy(self)
386
387
388 class MediaComment(Base, MediaCommentMixin):
389 __tablename__ = "core__media_comments"
390
391 id = Column(Integer, primary_key=True)
392 media_entry = Column(
393 Integer, ForeignKey(MediaEntry.id), nullable=False, index=True)
394 author = Column(Integer, ForeignKey(User.id), nullable=False)
395 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
396 content = Column(UnicodeText, nullable=False)
397
398 get_author = relationship(User)
399
400
401 class Collection(Base, CollectionMixin):
402 """An 'album' or 'set' of media by a user.
403
404 On deletion, contained CollectionItems get automatically reaped via
405 SQL cascade"""
406 __tablename__ = "core__collections"
407
408 id = Column(Integer, primary_key=True)
409 title = Column(Unicode, nullable=False)
410 slug = Column(Unicode)
411 created = Column(DateTime, nullable=False, default=datetime.datetime.now,
412 index=True)
413 description = Column(UnicodeText)
414 creator = Column(Integer, ForeignKey(User.id), nullable=False)
415 # TODO: No of items in Collection. Badly named, can we migrate to num_items?
416 items = Column(Integer, default=0)
417
418 get_creator = relationship(User, backref="collections")
419
420 def get_collection_items(self, ascending=False):
421 #TODO, is this still needed with self.collection_items being available?
422 order_col = CollectionItem.position
423 if not ascending:
424 order_col = desc(order_col)
425 return CollectionItem.query.filter_by(
426 collection=self.id).order_by(order_col)
427
428
429 class CollectionItem(Base, CollectionItemMixin):
430 __tablename__ = "core__collection_items"
431
432 id = Column(Integer, primary_key=True)
433 media_entry = Column(
434 Integer, ForeignKey(MediaEntry.id), nullable=False, index=True)
435 collection = Column(Integer, ForeignKey(Collection.id), nullable=False)
436 note = Column(UnicodeText, nullable=True)
437 added = Column(DateTime, nullable=False, default=datetime.datetime.now)
438 position = Column(Integer)
439 in_collection = relationship("Collection",
440 backref=backref(
441 "collection_items",
442 cascade="all, delete-orphan"))
443
444 get_media_entry = relationship(MediaEntry)
445
446 __table_args__ = (
447 UniqueConstraint('collection', 'media_entry'),
448 {})
449
450 @property
451 def dict_view(self):
452 """A dict like view on this object"""
453 return DictReadAttrProxy(self)
454
455
456 class ProcessingMetaData(Base):
457 __tablename__ = 'core__processing_metadata'
458
459 id = Column(Integer, primary_key=True)
460 media_entry_id = Column(Integer, ForeignKey(MediaEntry.id), nullable=False,
461 index=True)
462 media_entry = relationship(MediaEntry,
463 backref=backref('processing_metadata',
464 cascade='all, delete-orphan'))
465 callback_url = Column(Unicode)
466
467 @property
468 def dict_view(self):
469 """A dict like view on this object"""
470 return DictReadAttrProxy(self)
471
472
473 MODELS = [
474 User, MediaEntry, Tag, MediaTag, MediaComment, Collection, CollectionItem, MediaFile, FileKeynames,
475 MediaAttachmentFile, ProcessingMetaData]
476
477
478 ######################################################
479 # Special, migrations-tracking table
480 #
481 # Not listed in MODELS because this is special and not
482 # really migrated, but used for migrations (for now)
483 ######################################################
484
485 class MigrationData(Base):
486 __tablename__ = "core__migrations"
487
488 name = Column(Unicode, primary_key=True)
489 version = Column(Integer, nullable=False, default=0)
490
491 ######################################################
492
493
494 def show_table_init(engine_uri):
495 if engine_uri is None:
496 engine_uri = 'sqlite:///:memory:'
497 from sqlalchemy import create_engine
498 engine = create_engine(engine_uri, echo=True)
499
500 Base.metadata.create_all(engine)
501
502
503 if __name__ == '__main__':
504 from sys import argv
505 print repr(argv)
506 if len(argv) == 2:
507 uri = argv[1]
508 else:
509 uri = None
510 show_table_init(uri)