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