Add "Browse collections" link to profile pages
[mediagoblin.git] / mediagoblin / edit / views.py
CommitLineData
9bfe1d8e 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
9bfe1d8e
E
3#
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.
8#
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.
13#
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/>.
aba81c9f 16
3a8c3a38
JW
17from cgi import FieldStorage
18from datetime import datetime
19
62d14bf5 20from werkzeug.exceptions import Forbidden
3a8c3a38 21from werkzeug.utils import secure_filename
aba81c9f 22
d9ed098e 23from mediagoblin import messages
10d7496d 24from mediagoblin import mg_globals
152a3bfa 25
4837b2f2 26from mediagoblin.auth import lib as auth_lib
aba81c9f 27from mediagoblin.edit import forms
b5a64f78 28from mediagoblin.edit.lib import may_edit_media
abc4da29 29from mediagoblin.decorators import (require_active_login, active_user_from_url,
461dd971 30 get_media_entry_by_id,
abc4da29 31 get_user_media_entry, user_may_alter_collection, get_user_collection)
152a3bfa
AW
32from mediagoblin.tools.response import render_to_response, redirect
33from mediagoblin.tools.translate import pass_to_ugettext as _
34from mediagoblin.tools.text import (
a855e92a 35 convert_to_tag_list_of_dicts, media_tags_as_string)
be5be115 36from mediagoblin.db.util import check_media_slug_used, check_collection_slug_used
c849e690 37
825b1362
JW
38import mimetypes
39
97ec97db 40
461dd971 41@get_media_entry_by_id
aba81c9f
E
42@require_active_login
43def edit_media(request, media):
c849e690 44 if not may_edit_media(request, media):
cfa92229 45 raise Forbidden("User may not edit this media")
c849e690 46
2c437493 47 defaults = dict(
ec82fbd8 48 title=media.title,
5da0bf90 49 slug=media.slug,
1d939966 50 description=media.description,
a6c49d49 51 tags=media_tags_as_string(media.tags),
97ec97db 52 license=media.license)
aba81c9f 53
2c437493 54 form = forms.EditForm(
111a609d 55 request.form,
2c437493
JW
56 **defaults)
57
98857207 58 if request.method == 'POST' and form.validate():
d5e90fe4
CAW
59 # Make sure there isn't already a MediaEntry with such a slug
60 # and userid.
65969d3f
SS
61 slug_used = check_media_slug_used(media.uploader, request.form['slug'],
62 media.id)
3a8c3a38 63
b62b3b98 64 if slug_used:
d5e90fe4 65 form.slug.errors.append(
4b1adc13 66 _(u'An entry with that slug already exists for this user.'))
d5e90fe4 67 else:
111a609d
JW
68 media.title = unicode(request.form['title'])
69 media.description = unicode(request.form.get('description'))
de917303 70 media.tags = convert_to_tag_list_of_dicts(
111a609d 71 request.form.get('tags'))
3a8c3a38 72
111a609d 73 media.license = unicode(request.form.get('license', '')) or None
25b48323 74
111a609d 75 media.slug = unicode(request.form['slug'])
99a270e9 76
747623cc 77 media.save()
d5e90fe4 78
950124e6
SS
79 return redirect(request,
80 location=media.url_for_self(request.urlgen))
98857207 81
bec591d8 82 if request.user.is_admin \
5c2b8486 83 and media.uploader != request.user.id \
96a2c366
CAW
84 and request.method != 'POST':
85 messages.add_message(
86 request, messages.WARNING,
4b1adc13 87 _("You are editing another user's media. Proceed with caution."))
96a2c366 88
9038c9f9
CAW
89 return render_to_response(
90 request,
c9c24934
E
91 'mediagoblin/edit/edit.html',
92 {'media': media,
93 'form': form})
46fd661e 94
3a8c3a38 95
825b1362
JW
96# Mimetypes that browsers parse scripts in.
97# Content-sniffing isn't taken into consideration.
98UNSAFE_MIMETYPES = [
99 'text/html',
100 'text/svg+xml']
101
102
3a8c3a38 103@get_user_media_entry
630b57a3 104@require_active_login
3a8c3a38
JW
105def edit_attachments(request, media):
106 if mg_globals.app_config['allow_attachments']:
107 form = forms.EditAttachmentsForm()
108
109 # Add any attachements
c43f8c1d
JW
110 if 'attachment_file' in request.files \
111 and request.files['attachment_file']:
3a8c3a38 112
825b1362
JW
113 # Security measure to prevent attachments from being served as
114 # text/html, which will be parsed by web clients and pose an XSS
115 # threat.
116 #
117 # TODO
118 # This method isn't flawless as some browsers may perform
119 # content-sniffing.
120 # This method isn't flawless as we do the mimetype lookup on the
121 # machine parsing the upload form, and not necessarily the machine
122 # serving the attachments.
123 if mimetypes.guess_type(
c43f8c1d 124 request.files['attachment_file'].filename)[0] in \
825b1362
JW
125 UNSAFE_MIMETYPES:
126 public_filename = secure_filename('{0}.notsafe'.format(
c43f8c1d 127 request.files['attachment_file'].filename))
825b1362
JW
128 else:
129 public_filename = secure_filename(
c43f8c1d 130 request.files['attachment_file'].filename)
825b1362 131
3a8c3a38
JW
132 attachment_public_filepath \
133 = mg_globals.public_store.get_unique_filepath(
5c2b8486 134 ['media_entries', unicode(media.id), 'attachment',
825b1362 135 public_filename])
3a8c3a38
JW
136
137 attachment_public_file = mg_globals.public_store.get_file(
138 attachment_public_filepath, 'wb')
139
140 try:
141 attachment_public_file.write(
c43f8c1d 142 request.files['attachment_file'].stream.read())
3a8c3a38 143 finally:
c43f8c1d 144 request.files['attachment_file'].stream.close()
3a8c3a38 145
35029581 146 media.attachment_files.append(dict(
111a609d 147 name=request.form['attachment_name'] \
c43f8c1d 148 or request.files['attachment_file'].filename,
3a8c3a38 149 filepath=attachment_public_filepath,
243c3843 150 created=datetime.utcnow(),
3a8c3a38 151 ))
630b57a3 152
3a8c3a38
JW
153 media.save()
154
155 messages.add_message(
156 request, messages.SUCCESS,
32255ec0 157 _("You added the attachment %s!") \
111a609d 158 % (request.form['attachment_name']
c43f8c1d 159 or request.files['attachment_file'].filename))
3a8c3a38 160
950124e6
SS
161 return redirect(request,
162 location=media.url_for_self(request.urlgen))
3a8c3a38
JW
163 return render_to_response(
164 request,
165 'mediagoblin/edit/attachments.html',
166 {'media': media,
167 'form': form})
168 else:
cfa92229 169 raise Forbidden("Attachments are disabled")
3a8c3a38 170
abc4da29
SS
171@require_active_login
172def legacy_edit_profile(request):
173 """redirect the old /edit/profile/?username=USER to /u/USER/edit/"""
174 username = request.GET.get('username') or request.user.username
175 return redirect(request, 'mediagoblin.edit.profile', user=username)
176
3a8c3a38
JW
177
178@require_active_login
abc4da29
SS
179@active_user_from_url
180def edit_profile(request, url_user=None):
181 # admins may edit any user profile
182 if request.user.username != url_user.username:
183 if not request.user.is_admin:
184 raise Forbidden(_("You can only edit your own profile."))
185
a0cf14fe
CFD
186 # No need to warn again if admin just submitted an edited profile
187 if request.method != 'POST':
188 messages.add_message(
189 request, messages.WARNING,
4b1adc13 190 _("You are editing a user's profile. Proceed with caution."))
abc4da29
SS
191
192 user = url_user
a0cf14fe 193
111a609d 194 form = forms.EditProfileForm(request.form,
3a8c3a38
JW
195 url=user.get('url'),
196 bio=user.get('bio'))
630b57a3 197
198 if request.method == 'POST' and form.validate():
111a609d
JW
199 user.url = unicode(request.form['url'])
200 user.bio = unicode(request.form['bio'])
4c465852 201
c8071fa5 202 user.save()
630b57a3 203
c8071fa5
JS
204 messages.add_message(request,
205 messages.SUCCESS,
206 _("Profile changes saved"))
207 return redirect(request,
208 'mediagoblin.user_pages.user_home',
703d09b9 209 user=user.username)
630b57a3 210
211 return render_to_response(
212 request,
213 'mediagoblin/edit/edit_profile.html',
214 {'user': user,
215 'form': form})
c8071fa5
JS
216
217
218@require_active_login
219def edit_account(request):
c8071fa5 220 user = request.user
111a609d 221 form = forms.EditAccountForm(request.form,
fa72e516 222 wants_comment_notification=user.get('wants_comment_notification'))
c8071fa5 223
252eaf21 224 if request.method == 'POST':
fa72e516
DM
225 form_validated = form.validate()
226
227 #if the user has not filled in the new or old password fields
228 if not form.new_password.data and not form.old_password.data:
229 if form.wants_comment_notification.validate(form):
230 user.wants_comment_notification = \
231 form.wants_comment_notification.data
232 user.save()
233 messages.add_message(request,
234 messages.SUCCESS,
235 _("Account settings saved"))
236 return redirect(request,
237 'mediagoblin.user_pages.user_home',
238 user=user.username)
239
240 #so the user has filled in one or both of the password fields
241 else:
242 if form_validated:
243 password_matches = auth_lib.bcrypt_check_password(
244 form.old_password.data,
245 user.pw_hash)
246 if password_matches:
247 #the entire form validates and the password matches
248 user.pw_hash = auth_lib.bcrypt_gen_password_hash(
249 form.new_password.data)
250 user.wants_comment_notification = \
251 form.wants_comment_notification.data
252 user.save()
253 messages.add_message(request,
254 messages.SUCCESS,
255 _("Account settings saved"))
256 return redirect(request,
257 'mediagoblin.user_pages.user_home',
258 user=user.username)
259 else:
260 form.old_password.errors.append(_('Wrong password'))
630b57a3 261
262 return render_to_response(
263 request,
c8071fa5 264 'mediagoblin/edit/edit_account.html',
630b57a3 265 {'user': user,
266 'form': form})
be5be115
AW
267
268
380f22b8
SS
269@require_active_login
270def delete_account(request):
271 """Delete a user completely"""
272 user = request.user
273 if request.method == 'POST':
274 if request.form.get(u'confirmed'):
275 # Form submitted and confirmed. Actually delete the user account
276 # Log out user and delete cookies etc.
277 # TODO: Should we be using MG.auth.views.py:logout for this?
278 request.session.delete()
279
280 # Delete user account and all related media files etc....
281 request.user.delete()
282
283 # We should send a message that the user has been deleted
284 # successfully. But we just deleted the session, so we
285 # can't...
286 return redirect(request, 'index')
287
288 else: # Did not check the confirmation box...
289 messages.add_message(
290 request, messages.WARNING,
291 _('You need to confirm the deletion of your account.'))
292
293 # No POST submission or not confirmed, just show page
294 return render_to_response(
295 request,
296 'mediagoblin/edit/delete_account.html',
297 {'user': user})
298
299
be5be115
AW
300@require_active_login
301@user_may_alter_collection
302@get_user_collection
303def edit_collection(request, collection):
304 defaults = dict(
305 title=collection.title,
306 slug=collection.slug,
307 description=collection.description)
308
309 form = forms.EditCollectionForm(
111a609d 310 request.form,
be5be115
AW
311 **defaults)
312
313 if request.method == 'POST' and form.validate():
314 # Make sure there isn't already a Collection with such a slug
315 # and userid.
316 slug_used = check_collection_slug_used(request.db, collection.creator,
111a609d 317 request.form['slug'], collection.id)
c43f8c1d 318
be5be115
AW
319 # Make sure there isn't already a Collection with this title
320 existing_collection = request.db.Collection.find_one({
5c2b8486 321 'creator': request.user.id,
111a609d 322 'title':request.form['title']})
c43f8c1d 323
be5be115
AW
324 if existing_collection and existing_collection.id != collection.id:
325 messages.add_message(
a6481028
CAW
326 request, messages.ERROR,
327 _('You already have a collection called "%s"!') % \
111a609d 328 request.form['title'])
be5be115
AW
329 elif slug_used:
330 form.slug.errors.append(
331 _(u'A collection with that slug already exists for this user.'))
332 else:
111a609d
JW
333 collection.title = unicode(request.form['title'])
334 collection.description = unicode(request.form.get('description'))
335 collection.slug = unicode(request.form['slug'])
be5be115
AW
336
337 collection.save()
338
339 return redirect(request, "mediagoblin.user_pages.user_collection",
340 user=collection.get_creator.username,
341 collection=collection.slug)
342
343 if request.user.is_admin \
5c2b8486 344 and collection.creator != request.user.id \
be5be115
AW
345 and request.method != 'POST':
346 messages.add_message(
347 request, messages.WARNING,
348 _("You are editing another user's collection. Proceed with caution."))
349
350 return render_to_response(
351 request,
352 'mediagoblin/edit/edit_collection.html',
353 {'collection': collection,
354 'form': form})