Fix up tests
[mediagoblin.git] / mediagoblin / db / mixin.py
CommitLineData
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"""
18This module contains some Mixin classes for the db objects.
19
20A bunch of functions on the db objects are really more like
21"utility functions": They could live outside the classes
22and be called "by hand" passing the appropiate reference.
23They usually only use the public API of the object and
24rarely use database related stuff.
25
26These functions now live here and get "mixed in" into the
27real objects.
28"""
29
5f8b4ae8
SS
30from werkzeug.utils import cached_property
31
814334f6 32from mediagoblin import mg_globals
f42e49c3 33from mediagoblin.auth import lib as auth_lib
5f8b4ae8 34from mediagoblin.media_types import get_media_managers, FileTypeNotSupported
17c23e15 35from mediagoblin.tools import common, licenses
e61ab099 36from mediagoblin.tools.text import cleaned_markdown_conversion
814334f6 37from mediagoblin.tools.url import slugify
f42e49c3
E
38
39
40class UserMixin(object):
41 def check_login(self, password):
42 """
43 See if a user can login with this password
44 """
45 return auth_lib.bcrypt_check_password(
46 password, self.pw_hash)
47
e61ab099
E
48 @property
49 def bio_html(self):
50 return cleaned_markdown_conversion(self.bio)
51
f42e49c3
E
52
53class MediaEntryMixin(object):
814334f6
E
54 def generate_slug(self):
55 # import this here due to a cyclic import issue
56 # (db.models -> db.mixin -> db.util -> db.models)
57 from mediagoblin.db.util import check_media_slug_used
58
59 self.slug = slugify(self.title)
60
61 duplicate = check_media_slug_used(mg_globals.database,
62 self.uploader, self.slug, self.id)
63
64 if duplicate:
65 if self.id is not None:
5bd0adeb 66 self.slug = u"%s-%s" % (self.id, self.slug)
814334f6
E
67 else:
68 self.slug = None
69
1e72e075
E
70 @property
71 def description_html(self):
72 """
73 Rendered version of the description, run through
74 Markdown and cleaned with our cleaning tool.
75 """
76 return cleaned_markdown_conversion(self.description)
77
f42e49c3
E
78 def get_display_media(self, media_map,
79 fetch_order=common.DISPLAY_IMAGE_FETCHING_ORDER):
80 """
81 Find the best media for display.
82
83 Args:
84 - media_map: a dict like
85 {u'image_size': [u'dir1', u'dir2', u'image.jpg']}
86 - fetch_order: the order we should try fetching images in
87
88 Returns:
89 (media_size, media_path)
90 """
91 media_sizes = media_map.keys()
92
93 for media_size in common.DISPLAY_IMAGE_FETCHING_ORDER:
94 if media_size in media_sizes:
95 return media_map[media_size]
96
97 def main_mediafile(self):
98 pass
99
3e907d55
E
100 @property
101 def slug_or_id(self):
102 return (self.slug or self._id)
103
5f8b4ae8 104
cb7ae1e4 105 def url_for_self(self, urlgen, **extra_args):
f42e49c3
E
106 """
107 Generate an appropriate url for ourselves
108
109 Use a slug if we have one, else use our '_id'.
110 """
111 uploader = self.get_uploader
112
3e907d55
E
113 return urlgen(
114 'mediagoblin.user_pages.media_home',
115 user=uploader.username,
116 media=self.slug_or_id,
117 **extra_args)
f42e49c3 118
2e4ad359
SS
119 @property
120 def thumb_url(self):
121 """Return the thumbnail URL (for usage in templates)
122 Will return either the real thumbnail or a default fallback icon."""
123 # TODO: implement generic fallback in case MEDIA_MANAGER does
124 # not specify one?
125 if u'thumb' in self.media_files:
126 thumb_url = mg_globals.app.public_store.file_url(
127 self.media_files[u'thumb'])
128 else:
df1c4976 129 # No thumbnail in media available. Get the media's
2e4ad359 130 # MEDIA_MANAGER for the fallback icon and return static URL
5f8b4ae8
SS
131 # Raises FileTypeNotSupported in case no such manager is enabled
132 manager = self.media_manager
df1c4976 133 thumb_url = mg_globals.app.staticdirector(manager[u'default_thumb'])
2e4ad359
SS
134 return thumb_url
135
5f8b4ae8
SS
136 @cached_property
137 def media_manager(self):
138 """Returns the MEDIA_MANAGER of the media's media_type
139
140 Raises FileTypeNotSupported in case no such manager is enabled
141 """
142 # TODO, we should be able to make this a simple lookup rather
143 # than iterating through all media managers.
144 for media_type, manager in get_media_managers():
145 if media_type == self.media_type:
146 return manager
147 # Not found? Then raise an error
148 raise FileTypeNotSupported(
149 "MediaManager not in enabled types. Check media_types in config?")
150
f42e49c3
E
151 def get_fail_exception(self):
152 """
153 Get the exception that's appropriate for this error
154 """
51eb0267
JW
155 if self.fail_error:
156 return common.import_component(self.fail_error)
17c23e15
AW
157
158 def get_license_data(self):
159 """Return license dict for requested license"""
138a18fd 160 return licenses.get_license_by_url(self.license or "")
feba5c52 161
5bad26bc 162 def exif_display_iter(self):
7b82f56b
E
163 from mediagoblin.tools.exif import USEFUL_TAGS
164
5bad26bc
E
165 if not self.media_data:
166 return
167 exif_all = self.media_data.get("exif_all")
168
169 for key in USEFUL_TAGS:
170 if key in exif_all:
171 yield key, exif_all[key]
172
feba5c52
E
173
174class MediaCommentMixin(object):
175 @property
176 def content_html(self):
177 """
178 the actual html-rendered version of the comment displayed.
179 Run through Markdown and the HTML cleaner.
180 """
181 return cleaned_markdown_conversion(self.content)
be5be115
AW
182
183
184class CollectionMixin(object):
185 def generate_slug(self):
186 # import this here due to a cyclic import issue
187 # (db.models -> db.mixin -> db.util -> db.models)
188 from mediagoblin.db.util import check_collection_slug_used
189
190 self.slug = slugify(self.title)
191
192 duplicate = check_collection_slug_used(mg_globals.database,
193 self.creator, self.slug, self.id)
194
195 if duplicate:
196 if self.id is not None:
197 self.slug = u"%s-%s" % (self.id, self.slug)
198 else:
199 self.slug = None
200
201 @property
202 def description_html(self):
203 """
204 Rendered version of the description, run through
205 Markdown and cleaned with our cleaning tool.
206 """
207 return cleaned_markdown_conversion(self.description)
208
209 @property
210 def slug_or_id(self):
211 return (self.slug or self._id)
212
213 def url_for_self(self, urlgen, **extra_args):
214 """
215 Generate an appropriate url for ourselves
216
217 Use a slug if we have one, else use our '_id'.
218 """
219 creator = self.get_creator
220
221 return urlgen(
256f816f 222 'mediagoblin.user_pages.user_collection',
be5be115
AW
223 user=creator.username,
224 collection=self.slug_or_id,
225 **extra_args)
226
6d1e55b2 227
be5be115
AW
228class CollectionItemMixin(object):
229 @property
230 def note_html(self):
231 """
232 the actual html-rendered version of the note displayed.
233 Run through Markdown and the HTML cleaner.
234 """
235 return cleaned_markdown_conversion(self.note)