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
32 from werkzeug
.utils
import cached_property
34 from mediagoblin
import mg_globals
35 from mediagoblin
.auth
import lib
as auth_lib
36 from mediagoblin
.media_types
import get_media_managers
, FileTypeNotSupported
37 from mediagoblin
.tools
import common
, licenses
38 from mediagoblin
.tools
.text
import cleaned_markdown_conversion
39 from mediagoblin
.tools
.url
import slugify
42 class UserMixin(object):
43 def check_login(self
, password
):
45 See if a user can login with this password
47 return auth_lib
.bcrypt_check_password(
48 password
, self
.pw_hash
)
52 return cleaned_markdown_conversion(self
.bio
)
55 class MediaEntryMixin(object):
56 def generate_slug(self
):
58 Generate a unique slug for this MediaEntry.
60 This one does not *force* slugs, but usually it will probably result
63 The end *result* of the algorithm will result in these resolutions for
65 - If we have a slug, make sure it's clean and sanitized, and if it's
66 unique, we'll use that.
67 - If we have a title, slugify it, and if it's unique, we'll use that.
68 - If we can't get any sort of thing that looks like it'll be a useful
69 slug out of a title or an existing slug, bail, and don't set the
70 slug at all. Don't try to create something just because. Make
71 sure we have a reasonable basis for a slug first.
72 - If we have a reasonable basis for a slug (either based on existing
73 slug or slugified title) but it's not unique, first try appending
74 the entry's id, if that exists
75 - If that doesn't result in something unique, tack on some randomly
76 generated bits until it's unique. That'll be a little bit of junk,
77 but at least it has the basis of a nice slug.
79 # import this here due to a cyclic import issue
80 # (db.models -> db.mixin -> db.util -> db.models)
81 from mediagoblin
.db
.util
import check_media_slug_used
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 check_media_slug_used(self
.uploader
, self
.slug
, self
.id):
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 check_media_slug_used(self
.uploader
,
110 slug_with_id
, self
.id):
111 self
.slug
= slug_with_id
114 # okay, still no success;
115 # let's whack junk on there till it's unique.
116 self
.slug
+= '-' + uuid
.uuid4().hex[:4]
117 # keep going if necessary!
118 while check_media_slug_used(self
.uploader
, self
.slug
, self
.id):
119 self
.slug
+= uuid
.uuid4().hex[:4]
122 def description_html(self
):
124 Rendered version of the description, run through
125 Markdown and cleaned with our cleaning tool.
127 return cleaned_markdown_conversion(self
.description
)
129 def get_display_media(self
):
130 """Find the best media for display.
132 We try checking self.media_manager.fetching_order if it exists to
136 (media_size, media_path)
137 or, if not found, None.
140 fetch_order
= self
.media_manager
.get("media_fetch_order")
142 # No fetching order found? well, give up!
146 media_sizes
= self
.media_files
.keys()
148 for media_size
in fetch_order
:
149 if media_size
in media_sizes
:
150 return media_size
, self
.media_files
[media_size
]
152 def main_mediafile(self
):
156 def slug_or_id(self
):
160 return u
'id:%s' % self
.id
162 def url_for_self(self
, urlgen
, **extra_args
):
164 Generate an appropriate url for ourselves
166 Use a slug if we have one, else use our 'id'.
168 uploader
= self
.get_uploader
171 'mediagoblin.user_pages.media_home',
172 user
=uploader
.username
,
173 media
=self
.slug_or_id
,
178 """Return the thumbnail URL (for usage in templates)
179 Will return either the real thumbnail or a default fallback icon."""
180 # TODO: implement generic fallback in case MEDIA_MANAGER does
182 if u
'thumb' in self
.media_files
:
183 thumb_url
= mg_globals
.app
.public_store
.file_url(
184 self
.media_files
[u
'thumb'])
186 # No thumbnail in media available. Get the media's
187 # MEDIA_MANAGER for the fallback icon and return static URL
188 # Raises FileTypeNotSupported in case no such manager is enabled
189 manager
= self
.media_manager
190 thumb_url
= mg_globals
.app
.staticdirector(manager
[u
'default_thumb'])
194 def media_manager(self
):
195 """Returns the MEDIA_MANAGER of the media's media_type
197 Raises FileTypeNotSupported in case no such manager is enabled
199 # TODO, we should be able to make this a simple lookup rather
200 # than iterating through all media managers.
201 for media_type
, manager
in get_media_managers():
202 if media_type
== self
.media_type
:
204 # Not found? Then raise an error
205 raise FileTypeNotSupported(
206 "MediaManager not in enabled types. Check media_types in config?")
208 def get_fail_exception(self
):
210 Get the exception that's appropriate for this error
213 return common
.import_component(self
.fail_error
)
215 def get_license_data(self
):
216 """Return license dict for requested license"""
217 return licenses
.get_license_by_url(self
.license
or "")
219 def exif_display_iter(self
):
220 from mediagoblin
.tools
.exif
import USEFUL_TAGS
222 if not self
.media_data
:
224 exif_all
= self
.media_data
.get("exif_all")
226 for key
in USEFUL_TAGS
:
228 yield key
, exif_all
[key
]
231 class MediaCommentMixin(object):
233 def content_html(self
):
235 the actual html-rendered version of the comment displayed.
236 Run through Markdown and the HTML cleaner.
238 return cleaned_markdown_conversion(self
.content
)
241 class CollectionMixin(object):
242 def generate_slug(self
):
243 # import this here due to a cyclic import issue
244 # (db.models -> db.mixin -> db.util -> db.models)
245 from mediagoblin
.db
.util
import check_collection_slug_used
247 self
.slug
= slugify(self
.title
)
249 duplicate
= check_collection_slug_used(mg_globals
.database
,
250 self
.creator
, self
.slug
, self
.id)
253 if self
.id is not None:
254 self
.slug
= u
"%s-%s" % (self
.id, self
.slug
)
259 def description_html(self
):
261 Rendered version of the description, run through
262 Markdown and cleaned with our cleaning tool.
264 return cleaned_markdown_conversion(self
.description
)
267 def slug_or_id(self
):
268 return (self
.slug
or self
.id)
270 def url_for_self(self
, urlgen
, **extra_args
):
272 Generate an appropriate url for ourselves
274 Use a slug if we have one, else use our 'id'.
276 creator
= self
.get_creator
279 'mediagoblin.user_pages.user_collection',
280 user
=creator
.username
,
281 collection
=self
.slug_or_id
,
285 class CollectionItemMixin(object):
289 the actual html-rendered version of the note displayed.
290 Run through Markdown and the HTML cleaner.
292 return cleaned_markdown_conversion(self
.note
)