1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
18 TODO: indexes on foreignkeys, where useful.
24 from sqlalchemy
import Column
, Integer
, Unicode
, UnicodeText
, DateTime
, \
25 Boolean
, ForeignKey
, UniqueConstraint
, PrimaryKeyConstraint
, \
27 from sqlalchemy
.orm
import relationship
, backref
, with_polymorphic
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
34 from mediagoblin
.db
.extratypes
import PathTupleWithSlashes
, JSONEncoded
35 from mediagoblin
.db
.base
import Base
, DictReadAttrProxy
36 from mediagoblin
.db
.mixin
import UserMixin
, MediaEntryMixin
, \
37 MediaCommentMixin
, CollectionMixin
, CollectionItemMixin
38 from mediagoblin
.tools
.files
import delete_media_files
39 from mediagoblin
.tools
.common
import import_component
41 # It's actually kind of annoying how sqlalchemy-migrate does this, if
42 # I understand it right, but whatever. Anyway, don't remove this :P
44 # We could do migration calls more manually instead of relying on
45 # this import-based meddling...
46 from migrate
import changeset
48 _log
= logging
.getLogger(__name__
)
51 class User(Base
, UserMixin
):
53 TODO: We should consider moving some rarely used fields
54 into some sort of "shadow" table.
56 __tablename__
= "core__users"
58 id = Column(Integer
, primary_key
=True)
59 username
= Column(Unicode
, nullable
=False, unique
=True)
60 # Note: no db uniqueness constraint on email because it's not
61 # reliable (many email systems case insensitive despite against
62 # the RFC) and because it would be a mess to implement at this
64 email
= Column(Unicode
, nullable
=False)
65 pw_hash
= Column(Unicode
, nullable
=False)
66 email_verified
= Column(Boolean
, default
=False)
67 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
68 status
= Column(Unicode
, default
=u
"needs_email_verification", nullable
=False)
69 # Intented to be nullable=False, but migrations would not work for it
70 # set to nullable=True implicitly.
71 wants_comment_notification
= Column(Boolean
, default
=True)
72 license_preference
= Column(Unicode
)
73 is_admin
= Column(Boolean
, default
=False, nullable
=False)
75 bio
= Column(UnicodeText
) # ??
78 # plugin data would be in a separate model
81 return '<{0} #{1} {2} {3} "{4}">'.format(
82 self
.__class
__.__name
__,
84 'verified' if self
.email_verified
else 'non-verified',
85 'admin' if self
.is_admin
else 'user',
88 def delete(self
, **kwargs
):
89 """Deletes a User and all related entries/comments/files/..."""
90 # Collections get deleted by relationships.
92 media_entries
= MediaEntry
.query
.filter(MediaEntry
.uploader
== self
.id)
93 for media
in media_entries
:
94 # TODO: Make sure that "MediaEntry.delete()" also deletes
95 # all related files/Comments
96 media
.delete(del_orphan_tags
=False, commit
=False)
98 # Delete now unused tags
99 # TODO: import here due to cyclic imports!!! This cries for refactoring
100 from mediagoblin
.db
.util
import clean_orphan_tags
101 clean_orphan_tags(commit
=False)
103 # Delete user, pass through commit=False/True in kwargs
104 super(User
, self
).delete(**kwargs
)
105 _log
.info('Deleted user "{0}" account'.format(self
.username
))
108 class MediaEntry(Base
, MediaEntryMixin
):
110 TODO: Consider fetching the media_files using join
112 __tablename__
= "core__media_entries"
114 id = Column(Integer
, primary_key
=True)
115 uploader
= Column(Integer
, ForeignKey(User
.id), nullable
=False, index
=True)
116 title
= Column(Unicode
, nullable
=False)
117 slug
= Column(Unicode
)
118 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
,
120 description
= Column(UnicodeText
) # ??
121 media_type
= Column(Unicode
, nullable
=False)
122 state
= Column(Unicode
, default
=u
'unprocessed', nullable
=False)
123 # or use sqlalchemy.types.Enum?
124 license
= Column(Unicode
)
125 collected
= Column(Integer
, default
=0)
127 fail_error
= Column(Unicode
)
128 fail_metadata
= Column(JSONEncoded
)
130 transcoding_progress
= Column(SmallInteger
)
132 queued_media_file
= Column(PathTupleWithSlashes
)
134 queued_task_id
= Column(Unicode
)
137 UniqueConstraint('uploader', 'slug'),
140 get_uploader
= relationship(User
)
142 media_files_helper
= relationship("MediaFile",
143 collection_class
=attribute_mapped_collection("name"),
144 cascade
="all, delete-orphan"
146 media_files
= association_proxy('media_files_helper', 'file_path',
147 creator
=lambda k
, v
: MediaFile(name
=k
, file_path
=v
)
150 attachment_files_helper
= relationship("MediaAttachmentFile",
151 cascade
="all, delete-orphan",
152 order_by
="MediaAttachmentFile.created"
154 attachment_files
= association_proxy("attachment_files_helper", "dict_view",
155 creator
=lambda v
: MediaAttachmentFile(
156 name
=v
["name"], filepath
=v
["filepath"])
159 tags_helper
= relationship("MediaTag",
160 cascade
="all, delete-orphan" # should be automatically deleted
162 tags
= association_proxy("tags_helper", "dict_view",
163 creator
=lambda v
: MediaTag(name
=v
["name"], slug
=v
["slug"])
166 collections_helper
= relationship("CollectionItem",
167 cascade
="all, delete-orphan"
169 collections
= association_proxy("collections_helper", "in_collection")
174 def get_comments(self
, ascending
=False):
175 order_col
= MediaComment
.created
177 order_col
= desc(order_col
)
178 return self
.all_comments
.order_by(order_col
)
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()
187 if media
is not None:
188 return media
.url_for_self(urlgen
)
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()
197 if media
is not None:
198 return media
.url_for_self(urlgen
)
201 def media_data(self
):
202 return getattr(self
, self
.media_data_ref
)
204 def media_data_init(self
, **kwargs
):
206 Initialize or update the contents of a media entry's media_data row
208 media_data
= self
.media_data
210 if media_data
is None:
211 # Get the correct table:
212 table
= import_component(self
.media_type
+ '.models:DATA_MODEL')
213 # No media data, so actually add a new one
214 media_data
= table(**kwargs
)
215 # Get the relationship set up.
216 media_data
.get_media_entry
= self
218 # Update old media data
219 for field
, value
in kwargs
.iteritems():
220 setattr(media_data
, field
, value
)
223 def media_data_ref(self
):
224 return import_component(self
.media_type
+ '.models:BACKREF_NAME')
227 safe_title
= self
.title
.encode('ascii', 'replace')
229 return '<{classname} {id}: {title}>'.format(
230 classname
=self
.__class
__.__name
__,
234 def delete(self
, del_orphan_tags
=True, **kwargs
):
235 """Delete MediaEntry and all related files/attachments/comments
237 This will *not* automatically delete unused collections, which
240 :param del_orphan_tags: True/false if we delete unused Tags too
241 :param commit: True/False if this should end the db transaction"""
242 # User's CollectionItems are automatically deleted via "cascade".
243 # Comments on this Media are deleted by cascade, hopefully.
245 # Delete all related files/attachments
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.
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
)
264 class FileKeynames(Base
):
266 keywords for various places.
267 currently the MediaFile keys
269 __tablename__
= "core__file_keynames"
270 id = Column(Integer
, primary_key
=True)
271 name
= Column(Unicode
, unique
=True)
274 return "<FileKeyname %r: %r>" % (self
.id, self
.name
)
277 def find_or_new(cls
, name
):
278 t
= cls
.query
.filter_by(name
=name
).first()
281 return cls(name
=name
)
284 class MediaFile(Base
):
286 TODO: Highly consider moving "name" into a new table.
287 TODO: Consider preloading said table in software
289 __tablename__
= "core__mediafiles"
291 media_entry
= Column(
292 Integer
, ForeignKey(MediaEntry
.id),
294 name_id
= Column(SmallInteger
, ForeignKey(FileKeynames
.id), nullable
=False)
295 file_path
= Column(PathTupleWithSlashes
)
298 PrimaryKeyConstraint('media_entry', 'name_id'),
302 return "<MediaFile %s: %r>" % (self
.name
, self
.file_path
)
304 name_helper
= relationship(FileKeynames
, lazy
="joined", innerjoin
=True)
305 name
= association_proxy('name_helper', 'name',
306 creator
=FileKeynames
.find_or_new
310 class MediaAttachmentFile(Base
):
311 __tablename__
= "core__attachment_files"
313 id = Column(Integer
, primary_key
=True)
314 media_entry
= Column(
315 Integer
, ForeignKey(MediaEntry
.id),
317 name
= Column(Unicode
, nullable
=False)
318 filepath
= Column(PathTupleWithSlashes
)
319 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
323 """A dict like view on this object"""
324 return DictReadAttrProxy(self
)
328 __tablename__
= "core__tags"
330 id = Column(Integer
, primary_key
=True)
331 slug
= Column(Unicode
, nullable
=False, unique
=True)
334 return "<Tag %r: %r>" % (self
.id, self
.slug
)
337 def find_or_new(cls
, slug
):
338 t
= cls
.query
.filter_by(slug
=slug
).first()
341 return cls(slug
=slug
)
344 class MediaTag(Base
):
345 __tablename__
= "core__media_tags"
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)
356 UniqueConstraint('tag', 'media_entry'),
359 tag_helper
= relationship(Tag
)
360 slug
= association_proxy('tag_helper', 'slug',
361 creator
=Tag
.find_or_new
364 def __init__(self
, name
=None, slug
=None):
369 self
.tag_helper
= Tag
.find_or_new(slug
)
373 """A dict like view on this object"""
374 return DictReadAttrProxy(self
)
377 class MediaComment(Base
, MediaCommentMixin
):
378 __tablename__
= "core__media_comments"
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)
387 # Cascade: Comments are owned by their creator. So do the full thing.
388 # lazy=dynamic: People might post a *lot* of comments,
389 # so make the "posted_comments" a query-like thing.
390 get_author
= relationship(User
,
391 backref
=backref("posted_comments",
393 cascade
="all, delete-orphan"))
394 get_entry
= relationship(MediaEntry
,
395 backref
=backref("comments",
397 cascade
="all, delete-orphan"))
399 # Cascade: Comments are somewhat owned by their MediaEntry.
400 # So do the full thing.
401 # lazy=dynamic: MediaEntries might have many comments,
402 # so make the "all_comments" a query-like thing.
403 get_media_entry
= relationship(MediaEntry
,
404 backref
=backref("all_comments",
406 cascade
="all, delete-orphan"))
409 class Collection(Base
, CollectionMixin
):
410 """An 'album' or 'set' of media by a user.
412 On deletion, contained CollectionItems get automatically reaped via
414 __tablename__
= "core__collections"
416 id = Column(Integer
, primary_key
=True)
417 title
= Column(Unicode
, nullable
=False)
418 slug
= Column(Unicode
)
419 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
,
421 description
= Column(UnicodeText
)
422 creator
= Column(Integer
, ForeignKey(User
.id), nullable
=False)
423 # TODO: No of items in Collection. Badly named, can we migrate to num_items?
424 items
= Column(Integer
, default
=0)
426 # Cascade: Collections are owned by their creator. So do the full thing.
427 get_creator
= relationship(User
,
428 backref
=backref("collections",
429 cascade
="all, delete-orphan"))
432 UniqueConstraint('creator', 'slug'),
435 def get_collection_items(self
, ascending
=False):
436 #TODO, is this still needed with self.collection_items being available?
437 order_col
= CollectionItem
.position
439 order_col
= desc(order_col
)
440 return CollectionItem
.query
.filter_by(
441 collection
=self
.id).order_by(order_col
)
444 class CollectionItem(Base
, CollectionItemMixin
):
445 __tablename__
= "core__collection_items"
447 id = Column(Integer
, primary_key
=True)
448 media_entry
= Column(
449 Integer
, ForeignKey(MediaEntry
.id), nullable
=False, index
=True)
450 collection
= Column(Integer
, ForeignKey(Collection
.id), nullable
=False)
451 note
= Column(UnicodeText
, nullable
=True)
452 added
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
453 position
= Column(Integer
)
455 # Cascade: CollectionItems are owned by their Collection. So do the full thing.
456 in_collection
= relationship(Collection
,
459 cascade
="all, delete-orphan"))
461 get_media_entry
= relationship(MediaEntry
)
464 UniqueConstraint('collection', 'media_entry'),
469 """A dict like view on this object"""
470 return DictReadAttrProxy(self
)
473 class ProcessingMetaData(Base
):
474 __tablename__
= 'core__processing_metadata'
476 id = Column(Integer
, primary_key
=True)
477 media_entry_id
= Column(Integer
, ForeignKey(MediaEntry
.id), nullable
=False,
479 media_entry
= relationship(MediaEntry
,
480 backref
=backref('processing_metadata',
481 cascade
='all, delete-orphan'))
482 callback_url
= Column(Unicode
)
486 """A dict like view on this object"""
487 return DictReadAttrProxy(self
)
490 class CommentSubscription(Base
):
491 __tablename__
= 'core__comment_subscriptions'
492 id = Column(Integer
, primary_key
=True)
494 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
496 media_entry_id
= Column(Integer
, ForeignKey(MediaEntry
.id), nullable
=False)
497 media_entry
= relationship(MediaEntry
,
498 backref
=backref('comment_subscriptions',
499 cascade
='all, delete-orphan'))
501 user_id
= Column(Integer
, ForeignKey(User
.id), nullable
=False)
502 user
= relationship(User
,
503 backref
=backref('comment_subscriptions',
504 cascade
='all, delete-orphan'))
506 notify
= Column(Boolean
, nullable
=False, default
=True)
507 send_email
= Column(Boolean
, nullable
=False, default
=True)
510 return ('<{classname} #{id}: {user} {media} notify: '
511 '{notify} email: {email}>').format(
513 classname
=self
.__class
__.__name
__,
515 media
=self
.media_entry
,
517 email
=self
.send_email
)
520 class Notification(Base
):
521 __tablename__
= 'core__notifications'
522 id = Column(Integer
, primary_key
=True)
523 type = Column(Unicode
)
525 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
527 user_id
= Column(Integer
, ForeignKey('core__users.id'), nullable
=False,
529 seen
= Column(Boolean
, default
=lambda: False, index
=True)
532 backref
=backref('notifications', cascade
='all, delete-orphan'))
535 'polymorphic_identity': 'notification',
536 'polymorphic_on': type
540 return '<{klass} #{id}: {user}: {subject} ({seen})>'.format(
542 klass
=self
.__class
__.__name
__,
544 subject
=getattr(self
, 'subject', None),
545 seen
='unseen' if not self
.seen
else 'seen')
548 class CommentNotification(Notification
):
549 __tablename__
= 'core__comment_notifications'
550 id = Column(Integer
, ForeignKey(Notification
.id), primary_key
=True)
552 subject_id
= Column(Integer
, ForeignKey(MediaComment
.id))
553 subject
= relationship(
555 backref
=backref('comment_notifications', cascade
='all, delete-orphan'))
558 'polymorphic_identity': 'comment_notification'
562 class ProcessingNotification(Notification
):
563 __tablename__
= 'core__processing_notifications'
565 id = Column(Integer
, ForeignKey(Notification
.id), primary_key
=True)
567 subject_id
= Column(Integer
, ForeignKey(MediaEntry
.id))
568 subject
= relationship(
570 backref
=backref('processing_notifications',
571 cascade
='all, delete-orphan'))
574 'polymorphic_identity': 'processing_notification'
580 [ProcessingNotification
, CommentNotification
])
583 User
, MediaEntry
, Tag
, MediaTag
, MediaComment
, Collection
, CollectionItem
,
584 MediaFile
, FileKeynames
, MediaAttachmentFile
, ProcessingMetaData
,
585 Notification
, CommentNotification
, ProcessingNotification
,
589 ######################################################
590 # Special, migrations-tracking table
592 # Not listed in MODELS because this is special and not
593 # really migrated, but used for migrations (for now)
594 ######################################################
596 class MigrationData(Base
):
597 __tablename__
= "core__migrations"
599 name
= Column(Unicode
, primary_key
=True)
600 version
= Column(Integer
, nullable
=False, default
=0)
602 ######################################################
605 def show_table_init(engine_uri
):
606 if engine_uri
is None:
607 engine_uri
= 'sqlite:///:memory:'
608 from sqlalchemy
import create_engine
609 engine
= create_engine(engine_uri
, echo
=True)
611 Base
.metadata
.create_all(engine
)
614 if __name__
== '__main__':