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
34 from datetime
import datetime
36 from werkzeug
.utils
import cached_property
38 from mediagoblin
import mg_globals
39 from mediagoblin
.media_types
import get_media_managers
, FileTypeNotSupported
40 from mediagoblin
.tools
import common
, licenses
41 from mediagoblin
.tools
.text
import cleaned_markdown_conversion
42 from mediagoblin
.tools
.url
import slugify
45 class UserMixin(object):
48 return cleaned_markdown_conversion(self
.bio
)
51 class GenerateSlugMixin(object):
53 Mixin to add a generate_slug method to objects.
58 - self.check_slug_used(new_slug)
60 def generate_slug(self
):
62 Generate a unique slug for this object.
64 This one does not *force* slugs, but usually it will probably result
67 The end *result* of the algorithm will result in these resolutions for
69 - If we have a slug, make sure it's clean and sanitized, and if it's
70 unique, we'll use that.
71 - If we have a title, slugify it, and if it's unique, we'll use that.
72 - If we can't get any sort of thing that looks like it'll be a useful
73 slug out of a title or an existing slug, bail, and don't set the
74 slug at all. Don't try to create something just because. Make
75 sure we have a reasonable basis for a slug first.
76 - If we have a reasonable basis for a slug (either based on existing
77 slug or slugified title) but it's not unique, first try appending
78 the entry's id, if that exists
79 - If that doesn't result in something unique, tack on some randomly
80 generated bits until it's unique. That'll be a little bit of junk,
81 but at least it has the basis of a nice slug.
83 #Is already a slug assigned? Check if it is valid
85 self
.slug
= slugify(self
.slug
)
87 # otherwise, try to use the title.
89 # assign slug based on title
90 self
.slug
= slugify(self
.title
)
92 # We don't want any empty string slugs
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.
102 # Otherwise, let's see if this is unique.
103 if self
.check_slug_used(self
.slug
):
104 # It looks like it's being used... lame.
106 # Can we just append the object's id to the end?
108 slug_with_id
= u
"%s-%s" % (self
.slug
, self
.id)
109 if not self
.check_slug_used(slug_with_id
):
110 self
.slug
= slug_with_id
113 # okay, still no success;
114 # let's whack junk on there till it's unique.
115 self
.slug
+= '-' + uuid
.uuid4().hex[:4]
116 # keep going if necessary!
117 while self
.check_slug_used(self
.slug
):
118 self
.slug
+= uuid
.uuid4().hex[:4]
121 class MediaEntryMixin(GenerateSlugMixin
):
122 def check_slug_used(self
, slug
):
123 # import this here due to a cyclic import issue
124 # (db.models -> db.mixin -> db.util -> db.models)
125 from mediagoblin
.db
.util
import check_media_slug_used
127 return check_media_slug_used(self
.uploader
, slug
, self
.id)
130 def description_html(self
):
132 Rendered version of the description, run through
133 Markdown and cleaned with our cleaning tool.
135 return cleaned_markdown_conversion(self
.description
)
137 def get_display_media(self
):
138 """Find the best media for display.
140 We try checking self.media_manager.fetching_order if it exists to
144 (media_size, media_path)
145 or, if not found, None.
148 fetch_order
= self
.media_manager
.media_fetch_order
150 # No fetching order found? well, give up!
154 media_sizes
= self
.media_files
.keys()
156 for media_size
in fetch_order
:
157 if media_size
in media_sizes
:
158 return media_size
, self
.media_files
[media_size
]
160 def main_mediafile(self
):
164 def slug_or_id(self
):
168 return u
'id:%s' % self
.id
170 def url_for_self(self
, urlgen
, **extra_args
):
172 Generate an appropriate url for ourselves
174 Use a slug if we have one, else use our 'id'.
176 uploader
= self
.get_uploader
179 'mediagoblin.user_pages.media_home',
180 user
=uploader
.username
,
181 media
=self
.slug_or_id
,
186 """Return the thumbnail URL (for usage in templates)
187 Will return either the real thumbnail or a default fallback icon."""
188 # TODO: implement generic fallback in case MEDIA_MANAGER does
190 if u
'thumb' in self
.media_files
:
191 thumb_url
= mg_globals
.app
.public_store
.file_url(
192 self
.media_files
[u
'thumb'])
194 # No thumbnail in media available. Get the media's
195 # MEDIA_MANAGER for the fallback icon and return static URL
196 # Raises FileTypeNotSupported in case no such manager is enabled
197 manager
= self
.media_manager
198 thumb_url
= mg_globals
.app
.staticdirector(manager
[u
'default_thumb'])
202 def media_manager(self
):
203 """Returns the MEDIA_MANAGER of the media's media_type
205 Raises FileTypeNotSupported in case no such manager is enabled
207 # TODO, we should be able to make this a simple lookup rather
208 # than iterating through all media managers.
209 for media_type
, manager
in get_media_managers():
210 if media_type
== self
.media_type
:
212 # Not found? Then raise an error
213 raise FileTypeNotSupported(
214 "MediaManager not in enabled types. Check media_types in config?")
216 def get_fail_exception(self
):
218 Get the exception that's appropriate for this error
221 return common
.import_component(self
.fail_error
)
223 def get_license_data(self
):
224 """Return license dict for requested license"""
225 return licenses
.get_license_by_url(self
.license
or "")
227 def exif_display_iter(self
):
228 if not self
.media_data
:
230 exif_all
= self
.media_data
.get("exif_all")
233 label
= re
.sub('(.)([A-Z][a-z]+)', r
'\1 \2', key
)
234 yield label
.replace('EXIF', '').replace('Image', ''), exif_all
[key
]
236 def exif_display_data_short(self
):
237 """Display a very short practical version of exif info"""
238 if not self
.media_data
:
241 exif_all
= self
.media_data
.get("exif_all")
245 if 'Image DateTimeOriginal' in exif_all
:
247 takendate
= datetime
.datetime
.strptime(
248 exif_all
['Image DateTimeOriginal']['printable'],
249 '%Y:%m:%d %H:%M:%S').date()
250 taken
= takendate
.strftime('%B %d %Y')
252 exif_short
.update({'Date Taken': taken
})
255 if 'EXIF FNumber' in exif_all
:
256 fnum
= str(exif_all
['EXIF FNumber']['printable']).split('/')
260 aperture
= "f/%.1f" % (float(fnum
[0])/float(fnum
[1]))
261 elif fnum
[0] != 'None':
262 aperture
= "f/%s" % (fnum
[0])
265 exif_short
.update({'Aperture': aperture
})
268 ('Camera', 'Image Model', None),
269 ('Exposure', 'EXIF ExposureTime', lambda x
: '%s sec' % x
),
270 ('ISO Speed', 'EXIF ISOSpeedRatings', None),
271 ('Focal Length', 'EXIF FocalLength', lambda x
: '%s mm' % x
)]
273 for label
, key
, fmt_func
in short_keys
:
275 val
= fmt_func(exif_all
[key
]['printable']) if fmt_func \
276 else exif_all
[key
]['printable']
277 exif_short
.update({label
: val
})
284 class MediaCommentMixin(object):
286 def content_html(self
):
288 the actual html-rendered version of the comment displayed.
289 Run through Markdown and the HTML cleaner.
291 return cleaned_markdown_conversion(self
.content
)
294 return '<{klass} #{id} {author} "{comment}">'.format(
295 klass
=self
.__class
__.__name
__,
297 author
=self
.get_author
,
298 comment
=self
.content
)
301 class CollectionMixin(GenerateSlugMixin
):
302 def check_slug_used(self
, slug
):
303 # import this here due to a cyclic import issue
304 # (db.models -> db.mixin -> db.util -> db.models)
305 from mediagoblin
.db
.util
import check_collection_slug_used
307 return check_collection_slug_used(self
.creator
, slug
, self
.id)
310 def description_html(self
):
312 Rendered version of the description, run through
313 Markdown and cleaned with our cleaning tool.
315 return cleaned_markdown_conversion(self
.description
)
318 def slug_or_id(self
):
319 return (self
.slug
or self
.id)
321 def url_for_self(self
, urlgen
, **extra_args
):
323 Generate an appropriate url for ourselves
325 Use a slug if we have one, else use our 'id'.
327 creator
= self
.get_creator
330 'mediagoblin.user_pages.user_collection',
331 user
=creator
.username
,
332 collection
=self
.slug_or_id
,
336 class CollectionItemMixin(object):
340 the actual html-rendered version of the note displayed.
341 Run through Markdown and the HTML cleaner.
343 return cleaned_markdown_conversion(self
.note
)