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