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