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