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.
25 from sqlalchemy
import (
26 Column
, Integer
, Unicode
, UnicodeText
, DateTime
, Boolean
, ForeignKey
,
27 UniqueConstraint
, PrimaryKeyConstraint
, SmallInteger
)
28 from sqlalchemy
.orm
import relationship
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
34 from mediagoblin
.db
.sql
.extratypes
import PathTupleWithSlashes
, JSONEncoded
35 from mediagoblin
.db
.sql
.base
import Base
, DictReadAttrProxy
36 from mediagoblin
.db
.mixin
import UserMixin
, MediaEntryMixin
, MediaCommentMixin
37 from mediagoblin
.db
.sql
.base
import Session
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
42 # We could do migration calls more manually instead of relying on
43 # this import-based meddling...
44 from migrate
import changeset
47 class SimpleFieldAlias(object):
48 """An alias for any field"""
49 def __init__(self
, fieldname
):
50 self
.fieldname
= fieldname
52 def __get__(self
, instance
, cls
):
53 return getattr(instance
, self
.fieldname
)
55 def __set__(self
, instance
, val
):
56 setattr(instance
, self
.fieldname
, val
)
59 class User(Base
, UserMixin
):
61 TODO: We should consider moving some rarely used fields
62 into some sort of "shadow" table.
64 __tablename__
= "core__users"
66 id = Column(Integer
, primary_key
=True)
67 username
= Column(Unicode
, nullable
=False, unique
=True)
68 email
= Column(Unicode
, nullable
=False)
69 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
70 pw_hash
= Column(Unicode
, nullable
=False)
71 email_verified
= Column(Boolean
, default
=False)
72 status
= Column(Unicode
, default
=u
"needs_email_verification", nullable
=False)
73 verification_key
= Column(Unicode
)
74 is_admin
= Column(Boolean
, default
=False, nullable
=False)
76 bio
= Column(UnicodeText
) # ??
77 fp_verification_key
= Column(Unicode
)
78 fp_token_expire
= Column(DateTime
)
81 # plugin data would be in a separate model
83 _id
= SimpleFieldAlias("id")
86 class MediaEntry(Base
, MediaEntryMixin
):
88 TODO: Consider fetching the media_files using join
90 __tablename__
= "core__media_entries"
92 id = Column(Integer
, primary_key
=True)
93 uploader
= Column(Integer
, ForeignKey(User
.id), nullable
=False, index
=True)
94 title
= Column(Unicode
, nullable
=False)
95 slug
= Column(Unicode
)
96 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
,
98 description
= Column(UnicodeText
) # ??
99 media_type
= Column(Unicode
, nullable
=False)
100 state
= Column(Unicode
, default
=u
'unprocessed', nullable
=False)
101 # or use sqlalchemy.types.Enum?
102 license
= Column(Unicode
)
104 fail_error
= Column(Unicode
)
105 fail_metadata
= Column(JSONEncoded
)
107 queued_media_file
= Column(PathTupleWithSlashes
)
109 queued_task_id
= Column(Unicode
)
112 UniqueConstraint('uploader', 'slug'),
115 get_uploader
= relationship(User
)
117 media_files_helper
= relationship("MediaFile",
118 collection_class
=attribute_mapped_collection("name"),
119 cascade
="all, delete-orphan"
121 media_files
= association_proxy('media_files_helper', 'file_path',
122 creator
=lambda k
, v
: MediaFile(name
=k
, file_path
=v
)
125 attachment_files_helper
= relationship("MediaAttachmentFile",
126 cascade
="all, delete-orphan",
127 order_by
="MediaAttachmentFile.created"
129 attachment_files
= association_proxy("attachment_files_helper", "dict_view",
130 creator
=lambda v
: MediaAttachmentFile(
131 name
=v
["name"], filepath
=v
["filepath"])
134 tags_helper
= relationship("MediaTag",
135 cascade
="all, delete-orphan"
137 tags
= association_proxy("tags_helper", "dict_view",
138 creator
=lambda v
: MediaTag(name
=v
["name"], slug
=v
["slug"])
145 _id
= SimpleFieldAlias("id")
147 def get_comments(self
, ascending
=False):
148 order_col
= MediaComment
.created
150 order_col
= desc(order_col
)
151 return MediaComment
.query
.filter_by(
152 media_entry
=self
.id).order_by(order_col
)
154 def url_to_prev(self
, urlgen
):
155 """get the next 'newer' entry by this user"""
156 media
= MediaEntry
.query
.filter(
157 (MediaEntry
.uploader
== self
.uploader
)
158 & (MediaEntry
.state
== 'processed')
159 & (MediaEntry
.id > self
.id)).order_by(MediaEntry
.id).first()
161 if media
is not None:
162 return media
.url_for_self(urlgen
)
164 def url_to_next(self
, urlgen
):
165 """get the next 'older' entry by this user"""
166 media
= MediaEntry
.query
.filter(
167 (MediaEntry
.uploader
== self
.uploader
)
168 & (MediaEntry
.state
== 'processed')
169 & (MediaEntry
.id < self
.id)).order_by(desc(MediaEntry
.id)).first()
171 if media
is not None:
172 return media
.url_for_self(urlgen
)
176 def media_data(self
):
179 return session
.query(self
.media_data_table
).filter_by(
180 media_entry
=self
.id).first()
182 def media_data_init(self
, **kwargs
):
184 Initialize or update the contents of a media entry's media_data row
188 media_data
= session
.query(self
.media_data_table
).filter_by(
189 media_entry
=self
.id).first()
191 # No media data, so actually add a new one
193 media_data
= self
.media_data_table(
195 session
.add(media_data
)
196 # Update old media data
198 for field
, value
in kwargs
.iteritems():
199 setattr(media_data
, field
, value
)
202 def media_data_table(self
):
204 models_module
= self
.media_type
+ '.models'
205 __import__(models_module
)
206 return sys
.modules
[models_module
].DATA_MODEL
209 class FileKeynames(Base
):
211 keywords for various places.
212 currently the MediaFile keys
214 __tablename__
= "core__file_keynames"
215 id = Column(Integer
, primary_key
=True)
216 name
= Column(Unicode
, unique
=True)
219 return "<FileKeyname %r: %r>" % (self
.id, self
.name
)
222 def find_or_new(cls
, name
):
223 t
= cls
.query
.filter_by(name
=name
).first()
226 return cls(name
=name
)
229 class MediaFile(Base
):
231 TODO: Highly consider moving "name" into a new table.
232 TODO: Consider preloading said table in software
234 __tablename__
= "core__mediafiles"
236 media_entry
= Column(
237 Integer
, ForeignKey(MediaEntry
.id),
239 name_id
= Column(SmallInteger
, ForeignKey(FileKeynames
.id), nullable
=False)
240 file_path
= Column(PathTupleWithSlashes
)
243 PrimaryKeyConstraint('media_entry', 'name_id'),
247 return "<MediaFile %s: %r>" % (self
.name
, self
.file_path
)
249 name_helper
= relationship(FileKeynames
, lazy
="joined", innerjoin
=True)
250 name
= association_proxy('name_helper', 'name',
251 creator
=FileKeynames
.find_or_new
255 class MediaAttachmentFile(Base
):
256 __tablename__
= "core__attachment_files"
258 id = Column(Integer
, primary_key
=True)
259 media_entry
= Column(
260 Integer
, ForeignKey(MediaEntry
.id),
262 name
= Column(Unicode
, nullable
=False)
263 filepath
= Column(PathTupleWithSlashes
)
264 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
268 """A dict like view on this object"""
269 return DictReadAttrProxy(self
)
273 __tablename__
= "core__tags"
275 id = Column(Integer
, primary_key
=True)
276 slug
= Column(Unicode
, nullable
=False, unique
=True)
279 return "<Tag %r: %r>" % (self
.id, self
.slug
)
282 def find_or_new(cls
, slug
):
283 t
= cls
.query
.filter_by(slug
=slug
).first()
286 return cls(slug
=slug
)
289 class MediaTag(Base
):
290 __tablename__
= "core__media_tags"
292 id = Column(Integer
, primary_key
=True)
293 media_entry
= Column(
294 Integer
, ForeignKey(MediaEntry
.id),
295 nullable
=False, index
=True)
296 tag
= Column(Integer
, ForeignKey(Tag
.id), nullable
=False, index
=True)
297 name
= Column(Unicode
)
298 # created = Column(DateTime, nullable=False, default=datetime.datetime.now)
301 UniqueConstraint('tag', 'media_entry'),
304 tag_helper
= relationship(Tag
)
305 slug
= association_proxy('tag_helper', 'slug',
306 creator
=Tag
.find_or_new
309 def __init__(self
, name
=None, slug
=None):
314 self
.tag_helper
= Tag
.find_or_new(slug
)
318 """A dict like view on this object"""
319 return DictReadAttrProxy(self
)
322 class MediaComment(Base
, MediaCommentMixin
):
323 __tablename__
= "core__media_comments"
325 id = Column(Integer
, primary_key
=True)
326 media_entry
= Column(
327 Integer
, ForeignKey(MediaEntry
.id), nullable
=False, index
=True)
328 author
= Column(Integer
, ForeignKey(User
.id), nullable
=False)
329 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
330 content
= Column(UnicodeText
, nullable
=False)
332 get_author
= relationship(User
)
334 _id
= SimpleFieldAlias("id")
338 User
, MediaEntry
, Tag
, MediaTag
, MediaComment
, MediaFile
, FileKeynames
,
342 ######################################################
343 # Special, migrations-tracking table
345 # Not listed in MODELS because this is special and not
346 # really migrated, but used for migrations (for now)
347 ######################################################
349 class MigrationData(Base
):
350 __tablename__
= "core__migrations"
352 name
= Column(Unicode
, primary_key
=True)
353 version
= Column(Integer
, nullable
=False, default
=0)
355 ######################################################
358 def show_table_init(engine_uri
):
359 if engine_uri
is None:
360 engine_uri
= 'sqlite:///:memory:'
361 from sqlalchemy
import create_engine
362 engine
= create_engine(engine_uri
, echo
=True)
364 Base
.metadata
.create_all(engine
)
367 if __name__
== '__main__':