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