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/>.
20 from sqlalchemy
import (
21 Column
, Integer
, Unicode
, UnicodeText
, DateTime
, Boolean
, ForeignKey
,
23 from sqlalchemy
.orm
import relationship
24 from sqlalchemy
.orm
.collections
import attribute_mapped_collection
25 from sqlalchemy
.sql
.expression
import desc
26 from sqlalchemy
.ext
.associationproxy
import association_proxy
28 from mediagoblin
.db
.sql
.extratypes
import PathTupleWithSlashes
29 from mediagoblin
.db
.sql
.base
import Base
, DictReadAttrProxy
30 from mediagoblin
.db
.mixin
import UserMixin
, MediaEntryMixin
32 # It's actually kind of annoying how sqlalchemy-migrate does this, if
33 # I understand it right, but whatever. Anyway, don't remove this :P
35 # We could do migration calls more manually instead of relying on
36 # this import-based meddling...
37 from migrate
import changeset
40 class SimpleFieldAlias(object):
41 """An alias for any field"""
42 def __init__(self
, fieldname
):
43 self
.fieldname
= fieldname
45 def __get__(self
, instance
, cls
):
46 return getattr(instance
, self
.fieldname
)
48 def __set__(self
, instance
, val
):
49 setattr(instance
, self
.fieldname
, val
)
52 class User(Base
, UserMixin
):
53 __tablename__
= "users"
55 id = Column(Integer
, primary_key
=True)
56 username
= Column(Unicode
, nullable
=False, unique
=True)
57 email
= Column(Unicode
, nullable
=False)
58 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
59 pw_hash
= Column(Unicode
, nullable
=False)
60 email_verified
= Column(Boolean
)
61 status
= Column(Unicode
, default
=u
"needs_email_verification", nullable
=False)
62 verification_key
= Column(Unicode
)
63 is_admin
= Column(Boolean
, default
=False, nullable
=False)
65 bio
= Column(UnicodeText
) # ??
66 bio_html
= Column(UnicodeText
) # ??
67 fp_verification_key
= Column(Unicode
)
68 fp_token_expire
= Column(DateTime
)
71 # plugin data would be in a separate model
73 _id
= SimpleFieldAlias("id")
76 class MediaEntry(Base
, MediaEntryMixin
):
77 __tablename__
= "media_entries"
79 id = Column(Integer
, primary_key
=True)
80 uploader
= Column(Integer
, ForeignKey('users.id'), nullable
=False)
81 title
= Column(Unicode
, nullable
=False)
82 slug
= Column(Unicode
)
83 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
84 description
= Column(UnicodeText
) # ??
85 description_html
= Column(UnicodeText
) # ??
86 media_type
= Column(Unicode
, nullable
=False)
87 state
= Column(Unicode
, nullable
=False) # or use sqlalchemy.types.Enum?
88 license
= Column(Unicode
)
90 fail_error
= Column(Unicode
)
91 fail_metadata
= Column(UnicodeText
)
93 queued_media_file
= Column(PathTupleWithSlashes
)
95 queued_task_id
= Column(Unicode
)
98 UniqueConstraint('uploader', 'slug'),
101 get_uploader
= relationship(User
)
103 media_files_helper
= relationship("MediaFile",
104 collection_class
=attribute_mapped_collection("name"),
105 cascade
="all, delete-orphan"
107 media_files
= association_proxy('media_files_helper', 'file_path',
108 creator
=lambda k
, v
: MediaFile(name
=k
, file_path
=v
)
111 tags_helper
= relationship("MediaTag",
112 cascade
="all, delete-orphan"
114 tags
= association_proxy("tags_helper", "dict_view",
115 creator
=lambda v
: MediaTag(name
=v
["name"], slug
=v
["slug"])
123 def get_comments(self
, ascending
=False):
124 order_col
= MediaComment
.created
126 order_col
= desc(order_col
)
127 return MediaComment
.query
.filter_by(
128 media_entry
=self
.id).order_by(order_col
)
130 def url_to_prev(self
, urlgen
):
131 """get the next 'newer' entry by this user"""
132 media
= MediaEntry
.query
.filter(
133 (MediaEntry
.uploader
== self
.uploader
)
134 & (MediaEntry
.state
== 'processed')
135 & (MediaEntry
.id > self
.id)).order_by(MediaEntry
.id).first()
137 if media
is not None:
138 return media
.url_for_self(urlgen
)
140 def url_to_next(self
, urlgen
):
141 """get the next 'older' entry by this user"""
142 media
= MediaEntry
.query
.filter(
143 (MediaEntry
.uploader
== self
.uploader
)
144 & (MediaEntry
.state
== 'processed')
145 & (MediaEntry
.id < self
.id)).order_by(desc(MediaEntry
.id)).first()
147 if media
is not None:
148 return media
.url_for_self(urlgen
)
151 class MediaFile(Base
):
152 __tablename__
= "mediafiles"
154 media_entry
= Column(
155 Integer
, ForeignKey(MediaEntry
.id),
156 nullable
=False, primary_key
=True)
157 name
= Column(Unicode
, primary_key
=True)
158 file_path
= Column(PathTupleWithSlashes
)
161 return "<MediaFile %s: %r>" % (self
.name
, self
.file_path
)
165 __tablename__
= "tags"
167 id = Column(Integer
, primary_key
=True)
168 slug
= Column(Unicode
, nullable
=False, unique
=True)
171 return "<Tag %r: %r>" % (self
.id, self
.slug
)
174 def find_or_new(cls
, slug
):
175 t
= cls
.query
.filter_by(slug
=slug
).first()
178 return cls(slug
=slug
)
181 class MediaTag(Base
):
182 __tablename__
= "media_tags"
184 id = Column(Integer
, primary_key
=True)
185 media_entry
= Column(
186 Integer
, ForeignKey(MediaEntry
.id),
188 tag
= Column(Integer
, ForeignKey('tags.id'), nullable
=False)
189 name
= Column(Unicode
)
190 # created = Column(DateTime, nullable=False, default=datetime.datetime.now)
193 UniqueConstraint('tag', 'media_entry'),
196 tag_helper
= relationship(Tag
)
197 slug
= association_proxy('tag_helper', 'slug',
198 creator
=Tag
.find_or_new
201 def __init__(self
, name
, slug
):
204 self
.tag_helper
= Tag
.find_or_new(slug
)
208 """A dict like view on this object"""
209 return DictReadAttrProxy(self
)
212 class MediaComment(Base
):
213 __tablename__
= "media_comments"
215 id = Column(Integer
, primary_key
=True)
216 media_entry
= Column(
217 Integer
, ForeignKey('media_entries.id'), nullable
=False)
218 author
= Column(Integer
, ForeignKey('users.id'), nullable
=False)
219 created
= Column(DateTime
, nullable
=False, default
=datetime
.datetime
.now
)
220 content
= Column(UnicodeText
, nullable
=False)
221 content_html
= Column(UnicodeText
)
223 get_author
= relationship(User
)
227 User
, MediaEntry
, Tag
, MediaTag
, MediaComment
]
230 ######################################################
231 # Special, migrations-tracking table
233 # Not listed in MODELS because this is special and not
234 # really migrated, but used for migrations (for now)
235 ######################################################
237 class MigrationData(Base
):
238 __tablename__
= "migrations"
240 name
= Column(Unicode
, primary_key
=True)
241 version
= Column(Integer
, nullable
=False, default
=0)
243 ######################################################
246 def show_table_init():
247 from sqlalchemy
import create_engine
248 engine
= create_engine('sqlite:///:memory:', echo
=True)
250 Base
.metadata
.create_all(engine
)
253 if __name__
== '__main__':