Enable /u/USERNAME/edit/ pattern #588
[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_user_media_entry, user_may_alter_collection, get_user_collection)
31 from mediagoblin.tools.response import render_to_response, redirect
32 from mediagoblin.tools.translate import pass_to_ugettext as _
33 from mediagoblin.tools.text import (
34 convert_to_tag_list_of_dicts, media_tags_as_string)
35 from mediagoblin.db.util import check_media_slug_used, check_collection_slug_used
36
37 import mimetypes
38
39
40 @get_user_media_entry
41 @require_active_login
42 def edit_media(request, media):
43 if not may_edit_media(request, media):
44 raise Forbidden("User may not edit this media")
45
46 defaults = dict(
47 title=media.title,
48 slug=media.slug,
49 description=media.description,
50 tags=media_tags_as_string(media.tags),
51 license=media.license)
52
53 form = forms.EditForm(
54 request.form,
55 **defaults)
56
57 if request.method == 'POST' and form.validate():
58 # Make sure there isn't already a MediaEntry with such a slug
59 # and userid.
60 slug_used = check_media_slug_used(request.db, media.uploader,
61 request.form['slug'], media.id)
62
63 if slug_used:
64 form.slug.errors.append(
65 _(u'An entry with that slug already exists for this user.'))
66 else:
67 media.title = unicode(request.form['title'])
68 media.description = unicode(request.form.get('description'))
69 media.tags = convert_to_tag_list_of_dicts(
70 request.form.get('tags'))
71
72 media.license = unicode(request.form.get('license', '')) or None
73
74 media.slug = unicode(request.form['slug'])
75
76 media.save()
77
78 return redirect(request,
79 location=media.url_for_self(request.urlgen))
80
81 if request.user.is_admin \
82 and media.uploader != request.user.id \
83 and request.method != 'POST':
84 messages.add_message(
85 request, messages.WARNING,
86 _("You are editing another user's media. Proceed with caution."))
87
88 return render_to_response(
89 request,
90 'mediagoblin/edit/edit.html',
91 {'media': media,
92 'form': form})
93
94
95 # Mimetypes that browsers parse scripts in.
96 # Content-sniffing isn't taken into consideration.
97 UNSAFE_MIMETYPES = [
98 'text/html',
99 'text/svg+xml']
100
101
102 @get_user_media_entry
103 @require_active_login
104 def edit_attachments(request, media):
105 if mg_globals.app_config['allow_attachments']:
106 form = forms.EditAttachmentsForm()
107
108 # Add any attachements
109 if 'attachment_file' in request.files \
110 and request.files['attachment_file']:
111
112 # Security measure to prevent attachments from being served as
113 # text/html, which will be parsed by web clients and pose an XSS
114 # threat.
115 #
116 # TODO
117 # This method isn't flawless as some browsers may perform
118 # content-sniffing.
119 # This method isn't flawless as we do the mimetype lookup on the
120 # machine parsing the upload form, and not necessarily the machine
121 # serving the attachments.
122 if mimetypes.guess_type(
123 request.files['attachment_file'].filename)[0] in \
124 UNSAFE_MIMETYPES:
125 public_filename = secure_filename('{0}.notsafe'.format(
126 request.files['attachment_file'].filename))
127 else:
128 public_filename = secure_filename(
129 request.files['attachment_file'].filename)
130
131 attachment_public_filepath \
132 = mg_globals.public_store.get_unique_filepath(
133 ['media_entries', unicode(media.id), 'attachment',
134 public_filename])
135
136 attachment_public_file = mg_globals.public_store.get_file(
137 attachment_public_filepath, 'wb')
138
139 try:
140 attachment_public_file.write(
141 request.files['attachment_file'].stream.read())
142 finally:
143 request.files['attachment_file'].stream.close()
144
145 media.attachment_files.append(dict(
146 name=request.form['attachment_name'] \
147 or request.files['attachment_file'].filename,
148 filepath=attachment_public_filepath,
149 created=datetime.utcnow(),
150 ))
151
152 media.save()
153
154 messages.add_message(
155 request, messages.SUCCESS,
156 _("You added the attachment %s!") \
157 % (request.form['attachment_name']
158 or request.files['attachment_file'].filename))
159
160 return redirect(request,
161 location=media.url_for_self(request.urlgen))
162 return render_to_response(
163 request,
164 'mediagoblin/edit/attachments.html',
165 {'media': media,
166 'form': form})
167 else:
168 raise Forbidden("Attachments are disabled")
169
170 @require_active_login
171 def legacy_edit_profile(request):
172 """redirect the old /edit/profile/?username=USER to /u/USER/edit/"""
173 username = request.GET.get('username') or request.user.username
174 return redirect(request, 'mediagoblin.edit.profile', user=username)
175
176
177 @require_active_login
178 @active_user_from_url
179 def edit_profile(request, url_user=None):
180 # admins may edit any user profile
181 if request.user.username != url_user.username:
182 if not request.user.is_admin:
183 raise Forbidden(_("You can only edit your own profile."))
184
185 # No need to warn again if admin just submitted an edited profile
186 if request.method != 'POST':
187 messages.add_message(
188 request, messages.WARNING,
189 _("You are editing a user's profile. Proceed with caution."))
190
191 user = url_user
192
193 form = forms.EditProfileForm(request.form,
194 url=user.get('url'),
195 bio=user.get('bio'))
196
197 if request.method == 'POST' and form.validate():
198 user.url = unicode(request.form['url'])
199 user.bio = unicode(request.form['bio'])
200
201 user.save()
202
203 messages.add_message(request,
204 messages.SUCCESS,
205 _("Profile changes saved"))
206 return redirect(request,
207 'mediagoblin.user_pages.user_home',
208 user=user.username)
209
210 return render_to_response(
211 request,
212 'mediagoblin/edit/edit_profile.html',
213 {'user': user,
214 'form': form})
215
216
217 @require_active_login
218 def edit_account(request):
219 user = request.user
220 form = forms.EditAccountForm(request.form,
221 wants_comment_notification=user.get('wants_comment_notification'))
222
223 if request.method == 'POST':
224 form_validated = form.validate()
225
226 #if the user has not filled in the new or old password fields
227 if not form.new_password.data and not form.old_password.data:
228 if form.wants_comment_notification.validate(form):
229 user.wants_comment_notification = \
230 form.wants_comment_notification.data
231 user.save()
232 messages.add_message(request,
233 messages.SUCCESS,
234 _("Account settings saved"))
235 return redirect(request,
236 'mediagoblin.user_pages.user_home',
237 user=user.username)
238
239 #so the user has filled in one or both of the password fields
240 else:
241 if form_validated:
242 password_matches = auth_lib.bcrypt_check_password(
243 form.old_password.data,
244 user.pw_hash)
245 if password_matches:
246 #the entire form validates and the password matches
247 user.pw_hash = auth_lib.bcrypt_gen_password_hash(
248 form.new_password.data)
249 user.wants_comment_notification = \
250 form.wants_comment_notification.data
251 user.save()
252 messages.add_message(request,
253 messages.SUCCESS,
254 _("Account settings saved"))
255 return redirect(request,
256 'mediagoblin.user_pages.user_home',
257 user=user.username)
258 else:
259 form.old_password.errors.append(_('Wrong password'))
260
261 return render_to_response(
262 request,
263 'mediagoblin/edit/edit_account.html',
264 {'user': user,
265 'form': form})
266
267
268 @require_active_login
269 @user_may_alter_collection
270 @get_user_collection
271 def edit_collection(request, collection):
272 defaults = dict(
273 title=collection.title,
274 slug=collection.slug,
275 description=collection.description)
276
277 form = forms.EditCollectionForm(
278 request.form,
279 **defaults)
280
281 if request.method == 'POST' and form.validate():
282 # Make sure there isn't already a Collection with such a slug
283 # and userid.
284 slug_used = check_collection_slug_used(request.db, collection.creator,
285 request.form['slug'], collection.id)
286
287 # Make sure there isn't already a Collection with this title
288 existing_collection = request.db.Collection.find_one({
289 'creator': request.user.id,
290 'title':request.form['title']})
291
292 if existing_collection and existing_collection.id != collection.id:
293 messages.add_message(
294 request, messages.ERROR,
295 _('You already have a collection called "%s"!') % \
296 request.form['title'])
297 elif slug_used:
298 form.slug.errors.append(
299 _(u'A collection with that slug already exists for this user.'))
300 else:
301 collection.title = unicode(request.form['title'])
302 collection.description = unicode(request.form.get('description'))
303 collection.slug = unicode(request.form['slug'])
304
305 collection.save()
306
307 return redirect(request, "mediagoblin.user_pages.user_collection",
308 user=collection.get_creator.username,
309 collection=collection.slug)
310
311 if request.user.is_admin \
312 and collection.creator != request.user.id \
313 and request.method != 'POST':
314 messages.add_message(
315 request, messages.WARNING,
316 _("You are editing another user's collection. Proceed with caution."))
317
318 return render_to_response(
319 request,
320 'mediagoblin/edit/edit_collection.html',
321 {'collection': collection,
322 'form': form})