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
,
24 from mediagoblin
.tools
.response
import render_to_response
, render_404
, \
25 redirect
, redirect_obj
26 from mediagoblin
.tools
.text
import cleaned_markdown_conversion
27 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
28 from mediagoblin
.tools
.pagination
import Pagination
29 from mediagoblin
.user_pages
import forms
as user_forms
30 from mediagoblin
.user_pages
.lib
import add_media_to_collection
31 from mediagoblin
.notifications
import trigger_notification
, \
32 add_comment_subscription
, mark_comment_notification_seen
33 from mediagoblin
.decorators
import (uses_pagination
, get_user_media_entry
,
34 get_media_entry_by_id
,
35 require_active_login
, user_may_delete_media
, user_may_alter_collection
,
36 get_user_collection
, get_user_collection_item
, active_user_from_url
)
38 from werkzeug
.contrib
.atom
import AtomFeed
39 from werkzeug
.exceptions
import MethodNotAllowed
40 from werkzeug
.wrappers
import Response
43 _log
= logging
.getLogger(__name__
)
44 _log
.setLevel(logging
.DEBUG
)
48 def user_home(request
, page
):
49 """'Homepage' of a User()"""
50 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
52 return render_404(request
)
53 elif user
.status
!= u
'active':
54 return render_to_response(
56 'mediagoblin/user_pages/user_nonactive.html',
59 cursor
= MediaEntry
.query
.\
60 filter_by(uploader
= user
.id,
61 state
= u
'processed').order_by(MediaEntry
.created
.desc())
63 pagination
= Pagination(page
, cursor
)
64 media_entries
= pagination()
66 #if no data is available, return NotFound
67 if media_entries
== None:
68 return render_404(request
)
70 user_gallery_url
= request
.urlgen(
71 'mediagoblin.user_pages.user_gallery',
74 return render_to_response(
76 'mediagoblin/user_pages/user.html',
78 'user_gallery_url': user_gallery_url
,
79 'media_entries': media_entries
,
80 'pagination': pagination
})
85 def user_gallery(request
, page
, url_user
=None):
86 """'Gallery' of a User()"""
87 tag
= request
.matchdict
.get('tag', None)
88 cursor
= MediaEntry
.query
.filter_by(
90 state
=u
'processed').order_by(MediaEntry
.created
.desc())
92 # Filter potentially by tag too:
94 cursor
= cursor
.filter(
95 MediaEntry
.tags_helper
.any(
96 MediaTag
.slug
== request
.matchdict
['tag']))
99 pagination
= Pagination(page
, cursor
)
100 media_entries
= pagination()
102 #if no data is available, return NotFound
103 # TODO: Should we really also return 404 for empty galleries?
104 if media_entries
== None:
105 return render_404(request
)
107 return render_to_response(
109 'mediagoblin/user_pages/gallery.html',
110 {'user': url_user
, 'tag': tag
,
111 'media_entries': media_entries
,
112 'pagination': pagination
})
115 MEDIA_COMMENTS_PER_PAGE
= 50
118 @get_user_media_entry
120 def media_home(request
, media
, page
, **kwargs
):
122 'Homepage' of a MediaEntry()
124 comment_id
= request
.matchdict
.get('comment', None)
127 mark_comment_notification_seen(comment_id
, request
.user
)
129 pagination
= Pagination(
130 page
, media
.get_comments(
131 mg_globals
.app_config
['comments_ascending']),
132 MEDIA_COMMENTS_PER_PAGE
,
135 pagination
= Pagination(
136 page
, media
.get_comments(
137 mg_globals
.app_config
['comments_ascending']),
138 MEDIA_COMMENTS_PER_PAGE
)
140 comments
= pagination()
142 comment_form
= user_forms
.MediaCommentForm(request
.form
)
144 media_template_name
= media
.media_manager
.display_template
146 return render_to_response(
150 'comments': comments
,
151 'pagination': pagination
,
152 'comment_form': comment_form
,
153 'app_config': mg_globals
.app_config
})
156 @get_media_entry_by_id
157 @require_active_login
158 def media_post_comment(request
, media
):
160 recieves POST from a MediaEntry() comment form, saves the comment.
162 if not request
.method
== 'POST':
163 raise MethodNotAllowed()
165 comment
= request
.db
.MediaComment()
166 comment
.media_entry
= media
.id
167 comment
.author
= request
.user
.id
168 print request
.form
['comment_content']
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
)
197 def media_preview_comment(request
):
198 """Runs a comment through markdown so it can be previewed."""
199 # If this isn't an ajax request, render_404
200 if not request
.is_xhr
:
201 return render_404(request
)
203 comment
= unicode(request
.form
['comment_content'])
204 cleancomment
= { "content":cleaned_markdown_conversion(comment
)}
206 return Response(json
.dumps(cleancomment
))
208 @get_media_entry_by_id
209 @require_active_login
210 def media_collect(request
, media
):
211 """Add media to collection submission"""
213 form
= user_forms
.MediaCollectForm(request
.form
)
214 # A user's own collections:
215 form
.collection
.query
= Collection
.query
.filter_by(
216 creator
= request
.user
.id).order_by(Collection
.title
)
218 if request
.method
!= 'POST' or not form
.validate():
219 # No POST submission, or invalid form
220 if not form
.validate():
221 messages
.add_message(request
, messages
.ERROR
,
222 _('Please check your entries and try again.'))
224 return render_to_response(
226 'mediagoblin/user_pages/media_collect.html',
230 # If we are here, method=POST and the form is valid, submit things.
231 # If the user is adding a new collection, use that:
232 if form
.collection_title
.data
:
233 # Make sure this user isn't duplicating an existing collection
234 existing_collection
= Collection
.query
.filter_by(
235 creator
=request
.user
.id,
236 title
=form
.collection_title
.data
).first()
237 if existing_collection
:
238 messages
.add_message(request
, messages
.ERROR
,
239 _('You already have a collection called "%s"!')
240 % existing_collection
.title
)
241 return redirect(request
, "mediagoblin.user_pages.media_home",
242 user
=media
.get_uploader
.username
,
243 media
=media
.slug_or_id
)
245 collection
= Collection()
246 collection
.title
= form
.collection_title
.data
247 collection
.description
= form
.collection_description
.data
248 collection
.creator
= request
.user
.id
249 collection
.generate_slug()
252 # Otherwise, use the collection selected from the drop-down
254 collection
= form
.collection
.data
255 if collection
and collection
.creator
!= request
.user
.id:
258 # Make sure the user actually selected a collection
260 messages
.add_message(
261 request
, messages
.ERROR
,
262 _('You have to select or add a collection'))
263 return redirect(request
, "mediagoblin.user_pages.media_collect",
264 user
=media
.get_uploader
.username
,
268 # Check whether media already exists in collection
269 elif CollectionItem
.query
.filter_by(
270 media_entry
=media
.id,
271 collection
=collection
.id).first():
272 messages
.add_message(request
, messages
.ERROR
,
273 _('"%s" already in collection "%s"')
274 % (media
.title
, collection
.title
))
275 else: # Add item to collection
276 add_media_to_collection(collection
, media
, form
.note
.data
)
278 messages
.add_message(request
, messages
.SUCCESS
,
279 _('"%s" added to collection "%s"')
280 % (media
.title
, collection
.title
))
282 return redirect_obj(request
, media
)
285 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
286 @get_media_entry_by_id
287 @require_active_login
288 @user_may_delete_media
289 def media_confirm_delete(request
, media
):
291 form
= user_forms
.ConfirmDeleteForm(request
.form
)
293 if request
.method
== 'POST' and form
.validate():
294 if form
.confirm
.data
is True:
295 username
= media
.get_uploader
.username
297 media
.get_uploader
.uploaded
= media
.get_uploader
.uploaded
- \
299 media
.get_uploader
.save()
301 # Delete MediaEntry and all related files, comments etc.
303 messages
.add_message(
304 request
, messages
.SUCCESS
, _('You deleted the media.'))
306 location
= media
.url_to_next(request
.urlgen
)
308 location
=media
.url_to_prev(request
.urlgen
)
310 location
=request
.urlgen("mediagoblin.user_pages.user_home",
312 return redirect(request
, location
=location
)
314 messages
.add_message(
315 request
, messages
.ERROR
,
316 _("The media was not deleted because you didn't check that you were sure."))
317 return redirect_obj(request
, media
)
319 if ((request
.user
.is_admin
and
320 request
.user
.id != media
.uploader
)):
321 messages
.add_message(
322 request
, messages
.WARNING
,
323 _("You are about to delete another user's media. "
324 "Proceed with caution."))
326 return render_to_response(
328 'mediagoblin/user_pages/media_confirm_delete.html',
333 @active_user_from_url
335 def user_collection(request
, page
, url_user
=None):
336 """A User-defined Collection"""
337 collection
= Collection
.query
.filter_by(
338 get_creator
=url_user
,
339 slug
=request
.matchdict
['collection']).first()
342 return render_404(request
)
344 cursor
= collection
.get_collection_items()
346 pagination
= Pagination(page
, cursor
)
347 collection_items
= pagination()
349 # if no data is available, return NotFound
350 # TODO: Should an empty collection really also return 404?
351 if collection_items
== None:
352 return render_404(request
)
354 return render_to_response(
356 'mediagoblin/user_pages/collection.html',
358 'collection': collection
,
359 'collection_items': collection_items
,
360 'pagination': pagination
})
363 @active_user_from_url
364 def collection_list(request
, url_user
=None):
365 """A User-defined Collection"""
366 collections
= Collection
.query
.filter_by(
367 get_creator
=url_user
)
369 return render_to_response(
371 'mediagoblin/user_pages/collection_list.html',
373 'collections': collections
})
376 @get_user_collection_item
377 @require_active_login
378 @user_may_alter_collection
379 def collection_item_confirm_remove(request
, collection_item
):
381 form
= user_forms
.ConfirmCollectionItemRemoveForm(request
.form
)
383 if request
.method
== 'POST' and form
.validate():
384 username
= collection_item
.in_collection
.get_creator
.username
385 collection
= collection_item
.in_collection
387 if form
.confirm
.data
is True:
388 entry
= collection_item
.get_media_entry
389 entry
.collected
= entry
.collected
- 1
392 collection_item
.delete()
393 collection
.items
= collection
.items
- 1
396 messages
.add_message(
397 request
, messages
.SUCCESS
, _('You deleted the item from the collection.'))
399 messages
.add_message(
400 request
, messages
.ERROR
,
401 _("The item was not removed because you didn't check that you were sure."))
403 return redirect_obj(request
, collection
)
405 if ((request
.user
.is_admin
and
406 request
.user
.id != collection_item
.in_collection
.creator
)):
407 messages
.add_message(
408 request
, messages
.WARNING
,
409 _("You are about to delete an item from another user's collection. "
410 "Proceed with caution."))
412 return render_to_response(
414 'mediagoblin/user_pages/collection_item_confirm_remove.html',
415 {'collection_item': collection_item
,
420 @require_active_login
421 @user_may_alter_collection
422 def collection_confirm_delete(request
, collection
):
424 form
= user_forms
.ConfirmDeleteForm(request
.form
)
426 if request
.method
== 'POST' and form
.validate():
428 username
= collection
.get_creator
.username
430 if form
.confirm
.data
is True:
431 collection_title
= collection
.title
433 # Delete all the associated collection items
434 for item
in collection
.get_collection_items():
435 entry
= item
.get_media_entry
436 entry
.collected
= entry
.collected
- 1
441 messages
.add_message(request
, messages
.SUCCESS
,
442 _('You deleted the collection "%s"') % collection_title
)
444 return redirect(request
, "mediagoblin.user_pages.user_home",
447 messages
.add_message(
448 request
, messages
.ERROR
,
449 _("The collection was not deleted because you didn't check that you were sure."))
451 return redirect_obj(request
, collection
)
453 if ((request
.user
.is_admin
and
454 request
.user
.id != collection
.creator
)):
455 messages
.add_message(
456 request
, messages
.WARNING
,
457 _("You are about to delete another user's collection. "
458 "Proceed with caution."))
460 return render_to_response(
462 'mediagoblin/user_pages/collection_confirm_delete.html',
463 {'collection': collection
,
467 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
= 15
470 def atom_feed(request
):
472 generates the atom feed with the newest images
474 user
= User
.query
.filter_by(
475 username
= request
.matchdict
['user'],
476 status
= u
'active').first()
478 return render_404(request
)
480 cursor
= MediaEntry
.query
.filter_by(
482 state
= u
'processed').\
483 order_by(MediaEntry
.created
.desc()).\
484 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
487 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
490 'href': request
.urlgen(
491 'mediagoblin.user_pages.user_home',
492 qualified
=True, user
=request
.matchdict
['user']),
497 if mg_globals
.app_config
["push_urls"]:
498 for push_url
in mg_globals
.app_config
["push_urls"]:
504 "MediaGoblin: Feed for user '%s'" % request
.matchdict
['user'],
505 feed_url
=request
.url
,
506 id='tag:{host},{year}:gallery.user-{user}'.format(
508 year
=datetime
.datetime
.today().strftime('%Y'),
509 user
=request
.matchdict
['user']),
513 feed
.add(entry
.get('title'),
514 entry
.description_html
,
515 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
518 'name': entry
.get_uploader
.username
,
519 'uri': request
.urlgen(
520 'mediagoblin.user_pages.user_home',
521 qualified
=True, user
=entry
.get_uploader
.username
)},
522 updated
=entry
.get('created'),
524 'href': entry
.url_for_self(
528 'type': 'text/html'}])
530 return feed
.get_response()
533 def collection_atom_feed(request
):
535 generates the atom feed with the newest images from a collection
537 user
= User
.query
.filter_by(
538 username
= request
.matchdict
['user'],
539 status
= u
'active').first()
541 return render_404(request
)
543 collection
= Collection
.query
.filter_by(
545 slug
=request
.matchdict
['collection']).first()
547 return render_404(request
)
549 cursor
= CollectionItem
.query
.filter_by(
550 collection
=collection
.id) \
551 .order_by(CollectionItem
.added
.desc()) \
552 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
555 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
558 'href': collection
.url_for_self(request
.urlgen
, qualified
=True),
563 if mg_globals
.app_config
["push_urls"]:
564 for push_url
in mg_globals
.app_config
["push_urls"]:
570 "MediaGoblin: Feed for %s's collection %s" %
571 (request
.matchdict
['user'], collection
.title
),
572 feed_url
=request
.url
,
573 id=u
'tag:{host},{year}:gnu-mediagoblin.{user}.collection.{slug}'\
576 year
=collection
.created
.strftime('%Y'),
577 user
=request
.matchdict
['user'],
578 slug
=collection
.slug
),
582 entry
= item
.get_media_entry
583 feed
.add(entry
.get('title'),
585 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
588 'name': entry
.get_uploader
.username
,
589 'uri': request
.urlgen(
590 'mediagoblin.user_pages.user_home',
591 qualified
=True, user
=entry
.get_uploader
.username
)},
592 updated
=item
.get('added'),
594 'href': entry
.url_for_self(
598 'type': 'text/html'}])
600 return feed
.get_response()
603 @require_active_login
604 def processing_panel(request
):
606 Show to the user what media is still in conversion/processing...
607 and what failed, and why!
609 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
610 # TODO: XXX: Should this be a decorator?
612 # Make sure we have permission to access this user's panel. Only
613 # admins and this user herself should be able to do so.
614 if not (user
.id == request
.user
.id or request
.user
.is_admin
):
615 # No? Simply redirect to this user's homepage.
617 request
, 'mediagoblin.user_pages.user_home',
620 # Get media entries which are in-processing
621 processing_entries
= MediaEntry
.query
.\
622 filter_by(uploader
= user
.id,
623 state
= u
'processing').\
624 order_by(MediaEntry
.created
.desc())
626 # Get media entries which have failed to process
627 failed_entries
= MediaEntry
.query
.\
628 filter_by(uploader
= user
.id,
630 order_by(MediaEntry
.created
.desc())
632 processed_entries
= MediaEntry
.query
.\
633 filter_by(uploader
= user
.id,
634 state
= u
'processed').\
635 order_by(MediaEntry
.created
.desc()).\
639 return render_to_response(
641 'mediagoblin/user_pages/processing_panel.html',
643 'processing_entries': processing_entries
,
644 'failed_entries': failed_entries
,
645 'processed_entries': processed_entries
})