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