Adding thallian to the authors list
[mediagoblin.git] / mediagoblin / db / mixin.py
CommitLineData
f42e49c3 1# GNU MediaGoblin -- federated, autonomous media hosting
7f4ebeed 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
f42e49c3
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"""
18This module contains some Mixin classes for the db objects.
19
20A bunch of functions on the db objects are really more like
21"utility functions": They could live outside the classes
22and be called "by hand" passing the appropiate reference.
23They usually only use the public API of the object and
24rarely use database related stuff.
25
26These functions now live here and get "mixed in" into the
27real objects.
28"""
29
a81082fc 30import uuid
907bba31 31import re
2d7b6bde 32from datetime import datetime
72bb46c7 33
5f8b4ae8
SS
34from werkzeug.utils import cached_property
35
814334f6 36from mediagoblin import mg_globals
58a94757 37from mediagoblin.media_types import FileTypeNotSupported
17c23e15 38from mediagoblin.tools import common, licenses
58a94757 39from mediagoblin.tools.pluginapi import hook_handle
e61ab099 40from mediagoblin.tools.text import cleaned_markdown_conversion
814334f6 41from mediagoblin.tools.url import slugify
f42e49c3
E
42
43
44class UserMixin(object):
e61ab099
E
45 @property
46 def bio_html(self):
47 return cleaned_markdown_conversion(self.bio)
48
de6a313c
BP
49 def url_for_self(self, urlgen, **kwargs):
50 """Generate a URL for this User's home page."""
51 return urlgen('mediagoblin.user_pages.user_home',
52 user=self.username, **kwargs)
53
54
29c65044 55class GenerateSlugMixin(object):
44123853
E
56 """
57 Mixin to add a generate_slug method to objects.
58
59 Depends on:
60 - self.slug
61 - self.title
62 - self.check_slug_used(new_slug)
63 """
814334f6 64 def generate_slug(self):
88de830f 65 """
44123853 66 Generate a unique slug for this object.
98587109 67
88de830f
CAW
68 This one does not *force* slugs, but usually it will probably result
69 in a niceish one.
70
98587109
CAW
71 The end *result* of the algorithm will result in these resolutions for
72 these situations:
88de830f
CAW
73 - If we have a slug, make sure it's clean and sanitized, and if it's
74 unique, we'll use that.
75 - If we have a title, slugify it, and if it's unique, we'll use that.
76 - If we can't get any sort of thing that looks like it'll be a useful
77 slug out of a title or an existing slug, bail, and don't set the
78 slug at all. Don't try to create something just because. Make
79 sure we have a reasonable basis for a slug first.
80 - If we have a reasonable basis for a slug (either based on existing
81 slug or slugified title) but it's not unique, first try appending
82 the entry's id, if that exists
83 - If that doesn't result in something unique, tack on some randomly
84 generated bits until it's unique. That'll be a little bit of junk,
85 but at least it has the basis of a nice slug.
86 """
66d9f1b2
SS
87 #Is already a slug assigned? Check if it is valid
88 if self.slug:
89 self.slug = slugify(self.slug)
b1126f71 90
88de830f 91 # otherwise, try to use the title.
66d9f1b2 92 elif self.title:
88de830f 93 # assign slug based on title
66d9f1b2 94 self.slug = slugify(self.title)
b1126f71 95
b0118957
CAW
96 # We don't want any empty string slugs
97 if self.slug == u"":
98 self.slug = None
99
88de830f
CAW
100 # Do we have anything at this point?
101 # If not, we're not going to get a slug
102 # so just return... we're not going to force one.
103 if not self.slug:
104 return # giving up!
b1126f71 105
88de830f 106 # Otherwise, let's see if this is unique.
29c65044 107 if self.check_slug_used(self.slug):
88de830f 108 # It looks like it's being used... lame.
b1126f71 109
88de830f
CAW
110 # Can we just append the object's id to the end?
111 if self.id:
98587109 112 slug_with_id = u"%s-%s" % (self.slug, self.id)
29c65044 113 if not self.check_slug_used(slug_with_id):
88de830f
CAW
114 self.slug = slug_with_id
115 return # success!
b1126f71 116
88de830f
CAW
117 # okay, still no success;
118 # let's whack junk on there till it's unique.
a81082fc
CAW
119 self.slug += '-' + uuid.uuid4().hex[:4]
120 # keep going if necessary!
29c65044 121 while self.check_slug_used(self.slug):
a81082fc 122 self.slug += uuid.uuid4().hex[:4]
814334f6 123
29c65044
E
124
125class MediaEntryMixin(GenerateSlugMixin):
126 def check_slug_used(self, slug):
127 # import this here due to a cyclic import issue
128 # (db.models -> db.mixin -> db.util -> db.models)
129 from mediagoblin.db.util import check_media_slug_used
130
131 return check_media_slug_used(self.uploader, slug, self.id)
132
1e72e075
E
133 @property
134 def description_html(self):
135 """
136 Rendered version of the description, run through
137 Markdown and cleaned with our cleaning tool.
138 """
139 return cleaned_markdown_conversion(self.description)
140
e77df64f
CAW
141 def get_display_media(self):
142 """Find the best media for display.
f42e49c3 143
53024776 144 We try checking self.media_manager.fetching_order if it exists to
e77df64f 145 pull down the order.
f42e49c3
E
146
147 Returns:
ddbf6af1
CAW
148 (media_size, media_path)
149 or, if not found, None.
e77df64f 150
f42e49c3 151 """
e8676fa3 152 fetch_order = self.media_manager.media_fetch_order
f42e49c3 153
ddbf6af1
CAW
154 # No fetching order found? well, give up!
155 if not fetch_order:
156 return None
157
158 media_sizes = self.media_files.keys()
159
160 for media_size in fetch_order:
f42e49c3 161 if media_size in media_sizes:
ddbf6af1 162 return media_size, self.media_files[media_size]
f42e49c3
E
163
164 def main_mediafile(self):
165 pass
166
3e907d55
E
167 @property
168 def slug_or_id(self):
7de20e52
CAW
169 if self.slug:
170 return self.slug
171 else:
172 return u'id:%s' % self.id
5f8b4ae8 173
cb7ae1e4 174 def url_for_self(self, urlgen, **extra_args):
f42e49c3
E
175 """
176 Generate an appropriate url for ourselves
177
5c2b8486 178 Use a slug if we have one, else use our 'id'.
f42e49c3
E
179 """
180 uploader = self.get_uploader
181
3e907d55
E
182 return urlgen(
183 'mediagoblin.user_pages.media_home',
184 user=uploader.username,
185 media=self.slug_or_id,
186 **extra_args)
f42e49c3 187
2e4ad359
SS
188 @property
189 def thumb_url(self):
190 """Return the thumbnail URL (for usage in templates)
191 Will return either the real thumbnail or a default fallback icon."""
192 # TODO: implement generic fallback in case MEDIA_MANAGER does
193 # not specify one?
194 if u'thumb' in self.media_files:
195 thumb_url = mg_globals.app.public_store.file_url(
196 self.media_files[u'thumb'])
197 else:
df1c4976 198 # No thumbnail in media available. Get the media's
2e4ad359 199 # MEDIA_MANAGER for the fallback icon and return static URL
5f8b4ae8
SS
200 # Raises FileTypeNotSupported in case no such manager is enabled
201 manager = self.media_manager
df1c4976 202 thumb_url = mg_globals.app.staticdirector(manager[u'default_thumb'])
2e4ad359
SS
203 return thumb_url
204
5b014a08
JT
205 @property
206 def original_url(self):
207 """ Returns the URL for the original image
208 will return self.thumb_url if original url doesn't exist"""
209 if u"original" not in self.media_files:
210 return self.thumb_url
211
212 return mg_globals.app.public_store.file_url(
213 self.media_files[u"original"]
214 )
215
5f8b4ae8
SS
216 @cached_property
217 def media_manager(self):
218 """Returns the MEDIA_MANAGER of the media's media_type
219
220 Raises FileTypeNotSupported in case no such manager is enabled
221 """
6403bc92 222 manager = hook_handle(('media_manager', self.media_type))
58a94757 223 if manager:
4259ad5b
CAW
224 return manager(self)
225
5f8b4ae8
SS
226 # Not found? Then raise an error
227 raise FileTypeNotSupported(
e6991972
RE
228 "MediaManager not in enabled types. Check media_type plugins are"
229 " enabled in config?")
5f8b4ae8 230
f42e49c3
E
231 def get_fail_exception(self):
232 """
233 Get the exception that's appropriate for this error
234 """
51eb0267
JW
235 if self.fail_error:
236 return common.import_component(self.fail_error)
17c23e15
AW
237
238 def get_license_data(self):
239 """Return license dict for requested license"""
138a18fd 240 return licenses.get_license_by_url(self.license or "")
feba5c52 241
5bad26bc
E
242 def exif_display_iter(self):
243 if not self.media_data:
244 return
245 exif_all = self.media_data.get("exif_all")
246
b3566e1d
GS
247 for key in exif_all:
248 label = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', key)
249 yield label.replace('EXIF', '').replace('Image', ''), exif_all[key]
5bad26bc 250
420e1374
GS
251 def exif_display_data_short(self):
252 """Display a very short practical version of exif info"""
420e1374
GS
253 if not self.media_data:
254 return
907bba31 255
420e1374 256 exif_all = self.media_data.get("exif_all")
907bba31 257
14aa2eaa
JW
258 exif_short = {}
259
907bba31
JW
260 if 'Image DateTimeOriginal' in exif_all:
261 # format date taken
196cef38 262 takendate = datetime.strptime(
907bba31
JW
263 exif_all['Image DateTimeOriginal']['printable'],
264 '%Y:%m:%d %H:%M:%S').date()
265 taken = takendate.strftime('%B %d %Y')
266
14aa2eaa
JW
267 exif_short.update({'Date Taken': taken})
268
1b6a2b85 269 aperture = None
907bba31
JW
270 if 'EXIF FNumber' in exif_all:
271 fnum = str(exif_all['EXIF FNumber']['printable']).split('/')
272
1b6a2b85
JW
273 # calculate aperture
274 if len(fnum) == 2:
275 aperture = "f/%.1f" % (float(fnum[0])/float(fnum[1]))
276 elif fnum[0] != 'None':
277 aperture = "f/%s" % (fnum[0])
907bba31 278
14aa2eaa
JW
279 if aperture:
280 exif_short.update({'Aperture': aperture})
281
282 short_keys = [
283 ('Camera', 'Image Model', None),
284 ('Exposure', 'EXIF ExposureTime', lambda x: '%s sec' % x),
285 ('ISO Speed', 'EXIF ISOSpeedRatings', None),
286 ('Focal Length', 'EXIF FocalLength', lambda x: '%s mm' % x)]
287
288 for label, key, fmt_func in short_keys:
289 try:
290 val = fmt_func(exif_all[key]['printable']) if fmt_func \
291 else exif_all[key]['printable']
292 exif_short.update({label: val})
293 except KeyError:
294 pass
295
296 return exif_short
297
feba5c52
E
298
299class MediaCommentMixin(object):
300 @property
301 def content_html(self):
302 """
303 the actual html-rendered version of the comment displayed.
304 Run through Markdown and the HTML cleaner.
305 """
306 return cleaned_markdown_conversion(self.content)
be5be115 307
2d7b6bde 308 def __repr__(self):
09bed9a7 309 return u'<{klass} #{id} {author} "{comment}">'.format(
2d7b6bde
JW
310 klass=self.__class__.__name__,
311 id=self.id,
312 author=self.get_author,
313 comment=self.content)
314
be5be115 315
455fd36f
E
316class CollectionMixin(GenerateSlugMixin):
317 def check_slug_used(self, slug):
be5be115
AW
318 # import this here due to a cyclic import issue
319 # (db.models -> db.mixin -> db.util -> db.models)
320 from mediagoblin.db.util import check_collection_slug_used
321
455fd36f 322 return check_collection_slug_used(self.creator, slug, self.id)
be5be115
AW
323
324 @property
325 def description_html(self):
326 """
327 Rendered version of the description, run through
328 Markdown and cleaned with our cleaning tool.
329 """
330 return cleaned_markdown_conversion(self.description)
331
332 @property
333 def slug_or_id(self):
5c2b8486 334 return (self.slug or self.id)
be5be115
AW
335
336 def url_for_self(self, urlgen, **extra_args):
337 """
338 Generate an appropriate url for ourselves
339
5c2b8486 340 Use a slug if we have one, else use our 'id'.
be5be115
AW
341 """
342 creator = self.get_creator
343
344 return urlgen(
256f816f 345 'mediagoblin.user_pages.user_collection',
be5be115
AW
346 user=creator.username,
347 collection=self.slug_or_id,
348 **extra_args)
349
6d1e55b2 350
be5be115
AW
351class CollectionItemMixin(object):
352 @property
353 def note_html(self):
354 """
355 the actual html-rendered version of the note displayed.
356 Run through Markdown and the HTML cleaner.
357 """
358 return cleaned_markdown_conversion(self.note)