1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
18 This module contains some Mixin classes for the db objects.
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.
26 These functions now live here and get "mixed in" into the
32 from datetime
import datetime
34 from werkzeug
.utils
import cached_property
36 from mediagoblin
import mg_globals
37 from mediagoblin
.media_types
import FileTypeNotSupported
38 from mediagoblin
.tools
import common
, licenses
39 from mediagoblin
.tools
.pluginapi
import hook_handle
40 from mediagoblin
.tools
.text
import cleaned_markdown_conversion
41 from mediagoblin
.tools
.url
import slugify
42 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
45 class UserMixin(object):
46 object_type
= "person"
50 return cleaned_markdown_conversion(self
.bio
)
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
)
58 class GenerateSlugMixin(object):
60 Mixin to add a generate_slug method to objects.
65 - self.check_slug_used(new_slug)
67 def generate_slug(self
):
69 Generate a unique slug for this object.
71 This one does not *force* slugs, but usually it will probably result
74 The end *result* of the algorithm will result in these resolutions for
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.
90 #Is already a slug assigned? Check if it is valid
92 self
.slug
= slugify(self
.slug
)
94 # otherwise, try to use the title.
96 # assign slug based on title
97 self
.slug
= slugify(self
.title
)
99 # We don't want any empty string slugs
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.
109 # Otherwise, let's see if this is unique.
110 if self
.check_slug_used(self
.slug
):
111 # It looks like it's being used... lame.
113 # Can we just append the object's id to the end?
115 slug_with_id
= u
"%s-%s" % (self
.slug
, self
.id)
116 if not self
.check_slug_used(slug_with_id
):
117 self
.slug
= slug_with_id
120 # okay, still no success;
121 # let's whack junk on there till it's unique.
122 self
.slug
+= '-' + uuid
.uuid4().hex[:4]
123 # keep going if necessary!
124 while self
.check_slug_used(self
.slug
):
125 self
.slug
+= uuid
.uuid4().hex[:4]
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
134 return check_media_slug_used(self
.uploader
, slug
, self
.id)
137 def object_type(self
):
138 """ Converts media_type to pump-like type - don't use internally """
139 return self
.media_type
.split(".")[-1]
142 def description_html(self
):
144 Rendered version of the description, run through
145 Markdown and cleaned with our cleaning tool.
147 return cleaned_markdown_conversion(self
.description
)
149 def get_display_media(self
):
150 """Find the best media for display.
152 We try checking self.media_manager.fetching_order if it exists to
156 (media_size, media_path)
157 or, if not found, None.
160 fetch_order
= self
.media_manager
.media_fetch_order
162 # No fetching order found? well, give up!
166 media_sizes
= self
.media_files
.keys()
168 for media_size
in fetch_order
:
169 if media_size
in media_sizes
:
170 return media_size
, self
.media_files
[media_size
]
172 def main_mediafile(self
):
176 def slug_or_id(self
):
180 return u
'id:%s' % self
.id
182 def url_for_self(self
, urlgen
, **extra_args
):
184 Generate an appropriate url for ourselves
186 Use a slug if we have one, else use our 'id'.
188 uploader
= self
.get_uploader
191 'mediagoblin.user_pages.media_home',
192 user
=uploader
.username
,
193 media
=self
.slug_or_id
,
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
202 if u
'thumb' in self
.media_files
:
203 thumb_url
= mg_globals
.app
.public_store
.file_url(
204 self
.media_files
[u
'thumb'])
206 # No thumbnail in media available. Get the media's
207 # MEDIA_MANAGER for the fallback icon and return static URL
208 # Raises FileTypeNotSupported in case no such manager is enabled
209 manager
= self
.media_manager
210 thumb_url
= mg_globals
.app
.staticdirector(manager
[u
'default_thumb'])
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
220 return mg_globals
.app
.public_store
.file_url(
221 self
.media_files
[u
"original"]
225 def media_manager(self
):
226 """Returns the MEDIA_MANAGER of the media's media_type
228 Raises FileTypeNotSupported in case no such manager is enabled
230 manager
= hook_handle(('media_manager', self
.media_type
))
234 # Not found? Then raise an error
235 raise FileTypeNotSupported(
236 "MediaManager not in enabled types. Check media_type plugins are"
237 " enabled in config?")
239 def get_fail_exception(self
):
241 Get the exception that's appropriate for this error
244 return common
.import_component(self
.fail_error
)
246 def get_license_data(self
):
247 """Return license dict for requested license"""
248 return licenses
.get_license_by_url(self
.license
or "")
250 def exif_display_iter(self
):
251 if not self
.media_data
:
253 exif_all
= self
.media_data
.get("exif_all")
256 label
= re
.sub('(.)([A-Z][a-z]+)', r
'\1 \2', key
)
257 yield label
.replace('EXIF', '').replace('Image', ''), exif_all
[key
]
259 def exif_display_data_short(self
):
260 """Display a very short practical version of exif info"""
261 if not self
.media_data
:
264 exif_all
= self
.media_data
.get("exif_all")
268 if 'Image DateTimeOriginal' in exif_all
:
270 takendate
= datetime
.strptime(
271 exif_all
['Image DateTimeOriginal']['printable'],
272 '%Y:%m:%d %H:%M:%S').date()
273 taken
= takendate
.strftime('%B %d %Y')
275 exif_short
.update({'Date Taken': taken
})
278 if 'EXIF FNumber' in exif_all
:
279 fnum
= str(exif_all
['EXIF FNumber']['printable']).split('/')
283 aperture
= "f/%.1f" % (float(fnum
[0])/float(fnum
[1]))
284 elif fnum
[0] != 'None':
285 aperture
= "f/%s" % (fnum
[0])
288 exif_short
.update({'Aperture': aperture
})
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
)]
296 for label
, key
, fmt_func
in short_keys
:
298 val
= fmt_func(exif_all
[key
]['printable']) if fmt_func \
299 else exif_all
[key
]['printable']
300 exif_short
.update({label
: val
})
307 class MediaCommentMixin(object):
308 object_type
= "comment"
311 def content_html(self
):
313 the actual html-rendered version of the comment displayed.
314 Run through Markdown and the HTML cleaner.
316 return cleaned_markdown_conversion(self
.content
)
318 def __unicode__(self
):
319 return u
'<{klass} #{id} {author} "{comment}">'.format(
320 klass
=self
.__class
__.__name
__,
322 author
=self
.get_author
,
323 comment
=self
.content
)
326 return '<{klass} #{id} {author} "{comment}">'.format(
327 klass
=self
.__class
__.__name
__,
329 author
=self
.get_author
,
330 comment
=self
.content
)
333 class CollectionMixin(GenerateSlugMixin
):
334 object_type
= "collection"
336 def check_slug_used(self
, slug
):
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
341 return check_collection_slug_used(self
.creator
, slug
, self
.id)
344 def description_html(self
):
346 Rendered version of the description, run through
347 Markdown and cleaned with our cleaning tool.
349 return cleaned_markdown_conversion(self
.description
)
352 def slug_or_id(self
):
353 return (self
.slug
or self
.id)
355 def url_for_self(self
, urlgen
, **extra_args
):
357 Generate an appropriate url for ourselves
359 Use a slug if we have one, else use our 'id'.
361 creator
= self
.get_creator
364 'mediagoblin.user_pages.user_collection',
365 user
=creator
.username
,
366 collection
=self
.slug_or_id
,
370 class CollectionItemMixin(object):
374 the actual html-rendered version of the note displayed.
375 Run through Markdown and the HTML cleaner.
377 return cleaned_markdown_conversion(self
.note
)
379 class ActivityMixin(object):
380 object_type
= "activity"
382 VALID_VERBS
= ["add", "author", "create", "delete", "dislike", "favorite",
383 "follow", "like", "post", "share", "unfavorite", "unfollow",
384 "unlike", "unshare", "update", "tag"]
386 def get_url(self
, request
):
387 return request
.urlgen(
388 "mediagoblin.federation.activity_view",
389 username
=self
.get_actor
.username
,
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.
401 "simple" : _("{username} added {object}"),
402 "targetted": _("{username} added {object} to {target}"),
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}")},
412 "simple": _("{username} posted {object}"),
413 "targetted": _("{username} posted {object} to {targetted}"),
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}")},
424 obj
= self
.get_object()
425 target
= self
.get_target()
426 actor
= self
.get_actor
427 content
= verb_to_content
.get(self
.verb
, None)
429 if content
is None or obj
is None:
432 if target
is None or "targetted" not in content
:
433 self
.content
= content
["simple"].format(
434 username
=actor
.username
,
435 object=obj
.objectType
438 self
.content
= content
["targetted"].format(
439 username
=actor
.username
,
440 object=obj
.objectType
,
441 target
=target
.objectType
,
446 def serialize(self
, request
):
449 "actor": self
.get_actor
.serialize(request
),
451 "published": self
.published
.isoformat(),
452 "updated": self
.updated
.isoformat(),
453 "content": self
.content
,
454 "url": self
.get_url(request
),
455 "object": self
.get_object().serialize(request
),
456 "objectType": self
.object_type
,
460 obj
["generator"] = self
.get_generator
.seralize(request
)
463 obj
["title"] = self
.title
465 target
= self
.get_target()
466 if target
is not None:
467 obj
["target"] = target
.seralize(request
)
471 def unseralize(self
, data
):
473 Takes data given and set it on this activity.
475 Several pieces of data are not written on because of security
476 reasons. For example changing the author or id of an activity.
479 self
.verb
= data
["verb"]
482 self
.title
= data
["title"]
484 if "content" in data
:
485 self
.content
= data
["content"]