It's 2012 all up in here
[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 import uuid
18
19 from webob import exc
20 from string import split
21 from cgi import FieldStorage
22 from datetime import datetime
23
24 from werkzeug.utils import secure_filename
25
26 from mediagoblin import messages
27 from mediagoblin import mg_globals
28
29 from mediagoblin.auth import lib as auth_lib
30 from mediagoblin.edit import forms
31 from mediagoblin.edit.lib import may_edit_media
32 from mediagoblin.decorators import require_active_login, get_user_media_entry
33 from mediagoblin.tools.response import render_to_response, redirect
34 from mediagoblin.tools.translate import pass_to_ugettext as _
35 from mediagoblin.tools.text import (
36 clean_html, convert_to_tag_list_of_dicts,
37 media_tags_as_string, cleaned_markdown_conversion)
38 from mediagoblin.tools.licenses import SUPPORTED_LICENSES
39
40
41 @get_user_media_entry
42 @require_active_login
43 def edit_media(request, media):
44 if not may_edit_media(request, media):
45 return exc.HTTPForbidden()
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.POST,
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 existing_user_slug_entries = request.db.MediaEntry.find(
62 {'slug': request.POST['slug'],
63 'uploader': media.uploader,
64 '_id': {'$ne': media._id}}).count()
65
66 if existing_user_slug_entries:
67 form.slug.errors.append(
68 _(u'An entry with that slug already exists for this user.'))
69 else:
70 media.title = unicode(request.POST['title'])
71 media.description = unicode(request.POST.get('description'))
72 media.tags = convert_to_tag_list_of_dicts(
73 request.POST.get('tags'))
74
75 media.description_html = cleaned_markdown_conversion(
76 media.description)
77
78 media.license = unicode(request.POST.get('license', '')) or None
79
80 media.slug = unicode(request.POST['slug'])
81
82 media.save()
83
84 return exc.HTTPFound(
85 location=media.url_for_self(request.urlgen))
86
87 if request.user.is_admin \
88 and media.uploader != request.user._id \
89 and request.method != 'POST':
90 messages.add_message(
91 request, messages.WARNING,
92 _("You are editing another user's media. Proceed with caution."))
93
94 return render_to_response(
95 request,
96 'mediagoblin/edit/edit.html',
97 {'media': media,
98 'form': form})
99
100
101 @get_user_media_entry
102 @require_active_login
103 def edit_attachments(request, media):
104 if mg_globals.app_config['allow_attachments']:
105 form = forms.EditAttachmentsForm()
106
107 # Add any attachements
108 if ('attachment_file' in request.POST
109 and isinstance(request.POST['attachment_file'], FieldStorage)
110 and request.POST['attachment_file'].file):
111
112 attachment_public_filepath \
113 = mg_globals.public_store.get_unique_filepath(
114 ['media_entries', unicode(media._id), 'attachment',
115 secure_filename(request.POST['attachment_file'].filename)])
116
117 attachment_public_file = mg_globals.public_store.get_file(
118 attachment_public_filepath, 'wb')
119
120 try:
121 attachment_public_file.write(
122 request.POST['attachment_file'].file.read())
123 finally:
124 request.POST['attachment_file'].file.close()
125
126 media['attachment_files'].append(dict(
127 name=request.POST['attachment_name'] \
128 or request.POST['attachment_file'].filename,
129 filepath=attachment_public_filepath,
130 created=datetime.utcnow(),
131 ))
132
133 media.save()
134
135 messages.add_message(
136 request, messages.SUCCESS,
137 "You added the attachment %s!" \
138 % (request.POST['attachment_name']
139 or request.POST['attachment_file'].filename))
140
141 return exc.HTTPFound(
142 location=media.url_for_self(request.urlgen))
143 return render_to_response(
144 request,
145 'mediagoblin/edit/attachments.html',
146 {'media': media,
147 'form': form})
148 else:
149 return exc.HTTPForbidden()
150
151
152 @require_active_login
153 def edit_profile(request):
154 # admins may edit any user profile given a username in the querystring
155 edit_username = request.GET.get('username')
156 if request.user.is_admin and request.user.username != edit_username:
157 user = request.db.User.find_one({'username': edit_username})
158 # No need to warn again if admin just submitted an edited profile
159 if request.method != 'POST':
160 messages.add_message(
161 request, messages.WARNING,
162 _("You are editing a user's profile. Proceed with caution."))
163 else:
164 user = request.user
165
166 form = forms.EditProfileForm(request.POST,
167 url=user.get('url'),
168 bio=user.get('bio'))
169
170 if request.method == 'POST' and form.validate():
171 user.url = unicode(request.POST['url'])
172 user.bio = unicode(request.POST['bio'])
173
174 user.bio_html = cleaned_markdown_conversion(user.bio)
175
176 user.save()
177
178 messages.add_message(request,
179 messages.SUCCESS,
180 _("Profile changes saved"))
181 return redirect(request,
182 'mediagoblin.user_pages.user_home',
183 user=user['username'])
184
185 return render_to_response(
186 request,
187 'mediagoblin/edit/edit_profile.html',
188 {'user': user,
189 'form': form})
190
191
192 @require_active_login
193 def edit_account(request):
194 edit_username = request.GET.get('username')
195 user = request.user
196
197 form = forms.EditAccountForm(request.POST)
198
199 if request.method == 'POST' and form.validate():
200 password_matches = auth_lib.bcrypt_check_password(
201 request.POST['old_password'],
202 user.pw_hash)
203
204 if (request.POST['old_password'] or request.POST['new_password']) and not \
205 password_matches:
206 form.old_password.errors.append(_('Wrong password'))
207
208 return render_to_response(
209 request,
210 'mediagoblin/edit/edit_account.html',
211 {'user': user,
212 'form': form})
213
214 if password_matches:
215 user.pw_hash = auth_lib.bcrypt_gen_password_hash(
216 request.POST['new_password'])
217
218 user.save()
219
220 messages.add_message(request,
221 messages.SUCCESS,
222 _("Account settings saved"))
223 return redirect(request,
224 'mediagoblin.user_pages.user_home',
225 user=user.username)
226
227 return render_to_response(
228 request,
229 'mediagoblin/edit/edit_account.html',
230 {'user': user,
231 'form': form})