Commit | Line | Data |
---|---|---|
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 | """ | |
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 | ||
a81082fc | 30 | import uuid |
907bba31 | 31 | import re |
2d7b6bde | 32 | from datetime import datetime |
72bb46c7 | 33 | |
5f8b4ae8 SS |
34 | from werkzeug.utils import cached_property |
35 | ||
814334f6 | 36 | from mediagoblin import mg_globals |
58a94757 | 37 | from mediagoblin.media_types import FileTypeNotSupported |
17c23e15 | 38 | from mediagoblin.tools import common, licenses |
58a94757 | 39 | from mediagoblin.tools.pluginapi import hook_handle |
e61ab099 | 40 | from mediagoblin.tools.text import cleaned_markdown_conversion |
814334f6 | 41 | from mediagoblin.tools.url import slugify |
ce46470c | 42 | from mediagoblin.tools.translate import pass_to_ugettext as _ |
f42e49c3 E |
43 | |
44 | ||
45 | class 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 | 58 | class 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 | """ | |
66d9f1b2 SS |
90 | #Is already a slug assigned? Check if it is valid |
91 | if self.slug: | |
92 | self.slug = slugify(self.slug) | |
b1126f71 | 93 | |
88de830f | 94 | # otherwise, try to use the title. |
66d9f1b2 | 95 | elif self.title: |
88de830f | 96 | # assign slug based on title |
66d9f1b2 | 97 | self.slug = slugify(self.title) |
b1126f71 | 98 | |
b0118957 CAW |
99 | # We don't want any empty string slugs |
100 | if self.slug == u"": | |
101 | self.slug = None | |
102 | ||
88de830f CAW |
103 | # Do we have anything at this point? |
104 | # If not, we're not going to get a slug | |
105 | # so just return... we're not going to force one. | |
106 | if not self.slug: | |
107 | return # giving up! | |
b1126f71 | 108 | |
88de830f | 109 | # Otherwise, let's see if this is unique. |
29c65044 | 110 | if self.check_slug_used(self.slug): |
88de830f | 111 | # It looks like it's being used... lame. |
b1126f71 | 112 | |
88de830f CAW |
113 | # Can we just append the object's id to the end? |
114 | if self.id: | |
98587109 | 115 | slug_with_id = u"%s-%s" % (self.slug, self.id) |
29c65044 | 116 | if not self.check_slug_used(slug_with_id): |
88de830f CAW |
117 | self.slug = slug_with_id |
118 | return # success! | |
b1126f71 | 119 | |
88de830f CAW |
120 | # okay, still no success; |
121 | # let's whack junk on there till it's unique. | |
a81082fc CAW |
122 | self.slug += '-' + uuid.uuid4().hex[:4] |
123 | # keep going if necessary! | |
29c65044 | 124 | while self.check_slug_used(self.slug): |
a81082fc | 125 | self.slug += uuid.uuid4().hex[:4] |
814334f6 | 126 | |
29c65044 E |
127 | |
128 | class MediaEntryMixin(GenerateSlugMixin): | |
129 | def check_slug_used(self, slug): | |
130 | # import this here due to a cyclic import issue | |
131 | # (db.models -> db.mixin -> db.util -> db.models) | |
132 | from mediagoblin.db.util import check_media_slug_used | |
133 | ||
134 | return check_media_slug_used(self.uploader, slug, self.id) | |
135 | ||
0421fc5e JT |
136 | @property |
137 | def object_type(self): | |
138 | """ Converts media_type to pump-like type - don't use internally """ | |
139 | return self.media_type.split(".")[-1] | |
140 | ||
1e72e075 E |
141 | @property |
142 | def description_html(self): | |
143 | """ | |
144 | Rendered version of the description, run through | |
145 | Markdown and cleaned with our cleaning tool. | |
146 | """ | |
147 | return cleaned_markdown_conversion(self.description) | |
148 | ||
e77df64f CAW |
149 | def get_display_media(self): |
150 | """Find the best media for display. | |
f42e49c3 | 151 | |
53024776 | 152 | We try checking self.media_manager.fetching_order if it exists to |
e77df64f | 153 | pull down the order. |
f42e49c3 E |
154 | |
155 | Returns: | |
ddbf6af1 CAW |
156 | (media_size, media_path) |
157 | or, if not found, None. | |
e77df64f | 158 | |
f42e49c3 | 159 | """ |
e8676fa3 | 160 | fetch_order = self.media_manager.media_fetch_order |
f42e49c3 | 161 | |
ddbf6af1 CAW |
162 | # No fetching order found? well, give up! |
163 | if not fetch_order: | |
164 | return None | |
165 | ||
166 | media_sizes = self.media_files.keys() | |
167 | ||
168 | for media_size in fetch_order: | |
f42e49c3 | 169 | if media_size in media_sizes: |
ddbf6af1 | 170 | return media_size, self.media_files[media_size] |
f42e49c3 E |
171 | |
172 | def main_mediafile(self): | |
173 | pass | |
174 | ||
3e907d55 E |
175 | @property |
176 | def slug_or_id(self): | |
7de20e52 CAW |
177 | if self.slug: |
178 | return self.slug | |
179 | else: | |
180 | return u'id:%s' % self.id | |
5f8b4ae8 | 181 | |
cb7ae1e4 | 182 | def url_for_self(self, urlgen, **extra_args): |
f42e49c3 E |
183 | """ |
184 | Generate an appropriate url for ourselves | |
185 | ||
5c2b8486 | 186 | Use a slug if we have one, else use our 'id'. |
f42e49c3 E |
187 | """ |
188 | uploader = self.get_uploader | |
189 | ||
3e907d55 E |
190 | return urlgen( |
191 | 'mediagoblin.user_pages.media_home', | |
192 | user=uploader.username, | |
193 | media=self.slug_or_id, | |
194 | **extra_args) | |
f42e49c3 | 195 | |
2e4ad359 SS |
196 | @property |
197 | def thumb_url(self): | |
198 | """Return the thumbnail URL (for usage in templates) | |
199 | Will return either the real thumbnail or a default fallback icon.""" | |
200 | # TODO: implement generic fallback in case MEDIA_MANAGER does | |
201 | # not specify one? | |
202 | if u'thumb' in self.media_files: | |
203 | thumb_url = mg_globals.app.public_store.file_url( | |
204 | self.media_files[u'thumb']) | |
205 | else: | |
df1c4976 | 206 | # No thumbnail in media available. Get the media's |
2e4ad359 | 207 | # MEDIA_MANAGER for the fallback icon and return static URL |
5f8b4ae8 SS |
208 | # Raises FileTypeNotSupported in case no such manager is enabled |
209 | manager = self.media_manager | |
df1c4976 | 210 | thumb_url = mg_globals.app.staticdirector(manager[u'default_thumb']) |
2e4ad359 SS |
211 | return thumb_url |
212 | ||
5b014a08 JT |
213 | @property |
214 | def original_url(self): | |
215 | """ Returns the URL for the original image | |
216 | will return self.thumb_url if original url doesn't exist""" | |
217 | if u"original" not in self.media_files: | |
218 | return self.thumb_url | |
ce46470c | 219 | |
5b014a08 JT |
220 | return mg_globals.app.public_store.file_url( |
221 | self.media_files[u"original"] | |
222 | ) | |
223 | ||
5f8b4ae8 SS |
224 | @cached_property |
225 | def media_manager(self): | |
226 | """Returns the MEDIA_MANAGER of the media's media_type | |
227 | ||
228 | Raises FileTypeNotSupported in case no such manager is enabled | |
229 | """ | |
6403bc92 | 230 | manager = hook_handle(('media_manager', self.media_type)) |
58a94757 | 231 | if manager: |
4259ad5b CAW |
232 | return manager(self) |
233 | ||
5f8b4ae8 SS |
234 | # Not found? Then raise an error |
235 | raise FileTypeNotSupported( | |
e6991972 RE |
236 | "MediaManager not in enabled types. Check media_type plugins are" |
237 | " enabled in config?") | |
5f8b4ae8 | 238 | |
f42e49c3 E |
239 | def get_fail_exception(self): |
240 | """ | |
241 | Get the exception that's appropriate for this error | |
242 | """ | |
51eb0267 JW |
243 | if self.fail_error: |
244 | return common.import_component(self.fail_error) | |
17c23e15 AW |
245 | |
246 | def get_license_data(self): | |
247 | """Return license dict for requested license""" | |
138a18fd | 248 | return licenses.get_license_by_url(self.license or "") |
feba5c52 | 249 | |
5bad26bc E |
250 | def exif_display_iter(self): |
251 | if not self.media_data: | |
252 | return | |
253 | exif_all = self.media_data.get("exif_all") | |
254 | ||
b3566e1d GS |
255 | for key in exif_all: |
256 | label = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', key) | |
257 | yield label.replace('EXIF', '').replace('Image', ''), exif_all[key] | |
5bad26bc | 258 | |
420e1374 GS |
259 | def exif_display_data_short(self): |
260 | """Display a very short practical version of exif info""" | |
420e1374 GS |
261 | if not self.media_data: |
262 | return | |
907bba31 | 263 | |
420e1374 | 264 | exif_all = self.media_data.get("exif_all") |
907bba31 | 265 | |
14aa2eaa JW |
266 | exif_short = {} |
267 | ||
907bba31 JW |
268 | if 'Image DateTimeOriginal' in exif_all: |
269 | # format date taken | |
196cef38 | 270 | takendate = datetime.strptime( |
907bba31 JW |
271 | exif_all['Image DateTimeOriginal']['printable'], |
272 | '%Y:%m:%d %H:%M:%S').date() | |
273 | taken = takendate.strftime('%B %d %Y') | |
274 | ||
14aa2eaa JW |
275 | exif_short.update({'Date Taken': taken}) |
276 | ||
1b6a2b85 | 277 | aperture = None |
907bba31 JW |
278 | if 'EXIF FNumber' in exif_all: |
279 | fnum = str(exif_all['EXIF FNumber']['printable']).split('/') | |
280 | ||
1b6a2b85 JW |
281 | # calculate aperture |
282 | if len(fnum) == 2: | |
283 | aperture = "f/%.1f" % (float(fnum[0])/float(fnum[1])) | |
284 | elif fnum[0] != 'None': | |
285 | aperture = "f/%s" % (fnum[0]) | |
907bba31 | 286 | |
14aa2eaa JW |
287 | if aperture: |
288 | exif_short.update({'Aperture': aperture}) | |
289 | ||
290 | short_keys = [ | |
291 | ('Camera', 'Image Model', None), | |
292 | ('Exposure', 'EXIF ExposureTime', lambda x: '%s sec' % x), | |
293 | ('ISO Speed', 'EXIF ISOSpeedRatings', None), | |
294 | ('Focal Length', 'EXIF FocalLength', lambda x: '%s mm' % x)] | |
295 | ||
296 | for label, key, fmt_func in short_keys: | |
297 | try: | |
298 | val = fmt_func(exif_all[key]['printable']) if fmt_func \ | |
299 | else exif_all[key]['printable'] | |
300 | exif_short.update({label: val}) | |
301 | except KeyError: | |
302 | pass | |
303 | ||
304 | return exif_short | |
305 | ||
feba5c52 E |
306 | |
307 | class MediaCommentMixin(object): | |
0421fc5e JT |
308 | object_type = "comment" |
309 | ||
feba5c52 E |
310 | @property |
311 | def content_html(self): | |
312 | """ | |
313 | the actual html-rendered version of the comment displayed. | |
314 | Run through Markdown and the HTML cleaner. | |
315 | """ | |
316 | return cleaned_markdown_conversion(self.content) | |
be5be115 | 317 | |
dc19e98d | 318 | def __unicode__(self): |
09bed9a7 | 319 | return u'<{klass} #{id} {author} "{comment}">'.format( |
2d7b6bde JW |
320 | klass=self.__class__.__name__, |
321 | id=self.id, | |
322 | author=self.get_author, | |
323 | comment=self.content) | |
324 | ||
dc19e98d TB |
325 | def __repr__(self): |
326 | return '<{klass} #{id} {author} "{comment}">'.format( | |
327 | klass=self.__class__.__name__, | |
328 | id=self.id, | |
329 | author=self.get_author, | |
330 | comment=self.content) | |
331 | ||
be5be115 | 332 | |
455fd36f | 333 | class CollectionMixin(GenerateSlugMixin): |
0421fc5e JT |
334 | object_type = "collection" |
335 | ||
455fd36f | 336 | def check_slug_used(self, slug): |
be5be115 AW |
337 | # import this here due to a cyclic import issue |
338 | # (db.models -> db.mixin -> db.util -> db.models) | |
339 | from mediagoblin.db.util import check_collection_slug_used | |
340 | ||
455fd36f | 341 | return check_collection_slug_used(self.creator, slug, self.id) |
be5be115 AW |
342 | |
343 | @property | |
344 | def description_html(self): | |
345 | """ | |
346 | Rendered version of the description, run through | |
347 | Markdown and cleaned with our cleaning tool. | |
348 | """ | |
349 | return cleaned_markdown_conversion(self.description) | |
350 | ||
351 | @property | |
352 | def slug_or_id(self): | |
5c2b8486 | 353 | return (self.slug or self.id) |
be5be115 AW |
354 | |
355 | def url_for_self(self, urlgen, **extra_args): | |
356 | """ | |
357 | Generate an appropriate url for ourselves | |
358 | ||
5c2b8486 | 359 | Use a slug if we have one, else use our 'id'. |
be5be115 AW |
360 | """ |
361 | creator = self.get_creator | |
362 | ||
363 | return urlgen( | |
256f816f | 364 | 'mediagoblin.user_pages.user_collection', |
be5be115 AW |
365 | user=creator.username, |
366 | collection=self.slug_or_id, | |
367 | **extra_args) | |
368 | ||
6d1e55b2 | 369 | |
be5be115 AW |
370 | class CollectionItemMixin(object): |
371 | @property | |
372 | def note_html(self): | |
373 | """ | |
374 | the actual html-rendered version of the note displayed. | |
375 | Run through Markdown and the HTML cleaner. | |
376 | """ | |
377 | return cleaned_markdown_conversion(self.note) | |
ce46470c JT |
378 | |
379 | class ActivityMixin(object): | |
0421fc5e | 380 | object_type = "activity" |
ce46470c JT |
381 | |
382 | VALID_VERBS = ["add", "author", "create", "delete", "dislike", "favorite", | |
383 | "follow", "like", "post", "share", "unfavorite", "unfollow", | |
384 | "unlike", "unshare", "update", "tag"] | |
385 | ||
386 | def get_url(self, request): | |
387 | return request.urlgen( | |
388 | "mediagoblin.federation.activity_view", | |
389 | username=self.get_actor.username, | |
390 | id=self.id, | |
391 | qualified=True | |
392 | ) | |
393 | ||
394 | def generate_content(self): | |
395 | """ Produces a HTML content for object """ | |
396 | # some of these have simple and targetted. If self.target it set | |
397 | # it will pick the targetted. If they DON'T have a targetted version | |
398 | # the information in targetted won't be added to the content. | |
399 | verb_to_content = { | |
400 | "add": { | |
401 | "simple" : _("{username} added {object}"), | |
402 | "targetted": _("{username} added {object} to {target}"), | |
403 | }, | |
404 | "author": {"simple": _("{username} authored {object}")}, | |
405 | "create": {"simple": _("{username} created {object}")}, | |
406 | "delete": {"simple": _("{username} deleted {object}")}, | |
407 | "dislike": {"simple": _("{username} disliked {object}")}, | |
408 | "favorite": {"simple": _("{username} favorited {object}")}, | |
409 | "follow": {"simple": _("{username} followed {object}")}, | |
410 | "like": {"simple": _("{username} liked {object}")}, | |
411 | "post": { | |
412 | "simple": _("{username} posted {object}"), | |
413 | "targetted": _("{username} posted {object} to {targetted}"), | |
414 | }, | |
415 | "share": {"simple": _("{username} shared {object}")}, | |
416 | "unfavorite": {"simple": _("{username} unfavorited {object}")}, | |
417 | "unfollow": {"simple": _("{username} stopped following {object}")}, | |
418 | "unlike": {"simple": _("{username} unliked {object}")}, | |
419 | "unshare": {"simple": _("{username} unshared {object}")}, | |
420 | "update": {"simple": _("{username} updated {object}")}, | |
421 | "tag": {"simple": _("{username} tagged {object}")}, | |
422 | } | |
423 | ||
424 | obj = self.get_object() | |
425 | target = self.get_target() | |
426 | actor = self.get_actor | |
427 | content = verb_to_content.get(self.verb, None) | |
428 | ||
429 | if content is None or obj is None: | |
430 | return | |
431 | ||
432 | if target is None or "targetted" not in content: | |
433 | self.content = content["simple"].format( | |
434 | username=actor.username, | |
435 | object=obj.objectType | |
436 | ) | |
437 | else: | |
438 | self.content = content["targetted"].format( | |
439 | username=actor.username, | |
440 | object=obj.objectType, | |
441 | target=target.objectType, | |
442 | ) | |
443 | ||
444 | return self.content | |
445 | ||
446 | def serialize(self, request): | |
447 | obj = { | |
448 | "id": self.id, | |
449 | "actor": self.get_actor.serialize(request), | |
450 | "verb": self.verb, | |
451 | "published": self.published.isoformat(), | |
452 | "updated": self.updated.isoformat(), | |
453 | "content": self.content, | |
454 | "url": self.get_url(request), | |
0421fc5e JT |
455 | "object": self.get_object().serialize(request), |
456 | "objectType": self.object_type, | |
ce46470c JT |
457 | } |
458 | ||
459 | if self.generator: | |
460 | obj["generator"] = self.get_generator.seralize(request) | |
461 | ||
462 | if self.title: | |
463 | obj["title"] = self.title | |
464 | ||
465 | target = self.get_target() | |
466 | if target is not None: | |
467 | obj["target"] = target.seralize(request) | |
468 | ||
469 | return obj | |
470 | ||
471 | def unseralize(self, data): | |
472 | """ | |
473 | Takes data given and set it on this activity. | |
474 | ||
475 | Several pieces of data are not written on because of security | |
476 | reasons. For example changing the author or id of an activity. | |
477 | """ | |
478 | if "verb" in data: | |
479 | self.verb = data["verb"] | |
480 | ||
481 | if "title" in data: | |
482 | self.title = data["title"] | |
483 | ||
484 | if "content" in data: | |
485 | self.content = data["content"] |