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
, Collection
, CollectionItem
,
23 from mediagoblin
.tools
.response
import render_to_response
, render_404
, redirect
24 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
25 from mediagoblin
.tools
.pagination
import Pagination
26 from mediagoblin
.tools
.files
import delete_media_files
27 from mediagoblin
.user_pages
import forms
as user_forms
28 from mediagoblin
.user_pages
.lib
import send_comment_email
30 from mediagoblin
.decorators
import (uses_pagination
, get_user_media_entry
,
31 require_active_login
, user_may_delete_media
, user_may_alter_collection
,
32 get_user_collection
, get_user_collection_item
, active_user_from_url
)
34 from werkzeug
.contrib
.atom
import AtomFeed
37 _log
= logging
.getLogger(__name__
)
38 _log
.setLevel(logging
.DEBUG
)
42 def user_home(request
, page
):
43 """'Homepage' of a User()"""
44 # TODO: decide if we only want homepages for active users, we can
45 # then use the @get_active_user decorator and also simplify the
47 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
49 return render_404(request
)
50 elif user
.status
!= u
'active':
51 return render_to_response(
53 'mediagoblin/user_pages/user.html',
56 cursor
= MediaEntry
.query
.\
57 filter_by(uploader
= user
.id,
58 state
= u
'processed').order_by(MediaEntry
.created
.desc())
60 pagination
= Pagination(page
, cursor
)
61 media_entries
= pagination()
63 #if no data is available, return NotFound
64 if media_entries
== None:
65 return render_404(request
)
67 user_gallery_url
= request
.urlgen(
68 'mediagoblin.user_pages.user_gallery',
71 return render_to_response(
73 'mediagoblin/user_pages/user.html',
75 'user_gallery_url': user_gallery_url
,
76 'media_entries': media_entries
,
77 'pagination': pagination
})
82 def user_gallery(request
, page
, url_user
=None):
83 """'Gallery' of a User()"""
84 cursor
= MediaEntry
.query
.filter_by(
86 state
=u
'processed').order_by(MediaEntry
.created
.desc())
89 pagination
= Pagination(page
, cursor
)
90 media_entries
= pagination()
92 #if no data is available, return NotFound
93 # TODO: Should we really also return 404 for empty galleries?
94 if media_entries
== None:
95 return render_404(request
)
97 return render_to_response(
99 'mediagoblin/user_pages/gallery.html',
101 'media_entries': media_entries
,
102 'pagination': pagination
})
104 MEDIA_COMMENTS_PER_PAGE
= 50
107 @get_user_media_entry
109 def media_home(request
, media
, page
, **kwargs
):
111 'Homepage' of a MediaEntry()
113 if request
.matchdict
.get('comment', None):
114 pagination
= Pagination(
115 page
, media
.get_comments(
116 mg_globals
.app_config
['comments_ascending']),
117 MEDIA_COMMENTS_PER_PAGE
,
118 request
.matchdict
.get('comment'))
120 pagination
= Pagination(
121 page
, media
.get_comments(
122 mg_globals
.app_config
['comments_ascending']),
123 MEDIA_COMMENTS_PER_PAGE
)
125 comments
= pagination()
127 comment_form
= user_forms
.MediaCommentForm(request
.form
)
129 media_template_name
= media
.media_manager
['display_template']
131 return render_to_response(
135 'comments': comments
,
136 'pagination': pagination
,
137 'comment_form': comment_form
,
138 'app_config': mg_globals
.app_config
})
141 @get_user_media_entry
142 @require_active_login
143 def media_post_comment(request
, media
):
145 recieves POST from a MediaEntry() comment form, saves the comment.
147 assert request
.method
== 'POST'
149 comment
= request
.db
.MediaComment()
150 comment
.media_entry
= media
.id
151 comment
.author
= request
.user
.id
152 comment
.content
= unicode(request
.form
['comment_content'])
154 if not comment
.content
.strip():
155 messages
.add_message(
158 _("Oops, your comment was empty."))
162 messages
.add_message(
163 request
, messages
.SUCCESS
,
164 _('Your comment has been posted!'))
166 media_uploader
= media
.get_uploader
167 #don't send email if you comment on your own post
168 if (comment
.author
!= media_uploader
and
169 media_uploader
.wants_comment_notification
):
170 send_comment_email(media_uploader
, comment
, media
, request
)
172 return redirect(request
, location
=media
.url_for_self(request
.urlgen
))
175 @get_user_media_entry
176 @require_active_login
177 def media_collect(request
, media
):
178 """Add media to collection submission"""
180 form
= user_forms
.MediaCollectForm(request
.form
)
181 # A user's own collections:
182 form
.collection
.query
= Collection
.query
.filter_by(
183 creator
= request
.user
.id).order_by(Collection
.title
)
185 if request
.method
!= 'POST' or not form
.validate():
186 # No POST submission, or invalid form
187 if not form
.validate():
188 messages
.add_message(request
, messages
.ERROR
,
189 _('Please check your entries and try again.'))
191 return render_to_response(
193 'mediagoblin/user_pages/media_collect.html',
197 # If we are here, method=POST and the form is valid, submit things.
198 # If the user is adding a new collection, use that:
199 if request
.form
['collection_title']:
200 # Make sure this user isn't duplicating an existing collection
201 existing_collection
= Collection
.query
.filter_by(
202 creator
=request
.user
.id,
203 title
=request
.form
['collection_title']).first()
204 if existing_collection
:
205 messages
.add_message(request
, messages
.ERROR
,
206 _('You already have a collection called "%s"!'
208 return redirect(request
, "mediagoblin.user_pages.media_home",
209 user
=request
.user
.username
,
212 collection
= Collection()
213 collection
.title
= request
.form
['collection_title']
214 collection
.description
= request
.form
.get('collection_description')
215 collection
.creator
= request
.user
.id
216 collection
.generate_slug()
219 # Otherwise, use the collection selected from the drop-down
221 collection
= Collection
.query
.filter_by(
222 id=request
.form
.get('collection')).first()
224 # Make sure the user actually selected a collection
226 messages
.add_message(
227 request
, messages
.ERROR
,
228 _('You have to select or add a collection'))
230 # Check whether media already exists in collection
231 elif CollectionItem
.query
.filter_by(
232 media_entry
=media
.id,
233 collection
=collection
.id).first():
234 messages
.add_message(request
, messages
.ERROR
,
235 _('"%s" already in collection "%s"'
236 % (media
.title
, collection
.title
)))
237 else: # Add item to collection
238 collection_item
= request
.db
.CollectionItem()
239 collection_item
.collection
= collection
.id
240 collection_item
.media_entry
= media
.id
241 collection_item
.author
= request
.user
.id
242 collection_item
.note
= request
.form
['note']
243 collection_item
.save()
245 collection
.items
= collection
.items
+ 1
248 media
.collected
= media
.collected
+ 1
251 messages
.add_message(request
, messages
.SUCCESS
,
252 _('"%s" added to collection "%s"'
253 % (media
.title
, collection
.title
)))
255 return redirect(request
, "mediagoblin.user_pages.media_home",
256 user
=media
.get_uploader
.username
,
260 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
261 @get_user_media_entry
262 @require_active_login
263 @user_may_delete_media
264 def media_confirm_delete(request
, media
):
266 form
= user_forms
.ConfirmDeleteForm(request
.form
)
268 if request
.method
== 'POST' and form
.validate():
269 if form
.confirm
.data
is True:
270 username
= media
.get_uploader
.username
272 # Delete all the associated comments
273 for comment
in media
.get_comments():
276 # Delete all files on the public storage
278 delete_media_files(media
)
279 except OSError, error
:
280 _log
.error('No such files from the user "{1}"'
281 ' to delete: {0}'.format(str(error
), username
))
282 messages
.add_message(request
, messages
.ERROR
,
283 _('Some of the files with this entry seem'
284 ' to be missing. Deleting anyway.'))
287 messages
.add_message(
288 request
, messages
.SUCCESS
, _('You deleted the media.'))
290 return redirect(request
, "mediagoblin.user_pages.user_home",
293 messages
.add_message(
294 request
, messages
.ERROR
,
295 _("The media was not deleted because you didn't check that you were sure."))
296 return redirect(request
,
297 location
=media
.url_for_self(request
.urlgen
))
299 if ((request
.user
.is_admin
and
300 request
.user
.id != media
.uploader
)):
301 messages
.add_message(
302 request
, messages
.WARNING
,
303 _("You are about to delete another user's media. "
304 "Proceed with caution."))
306 return render_to_response(
308 'mediagoblin/user_pages/media_confirm_delete.html',
313 @active_user_from_url
315 def user_collection(request
, page
, url_user
=None):
316 """A User-defined Collection"""
317 collection
= Collection
.query
.filter_by(
318 get_creator
=url_user
,
319 slug
=request
.matchdict
['collection']).first()
321 cursor
= collection
.get_collection_items()
323 pagination
= Pagination(page
, cursor
)
324 collection_items
= pagination()
326 # if no data is available, return NotFound
327 # TODO: Should an empty collection really also return 404?
328 if collection_items
== None:
329 return render_404(request
)
331 return render_to_response(
333 'mediagoblin/user_pages/collection.html',
335 'collection': collection
,
336 'collection_items': collection_items
,
337 'pagination': pagination
})
340 @active_user_from_url
341 def collection_list(request
, url_user
=None):
342 """A User-defined Collection"""
343 collections
= Collection
.query
.filter_by(
344 get_creator
=url_user
)
346 return render_to_response(
348 'mediagoblin/user_pages/collection_list.html',
350 'collections': collections
})
353 @get_user_collection_item
354 @require_active_login
355 @user_may_alter_collection
356 def collection_item_confirm_remove(request
, collection_item
):
358 form
= user_forms
.ConfirmCollectionItemRemoveForm(request
.form
)
360 if request
.method
== 'POST' and form
.validate():
361 username
= collection_item
.in_collection
.get_creator
.username
362 collection
= collection_item
.in_collection
364 if form
.confirm
.data
is True:
365 entry
= collection_item
.get_media_entry
366 entry
.collected
= entry
.collected
- 1
369 collection_item
.delete()
370 collection
.items
= collection
.items
- 1
373 messages
.add_message(
374 request
, messages
.SUCCESS
, _('You deleted the item from the collection.'))
376 messages
.add_message(
377 request
, messages
.ERROR
,
378 _("The item was not removed because you didn't check that you were sure."))
380 return redirect(request
, "mediagoblin.user_pages.user_collection",
382 collection
=collection
.slug
)
384 if ((request
.user
.is_admin
and
385 request
.user
.id != collection_item
.in_collection
.creator
)):
386 messages
.add_message(
387 request
, messages
.WARNING
,
388 _("You are about to delete an item from another user's collection. "
389 "Proceed with caution."))
391 return render_to_response(
393 'mediagoblin/user_pages/collection_item_confirm_remove.html',
394 {'collection_item': collection_item
,
399 @require_active_login
400 @user_may_alter_collection
401 def collection_confirm_delete(request
, collection
):
403 form
= user_forms
.ConfirmDeleteForm(request
.form
)
405 if request
.method
== 'POST' and form
.validate():
407 username
= collection
.get_creator
.username
409 if form
.confirm
.data
is True:
410 collection_title
= collection
.title
412 # Delete all the associated collection items
413 for item
in collection
.get_collection_items():
414 entry
= item
.get_media_entry
415 entry
.collected
= entry
.collected
- 1
420 messages
.add_message(
421 request
, messages
.SUCCESS
, _('You deleted the collection "%s"' % collection_title
))
423 return redirect(request
, "mediagoblin.user_pages.user_home",
426 messages
.add_message(
427 request
, messages
.ERROR
,
428 _("The collection was not deleted because you didn't check that you were sure."))
430 return redirect(request
, "mediagoblin.user_pages.user_collection",
432 collection
=collection
.slug
)
434 if ((request
.user
.is_admin
and
435 request
.user
.id != collection
.creator
)):
436 messages
.add_message(
437 request
, messages
.WARNING
,
438 _("You are about to delete another user's collection. "
439 "Proceed with caution."))
441 return render_to_response(
443 'mediagoblin/user_pages/collection_confirm_delete.html',
444 {'collection': collection
,
448 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
= 15
451 def atom_feed(request
):
453 generates the atom feed with the newest images
455 user
= User
.query
.filter_by(
456 username
= request
.matchdict
['user'],
457 status
= u
'active').first()
459 return render_404(request
)
461 cursor
= MediaEntry
.query
.filter_by(
463 state
= u
'processed').\
464 order_by(MediaEntry
.created
.desc()).\
465 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
468 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
471 'href': request
.urlgen(
472 'mediagoblin.user_pages.user_home',
473 qualified
=True, user
=request
.matchdict
['user']),
478 if mg_globals
.app_config
["push_urls"]:
479 for push_url
in mg_globals
.app_config
["push_urls"]:
485 "MediaGoblin: Feed for user '%s'" % request
.matchdict
['user'],
486 feed_url
=request
.url
,
487 id='tag:{host},{year}:gallery.user-{user}'.format(
489 year
=datetime
.datetime
.today().strftime('%Y'),
490 user
=request
.matchdict
['user']),
494 feed
.add(entry
.get('title'),
495 entry
.description_html
,
496 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
499 'name': entry
.get_uploader
.username
,
500 'uri': request
.urlgen(
501 'mediagoblin.user_pages.user_home',
502 qualified
=True, user
=entry
.get_uploader
.username
)},
503 updated
=entry
.get('created'),
505 'href': entry
.url_for_self(
509 'type': 'text/html'}])
511 return feed
.get_response()
514 def collection_atom_feed(request
):
516 generates the atom feed with the newest images from a collection
518 user
= User
.query
.filter_by(
519 username
= request
.matchdict
['user'],
520 status
= u
'active').first()
522 return render_404(request
)
524 collection
= Collection
.query
.filter_by(
526 slug
=request
.matchdict
['collection']).first()
528 cursor
= CollectionItem
.query
.filter_by(
529 collection
=collection
.id) \
530 .order_by(CollectionItem
.added
.desc()) \
531 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
534 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
537 'href': request
.urlgen(
538 'mediagoblin.user_pages.user_collection',
539 qualified
=True, user
=request
.matchdict
['user'], collection
=collection
.slug
),
544 if mg_globals
.app_config
["push_urls"]:
545 for push_url
in mg_globals
.app_config
["push_urls"]:
551 "MediaGoblin: Feed for %s's collection %s" % (request
.matchdict
['user'], collection
.title
),
552 feed_url
=request
.url
,
553 id='tag:{host},{year}:collection.user-{user}.title-{title}'.format(
555 year
=datetime
.datetime
.today().strftime('%Y'),
556 user
=request
.matchdict
['user'],
557 title
=collection
.title
),
561 entry
= item
.get_media_entry
562 feed
.add(entry
.get('title'),
564 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
567 'name': entry
.get_uploader
.username
,
568 'uri': request
.urlgen(
569 'mediagoblin.user_pages.user_home',
570 qualified
=True, user
=entry
.get_uploader
.username
)},
571 updated
=item
.get('added'),
573 'href': entry
.url_for_self(
577 'type': 'text/html'}])
579 return feed
.get_response()
582 @require_active_login
583 def processing_panel(request
):
585 Show to the user what media is still in conversion/processing...
586 and what failed, and why!
588 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
589 # TODO: XXX: Should this be a decorator?
591 # Make sure we have permission to access this user's panel. Only
592 # admins and this user herself should be able to do so.
593 if not (user
.id == request
.user
.id or request
.user
.is_admin
):
594 # No? Simply redirect to this user's homepage.
596 request
, 'mediagoblin.user_pages.user_home',
599 # Get media entries which are in-processing
600 processing_entries
= MediaEntry
.query
.\
601 filter_by(uploader
= user
.id,
602 state
= u
'processing').\
603 order_by(MediaEntry
.created
.desc())
605 # Get media entries which have failed to process
606 failed_entries
= MediaEntry
.query
.\
607 filter_by(uploader
= user
.id,
609 order_by(MediaEntry
.created
.desc())
611 processed_entries
= MediaEntry
.query
.\
612 filter_by(uploader
= user
.id,
613 state
= u
'processed').\
614 order_by(MediaEntry
.created
.desc()).\
618 return render_to_response(
620 'mediagoblin/user_pages/processing_panel.html',
622 'processing_entries': processing_entries
,
623 'failed_entries': failed_entries
,
624 'processed_entries': processed_entries
})