Added migration for license field, resolved conflict in db/sql/models.py
[mediagoblin.git] / mediagoblin / edit / views.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 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 = (
79 unicode(request.POST.get('license'))
80 or '')
81
82 media.slug = unicode(request.POST['slug'])
83
84 media.save()
85
86 return exc.HTTPFound(
87 location=media.url_for_self(request.urlgen))
88
89 if request.user.is_admin \
90 and media.uploader != request.user._id \
91 and request.method != 'POST':
92 messages.add_message(
93 request, messages.WARNING,
94 _("You are editing another user's media. Proceed with caution."))
95
96 return render_to_response(
97 request,
98 'mediagoblin/edit/edit.html',
99 {'media': media,
100 'form': form})
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.POST
111 and isinstance(request.POST['attachment_file'], FieldStorage)
112 and request.POST['attachment_file'].file):
113
114 attachment_public_filepath \
115 = mg_globals.public_store.get_unique_filepath(
116 ['media_entries', unicode(media._id), 'attachment',
117 secure_filename(request.POST['attachment_file'].filename)])
118
119 attachment_public_file = mg_globals.public_store.get_file(
120 attachment_public_filepath, 'wb')
121
122 try:
123 attachment_public_file.write(
124 request.POST['attachment_file'].file.read())
125 finally:
126 request.POST['attachment_file'].file.close()
127
128 media['attachment_files'].append(dict(
129 name=request.POST['attachment_name'] \
130 or request.POST['attachment_file'].filename,
131 filepath=attachment_public_filepath,
132 created=datetime.utcnow(),
133 ))
134
135 media.save()
136
137 messages.add_message(
138 request, messages.SUCCESS,
139 "You added the attachment %s!" \
140 % (request.POST['attachment_name']
141 or request.POST['attachment_file'].filename))
142
143 return exc.HTTPFound(
144 location=media.url_for_self(request.urlgen))
145 return render_to_response(
146 request,
147 'mediagoblin/edit/attachments.html',
148 {'media': media,
149 'form': form})
150 else:
151 return exc.HTTPForbidden()
152
153
154 @require_active_login
155 def edit_profile(request):
156 # admins may edit any user profile given a username in the querystring
157 edit_username = request.GET.get('username')
158 if request.user.is_admin and request.user.username != edit_username:
159 user = request.db.User.find_one({'username': edit_username})
160 # No need to warn again if admin just submitted an edited profile
161 if request.method != 'POST':
162 messages.add_message(
163 request, messages.WARNING,
164 _("You are editing a user's profile. Proceed with caution."))
165 else:
166 user = request.user
167
168 form = forms.EditProfileForm(request.POST,
169 url=user.get('url'),
170 bio=user.get('bio'))
171
172 if request.method == 'POST' and form.validate():
173 user.url = unicode(request.POST['url'])
174 user.bio = unicode(request.POST['bio'])
175
176 user.bio_html = cleaned_markdown_conversion(user.bio)
177
178 user.save()
179
180 messages.add_message(request,
181 messages.SUCCESS,
182 _("Profile changes saved"))
183 return redirect(request,
184 'mediagoblin.user_pages.user_home',
185 user=user['username'])
186
187 return render_to_response(
188 request,
189 'mediagoblin/edit/edit_profile.html',
190 {'user': user,
191 'form': form})
192
193
194 @require_active_login
195 def edit_account(request):
196 edit_username = request.GET.get('username')
197 user = request.user
198
199 form = forms.EditAccountForm(request.POST)
200
201 if request.method == 'POST' and form.validate():
202 password_matches = auth_lib.bcrypt_check_password(
203 request.POST['old_password'],
204 user.pw_hash)
205
206 if (request.POST['old_password'] or request.POST['new_password']) and not \
207 password_matches:
208 form.old_password.errors.append(_('Wrong password'))
209
210 return render_to_response(
211 request,
212 'mediagoblin/edit/edit_account.html',
213 {'user': user,
214 'form': form})
215
216 if password_matches:
217 user.pw_hash = auth_lib.bcrypt_gen_password_hash(
218 request.POST['new_password'])
219
220 user.save()
221
222 messages.add_message(request,
223 messages.SUCCESS,
224 _("Account settings saved"))
225 return redirect(request,
226 'mediagoblin.user_pages.user_home',
227 user=user.username)
228
229 return render_to_response(
230 request,
231 'mediagoblin/edit/edit_account.html',
232 {'user': user,
233 'form': form})