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/>.
23 from mediagoblin
import messages
, mg_globals
24 from mediagoblin
.db
.models
import (MediaEntry
, MediaTag
, Collection
,
25 CollectionItem
, LocalUser
, Activity
)
26 from mediagoblin
.tools
.response
import render_to_response
, render_404
, \
27 redirect
, redirect_obj
28 from mediagoblin
.tools
.text
import cleaned_markdown_conversion
29 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
30 from mediagoblin
.tools
.pagination
import Pagination
31 from mediagoblin
.tools
.federation
import create_activity
32 from mediagoblin
.user_pages
import forms
as user_forms
33 from mediagoblin
.user_pages
.lib
import (send_comment_email
,
34 add_media_to_collection
, build_report_object
)
35 from mediagoblin
.notifications
import trigger_notification
, \
36 add_comment_subscription
, mark_comment_notification_seen
37 from mediagoblin
.tools
.pluginapi
import hook_transform
39 from mediagoblin
.decorators
import (uses_pagination
, get_user_media_entry
,
40 get_media_entry_by_id
, user_has_privilege
, user_not_banned
,
41 require_active_login
, user_may_delete_media
, user_may_alter_collection
,
42 get_user_collection
, get_user_collection_item
, active_user_from_url
,
43 get_optional_media_comment_by_id
, allow_reporting
)
45 from werkzeug
.contrib
.atom
import AtomFeed
46 from werkzeug
.exceptions
import MethodNotAllowed
47 from werkzeug
.wrappers
import Response
50 _log
= logging
.getLogger(__name__
)
51 _log
.setLevel(logging
.DEBUG
)
55 def user_home(request
, page
):
56 """'Homepage' of a LocalUser()"""
57 user
= LocalUser
.query
.filter_by(username
=request
.matchdict
['user']).first()
59 return render_404(request
)
60 elif not user
.has_privilege(u
'active'):
61 return render_to_response(
63 'mediagoblin/user_pages/user_nonactive.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 LocalUser()"""
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
155 'comments': comments
,
156 'pagination': pagination
,
157 'comment_form': comment_form
,
158 'app_config': mg_globals
.app_config
}
160 # Since the media template name gets swapped out for each media
161 # type, normal context hooks don't work if you want to affect all
162 # media displays. This gives a general purpose hook.
163 context
= hook_transform(
164 "media_home_context", context
)
166 return render_to_response(
172 @get_media_entry_by_id
173 @user_has_privilege(u
'commenter')
174 def media_post_comment(request
, media
):
176 recieves POST from a MediaEntry() comment form, saves the comment.
178 if not request
.method
== 'POST':
179 raise MethodNotAllowed()
181 comment
= request
.db
.MediaComment()
182 comment
.media_entry
= media
.id
183 comment
.author
= request
.user
.id
184 comment
.content
= six
.text_type(request
.form
['comment_content'])
186 # Show error message if commenting is disabled.
187 if not mg_globals
.app_config
['allow_comments']:
188 messages
.add_message(
191 _("Sorry, comments are disabled."))
192 elif not comment
.content
.strip():
193 messages
.add_message(
196 _("Oops, your comment was empty."))
198 create_activity("post", comment
, comment
.author
, target
=media
)
199 add_comment_subscription(request
.user
, media
)
202 messages
.add_message(
203 request
, messages
.SUCCESS
,
204 _('Your comment has been posted!'))
205 trigger_notification(comment
, media
, request
)
207 return redirect_obj(request
, media
)
211 def media_preview_comment(request
):
212 """Runs a comment through markdown so it can be previewed."""
213 # If this isn't an ajax request, render_404
214 if not request
.is_xhr
:
215 return render_404(request
)
217 comment
= six
.text_type(request
.form
['comment_content'])
218 cleancomment
= { "content":cleaned_markdown_conversion(comment
)}
220 return Response(json
.dumps(cleancomment
))
223 @get_media_entry_by_id
224 @require_active_login
225 def media_collect(request
, media
):
226 """Add media to collection submission"""
228 form
= user_forms
.MediaCollectForm(request
.form
)
229 # A user's own collections:
230 form
.collection
.query
= Collection
.query
.filter_by(
231 creator
= request
.user
.id).order_by(Collection
.title
)
233 if request
.method
!= 'POST' or not form
.validate():
234 # No POST submission, or invalid form
235 if not form
.validate():
236 messages
.add_message(request
, messages
.ERROR
,
237 _('Please check your entries and try again.'))
239 return render_to_response(
241 'mediagoblin/user_pages/media_collect.html',
245 # If we are here, method=POST and the form is valid, submit things.
246 # If the user is adding a new collection, use that:
247 if form
.collection_title
.data
:
248 # Make sure this user isn't duplicating an existing collection
249 existing_collection
= Collection
.query
.filter_by(
250 creator
=request
.user
.id,
251 title
=form
.collection_title
.data
).first()
252 if existing_collection
:
253 messages
.add_message(request
, messages
.ERROR
,
254 _('You already have a collection called "%s"!')
255 % existing_collection
.title
)
256 return redirect(request
, "mediagoblin.user_pages.media_home",
257 user
=media
.get_uploader
.username
,
258 media
=media
.slug_or_id
)
260 collection
= Collection()
261 collection
.title
= form
.collection_title
.data
262 collection
.description
= form
.collection_description
.data
263 collection
.creator
= request
.user
.id
264 collection
.generate_slug()
265 create_activity("create", collection
, collection
.creator
)
268 # Otherwise, use the collection selected from the drop-down
270 collection
= form
.collection
.data
271 if collection
and collection
.creator
!= request
.user
.id:
274 # Make sure the user actually selected a collection
276 messages
.add_message(
277 request
, messages
.ERROR
,
278 _('You have to select or add a collection'))
279 return redirect(request
, "mediagoblin.user_pages.media_collect",
280 user
=media
.get_uploader
.username
,
284 # Check whether media already exists in collection
285 elif CollectionItem
.query
.filter_by(
286 media_entry
=media
.id,
287 collection
=collection
.id).first():
288 messages
.add_message(request
, messages
.ERROR
,
289 _('"%s" already in collection "%s"')
290 % (media
.title
, collection
.title
))
291 else: # Add item to collection
292 add_media_to_collection(collection
, media
, form
.note
.data
)
293 create_activity("add", media
, request
.user
, target
=collection
)
294 messages
.add_message(request
, messages
.SUCCESS
,
295 _('"%s" added to collection "%s"')
296 % (media
.title
, collection
.title
))
298 return redirect_obj(request
, media
)
301 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
302 @get_media_entry_by_id
303 @require_active_login
304 @user_may_delete_media
305 def media_confirm_delete(request
, media
):
307 form
= user_forms
.ConfirmDeleteForm(request
.form
)
309 if request
.method
== 'POST' and form
.validate():
310 if form
.confirm
.data
is True:
311 username
= media
.get_uploader
.username
313 media
.get_uploader
.uploaded
= media
.get_uploader
.uploaded
- \
315 media
.get_uploader
.save()
317 # Delete MediaEntry and all related files, comments etc.
319 messages
.add_message(
320 request
, messages
.SUCCESS
, _('You deleted the media.'))
322 location
= media
.url_to_next(request
.urlgen
)
324 location
=media
.url_to_prev(request
.urlgen
)
326 location
=request
.urlgen("mediagoblin.user_pages.user_home",
328 return redirect(request
, location
=location
)
330 messages
.add_message(
331 request
, messages
.ERROR
,
332 _("The media was not deleted because you didn't check that you were sure."))
333 return redirect_obj(request
, media
)
335 if ((request
.user
.has_privilege(u
'admin') and
336 request
.user
.id != media
.uploader
)):
337 messages
.add_message(
338 request
, messages
.WARNING
,
339 _("You are about to delete another user's media. "
340 "Proceed with caution."))
342 return render_to_response(
344 'mediagoblin/user_pages/media_confirm_delete.html',
349 @active_user_from_url
351 def user_collection(request
, page
, url_user
=None):
352 """A User-defined Collection"""
353 collection
= Collection
.query
.filter_by(
354 get_creator
=url_user
,
355 slug
=request
.matchdict
['collection']).first()
358 return render_404(request
)
360 cursor
= collection
.get_collection_items()
362 pagination
= Pagination(page
, cursor
)
363 collection_items
= pagination()
365 # if no data is available, return NotFound
366 # TODO: Should an empty collection really also return 404?
367 if collection_items
== None:
368 return render_404(request
)
370 return render_to_response(
372 'mediagoblin/user_pages/collection.html',
374 'collection': collection
,
375 'collection_items': collection_items
,
376 'pagination': pagination
})
379 @active_user_from_url
380 def collection_list(request
, url_user
=None):
381 """A User-defined Collection"""
382 collections
= Collection
.query
.filter_by(
383 get_creator
=url_user
)
385 return render_to_response(
387 'mediagoblin/user_pages/collection_list.html',
389 'collections': collections
})
392 @get_user_collection_item
393 @require_active_login
394 @user_may_alter_collection
395 def collection_item_confirm_remove(request
, collection_item
):
397 form
= user_forms
.ConfirmCollectionItemRemoveForm(request
.form
)
399 if request
.method
== 'POST' and form
.validate():
400 username
= collection_item
.in_collection
.get_creator
.username
401 collection
= collection_item
.in_collection
403 if form
.confirm
.data
is True:
404 entry
= collection_item
.get_media_entry
407 collection_item
.delete()
408 collection
.items
= collection
.items
- 1
411 messages
.add_message(
412 request
, messages
.SUCCESS
, _('You deleted the item from the collection.'))
414 messages
.add_message(
415 request
, messages
.ERROR
,
416 _("The item was not removed because you didn't check that you were sure."))
418 return redirect_obj(request
, collection
)
420 if ((request
.user
.has_privilege(u
'admin') and
421 request
.user
.id != collection_item
.in_collection
.creator
)):
422 messages
.add_message(
423 request
, messages
.WARNING
,
424 _("You are about to delete an item from another user's collection. "
425 "Proceed with caution."))
427 return render_to_response(
429 'mediagoblin/user_pages/collection_item_confirm_remove.html',
430 {'collection_item': collection_item
,
435 @require_active_login
436 @user_may_alter_collection
437 def collection_confirm_delete(request
, collection
):
439 form
= user_forms
.ConfirmDeleteForm(request
.form
)
441 if request
.method
== 'POST' and form
.validate():
443 username
= collection
.get_creator
.username
445 if form
.confirm
.data
is True:
446 collection_title
= collection
.title
448 # Delete all the associated collection items
449 for item
in collection
.get_collection_items():
450 entry
= item
.get_media_entry
455 messages
.add_message(request
, messages
.SUCCESS
,
456 _('You deleted the collection "%s"') % collection_title
)
458 return redirect(request
, "mediagoblin.user_pages.user_home",
461 messages
.add_message(
462 request
, messages
.ERROR
,
463 _("The collection was not deleted because you didn't check that you were sure."))
465 return redirect_obj(request
, collection
)
467 if ((request
.user
.has_privilege(u
'admin') and
468 request
.user
.id != collection
.creator
)):
469 messages
.add_message(
470 request
, messages
.WARNING
,
471 _("You are about to delete another user's collection. "
472 "Proceed with caution."))
474 return render_to_response(
476 'mediagoblin/user_pages/collection_confirm_delete.html',
477 {'collection': collection
,
481 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
= 15
484 def atom_feed(request
):
486 generates the atom feed with the newest images
488 user
= LocalUser
.query
.filter_by(
489 username
= request
.matchdict
['user']).first()
490 if not user
or not user
.has_privilege(u
'active'):
491 return render_404(request
)
493 cursor
= MediaEntry
.query
.filter_by(
495 state
= u
'processed').\
496 order_by(MediaEntry
.created
.desc()).\
497 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
500 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
503 'href': request
.urlgen(
504 'mediagoblin.user_pages.user_home',
505 qualified
=True, user
=request
.matchdict
['user']),
510 if mg_globals
.app_config
["push_urls"]:
511 for push_url
in mg_globals
.app_config
["push_urls"]:
517 "MediaGoblin: Feed for user '%s'" % request
.matchdict
['user'],
518 feed_url
=request
.url
,
519 id='tag:{host},{year}:gallery.user-{user}'.format(
521 year
=datetime
.datetime
.today().strftime('%Y'),
522 user
=request
.matchdict
['user']),
526 feed
.add(entry
.get('title'),
527 entry
.description_html
,
528 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
531 'name': entry
.get_uploader
.username
,
532 'uri': request
.urlgen(
533 'mediagoblin.user_pages.user_home',
534 qualified
=True, user
=entry
.get_uploader
.username
)},
535 updated
=entry
.get('created'),
537 'href': entry
.url_for_self(
541 'type': 'text/html'}])
543 return feed
.get_response()
546 def collection_atom_feed(request
):
548 generates the atom feed with the newest images from a collection
550 user
= LocalUser
.query
.filter_by(
551 username
= request
.matchdict
['user']).first()
552 if not user
or not user
.has_privilege(u
'active'):
553 return render_404(request
)
555 collection
= Collection
.query
.filter_by(
557 slug
=request
.matchdict
['collection']).first()
559 return render_404(request
)
561 cursor
= CollectionItem
.query
.filter_by(
562 collection
=collection
.id) \
563 .order_by(CollectionItem
.added
.desc()) \
564 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
567 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
570 'href': collection
.url_for_self(request
.urlgen
, qualified
=True),
575 if mg_globals
.app_config
["push_urls"]:
576 for push_url
in mg_globals
.app_config
["push_urls"]:
582 "MediaGoblin: Feed for %s's collection %s" %
583 (request
.matchdict
['user'], collection
.title
),
584 feed_url
=request
.url
,
585 id=u
'tag:{host},{year}:gnu-mediagoblin.{user}.collection.{slug}'\
588 year
=collection
.created
.strftime('%Y'),
589 user
=request
.matchdict
['user'],
590 slug
=collection
.slug
),
594 entry
= item
.get_media_entry
595 feed
.add(entry
.get('title'),
597 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
600 'name': entry
.get_uploader
.username
,
601 'uri': request
.urlgen(
602 'mediagoblin.user_pages.user_home',
603 qualified
=True, user
=entry
.get_uploader
.username
)},
604 updated
=item
.get('added'),
606 'href': entry
.url_for_self(
610 'type': 'text/html'}])
612 return feed
.get_response()
614 @require_active_login
615 def processing_panel(request
):
617 Show to the user what media is still in conversion/processing...
618 and what failed, and why!
620 user
= LocalUser
.query
.filter_by(username
=request
.matchdict
['user']).first()
621 # TODO: XXX: Should this be a decorator?
623 # Make sure we have permission to access this user's panel. Only
624 # admins and this user herself should be able to do so.
625 if not (user
.id == request
.user
.id or request
.user
.has_privilege(u
'admin')):
626 # No? Simply redirect to this user's homepage.
628 request
, 'mediagoblin.user_pages.user_home',
631 # Get media entries which are in-processing
632 processing_entries
= MediaEntry
.query
.\
633 filter_by(uploader
= user
.id,
634 state
= u
'processing').\
635 order_by(MediaEntry
.created
.desc())
637 # Get media entries which have failed to process
638 failed_entries
= MediaEntry
.query
.\
639 filter_by(uploader
= user
.id,
641 order_by(MediaEntry
.created
.desc())
643 processed_entries
= MediaEntry
.query
.\
644 filter_by(uploader
= user
.id,
645 state
= u
'processed').\
646 order_by(MediaEntry
.created
.desc()).\
650 return render_to_response(
652 'mediagoblin/user_pages/processing_panel.html',
654 'processing_entries': processing_entries
,
655 'failed_entries': failed_entries
,
656 'processed_entries': processed_entries
})
659 @get_user_media_entry
660 @user_has_privilege(u
'reporter')
661 @get_optional_media_comment_by_id
662 def file_a_report(request
, media
, comment
):
664 This view handles the filing of a MediaReport or a CommentReport.
666 if comment
is not None:
667 if not comment
.get_media_entry
.id == media
.id:
668 return render_404(request
)
670 form
= user_forms
.CommentReportForm(request
.form
)
671 context
= {'media': media
,
675 form
= user_forms
.MediaReportForm(request
.form
)
676 context
= {'media': media
,
678 form
.reporter_id
.data
= request
.user
.id
681 if request
.method
== "POST":
682 report_object
= build_report_object(form
,
686 # if the object was built successfully, report_table will not be None
694 return render_to_response(
696 'mediagoblin/user_pages/report.html',
699 @require_active_login
700 def activity_view(request
):
701 """ /<username>/activity/<id> - Display activity
703 This should display a HTML presentation of the activity
704 this is NOT an API endpoint.
706 # Get the user object.
707 username
= request
.matchdict
["username"]
708 user
= LocalUser
.query
.filter_by(username
=username
).first()
710 activity_id
= request
.matchdict
["id"]
712 if request
.user
is None:
713 return render_404(request
)
715 activity
= Activity
.query
.filter_by(
721 return render_404(request
)
723 return render_to_response(
725 "mediagoblin/api/activity.html",
726 {"activity": activity
}