Improve sqlalchemy filter rules
[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.util import DESCENDING, ObjectId
22 from mediagoblin.db.sql.models import (MediaEntry, Collection, CollectionItem,
23 User)
24 from mediagoblin.tools.response import render_to_response, render_404, redirect
25 from mediagoblin.tools.translate import pass_to_ugettext as _
26 from mediagoblin.tools.pagination import Pagination
27 from mediagoblin.tools.files import delete_media_files
28 from mediagoblin.user_pages import forms as user_forms
29 from mediagoblin.user_pages.lib import send_comment_email
30
31 from mediagoblin.decorators import (uses_pagination, get_user_media_entry,
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').sort('created', DESCENDING)
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 cursor = MediaEntry.query.filter_by(
86 uploader=url_user.id,
87 state=u'processed').order_by(MediaEntry.created.desc())
88
89 # Paginate gallery
90 pagination = Pagination(page, cursor)
91 media_entries = pagination()
92
93 #if no data is available, return NotFound
94 # TODO: Should we really also return 404 for empty galleries?
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': url_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 request.matchdict.get('comment', None):
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 redirect(request, location=media.url_for_self(request.urlgen))
174
175
176 @get_user_media_entry
177 @require_active_login
178 def media_collect(request, media):
179 """Add media to collection submission"""
180
181 form = user_forms.MediaCollectForm(request.form)
182 # A user's own collections:
183 form.collection.query = Collection.query.filter_by(
184 creator = request.user.id).order_by(Collection.title)
185
186 if request.method != 'POST' or not form.validate():
187 # No POST submission, or invalid form
188 if not form.validate():
189 messages.add_message(request, messages.ERROR,
190 _('Please check your entries and try again.'))
191
192 return render_to_response(
193 request,
194 'mediagoblin/user_pages/media_collect.html',
195 {'media': media,
196 'form': form})
197
198 # If we are here, method=POST and the form is valid, submit things.
199 # If the user is adding a new collection, use that:
200 if request.form['collection_title']:
201 # Make sure this user isn't duplicating an existing collection
202 existing_collection = Collection.query.filter_by(
203 creator=request.user.id,
204 title=request.form['collection_title']).first()
205 if existing_collection:
206 messages.add_message(request, messages.ERROR,
207 _('You already have a collection called "%s"!'
208 % collection.title))
209 return redirect(request, "mediagoblin.user_pages.media_home",
210 user=request.user.username,
211 media=media.id)
212
213 collection = Collection()
214 collection.title = request.form['collection_title']
215 collection.description = request.form.get('collection_description')
216 collection.creator = request.user.id
217 collection.generate_slug()
218 collection.save(validate=True)
219
220 # Otherwise, use the collection selected from the drop-down
221 else:
222 collection = Collection.query.filter_by(
223 id=request.form.get('collection')).first()
224
225 # Make sure the user actually selected a collection
226 if not collection:
227 messages.add_message(
228 request, messages.ERROR,
229 _('You have to select or add a collection'))
230
231 # Check whether media already exists in collection
232 elif CollectionItem.query.filter_by(
233 media_entry=media.id,
234 collection=collection.id).first():
235 messages.add_message(request, messages.ERROR,
236 _('"%s" already in collection "%s"'
237 % (media.title, collection.title)))
238 else: # Add item to collection
239 collection_item = request.db.CollectionItem()
240 collection_item.collection = collection.id
241 collection_item.media_entry = media.id
242 collection_item.author = request.user.id
243 collection_item.note = request.form['note']
244 collection_item.save(validate=True)
245
246 collection.items = collection.items + 1
247 collection.save(validate=True)
248
249 media.collected = media.collected + 1
250 media.save()
251
252 messages.add_message(request, messages.SUCCESS,
253 _('"%s" added to collection "%s"'
254 % (media.title, collection.title)))
255
256 return redirect(request, "mediagoblin.user_pages.media_home",
257 user=media.get_uploader.username,
258 media=media.id)
259
260
261 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
262 @get_user_media_entry
263 @require_active_login
264 @user_may_delete_media
265 def media_confirm_delete(request, media):
266
267 form = user_forms.ConfirmDeleteForm(request.form)
268
269 if request.method == 'POST' and form.validate():
270 if form.confirm.data is True:
271 username = media.get_uploader.username
272
273 # Delete all the associated comments
274 for comment in media.get_comments():
275 comment.delete()
276
277 # Delete all files on the public storage
278 try:
279 delete_media_files(media)
280 except OSError, error:
281 _log.error('No such files from the user "{1}"'
282 ' to delete: {0}'.format(str(error), username))
283 messages.add_message(request, messages.ERROR,
284 _('Some of the files with this entry seem'
285 ' to be missing. Deleting anyway.'))
286
287 media.delete()
288 messages.add_message(
289 request, messages.SUCCESS, _('You deleted the media.'))
290
291 return redirect(request, "mediagoblin.user_pages.user_home",
292 user=username)
293 else:
294 messages.add_message(
295 request, messages.ERROR,
296 _("The media was not deleted because you didn't check that you were sure."))
297 return redirect(request,
298 location=media.url_for_self(request.urlgen))
299
300 if ((request.user.is_admin and
301 request.user.id != media.uploader)):
302 messages.add_message(
303 request, messages.WARNING,
304 _("You are about to delete another user's media. "
305 "Proceed with caution."))
306
307 return render_to_response(
308 request,
309 'mediagoblin/user_pages/media_confirm_delete.html',
310 {'media': media,
311 'form': form})
312
313
314 @active_user_from_url
315 @uses_pagination
316 def user_collection(request, page, url_user=None):
317 """A User-defined Collection"""
318 collection = Collection.query.filter_by(
319 get_creator=url_user,
320 slug=request.matchdict['collection']).first()
321
322 cursor = collection.get_collection_items()
323
324 pagination = Pagination(page, cursor)
325 collection_items = pagination()
326
327 # if no data is available, return NotFound
328 # TODO: Should an empty collection really also return 404?
329 if collection_items == None:
330 return render_404(request)
331
332 return render_to_response(
333 request,
334 'mediagoblin/user_pages/collection.html',
335 {'user': url_user,
336 'collection': collection,
337 'collection_items': collection_items,
338 'pagination': pagination})
339
340
341 @get_user_collection_item
342 @require_active_login
343 @user_may_alter_collection
344 def collection_item_confirm_remove(request, collection_item):
345
346 form = user_forms.ConfirmCollectionItemRemoveForm(request.form)
347
348 if request.method == 'POST' and form.validate():
349 username = collection_item.in_collection.get_creator.username
350 collection = collection_item.in_collection
351
352 if form.confirm.data is True:
353 entry = collection_item.get_media_entry
354 entry.collected = entry.collected - 1
355 entry.save()
356
357 collection_item.delete()
358 collection.items = collection.items - 1
359 collection.save()
360
361 messages.add_message(
362 request, messages.SUCCESS, _('You deleted the item from the collection.'))
363 else:
364 messages.add_message(
365 request, messages.ERROR,
366 _("The item was not removed because you didn't check that you were sure."))
367
368 return redirect(request, "mediagoblin.user_pages.user_collection",
369 user=username,
370 collection=collection.slug)
371
372 if ((request.user.is_admin and
373 request.user.id != collection_item.in_collection.creator)):
374 messages.add_message(
375 request, messages.WARNING,
376 _("You are about to delete an item from another user's collection. "
377 "Proceed with caution."))
378
379 return render_to_response(
380 request,
381 'mediagoblin/user_pages/collection_item_confirm_remove.html',
382 {'collection_item': collection_item,
383 'form': form})
384
385
386 @get_user_collection
387 @require_active_login
388 @user_may_alter_collection
389 def collection_confirm_delete(request, collection):
390
391 form = user_forms.ConfirmDeleteForm(request.form)
392
393 if request.method == 'POST' and form.validate():
394
395 username = collection.get_creator.username
396
397 if form.confirm.data is True:
398 collection_title = collection.title
399
400 # Delete all the associated collection items
401 for item in collection.get_collection_items():
402 entry = item.get_media_entry
403 entry.collected = entry.collected - 1
404 entry.save()
405 item.delete()
406
407 collection.delete()
408 messages.add_message(
409 request, messages.SUCCESS, _('You deleted the collection "%s"' % collection_title))
410
411 return redirect(request, "mediagoblin.user_pages.user_home",
412 user=username)
413 else:
414 messages.add_message(
415 request, messages.ERROR,
416 _("The collection was not deleted because you didn't check that you were sure."))
417
418 return redirect(request, "mediagoblin.user_pages.user_collection",
419 user=username,
420 collection=collection.slug)
421
422 if ((request.user.is_admin and
423 request.user.id != collection.creator)):
424 messages.add_message(
425 request, messages.WARNING,
426 _("You are about to delete another user's collection. "
427 "Proceed with caution."))
428
429 return render_to_response(
430 request,
431 'mediagoblin/user_pages/collection_confirm_delete.html',
432 {'collection': collection,
433 'form': form})
434
435
436 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS = 15
437
438
439 def atom_feed(request):
440 """
441 generates the atom feed with the newest images
442 """
443 user = User.query.filter_by(
444 username = request.matchdict['user'],
445 status = u'active').first()
446 if not user:
447 return render_404(request)
448
449 cursor = MediaEntry.query.filter_by(
450 uploader = user.id,
451 state = u'processed').\
452 sort('created', DESCENDING).\
453 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS)
454
455 """
456 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
457 """
458 atomlinks = [{
459 'href': request.urlgen(
460 'mediagoblin.user_pages.user_home',
461 qualified=True, user=request.matchdict['user']),
462 'rel': 'alternate',
463 'type': 'text/html'
464 }]
465
466 if mg_globals.app_config["push_urls"]:
467 for push_url in mg_globals.app_config["push_urls"]:
468 atomlinks.append({
469 'rel': 'hub',
470 'href': push_url})
471
472 feed = AtomFeed(
473 "MediaGoblin: Feed for user '%s'" % request.matchdict['user'],
474 feed_url=request.url,
475 id='tag:{host},{year}:gallery.user-{user}'.format(
476 host=request.host,
477 year=datetime.datetime.today().strftime('%Y'),
478 user=request.matchdict['user']),
479 links=atomlinks)
480
481 for entry in cursor:
482 feed.add(entry.get('title'),
483 entry.description_html,
484 id=entry.url_for_self(request.urlgen, qualified=True),
485 content_type='html',
486 author={
487 'name': entry.get_uploader.username,
488 'uri': request.urlgen(
489 'mediagoblin.user_pages.user_home',
490 qualified=True, user=entry.get_uploader.username)},
491 updated=entry.get('created'),
492 links=[{
493 'href': entry.url_for_self(
494 request.urlgen,
495 qualified=True),
496 'rel': 'alternate',
497 'type': 'text/html'}])
498
499 return feed.get_response()
500
501
502 def collection_atom_feed(request):
503 """
504 generates the atom feed with the newest images from a collection
505 """
506 user = User.query.filter_by(
507 username = request.matchdict['user'],
508 status = u'active').first()
509 if not user:
510 return render_404(request)
511
512 collection = Collection.query.filter_by(
513 creator=user.id,
514 slug=request.matchdict['collection']).first()
515
516 cursor = CollectionItem.query.filter_by(
517 collection=collection.id) \
518 .sort(CollectionItem.added.desc()) \
519 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS)
520
521 """
522 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
523 """
524 atomlinks = [{
525 'href': request.urlgen(
526 'mediagoblin.user_pages.user_collection',
527 qualified=True, user=request.matchdict['user'], collection=collection.slug),
528 'rel': 'alternate',
529 'type': 'text/html'
530 }]
531
532 if mg_globals.app_config["push_urls"]:
533 for push_url in mg_globals.app_config["push_urls"]:
534 atomlinks.append({
535 'rel': 'hub',
536 'href': push_url})
537
538 feed = AtomFeed(
539 "MediaGoblin: Feed for %s's collection %s" % (request.matchdict['user'], collection.title),
540 feed_url=request.url,
541 id='tag:{host},{year}:collection.user-{user}.title-{title}'.format(
542 host=request.host,
543 year=datetime.datetime.today().strftime('%Y'),
544 user=request.matchdict['user'],
545 title=collection.title),
546 links=atomlinks)
547
548 for item in cursor:
549 entry = item.get_media_entry
550 feed.add(entry.get('title'),
551 item.note_html,
552 id=entry.url_for_self(request.urlgen, qualified=True),
553 content_type='html',
554 author={
555 'name': entry.get_uploader.username,
556 'uri': request.urlgen(
557 'mediagoblin.user_pages.user_home',
558 qualified=True, user=entry.get_uploader.username)},
559 updated=item.get('added'),
560 links=[{
561 'href': entry.url_for_self(
562 request.urlgen,
563 qualified=True),
564 'rel': 'alternate',
565 'type': 'text/html'}])
566
567 return feed.get_response()
568
569
570 @require_active_login
571 def processing_panel(request):
572 """
573 Show to the user what media is still in conversion/processing...
574 and what failed, and why!
575 """
576 user = User.query.filter_by(username=request.matchdict['user']).first()
577 # TODO: XXX: Should this be a decorator?
578 #
579 # Make sure we have permission to access this user's panel. Only
580 # admins and this user herself should be able to do so.
581 if not (user == request.user
582 or request.user.is_admin):
583 # No? Simply redirect to this user's homepage.
584 print user
585 print request.user
586 return redirect(
587 request, 'mediagoblin.user_pages.user_home',
588 user=user.username)
589
590 # Get media entries which are in-processing
591 processing_entries = MediaEntry.query.\
592 filter_by(uploader = user.id,
593 state = u'processing').\
594 order_by(MediaEntry.created.desc())
595
596 # Get media entries which have failed to process
597 failed_entries = MediaEntry.query.\
598 filter_by(uploader = user.id,
599 state = u'failed').\
600 order_by(MediaEntry.created.desc())
601
602 processed_entries = MediaEntry.query.\
603 filter_by(uploader = user.id,
604 state = u'processed').\
605 order_by(MediaEntry.created.desc()).\
606 limit(10)
607
608 # Render to response
609 return render_to_response(
610 request,
611 'mediagoblin/user_pages/processing_panel.html',
612 {'user': user,
613 'processing_entries': processing_entries,
614 'failed_entries': failed_entries,
615 'processed_entries': processed_entries})