Merge remote-tracking branch 'aleksej/632_config_spec_comment_typo'
[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 cascade="all, delete-orphan",
149 order_by="MediaAttachmentFile.created"
150 )
151 attachment_files = association_proxy("attachment_files_helper", "dict_view",
152 creator=lambda v: MediaAttachmentFile(
153 name=v["name"], filepath=v["filepath"])
154 )
155
156 tags_helper = relationship("MediaTag",
157 cascade="all, delete-orphan" # should be automatically deleted
158 )
159 tags = association_proxy("tags_helper", "dict_view",
160 creator=lambda v: MediaTag(name=v["name"], slug=v["slug"])
161 )
162
163 collections_helper = relationship("CollectionItem",
164 cascade="all, delete-orphan"
165 )
166 collections = association_proxy("collections_helper", "in_collection")
167
168 ## TODO
169 # fail_error
170
171 def get_comments(self, ascending=False):
172 order_col = MediaComment.created
173 if not ascending:
174 order_col = desc(order_col)
175 return MediaComment.query.filter_by(
176 media_entry=self.id).order_by(order_col)
177
178 def url_to_prev(self, urlgen):
179 """get the next 'newer' entry by this user"""
180 media = MediaEntry.query.filter(
181 (MediaEntry.uploader == self.uploader)
182 & (MediaEntry.state == u'processed')
183 & (MediaEntry.id > self.id)).order_by(MediaEntry.id).first()
184
185 if media is not None:
186 return media.url_for_self(urlgen)
187
188 def url_to_next(self, urlgen):
189 """get the next 'older' entry by this user"""
190 media = MediaEntry.query.filter(
191 (MediaEntry.uploader == self.uploader)
192 & (MediaEntry.state == u'processed')
193 & (MediaEntry.id < self.id)).order_by(desc(MediaEntry.id)).first()
194
195 if media is not None:
196 return media.url_for_self(urlgen)
197
198 @property
199 def media_data(self):
200 return getattr(self, self.media_data_ref)
201
202 def media_data_init(self, **kwargs):
203 """
204 Initialize or update the contents of a media entry's media_data row
205 """
206 media_data = self.media_data
207
208 if media_data is None:
209 # Get the correct table:
210 table = import_component(self.media_type + '.models:DATA_MODEL')
211 # No media data, so actually add a new one
212 media_data = table(**kwargs)
213 # Get the relationship set up.
214 media_data.get_media_entry = self
215 else:
216 # Update old media data
217 for field, value in kwargs.iteritems():
218 setattr(media_data, field, value)
219
220 @memoized_property
221 def media_data_ref(self):
222 return import_component(self.media_type + '.models:BACKREF_NAME')
223
224 def __repr__(self):
225 safe_title = self.title.encode('ascii', 'replace')
226
227 return '<{classname} {id}: {title}>'.format(
228 classname=self.__class__.__name__,
229 id=self.id,
230 title=safe_title)
231
232 def delete(self, del_orphan_tags=True, **kwargs):
233 """Delete MediaEntry and all related files/attachments/comments
234
235 This will *not* automatically delete unused collections, which
236 can remain empty...
237
238 :param del_orphan_tags: True/false if we delete unused Tags too
239 :param commit: True/False if this should end the db transaction"""
240 # User's CollectionItems are automatically deleted via "cascade".
241 # Delete all the associated comments
242 for comment in self.get_comments():
243 comment.delete(commit=False)
244
245 # Delete all related files/attachments
246 try:
247 delete_media_files(self)
248 except OSError, error:
249 # Returns list of files we failed to delete
250 _log.error('No such files from the user "{1}" to delete: '
251 '{0}'.format(str(error), self.get_uploader))
252 _log.info('Deleted Media entry id "{0}"'.format(self.id))
253 # Related MediaTag's are automatically cleaned, but we might
254 # want to clean out unused Tag's too.
255 if del_orphan_tags:
256 # TODO: Import here due to cyclic imports!!!
257 # This cries for refactoring
258 from mediagoblin.db.util import clean_orphan_tags
259 clean_orphan_tags(commit=False)
260 # pass through commit=False/True in kwargs
261 super(MediaEntry, self).delete(**kwargs)
262
263
264 class FileKeynames(Base):
265 """
266 keywords for various places.
267 currently the MediaFile keys
268 """
269 __tablename__ = "core__file_keynames"
270 id = Column(Integer, primary_key=True)
271 name = Column(Unicode, unique=True)
272
273 def __repr__(self):
274 return "<FileKeyname %r: %r>" % (self.id, self.name)
275
276 @classmethod
277 def find_or_new(cls, name):
278 t = cls.query.filter_by(name=name).first()
279 if t is not None:
280 return t
281 return cls(name=name)
282
283
284 class MediaFile(Base):
285 """
286 TODO: Highly consider moving "name" into a new table.
287 TODO: Consider preloading said table in software
288 """
289 __tablename__ = "core__mediafiles"
290
291 media_entry = Column(
292 Integer, ForeignKey(MediaEntry.id),
293 nullable=False)
294 name_id = Column(SmallInteger, ForeignKey(FileKeynames.id), nullable=False)
295 file_path = Column(PathTupleWithSlashes)
296
297 __table_args__ = (
298 PrimaryKeyConstraint('media_entry', 'name_id'),
299 {})
300
301 def __repr__(self):
302 return "<MediaFile %s: %r>" % (self.name, self.file_path)
303
304 name_helper = relationship(FileKeynames, lazy="joined", innerjoin=True)
305 name = association_proxy('name_helper', 'name',
306 creator=FileKeynames.find_or_new
307 )
308
309
310 class MediaAttachmentFile(Base):
311 __tablename__ = "core__attachment_files"
312
313 id = Column(Integer, primary_key=True)
314 media_entry = Column(
315 Integer, ForeignKey(MediaEntry.id),
316 nullable=False)
317 name = Column(Unicode, nullable=False)
318 filepath = Column(PathTupleWithSlashes)
319 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
320
321 @property
322 def dict_view(self):
323 """A dict like view on this object"""
324 return DictReadAttrProxy(self)
325
326
327 class Tag(Base):
328 __tablename__ = "core__tags"
329
330 id = Column(Integer, primary_key=True)
331 slug = Column(Unicode, nullable=False, unique=True)
332
333 def __repr__(self):
334 return "<Tag %r: %r>" % (self.id, self.slug)
335
336 @classmethod
337 def find_or_new(cls, slug):
338 t = cls.query.filter_by(slug=slug).first()
339 if t is not None:
340 return t
341 return cls(slug=slug)
342
343
344 class MediaTag(Base):
345 __tablename__ = "core__media_tags"
346
347 id = Column(Integer, primary_key=True)
348 media_entry = Column(
349 Integer, ForeignKey(MediaEntry.id),
350 nullable=False, index=True)
351 tag = Column(Integer, ForeignKey(Tag.id), nullable=False, index=True)
352 name = Column(Unicode)
353 # created = Column(DateTime, nullable=False, default=datetime.datetime.now)
354
355 __table_args__ = (
356 UniqueConstraint('tag', 'media_entry'),
357 {})
358
359 tag_helper = relationship(Tag)
360 slug = association_proxy('tag_helper', 'slug',
361 creator=Tag.find_or_new
362 )
363
364 def __init__(self, name=None, slug=None):
365 Base.__init__(self)
366 if name is not None:
367 self.name = name
368 if slug is not None:
369 self.tag_helper = Tag.find_or_new(slug)
370
371 @property
372 def dict_view(self):
373 """A dict like view on this object"""
374 return DictReadAttrProxy(self)
375
376
377 class MediaComment(Base, MediaCommentMixin):
378 __tablename__ = "core__media_comments"
379
380 id = Column(Integer, primary_key=True)
381 media_entry = Column(
382 Integer, ForeignKey(MediaEntry.id), nullable=False, index=True)
383 author = Column(Integer, ForeignKey(User.id), nullable=False)
384 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
385 content = Column(UnicodeText, nullable=False)
386
387 # Cascade: Comments are owned by their creator. So do the full thing.
388 # lazy=dynamic: People might post a *lot* of comments, so make
389 # the "posted_comments" a query-like thing.
390 get_author = relationship(User,
391 backref=backref("posted_comments",
392 lazy="dynamic",
393 cascade="all, delete-orphan"))
394
395
396 class Collection(Base, CollectionMixin):
397 """An 'album' or 'set' of media by a user.
398
399 On deletion, contained CollectionItems get automatically reaped via
400 SQL cascade"""
401 __tablename__ = "core__collections"
402
403 id = Column(Integer, primary_key=True)
404 title = Column(Unicode, nullable=False)
405 slug = Column(Unicode)
406 created = Column(DateTime, nullable=False, default=datetime.datetime.now,
407 index=True)
408 description = Column(UnicodeText)
409 creator = Column(Integer, ForeignKey(User.id), nullable=False)
410 # TODO: No of items in Collection. Badly named, can we migrate to num_items?
411 items = Column(Integer, default=0)
412
413 # Cascade: Collections are owned by their creator. So do the full thing.
414 get_creator = relationship(User,
415 backref=backref("collections",
416 cascade="all, delete-orphan"))
417
418 def get_collection_items(self, ascending=False):
419 #TODO, is this still needed with self.collection_items being available?
420 order_col = CollectionItem.position
421 if not ascending:
422 order_col = desc(order_col)
423 return CollectionItem.query.filter_by(
424 collection=self.id).order_by(order_col)
425
426
427 class CollectionItem(Base, CollectionItemMixin):
428 __tablename__ = "core__collection_items"
429
430 id = Column(Integer, primary_key=True)
431 media_entry = Column(
432 Integer, ForeignKey(MediaEntry.id), nullable=False, index=True)
433 collection = Column(Integer, ForeignKey(Collection.id), nullable=False)
434 note = Column(UnicodeText, nullable=True)
435 added = Column(DateTime, nullable=False, default=datetime.datetime.now)
436 position = Column(Integer)
437
438 # Cascade: CollectionItems are owned by their Collection. So do the full thing.
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)