Merge remote-tracking branch 'refs/remotes/origin/533-new-dropdown'
[mediagoblin.git] / mediagoblin / edit / views.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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/>.
16
17 from cgi import FieldStorage
18 from datetime import datetime
19
20 from werkzeug.exceptions import Forbidden
21 from werkzeug.utils import secure_filename
22
23 from mediagoblin import messages
24 from mediagoblin import mg_globals
25
26 from mediagoblin.auth import lib as auth_lib
27 from mediagoblin.edit import forms
28 from mediagoblin.edit.lib import may_edit_media
29 from mediagoblin.decorators import (require_active_login, active_user_from_url,
30 get_media_entry_by_id,
31 get_user_media_entry, user_may_alter_collection, get_user_collection)
32 from mediagoblin.tools.response import render_to_response, redirect
33 from mediagoblin.tools.translate import pass_to_ugettext as _
34 from mediagoblin.tools.text import (
35 convert_to_tag_list_of_dicts, media_tags_as_string)
36 from mediagoblin.db.util import check_media_slug_used, check_collection_slug_used
37
38 import mimetypes
39
40
41 @get_media_entry_by_id
42 @require_active_login
43 def edit_media(request, media):
44 if not may_edit_media(request, media):
45 raise Forbidden("User may not edit this media")
46
47 defaults = dict(
48 title=media.title,
49 slug=media.slug,
50 description=media.description,
51 tags=media_tags_as_string(media.tags),
52 license=media.license)
53
54 form = forms.EditForm(
55 request.form,
56 **defaults)
57
58 if request.method == 'POST' and form.validate():
59 # Make sure there isn't already a MediaEntry with such a slug
60 # and userid.
61 slug_used = check_media_slug_used(media.uploader, request.form['slug'],
62 media.id)
63
64 if slug_used:
65 form.slug.errors.append(
66 _(u'An entry with that slug already exists for this user.'))
67 else:
68 media.title = unicode(request.form['title'])
69 media.description = unicode(request.form.get('description'))
70 media.tags = convert_to_tag_list_of_dicts(
71 request.form.get('tags'))
72
73 media.license = unicode(request.form.get('license', '')) or None
74
75 media.slug = unicode(request.form['slug'])
76
77 media.save()
78
79 return redirect(request,
80 location=media.url_for_self(request.urlgen))
81
82 if request.user.is_admin \
83 and media.uploader != request.user.id \
84 and request.method != 'POST':
85 messages.add_message(
86 request, messages.WARNING,
87 _("You are editing another user's media. Proceed with caution."))
88
89 return render_to_response(
90 request,
91 'mediagoblin/edit/edit.html',
92 {'media': media,
93 'form': form})
94
95
96 # Mimetypes that browsers parse scripts in.
97 # Content-sniffing isn't taken into consideration.
98 UNSAFE_MIMETYPES = [
99 'text/html',
100 'text/svg+xml']
101
102
103 @get_user_media_entry
104 @require_active_login
105 def edit_attachments(request, media):
106 if mg_globals.app_config['allow_attachments']:
107 form = forms.EditAttachmentsForm()
108
109 # Add any attachements
110 if 'attachment_file' in request.files \
111 and request.files['attachment_file']:
112
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(
124 request.files['attachment_file'].filename)[0] in \
125 UNSAFE_MIMETYPES:
126 public_filename = secure_filename('{0}.notsafe'.format(
127 request.files['attachment_file'].filename))
128 else:
129 public_filename = secure_filename(
130 request.files['attachment_file'].filename)
131
132 attachment_public_filepath \
133 = mg_globals.public_store.get_unique_filepath(
134 ['media_entries', unicode(media.id), 'attachment',
135 public_filename])
136
137 attachment_public_file = mg_globals.public_store.get_file(
138 attachment_public_filepath, 'wb')
139
140 try:
141 attachment_public_file.write(
142 request.files['attachment_file'].stream.read())
143 finally:
144 request.files['attachment_file'].stream.close()
145
146 media.attachment_files.append(dict(
147 name=request.form['attachment_name'] \
148 or request.files['attachment_file'].filename,
149 filepath=attachment_public_filepath,
150 created=datetime.utcnow(),
151 ))
152
153 media.save()
154
155 messages.add_message(
156 request, messages.SUCCESS,
157 _("You added the attachment %s!") \
158 % (request.form['attachment_name']
159 or request.files['attachment_file'].filename))
160
161 return redirect(request,
162 location=media.url_for_self(request.urlgen))
163 return render_to_response(
164 request,
165 'mediagoblin/edit/attachments.html',
166 {'media': media,
167 'form': form})
168 else:
169 raise Forbidden("Attachments are disabled")
170
171 @require_active_login
172 def 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
177
178 @require_active_login
179 @active_user_from_url
180 def 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
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,
190 _("You are editing a user's profile. Proceed with caution."))
191
192 user = url_user
193
194 form = forms.EditProfileForm(request.form,
195 url=user.get('url'),
196 bio=user.get('bio'))
197
198 if request.method == 'POST' and form.validate():
199 user.url = unicode(request.form['url'])
200 user.bio = unicode(request.form['bio'])
201
202 user.save()
203
204 messages.add_message(request,
205 messages.SUCCESS,
206 _("Profile changes saved"))
207 return redirect(request,
208 'mediagoblin.user_pages.user_home',
209 user=user.username)
210
211 return render_to_response(
212 request,
213 'mediagoblin/edit/edit_profile.html',
214 {'user': user,
215 'form': form})
216
217
218 @require_active_login
219 def edit_account(request):
220 user = request.user
221 form = forms.EditAccountForm(request.form,
222 wants_comment_notification=user.get('wants_comment_notification'))
223
224 if request.method == 'POST':
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'))
261
262 return render_to_response(
263 request,
264 'mediagoblin/edit/edit_account.html',
265 {'user': user,
266 'form': form})
267
268
269 @require_active_login
270 def 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
300 @require_active_login
301 @user_may_alter_collection
302 @get_user_collection
303 def edit_collection(request, collection):
304 defaults = dict(
305 title=collection.title,
306 slug=collection.slug,
307 description=collection.description)
308
309 form = forms.EditCollectionForm(
310 request.form,
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,
317 request.form['slug'], collection.id)
318
319 # Make sure there isn't already a Collection with this title
320 existing_collection = request.db.Collection.find_one({
321 'creator': request.user.id,
322 'title':request.form['title']})
323
324 if existing_collection and existing_collection.id != collection.id:
325 messages.add_message(
326 request, messages.ERROR,
327 _('You already have a collection called "%s"!') % \
328 request.form['title'])
329 elif slug_used:
330 form.slug.errors.append(
331 _(u'A collection with that slug already exists for this user.'))
332 else:
333 collection.title = unicode(request.form['title'])
334 collection.description = unicode(request.form.get('description'))
335 collection.slug = unicode(request.form['slug'])
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 \
344 and collection.creator != request.user.id \
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})