Cleaning up
[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 import six
18
19 from datetime import datetime
20
21 from itsdangerous import BadSignature
22 from pyld import jsonld
23 from werkzeug.exceptions import Forbidden
24 from werkzeug.utils import secure_filename
25 from jsonschema import ValidationError, Draft4Validator
26
27 from mediagoblin import messages
28 from mediagoblin import mg_globals
29
30 from mediagoblin.auth import (check_password,
31 tools as auth_tools)
32 from mediagoblin.edit import forms
33 from mediagoblin.edit.lib import may_edit_media
34 from mediagoblin.decorators import (require_active_login, active_user_from_url,
35 get_media_entry_by_id, user_may_alter_collection,
36 get_user_collection, user_has_privilege,
37 user_not_banned, path_subtitle)
38 from mediagoblin.tools.crypto import get_timed_signer_url
39 from mediagoblin.tools.metadata import (compact_and_validate, DEFAULT_CHECKER,
40 DEFAULT_SCHEMA)
41 from mediagoblin.tools.mail import email_debug_message
42 from mediagoblin.tools.response import (render_to_response,
43 redirect, redirect_obj, render_404)
44 from mediagoblin.tools.translate import pass_to_ugettext as _
45 from mediagoblin.tools.template import render_template
46 from mediagoblin.tools.text import (
47 convert_to_tag_list_of_dicts, media_tags_as_string)
48 from mediagoblin.tools.url import slugify
49 from mediagoblin.db.util import check_media_slug_used, check_collection_slug_used
50 from mediagoblin.db.models import User, LocalUser, Client, AccessToken, Location
51
52 import mimetypes
53
54
55 @get_media_entry_by_id
56 @require_active_login
57 def edit_media(request, media):
58 if not may_edit_media(request, media):
59 raise Forbidden("User may not edit this media")
60
61 defaults = dict(
62 title=media.title,
63 slug=media.slug,
64 description=media.description,
65 tags=media_tags_as_string(media.tags),
66 license=media.license)
67
68 form = forms.EditForm(
69 request.form,
70 **defaults)
71
72 if request.method == 'POST' and form.validate():
73 # Make sure there isn't already a MediaEntry with such a slug
74 # and userid.
75 slug = slugify(form.slug.data)
76 slug_used = check_media_slug_used(media.actor, slug, media.id)
77
78 if slug_used:
79 form.slug.errors.append(
80 _(u'An entry with that slug already exists for this user.'))
81 else:
82 media.title = form.title.data
83 media.description = form.description.data
84 media.tags = convert_to_tag_list_of_dicts(
85 form.tags.data)
86
87 media.license = six.text_type(form.license.data) or None
88 media.slug = slug
89 media.save()
90
91 return redirect_obj(request, media)
92
93 if request.user.has_privilege(u'admin') \
94 and media.actor != request.user.id \
95 and request.method != 'POST':
96 messages.add_message(
97 request,
98 messages.WARNING,
99 _("You are editing another user's media. Proceed with caution."))
100
101 return render_to_response(
102 request,
103 'mediagoblin/edit/edit.html',
104 {'media': media,
105 'form': form})
106
107
108 # Mimetypes that browsers parse scripts in.
109 # Content-sniffing isn't taken into consideration.
110 UNSAFE_MIMETYPES = [
111 'text/html',
112 'text/svg+xml']
113
114
115 @get_media_entry_by_id
116 @require_active_login
117 def edit_attachments(request, media):
118 if mg_globals.app_config['allow_attachments']:
119 form = forms.EditAttachmentsForm()
120
121 # Add any attachements
122 if 'attachment_file' in request.files \
123 and request.files['attachment_file']:
124
125 # Security measure to prevent attachments from being served as
126 # text/html, which will be parsed by web clients and pose an XSS
127 # threat.
128 #
129 # TODO
130 # This method isn't flawless as some browsers may perform
131 # content-sniffing.
132 # This method isn't flawless as we do the mimetype lookup on the
133 # machine parsing the upload form, and not necessarily the machine
134 # serving the attachments.
135 if mimetypes.guess_type(
136 request.files['attachment_file'].filename)[0] in \
137 UNSAFE_MIMETYPES:
138 public_filename = secure_filename('{0}.notsafe'.format(
139 request.files['attachment_file'].filename))
140 else:
141 public_filename = secure_filename(
142 request.files['attachment_file'].filename)
143
144 attachment_public_filepath \
145 = mg_globals.public_store.get_unique_filepath(
146 ['media_entries', six.text_type(media.id), 'attachment',
147 public_filename])
148
149 attachment_public_file = mg_globals.public_store.get_file(
150 attachment_public_filepath, 'wb')
151
152 try:
153 attachment_public_file.write(
154 request.files['attachment_file'].stream.read())
155 finally:
156 request.files['attachment_file'].stream.close()
157
158 media.attachment_files.append(dict(
159 name=form.attachment_name.data \
160 or request.files['attachment_file'].filename,
161 filepath=attachment_public_filepath,
162 created=datetime.utcnow(),
163 ))
164
165 media.save()
166
167 messages.add_message(
168 request,
169 messages.SUCCESS,
170 _("You added the attachment %s!") %
171 (form.attachment_name.data or
172 request.files['attachment_file'].filename))
173
174 return redirect(request,
175 location=media.url_for_self(request.urlgen))
176 return render_to_response(
177 request,
178 'mediagoblin/edit/attachments.html',
179 {'media': media,
180 'form': form})
181 else:
182 raise Forbidden("Attachments are disabled")
183
184 @get_media_entry_by_id
185 @require_active_login
186 def edit_subtitles(request, media):
187 if mg_globals.app_config['allow_subtitles']:
188 form = forms.EditSubtitlesForm(request.form)
189
190 # Add any subtitles
191 if 'subtitle_file' in request.files \
192 and request.files['subtitle_file']:
193 if mimetypes.guess_type(
194 request.files['subtitle_file'].filename)[0] in \
195 UNSAFE_MIMETYPES:
196 public_filename = secure_filename('{0}.notsafe'.format(
197 request.files['subtitle_file'].filename))
198 else:
199 public_filename = secure_filename(
200 request.files['subtitle_file'].filename)
201
202 subtitle_public_filepath \
203 = mg_globals.public_store.get_unique_filepath(
204 ['media_entries', six.text_type(media.id), 'subtitle',
205 public_filename])
206
207 subtitle_public_file = mg_globals.public_store.get_file(
208 subtitle_public_filepath, 'wb')
209
210 try:
211 subtitle_public_file.write(
212 request.files['subtitle_file'].stream.read())
213 finally:
214 request.files['subtitle_file'].stream.close()
215
216 media.subtitle_files.append(dict(
217 name=form.subtitle_language.data \
218 or request.files['subtitle_file'].filename,
219 filepath=subtitle_public_filepath,
220 created=datetime.utcnow(),
221 ))
222
223 media.save()
224
225 messages.add_message(
226 request,
227 messages.SUCCESS,
228 _("You added the subttile %s!") %
229 (form.subtitle_language.data or
230 request.files['subtitle_file'].filename))
231
232 return redirect(request,
233 location=media.url_for_self(request.urlgen))
234 return render_to_response(
235 request,
236 'mediagoblin/edit/subtitles.html',
237 {'media': media,
238 'form': form})
239 else:
240 raise Forbidden("Subtitles are disabled")
241
242 @require_active_login
243 def legacy_edit_profile(request):
244 """redirect the old /edit/profile/?username=USER to /u/USER/edit/"""
245 username = request.GET.get('username') or request.user.username
246 return redirect(request, 'mediagoblin.edit.profile', user=username)
247
248
249 @require_active_login
250 @active_user_from_url
251 def edit_profile(request, url_user=None):
252 # admins may edit any user profile
253 if request.user.username != url_user.username:
254 if not request.user.has_privilege(u'admin'):
255 raise Forbidden(_("You can only edit your own profile."))
256
257 # No need to warn again if admin just submitted an edited profile
258 if request.method != 'POST':
259 messages.add_message(
260 request,
261 messages.WARNING,
262 _("You are editing a user's profile. Proceed with caution."))
263
264 user = url_user
265
266 # Get the location name
267 if user.location is None:
268 location = ""
269 else:
270 location = user.get_location.name
271
272 form = forms.EditProfileForm(request.form,
273 url=user.url,
274 bio=user.bio,
275 location=location)
276
277 if request.method == 'POST' and form.validate():
278 user.url = six.text_type(form.url.data)
279 user.bio = six.text_type(form.bio.data)
280
281 # Save location
282 if form.location.data and user.location is None:
283 user.get_location = Location(name=six.text_type(form.location.data))
284 elif form.location.data:
285 location = user.get_location
286 location.name = six.text_type(form.location.data)
287 location.save()
288
289 user.save()
290
291 messages.add_message(
292 request,
293 messages.SUCCESS,
294 _("Profile changes saved"))
295 return redirect(request,
296 'mediagoblin.user_pages.user_home',
297 user=user.username)
298
299 return render_to_response(
300 request,
301 'mediagoblin/edit/edit_profile.html',
302 {'user': user,
303 'form': form})
304
305 EMAIL_VERIFICATION_TEMPLATE = (
306 u'{uri}?'
307 u'token={verification_key}')
308
309
310 @require_active_login
311 def edit_account(request):
312 user = request.user
313 form = forms.EditAccountForm(request.form,
314 wants_comment_notification=user.wants_comment_notification,
315 license_preference=user.license_preference,
316 wants_notifications=user.wants_notifications)
317
318 if request.method == 'POST' and form.validate():
319 user.wants_comment_notification = form.wants_comment_notification.data
320 user.wants_notifications = form.wants_notifications.data
321
322 user.license_preference = form.license_preference.data
323
324 user.save()
325 messages.add_message(
326 request,
327 messages.SUCCESS,
328 _("Account settings saved"))
329 return redirect(request,
330 'mediagoblin.user_pages.user_home',
331 user=user.username)
332
333 return render_to_response(
334 request,
335 'mediagoblin/edit/edit_account.html',
336 {'user': user,
337 'form': form})
338
339 @require_active_login
340 def deauthorize_applications(request):
341 """ Deauthroize OAuth applications """
342 if request.method == 'POST' and "application" in request.form:
343 token = request.form["application"]
344 access_token = AccessToken.query.filter_by(token=token).first()
345 if access_token is None:
346 messages.add_message(
347 request,
348 messages.ERROR,
349 _("Unknown application, not able to deauthorize")
350 )
351 else:
352 access_token.delete()
353 messages.add_message(
354 request,
355 messages.SUCCESS,
356 _("Application has been deauthorized")
357 )
358
359 access_tokens = AccessToken.query.filter_by(actor=request.user.id)
360 applications = [(a.get_requesttoken, a) for a in access_tokens]
361
362 return render_to_response(
363 request,
364 'mediagoblin/edit/deauthorize_applications.html',
365 {'applications': applications}
366 )
367
368 @require_active_login
369 def delete_account(request):
370 """Delete a user completely"""
371 user = request.user
372 if request.method == 'POST':
373 if request.form.get(u'confirmed'):
374 # Form submitted and confirmed. Actually delete the user account
375 # Log out user and delete cookies etc.
376 # TODO: Should we be using MG.auth.views.py:logout for this?
377 request.session.delete()
378
379 # Delete user account and all related media files etc....
380 user = User.query.filter(User.id==user.id).first()
381 user.delete()
382
383 # We should send a message that the user has been deleted
384 # successfully. But we just deleted the session, so we
385 # can't...
386 return redirect(request, 'index')
387
388 else: # Did not check the confirmation box...
389 messages.add_message(
390 request,
391 messages.WARNING,
392 _('You need to confirm the deletion of your account.'))
393
394 # No POST submission or not confirmed, just show page
395 return render_to_response(
396 request,
397 'mediagoblin/edit/delete_account.html',
398 {'user': user})
399
400
401 @require_active_login
402 @user_may_alter_collection
403 @get_user_collection
404 def edit_collection(request, collection):
405 defaults = dict(
406 title=collection.title,
407 slug=collection.slug,
408 description=collection.description)
409
410 form = forms.EditCollectionForm(
411 request.form,
412 **defaults)
413
414 if request.method == 'POST' and form.validate():
415 # Make sure there isn't already a Collection with such a slug
416 # and userid.
417 slug_used = check_collection_slug_used(collection.actor,
418 form.slug.data, collection.id)
419
420 # Make sure there isn't already a Collection with this title
421 existing_collection = request.db.Collection.query.filter_by(
422 actor=request.user.id,
423 title=form.title.data).first()
424
425 if existing_collection and existing_collection.id != collection.id:
426 messages.add_message(
427 request,
428 messages.ERROR,
429 _('You already have a collection called "%s"!') %
430 form.title.data)
431 elif slug_used:
432 form.slug.errors.append(
433 _(u'A collection with that slug already exists for this user.'))
434 else:
435 collection.title = six.text_type(form.title.data)
436 collection.description = six.text_type(form.description.data)
437 collection.slug = six.text_type(form.slug.data)
438
439 collection.save()
440
441 return redirect_obj(request, collection)
442
443 if request.user.has_privilege(u'admin') \
444 and collection.actor != request.user.id \
445 and request.method != 'POST':
446 messages.add_message(
447 request,
448 messages.WARNING,
449 _("You are editing another user's collection. "
450 "Proceed with caution."))
451
452 return render_to_response(
453 request,
454 'mediagoblin/edit/edit_collection.html',
455 {'collection': collection,
456 'form': form})
457
458
459 def verify_email(request):
460 """
461 Email verification view for changing email address
462 """
463 # If no token, we can't do anything
464 if not 'token' in request.GET:
465 return render_404(request)
466
467 # Catch error if token is faked or expired
468 token = None
469 try:
470 token = get_timed_signer_url("mail_verification_token") \
471 .loads(request.GET['token'], max_age=10*24*3600)
472 except BadSignature:
473 messages.add_message(
474 request,
475 messages.ERROR,
476 _('The verification key or user id is incorrect.'))
477
478 return redirect(
479 request,
480 'index')
481
482 user = User.query.filter_by(id=int(token['user'])).first()
483
484 if user:
485 user.email = token['email']
486 user.save()
487
488 messages.add_message(
489 request,
490 messages.SUCCESS,
491 _('Your email address has been verified.'))
492
493 else:
494 messages.add_message(
495 request,
496 messages.ERROR,
497 _('The verification key or user id is incorrect.'))
498
499 return redirect(
500 request, 'mediagoblin.user_pages.user_home',
501 user=user.username)
502
503
504 def change_email(request):
505 """ View to change the user's email """
506 form = forms.ChangeEmailForm(request.form)
507 user = request.user
508
509 # If no password authentication, no need to enter a password
510 if 'pass_auth' not in request.template_env.globals or not user.pw_hash:
511 form.__delitem__('password')
512
513 if request.method == 'POST' and form.validate():
514 new_email = form.new_email.data
515 users_with_email = User.query.filter(
516 LocalUser.email==new_email
517 ).count()
518
519 if users_with_email:
520 form.new_email.errors.append(
521 _('Sorry, a user with that email address'
522 ' already exists.'))
523
524 if form.password and user.pw_hash and not check_password(
525 form.password.data, user.pw_hash):
526 form.password.errors.append(
527 _('Wrong password'))
528
529 if not form.errors:
530 verification_key = get_timed_signer_url(
531 'mail_verification_token').dumps({
532 'user': user.id,
533 'email': new_email})
534
535 rendered_email = render_template(
536 request, 'mediagoblin/edit/verification.txt',
537 {'username': user.username,
538 'verification_url': EMAIL_VERIFICATION_TEMPLATE.format(
539 uri=request.urlgen('mediagoblin.edit.verify_email',
540 qualified=True),
541 verification_key=verification_key)})
542
543 email_debug_message(request)
544 auth_tools.send_verification_email(user, request, new_email,
545 rendered_email)
546
547 return redirect(request, 'mediagoblin.edit.account')
548
549 return render_to_response(
550 request,
551 'mediagoblin/edit/change_email.html',
552 {'form': form,
553 'user': user})
554
555 @user_has_privilege(u'admin')
556 @require_active_login
557 @get_media_entry_by_id
558 def edit_metadata(request, media):
559 form = forms.EditMetaDataForm(request.form)
560 if request.method == "POST" and form.validate():
561 metadata_dict = dict([(row['identifier'],row['value'])
562 for row in form.media_metadata.data])
563 json_ld_metadata = None
564 json_ld_metadata = compact_and_validate(metadata_dict)
565 media.media_metadata = json_ld_metadata
566 media.save()
567 return redirect_obj(request, media)
568
569 if len(form.media_metadata) == 0:
570 for identifier, value in six.iteritems(media.media_metadata):
571 if identifier == "@context": continue
572 form.media_metadata.append_entry({
573 'identifier':identifier,
574 'value':value})
575
576 return render_to_response(
577 request,
578 'mediagoblin/edit/metadata.html',
579 {'form':form,
580 'media':media})
581
582
583 @require_active_login
584 @path_subtitle
585 def custom_subtitles(request,path=None):
586 form = forms.CustomizeSubtitlesForm(request.form)
587 return render_to_response(
588 request,
589 "mediagoblin/edit/custom_subtitles.html",
590 {"path": path,
591 "form": form })