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/>.
21 from mediagoblin
import messages
, mg_globals
22 from mediagoblin
.db
.models
import (MediaEntry
, MediaTag
, Collection
,
23 CollectionItem
, User
, MediaComment
,
24 CommentReport
, MediaReport
)
25 from mediagoblin
.tools
.response
import render_to_response
, render_404
, \
26 redirect
, redirect_obj
27 from mediagoblin
.tools
.text
import cleaned_markdown_conversion
28 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
29 from mediagoblin
.tools
.pagination
import Pagination
30 from mediagoblin
.user_pages
import forms
as user_forms
31 from mediagoblin
.user_pages
.lib
import (send_comment_email
,
32 add_media_to_collection
, build_report_object
)
33 from mediagoblin
.notifications
import trigger_notification
, \
34 add_comment_subscription
, mark_comment_notification_seen
36 from mediagoblin
.decorators
import (uses_pagination
, get_user_media_entry
,
37 get_media_entry_by_id
, user_has_privilege
,
38 require_active_login
, user_may_delete_media
, user_may_alter_collection
,
39 get_user_collection
, get_user_collection_item
, active_user_from_url
,
40 get_media_comment_by_id
, user_not_banned
)
42 from werkzeug
.contrib
.atom
import AtomFeed
43 from werkzeug
.exceptions
import MethodNotAllowed
44 from werkzeug
.wrappers
import Response
47 _log
= logging
.getLogger(__name__
)
48 _log
.setLevel(logging
.DEBUG
)
52 def user_home(request
, page
):
53 """'Homepage' of a User()"""
54 # TODO: decide if we only want homepages for active users, we can
55 # then use the @get_active_user decorator and also simplify the
57 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
59 return render_404(request
)
60 elif user
.status
!= u
'active':
61 return render_to_response(
63 'mediagoblin/user_pages/user.html',
66 cursor
= MediaEntry
.query
.\
67 filter_by(uploader
= user
.id,
68 state
= u
'processed').order_by(MediaEntry
.created
.desc())
70 pagination
= Pagination(page
, cursor
)
71 media_entries
= pagination()
73 #if no data is available, return NotFound
74 if media_entries
== None:
75 return render_404(request
)
77 user_gallery_url
= request
.urlgen(
78 'mediagoblin.user_pages.user_gallery',
81 return render_to_response(
83 'mediagoblin/user_pages/user.html',
85 'user_gallery_url': user_gallery_url
,
86 'media_entries': media_entries
,
87 'pagination': pagination
})
92 def user_gallery(request
, page
, url_user
=None):
93 """'Gallery' of a User()"""
94 tag
= request
.matchdict
.get('tag', None)
95 cursor
= MediaEntry
.query
.filter_by(
97 state
=u
'processed').order_by(MediaEntry
.created
.desc())
99 # Filter potentially by tag too:
101 cursor
= cursor
.filter(
102 MediaEntry
.tags_helper
.any(
103 MediaTag
.slug
== request
.matchdict
['tag']))
106 pagination
= Pagination(page
, cursor
)
107 media_entries
= pagination()
109 #if no data is available, return NotFound
110 # TODO: Should we really also return 404 for empty galleries?
111 if media_entries
== None:
112 return render_404(request
)
114 return render_to_response(
116 'mediagoblin/user_pages/gallery.html',
117 {'user': url_user
, 'tag': tag
,
118 'media_entries': media_entries
,
119 'pagination': pagination
})
122 MEDIA_COMMENTS_PER_PAGE
= 50
125 @get_user_media_entry
127 def media_home(request
, media
, page
, **kwargs
):
129 'Homepage' of a MediaEntry()
131 comment_id
= request
.matchdict
.get('comment', None)
134 mark_comment_notification_seen(comment_id
, request
.user
)
136 pagination
= Pagination(
137 page
, media
.get_comments(
138 mg_globals
.app_config
['comments_ascending']),
139 MEDIA_COMMENTS_PER_PAGE
,
142 pagination
= Pagination(
143 page
, media
.get_comments(
144 mg_globals
.app_config
['comments_ascending']),
145 MEDIA_COMMENTS_PER_PAGE
)
147 comments
= pagination()
149 comment_form
= user_forms
.MediaCommentForm(request
.form
)
151 media_template_name
= media
.media_manager
.display_template
153 return render_to_response(
157 'comments': comments
,
158 'pagination': pagination
,
159 'comment_form': comment_form
,
160 'app_config': mg_globals
.app_config
})
163 @get_media_entry_by_id
164 @require_active_login
165 @user_has_privilege(u
'commenter')
166 def media_post_comment(request
, media
):
168 recieves POST from a MediaEntry() comment form, saves the comment.
170 if not request
.method
== 'POST':
171 raise MethodNotAllowed()
173 comment
= request
.db
.MediaComment()
174 comment
.media_entry
= media
.id
175 comment
.author
= request
.user
.id
176 comment
.content
= unicode(request
.form
['comment_content'])
178 # Show error message if commenting is disabled.
179 if not mg_globals
.app_config
['allow_comments']:
180 messages
.add_message(
183 _("Sorry, comments are disabled."))
184 elif not comment
.content
.strip():
185 messages
.add_message(
188 _("Oops, your comment was empty."))
192 messages
.add_message(
193 request
, messages
.SUCCESS
,
194 _('Your comment has been posted!'))
196 trigger_notification(comment
, media
, request
)
198 add_comment_subscription(request
.user
, media
)
200 return redirect_obj(request
, media
)
203 @get_media_entry_by_id
204 @require_active_login
205 def media_collect(request
, media
):
206 """Add media to collection submission"""
208 form
= user_forms
.MediaCollectForm(request
.form
)
209 # A user's own collections:
210 form
.collection
.query
= Collection
.query
.filter_by(
211 creator
= request
.user
.id).order_by(Collection
.title
)
213 if request
.method
!= 'POST' or not form
.validate():
214 # No POST submission, or invalid form
215 if not form
.validate():
216 messages
.add_message(request
, messages
.ERROR
,
217 _('Please check your entries and try again.'))
219 return render_to_response(
221 'mediagoblin/user_pages/media_collect.html',
225 # If we are here, method=POST and the form is valid, submit things.
226 # If the user is adding a new collection, use that:
227 if form
.collection_title
.data
:
228 # Make sure this user isn't duplicating an existing collection
229 existing_collection
= Collection
.query
.filter_by(
230 creator
=request
.user
.id,
231 title
=form
.collection_title
.data
).first()
232 if existing_collection
:
233 messages
.add_message(request
, messages
.ERROR
,
234 _('You already have a collection called "%s"!')
235 % existing_collection
.title
)
236 return redirect(request
, "mediagoblin.user_pages.media_home",
237 user
=media
.get_uploader
.username
,
238 media
=media
.slug_or_id
)
240 collection
= Collection()
241 collection
.title
= form
.collection_title
.data
242 collection
.description
= form
.collection_description
.data
243 collection
.creator
= request
.user
.id
244 collection
.generate_slug()
247 # Otherwise, use the collection selected from the drop-down
249 collection
= form
.collection
.data
250 if collection
and collection
.creator
!= request
.user
.id:
253 # Make sure the user actually selected a collection
255 messages
.add_message(
256 request
, messages
.ERROR
,
257 _('You have to select or add a collection'))
258 return redirect(request
, "mediagoblin.user_pages.media_collect",
259 user
=media
.get_uploader
.username
,
263 # Check whether media already exists in collection
264 elif CollectionItem
.query
.filter_by(
265 media_entry
=media
.id,
266 collection
=collection
.id).first():
267 messages
.add_message(request
, messages
.ERROR
,
268 _('"%s" already in collection "%s"')
269 % (media
.title
, collection
.title
))
270 else: # Add item to collection
271 add_media_to_collection(collection
, media
, form
.note
.data
)
273 messages
.add_message(request
, messages
.SUCCESS
,
274 _('"%s" added to collection "%s"')
275 % (media
.title
, collection
.title
))
277 return redirect_obj(request
, media
)
280 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
282 @get_media_entry_by_id
283 @require_active_login
284 @user_may_delete_media
285 def media_confirm_delete(request
, media
):
287 form
= user_forms
.ConfirmDeleteForm(request
.form
)
289 if request
.method
== 'POST' and form
.validate():
290 if form
.confirm
.data
is True:
291 username
= media
.get_uploader
.username
292 # Delete MediaEntry and all related files, comments etc.
294 messages
.add_message(
295 request
, messages
.SUCCESS
, _('You deleted the media.'))
297 location
= media
.url_to_next(request
.urlgen
)
299 location
=media
.url_to_prev(request
.urlgen
)
301 location
=request
.urlgen("mediagoblin.user_pages.user_home",
303 return redirect(request
, location
=location
)
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 redirect_obj(request
, media
)
310 if ((request
.user
.has_privilege(u
'admin') and
311 request
.user
.id != media
.uploader
)):
312 messages
.add_message(
313 request
, messages
.WARNING
,
314 _("You are about to delete another user's media. "
315 "Proceed with caution."))
317 return render_to_response(
319 'mediagoblin/user_pages/media_confirm_delete.html',
324 @active_user_from_url
326 def user_collection(request
, page
, url_user
=None):
327 """A User-defined Collection"""
328 collection
= Collection
.query
.filter_by(
329 get_creator
=url_user
,
330 slug
=request
.matchdict
['collection']).first()
333 return render_404(request
)
335 cursor
= collection
.get_collection_items()
337 pagination
= Pagination(page
, cursor
)
338 collection_items
= pagination()
340 # if no data is available, return NotFound
341 # TODO: Should an empty collection really also return 404?
342 if collection_items
== None:
343 return render_404(request
)
345 return render_to_response(
347 'mediagoblin/user_pages/collection.html',
349 'collection': collection
,
350 'collection_items': collection_items
,
351 'pagination': pagination
})
354 @active_user_from_url
355 def collection_list(request
, url_user
=None):
356 """A User-defined Collection"""
357 collections
= Collection
.query
.filter_by(
358 get_creator
=url_user
)
360 return render_to_response(
362 'mediagoblin/user_pages/collection_list.html',
364 'collections': collections
})
367 @get_user_collection_item
368 @require_active_login
369 @user_may_alter_collection
370 def collection_item_confirm_remove(request
, collection_item
):
372 form
= user_forms
.ConfirmCollectionItemRemoveForm(request
.form
)
374 if request
.method
== 'POST' and form
.validate():
375 username
= collection_item
.in_collection
.get_creator
.username
376 collection
= collection_item
.in_collection
378 if form
.confirm
.data
is True:
379 entry
= collection_item
.get_media_entry
380 entry
.collected
= entry
.collected
- 1
383 collection_item
.delete()
384 collection
.items
= collection
.items
- 1
387 messages
.add_message(
388 request
, messages
.SUCCESS
, _('You deleted the item from the collection.'))
390 messages
.add_message(
391 request
, messages
.ERROR
,
392 _("The item was not removed because you didn't check that you were sure."))
394 return redirect_obj(request
, collection
)
396 if ((request
.user
.has_privilege(u
'admin') and
397 request
.user
.id != collection_item
.in_collection
.creator
)):
398 messages
.add_message(
399 request
, messages
.WARNING
,
400 _("You are about to delete an item from another user's collection. "
401 "Proceed with caution."))
403 return render_to_response(
405 'mediagoblin/user_pages/collection_item_confirm_remove.html',
406 {'collection_item': collection_item
,
411 @require_active_login
412 @user_may_alter_collection
413 def collection_confirm_delete(request
, collection
):
415 form
= user_forms
.ConfirmDeleteForm(request
.form
)
417 if request
.method
== 'POST' and form
.validate():
419 username
= collection
.get_creator
.username
421 if form
.confirm
.data
is True:
422 collection_title
= collection
.title
424 # Delete all the associated collection items
425 for item
in collection
.get_collection_items():
426 entry
= item
.get_media_entry
427 entry
.collected
= entry
.collected
- 1
432 messages
.add_message(request
, messages
.SUCCESS
,
433 _('You deleted the collection "%s"') % collection_title
)
435 return redirect(request
, "mediagoblin.user_pages.user_home",
438 messages
.add_message(
439 request
, messages
.ERROR
,
440 _("The collection was not deleted because you didn't check that you were sure."))
442 return redirect_obj(request
, collection
)
444 if ((request
.user
.has_privilege(u
'admin') and
445 request
.user
.id != collection
.creator
)):
446 messages
.add_message(
447 request
, messages
.WARNING
,
448 _("You are about to delete another user's collection. "
449 "Proceed with caution."))
451 return render_to_response(
453 'mediagoblin/user_pages/collection_confirm_delete.html',
454 {'collection': collection
,
458 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
= 15
461 def atom_feed(request
):
463 generates the atom feed with the newest images
465 user
= User
.query
.filter_by(
466 username
= request
.matchdict
['user'],
467 status
= u
'active').first()
469 return render_404(request
)
471 cursor
= MediaEntry
.query
.filter_by(
473 state
= u
'processed').\
474 order_by(MediaEntry
.created
.desc()).\
475 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
478 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
481 'href': request
.urlgen(
482 'mediagoblin.user_pages.user_home',
483 qualified
=True, user
=request
.matchdict
['user']),
488 if mg_globals
.app_config
["push_urls"]:
489 for push_url
in mg_globals
.app_config
["push_urls"]:
495 "MediaGoblin: Feed for user '%s'" % request
.matchdict
['user'],
496 feed_url
=request
.url
,
497 id='tag:{host},{year}:gallery.user-{user}'.format(
499 year
=datetime
.datetime
.today().strftime('%Y'),
500 user
=request
.matchdict
['user']),
504 feed
.add(entry
.get('title'),
505 entry
.description_html
,
506 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
509 'name': entry
.get_uploader
.username
,
510 'uri': request
.urlgen(
511 'mediagoblin.user_pages.user_home',
512 qualified
=True, user
=entry
.get_uploader
.username
)},
513 updated
=entry
.get('created'),
515 'href': entry
.url_for_self(
519 'type': 'text/html'}])
521 return feed
.get_response()
524 def collection_atom_feed(request
):
526 generates the atom feed with the newest images from a collection
528 user
= User
.query
.filter_by(
529 username
= request
.matchdict
['user'],
530 status
= u
'active').first()
532 return render_404(request
)
534 collection
= Collection
.query
.filter_by(
536 slug
=request
.matchdict
['collection']).first()
538 return render_404(request
)
540 cursor
= CollectionItem
.query
.filter_by(
541 collection
=collection
.id) \
542 .order_by(CollectionItem
.added
.desc()) \
543 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
546 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
549 'href': collection
.url_for_self(request
.urlgen
, qualified
=True),
554 if mg_globals
.app_config
["push_urls"]:
555 for push_url
in mg_globals
.app_config
["push_urls"]:
561 "MediaGoblin: Feed for %s's collection %s" %
562 (request
.matchdict
['user'], collection
.title
),
563 feed_url
=request
.url
,
564 id=u
'tag:{host},{year}:gnu-mediagoblin.{user}.collection.{slug}'\
567 year
=collection
.created
.strftime('%Y'),
568 user
=request
.matchdict
['user'],
569 slug
=collection
.slug
),
573 entry
= item
.get_media_entry
574 feed
.add(entry
.get('title'),
576 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
579 'name': entry
.get_uploader
.username
,
580 'uri': request
.urlgen(
581 'mediagoblin.user_pages.user_home',
582 qualified
=True, user
=entry
.get_uploader
.username
)},
583 updated
=item
.get('added'),
585 'href': entry
.url_for_self(
589 'type': 'text/html'}])
591 return feed
.get_response()
594 @require_active_login
595 def processing_panel(request
):
597 Show to the user what media is still in conversion/processing...
598 and what failed, and why!
600 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
601 # TODO: XXX: Should this be a decorator?
603 # Make sure we have permission to access this user's panel. Only
604 # admins and this user herself should be able to do so.
605 if not (user
.id == request
.user
.id or request
.user
.has_privilege(u
'admin')):
606 # No? Simply redirect to this user's homepage.
608 request
, 'mediagoblin.user_pages.user_home',
611 # Get media entries which are in-processing
612 processing_entries
= MediaEntry
.query
.\
613 filter_by(uploader
= user
.id,
614 state
= u
'processing').\
615 order_by(MediaEntry
.created
.desc())
617 # Get media entries which have failed to process
618 failed_entries
= MediaEntry
.query
.\
619 filter_by(uploader
= user
.id,
621 order_by(MediaEntry
.created
.desc())
623 processed_entries
= MediaEntry
.query
.\
624 filter_by(uploader
= user
.id,
625 state
= u
'processed').\
626 order_by(MediaEntry
.created
.desc()).\
630 return render_to_response(
632 'mediagoblin/user_pages/processing_panel.html',
634 'processing_entries': processing_entries
,
635 'failed_entries': failed_entries
,
636 'processed_entries': processed_entries
})
638 @require_active_login
639 @get_user_media_entry
640 @user_has_privilege(u
'reporter')
641 def file_a_report(request
, media
, comment
=None):
642 if comment
is not None:
643 form
= user_forms
.CommentReportForm(request
.form
)
644 form
.reporter_id
.data
= request
.user
.id
645 context
= {'media': media
,
649 form
= user_forms
.MediaReportForm(request
.form
)
650 form
.reporter_id
.data
= request
.user
.id
651 context
= {'media': media
,
654 if request
.method
== "POST":
655 report_object
= build_report_object(form
,
659 # if the object was built successfully, report_table will not be None
667 return render_to_response(
669 'mediagoblin/user_pages/report.html',
672 @require_active_login
673 @get_user_media_entry
674 @get_media_comment_by_id
675 def file_a_comment_report(request
, media
, comment
):
676 return file_a_report(request
, comment
=comment
)