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