This was a big commit! I included lots of documentation below, but generally I
[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 from mediagoblin import messages, mg_globals
22 from mediagoblin.db.models import (MediaEntry, MediaTag, Collection,
23 CollectionItem, User, MediaComment,
24 CommentReport, MediaReport)
25 from mediagoblin.tools.response import render_to_response, render_404, \
26 redirect, redirect_obj
27 from mediagoblin.tools.text import cleaned_markdown_conversion
28 from mediagoblin.tools.translate import pass_to_ugettext as _
29 from mediagoblin.tools.pagination import Pagination
30 from mediagoblin.user_pages import forms as user_forms
31 from mediagoblin.user_pages.lib import (send_comment_email,
32 add_media_to_collection, build_report_object)
33 from mediagoblin.notifications import trigger_notification, \
34 add_comment_subscription, mark_comment_notification_seen
35
36 from mediagoblin.decorators import (uses_pagination, get_user_media_entry,
37 get_media_entry_by_id, user_has_privilege,
38 require_active_login, user_may_delete_media, user_may_alter_collection,
39 get_user_collection, get_user_collection_item, active_user_from_url,
40 get_media_comment_by_id, user_not_banned)
41
42 from werkzeug.contrib.atom import AtomFeed
43 from werkzeug.exceptions import MethodNotAllowed
44 from werkzeug.wrappers import Response
45
46
47 _log = logging.getLogger(__name__)
48 _log.setLevel(logging.DEBUG)
49
50 @user_not_banned
51 @uses_pagination
52 def user_home(request, page):
53 """'Homepage' of a User()"""
54 # TODO: decide if we only want homepages for active users, we can
55 # then use the @get_active_user decorator and also simplify the
56 # template html.
57 user = User.query.filter_by(username=request.matchdict['user']).first()
58 if not user:
59 return render_404(request)
60 elif user.status != u'active':
61 return render_to_response(
62 request,
63 'mediagoblin/user_pages/user.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 User()"""
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 return render_to_response(
154 request,
155 media_template_name,
156 {'media': media,
157 'comments': comments,
158 'pagination': pagination,
159 'comment_form': comment_form,
160 'app_config': mg_globals.app_config})
161
162
163 @get_media_entry_by_id
164 @require_active_login
165 @user_has_privilege(u'commenter')
166 def media_post_comment(request, media):
167 """
168 recieves POST from a MediaEntry() comment form, saves the comment.
169 """
170 if not request.method == 'POST':
171 raise MethodNotAllowed()
172
173 comment = request.db.MediaComment()
174 comment.media_entry = media.id
175 comment.author = request.user.id
176 comment.content = unicode(request.form['comment_content'])
177
178 # Show error message if commenting is disabled.
179 if not mg_globals.app_config['allow_comments']:
180 messages.add_message(
181 request,
182 messages.ERROR,
183 _("Sorry, comments are disabled."))
184 elif not comment.content.strip():
185 messages.add_message(
186 request,
187 messages.ERROR,
188 _("Oops, your comment was empty."))
189 else:
190 comment.save()
191
192 messages.add_message(
193 request, messages.SUCCESS,
194 _('Your comment has been posted!'))
195
196 trigger_notification(comment, media, request)
197
198 add_comment_subscription(request.user, media)
199
200 return redirect_obj(request, media)
201
202 @user_not_banned
203 @get_media_entry_by_id
204 @require_active_login
205 def media_collect(request, media):
206 """Add media to collection submission"""
207
208 form = user_forms.MediaCollectForm(request.form)
209 # A user's own collections:
210 form.collection.query = Collection.query.filter_by(
211 creator = request.user.id).order_by(Collection.title)
212
213 if request.method != 'POST' or not form.validate():
214 # No POST submission, or invalid form
215 if not form.validate():
216 messages.add_message(request, messages.ERROR,
217 _('Please check your entries and try again.'))
218
219 return render_to_response(
220 request,
221 'mediagoblin/user_pages/media_collect.html',
222 {'media': media,
223 'form': form})
224
225 # If we are here, method=POST and the form is valid, submit things.
226 # If the user is adding a new collection, use that:
227 if form.collection_title.data:
228 # Make sure this user isn't duplicating an existing collection
229 existing_collection = Collection.query.filter_by(
230 creator=request.user.id,
231 title=form.collection_title.data).first()
232 if existing_collection:
233 messages.add_message(request, messages.ERROR,
234 _('You already have a collection called "%s"!')
235 % existing_collection.title)
236 return redirect(request, "mediagoblin.user_pages.media_home",
237 user=media.get_uploader.username,
238 media=media.slug_or_id)
239
240 collection = Collection()
241 collection.title = form.collection_title.data
242 collection.description = form.collection_description.data
243 collection.creator = request.user.id
244 collection.generate_slug()
245 collection.save()
246
247 # Otherwise, use the collection selected from the drop-down
248 else:
249 collection = form.collection.data
250 if collection and collection.creator != request.user.id:
251 collection = None
252
253 # Make sure the user actually selected a collection
254 if not collection:
255 messages.add_message(
256 request, messages.ERROR,
257 _('You have to select or add a collection'))
258 return redirect(request, "mediagoblin.user_pages.media_collect",
259 user=media.get_uploader.username,
260 media_id=media.id)
261
262
263 # Check whether media already exists in collection
264 elif CollectionItem.query.filter_by(
265 media_entry=media.id,
266 collection=collection.id).first():
267 messages.add_message(request, messages.ERROR,
268 _('"%s" already in collection "%s"')
269 % (media.title, collection.title))
270 else: # Add item to collection
271 add_media_to_collection(collection, media, form.note.data)
272
273 messages.add_message(request, messages.SUCCESS,
274 _('"%s" added to collection "%s"')
275 % (media.title, collection.title))
276
277 return redirect_obj(request, media)
278
279
280 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
281 @user_not_banned
282 @get_media_entry_by_id
283 @require_active_login
284 @user_may_delete_media
285 def media_confirm_delete(request, media):
286
287 form = user_forms.ConfirmDeleteForm(request.form)
288
289 if request.method == 'POST' and form.validate():
290 if form.confirm.data is True:
291 username = media.get_uploader.username
292 # Delete MediaEntry and all related files, comments etc.
293 media.delete()
294 messages.add_message(
295 request, messages.SUCCESS, _('You deleted the media.'))
296
297 location = media.url_to_next(request.urlgen)
298 if not location:
299 location=media.url_to_prev(request.urlgen)
300 if not location:
301 location=request.urlgen("mediagoblin.user_pages.user_home",
302 user=username)
303 return redirect(request, location=location)
304 else:
305 messages.add_message(
306 request, messages.ERROR,
307 _("The media was not deleted because you didn't check that you were sure."))
308 return redirect_obj(request, media)
309
310 if ((request.user.has_privilege(u'admin') and
311 request.user.id != media.uploader)):
312 messages.add_message(
313 request, messages.WARNING,
314 _("You are about to delete another user's media. "
315 "Proceed with caution."))
316
317 return render_to_response(
318 request,
319 'mediagoblin/user_pages/media_confirm_delete.html',
320 {'media': media,
321 'form': form})
322
323 @user_not_banned
324 @active_user_from_url
325 @uses_pagination
326 def user_collection(request, page, url_user=None):
327 """A User-defined Collection"""
328 collection = Collection.query.filter_by(
329 get_creator=url_user,
330 slug=request.matchdict['collection']).first()
331
332 if not collection:
333 return render_404(request)
334
335 cursor = collection.get_collection_items()
336
337 pagination = Pagination(page, cursor)
338 collection_items = pagination()
339
340 # if no data is available, return NotFound
341 # TODO: Should an empty collection really also return 404?
342 if collection_items == None:
343 return render_404(request)
344
345 return render_to_response(
346 request,
347 'mediagoblin/user_pages/collection.html',
348 {'user': url_user,
349 'collection': collection,
350 'collection_items': collection_items,
351 'pagination': pagination})
352
353 @user_not_banned
354 @active_user_from_url
355 def collection_list(request, url_user=None):
356 """A User-defined Collection"""
357 collections = Collection.query.filter_by(
358 get_creator=url_user)
359
360 return render_to_response(
361 request,
362 'mediagoblin/user_pages/collection_list.html',
363 {'user': url_user,
364 'collections': collections})
365
366
367 @get_user_collection_item
368 @require_active_login
369 @user_may_alter_collection
370 def collection_item_confirm_remove(request, collection_item):
371
372 form = user_forms.ConfirmCollectionItemRemoveForm(request.form)
373
374 if request.method == 'POST' and form.validate():
375 username = collection_item.in_collection.get_creator.username
376 collection = collection_item.in_collection
377
378 if form.confirm.data is True:
379 entry = collection_item.get_media_entry
380 entry.collected = entry.collected - 1
381 entry.save()
382
383 collection_item.delete()
384 collection.items = collection.items - 1
385 collection.save()
386
387 messages.add_message(
388 request, messages.SUCCESS, _('You deleted the item from the collection.'))
389 else:
390 messages.add_message(
391 request, messages.ERROR,
392 _("The item was not removed because you didn't check that you were sure."))
393
394 return redirect_obj(request, collection)
395
396 if ((request.user.has_privilege(u'admin') and
397 request.user.id != collection_item.in_collection.creator)):
398 messages.add_message(
399 request, messages.WARNING,
400 _("You are about to delete an item from another user's collection. "
401 "Proceed with caution."))
402
403 return render_to_response(
404 request,
405 'mediagoblin/user_pages/collection_item_confirm_remove.html',
406 {'collection_item': collection_item,
407 'form': form})
408
409 @user_not_banned
410 @get_user_collection
411 @require_active_login
412 @user_may_alter_collection
413 def collection_confirm_delete(request, collection):
414
415 form = user_forms.ConfirmDeleteForm(request.form)
416
417 if request.method == 'POST' and form.validate():
418
419 username = collection.get_creator.username
420
421 if form.confirm.data is True:
422 collection_title = collection.title
423
424 # Delete all the associated collection items
425 for item in collection.get_collection_items():
426 entry = item.get_media_entry
427 entry.collected = entry.collected - 1
428 entry.save()
429 item.delete()
430
431 collection.delete()
432 messages.add_message(request, messages.SUCCESS,
433 _('You deleted the collection "%s"') % collection_title)
434
435 return redirect(request, "mediagoblin.user_pages.user_home",
436 user=username)
437 else:
438 messages.add_message(
439 request, messages.ERROR,
440 _("The collection was not deleted because you didn't check that you were sure."))
441
442 return redirect_obj(request, collection)
443
444 if ((request.user.has_privilege(u'admin') and
445 request.user.id != collection.creator)):
446 messages.add_message(
447 request, messages.WARNING,
448 _("You are about to delete another user's collection. "
449 "Proceed with caution."))
450
451 return render_to_response(
452 request,
453 'mediagoblin/user_pages/collection_confirm_delete.html',
454 {'collection': collection,
455 'form': form})
456
457
458 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS = 15
459
460
461 def atom_feed(request):
462 """
463 generates the atom feed with the newest images
464 """
465 user = User.query.filter_by(
466 username = request.matchdict['user'],
467 status = u'active').first()
468 if not user:
469 return render_404(request)
470
471 cursor = MediaEntry.query.filter_by(
472 uploader = user.id,
473 state = u'processed').\
474 order_by(MediaEntry.created.desc()).\
475 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS)
476
477 """
478 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
479 """
480 atomlinks = [{
481 'href': request.urlgen(
482 'mediagoblin.user_pages.user_home',
483 qualified=True, user=request.matchdict['user']),
484 'rel': 'alternate',
485 'type': 'text/html'
486 }]
487
488 if mg_globals.app_config["push_urls"]:
489 for push_url in mg_globals.app_config["push_urls"]:
490 atomlinks.append({
491 'rel': 'hub',
492 'href': push_url})
493
494 feed = AtomFeed(
495 "MediaGoblin: Feed for user '%s'" % request.matchdict['user'],
496 feed_url=request.url,
497 id='tag:{host},{year}:gallery.user-{user}'.format(
498 host=request.host,
499 year=datetime.datetime.today().strftime('%Y'),
500 user=request.matchdict['user']),
501 links=atomlinks)
502
503 for entry in cursor:
504 feed.add(entry.get('title'),
505 entry.description_html,
506 id=entry.url_for_self(request.urlgen, qualified=True),
507 content_type='html',
508 author={
509 'name': entry.get_uploader.username,
510 'uri': request.urlgen(
511 'mediagoblin.user_pages.user_home',
512 qualified=True, user=entry.get_uploader.username)},
513 updated=entry.get('created'),
514 links=[{
515 'href': entry.url_for_self(
516 request.urlgen,
517 qualified=True),
518 'rel': 'alternate',
519 'type': 'text/html'}])
520
521 return feed.get_response()
522
523
524 def collection_atom_feed(request):
525 """
526 generates the atom feed with the newest images from a collection
527 """
528 user = User.query.filter_by(
529 username = request.matchdict['user'],
530 status = u'active').first()
531 if not user:
532 return render_404(request)
533
534 collection = Collection.query.filter_by(
535 creator=user.id,
536 slug=request.matchdict['collection']).first()
537 if not collection:
538 return render_404(request)
539
540 cursor = CollectionItem.query.filter_by(
541 collection=collection.id) \
542 .order_by(CollectionItem.added.desc()) \
543 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS)
544
545 """
546 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
547 """
548 atomlinks = [{
549 'href': collection.url_for_self(request.urlgen, qualified=True),
550 'rel': 'alternate',
551 'type': 'text/html'
552 }]
553
554 if mg_globals.app_config["push_urls"]:
555 for push_url in mg_globals.app_config["push_urls"]:
556 atomlinks.append({
557 'rel': 'hub',
558 'href': push_url})
559
560 feed = AtomFeed(
561 "MediaGoblin: Feed for %s's collection %s" %
562 (request.matchdict['user'], collection.title),
563 feed_url=request.url,
564 id=u'tag:{host},{year}:gnu-mediagoblin.{user}.collection.{slug}'\
565 .format(
566 host=request.host,
567 year=collection.created.strftime('%Y'),
568 user=request.matchdict['user'],
569 slug=collection.slug),
570 links=atomlinks)
571
572 for item in cursor:
573 entry = item.get_media_entry
574 feed.add(entry.get('title'),
575 item.note_html,
576 id=entry.url_for_self(request.urlgen, qualified=True),
577 content_type='html',
578 author={
579 'name': entry.get_uploader.username,
580 'uri': request.urlgen(
581 'mediagoblin.user_pages.user_home',
582 qualified=True, user=entry.get_uploader.username)},
583 updated=item.get('added'),
584 links=[{
585 'href': entry.url_for_self(
586 request.urlgen,
587 qualified=True),
588 'rel': 'alternate',
589 'type': 'text/html'}])
590
591 return feed.get_response()
592
593 @user_not_banned
594 @require_active_login
595 def processing_panel(request):
596 """
597 Show to the user what media is still in conversion/processing...
598 and what failed, and why!
599 """
600 user = User.query.filter_by(username=request.matchdict['user']).first()
601 # TODO: XXX: Should this be a decorator?
602 #
603 # Make sure we have permission to access this user's panel. Only
604 # admins and this user herself should be able to do so.
605 if not (user.id == request.user.id or request.user.has_privilege(u'admin')):
606 # No? Simply redirect to this user's homepage.
607 return redirect(
608 request, 'mediagoblin.user_pages.user_home',
609 user=user.username)
610
611 # Get media entries which are in-processing
612 processing_entries = MediaEntry.query.\
613 filter_by(uploader = user.id,
614 state = u'processing').\
615 order_by(MediaEntry.created.desc())
616
617 # Get media entries which have failed to process
618 failed_entries = MediaEntry.query.\
619 filter_by(uploader = user.id,
620 state = u'failed').\
621 order_by(MediaEntry.created.desc())
622
623 processed_entries = MediaEntry.query.\
624 filter_by(uploader = user.id,
625 state = u'processed').\
626 order_by(MediaEntry.created.desc()).\
627 limit(10)
628
629 # Render to response
630 return render_to_response(
631 request,
632 'mediagoblin/user_pages/processing_panel.html',
633 {'user': user,
634 'processing_entries': processing_entries,
635 'failed_entries': failed_entries,
636 'processed_entries': processed_entries})
637
638 @require_active_login
639 @get_user_media_entry
640 @user_has_privilege(u'reporter')
641 def file_a_report(request, media, comment=None):
642 if comment is not None:
643 form = user_forms.CommentReportForm(request.form)
644 form.reporter_id.data = request.user.id
645 context = {'media': media,
646 'comment':comment,
647 'form':form}
648 else:
649 form = user_forms.MediaReportForm(request.form)
650 form.reporter_id.data = request.user.id
651 context = {'media': media,
652 'form':form}
653
654 if request.method == "POST":
655 report_object = build_report_object(form,
656 media_entry=media,
657 comment=comment)
658
659 # if the object was built successfully, report_table will not be None
660 if report_object:
661 report_object.save()
662 return redirect(
663 request,
664 'index')
665
666
667 return render_to_response(
668 request,
669 'mediagoblin/user_pages/report.html',
670 context)
671
672 @require_active_login
673 @get_user_media_entry
674 @get_media_comment_by_id
675 def file_a_comment_report(request, media, comment):
676 return file_a_report(request, comment=comment)