Sanitize slug input on media edit
[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
65969d3f 61 duplicate = check_media_slug_used(self.uploader, self.slug, self.id)
814334f6
E
62
63 if duplicate:
64 if self.id is not None:
5bd0adeb 65 self.slug = u"%s-%s" % (self.id, self.slug)
814334f6
E
66 else:
67 self.slug = None
68
1e72e075
E
69 @property
70 def description_html(self):
71 """
72 Rendered version of the description, run through
73 Markdown and cleaned with our cleaning tool.
74 """
75 return cleaned_markdown_conversion(self.description)
76
f42e49c3
E
77 def get_display_media(self, media_map,
78 fetch_order=common.DISPLAY_IMAGE_FETCHING_ORDER):
79 """
80 Find the best media for display.
81
82 Args:
83 - media_map: a dict like
84 {u'image_size': [u'dir1', u'dir2', u'image.jpg']}
85 - fetch_order: the order we should try fetching images in
86
87 Returns:
88 (media_size, media_path)
89 """
90 media_sizes = media_map.keys()
91
92 for media_size in common.DISPLAY_IMAGE_FETCHING_ORDER:
93 if media_size in media_sizes:
94 return media_map[media_size]
95
96 def main_mediafile(self):
97 pass
98
3e907d55
E
99 @property
100 def slug_or_id(self):
5c2b8486 101 return (self.slug or self.id)
3e907d55 102
5f8b4ae8 103
cb7ae1e4 104 def url_for_self(self, urlgen, **extra_args):
f42e49c3
E
105 """
106 Generate an appropriate url for ourselves
107
5c2b8486 108 Use a slug if we have one, else use our 'id'.
f42e49c3
E
109 """
110 uploader = self.get_uploader
111
3e907d55
E
112 return urlgen(
113 'mediagoblin.user_pages.media_home',
114 user=uploader.username,
115 media=self.slug_or_id,
116 **extra_args)
f42e49c3 117
2e4ad359
SS
118 @property
119 def thumb_url(self):
120 """Return the thumbnail URL (for usage in templates)
121 Will return either the real thumbnail or a default fallback icon."""
122 # TODO: implement generic fallback in case MEDIA_MANAGER does
123 # not specify one?
124 if u'thumb' in self.media_files:
125 thumb_url = mg_globals.app.public_store.file_url(
126 self.media_files[u'thumb'])
127 else:
df1c4976 128 # No thumbnail in media available. Get the media's
2e4ad359 129 # MEDIA_MANAGER for the fallback icon and return static URL
5f8b4ae8
SS
130 # Raises FileTypeNotSupported in case no such manager is enabled
131 manager = self.media_manager
df1c4976 132 thumb_url = mg_globals.app.staticdirector(manager[u'default_thumb'])
2e4ad359
SS
133 return thumb_url
134
5f8b4ae8
SS
135 @cached_property
136 def media_manager(self):
137 """Returns the MEDIA_MANAGER of the media's media_type
138
139 Raises FileTypeNotSupported in case no such manager is enabled
140 """
141 # TODO, we should be able to make this a simple lookup rather
142 # than iterating through all media managers.
143 for media_type, manager in get_media_managers():
144 if media_type == self.media_type:
145 return manager
146 # Not found? Then raise an error
147 raise FileTypeNotSupported(
148 "MediaManager not in enabled types. Check media_types in config?")
149
f42e49c3
E
150 def get_fail_exception(self):
151 """
152 Get the exception that's appropriate for this error
153 """
51eb0267
JW
154 if self.fail_error:
155 return common.import_component(self.fail_error)
17c23e15
AW
156
157 def get_license_data(self):
158 """Return license dict for requested license"""
138a18fd 159 return licenses.get_license_by_url(self.license or "")
feba5c52 160
5bad26bc 161 def exif_display_iter(self):
7b82f56b
E
162 from mediagoblin.tools.exif import USEFUL_TAGS
163
5bad26bc
E
164 if not self.media_data:
165 return
166 exif_all = self.media_data.get("exif_all")
167
168 for key in USEFUL_TAGS:
169 if key in exif_all:
170 yield key, exif_all[key]
171
feba5c52
E
172
173class MediaCommentMixin(object):
174 @property
175 def content_html(self):
176 """
177 the actual html-rendered version of the comment displayed.
178 Run through Markdown and the HTML cleaner.
179 """
180 return cleaned_markdown_conversion(self.content)
be5be115
AW
181
182
183class CollectionMixin(object):
184 def generate_slug(self):
185 # import this here due to a cyclic import issue
186 # (db.models -> db.mixin -> db.util -> db.models)
187 from mediagoblin.db.util import check_collection_slug_used
188
189 self.slug = slugify(self.title)
190
191 duplicate = check_collection_slug_used(mg_globals.database,
192 self.creator, self.slug, self.id)
193
194 if duplicate:
195 if self.id is not None:
196 self.slug = u"%s-%s" % (self.id, self.slug)
197 else:
198 self.slug = None
199
200 @property
201 def description_html(self):
202 """
203 Rendered version of the description, run through
204 Markdown and cleaned with our cleaning tool.
205 """
206 return cleaned_markdown_conversion(self.description)
207
208 @property
209 def slug_or_id(self):
5c2b8486 210 return (self.slug or self.id)
be5be115
AW
211
212 def url_for_self(self, urlgen, **extra_args):
213 """
214 Generate an appropriate url for ourselves
215
5c2b8486 216 Use a slug if we have one, else use our 'id'.
be5be115
AW
217 """
218 creator = self.get_creator
219
220 return urlgen(
256f816f 221 'mediagoblin.user_pages.user_collection',
be5be115
AW
222 user=creator.username,
223 collection=self.slug_or_id,
224 **extra_args)
225
6d1e55b2 226
be5be115
AW
227class CollectionItemMixin(object):
228 @property
229 def note_html(self):
230 """
231 the actual html-rendered version of the note displayed.
232 Run through Markdown and the HTML cleaner.
233 """
234 return cleaned_markdown_conversion(self.note)