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