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