1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
20 from mediagoblin
import messages
, mg_globals
21 from mediagoblin
.db
.models
import (MediaEntry
, MediaTag
, Collection
,
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
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
)
37 from werkzeug
.contrib
.atom
import AtomFeed
38 from werkzeug
.exceptions
import MethodNotAllowed
41 _log
= logging
.getLogger(__name__
)
42 _log
.setLevel(logging
.DEBUG
)
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
51 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
53 return render_404(request
)
54 elif user
.status
!= u
'active':
55 return render_to_response(
57 'mediagoblin/user_pages/user.html',
60 cursor
= MediaEntry
.query
.\
61 filter_by(uploader
= user
.id,
62 state
= u
'processed').order_by(MediaEntry
.created
.desc())
64 pagination
= Pagination(page
, cursor
)
65 media_entries
= pagination()
67 #if no data is available, return NotFound
68 if media_entries
== None:
69 return render_404(request
)
71 user_gallery_url
= request
.urlgen(
72 'mediagoblin.user_pages.user_gallery',
75 return render_to_response(
77 'mediagoblin/user_pages/user.html',
79 'user_gallery_url': user_gallery_url
,
80 'media_entries': media_entries
,
81 'pagination': 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(
91 state
=u
'processed').order_by(MediaEntry
.created
.desc())
93 # Filter potentially by tag too:
95 cursor
= cursor
.filter(
96 MediaEntry
.tags_helper
.any(
97 MediaTag
.slug
== request
.matchdict
['tag']))
100 pagination
= Pagination(page
, cursor
)
101 media_entries
= pagination()
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
)
108 return render_to_response(
110 'mediagoblin/user_pages/gallery.html',
111 {'user': url_user
, 'tag': tag
,
112 'media_entries': media_entries
,
113 'pagination': pagination
})
116 MEDIA_COMMENTS_PER_PAGE
= 50
119 @get_user_media_entry
121 def media_home(request
, media
, page
, **kwargs
):
123 'Homepage' of a MediaEntry()
125 comment_id
= request
.matchdict
.get('comment', None)
128 mark_comment_notification_seen(comment_id
, request
.user
)
130 pagination
= Pagination(
131 page
, media
.get_comments(
132 mg_globals
.app_config
['comments_ascending']),
133 MEDIA_COMMENTS_PER_PAGE
,
136 pagination
= Pagination(
137 page
, media
.get_comments(
138 mg_globals
.app_config
['comments_ascending']),
139 MEDIA_COMMENTS_PER_PAGE
)
141 comments
= pagination()
143 comment_form
= user_forms
.MediaCommentForm(request
.form
)
145 media_template_name
= media
.media_manager
.display_template
147 return render_to_response(
151 'comments': comments
,
152 'pagination': pagination
,
153 'comment_form': comment_form
,
154 'app_config': mg_globals
.app_config
})
157 @get_media_entry_by_id
158 @require_active_login
159 def media_post_comment(request
, media
):
161 recieves POST from a MediaEntry() comment form, saves the comment.
163 if not request
.method
== 'POST':
164 raise MethodNotAllowed()
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'])
171 # Show error message if commenting is disabled.
172 if not mg_globals
.app_config
['allow_comments']:
173 messages
.add_message(
176 _("Sorry, comments are disabled."))
177 elif not comment
.content
.strip():
178 messages
.add_message(
181 _("Oops, your comment was empty."))
185 messages
.add_message(
186 request
, messages
.SUCCESS
,
187 _('Your comment has been posted!'))
189 trigger_notification(comment
, media
, request
)
191 add_comment_subscription(request
.user
, media
)
193 return redirect_obj(request
, media
)
196 @get_media_entry_by_id
197 @require_active_login
198 def media_collect(request
, media
):
199 """Add media to collection submission"""
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
)
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.'))
212 return render_to_response(
214 'mediagoblin/user_pages/media_collect.html',
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
)
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()
240 # Otherwise, use the collection selected from the drop-down
242 collection
= form
.collection
.data
243 if collection
and collection
.creator
!= request
.user
.id:
246 # Make sure the user actually selected a 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
,
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
)
266 messages
.add_message(request
, messages
.SUCCESS
,
267 _('"%s" added to collection "%s"')
268 % (media
.title
, collection
.title
))
270 return redirect_obj(request
, media
)
273 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
275 @require_active_login
276 def media_confirm_delete(request
):
278 allowed_state
= [u
'failed', u
'processed']
280 for media_state
in allowed_state
:
281 media
= request
.db
.MediaEntry
.query
.filter_by(id=request
.matchdict
['media_id'], state
=media_state
).first()
286 return render_404(request
)
288 given_username
= request
.matchdict
.get('user')
289 if given_username
and (given_username
!= media
.get_uploader
.username
):
290 return render_404(request
)
292 uploader_id
= media
.uploader
293 if not (request
.user
.is_admin
or
294 request
.user
.id == uploader_id
):
297 form
= user_forms
.ConfirmDeleteForm(request
.form
)
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.
304 messages
.add_message(
305 request
, messages
.SUCCESS
, _('You deleted the media.'))
307 return redirect(request
, "mediagoblin.user_pages.user_home",
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
)
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."))
322 return render_to_response(
324 'mediagoblin/user_pages/media_confirm_delete.html',
329 @active_user_from_url
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()
338 return render_404(request
)
340 cursor
= collection
.get_collection_items()
342 pagination
= Pagination(page
, cursor
)
343 collection_items
= pagination()
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
)
350 return render_to_response(
352 'mediagoblin/user_pages/collection.html',
354 'collection': collection
,
355 'collection_items': collection_items
,
356 'pagination': pagination
})
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
)
365 return render_to_response(
367 'mediagoblin/user_pages/collection_list.html',
369 'collections': collections
})
372 @get_user_collection_item
373 @require_active_login
374 @user_may_alter_collection
375 def collection_item_confirm_remove(request
, collection_item
):
377 form
= user_forms
.ConfirmCollectionItemRemoveForm(request
.form
)
379 if request
.method
== 'POST' and form
.validate():
380 username
= collection_item
.in_collection
.get_creator
.username
381 collection
= collection_item
.in_collection
383 if form
.confirm
.data
is True:
384 entry
= collection_item
.get_media_entry
385 entry
.collected
= entry
.collected
- 1
388 collection_item
.delete()
389 collection
.items
= collection
.items
- 1
392 messages
.add_message(
393 request
, messages
.SUCCESS
, _('You deleted the item from the collection.'))
395 messages
.add_message(
396 request
, messages
.ERROR
,
397 _("The item was not removed because you didn't check that you were sure."))
399 return redirect_obj(request
, collection
)
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."))
408 return render_to_response(
410 'mediagoblin/user_pages/collection_item_confirm_remove.html',
411 {'collection_item': collection_item
,
416 @require_active_login
417 @user_may_alter_collection
418 def collection_confirm_delete(request
, collection
):
420 form
= user_forms
.ConfirmDeleteForm(request
.form
)
422 if request
.method
== 'POST' and form
.validate():
424 username
= collection
.get_creator
.username
426 if form
.confirm
.data
is True:
427 collection_title
= collection
.title
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
437 messages
.add_message(request
, messages
.SUCCESS
,
438 _('You deleted the collection "%s"') % collection_title
)
440 return redirect(request
, "mediagoblin.user_pages.user_home",
443 messages
.add_message(
444 request
, messages
.ERROR
,
445 _("The collection was not deleted because you didn't check that you were sure."))
447 return redirect_obj(request
, collection
)
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."))
456 return render_to_response(
458 'mediagoblin/user_pages/collection_confirm_delete.html',
459 {'collection': collection
,
463 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
= 15
466 def atom_feed(request
):
468 generates the atom feed with the newest images
470 user
= User
.query
.filter_by(
471 username
= request
.matchdict
['user'],
472 status
= u
'active').first()
474 return render_404(request
)
476 cursor
= MediaEntry
.query
.filter_by(
478 state
= u
'processed').\
479 order_by(MediaEntry
.created
.desc()).\
480 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
483 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
486 'href': request
.urlgen(
487 'mediagoblin.user_pages.user_home',
488 qualified
=True, user
=request
.matchdict
['user']),
493 if mg_globals
.app_config
["push_urls"]:
494 for push_url
in mg_globals
.app_config
["push_urls"]:
500 "MediaGoblin: Feed for user '%s'" % request
.matchdict
['user'],
501 feed_url
=request
.url
,
502 id='tag:{host},{year}:gallery.user-{user}'.format(
504 year
=datetime
.datetime
.today().strftime('%Y'),
505 user
=request
.matchdict
['user']),
509 feed
.add(entry
.get('title'),
510 entry
.description_html
,
511 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
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'),
520 'href': entry
.url_for_self(
524 'type': 'text/html'}])
526 return feed
.get_response()
529 def collection_atom_feed(request
):
531 generates the atom feed with the newest images from a collection
533 user
= User
.query
.filter_by(
534 username
= request
.matchdict
['user'],
535 status
= u
'active').first()
537 return render_404(request
)
539 collection
= Collection
.query
.filter_by(
541 slug
=request
.matchdict
['collection']).first()
543 return render_404(request
)
545 cursor
= CollectionItem
.query
.filter_by(
546 collection
=collection
.id) \
547 .order_by(CollectionItem
.added
.desc()) \
548 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
551 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
554 'href': collection
.url_for_self(request
.urlgen
, qualified
=True),
559 if mg_globals
.app_config
["push_urls"]:
560 for push_url
in mg_globals
.app_config
["push_urls"]:
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}'\
572 year
=collection
.created
.strftime('%Y'),
573 user
=request
.matchdict
['user'],
574 slug
=collection
.slug
),
578 entry
= item
.get_media_entry
579 feed
.add(entry
.get('title'),
581 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
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'),
590 'href': entry
.url_for_self(
594 'type': 'text/html'}])
596 return feed
.get_response()
599 @require_active_login
600 def processing_panel(request
):
602 Show to the user what media is still in conversion/processing...
603 and what failed, and why!
605 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
606 # TODO: XXX: Should this be a decorator?
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.
613 request
, 'mediagoblin.user_pages.user_home',
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())
622 # Get media entries which have failed to process
623 failed_entries
= MediaEntry
.query
.\
624 filter_by(uploader
= user
.id,
626 order_by(MediaEntry
.created
.desc())
628 processed_entries
= MediaEntry
.query
.\
629 filter_by(uploader
= user
.id,
630 state
= u
'processed').\
631 order_by(MediaEntry
.created
.desc()).\
635 return render_to_response(
637 'mediagoblin/user_pages/processing_panel.html',
639 'processing_entries': processing_entries
,
640 'failed_entries': failed_entries
,
641 'processed_entries': processed_entries
})