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