added unittests, now using form errors and fixed bug when no GET parameter is given...
[mediagoblin.git] / mediagoblin / edit / views.py
CommitLineData
9bfe1d8e 1# GNU MediaGoblin -- federated, autonomous media hosting
12a100e4 2# Copyright (C) 2011 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
08750772 17import uuid
aba81c9f 18
1c63ad5d 19from webob import exc
04a95150 20from string import split
3a8c3a38
JW
21from cgi import FieldStorage
22from datetime import datetime
23
24from werkzeug.utils import secure_filename
aba81c9f 25
d9ed098e 26from mediagoblin import messages
10d7496d 27from mediagoblin import mg_globals
152a3bfa 28
4837b2f2 29from mediagoblin.auth import lib as auth_lib
aba81c9f 30from mediagoblin.edit import forms
0732236e 31from mediagoblin.edit.lib import may_edit_media
8cd5d4f8 32from mediagoblin.decorators import require_active_login, get_user_media_entry
152a3bfa
AW
33from mediagoblin.tools.response import render_to_response, redirect
34from mediagoblin.tools.translate import pass_to_ugettext as _
35from mediagoblin.tools.text import (
36 clean_html, convert_to_tag_list_of_dicts,
37 media_tags_as_string, cleaned_markdown_conversion)
c849e690 38
8cd5d4f8 39@get_user_media_entry
aba81c9f
E
40@require_active_login
41def edit_media(request, media):
c849e690
E
42 if not may_edit_media(request, media):
43 return exc.HTTPForbidden()
44
2c437493 45 defaults = dict(
3a8c3a38
JW
46 title=media['title'],
47 slug=media['slug'],
48 description=media['description'],
49 tags=media_tags_as_string(media['tags']))
aba81c9f 50
2c437493
JW
51 form = forms.EditForm(
52 request.POST,
53 **defaults)
54
98857207 55 if request.method == 'POST' and form.validate():
d5e90fe4
CAW
56 # Make sure there isn't already a MediaEntry with such a slug
57 # and userid.
58 existing_user_slug_entries = request.db.MediaEntry.find(
59 {'slug': request.POST['slug'],
60 'uploader': media['uploader'],
eabe6b67 61 '_id': {'$ne': media._id}}).count()
3a8c3a38 62
d5e90fe4
CAW
63 if existing_user_slug_entries:
64 form.slug.errors.append(
4b1adc13 65 _(u'An entry with that slug already exists for this user.'))
d5e90fe4 66 else:
08750772
MH
67 media['title'] = unicode(request.POST['title'])
68 media['description'] = unicode(request.POST.get('description'))
0712a06d
CFD
69 media['tags'] = convert_to_tag_list_of_dicts(
70 request.POST.get('tags'))
3a8c3a38 71
0d91af09
CAW
72 media['description_html'] = cleaned_markdown_conversion(
73 media['description'])
44e2da2f 74
08750772 75 media['slug'] = unicode(request.POST['slug'])
747623cc 76 media.save()
d5e90fe4 77
8d7b549b
E
78 return exc.HTTPFound(
79 location=media.url_for_self(request.urlgen))
98857207 80
96a2c366 81 if request.user['is_admin'] \
eabe6b67 82 and media['uploader'] != request.user._id \
96a2c366
CAW
83 and request.method != 'POST':
84 messages.add_message(
85 request, messages.WARNING,
4b1adc13 86 _("You are editing another user's media. Proceed with caution."))
96a2c366 87
9038c9f9
CAW
88 return render_to_response(
89 request,
c9c24934
E
90 'mediagoblin/edit/edit.html',
91 {'media': media,
92 'form': form})
46fd661e 93
3a8c3a38
JW
94
95@get_user_media_entry
630b57a3 96@require_active_login
3a8c3a38
JW
97def edit_attachments(request, media):
98 if mg_globals.app_config['allow_attachments']:
99 form = forms.EditAttachmentsForm()
100
101 # Add any attachements
102 if ('attachment_file' in request.POST
103 and isinstance(request.POST['attachment_file'], FieldStorage)
104 and request.POST['attachment_file'].file):
105
106 attachment_public_filepath \
107 = mg_globals.public_store.get_unique_filepath(
eabe6b67 108 ['media_entries', unicode(media._id), 'attachment',
3a8c3a38
JW
109 secure_filename(request.POST['attachment_file'].filename)])
110
111 attachment_public_file = mg_globals.public_store.get_file(
112 attachment_public_filepath, 'wb')
113
114 try:
115 attachment_public_file.write(
116 request.POST['attachment_file'].file.read())
117 finally:
118 request.POST['attachment_file'].file.close()
119
120 media['attachment_files'].append(dict(
121 name=request.POST['attachment_name'] \
122 or request.POST['attachment_file'].filename,
123 filepath=attachment_public_filepath,
243c3843 124 created=datetime.utcnow(),
3a8c3a38 125 ))
630b57a3 126
3a8c3a38
JW
127 media.save()
128
129 messages.add_message(
130 request, messages.SUCCESS,
131 "You added the attachment %s!" \
132 % (request.POST['attachment_name']
133 or request.POST['attachment_file'].filename))
134
8d7b549b
E
135 return exc.HTTPFound(
136 location=media.url_for_self(request.urlgen))
3a8c3a38
JW
137 return render_to_response(
138 request,
139 'mediagoblin/edit/attachments.html',
140 {'media': media,
141 'form': form})
142 else:
143 return exc.HTTPForbidden()
144
145
146@require_active_login
147def edit_profile(request):
a0cf14fe
CFD
148 # admins may edit any user profile given a username in the querystring
149 edit_username = request.GET.get('username')
150 if request.user['is_admin'] and request.user['username'] != edit_username:
151 user = request.db.User.find_one({'username': edit_username})
152 # No need to warn again if admin just submitted an edited profile
153 if request.method != 'POST':
154 messages.add_message(
155 request, messages.WARNING,
4b1adc13 156 _("You are editing a user's profile. Proceed with caution."))
a0cf14fe
CFD
157 else:
158 user = request.user
159
630b57a3 160 form = forms.EditProfileForm(request.POST,
3a8c3a38
JW
161 url=user.get('url'),
162 bio=user.get('bio'))
630b57a3 163
164 if request.method == 'POST' and form.validate():
c8ccd23e
JK
165 password_matches = auth_lib.bcrypt_check_password(
166 request.POST['old_password'],
167 user['pw_hash'])
630b57a3 168
4837b2f2
JK
169 if (request.POST['old_password'] or request.POST['new_password']) and not \
170 password_matches:
c8ccd23e
JK
171 form.old_password.errors.append(_('Wrong password'))
172
173 return render_to_response(
174 request,
175 'mediagoblin/edit/edit_profile.html',
176 {'user': user,
177 'form': form})
178
179 user['url'] = unicode(request.POST['url'])
180 user['bio'] = unicode(request.POST['bio'])
4837b2f2
JK
181
182 if password_matches:
183 user['pw_hash'] = auth_lib.bcrypt_gen_password_hash(
184 request.POST['new_password'])
185
186 user['bio_html'] = cleaned_markdown_conversion(user['bio'])
187
188 user.save()
189
190 messages.add_message(request,
191 messages.SUCCESS,
192 _("Profile edited!"))
193 return redirect(request,
194 'mediagoblin.user_pages.user_home',
c8ccd23e 195 user=user['username'])
630b57a3 196
197 return render_to_response(
198 request,
199 'mediagoblin/edit/edit_profile.html',
200 {'user': user,
201 'form': form})