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 GenerateSlugMixin(object):
57 Mixin to add a generate_slug method to objects.
62 - self.check_slug_used(new_slug)
64 def generate_slug(self
):
66 Generate a unique slug for this object.
68 This one does not *force* slugs, but usually it will probably result
71 The end *result* of the algorithm will result in these resolutions for
73 - If we have a slug, make sure it's clean and sanitized, and if it's
74 unique, we'll use that.
75 - If we have a title, slugify it, and if it's unique, we'll use that.
76 - If we can't get any sort of thing that looks like it'll be a useful
77 slug out of a title or an existing slug, bail, and don't set the
78 slug at all. Don't try to create something just because. Make
79 sure we have a reasonable basis for a slug first.
80 - If we have a reasonable basis for a slug (either based on existing
81 slug or slugified title) but it's not unique, first try appending
82 the entry's id, if that exists
83 - If that doesn't result in something unique, tack on some randomly
84 generated bits until it's unique. That'll be a little bit of junk,
85 but at least it has the basis of a nice slug.
87 #Is already a slug assigned? Check if it is valid
89 self
.slug
= slugify(self
.slug
)
91 # otherwise, try to use the title.
93 # assign slug based on title
94 self
.slug
= slugify(self
.title
)
96 # We don't want any empty string slugs
100 # Do we have anything at this point?
101 # If not, we're not going to get a slug
102 # so just return... we're not going to force one.
106 # Otherwise, let's see if this is unique.
107 if self
.check_slug_used(self
.slug
):
108 # It looks like it's being used... lame.
110 # Can we just append the object's id to the end?
112 slug_with_id
= u
"%s-%s" % (self
.slug
, self
.id)
113 if not self
.check_slug_used(slug_with_id
):
114 self
.slug
= slug_with_id
117 # okay, still no success;
118 # let's whack junk on there till it's unique.
119 self
.slug
+= '-' + uuid
.uuid4().hex[:4]
120 # keep going if necessary!
121 while self
.check_slug_used(self
.slug
):
122 self
.slug
+= uuid
.uuid4().hex[:4]
125 class MediaEntryMixin(GenerateSlugMixin
):
126 def check_slug_used(self
, slug
):
127 # import this here due to a cyclic import issue
128 # (db.models -> db.mixin -> db.util -> db.models)
129 from mediagoblin
.db
.util
import check_media_slug_used
131 return check_media_slug_used(self
.uploader
, slug
, self
.id)
134 def description_html(self
):
136 Rendered version of the description, run through
137 Markdown and cleaned with our cleaning tool.
139 return cleaned_markdown_conversion(self
.description
)
141 def get_display_media(self
):
142 """Find the best media for display.
144 We try checking self.media_manager.fetching_order if it exists to
148 (media_size, media_path)
149 or, if not found, None.
152 fetch_order
= self
.media_manager
.get("media_fetch_order")
154 # No fetching order found? well, give up!
158 media_sizes
= self
.media_files
.keys()
160 for media_size
in fetch_order
:
161 if media_size
in media_sizes
:
162 return media_size
, self
.media_files
[media_size
]
164 def main_mediafile(self
):
168 def slug_or_id(self
):
172 return u
'id:%s' % self
.id
174 def url_for_self(self
, urlgen
, **extra_args
):
176 Generate an appropriate url for ourselves
178 Use a slug if we have one, else use our 'id'.
180 uploader
= self
.get_uploader
183 'mediagoblin.user_pages.media_home',
184 user
=uploader
.username
,
185 media
=self
.slug_or_id
,
190 """Return the thumbnail URL (for usage in templates)
191 Will return either the real thumbnail or a default fallback icon."""
192 # TODO: implement generic fallback in case MEDIA_MANAGER does
194 if u
'thumb' in self
.media_files
:
195 thumb_url
= mg_globals
.app
.public_store
.file_url(
196 self
.media_files
[u
'thumb'])
198 # No thumbnail in media available. Get the media's
199 # MEDIA_MANAGER for the fallback icon and return static URL
200 # Raises FileTypeNotSupported in case no such manager is enabled
201 manager
= self
.media_manager
202 thumb_url
= mg_globals
.app
.staticdirector(manager
[u
'default_thumb'])
206 def media_manager(self
):
207 """Returns the MEDIA_MANAGER of the media's media_type
209 Raises FileTypeNotSupported in case no such manager is enabled
211 # TODO, we should be able to make this a simple lookup rather
212 # than iterating through all media managers.
213 for media_type
, manager
in get_media_managers():
214 if media_type
== self
.media_type
:
216 # Not found? Then raise an error
217 raise FileTypeNotSupported(
218 "MediaManager not in enabled types. Check media_types in config?")
220 def get_fail_exception(self
):
222 Get the exception that's appropriate for this error
225 return common
.import_component(self
.fail_error
)
227 def get_license_data(self
):
228 """Return license dict for requested license"""
229 return licenses
.get_license_by_url(self
.license
or "")
231 def exif_display_iter(self
):
232 from mediagoblin
.tools
.exif
import USEFUL_TAGS
234 if not self
.media_data
:
236 exif_all
= self
.media_data
.get("exif_all")
238 for key
in USEFUL_TAGS
:
240 yield key
, exif_all
[key
]
243 class MediaCommentMixin(object):
245 def content_html(self
):
247 the actual html-rendered version of the comment displayed.
248 Run through Markdown and the HTML cleaner.
250 return cleaned_markdown_conversion(self
.content
)
253 class CollectionMixin(GenerateSlugMixin
):
254 def check_slug_used(self
, slug
):
255 # import this here due to a cyclic import issue
256 # (db.models -> db.mixin -> db.util -> db.models)
257 from mediagoblin
.db
.util
import check_collection_slug_used
259 return check_collection_slug_used(self
.creator
, slug
, self
.id)
262 def description_html(self
):
264 Rendered version of the description, run through
265 Markdown and cleaned with our cleaning tool.
267 return cleaned_markdown_conversion(self
.description
)
270 def slug_or_id(self
):
271 return (self
.slug
or self
.id)
273 def url_for_self(self
, urlgen
, **extra_args
):
275 Generate an appropriate url for ourselves
277 Use a slug if we have one, else use our 'id'.
279 creator
= self
.get_creator
282 'mediagoblin.user_pages.user_collection',
283 user
=creator
.username
,
284 collection
=self
.slug_or_id
,
288 class CollectionItemMixin(object):
292 the actual html-rendered version of the note displayed.
293 Run through Markdown and the HTML cleaner.
295 return cleaned_markdown_conversion(self
.note
)