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
.util
import DESCENDING
, ObjectId
22 from mediagoblin
.db
.sql
.models
import (MediaEntry
, Collection
, CollectionItem
,
24 from mediagoblin
.tools
.response
import render_to_response
, render_404
, redirect
25 from mediagoblin
.tools
.translate
import pass_to_ugettext
as _
26 from mediagoblin
.tools
.pagination
import Pagination
27 from mediagoblin
.tools
.files
import delete_media_files
28 from mediagoblin
.user_pages
import forms
as user_forms
29 from mediagoblin
.user_pages
.lib
import send_comment_email
31 from mediagoblin
.decorators
import (uses_pagination
, get_user_media_entry
,
32 require_active_login
, user_may_delete_media
, user_may_alter_collection
,
33 get_user_collection
, get_user_collection_item
, active_user_from_url
)
35 from werkzeug
.contrib
.atom
import AtomFeed
38 _log
= logging
.getLogger(__name__
)
39 _log
.setLevel(logging
.DEBUG
)
43 def user_home(request
, page
):
44 """'Homepage' of a User()"""
45 # TODO: decide if we only want homepages for active users, we can
46 # then use the @get_active_user decorator and also simplify the
48 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
50 return render_404(request
)
51 elif user
.status
!= u
'active':
52 return render_to_response(
54 'mediagoblin/user_pages/user.html',
57 cursor
= MediaEntry
.query
.\
58 filter_by(uploader
= user
.id,
59 state
= u
'processed').sort('created', DESCENDING
)
61 pagination
= Pagination(page
, cursor
)
62 media_entries
= pagination()
64 #if no data is available, return NotFound
65 if media_entries
== None:
66 return render_404(request
)
68 user_gallery_url
= request
.urlgen(
69 'mediagoblin.user_pages.user_gallery',
72 return render_to_response(
74 'mediagoblin/user_pages/user.html',
76 'user_gallery_url': user_gallery_url
,
77 'media_entries': media_entries
,
78 'pagination': pagination
})
83 def user_gallery(request
, page
, url_user
=None):
84 """'Gallery' of a User()"""
85 cursor
= MediaEntry
.query
.filter_by(
87 state
=u
'processed').order_by(MediaEntry
.created
.desc())
90 pagination
= Pagination(page
, cursor
)
91 media_entries
= pagination()
93 #if no data is available, return NotFound
94 # TODO: Should we really also return 404 for empty galleries?
95 if media_entries
== None:
96 return render_404(request
)
98 return render_to_response(
100 'mediagoblin/user_pages/gallery.html',
102 'media_entries': media_entries
,
103 'pagination': pagination
})
105 MEDIA_COMMENTS_PER_PAGE
= 50
108 @get_user_media_entry
110 def media_home(request
, media
, page
, **kwargs
):
112 'Homepage' of a MediaEntry()
114 if request
.matchdict
.get('comment', None):
115 pagination
= Pagination(
116 page
, media
.get_comments(
117 mg_globals
.app_config
['comments_ascending']),
118 MEDIA_COMMENTS_PER_PAGE
,
119 ObjectId(request
.matchdict
.get('comment')))
121 pagination
= Pagination(
122 page
, media
.get_comments(
123 mg_globals
.app_config
['comments_ascending']),
124 MEDIA_COMMENTS_PER_PAGE
)
126 comments
= pagination()
128 comment_form
= user_forms
.MediaCommentForm(request
.form
)
130 media_template_name
= media
.media_manager
['display_template']
132 return render_to_response(
136 'comments': comments
,
137 'pagination': pagination
,
138 'comment_form': comment_form
,
139 'app_config': mg_globals
.app_config
})
142 @get_user_media_entry
143 @require_active_login
144 def media_post_comment(request
, media
):
146 recieves POST from a MediaEntry() comment form, saves the comment.
148 assert request
.method
== 'POST'
150 comment
= request
.db
.MediaComment()
151 comment
.media_entry
= media
.id
152 comment
.author
= request
.user
.id
153 comment
.content
= unicode(request
.form
['comment_content'])
155 if not comment
.content
.strip():
156 messages
.add_message(
159 _("Oops, your comment was empty."))
163 messages
.add_message(
164 request
, messages
.SUCCESS
,
165 _('Your comment has been posted!'))
167 media_uploader
= media
.get_uploader
168 #don't send email if you comment on your own post
169 if (comment
.author
!= media_uploader
and
170 media_uploader
.wants_comment_notification
):
171 send_comment_email(media_uploader
, comment
, media
, request
)
173 return redirect(request
, location
=media
.url_for_self(request
.urlgen
))
176 @get_user_media_entry
177 @require_active_login
178 def media_collect(request
, media
):
179 """Add media to collection submission"""
181 form
= user_forms
.MediaCollectForm(request
.form
)
182 # A user's own collections:
183 form
.collection
.query
= Collection
.query
.filter_by(
184 creator
= request
.user
.id).order_by(Collection
.title
)
186 if request
.method
!= 'POST' or not form
.validate():
187 # No POST submission, or invalid form
188 if not form
.validate():
189 messages
.add_message(request
, messages
.ERROR
,
190 _('Please check your entries and try again.'))
192 return render_to_response(
194 'mediagoblin/user_pages/media_collect.html',
198 # If we are here, method=POST and the form is valid, submit things.
199 # If the user is adding a new collection, use that:
200 if request
.form
['collection_title']:
201 # Make sure this user isn't duplicating an existing collection
202 existing_collection
= Collection
.query
.filter_by(
203 creator
=request
.user
.id,
204 title
=request
.form
['collection_title']).first()
205 if existing_collection
:
206 messages
.add_message(request
, messages
.ERROR
,
207 _('You already have a collection called "%s"!'
209 return redirect(request
, "mediagoblin.user_pages.media_home",
210 user
=request
.user
.username
,
213 collection
= Collection()
214 collection
.title
= request
.form
['collection_title']
215 collection
.description
= request
.form
.get('collection_description')
216 collection
.creator
= request
.user
.id
217 collection
.generate_slug()
218 collection
.save(validate
=True)
220 # Otherwise, use the collection selected from the drop-down
222 collection
= Collection
.query
.filter_by(
223 id=request
.form
.get('collection')).first()
225 # Make sure the user actually selected a collection
227 messages
.add_message(
228 request
, messages
.ERROR
,
229 _('You have to select or add a collection'))
231 # Check whether media already exists in collection
232 elif CollectionItem
.query
.filter_by(
233 media_entry
=media
.id,
234 collection
=collection
.id).first():
235 messages
.add_message(request
, messages
.ERROR
,
236 _('"%s" already in collection "%s"'
237 % (media
.title
, collection
.title
)))
238 else: # Add item to collection
239 collection_item
= request
.db
.CollectionItem()
240 collection_item
.collection
= collection
.id
241 collection_item
.media_entry
= media
.id
242 collection_item
.author
= request
.user
.id
243 collection_item
.note
= request
.form
['note']
244 collection_item
.save(validate
=True)
246 collection
.items
= collection
.items
+ 1
247 collection
.save(validate
=True)
249 media
.collected
= media
.collected
+ 1
252 messages
.add_message(request
, messages
.SUCCESS
,
253 _('"%s" added to collection "%s"'
254 % (media
.title
, collection
.title
)))
256 return redirect(request
, "mediagoblin.user_pages.media_home",
257 user
=media
.get_uploader
.username
,
261 #TODO: Why does @user_may_delete_media not implicate @require_active_login?
262 @get_user_media_entry
263 @require_active_login
264 @user_may_delete_media
265 def media_confirm_delete(request
, media
):
267 form
= user_forms
.ConfirmDeleteForm(request
.form
)
269 if request
.method
== 'POST' and form
.validate():
270 if form
.confirm
.data
is True:
271 username
= media
.get_uploader
.username
273 # Delete all the associated comments
274 for comment
in media
.get_comments():
277 # Delete all files on the public storage
279 delete_media_files(media
)
280 except OSError, error
:
281 _log
.error('No such files from the user "{1}"'
282 ' to delete: {0}'.format(str(error
), username
))
283 messages
.add_message(request
, messages
.ERROR
,
284 _('Some of the files with this entry seem'
285 ' to be missing. Deleting anyway.'))
288 messages
.add_message(
289 request
, messages
.SUCCESS
, _('You deleted the media.'))
291 return redirect(request
, "mediagoblin.user_pages.user_home",
294 messages
.add_message(
295 request
, messages
.ERROR
,
296 _("The media was not deleted because you didn't check that you were sure."))
297 return redirect(request
,
298 location
=media
.url_for_self(request
.urlgen
))
300 if ((request
.user
.is_admin
and
301 request
.user
.id != media
.uploader
)):
302 messages
.add_message(
303 request
, messages
.WARNING
,
304 _("You are about to delete another user's media. "
305 "Proceed with caution."))
307 return render_to_response(
309 'mediagoblin/user_pages/media_confirm_delete.html',
314 @active_user_from_url
316 def user_collection(request
, page
, url_user
=None):
317 """A User-defined Collection"""
318 collection
= Collection
.query
.filter_by(
319 get_creator
=url_user
,
320 slug
=request
.matchdict
['collection']).first()
322 cursor
= collection
.get_collection_items()
324 pagination
= Pagination(page
, cursor
)
325 collection_items
= pagination()
327 # if no data is available, return NotFound
328 # TODO: Should an empty collection really also return 404?
329 if collection_items
== None:
330 return render_404(request
)
332 return render_to_response(
334 'mediagoblin/user_pages/collection.html',
336 'collection': collection
,
337 'collection_items': collection_items
,
338 'pagination': pagination
})
341 @get_user_collection_item
342 @require_active_login
343 @user_may_alter_collection
344 def collection_item_confirm_remove(request
, collection_item
):
346 form
= user_forms
.ConfirmCollectionItemRemoveForm(request
.form
)
348 if request
.method
== 'POST' and form
.validate():
349 username
= collection_item
.in_collection
.get_creator
.username
350 collection
= collection_item
.in_collection
352 if form
.confirm
.data
is True:
353 entry
= collection_item
.get_media_entry
354 entry
.collected
= entry
.collected
- 1
357 collection_item
.delete()
358 collection
.items
= collection
.items
- 1
361 messages
.add_message(
362 request
, messages
.SUCCESS
, _('You deleted the item from the collection.'))
364 messages
.add_message(
365 request
, messages
.ERROR
,
366 _("The item was not removed because you didn't check that you were sure."))
368 return redirect(request
, "mediagoblin.user_pages.user_collection",
370 collection
=collection
.slug
)
372 if ((request
.user
.is_admin
and
373 request
.user
.id != collection_item
.in_collection
.creator
)):
374 messages
.add_message(
375 request
, messages
.WARNING
,
376 _("You are about to delete an item from another user's collection. "
377 "Proceed with caution."))
379 return render_to_response(
381 'mediagoblin/user_pages/collection_item_confirm_remove.html',
382 {'collection_item': collection_item
,
387 @require_active_login
388 @user_may_alter_collection
389 def collection_confirm_delete(request
, collection
):
391 form
= user_forms
.ConfirmDeleteForm(request
.form
)
393 if request
.method
== 'POST' and form
.validate():
395 username
= collection
.get_creator
.username
397 if form
.confirm
.data
is True:
398 collection_title
= collection
.title
400 # Delete all the associated collection items
401 for item
in collection
.get_collection_items():
402 entry
= item
.get_media_entry
403 entry
.collected
= entry
.collected
- 1
408 messages
.add_message(
409 request
, messages
.SUCCESS
, _('You deleted the collection "%s"' % collection_title
))
411 return redirect(request
, "mediagoblin.user_pages.user_home",
414 messages
.add_message(
415 request
, messages
.ERROR
,
416 _("The collection was not deleted because you didn't check that you were sure."))
418 return redirect(request
, "mediagoblin.user_pages.user_collection",
420 collection
=collection
.slug
)
422 if ((request
.user
.is_admin
and
423 request
.user
.id != collection
.creator
)):
424 messages
.add_message(
425 request
, messages
.WARNING
,
426 _("You are about to delete another user's collection. "
427 "Proceed with caution."))
429 return render_to_response(
431 'mediagoblin/user_pages/collection_confirm_delete.html',
432 {'collection': collection
,
436 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
= 15
439 def atom_feed(request
):
441 generates the atom feed with the newest images
443 user
= User
.query
.filter_by(
444 username
= request
.matchdict
['user'],
445 status
= u
'active').first()
447 return render_404(request
)
449 cursor
= MediaEntry
.query
.filter_by(
451 state
= u
'processed').\
452 sort('created', DESCENDING
).\
453 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
456 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
459 'href': request
.urlgen(
460 'mediagoblin.user_pages.user_home',
461 qualified
=True, user
=request
.matchdict
['user']),
466 if mg_globals
.app_config
["push_urls"]:
467 for push_url
in mg_globals
.app_config
["push_urls"]:
473 "MediaGoblin: Feed for user '%s'" % request
.matchdict
['user'],
474 feed_url
=request
.url
,
475 id='tag:{host},{year}:gallery.user-{user}'.format(
477 year
=datetime
.datetime
.today().strftime('%Y'),
478 user
=request
.matchdict
['user']),
482 feed
.add(entry
.get('title'),
483 entry
.description_html
,
484 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
487 'name': entry
.get_uploader
.username
,
488 'uri': request
.urlgen(
489 'mediagoblin.user_pages.user_home',
490 qualified
=True, user
=entry
.get_uploader
.username
)},
491 updated
=entry
.get('created'),
493 'href': entry
.url_for_self(
497 'type': 'text/html'}])
499 return feed
.get_response()
502 def collection_atom_feed(request
):
504 generates the atom feed with the newest images from a collection
506 user
= User
.query
.filter_by(
507 username
= request
.matchdict
['user'],
508 status
= u
'active').first()
510 return render_404(request
)
512 collection
= Collection
.query
.filter_by(
514 slug
=request
.matchdict
['collection']).first()
516 cursor
= CollectionItem
.query
.filter_by(
517 collection
=collection
.id) \
518 .sort(CollectionItem
.added
.desc()) \
519 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
522 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
525 'href': request
.urlgen(
526 'mediagoblin.user_pages.user_collection',
527 qualified
=True, user
=request
.matchdict
['user'], collection
=collection
.slug
),
532 if mg_globals
.app_config
["push_urls"]:
533 for push_url
in mg_globals
.app_config
["push_urls"]:
539 "MediaGoblin: Feed for %s's collection %s" % (request
.matchdict
['user'], collection
.title
),
540 feed_url
=request
.url
,
541 id='tag:{host},{year}:collection.user-{user}.title-{title}'.format(
543 year
=datetime
.datetime
.today().strftime('%Y'),
544 user
=request
.matchdict
['user'],
545 title
=collection
.title
),
549 entry
= item
.get_media_entry
550 feed
.add(entry
.get('title'),
552 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
555 'name': entry
.get_uploader
.username
,
556 'uri': request
.urlgen(
557 'mediagoblin.user_pages.user_home',
558 qualified
=True, user
=entry
.get_uploader
.username
)},
559 updated
=item
.get('added'),
561 'href': entry
.url_for_self(
565 'type': 'text/html'}])
567 return feed
.get_response()
570 @require_active_login
571 def processing_panel(request
):
573 Show to the user what media is still in conversion/processing...
574 and what failed, and why!
576 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
577 # TODO: XXX: Should this be a decorator?
579 # Make sure we have permission to access this user's panel. Only
580 # admins and this user herself should be able to do so.
581 if not (user
== request
.user
582 or request
.user
.is_admin
):
583 # No? Simply redirect to this user's homepage.
587 request
, 'mediagoblin.user_pages.user_home',
590 # Get media entries which are in-processing
591 processing_entries
= MediaEntry
.query
.\
592 filter_by(uploader
= user
.id,
593 state
= u
'processing').\
594 order_by(MediaEntry
.created
.desc())
596 # Get media entries which have failed to process
597 failed_entries
= MediaEntry
.query
.\
598 filter_by(uploader
= user
.id,
600 order_by(MediaEntry
.created
.desc())
602 processed_entries
= MediaEntry
.query
.\
603 filter_by(uploader
= user
.id,
604 state
= u
'processed').\
605 order_by(MediaEntry
.created
.desc()).\
609 return render_to_response(
611 'mediagoblin/user_pages/processing_panel.html',
613 'processing_entries': processing_entries
,
614 'failed_entries': failed_entries
,
615 'processed_entries': processed_entries
})