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