Fix for ticket #386
[mediagoblin.git] / mediagoblin / db / sql / models.py
CommitLineData
fbad3a9f 1# GNU MediaGoblin -- federated, autonomous media hosting
7f4ebeed 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
fbad3a9f
E
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
ccca0fbf
CAW
18import datetime
19
ccca0fbf
CAW
20from sqlalchemy import (
21 Column, Integer, Unicode, UnicodeText, DateTime, Boolean, ForeignKey,
22 UniqueConstraint)
88e90f41 23from sqlalchemy.orm import relationship
02db7e0a 24from sqlalchemy.orm.collections import attribute_mapped_collection
c47a03b9 25from sqlalchemy.sql.expression import desc
02db7e0a 26from sqlalchemy.ext.associationproxy import association_proxy
ccca0fbf 27
02db7e0a 28from mediagoblin.db.sql.extratypes import PathTupleWithSlashes
de917303 29from mediagoblin.db.sql.base import Base, DictReadAttrProxy
f42e49c3 30from mediagoblin.db.mixin import UserMixin, MediaEntryMixin
ccca0fbf 31
7b194a79 32
19ed039b
E
33class SimpleFieldAlias(object):
34 """An alias for any field"""
35 def __init__(self, fieldname):
36 self.fieldname = fieldname
37
38 def __get__(self, instance, cls):
39 return getattr(instance, self.fieldname)
40
41 def __set__(self, instance, val):
42 setattr(instance, self.fieldname, val)
43
44
f42e49c3 45class User(Base, UserMixin):
ccca0fbf
CAW
46 __tablename__ = "users"
47
48 id = Column(Integer, primary_key=True)
49 username = Column(Unicode, nullable=False, unique=True)
50 email = Column(Unicode, nullable=False)
51 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
52 pw_hash = Column(Unicode, nullable=False)
51fba991 53 email_verified = Column(Boolean, default=False)
e365f980 54 status = Column(Unicode, default=u"needs_email_verification", nullable=False)
ccca0fbf
CAW
55 verification_key = Column(Unicode)
56 is_admin = Column(Boolean, default=False, nullable=False)
57 url = Column(Unicode)
fbad3a9f
E
58 bio = Column(UnicodeText) # ??
59 bio_html = Column(UnicodeText) # ??
ccca0fbf 60 fp_verification_key = Column(Unicode)
7c2c56a5 61 fp_token_expire = Column(DateTime)
ccca0fbf
CAW
62
63 ## TODO
64 # plugin data would be in a separate model
65
19ed039b
E
66 _id = SimpleFieldAlias("id")
67
ccca0fbf 68
f42e49c3 69class MediaEntry(Base, MediaEntryMixin):
ccca0fbf
CAW
70 __tablename__ = "media_entries"
71
72 id = Column(Integer, primary_key=True)
73 uploader = Column(Integer, ForeignKey('users.id'), nullable=False)
7c2c56a5 74 title = Column(Unicode, nullable=False)
3e907d55 75 slug = Column(Unicode)
ccca0fbf
CAW
76 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
77 description = Column(UnicodeText) # ??
78 description_html = Column(UnicodeText) # ??
79 media_type = Column(Unicode, nullable=False)
51fba991
E
80 state = Column(Unicode, default=u'unprocessed', nullable=False)
81 # or use sqlalchemy.types.Enum?
2788e6a1 82 license = Column(Unicode)
fbad3a9f 83
ccca0fbf
CAW
84 fail_error = Column(Unicode)
85 fail_metadata = Column(UnicodeText)
86
02db7e0a 87 queued_media_file = Column(PathTupleWithSlashes)
ccca0fbf
CAW
88
89 queued_task_id = Column(Unicode)
90
91 __table_args__ = (
92 UniqueConstraint('uploader', 'slug'),
93 {})
94
88e90f41
E
95 get_uploader = relationship(User)
96
02db7e0a
E
97 media_files_helper = relationship("MediaFile",
98 collection_class=attribute_mapped_collection("name"),
99 cascade="all, delete-orphan"
100 )
101 media_files = association_proxy('media_files_helper', 'file_path',
fbad3a9f 102 creator=lambda k, v: MediaFile(name=k, file_path=v)
02db7e0a
E
103 )
104
de917303
E
105 tags_helper = relationship("MediaTag",
106 cascade="all, delete-orphan"
107 )
108 tags = association_proxy("tags_helper", "dict_view",
109 creator=lambda v: MediaTag(name=v["name"], slug=v["slug"])
110 )
111
ccca0fbf 112 ## TODO
ccca0fbf
CAW
113 # media_data
114 # attachment_files
115 # fail_error
116
51fba991
E
117 _id = SimpleFieldAlias("id")
118
02ede858
E
119 def get_comments(self, ascending=False):
120 order_col = MediaComment.created
121 if not ascending:
122 order_col = desc(order_col)
123 return MediaComment.query.filter_by(
124 media_entry=self.id).order_by(order_col)
125
c47a03b9
E
126 def url_to_prev(self, urlgen):
127 """get the next 'newer' entry by this user"""
128 media = MediaEntry.query.filter(
129 (MediaEntry.uploader == self.uploader)
130 & (MediaEntry.state == 'processed')
131 & (MediaEntry.id > self.id)).order_by(MediaEntry.id).first()
132
133 if media is not None:
134 return media.url_for_self(urlgen)
135
136 def url_to_next(self, urlgen):
137 """get the next 'older' entry by this user"""
138 media = MediaEntry.query.filter(
139 (MediaEntry.uploader == self.uploader)
140 & (MediaEntry.state == 'processed')
141 & (MediaEntry.id < self.id)).order_by(desc(MediaEntry.id)).first()
142
143 if media is not None:
144 return media.url_for_self(urlgen)
145
ccca0fbf 146
02db7e0a
E
147class MediaFile(Base):
148 __tablename__ = "mediafiles"
149
150 media_entry = Column(
151 Integer, ForeignKey(MediaEntry.id),
152 nullable=False, primary_key=True)
153 name = Column(Unicode, primary_key=True)
154 file_path = Column(PathTupleWithSlashes)
155
156 def __repr__(self):
157 return "<MediaFile %s: %r>" % (self.name, self.file_path)
158
159
ccca0fbf
CAW
160class Tag(Base):
161 __tablename__ = "tags"
162
163 id = Column(Integer, primary_key=True)
164 slug = Column(Unicode, nullable=False, unique=True)
165
de917303
E
166 def __repr__(self):
167 return "<Tag %r: %r>" % (self.id, self.slug)
168
169 @classmethod
170 def find_or_new(cls, slug):
171 t = cls.query.filter_by(slug=slug).first()
172 if t is not None:
173 return t
174 return cls(slug=slug)
175
ccca0fbf
CAW
176
177class MediaTag(Base):
178 __tablename__ = "media_tags"
179
180 id = Column(Integer, primary_key=True)
ccca0fbf 181 media_entry = Column(
de917303 182 Integer, ForeignKey(MediaEntry.id),
ccca0fbf 183 nullable=False)
de917303
E
184 tag = Column(Integer, ForeignKey('tags.id'), nullable=False)
185 name = Column(Unicode)
ccca0fbf
CAW
186 # created = Column(DateTime, nullable=False, default=datetime.datetime.now)
187
188 __table_args__ = (
189 UniqueConstraint('tag', 'media_entry'),
190 {})
191
de917303
E
192 tag_helper = relationship(Tag)
193 slug = association_proxy('tag_helper', 'slug',
194 creator=Tag.find_or_new
195 )
196
197 def __init__(self, name, slug):
198 Base.__init__(self)
199 self.name = name
200 self.tag_helper = Tag.find_or_new(slug)
201
202 @property
203 def dict_view(self):
204 """A dict like view on this object"""
205 return DictReadAttrProxy(self)
206
ccca0fbf
CAW
207
208class MediaComment(Base):
209 __tablename__ = "media_comments"
fbad3a9f 210
ccca0fbf
CAW
211 id = Column(Integer, primary_key=True)
212 media_entry = Column(
213 Integer, ForeignKey('media_entries.id'), nullable=False)
214 author = Column(Integer, ForeignKey('users.id'), nullable=False)
215 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
216 content = Column(UnicodeText, nullable=False)
217 content_html = Column(UnicodeText)
e365f980 218
88e90f41
E
219 get_author = relationship(User)
220
51fba991
E
221 _id = SimpleFieldAlias("id")
222
e365f980
E
223
224def show_table_init():
225 from sqlalchemy import create_engine
226 engine = create_engine('sqlite:///:memory:', echo=True)
227
228 Base.metadata.create_all(engine)
229
230
231if __name__ == '__main__':
232 show_table_init()