Merge branch 'master' into joar-skip_transcoding
[mediagoblin.git] / mediagoblin / edit / views.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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 from datetime import datetime
18
19 from werkzeug.exceptions import Forbidden
20 from werkzeug.utils import secure_filename
21
22 from mediagoblin import messages
23 from mediagoblin import mg_globals
24
25 from mediagoblin.auth import lib as auth_lib
26 from mediagoblin.edit import forms
27 from mediagoblin.edit.lib import may_edit_media
28 from mediagoblin.decorators import (require_active_login, active_user_from_url,
29 get_media_entry_by_id,
30 user_may_alter_collection, get_user_collection)
31 from mediagoblin.tools.response import render_to_response, redirect
32 from mediagoblin.tools.translate import pass_to_ugettext as _
33 from mediagoblin.tools.text import (
34 convert_to_tag_list_of_dicts, media_tags_as_string)
35 from mediagoblin.tools.url import slugify
36 from mediagoblin.db.util import check_media_slug_used, check_collection_slug_used
37
38 import mimetypes
39
40
41 @get_media_entry_by_id
42 @require_active_login
43 def edit_media(request, media):
44 if not may_edit_media(request, media):
45 raise Forbidden("User may not edit this media")
46
47 defaults = dict(
48 title=media.title,
49 slug=media.slug,
50 description=media.description,
51 tags=media_tags_as_string(media.tags),
52 license=media.license)
53
54 form = forms.EditForm(
55 request.form,
56 **defaults)
57
58 if request.method == 'POST' and form.validate():
59 # Make sure there isn't already a MediaEntry with such a slug
60 # and userid.
61 slug = slugify(request.form['slug'])
62 slug_used = check_media_slug_used(media.uploader, slug, media.id)
63
64 if slug_used:
65 form.slug.errors.append(
66 _(u'An entry with that slug already exists for this user.'))
67 else:
68 media.title = request.form['title']
69 media.description = request.form.get('description')
70 media.tags = convert_to_tag_list_of_dicts(
71 request.form.get('tags'))
72
73 media.license = unicode(request.form.get('license', '')) or None
74 media.slug = slug
75 media.save()
76
77 return redirect(request,
78 location=media.url_for_self(request.urlgen))
79
80 if request.user.is_admin \
81 and media.uploader != request.user.id \
82 and request.method != 'POST':
83 messages.add_message(
84 request, messages.WARNING,
85 _("You are editing another user's media. Proceed with caution."))
86
87 return render_to_response(
88 request,
89 'mediagoblin/edit/edit.html',
90 {'media': media,
91 'form': form})
92
93
94 # Mimetypes that browsers parse scripts in.
95 # Content-sniffing isn't taken into consideration.
96 UNSAFE_MIMETYPES = [
97 'text/html',
98 'text/svg+xml']
99
100
101 @get_media_entry_by_id
102 @require_active_login
103 def edit_attachments(request, media):
104 if mg_globals.app_config['allow_attachments']:
105 form = forms.EditAttachmentsForm()
106
107 # Add any attachements
108 if 'attachment_file' in request.files \
109 and request.files['attachment_file']:
110
111 # Security measure to prevent attachments from being served as
112 # text/html, which will be parsed by web clients and pose an XSS
113 # threat.
114 #
115 # TODO
116 # This method isn't flawless as some browsers may perform
117 # content-sniffing.
118 # This method isn't flawless as we do the mimetype lookup on the
119 # machine parsing the upload form, and not necessarily the machine
120 # serving the attachments.
121 if mimetypes.guess_type(
122 request.files['attachment_file'].filename)[0] in \
123 UNSAFE_MIMETYPES:
124 public_filename = secure_filename('{0}.notsafe'.format(
125 request.files['attachment_file'].filename))
126 else:
127 public_filename = secure_filename(
128 request.files['attachment_file'].filename)
129
130 attachment_public_filepath \
131 = mg_globals.public_store.get_unique_filepath(
132 ['media_entries', unicode(media.id), 'attachment',
133 public_filename])
134
135 attachment_public_file = mg_globals.public_store.get_file(
136 attachment_public_filepath, 'wb')
137
138 try:
139 attachment_public_file.write(
140 request.files['attachment_file'].stream.read())
141 finally:
142 request.files['attachment_file'].stream.close()
143
144 media.attachment_files.append(dict(
145 name=request.form['attachment_name'] \
146 or request.files['attachment_file'].filename,
147 filepath=attachment_public_filepath,
148 created=datetime.utcnow(),
149 ))
150
151 media.save()
152
153 messages.add_message(
154 request, messages.SUCCESS,
155 _("You added the attachment %s!") \
156 % (request.form['attachment_name']
157 or request.files['attachment_file'].filename))
158
159 return redirect(request,
160 location=media.url_for_self(request.urlgen))
161 return render_to_response(
162 request,
163 'mediagoblin/edit/attachments.html',
164 {'media': media,
165 'form': form})
166 else:
167 raise Forbidden("Attachments are disabled")
168
169 @require_active_login
170 def legacy_edit_profile(request):
171 """redirect the old /edit/profile/?username=USER to /u/USER/edit/"""
172 username = request.GET.get('username') or request.user.username
173 return redirect(request, 'mediagoblin.edit.profile', user=username)
174
175
176 @require_active_login
177 @active_user_from_url
178 def edit_profile(request, url_user=None):
179 # admins may edit any user profile
180 if request.user.username != url_user.username:
181 if not request.user.is_admin:
182 raise Forbidden(_("You can only edit your own profile."))
183
184 # No need to warn again if admin just submitted an edited profile
185 if request.method != 'POST':
186 messages.add_message(
187 request, messages.WARNING,
188 _("You are editing a user's profile. Proceed with caution."))
189
190 user = url_user
191
192 form = forms.EditProfileForm(request.form,
193 url=user.url,
194 bio=user.bio)
195
196 if request.method == 'POST' and form.validate():
197 user.url = unicode(request.form['url'])
198 user.bio = unicode(request.form['bio'])
199
200 user.save()
201
202 messages.add_message(request,
203 messages.SUCCESS,
204 _("Profile changes saved"))
205 return redirect(request,
206 'mediagoblin.user_pages.user_home',
207 user=user.username)
208
209 return render_to_response(
210 request,
211 'mediagoblin/edit/edit_profile.html',
212 {'user': user,
213 'form': form})
214
215
216 @require_active_login
217 def edit_account(request):
218 user = request.user
219 form = forms.EditAccountForm(request.form,
220 wants_comment_notification=user.wants_comment_notification,
221 license_preference=user.license_preference)
222
223 if request.method == 'POST':
224 form_validated = form.validate()
225
226 if form_validated and \
227 form.wants_comment_notification.validate(form):
228 user.wants_comment_notification = \
229 form.wants_comment_notification.data
230
231 if form_validated and \
232 form.new_password.data or form.old_password.data:
233 password_matches = auth_lib.bcrypt_check_password(
234 form.old_password.data,
235 user.pw_hash)
236 if password_matches:
237 #the entire form validates and the password matches
238 user.pw_hash = auth_lib.bcrypt_gen_password_hash(
239 form.new_password.data)
240 else:
241 form.old_password.errors.append(_('Wrong password'))
242
243 if form_validated and \
244 form.license_preference.validate(form):
245 user.license_preference = \
246 form.license_preference.data
247
248 if form_validated and not form.errors:
249 user.save()
250 messages.add_message(request,
251 messages.SUCCESS,
252 _("Account settings saved"))
253 return redirect(request,
254 'mediagoblin.user_pages.user_home',
255 user=user.username)
256
257 return render_to_response(
258 request,
259 'mediagoblin/edit/edit_account.html',
260 {'user': user,
261 'form': form})
262
263
264 @require_active_login
265 def delete_account(request):
266 """Delete a user completely"""
267 user = request.user
268 if request.method == 'POST':
269 if request.form.get(u'confirmed'):
270 # Form submitted and confirmed. Actually delete the user account
271 # Log out user and delete cookies etc.
272 # TODO: Should we be using MG.auth.views.py:logout for this?
273 request.session.delete()
274
275 # Delete user account and all related media files etc....
276 request.user.delete()
277
278 # We should send a message that the user has been deleted
279 # successfully. But we just deleted the session, so we
280 # can't...
281 return redirect(request, 'index')
282
283 else: # Did not check the confirmation box...
284 messages.add_message(
285 request, messages.WARNING,
286 _('You need to confirm the deletion of your account.'))
287
288 # No POST submission or not confirmed, just show page
289 return render_to_response(
290 request,
291 'mediagoblin/edit/delete_account.html',
292 {'user': user})
293
294
295 @require_active_login
296 @user_may_alter_collection
297 @get_user_collection
298 def edit_collection(request, collection):
299 defaults = dict(
300 title=collection.title,
301 slug=collection.slug,
302 description=collection.description)
303
304 form = forms.EditCollectionForm(
305 request.form,
306 **defaults)
307
308 if request.method == 'POST' and form.validate():
309 # Make sure there isn't already a Collection with such a slug
310 # and userid.
311 slug_used = check_collection_slug_used(request.db, collection.creator,
312 request.form['slug'], collection.id)
313
314 # Make sure there isn't already a Collection with this title
315 existing_collection = request.db.Collection.find_one({
316 'creator': request.user.id,
317 'title':request.form['title']})
318
319 if existing_collection and existing_collection.id != collection.id:
320 messages.add_message(
321 request, messages.ERROR,
322 _('You already have a collection called "%s"!') % \
323 request.form['title'])
324 elif slug_used:
325 form.slug.errors.append(
326 _(u'A collection with that slug already exists for this user.'))
327 else:
328 collection.title = unicode(request.form['title'])
329 collection.description = unicode(request.form.get('description'))
330 collection.slug = unicode(request.form['slug'])
331
332 collection.save()
333
334 return redirect(request, "mediagoblin.user_pages.user_collection",
335 user=collection.get_creator.username,
336 collection=collection.slug)
337
338 if request.user.is_admin \
339 and collection.creator != request.user.id \
340 and request.method != 'POST':
341 messages.add_message(
342 request, messages.WARNING,
343 _("You are editing another user's collection. Proceed with caution."))
344
345 return render_to_response(
346 request,
347 'mediagoblin/edit/edit_collection.html',
348 {'collection': collection,
349 'form': form})