Change codebase to query or create correct User model
[mediagoblin.git] / mediagoblin / user_pages / 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 logging
18 import datetime
19 import json
20
21 import six
22
23 from mediagoblin import messages, mg_globals
24 from mediagoblin.db.models import (MediaEntry, MediaTag, Collection,
25 CollectionItem, LocalUser, Activity)
26 from mediagoblin.tools.response import render_to_response, render_404, \
27 redirect, redirect_obj
28 from mediagoblin.tools.text import cleaned_markdown_conversion
29 from mediagoblin.tools.translate import pass_to_ugettext as _
30 from mediagoblin.tools.pagination import Pagination
31 from mediagoblin.tools.federation import create_activity
32 from mediagoblin.user_pages import forms as user_forms
33 from mediagoblin.user_pages.lib import (send_comment_email,
34 add_media_to_collection, build_report_object)
35 from mediagoblin.notifications import trigger_notification, \
36 add_comment_subscription, mark_comment_notification_seen
37 from mediagoblin.tools.pluginapi import hook_transform
38
39 from mediagoblin.decorators import (uses_pagination, get_user_media_entry,
40 get_media_entry_by_id, user_has_privilege, user_not_banned,
41 require_active_login, user_may_delete_media, user_may_alter_collection,
42 get_user_collection, get_user_collection_item, active_user_from_url,
43 get_optional_media_comment_by_id, allow_reporting)
44
45 from werkzeug.contrib.atom import AtomFeed
46 from werkzeug.exceptions import MethodNotAllowed
47 from werkzeug.wrappers import Response
48
49
50 _log = logging.getLogger(__name__)
51 _log.setLevel(logging.DEBUG)
52
53 @user_not_banned
54 @uses_pagination
55 def user_home(request, page):
56 """'Homepage' of a LocalUser()"""
57 user = LocalUser.query.filter_by(username=request.matchdict['user']).first()
58 if not user:
59 return render_404(request)
60 elif not user.has_privilege(u'active'):
61 return render_to_response(
62 request,
63 'mediagoblin/user_pages/user_nonactive.html',
64 {'user': user})
65
66 cursor = MediaEntry.query.\
67 filter_by(uploader = user.id,
68 state = u'processed').order_by(MediaEntry.created.desc())
69
70 pagination = Pagination(page, cursor)
71 media_entries = pagination()
72
73 #if no data is available, return NotFound
74 if media_entries == None:
75 return render_404(request)
76
77 user_gallery_url = request.urlgen(
78 'mediagoblin.user_pages.user_gallery',
79 user=user.username)
80
81 return render_to_response(
82 request,
83 'mediagoblin/user_pages/user.html',
84 {'user': user,
85 'user_gallery_url': user_gallery_url,
86 'media_entries': media_entries,
87 'pagination': pagination})
88
89 @user_not_banned
90 @active_user_from_url
91 @uses_pagination
92 def user_gallery(request, page, url_user=None):
93 """'Gallery' of a LocalUser()"""
94 tag = request.matchdict.get('tag', None)
95 cursor = MediaEntry.query.filter_by(
96 uploader=url_user.id,
97 state=u'processed').order_by(MediaEntry.created.desc())
98
99 # Filter potentially by tag too:
100 if tag:
101 cursor = cursor.filter(
102 MediaEntry.tags_helper.any(
103 MediaTag.slug == request.matchdict['tag']))
104
105 # Paginate gallery
106 pagination = Pagination(page, cursor)
107 media_entries = pagination()
108
109 #if no data is available, return NotFound
110 # TODO: Should we really also return 404 for empty galleries?
111 if media_entries == None:
112 return render_404(request)
113
114 return render_to_response(
115 request,
116 'mediagoblin/user_pages/gallery.html',
117 {'user': url_user, 'tag': tag,
118 'media_entries': media_entries,
119 'pagination': pagination})
120
121
122 MEDIA_COMMENTS_PER_PAGE = 50
123
124 @user_not_banned
125 @get_user_media_entry
126 @uses_pagination
127 def media_home(request, media, page, **kwargs):
128 """
129 'Homepage' of a MediaEntry()
130 """
131 comment_id = request.matchdict.get('comment', None)
132 if comment_id:
133 if request.user:
134 mark_comment_notification_seen(comment_id, request.user)
135
136 pagination = Pagination(
137 page, media.get_comments(
138 mg_globals.app_config['comments_ascending']),
139 MEDIA_COMMENTS_PER_PAGE,
140 comment_id)
141 else:
142 pagination = Pagination(
143 page, media.get_comments(
144 mg_globals.app_config['comments_ascending']),
145 MEDIA_COMMENTS_PER_PAGE)
146
147 comments = pagination()
148
149 comment_form = user_forms.MediaCommentForm(request.form)
150
151 media_template_name = media.media_manager.display_template
152
153 context = {
154 'media': media,
155 'comments': comments,
156 'pagination': pagination,
157 'comment_form': comment_form,
158 'app_config': mg_globals.app_config}
159
160 # Since the media template name gets swapped out for each media
161 # type, normal context hooks don't work if you want to affect all
162 # media displays. This gives a general purpose hook.
163 context = hook_transform(
164 "media_home_context", context)
165
166 return render_to_response(
167 request,
168 media_template_name,
169 context)
170
171
172 @get_media_entry_by_id
173 @user_has_privilege(u'commenter')
174 def media_post_comment(request, media):
175 """
176 recieves POST from a MediaEntry() comment form, saves the comment.
177 """
178 if not request.method == 'POST':
179 raise MethodNotAllowed()
180
181 comment = request.db.MediaComment()
182 comment.media_entry = media.id
183 comment.author = request.user.id
184 comment.content = six.text_type(request.form['comment_content'])
185
186 # Show error message if commenting is disabled.
187 if not mg_globals.app_config['allow_comments']:
188 messages.add_message(
189 request,
190 messages.ERROR,
191 _("Sorry, comments are disabled."))
192 elif not comment.content.strip():
193 messages.add_message(
194 request,
195 messages.ERROR,
196 _("Oops, your comment was empty."))
197 else:
198 create_activity("post", comment, comment.author, target=media)
199 add_comment_subscription(request.user, media)
200 comment.save()
201
202 messages.add_message(
203 request, messages.SUCCESS,
204 _('Your comment has been posted!'))
205 trigger_notification(comment, media, request)
206
207 return redirect_obj(request, media)
208
209
210
211 def media_preview_comment(request):
212 """Runs a comment through markdown so it can be previewed."""
213 # If this isn't an ajax request, render_404
214 if not request.is_xhr:
215 return render_404(request)
216
217 comment = six.text_type(request.form['comment_content'])
218 cleancomment = { "content":cleaned_markdown_conversion(comment)}
219
220 return Response(json.dumps(cleancomment))
221
222 @user_not_banned
223 @get_media_entry_by_id
224 @require_active_login
225 def media_collect(request, media):
226 """Add media to collection submission"""
227
228 form = user_forms.MediaCollectForm(request.form)
229 # A user's own collections:
230 form.collection.query = Collection.query.filter_by(
231 creator = request.user.id).order_by(Collection.title)
232
233 if request.method != 'POST' or not form.validate():
234 # No POST submission, or invalid form
235 if not form.validate():
236 messages.add_message(request, messages.ERROR,
237 _('Please check your entries and try again.'))
238
239 return render_to_response(
240 request,
241 'mediagoblin/user_pages/media_collect.html',
242 {'media': media,
243 'form': form})
244
245 # If we are here, method=POST and the form is valid, submit things.
246 # If the user is adding a new collection, use that:
247 if form.collection_title.data:
248 # Make sure this user isn't duplicating an existing collection
249 existing_collection = Collection.query.filter_by(
250 creator=request.user.id,
251 title=form.collection_title.data).first()
252 if existing_collection:
253 messages.add_message(request, messages.ERROR,
254 _('You already have a collection called "%s"!')
255 % existing_collection.title)
256 return redirect(request, "mediagoblin.user_pages.media_home",
257 user=media.get_uploader.username,
258 media=media.slug_or_id)
259
260 collection = Collection()
261 collection.title = form.collection_title.data
262 collection.description = form.collection_description.data
263 collection.creator = request.user.id
264 collection.generate_slug()
265 create_activity("create", collection, collection.creator)
266 collection.save()
267
268 # Otherwise, use the collection selected from the drop-down
269 else:
270 collection = form.collection.data
271 if collection and collection.creator != request.user.id:
272 collection = None
273
274 # Make sure the user actually selected a collection
275 if not collection:
276 messages.add_message(
277 request, messages.ERROR,
278 _('You have to select or add a collection'))
279 return redirect(request, "mediagoblin.user_pages.media_collect",
280 user=media.get_uploader.username,
281 media_id=media.id)
282
283
284 # Check whether media already exists in collection
285 elif CollectionItem.query.filter_by(
286 media_entry=media.id,
287 collection=collection.id).first():
288 messages.add_message(request, messages.ERROR,
289 _('"%s" already in collection "%s"')
290 % (media.title, collection.title))
291 else: # Add item to collection
292 add_media_to_collection(collection, media, form.note.data)
293 create_activity("add", media, request.user, target=collection)
294 messages.add_message(request, messages.SUCCESS,
295 _('"%s" added to collection "%s"')
296 % (media.title, collection.title))
297
298 return redirect_obj(request, media)
299
300
301 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
302 @get_media_entry_by_id
303 @require_active_login
304 @user_may_delete_media
305 def media_confirm_delete(request, media):
306
307 form = user_forms.ConfirmDeleteForm(request.form)
308
309 if request.method == 'POST' and form.validate():
310 if form.confirm.data is True:
311 username = media.get_uploader.username
312
313 media.get_uploader.uploaded = media.get_uploader.uploaded - \
314 media.file_size
315 media.get_uploader.save()
316
317 # Delete MediaEntry and all related files, comments etc.
318 media.delete()
319 messages.add_message(
320 request, messages.SUCCESS, _('You deleted the media.'))
321
322 location = media.url_to_next(request.urlgen)
323 if not location:
324 location=media.url_to_prev(request.urlgen)
325 if not location:
326 location=request.urlgen("mediagoblin.user_pages.user_home",
327 user=username)
328 return redirect(request, location=location)
329 else:
330 messages.add_message(
331 request, messages.ERROR,
332 _("The media was not deleted because you didn't check that you were sure."))
333 return redirect_obj(request, media)
334
335 if ((request.user.has_privilege(u'admin') and
336 request.user.id != media.uploader)):
337 messages.add_message(
338 request, messages.WARNING,
339 _("You are about to delete another user's media. "
340 "Proceed with caution."))
341
342 return render_to_response(
343 request,
344 'mediagoblin/user_pages/media_confirm_delete.html',
345 {'media': media,
346 'form': form})
347
348 @user_not_banned
349 @active_user_from_url
350 @uses_pagination
351 def user_collection(request, page, url_user=None):
352 """A User-defined Collection"""
353 collection = Collection.query.filter_by(
354 get_creator=url_user,
355 slug=request.matchdict['collection']).first()
356
357 if not collection:
358 return render_404(request)
359
360 cursor = collection.get_collection_items()
361
362 pagination = Pagination(page, cursor)
363 collection_items = pagination()
364
365 # if no data is available, return NotFound
366 # TODO: Should an empty collection really also return 404?
367 if collection_items == None:
368 return render_404(request)
369
370 return render_to_response(
371 request,
372 'mediagoblin/user_pages/collection.html',
373 {'user': url_user,
374 'collection': collection,
375 'collection_items': collection_items,
376 'pagination': pagination})
377
378 @user_not_banned
379 @active_user_from_url
380 def collection_list(request, url_user=None):
381 """A User-defined Collection"""
382 collections = Collection.query.filter_by(
383 get_creator=url_user)
384
385 return render_to_response(
386 request,
387 'mediagoblin/user_pages/collection_list.html',
388 {'user': url_user,
389 'collections': collections})
390
391
392 @get_user_collection_item
393 @require_active_login
394 @user_may_alter_collection
395 def collection_item_confirm_remove(request, collection_item):
396
397 form = user_forms.ConfirmCollectionItemRemoveForm(request.form)
398
399 if request.method == 'POST' and form.validate():
400 username = collection_item.in_collection.get_creator.username
401 collection = collection_item.in_collection
402
403 if form.confirm.data is True:
404 entry = collection_item.get_media_entry
405 entry.save()
406
407 collection_item.delete()
408 collection.items = collection.items - 1
409 collection.save()
410
411 messages.add_message(
412 request, messages.SUCCESS, _('You deleted the item from the collection.'))
413 else:
414 messages.add_message(
415 request, messages.ERROR,
416 _("The item was not removed because you didn't check that you were sure."))
417
418 return redirect_obj(request, collection)
419
420 if ((request.user.has_privilege(u'admin') and
421 request.user.id != collection_item.in_collection.creator)):
422 messages.add_message(
423 request, messages.WARNING,
424 _("You are about to delete an item from another user's collection. "
425 "Proceed with caution."))
426
427 return render_to_response(
428 request,
429 'mediagoblin/user_pages/collection_item_confirm_remove.html',
430 {'collection_item': collection_item,
431 'form': form})
432
433
434 @get_user_collection
435 @require_active_login
436 @user_may_alter_collection
437 def collection_confirm_delete(request, collection):
438
439 form = user_forms.ConfirmDeleteForm(request.form)
440
441 if request.method == 'POST' and form.validate():
442
443 username = collection.get_creator.username
444
445 if form.confirm.data is True:
446 collection_title = collection.title
447
448 # Delete all the associated collection items
449 for item in collection.get_collection_items():
450 entry = item.get_media_entry
451 entry.save()
452 item.delete()
453
454 collection.delete()
455 messages.add_message(request, messages.SUCCESS,
456 _('You deleted the collection "%s"') % collection_title)
457
458 return redirect(request, "mediagoblin.user_pages.user_home",
459 user=username)
460 else:
461 messages.add_message(
462 request, messages.ERROR,
463 _("The collection was not deleted because you didn't check that you were sure."))
464
465 return redirect_obj(request, collection)
466
467 if ((request.user.has_privilege(u'admin') and
468 request.user.id != collection.creator)):
469 messages.add_message(
470 request, messages.WARNING,
471 _("You are about to delete another user's collection. "
472 "Proceed with caution."))
473
474 return render_to_response(
475 request,
476 'mediagoblin/user_pages/collection_confirm_delete.html',
477 {'collection': collection,
478 'form': form})
479
480
481 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS = 15
482
483
484 def atom_feed(request):
485 """
486 generates the atom feed with the newest images
487 """
488 user = LocalUser.query.filter_by(
489 username = request.matchdict['user']).first()
490 if not user or not user.has_privilege(u'active'):
491 return render_404(request)
492
493 cursor = MediaEntry.query.filter_by(
494 uploader = user.id,
495 state = u'processed').\
496 order_by(MediaEntry.created.desc()).\
497 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS)
498
499 """
500 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
501 """
502 atomlinks = [{
503 'href': request.urlgen(
504 'mediagoblin.user_pages.user_home',
505 qualified=True, user=request.matchdict['user']),
506 'rel': 'alternate',
507 'type': 'text/html'
508 }]
509
510 if mg_globals.app_config["push_urls"]:
511 for push_url in mg_globals.app_config["push_urls"]:
512 atomlinks.append({
513 'rel': 'hub',
514 'href': push_url})
515
516 feed = AtomFeed(
517 "MediaGoblin: Feed for user '%s'" % request.matchdict['user'],
518 feed_url=request.url,
519 id='tag:{host},{year}:gallery.user-{user}'.format(
520 host=request.host,
521 year=datetime.datetime.today().strftime('%Y'),
522 user=request.matchdict['user']),
523 links=atomlinks)
524
525 for entry in cursor:
526 feed.add(entry.get('title'),
527 entry.description_html,
528 id=entry.url_for_self(request.urlgen, qualified=True),
529 content_type='html',
530 author={
531 'name': entry.get_uploader.username,
532 'uri': request.urlgen(
533 'mediagoblin.user_pages.user_home',
534 qualified=True, user=entry.get_uploader.username)},
535 updated=entry.get('created'),
536 links=[{
537 'href': entry.url_for_self(
538 request.urlgen,
539 qualified=True),
540 'rel': 'alternate',
541 'type': 'text/html'}])
542
543 return feed.get_response()
544
545
546 def collection_atom_feed(request):
547 """
548 generates the atom feed with the newest images from a collection
549 """
550 user = LocalUser.query.filter_by(
551 username = request.matchdict['user']).first()
552 if not user or not user.has_privilege(u'active'):
553 return render_404(request)
554
555 collection = Collection.query.filter_by(
556 creator=user.id,
557 slug=request.matchdict['collection']).first()
558 if not collection:
559 return render_404(request)
560
561 cursor = CollectionItem.query.filter_by(
562 collection=collection.id) \
563 .order_by(CollectionItem.added.desc()) \
564 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS)
565
566 """
567 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
568 """
569 atomlinks = [{
570 'href': collection.url_for_self(request.urlgen, qualified=True),
571 'rel': 'alternate',
572 'type': 'text/html'
573 }]
574
575 if mg_globals.app_config["push_urls"]:
576 for push_url in mg_globals.app_config["push_urls"]:
577 atomlinks.append({
578 'rel': 'hub',
579 'href': push_url})
580
581 feed = AtomFeed(
582 "MediaGoblin: Feed for %s's collection %s" %
583 (request.matchdict['user'], collection.title),
584 feed_url=request.url,
585 id=u'tag:{host},{year}:gnu-mediagoblin.{user}.collection.{slug}'\
586 .format(
587 host=request.host,
588 year=collection.created.strftime('%Y'),
589 user=request.matchdict['user'],
590 slug=collection.slug),
591 links=atomlinks)
592
593 for item in cursor:
594 entry = item.get_media_entry
595 feed.add(entry.get('title'),
596 item.note_html,
597 id=entry.url_for_self(request.urlgen, qualified=True),
598 content_type='html',
599 author={
600 'name': entry.get_uploader.username,
601 'uri': request.urlgen(
602 'mediagoblin.user_pages.user_home',
603 qualified=True, user=entry.get_uploader.username)},
604 updated=item.get('added'),
605 links=[{
606 'href': entry.url_for_self(
607 request.urlgen,
608 qualified=True),
609 'rel': 'alternate',
610 'type': 'text/html'}])
611
612 return feed.get_response()
613
614 @require_active_login
615 def processing_panel(request):
616 """
617 Show to the user what media is still in conversion/processing...
618 and what failed, and why!
619 """
620 user = LocalUser.query.filter_by(username=request.matchdict['user']).first()
621 # TODO: XXX: Should this be a decorator?
622 #
623 # Make sure we have permission to access this user's panel. Only
624 # admins and this user herself should be able to do so.
625 if not (user.id == request.user.id or request.user.has_privilege(u'admin')):
626 # No? Simply redirect to this user's homepage.
627 return redirect(
628 request, 'mediagoblin.user_pages.user_home',
629 user=user.username)
630
631 # Get media entries which are in-processing
632 processing_entries = MediaEntry.query.\
633 filter_by(uploader = user.id,
634 state = u'processing').\
635 order_by(MediaEntry.created.desc())
636
637 # Get media entries which have failed to process
638 failed_entries = MediaEntry.query.\
639 filter_by(uploader = user.id,
640 state = u'failed').\
641 order_by(MediaEntry.created.desc())
642
643 processed_entries = MediaEntry.query.\
644 filter_by(uploader = user.id,
645 state = u'processed').\
646 order_by(MediaEntry.created.desc()).\
647 limit(10)
648
649 # Render to response
650 return render_to_response(
651 request,
652 'mediagoblin/user_pages/processing_panel.html',
653 {'user': user,
654 'processing_entries': processing_entries,
655 'failed_entries': failed_entries,
656 'processed_entries': processed_entries})
657
658 @allow_reporting
659 @get_user_media_entry
660 @user_has_privilege(u'reporter')
661 @get_optional_media_comment_by_id
662 def file_a_report(request, media, comment):
663 """
664 This view handles the filing of a MediaReport or a CommentReport.
665 """
666 if comment is not None:
667 if not comment.get_media_entry.id == media.id:
668 return render_404(request)
669
670 form = user_forms.CommentReportForm(request.form)
671 context = {'media': media,
672 'comment':comment,
673 'form':form}
674 else:
675 form = user_forms.MediaReportForm(request.form)
676 context = {'media': media,
677 'form':form}
678 form.reporter_id.data = request.user.id
679
680
681 if request.method == "POST":
682 report_object = build_report_object(form,
683 media_entry=media,
684 comment=comment)
685
686 # if the object was built successfully, report_table will not be None
687 if report_object:
688 report_object.save()
689 return redirect(
690 request,
691 'index')
692
693
694 return render_to_response(
695 request,
696 'mediagoblin/user_pages/report.html',
697 context)
698
699 @require_active_login
700 def activity_view(request):
701 """ /<username>/activity/<id> - Display activity
702
703 This should display a HTML presentation of the activity
704 this is NOT an API endpoint.
705 """
706 # Get the user object.
707 username = request.matchdict["username"]
708 user = LocalUser.query.filter_by(username=username).first()
709
710 activity_id = request.matchdict["id"]
711
712 if request.user is None:
713 return render_404(request)
714
715 activity = Activity.query.filter_by(
716 id=activity_id,
717 author=user.id
718 ).first()
719
720 if activity is None:
721 return render_404(request)
722
723 return render_to_response(
724 request,
725 "mediagoblin/api/activity.html",
726 {"activity": activity}
727 )
728