Merge branch 'merge-python3-port'
[mediagoblin.git] / mediagoblin / plugins / piwigo / views.py
CommitLineData
427beb08
E
1# GNU MediaGoblin -- federated, autonomous media hosting
2# Copyright (C) 2013 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
17import logging
398d3841 18import re
427beb08 19
e49b7e02
BP
20import six
21
90d7de25 22from werkzeug.exceptions import MethodNotAllowed, BadRequest, NotImplemented
e4e5948c 23from werkzeug.wrappers import BaseResponse
427beb08 24
860b380b 25from mediagoblin.tools.translate import pass_to_ugettext as _
427beb08 26from mediagoblin.meddleware.csrf import csrf_exempt
1d321f1c 27from mediagoblin.auth.tools import check_login_simple
860b380b
CAW
28from mediagoblin.submit.lib import \
29 submit_media, check_file_field, get_upload_file_limits, \
30 FileUploadLimit, UserUploadLimit, UserPastUploadLimit
31
c732f422 32
41501106
MS
33from mediagoblin.user_pages.lib import add_media_to_collection
34from mediagoblin.db.models import Collection
35
4adc3a85
E
36from .tools import CmdTable, response_xml, check_form, \
37 PWGSession, PwgNamedArray, PwgError
c1df8d19 38from .forms import AddSimpleForm, AddForm
427beb08
E
39
40
41_log = logging.getLogger(__name__)
42
43
427beb08
E
44@CmdTable("pwg.session.login", True)
45def pwg_login(request):
46 username = request.form.get("username")
47 password = request.form.get("password")
1d321f1c 48 user = check_login_simple(username, password)
7fb419dd 49 if not user:
4adc3a85 50 return PwgError(999, 'Invalid username/password')
7fb419dd
E
51 request.session["user_id"] = user.id
52 request.session.save()
e4e5948c 53 return True
bd3bc044
E
54
55
56@CmdTable("pwg.session.logout")
57def pwg_logout(request):
58 _log.info("Logout")
7fb419dd 59 request.session.delete()
e4e5948c 60 return True
bd3bc044
E
61
62
63@CmdTable("pwg.getVersion")
64def pwg_getversion(request):
9924cd0f 65 return "2.5.0 (MediaGoblin)"
cf0816c1
E
66
67
68@CmdTable("pwg.session.getStatus")
69def pwg_session_getStatus(request):
66594603
E
70 if request.user:
71 username = request.user.username
72 else:
73 username = "guest"
74 return {'username': username}
e4e5948c
E
75
76
77@CmdTable("pwg.categories.getList")
78def pwg_categories_getList(request):
41501106 79 catlist = [{'id': -29711,
cf0816c1 80 'uppercats': "-29711",
41501106
MS
81 'name': "All my images"}]
82
7da90d56 83 if request.user:
cac478e5
MS
84 collections = Collection.query.filter_by(
85 get_creator=request.user).order_by(Collection.title)
86
7da90d56
MS
87 for c in collections:
88 catlist.append({'id': c.id,
89 'uppercats': str(c.id),
90 'name': c.title,
91 'comment': c.description
92 })
41501106 93
e4e5948c
E
94 return {
95 'categories': PwgNamedArray(
96 catlist,
97 'category',
98 (
99 'id',
100 'url',
101 'nb_images',
102 'total_nb_images',
103 'nb_categories',
104 'date_last',
105 'max_date_last',
106 )
107 )
108 }
427beb08
E
109
110
398d3841
E
111@CmdTable("pwg.images.exist")
112def pwg_images_exist(request):
113 return {}
114
115
79f87b97
E
116@CmdTable("pwg.images.addSimple", True)
117def pwg_images_addSimple(request):
118 form = AddSimpleForm(request.form)
119 if not form.validate():
120 _log.error("addSimple: form failed")
121 raise BadRequest()
122 dump = []
123 for f in form:
124 dump.append("%s=%r" % (f.name, f.data))
1d321f1c 125 _log.info("addSimple: %r %s %r", request.form, " ".join(dump),
18e64476 126 request.files)
79f87b97 127
f6f55769
E
128 if not check_file_field(request, 'image'):
129 raise BadRequest()
130
860b380b
CAW
131 upload_limit, max_file_size = get_upload_file_limits(request.user)
132
133 try:
134 entry = submit_media(
a8413d8b
CAW
135 mg_app=request.app, user=request.user,
136 submitted_file=request.files['image'],
137 filename=request.files['image'].filename,
e49b7e02
BP
138 title=six.text_type(form.name.data),
139 description=six.text_type(form.comment.data),
a8413d8b 140 upload_limit=upload_limit, max_file_size=max_file_size)
860b380b
CAW
141
142 collection_id = form.category.data
143 if collection_id > 0:
144 collection = Collection.query.get(collection_id)
145 if collection is not None and collection.creator == request.user.id:
146 add_media_to_collection(collection, entry, "")
147
148 return {
149 'image_id': entry.id,
150 'url': entry.url_for_self(
151 request.urlgen,
152 qualified=True)}
153
154 # Handle upload limit issues
155 except FileUploadLimit:
156 raise BadRequest(
157 _(u'Sorry, the file size is too big.'))
158 except UserUploadLimit:
159 raise BadRequest(
160 _('Sorry, uploading this file will put you over your'
161 ' upload limit.'))
162 except UserPastUploadLimit:
163 raise BadRequest(
164 _('Sorry, you have reached your upload limit.'))
c732f422 165
79f87b97 166
398d3841
E
167md5sum_matcher = re.compile(r"^[0-9a-fA-F]{32}$")
168
c732f422 169
398d3841
E
170def fetch_md5(request, parm_name, optional_parm=False):
171 val = request.form.get(parm_name)
172 if (val is None) and (not optional_parm):
173 _log.error("Parameter %s missing", parm_name)
174 raise BadRequest("Parameter %s missing" % parm_name)
175 if not md5sum_matcher.match(val):
176 _log.error("Parameter %s=%r has no valid md5 value", parm_name, val)
177 raise BadRequest("Parameter %s is not md5" % parm_name)
178 return val
179
180
181@CmdTable("pwg.images.addChunk", True)
182def pwg_images_addChunk(request):
183 o_sum = fetch_md5(request, 'original_sum')
184 typ = request.form.get('type')
185 pos = request.form.get('position')
186 data = request.form.get('data')
187
188 # Validate params:
189 pos = int(pos)
190 if not typ in ("file", "thumb"):
191 _log.error("type %r not allowed for now", typ)
192 return False
193
194 _log.info("addChunk for %r, type %r, position %d, len: %d",
195 o_sum, typ, pos, len(data))
196 if typ == "thumb":
197 _log.info("addChunk: Ignoring thumb, because we create our own")
198 return True
199
200 return True
201
202
c1df8d19
E
203@CmdTable("pwg.images.add", True)
204def pwg_images_add(request):
205 _log.info("add: %r", request.form)
206 form = AddForm(request.form)
207 check_form(form)
208
209 return {'image_id': 123456, 'url': ''}
210
211
427beb08
E
212@csrf_exempt
213def ws_php(request):
214 if request.method not in ("GET", "POST"):
215 _log.error("Method %r not supported", request.method)
216 raise MethodNotAllowed()
217
218 func = CmdTable.find_func(request)
219 if not func:
220 _log.warn("wsphp: Unhandled %s %r %r", request.method,
221 request.args, request.form)
90d7de25 222 raise NotImplemented()
427beb08 223
7fb419dd
E
224 with PWGSession(request) as session:
225 result = func(request)
427beb08 226
7fb419dd
E
227 if isinstance(result, BaseResponse):
228 return result
e4e5948c 229
7fb419dd
E
230 response = response_xml(result)
231 session.save_to_cookie(response)
dc7c26f3 232
7fb419dd 233 return response