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
.sql
.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 @get_user_collection_item
341 @require_active_login
342 @user_may_alter_collection
343 def collection_item_confirm_remove(request
, collection_item
):
345 form
= user_forms
.ConfirmCollectionItemRemoveForm(request
.form
)
347 if request
.method
== 'POST' and form
.validate():
348 username
= collection_item
.in_collection
.get_creator
.username
349 collection
= collection_item
.in_collection
351 if form
.confirm
.data
is True:
352 entry
= collection_item
.get_media_entry
353 entry
.collected
= entry
.collected
- 1
356 collection_item
.delete()
357 collection
.items
= collection
.items
- 1
360 messages
.add_message(
361 request
, messages
.SUCCESS
, _('You deleted the item from the collection.'))
363 messages
.add_message(
364 request
, messages
.ERROR
,
365 _("The item was not removed because you didn't check that you were sure."))
367 return redirect(request
, "mediagoblin.user_pages.user_collection",
369 collection
=collection
.slug
)
371 if ((request
.user
.is_admin
and
372 request
.user
.id != collection_item
.in_collection
.creator
)):
373 messages
.add_message(
374 request
, messages
.WARNING
,
375 _("You are about to delete an item from another user's collection. "
376 "Proceed with caution."))
378 return render_to_response(
380 'mediagoblin/user_pages/collection_item_confirm_remove.html',
381 {'collection_item': collection_item
,
386 @require_active_login
387 @user_may_alter_collection
388 def collection_confirm_delete(request
, collection
):
390 form
= user_forms
.ConfirmDeleteForm(request
.form
)
392 if request
.method
== 'POST' and form
.validate():
394 username
= collection
.get_creator
.username
396 if form
.confirm
.data
is True:
397 collection_title
= collection
.title
399 # Delete all the associated collection items
400 for item
in collection
.get_collection_items():
401 entry
= item
.get_media_entry
402 entry
.collected
= entry
.collected
- 1
407 messages
.add_message(
408 request
, messages
.SUCCESS
, _('You deleted the collection "%s"' % collection_title
))
410 return redirect(request
, "mediagoblin.user_pages.user_home",
413 messages
.add_message(
414 request
, messages
.ERROR
,
415 _("The collection was not deleted because you didn't check that you were sure."))
417 return redirect(request
, "mediagoblin.user_pages.user_collection",
419 collection
=collection
.slug
)
421 if ((request
.user
.is_admin
and
422 request
.user
.id != collection
.creator
)):
423 messages
.add_message(
424 request
, messages
.WARNING
,
425 _("You are about to delete another user's collection. "
426 "Proceed with caution."))
428 return render_to_response(
430 'mediagoblin/user_pages/collection_confirm_delete.html',
431 {'collection': collection
,
435 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
= 15
438 def atom_feed(request
):
440 generates the atom feed with the newest images
442 user
= User
.query
.filter_by(
443 username
= request
.matchdict
['user'],
444 status
= u
'active').first()
446 return render_404(request
)
448 cursor
= MediaEntry
.query
.filter_by(
450 state
= u
'processed').\
451 order_by(MediaEntry
.created
.desc()).\
452 limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
455 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
458 'href': request
.urlgen(
459 'mediagoblin.user_pages.user_home',
460 qualified
=True, user
=request
.matchdict
['user']),
465 if mg_globals
.app_config
["push_urls"]:
466 for push_url
in mg_globals
.app_config
["push_urls"]:
472 "MediaGoblin: Feed for user '%s'" % request
.matchdict
['user'],
473 feed_url
=request
.url
,
474 id='tag:{host},{year}:gallery.user-{user}'.format(
476 year
=datetime
.datetime
.today().strftime('%Y'),
477 user
=request
.matchdict
['user']),
481 feed
.add(entry
.get('title'),
482 entry
.description_html
,
483 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
486 'name': entry
.get_uploader
.username
,
487 'uri': request
.urlgen(
488 'mediagoblin.user_pages.user_home',
489 qualified
=True, user
=entry
.get_uploader
.username
)},
490 updated
=entry
.get('created'),
492 'href': entry
.url_for_self(
496 'type': 'text/html'}])
498 return feed
.get_response()
501 def collection_atom_feed(request
):
503 generates the atom feed with the newest images from a collection
505 user
= User
.query
.filter_by(
506 username
= request
.matchdict
['user'],
507 status
= u
'active').first()
509 return render_404(request
)
511 collection
= Collection
.query
.filter_by(
513 slug
=request
.matchdict
['collection']).first()
515 cursor
= CollectionItem
.query
.filter_by(
516 collection
=collection
.id) \
517 .sort(CollectionItem
.added
.desc()) \
518 .limit(ATOM_DEFAULT_NR_OF_UPDATED_ITEMS
)
521 ATOM feed id is a tag URI (see http://en.wikipedia.org/wiki/Tag_URI)
524 'href': request
.urlgen(
525 'mediagoblin.user_pages.user_collection',
526 qualified
=True, user
=request
.matchdict
['user'], collection
=collection
.slug
),
531 if mg_globals
.app_config
["push_urls"]:
532 for push_url
in mg_globals
.app_config
["push_urls"]:
538 "MediaGoblin: Feed for %s's collection %s" % (request
.matchdict
['user'], collection
.title
),
539 feed_url
=request
.url
,
540 id='tag:{host},{year}:collection.user-{user}.title-{title}'.format(
542 year
=datetime
.datetime
.today().strftime('%Y'),
543 user
=request
.matchdict
['user'],
544 title
=collection
.title
),
548 entry
= item
.get_media_entry
549 feed
.add(entry
.get('title'),
551 id=entry
.url_for_self(request
.urlgen
, qualified
=True),
554 'name': entry
.get_uploader
.username
,
555 'uri': request
.urlgen(
556 'mediagoblin.user_pages.user_home',
557 qualified
=True, user
=entry
.get_uploader
.username
)},
558 updated
=item
.get('added'),
560 'href': entry
.url_for_self(
564 'type': 'text/html'}])
566 return feed
.get_response()
569 @require_active_login
570 def processing_panel(request
):
572 Show to the user what media is still in conversion/processing...
573 and what failed, and why!
575 user
= User
.query
.filter_by(username
=request
.matchdict
['user']).first()
576 # TODO: XXX: Should this be a decorator?
578 # Make sure we have permission to access this user's panel. Only
579 # admins and this user herself should be able to do so.
580 if not (user
.id == request
.user
.id or request
.user
.is_admin
):
581 # No? Simply redirect to this user's homepage.
583 request
, 'mediagoblin.user_pages.user_home',
586 # Get media entries which are in-processing
587 processing_entries
= MediaEntry
.query
.\
588 filter_by(uploader
= user
.id,
589 state
= u
'processing').\
590 order_by(MediaEntry
.created
.desc())
592 # Get media entries which have failed to process
593 failed_entries
= MediaEntry
.query
.\
594 filter_by(uploader
= user
.id,
596 order_by(MediaEntry
.created
.desc())
598 processed_entries
= MediaEntry
.query
.\
599 filter_by(uploader
= user
.id,
600 state
= u
'processed').\
601 order_by(MediaEntry
.created
.desc()).\
605 return render_to_response(
607 'mediagoblin/user_pages/processing_panel.html',
609 'processing_entries': processing_entries
,
610 'failed_entries': failed_entries
,
611 'processed_entries': processed_entries
})