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
, Comment
,
25 CollectionItem
, LocalUser
, Activity
, \
26 GenericModelReference
)
27 from mediagoblin
.plugins
.api
.tools
import get_media_file_paths
28 from mediagoblin
.tools
.response
import render_to_response
, render_404
, \
29 redirect
, redirect_obj
30 from mediagoblin
.tools
.text
import cleaned_markdown_conversion
31 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
32 from mediagoblin
.tools
.pagination
import Pagination
33 from mediagoblin
.tools
.federation
import create_activity
34 from mediagoblin
.user_pages
import forms
as user_forms
35 from mediagoblin
.user_pages
.lib
import (send_comment_email
,
36 add_media_to_collection
, build_report_object
)
37 from mediagoblin
.notifications
import trigger_notification
, \
38 add_comment_subscription
, mark_comment_notification_seen
39 from mediagoblin
.tools
.pluginapi
import hook_transform
41 from mediagoblin
.decorators
import (uses_pagination
, get_user_media_entry
,
42 get_media_entry_by_id
, user_has_privilege
, user_not_banned
,
43 require_active_login
, user_may_delete_media
, user_may_alter_collection
,
44 get_user_collection
, get_user_collection_item
, active_user_from_url
,
45 get_optional_media_comment_by_id
, allow_reporting
)
47 from werkzeug
.contrib
.atom
import AtomFeed
48 from werkzeug
.exceptions
import MethodNotAllowed
49 from werkzeug
.wrappers
import Response
52 _log
= logging
.getLogger(__name__
)
53 _log
.setLevel(logging
.DEBUG
)
57 def user_home(request
, page
):
58 """'Homepage' of a LocalUser()"""
59 user
= LocalUser
.query
.filter_by(username
=request
.matchdict
['user']).first()
61 return render_404(request
)
62 elif not user
.has_privilege(u
'active'):
63 return render_to_response(
65 'mediagoblin/user_pages/user_nonactive.html',
68 cursor
= MediaEntry
.query
.\
69 filter_by(actor
= user
.id,
70 state
= u
'processed').order_by(MediaEntry
.created
.desc())
72 pagination
= Pagination(page
, cursor
)
73 media_entries
= pagination()
75 #if no data is available, return NotFound
76 if media_entries
== None:
77 return render_404(request
)
79 user_gallery_url
= request
.urlgen(
80 'mediagoblin.user_pages.user_gallery',
83 return render_to_response(
85 'mediagoblin/user_pages/user.html',
87 'user_gallery_url': user_gallery_url
,
88 'media_entries': media_entries
,
89 'pagination': pagination
})
94 def user_gallery(request
, page
, url_user
=None):
95 """'Gallery' of a LocalUser()"""
96 tag
= request
.matchdict
.get('tag', None)
97 cursor
= MediaEntry
.query
.filter_by(
99 state
=u
'processed').order_by(MediaEntry
.created
.desc())
101 # Filter potentially by tag too:
103 cursor
= cursor
.filter(
104 MediaEntry
.tags_helper
.any(
105 MediaTag
.slug
== request
.matchdict
['tag']))
108 pagination
= Pagination(page
, cursor
)
109 media_entries
= pagination()
111 #if no data is available, return NotFound
112 # TODO: Should we really also return 404 for empty galleries?
113 if media_entries
== None:
114 return render_404(request
)
116 return render_to_response(
118 'mediagoblin/user_pages/gallery.html',
119 {'user': url_user
, 'tag': tag
,
120 'media_entries': media_entries
,
121 'pagination': pagination
})
124 MEDIA_COMMENTS_PER_PAGE
= 50
127 @get_user_media_entry
129 def media_home(request
, media
, page
, **kwargs
):
131 'Homepage' of a MediaEntry()
133 comment_id
= request
.matchdict
.get('comment', None)
136 mark_comment_notification_seen(comment_id
, request
.user
)
138 pagination
= Pagination(
139 page
, media
.get_comments(
140 mg_globals
.app_config
['comments_ascending']),
141 MEDIA_COMMENTS_PER_PAGE
,
144 pagination
= Pagination(
145 page
, media
.get_comments(
146 mg_globals
.app_config
['comments_ascending']),
147 MEDIA_COMMENTS_PER_PAGE
)
149 comments
= pagination()
151 comment_form
= user_forms
.MediaCommentForm(request
.form
)
153 media_template_name
= media
.media_manager
.display_template
157 'comments': comments
,
158 'pagination': pagination
,
159 'comment_form': comment_form
,
160 'app_config': mg_globals
.app_config
}
162 # Since the media template name gets swapped out for each media
163 # type, normal context hooks don't work if you want to affect all
164 # media displays. This gives a general purpose hook.
165 context
= hook_transform(
166 "media_home_context", context
)
168 return render_to_response(
174 @get_media_entry_by_id
175 @user_has_privilege(u
'commenter')
176 def media_post_comment(request
, media
):
178 recieves POST from a MediaEntry() comment form, saves the comment.
180 if not request
.method
== 'POST':
181 raise MethodNotAllowed()
183 comment
= request
.db
.TextComment()
184 comment
.actor
= request
.user
.id
185 comment
.content
= six
.text_type(request
.form
['comment_content'])
187 # Show error message if commenting is disabled.
188 if not mg_globals
.app_config
['allow_comments']:
189 messages
.add_message(
192 _("Sorry, comments are disabled."))
193 elif not comment
.content
.strip():
194 messages
.add_message(
197 _("Oops, your comment was empty."))
199 create_activity("post", comment
, comment
.actor
, target
=media
)
200 add_comment_subscription(request
.user
, media
)
203 link
= request
.db
.Comment()
205 link
.comment
= comment
208 messages
.add_message(
211 _('Your comment has been posted!'))
212 trigger_notification(link
, media
, request
)
214 return redirect_obj(request
, media
)
218 def media_preview_comment(request
):
219 """Runs a comment through markdown so it can be previewed."""
220 # If this isn't an ajax request, render_404
221 if not request
.is_xhr
:
222 return render_404(request
)
224 comment
= six
.text_type(request
.form
['comment_content'])
225 cleancomment
= { "content":cleaned_markdown_conversion(comment
)}
227 return Response(json
.dumps(cleancomment
))
230 @get_media_entry_by_id
231 @require_active_login
232 def media_collect(request
, media
):
233 """Add media to collection submission"""
235 form
= user_forms
.MediaCollectForm(request
.form
)
236 # A user's own collections:
237 form
.collection
.query
= Collection
.query
.filter_by(
238 actor
=request
.user
.id,
239 type=Collection
.USER_DEFINED_TYPE
240 ).order_by(Collection
.title
)
242 if request
.method
!= 'POST' or not form
.validate():
243 # No POST submission, or invalid form
244 if not form
.validate():
245 messages
.add_message(
248 _('Please check your entries and try again.'))
250 return render_to_response(
252 'mediagoblin/user_pages/media_collect.html',
256 # If we are here, method=POST and the form is valid, submit things.
257 # If the user is adding a new collection, use that:
258 if form
.collection_title
.data
:
259 # Make sure this user isn't duplicating an existing collection
260 existing_collection
= Collection
.query
.filter_by(
261 actor
=request
.user
.id,
262 title
=form
.collection_title
.data
,
263 type=Collection
.USER_DEFINED_TYPE
265 if existing_collection
:
266 messages
.add_message(
269 _('You already have a collection called "%s"!') %
270 existing_collection
.title
)
271 return redirect(request
, "mediagoblin.user_pages.media_home",
272 user
=media
.get_actor
.username
,
273 media
=media
.slug_or_id
)
275 collection
= Collection()
276 collection
.title
= form
.collection_title
.data
277 collection
.description
= form
.collection_description
.data
278 collection
.actor
= request
.user
.id
279 collection
.type = Collection
.USER_DEFINED_TYPE
280 collection
.generate_slug()
281 collection
.get_public_id(request
.urlgen
)
282 create_activity("create", collection
, collection
.actor
)
285 # Otherwise, use the collection selected from the drop-down
287 collection
= form
.collection
.data
288 if collection
and collection
.actor
!= request
.user
.id:
291 # Make sure the user actually selected a collection
292 item
= CollectionItem
.query
.filter_by(collection
=collection
.id)
293 item
= item
.join(CollectionItem
.object_helper
).filter_by(
294 model_type
=media
.__tablename
__,
299 messages
.add_message(
302 _('You have to select or add a collection'))
303 return redirect(request
, "mediagoblin.user_pages.media_collect",
304 user
=media
.get_actor
.username
,
307 # Check whether media already exists in collection
308 elif item
is not None:
309 messages
.add_message(
312 _('"%s" already in collection "%s"') %
313 (media
.title
, collection
.title
))
314 else: # Add item to collection
315 add_media_to_collection(collection
, media
, form
.note
.data
)
316 create_activity("add", media
, request
.user
, target
=collection
)
317 messages
.add_message(
320 _('"%s" added to collection "%s"') %
321 (media
.title
, collection
.title
))
323 return redirect_obj(request
, media
)
326 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
327 @get_media_entry_by_id
328 @require_active_login
329 @user_may_delete_media
330 def media_confirm_delete(request
, media
):
332 form
= user_forms
.ConfirmDeleteForm(request
.form
)
334 if request
.method
== 'POST' and form
.validate():
335 if form
.confirm
.data
is True:
336 username
= media
.get_actor
.username
338 # This probably is already filled but just in case it has slipped
339 # through the net somehow, we need to try and make sure the
340 # MediaEntry has a public ID so it gets properly soft-deleted.
341 media
.get_public_id(request
.urlgen
)
343 # Decrement the users uploaded quota.
344 media
.get_actor
.uploaded
= media
.get_actor
.uploaded
- \
346 media
.get_actor
.save()
348 # Delete MediaEntry and all related files, comments etc.
350 messages
.add_message(
353 _('You deleted the media.'))
355 location
= media
.url_to_next(request
.urlgen
)
357 location
=media
.url_to_prev(request
.urlgen
)
359 location
=request
.urlgen("mediagoblin.user_pages.user_home",
361 return redirect(request
, location
=location
)
363 messages
.add_message(
366 _("The media was not deleted because you didn't check "
367 "that you were sure."))
368 return redirect_obj(request
, media
)
370 if ((request
.user
.has_privilege(u
'admin') and
371 request
.user
.id != media
.actor
)):
372 messages
.add_message(
375 _("You are about to delete another user's media. "
376 "Proceed with caution."))
378 return render_to_response(
380 'mediagoblin/user_pages/media_confirm_delete.html',
385 @active_user_from_url
387 def user_collection(request
, page
, url_user
=None):
388 """A User-defined Collection"""
389 collection
= Collection
.query
.filter_by(
391 slug
=request
.matchdict
['collection']).first()
394 return render_404(request
)
396 cursor
= collection
.get_collection_items()
398 pagination
= Pagination(page
, cursor
)
399 collection_items
= pagination()
401 # if no data is available, return NotFound
402 # TODO: Should an empty collection really also return 404?
403 if collection_items
== None:
404 return render_404(request
)
406 return render_to_response(
408 'mediagoblin/user_pages/collection.html',
410 'collection': collection
,
411 'collection_items': collection_items
,
412 'pagination': pagination
})
415 @active_user_from_url
416 def collection_list(request
, url_user
=None):
417 """A User-defined Collection"""
418 collections
= Collection
.query
.filter_by(
421 return render_to_response(
423 'mediagoblin/user_pages/collection_list.html',
425 'collections': collections
})
428 @get_user_collection_item
429 @require_active_login
430 @user_may_alter_collection
431 def collection_item_confirm_remove(request
, collection_item
):
433 form
= user_forms
.ConfirmCollectionItemRemoveForm(request
.form
)
435 if request
.method
== 'POST' and form
.validate():
436 username
= collection_item
.in_collection
.get_actor
.username
437 collection
= collection_item
.in_collection
439 if form
.confirm
.data
is True:
440 obj
= collection_item
.get_object()
443 collection_item
.delete()
444 collection
.num_items
= collection
.num_items
- 1
447 messages
.add_message(
450 _('You deleted the item from the collection.'))
452 messages
.add_message(
455 _("The item was not removed because you didn't check "
456 "that you were sure."))
458 return redirect_obj(request
, collection
)
460 if ((request
.user
.has_privilege(u
'admin') and
461 request
.user
.id != collection_item
.in_collection
.actor
)):
462 messages
.add_message(
465 _("You are about to delete an item from another user's collection. "
466 "Proceed with caution."))
468 return render_to_response(
470 'mediagoblin/user_pages/collection_item_confirm_remove.html',
471 {'collection_item': collection_item
,
476 @require_active_login
477 @user_may_alter_collection
478 def collection_confirm_delete(request
, collection
):
480 form
= user_forms
.ConfirmDeleteForm(request
.form
)
482 if request
.method
== 'POST' and form
.validate():
484 username
= collection
.get_actor
.username
486 if form
.confirm
.data
is True:
487 collection_title
= collection
.title
489 # Firstly like with the MediaEntry delete, lets ensure the
490 # public_id is populated as this is really important!
491 collection
.get_public_id(request
.urlgen
)
493 # Delete all the associated collection items
494 for item
in collection
.get_collection_items():
495 obj
= item
.get_object()
500 messages
.add_message(
503 _('You deleted the collection "%s"') %
506 return redirect(request
, "mediagoblin.user_pages.user_home",
509 messages
.add_message(
512 _("The collection was not deleted because you didn't "
513 "check that you were sure."))
515 return redirect_obj(request
, collection
)
517 if ((request
.user
.has_privilege(u
'admin') and
518 request
.user
.id != collection
.actor
)):
519 messages
.add_message(
520 request
, messages
.WARNING
,
521 _("You are about to delete another user's collection. "
522 "Proceed with caution."))
524 return render_to_response(
526 'mediagoblin/user_pages/collection_confirm_delete.html',
527 {'collection': collection
,
531 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
= 15
534 def atom_feed(request
):
536 generates the atom feed with the newest images
538 user
= LocalUser
.query
.filter_by(
539 username
= request
.matchdict
['user']).first()
540 if not user
or not user
.has_privilege(u
'active'):
541 return render_404(request
)
542 feed_title
= "MediaGoblin Feed for user '%s'" % request
.matchdict
['user']
543 link
= request
.urlgen('mediagoblin.user_pages.user_home',
544 qualified
=True, user
=request
.matchdict
['user'])
545 cursor
= MediaEntry
.query
.filter_by(actor
=user
.id, state
=u
'processed')
546 cursor
= cursor
.order_by(MediaEntry
.created
.desc())
547 cursor
= cursor
.limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
551 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
556 'type': 'text/html'}]
558 if mg_globals
.app_config
["push_urls"]:
559 for push_url
in mg_globals
.app_config
["push_urls"]:
566 feed_url
=request
.url
,
567 id='tag:{host},{year}:gallery.user-{user}'.format(
569 year
=datetime
.datetime
.today().strftime('%Y'),
570 user
=request
.matchdict
['user']),
574 # Include a thumbnail image in content.
575 file_urls
= get_media_file_paths(entry
.media_files
, request
.urlgen
)
576 if 'thumb' in file_urls
:
577 content
= '<img src="{thumb}" alt='' /> {desc}'.format(
578 thumb
=file_urls
['thumb'], desc
=entry
.description_html
)
580 content
= entry
.description_html
585 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
588 'name': entry
.get_actor
.username
,
589 'uri': request
.urlgen(
590 'mediagoblin.user_pages.user_home',
592 user
=entry
.get_actor
.username
)},
593 updated
=entry
.get('created'),
595 'href': entry
.url_for_self(
599 'type': 'text/html'}])
601 return feed
.get_response()
604 def collection_atom_feed(request
):
606 generates the atom feed with the newest images from a collection
608 user
= LocalUser
.query
.filter_by(
609 username
= request
.matchdict
['user']).first()
610 if not user
or not user
.has_privilege(u
'active'):
611 return render_404(request
)
613 collection
= Collection
.query
.filter_by(
615 slug
=request
.matchdict
['collection']).first()
617 return render_404(request
)
619 cursor
= CollectionItem
.query
.filter_by(
620 collection
=collection
.id) \
621 .order_by(CollectionItem
.added
.desc()) \
622 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
625 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
628 'href': collection
.url_for_self(request
.urlgen
, qualified
=True),
633 if mg_globals
.app_config
["push_urls"]:
634 for push_url
in mg_globals
.app_config
["push_urls"]:
640 "MediaGoblin: Feed for %s's collection %s" %
641 (request
.matchdict
['user'], collection
.title
),
642 feed_url
=request
.url
,
643 id=u
'tag:{host},{year}:gnu-mediagoblin.{user}.collection.{slug}'\
646 year
=collection
.created
.strftime('%Y'),
647 user
=request
.matchdict
['user'],
648 slug
=collection
.slug
),
652 obj
= item
.get_object()
656 id=obj
.url_for_self(request
.urlgen
, qualified
=True),
659 'name': obj
.get_actor
.username
,
660 'uri': request
.urlgen(
661 'mediagoblin.user_pages.user_home',
662 qualified
=True, user
=obj
.get_actor
.username
)},
663 updated
=item
.get('added'),
665 'href': obj
.url_for_self(
669 'type': 'text/html'}])
671 return feed
.get_response()
673 @active_user_from_url
675 @require_active_login
676 def processing_panel(request
, page
, url_user
):
678 Show to the user what media is still in conversion/processing...
679 and what failed, and why!
681 user
= LocalUser
.query
.filter_by(username
=request
.matchdict
['user']).first()
682 # TODO: XXX: Should this be a decorator?
684 # Make sure we have permission to access this user's panel. Only
685 # admins and this user herself should be able to do so.
686 if not (user
.id == request
.user
.id or request
.user
.has_privilege(u
'admin')):
687 # No? Simply redirect to this user's homepage.
689 request
, 'mediagoblin.user_pages.user_home',
691 # Get media entries which are in-processing
692 entries
= (MediaEntry
.query
.filter_by(actor
=user
.id)
693 .order_by(MediaEntry
.created
.desc()))
696 state
= request
.matchdict
['state']
697 # no exception was thrown, filter entries by state
698 entries
= entries
.filter_by(state
=state
)
703 pagination
= Pagination(page
, entries
)
704 pagination
.per_page
= 30
705 entries_on_a_page
= pagination()
708 return render_to_response(
710 'mediagoblin/user_pages/processing_panel.html',
712 'entries': entries_on_a_page
,
713 'pagination': pagination
})
716 @get_user_media_entry
717 @user_has_privilege(u
'reporter')
718 @get_optional_media_comment_by_id
719 def file_a_report(request
, media
, comment
):
721 This view handles the filing of a Report.
723 if comment
is not None:
724 if not comment
.target().id == media
.id:
725 return render_404(request
)
727 form
= user_forms
.CommentReportForm(request
.form
)
728 context
= {'media': comment
.target(),
732 form
= user_forms
.MediaReportForm(request
.form
)
733 context
= {'media': media
,
735 form
.reporter_id
.data
= request
.user
.id
738 if request
.method
== "POST":
739 report_object
= build_report_object(
745 # if the object was built successfully, report_table will not be None
753 return render_to_response(
755 'mediagoblin/user_pages/report.html',
758 @require_active_login
759 def activity_view(request
):
760 """ /<username>/activity/<id> - Display activity
762 This should display a HTML presentation of the activity
763 this is NOT an API endpoint.
765 # Get the user object.
766 username
= request
.matchdict
["username"]
767 user
= LocalUser
.query
.filter_by(username
=username
).first()
769 activity_id
= request
.matchdict
["id"]
771 if request
.user
is None:
772 return render_404(request
)
774 activity
= Activity
.query
.filter_by(
779 # There isn't many places to check that the public_id is filled so this
780 # will do, it really should be, lets try and fix that if it isn't.
781 activity
.get_public_id(request
.urlgen
)
784 return render_404(request
)
786 return render_to_response(
788 "mediagoblin/api/activity.html",
789 {"activity": activity
}