Fix bugs with the exifread library update
[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
45e687fc 34from pytz import UTC
5f8b4ae8
SS
35from werkzeug.utils import cached_property
36
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
ce46470c 42from mediagoblin.tools.translate import pass_to_ugettext as _
f42e49c3
E
43
44
45class UserMixin(object):
0421fc5e
JT
46 object_type = "person"
47
e61ab099
E
48 @property
49 def bio_html(self):
50 return cleaned_markdown_conversion(self.bio)
51
de6a313c
BP
52 def url_for_self(self, urlgen, **kwargs):
53 """Generate a URL for this User's home page."""
54 return urlgen('mediagoblin.user_pages.user_home',
55 user=self.username, **kwargs)
56
57
29c65044 58class GenerateSlugMixin(object):
44123853
E
59 """
60 Mixin to add a generate_slug method to objects.
61
62 Depends on:
63 - self.slug
64 - self.title
65 - self.check_slug_used(new_slug)
66 """
814334f6 67 def generate_slug(self):
88de830f 68 """
44123853 69 Generate a unique slug for this object.
98587109 70
88de830f
CAW
71 This one does not *force* slugs, but usually it will probably result
72 in a niceish one.
73
98587109
CAW
74 The end *result* of the algorithm will result in these resolutions for
75 these situations:
88de830f
CAW
76 - If we have a slug, make sure it's clean and sanitized, and if it's
77 unique, we'll use that.
78 - If we have a title, slugify it, and if it's unique, we'll use that.
79 - If we can't get any sort of thing that looks like it'll be a useful
80 slug out of a title or an existing slug, bail, and don't set the
81 slug at all. Don't try to create something just because. Make
82 sure we have a reasonable basis for a slug first.
83 - If we have a reasonable basis for a slug (either based on existing
84 slug or slugified title) but it's not unique, first try appending
85 the entry's id, if that exists
86 - If that doesn't result in something unique, tack on some randomly
87 generated bits until it's unique. That'll be a little bit of junk,
88 but at least it has the basis of a nice slug.
89 """
c785f3a0 90
66d9f1b2
SS
91 #Is already a slug assigned? Check if it is valid
92 if self.slug:
c785f3a0 93 slug = slugify(self.slug)
b1126f71 94
88de830f 95 # otherwise, try to use the title.
66d9f1b2 96 elif self.title:
88de830f 97 # assign slug based on title
c785f3a0 98 slug = slugify(self.title)
b1126f71 99
c785f3a0
JT
100 else:
101 # We don't have any information to set a slug
102 return
b0118957 103
c785f3a0
JT
104 # We don't want any empty string slugs
105 if slug == u"":
106 return
b1126f71 107
88de830f 108 # Otherwise, let's see if this is unique.
c785f3a0 109 if self.check_slug_used(slug):
88de830f 110 # It looks like it's being used... lame.
b1126f71 111
88de830f
CAW
112 # Can we just append the object's id to the end?
113 if self.id:
c785f3a0 114 slug_with_id = u"%s-%s" % (slug, self.id)
29c65044 115 if not self.check_slug_used(slug_with_id):
88de830f
CAW
116 self.slug = slug_with_id
117 return # success!
b1126f71 118
88de830f
CAW
119 # okay, still no success;
120 # let's whack junk on there till it's unique.
c785f3a0 121 slug += '-' + uuid.uuid4().hex[:4]
a81082fc 122 # keep going if necessary!
c785f3a0
JT
123 while self.check_slug_used(slug):
124 slug += uuid.uuid4().hex[:4]
125
126 # self.check_slug_used(slug) must be False now so we have a slug that
127 # we can use now.
128 self.slug = slug
814334f6 129
29c65044
E
130
131class MediaEntryMixin(GenerateSlugMixin):
132 def check_slug_used(self, slug):
133 # import this here due to a cyclic import issue
134 # (db.models -> db.mixin -> db.util -> db.models)
135 from mediagoblin.db.util import check_media_slug_used
136
137 return check_media_slug_used(self.uploader, slug, self.id)
138
0421fc5e
JT
139 @property
140 def object_type(self):
141 """ Converts media_type to pump-like type - don't use internally """
142 return self.media_type.split(".")[-1]
143
1e72e075
E
144 @property
145 def description_html(self):
146 """
147 Rendered version of the description, run through
148 Markdown and cleaned with our cleaning tool.
149 """
150 return cleaned_markdown_conversion(self.description)
151
e77df64f
CAW
152 def get_display_media(self):
153 """Find the best media for display.
f42e49c3 154
53024776 155 We try checking self.media_manager.fetching_order if it exists to
e77df64f 156 pull down the order.
f42e49c3
E
157
158 Returns:
ddbf6af1
CAW
159 (media_size, media_path)
160 or, if not found, None.
e77df64f 161
f42e49c3 162 """
e8676fa3 163 fetch_order = self.media_manager.media_fetch_order
f42e49c3 164
ddbf6af1
CAW
165 # No fetching order found? well, give up!
166 if not fetch_order:
167 return None
168
169 media_sizes = self.media_files.keys()
170
171 for media_size in fetch_order:
f42e49c3 172 if media_size in media_sizes:
ddbf6af1 173 return media_size, self.media_files[media_size]
f42e49c3
E
174
175 def main_mediafile(self):
176 pass
177
3e907d55
E
178 @property
179 def slug_or_id(self):
7de20e52
CAW
180 if self.slug:
181 return self.slug
182 else:
183 return u'id:%s' % self.id
5f8b4ae8 184
cb7ae1e4 185 def url_for_self(self, urlgen, **extra_args):
f42e49c3
E
186 """
187 Generate an appropriate url for ourselves
188
5c2b8486 189 Use a slug if we have one, else use our 'id'.
f42e49c3
E
190 """
191 uploader = self.get_uploader
192
3e907d55
E
193 return urlgen(
194 'mediagoblin.user_pages.media_home',
195 user=uploader.username,
196 media=self.slug_or_id,
197 **extra_args)
f42e49c3 198
35fbad47
JT
199 def get_public_id(self, request):
200 """ Returns the public_id of the MediaEntry
201
202 If the MediaEntry has no public ID one will be produced from the
203 current request.
204 """
205 if self.public_id is None:
206 self.public_id = request.urlgen(
207 "mediagoblin.api.object",
208 object_type=self.object_type,
209 id=self.id,
210 qualified=True
211 )
212 # We need to ensure this ID is reused once we've given it out.
213 self.save()
214
215 return self.public_id
216
217
2e4ad359
SS
218 @property
219 def thumb_url(self):
220 """Return the thumbnail URL (for usage in templates)
221 Will return either the real thumbnail or a default fallback icon."""
222 # TODO: implement generic fallback in case MEDIA_MANAGER does
223 # not specify one?
224 if u'thumb' in self.media_files:
ddabf20f 225 thumb_url = self._app.public_store.file_url(
2e4ad359
SS
226 self.media_files[u'thumb'])
227 else:
df1c4976 228 # No thumbnail in media available. Get the media's
2e4ad359 229 # MEDIA_MANAGER for the fallback icon and return static URL
5f8b4ae8
SS
230 # Raises FileTypeNotSupported in case no such manager is enabled
231 manager = self.media_manager
ddabf20f 232 thumb_url = self._app.staticdirector(manager[u'default_thumb'])
2e4ad359
SS
233 return thumb_url
234
5b014a08
JT
235 @property
236 def original_url(self):
237 """ Returns the URL for the original image
238 will return self.thumb_url if original url doesn't exist"""
239 if u"original" not in self.media_files:
240 return self.thumb_url
ce46470c 241
ddabf20f 242 return self._app.public_store.file_url(
5b014a08
JT
243 self.media_files[u"original"]
244 )
245
5f8b4ae8
SS
246 @cached_property
247 def media_manager(self):
248 """Returns the MEDIA_MANAGER of the media's media_type
249
250 Raises FileTypeNotSupported in case no such manager is enabled
251 """
6403bc92 252 manager = hook_handle(('media_manager', self.media_type))
58a94757 253 if manager:
4259ad5b
CAW
254 return manager(self)
255
5f8b4ae8
SS
256 # Not found? Then raise an error
257 raise FileTypeNotSupported(
e6991972
RE
258 "MediaManager not in enabled types. Check media_type plugins are"
259 " enabled in config?")
5f8b4ae8 260
f42e49c3
E
261 def get_fail_exception(self):
262 """
263 Get the exception that's appropriate for this error
264 """
51eb0267
JW
265 if self.fail_error:
266 return common.import_component(self.fail_error)
17c23e15
AW
267
268 def get_license_data(self):
269 """Return license dict for requested license"""
138a18fd 270 return licenses.get_license_by_url(self.license or "")
feba5c52 271
5bad26bc
E
272 def exif_display_iter(self):
273 if not self.media_data:
274 return
275 exif_all = self.media_data.get("exif_all")
276
b3566e1d
GS
277 for key in exif_all:
278 label = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', key)
279 yield label.replace('EXIF', '').replace('Image', ''), exif_all[key]
5bad26bc 280
420e1374
GS
281 def exif_display_data_short(self):
282 """Display a very short practical version of exif info"""
420e1374
GS
283 if not self.media_data:
284 return
907bba31 285
420e1374 286 exif_all = self.media_data.get("exif_all")
907bba31 287
14aa2eaa
JW
288 exif_short = {}
289
907bba31
JW
290 if 'Image DateTimeOriginal' in exif_all:
291 # format date taken
196cef38 292 takendate = datetime.strptime(
907bba31
JW
293 exif_all['Image DateTimeOriginal']['printable'],
294 '%Y:%m:%d %H:%M:%S').date()
295 taken = takendate.strftime('%B %d %Y')
296
14aa2eaa
JW
297 exif_short.update({'Date Taken': taken})
298
1b6a2b85 299 aperture = None
907bba31
JW
300 if 'EXIF FNumber' in exif_all:
301 fnum = str(exif_all['EXIF FNumber']['printable']).split('/')
302
1b6a2b85
JW
303 # calculate aperture
304 if len(fnum) == 2:
305 aperture = "f/%.1f" % (float(fnum[0])/float(fnum[1]))
306 elif fnum[0] != 'None':
307 aperture = "f/%s" % (fnum[0])
907bba31 308
14aa2eaa
JW
309 if aperture:
310 exif_short.update({'Aperture': aperture})
311
312 short_keys = [
313 ('Camera', 'Image Model', None),
314 ('Exposure', 'EXIF ExposureTime', lambda x: '%s sec' % x),
315 ('ISO Speed', 'EXIF ISOSpeedRatings', None),
316 ('Focal Length', 'EXIF FocalLength', lambda x: '%s mm' % x)]
317
318 for label, key, fmt_func in short_keys:
319 try:
320 val = fmt_func(exif_all[key]['printable']) if fmt_func \
321 else exif_all[key]['printable']
322 exif_short.update({label: val})
323 except KeyError:
324 pass
325
326 return exif_short
327
feba5c52
E
328
329class MediaCommentMixin(object):
0421fc5e
JT
330 object_type = "comment"
331
feba5c52
E
332 @property
333 def content_html(self):
334 """
335 the actual html-rendered version of the comment displayed.
336 Run through Markdown and the HTML cleaner.
337 """
338 return cleaned_markdown_conversion(self.content)
be5be115 339
dc19e98d 340 def __unicode__(self):
09bed9a7 341 return u'<{klass} #{id} {author} "{comment}">'.format(
2d7b6bde
JW
342 klass=self.__class__.__name__,
343 id=self.id,
344 author=self.get_author,
345 comment=self.content)
346
dc19e98d
TB
347 def __repr__(self):
348 return '<{klass} #{id} {author} "{comment}">'.format(
349 klass=self.__class__.__name__,
350 id=self.id,
351 author=self.get_author,
352 comment=self.content)
353
be5be115 354
455fd36f 355class CollectionMixin(GenerateSlugMixin):
0421fc5e
JT
356 object_type = "collection"
357
455fd36f 358 def check_slug_used(self, slug):
be5be115
AW
359 # import this here due to a cyclic import issue
360 # (db.models -> db.mixin -> db.util -> db.models)
361 from mediagoblin.db.util import check_collection_slug_used
362
455fd36f 363 return check_collection_slug_used(self.creator, slug, self.id)
be5be115
AW
364
365 @property
366 def description_html(self):
367 """
368 Rendered version of the description, run through
369 Markdown and cleaned with our cleaning tool.
370 """
371 return cleaned_markdown_conversion(self.description)
372
373 @property
374 def slug_or_id(self):
5c2b8486 375 return (self.slug or self.id)
be5be115
AW
376
377 def url_for_self(self, urlgen, **extra_args):
378 """
379 Generate an appropriate url for ourselves
380
5c2b8486 381 Use a slug if we have one, else use our 'id'.
be5be115
AW
382 """
383 creator = self.get_creator
384
385 return urlgen(
256f816f 386 'mediagoblin.user_pages.user_collection',
be5be115
AW
387 user=creator.username,
388 collection=self.slug_or_id,
389 **extra_args)
390
6d1e55b2 391
be5be115
AW
392class CollectionItemMixin(object):
393 @property
394 def note_html(self):
395 """
396 the actual html-rendered version of the note displayed.
397 Run through Markdown and the HTML cleaner.
398 """
399 return cleaned_markdown_conversion(self.note)
ce46470c
JT
400
401class ActivityMixin(object):
0421fc5e 402 object_type = "activity"
ce46470c
JT
403
404 VALID_VERBS = ["add", "author", "create", "delete", "dislike", "favorite",
405 "follow", "like", "post", "share", "unfavorite", "unfollow",
406 "unlike", "unshare", "update", "tag"]
407
408 def get_url(self, request):
409 return request.urlgen(
4fd52036 410 "mediagoblin.user_pages.activity_view",
ce46470c
JT
411 username=self.get_actor.username,
412 id=self.id,
413 qualified=True
414 )
415
416 def generate_content(self):
417 """ Produces a HTML content for object """
418 # some of these have simple and targetted. If self.target it set
419 # it will pick the targetted. If they DON'T have a targetted version
420 # the information in targetted won't be added to the content.
421 verb_to_content = {
422 "add": {
423 "simple" : _("{username} added {object}"),
424 "targetted": _("{username} added {object} to {target}"),
425 },
426 "author": {"simple": _("{username} authored {object}")},
427 "create": {"simple": _("{username} created {object}")},
428 "delete": {"simple": _("{username} deleted {object}")},
429 "dislike": {"simple": _("{username} disliked {object}")},
430 "favorite": {"simple": _("{username} favorited {object}")},
431 "follow": {"simple": _("{username} followed {object}")},
432 "like": {"simple": _("{username} liked {object}")},
433 "post": {
434 "simple": _("{username} posted {object}"),
2b191618 435 "targetted": _("{username} posted {object} to {target}"),
ce46470c
JT
436 },
437 "share": {"simple": _("{username} shared {object}")},
438 "unfavorite": {"simple": _("{username} unfavorited {object}")},
439 "unfollow": {"simple": _("{username} stopped following {object}")},
440 "unlike": {"simple": _("{username} unliked {object}")},
441 "unshare": {"simple": _("{username} unshared {object}")},
442 "update": {"simple": _("{username} updated {object}")},
443 "tag": {"simple": _("{username} tagged {object}")},
444 }
445
1e0c938c
JT
446 object_map = {
447 "image": _("an image"),
448 "comment": _("a comment"),
449 "collection": _("a collection"),
450 "video": _("a video"),
451 "audio": _("audio"),
452 "person": _("a person"),
453 }
b4997540
JT
454 obj = self.object()
455 target = None if self.target_id is None else self.target()
ce46470c
JT
456 actor = self.get_actor
457 content = verb_to_content.get(self.verb, None)
458
2d73983e 459 if content is None or self.object is None:
ce46470c
JT
460 return
461
1e0c938c
JT
462 # Decide what to fill the object with
463 if hasattr(obj, "title") and obj.title.strip(" "):
7eac1e6d 464 object_value = obj.title
1e0c938c 465 elif obj.object_type in object_map:
7eac1e6d 466 object_value = object_map[obj.object_type]
1e0c938c 467 else:
7eac1e6d 468 object_value = _("an object")
1e0c938c 469
7eac1e6d
JT
470 # Do we want to add a target (indirect object) to content?
471 if target is not None and "targetted" in content:
472 if hasattr(target, "title") and target.title.strip(" "):
b4997540 473 target_value = target.title
7eac1e6d
JT
474 elif target.object_type in object_map:
475 target_value = object_map[target.object_type]
476 else:
477 target_value = _("an object")
478
479 self.content = content["targetted"].format(
ce46470c 480 username=actor.username,
7eac1e6d
JT
481 object=object_value,
482 target=target_value
ce46470c
JT
483 )
484 else:
7eac1e6d 485 self.content = content["simple"].format(
ce46470c 486 username=actor.username,
7eac1e6d 487 object=object_value
ce46470c
JT
488 )
489
490 return self.content
491
492 def serialize(self, request):
9c602458 493 href = request.urlgen(
4fd52036 494 "mediagoblin.api.object",
9c602458
JT
495 object_type=self.object_type,
496 id=self.id,
497 qualified=True
498 )
45e687fc
JT
499 published = UTC.localize(self.published)
500 updated = UTC.localize(self.updated)
ce46470c 501 obj = {
9c602458 502 "id": href,
ce46470c
JT
503 "actor": self.get_actor.serialize(request),
504 "verb": self.verb,
45e687fc
JT
505 "published": published.isoformat(),
506 "updated": updated.isoformat(),
ce46470c
JT
507 "content": self.content,
508 "url": self.get_url(request),
de366f73 509 "object": self.object().serialize(request),
0421fc5e 510 "objectType": self.object_type,
35885226
JT
511 "links": {
512 "self": {
513 "href": href,
514 },
515 },
ce46470c
JT
516 }
517
518 if self.generator:
6d36f75f 519 obj["generator"] = self.get_generator.serialize(request)
ce46470c
JT
520
521 if self.title:
522 obj["title"] = self.title
523
de366f73
JT
524 if self.target_id is not None:
525 obj["target"] = self.target().serialize(request)
ce46470c
JT
526
527 return obj
528
529 def unseralize(self, data):
530 """
531 Takes data given and set it on this activity.
532
533 Several pieces of data are not written on because of security
534 reasons. For example changing the author or id of an activity.
535 """
536 if "verb" in data:
537 self.verb = data["verb"]
538
539 if "title" in data:
540 self.title = data["title"]
541
542 if "content" in data:
543 self.content = data["content"]