Switch test_app generation over to use py.test fixtures.
[mediagoblin.git] / mediagoblin / db / mixin.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 This module contains some Mixin classes for the db objects.
19
20 A bunch of functions on the db objects are really more like
21 "utility functions": They could live outside the classes
22 and be called "by hand" passing the appropiate reference.
23 They usually only use the public API of the object and
24 rarely use database related stuff.
25
26 These functions now live here and get "mixed in" into the
27 real objects.
28 """
29
30 import uuid
31
32 from werkzeug.utils import cached_property
33
34 from mediagoblin import mg_globals
35 from mediagoblin.auth import lib as auth_lib
36 from mediagoblin.media_types import get_media_managers, FileTypeNotSupported
37 from mediagoblin.tools import common, licenses
38 from mediagoblin.tools.text import cleaned_markdown_conversion
39 from mediagoblin.tools.url import slugify
40
41
42 class UserMixin(object):
43 def check_login(self, password):
44 """
45 See if a user can login with this password
46 """
47 return auth_lib.bcrypt_check_password(
48 password, self.pw_hash)
49
50 @property
51 def bio_html(self):
52 return cleaned_markdown_conversion(self.bio)
53
54
55 class MediaEntryMixin(object):
56 def generate_slug(self):
57 """
58 Generate a unique slug for this MediaEntry.
59
60 This one does not *force* slugs, but usually it will probably result
61 in a niceish one.
62
63 The end *result* of the algorithm will result in these resolutions for
64 these situations:
65 - If we have a slug, make sure it's clean and sanitized, and if it's
66 unique, we'll use that.
67 - If we have a title, slugify it, and if it's unique, we'll use that.
68 - If we can't get any sort of thing that looks like it'll be a useful
69 slug out of a title or an existing slug, bail, and don't set the
70 slug at all. Don't try to create something just because. Make
71 sure we have a reasonable basis for a slug first.
72 - If we have a reasonable basis for a slug (either based on existing
73 slug or slugified title) but it's not unique, first try appending
74 the entry's id, if that exists
75 - If that doesn't result in something unique, tack on some randomly
76 generated bits until it's unique. That'll be a little bit of junk,
77 but at least it has the basis of a nice slug.
78 """
79 # import this here due to a cyclic import issue
80 # (db.models -> db.mixin -> db.util -> db.models)
81 from mediagoblin.db.util import check_media_slug_used
82
83 #Is already a slug assigned? Check if it is valid
84 if self.slug:
85 self.slug = slugify(self.slug)
86
87 # otherwise, try to use the title.
88 elif self.title:
89 # assign slug based on title
90 self.slug = slugify(self.title)
91
92 # We don't want any empty string slugs
93 if self.slug == u"":
94 self.slug = None
95
96 # Do we have anything at this point?
97 # If not, we're not going to get a slug
98 # so just return... we're not going to force one.
99 if not self.slug:
100 return # giving up!
101
102 # Otherwise, let's see if this is unique.
103 if check_media_slug_used(self.uploader, self.slug, self.id):
104 # It looks like it's being used... lame.
105
106 # Can we just append the object's id to the end?
107 if self.id:
108 slug_with_id = u"%s-%s" % (self.slug, self.id)
109 if not check_media_slug_used(self.uploader,
110 slug_with_id, self.id):
111 self.slug = slug_with_id
112 return # success!
113
114 # okay, still no success;
115 # let's whack junk on there till it's unique.
116 self.slug += '-' + uuid.uuid4().hex[:4]
117 # keep going if necessary!
118 while check_media_slug_used(self.uploader, self.slug, self.id):
119 self.slug += uuid.uuid4().hex[:4]
120
121 @property
122 def description_html(self):
123 """
124 Rendered version of the description, run through
125 Markdown and cleaned with our cleaning tool.
126 """
127 return cleaned_markdown_conversion(self.description)
128
129 def get_display_media(self):
130 """Find the best media for display.
131
132 We try checking self.media_manager.fetching_order if it exists to
133 pull down the order.
134
135 Returns:
136 (media_size, media_path)
137 or, if not found, None.
138
139 """
140 fetch_order = self.media_manager.get("media_fetch_order")
141
142 # No fetching order found? well, give up!
143 if not fetch_order:
144 return None
145
146 media_sizes = self.media_files.keys()
147
148 for media_size in fetch_order:
149 if media_size in media_sizes:
150 return media_size, self.media_files[media_size]
151
152 def main_mediafile(self):
153 pass
154
155 @property
156 def slug_or_id(self):
157 if self.slug:
158 return self.slug
159 else:
160 return u'id:%s' % self.id
161
162 def url_for_self(self, urlgen, **extra_args):
163 """
164 Generate an appropriate url for ourselves
165
166 Use a slug if we have one, else use our 'id'.
167 """
168 uploader = self.get_uploader
169
170 return urlgen(
171 'mediagoblin.user_pages.media_home',
172 user=uploader.username,
173 media=self.slug_or_id,
174 **extra_args)
175
176 @property
177 def thumb_url(self):
178 """Return the thumbnail URL (for usage in templates)
179 Will return either the real thumbnail or a default fallback icon."""
180 # TODO: implement generic fallback in case MEDIA_MANAGER does
181 # not specify one?
182 if u'thumb' in self.media_files:
183 thumb_url = mg_globals.app.public_store.file_url(
184 self.media_files[u'thumb'])
185 else:
186 # No thumbnail in media available. Get the media's
187 # MEDIA_MANAGER for the fallback icon and return static URL
188 # Raises FileTypeNotSupported in case no such manager is enabled
189 manager = self.media_manager
190 thumb_url = mg_globals.app.staticdirector(manager[u'default_thumb'])
191 return thumb_url
192
193 @cached_property
194 def media_manager(self):
195 """Returns the MEDIA_MANAGER of the media's media_type
196
197 Raises FileTypeNotSupported in case no such manager is enabled
198 """
199 # TODO, we should be able to make this a simple lookup rather
200 # than iterating through all media managers.
201 for media_type, manager in get_media_managers():
202 if media_type == self.media_type:
203 return manager
204 # Not found? Then raise an error
205 raise FileTypeNotSupported(
206 "MediaManager not in enabled types. Check media_types in config?")
207
208 def get_fail_exception(self):
209 """
210 Get the exception that's appropriate for this error
211 """
212 if self.fail_error:
213 return common.import_component(self.fail_error)
214
215 def get_license_data(self):
216 """Return license dict for requested license"""
217 return licenses.get_license_by_url(self.license or "")
218
219 def exif_display_iter(self):
220 from mediagoblin.tools.exif import USEFUL_TAGS
221
222 if not self.media_data:
223 return
224 exif_all = self.media_data.get("exif_all")
225
226 for key in USEFUL_TAGS:
227 if key in exif_all:
228 yield key, exif_all[key]
229
230
231 class MediaCommentMixin(object):
232 @property
233 def content_html(self):
234 """
235 the actual html-rendered version of the comment displayed.
236 Run through Markdown and the HTML cleaner.
237 """
238 return cleaned_markdown_conversion(self.content)
239
240
241 class CollectionMixin(object):
242 def generate_slug(self):
243 # import this here due to a cyclic import issue
244 # (db.models -> db.mixin -> db.util -> db.models)
245 from mediagoblin.db.util import check_collection_slug_used
246
247 self.slug = slugify(self.title)
248
249 duplicate = check_collection_slug_used(mg_globals.database,
250 self.creator, self.slug, self.id)
251
252 if duplicate:
253 if self.id is not None:
254 self.slug = u"%s-%s" % (self.id, self.slug)
255 else:
256 self.slug = None
257
258 @property
259 def description_html(self):
260 """
261 Rendered version of the description, run through
262 Markdown and cleaned with our cleaning tool.
263 """
264 return cleaned_markdown_conversion(self.description)
265
266 @property
267 def slug_or_id(self):
268 return (self.slug or self.id)
269
270 def url_for_self(self, urlgen, **extra_args):
271 """
272 Generate an appropriate url for ourselves
273
274 Use a slug if we have one, else use our 'id'.
275 """
276 creator = self.get_creator
277
278 return urlgen(
279 'mediagoblin.user_pages.user_collection',
280 user=creator.username,
281 collection=self.slug_or_id,
282 **extra_args)
283
284
285 class CollectionItemMixin(object):
286 @property
287 def note_html(self):
288 """
289 the actual html-rendered version of the note displayed.
290 Run through Markdown and the HTML cleaner.
291 """
292 return cleaned_markdown_conversion(self.note)