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 JW |
31 | import re |
32 | import datetime | |
72bb46c7 | 33 | |
2d7b6bde JW |
34 | from datetime import datetime |
35 | ||
5f8b4ae8 SS |
36 | from werkzeug.utils import cached_property |
37 | ||
814334f6 | 38 | from mediagoblin import mg_globals |
5f8b4ae8 | 39 | from mediagoblin.media_types import get_media_managers, FileTypeNotSupported |
17c23e15 | 40 | from mediagoblin.tools import common, licenses |
e61ab099 | 41 | from mediagoblin.tools.text import cleaned_markdown_conversion |
814334f6 | 42 | from mediagoblin.tools.url import slugify |
f42e49c3 E |
43 | |
44 | ||
45 | class UserMixin(object): | |
e61ab099 E |
46 | @property |
47 | def bio_html(self): | |
48 | return cleaned_markdown_conversion(self.bio) | |
49 | ||
f42e49c3 | 50 | |
29c65044 | 51 | class GenerateSlugMixin(object): |
44123853 E |
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 | """ | |
814334f6 | 60 | def generate_slug(self): |
88de830f | 61 | """ |
44123853 | 62 | Generate a unique slug for this object. |
98587109 | 63 | |
88de830f CAW |
64 | This one does not *force* slugs, but usually it will probably result |
65 | in a niceish one. | |
66 | ||
98587109 CAW |
67 | The end *result* of the algorithm will result in these resolutions for |
68 | these situations: | |
88de830f CAW |
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 | """ | |
66d9f1b2 SS |
83 | #Is already a slug assigned? Check if it is valid |
84 | if self.slug: | |
85 | self.slug = slugify(self.slug) | |
b1126f71 | 86 | |
88de830f | 87 | # otherwise, try to use the title. |
66d9f1b2 | 88 | elif self.title: |
88de830f | 89 | # assign slug based on title |
66d9f1b2 | 90 | self.slug = slugify(self.title) |
b1126f71 | 91 | |
b0118957 CAW |
92 | # We don't want any empty string slugs |
93 | if self.slug == u"": | |
94 | self.slug = None | |
95 | ||
88de830f CAW |
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! | |
b1126f71 | 101 | |
88de830f | 102 | # Otherwise, let's see if this is unique. |
29c65044 | 103 | if self.check_slug_used(self.slug): |
88de830f | 104 | # It looks like it's being used... lame. |
b1126f71 | 105 | |
88de830f CAW |
106 | # Can we just append the object's id to the end? |
107 | if self.id: | |
98587109 | 108 | slug_with_id = u"%s-%s" % (self.slug, self.id) |
29c65044 | 109 | if not self.check_slug_used(slug_with_id): |
88de830f CAW |
110 | self.slug = slug_with_id |
111 | return # success! | |
b1126f71 | 112 | |
88de830f CAW |
113 | # okay, still no success; |
114 | # let's whack junk on there till it's unique. | |
a81082fc CAW |
115 | self.slug += '-' + uuid.uuid4().hex[:4] |
116 | # keep going if necessary! | |
29c65044 | 117 | while self.check_slug_used(self.slug): |
a81082fc | 118 | self.slug += uuid.uuid4().hex[:4] |
814334f6 | 119 | |
29c65044 E |
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 | ||
1e72e075 E |
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 | ||
e77df64f CAW |
137 | def get_display_media(self): |
138 | """Find the best media for display. | |
f42e49c3 | 139 | |
53024776 | 140 | We try checking self.media_manager.fetching_order if it exists to |
e77df64f | 141 | pull down the order. |
f42e49c3 E |
142 | |
143 | Returns: | |
ddbf6af1 CAW |
144 | (media_size, media_path) |
145 | or, if not found, None. | |
e77df64f | 146 | |
f42e49c3 | 147 | """ |
e8676fa3 | 148 | fetch_order = self.media_manager.media_fetch_order |
f42e49c3 | 149 | |
ddbf6af1 CAW |
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: | |
f42e49c3 | 157 | if media_size in media_sizes: |
ddbf6af1 | 158 | return media_size, self.media_files[media_size] |
f42e49c3 E |
159 | |
160 | def main_mediafile(self): | |
161 | pass | |
162 | ||
3e907d55 E |
163 | @property |
164 | def slug_or_id(self): | |
7de20e52 CAW |
165 | if self.slug: |
166 | return self.slug | |
167 | else: | |
168 | return u'id:%s' % self.id | |
5f8b4ae8 | 169 | |
cb7ae1e4 | 170 | def url_for_self(self, urlgen, **extra_args): |
f42e49c3 E |
171 | """ |
172 | Generate an appropriate url for ourselves | |
173 | ||
5c2b8486 | 174 | Use a slug if we have one, else use our 'id'. |
f42e49c3 E |
175 | """ |
176 | uploader = self.get_uploader | |
177 | ||
3e907d55 E |
178 | return urlgen( |
179 | 'mediagoblin.user_pages.media_home', | |
180 | user=uploader.username, | |
181 | media=self.slug_or_id, | |
182 | **extra_args) | |
f42e49c3 | 183 | |
2e4ad359 SS |
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: | |
df1c4976 | 194 | # No thumbnail in media available. Get the media's |
2e4ad359 | 195 | # MEDIA_MANAGER for the fallback icon and return static URL |
5f8b4ae8 SS |
196 | # Raises FileTypeNotSupported in case no such manager is enabled |
197 | manager = self.media_manager | |
df1c4976 | 198 | thumb_url = mg_globals.app.staticdirector(manager[u'default_thumb']) |
2e4ad359 SS |
199 | return thumb_url |
200 | ||
5f8b4ae8 SS |
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: | |
2077d6ed | 211 | return manager(self) |
5f8b4ae8 SS |
212 | # Not found? Then raise an error |
213 | raise FileTypeNotSupported( | |
214 | "MediaManager not in enabled types. Check media_types in config?") | |
215 | ||
f42e49c3 E |
216 | def get_fail_exception(self): |
217 | """ | |
218 | Get the exception that's appropriate for this error | |
219 | """ | |
51eb0267 JW |
220 | if self.fail_error: |
221 | return common.import_component(self.fail_error) | |
17c23e15 AW |
222 | |
223 | def get_license_data(self): | |
224 | """Return license dict for requested license""" | |
138a18fd | 225 | return licenses.get_license_by_url(self.license or "") |
feba5c52 | 226 | |
5bad26bc E |
227 | def exif_display_iter(self): |
228 | if not self.media_data: | |
229 | return | |
230 | exif_all = self.media_data.get("exif_all") | |
231 | ||
b3566e1d GS |
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] | |
5bad26bc | 235 | |
420e1374 GS |
236 | def exif_display_data_short(self): |
237 | """Display a very short practical version of exif info""" | |
420e1374 GS |
238 | if not self.media_data: |
239 | return | |
907bba31 | 240 | |
420e1374 | 241 | exif_all = self.media_data.get("exif_all") |
907bba31 | 242 | |
14aa2eaa JW |
243 | exif_short = {} |
244 | ||
907bba31 JW |
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 | ||
14aa2eaa JW |
252 | exif_short.update({'Date Taken': taken}) |
253 | ||
1b6a2b85 | 254 | aperture = None |
907bba31 JW |
255 | if 'EXIF FNumber' in exif_all: |
256 | fnum = str(exif_all['EXIF FNumber']['printable']).split('/') | |
257 | ||
1b6a2b85 JW |
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]) | |
907bba31 | 263 | |
14aa2eaa JW |
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 | ||
feba5c52 E |
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) | |
be5be115 | 292 | |
2d7b6bde JW |
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 | ||
be5be115 | 300 | |
455fd36f E |
301 | class CollectionMixin(GenerateSlugMixin): |
302 | def check_slug_used(self, slug): | |
be5be115 AW |
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 | ||
455fd36f | 307 | return check_collection_slug_used(self.creator, slug, self.id) |
be5be115 AW |
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): | |
5c2b8486 | 319 | return (self.slug or self.id) |
be5be115 AW |
320 | |
321 | def url_for_self(self, urlgen, **extra_args): | |
322 | """ | |
323 | Generate an appropriate url for ourselves | |
324 | ||
5c2b8486 | 325 | Use a slug if we have one, else use our 'id'. |
be5be115 AW |
326 | """ |
327 | creator = self.get_creator | |
328 | ||
329 | return urlgen( | |
256f816f | 330 | 'mediagoblin.user_pages.user_collection', |
be5be115 AW |
331 | user=creator.username, |
332 | collection=self.slug_or_id, | |
333 | **extra_args) | |
334 | ||
6d1e55b2 | 335 | |
be5be115 AW |
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) |