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