Patch by Strum. Ticket #451 - Convert all mongokit style .find, .find_one, .one calls...
[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 datetime import datetime
35
36 from werkzeug.utils import cached_property
37
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
43
44
45 class UserMixin(object):
46 @property
47 def bio_html(self):
48 return cleaned_markdown_conversion(self.bio)
49
50
51 class GenerateSlugMixin(object):
52 """
53 Mixin to add a generate_slug method to objects.
54
55 Depends on:
56 - self.slug
57 - self.title
58 - self.check_slug_used(new_slug)
59 """
60 def generate_slug(self):
61 """
62 Generate a unique slug for this object.
63
64 This one does not *force* slugs, but usually it will probably result
65 in a niceish one.
66
67 The end *result* of the algorithm will result in these resolutions for
68 these situations:
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.
82 """
83 #Is already a slug assigned? Check if it is valid
84 if self.slug:
85 self.slug = slugify(self.slug)
86
87 # otherwise, try to use the title.
88 elif self.title:
89 # assign slug based on title
90 self.slug = slugify(self.title)
91
92 # We don't want any empty string slugs
93 if self.slug == u"":
94 self.slug = None
95
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.
99 if not self.slug:
100 return # giving up!
101
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.
105
106 # Can we just append the object's id to the end?
107 if self.id:
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
111 return # success!
112
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]
119
120
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
126
127 return check_media_slug_used(self.uploader, slug, self.id)
128
129 @property
130 def description_html(self):
131 """
132 Rendered version of the description, run through
133 Markdown and cleaned with our cleaning tool.
134 """
135 return cleaned_markdown_conversion(self.description)
136
137 def get_display_media(self):
138 """Find the best media for display.
139
140 We try checking self.media_manager.fetching_order if it exists to
141 pull down the order.
142
143 Returns:
144 (media_size, media_path)
145 or, if not found, None.
146
147 """
148 fetch_order = self.media_manager.media_fetch_order
149
150 # No fetching order found? well, give up!
151 if not fetch_order:
152 return None
153
154 media_sizes = self.media_files.keys()
155
156 for media_size in fetch_order:
157 if media_size in media_sizes:
158 return media_size, self.media_files[media_size]
159
160 def main_mediafile(self):
161 pass
162
163 @property
164 def slug_or_id(self):
165 if self.slug:
166 return self.slug
167 else:
168 return u'id:%s' % self.id
169
170 def url_for_self(self, urlgen, **extra_args):
171 """
172 Generate an appropriate url for ourselves
173
174 Use a slug if we have one, else use our 'id'.
175 """
176 uploader = self.get_uploader
177
178 return urlgen(
179 'mediagoblin.user_pages.media_home',
180 user=uploader.username,
181 media=self.slug_or_id,
182 **extra_args)
183
184 @property
185 def thumb_url(self):
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
189 # not specify one?
190 if u'thumb' in self.media_files:
191 thumb_url = mg_globals.app.public_store.file_url(
192 self.media_files[u'thumb'])
193 else:
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'])
199 return thumb_url
200
201 @cached_property
202 def media_manager(self):
203 """Returns the MEDIA_MANAGER of the media's media_type
204
205 Raises FileTypeNotSupported in case no such manager is enabled
206 """
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:
211 return manager(self)
212 # Not found? Then raise an error
213 raise FileTypeNotSupported(
214 "MediaManager not in enabled types. Check media_types in config?")
215
216 def get_fail_exception(self):
217 """
218 Get the exception that's appropriate for this error
219 """
220 if self.fail_error:
221 return common.import_component(self.fail_error)
222
223 def get_license_data(self):
224 """Return license dict for requested license"""
225 return licenses.get_license_by_url(self.license or "")
226
227 def exif_display_iter(self):
228 if not self.media_data:
229 return
230 exif_all = self.media_data.get("exif_all")
231
232 for key in exif_all:
233 label = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', key)
234 yield label.replace('EXIF', '').replace('Image', ''), exif_all[key]
235
236 def exif_display_data_short(self):
237 """Display a very short practical version of exif info"""
238 if not self.media_data:
239 return
240
241 exif_all = self.media_data.get("exif_all")
242
243 exif_short = {}
244
245 if 'Image DateTimeOriginal' in exif_all:
246 # format date taken
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')
251
252 exif_short.update({'Date Taken': taken})
253
254 aperture = None
255 if 'EXIF FNumber' in exif_all:
256 fnum = str(exif_all['EXIF FNumber']['printable']).split('/')
257
258 # calculate aperture
259 if len(fnum) == 2:
260 aperture = "f/%.1f" % (float(fnum[0])/float(fnum[1]))
261 elif fnum[0] != 'None':
262 aperture = "f/%s" % (fnum[0])
263
264 if aperture:
265 exif_short.update({'Aperture': aperture})
266
267 short_keys = [
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)]
272
273 for label, key, fmt_func in short_keys:
274 try:
275 val = fmt_func(exif_all[key]['printable']) if fmt_func \
276 else exif_all[key]['printable']
277 exif_short.update({label: val})
278 except KeyError:
279 pass
280
281 return exif_short
282
283
284 class MediaCommentMixin(object):
285 @property
286 def content_html(self):
287 """
288 the actual html-rendered version of the comment displayed.
289 Run through Markdown and the HTML cleaner.
290 """
291 return cleaned_markdown_conversion(self.content)
292
293 def __repr__(self):
294 return '<{klass} #{id} {author} "{comment}">'.format(
295 klass=self.__class__.__name__,
296 id=self.id,
297 author=self.get_author,
298 comment=self.content)
299
300
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
306
307 return check_collection_slug_used(self.creator, slug, self.id)
308
309 @property
310 def description_html(self):
311 """
312 Rendered version of the description, run through
313 Markdown and cleaned with our cleaning tool.
314 """
315 return cleaned_markdown_conversion(self.description)
316
317 @property
318 def slug_or_id(self):
319 return (self.slug or self.id)
320
321 def url_for_self(self, urlgen, **extra_args):
322 """
323 Generate an appropriate url for ourselves
324
325 Use a slug if we have one, else use our 'id'.
326 """
327 creator = self.get_creator
328
329 return urlgen(
330 'mediagoblin.user_pages.user_collection',
331 user=creator.username,
332 collection=self.slug_or_id,
333 **extra_args)
334
335
336 class CollectionItemMixin(object):
337 @property
338 def note_html(self):
339 """
340 the actual html-rendered version of the note displayed.
341 Run through Markdown and the HTML cleaner.
342 """
343 return cleaned_markdown_conversion(self.note)