Use check_file_field in pwg_images_addSimple.
[mediagoblin.git] / mediagoblin / plugins / piwigo / views.py
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
17 import logging
18 import re
19
20 from werkzeug.exceptions import MethodNotAllowed, BadRequest
21 from werkzeug.wrappers import BaseResponse
22
23 from mediagoblin import mg_globals
24 from mediagoblin.meddleware.csrf import csrf_exempt
25 from mediagoblin.tools.response import render_404
26 from mediagoblin.submit.lib import check_file_field
27 from .tools import CmdTable, PwgNamedArray, response_xml
28 from .forms import AddSimpleForm
29
30
31 _log = logging.getLogger(__name__)
32
33
34 @CmdTable("pwg.session.login", True)
35 def pwg_login(request):
36 username = request.form.get("username")
37 password = request.form.get("password")
38 _log.info("Login for %r/%r...", username, password)
39 return True
40
41
42 @CmdTable("pwg.session.logout")
43 def pwg_logout(request):
44 _log.info("Logout")
45 return True
46
47
48 @CmdTable("pwg.getVersion")
49 def pwg_getversion(request):
50 return "2.5.0 (MediaGoblin)"
51
52
53 @CmdTable("pwg.session.getStatus")
54 def pwg_session_getStatus(request):
55 return {'username': "fake_user"}
56
57
58 @CmdTable("pwg.categories.getList")
59 def pwg_categories_getList(request):
60 catlist = ({'id': -29711,
61 'uppercats': "-29711",
62 'name': "All my images"},)
63 return {
64 'categories': PwgNamedArray(
65 catlist,
66 'category',
67 (
68 'id',
69 'url',
70 'nb_images',
71 'total_nb_images',
72 'nb_categories',
73 'date_last',
74 'max_date_last',
75 )
76 )
77 }
78
79
80 @CmdTable("pwg.images.exist")
81 def pwg_images_exist(request):
82 return {}
83
84
85 @CmdTable("pwg.images.addSimple", True)
86 def pwg_images_addSimple(request):
87 form = AddSimpleForm(request.form)
88 if not form.validate():
89 _log.error("addSimple: form failed")
90 raise BadRequest()
91 dump = []
92 for f in form:
93 dump.append("%s=%r" % (f.name, f.data))
94 _log.info("addimple: %r %s %r", request.form, " ".join(dump), request.files)
95
96 if not check_file_field(request, 'image'):
97 raise BadRequest()
98
99 return {'image_id': 123456, 'url': ''}
100
101
102 md5sum_matcher = re.compile(r"^[0-9a-fA-F]{32}$")
103
104 def fetch_md5(request, parm_name, optional_parm=False):
105 val = request.form.get(parm_name)
106 if (val is None) and (not optional_parm):
107 _log.error("Parameter %s missing", parm_name)
108 raise BadRequest("Parameter %s missing" % parm_name)
109 if not md5sum_matcher.match(val):
110 _log.error("Parameter %s=%r has no valid md5 value", parm_name, val)
111 raise BadRequest("Parameter %s is not md5" % parm_name)
112 return val
113
114
115 @CmdTable("pwg.images.addChunk", True)
116 def pwg_images_addChunk(request):
117 o_sum = fetch_md5(request, 'original_sum')
118 typ = request.form.get('type')
119 pos = request.form.get('position')
120 data = request.form.get('data')
121
122 # Validate params:
123 pos = int(pos)
124 if not typ in ("file", "thumb"):
125 _log.error("type %r not allowed for now", typ)
126 return False
127
128 _log.info("addChunk for %r, type %r, position %d, len: %d",
129 o_sum, typ, pos, len(data))
130 if typ == "thumb":
131 _log.info("addChunk: Ignoring thumb, because we create our own")
132 return True
133
134 return True
135
136
137 def possibly_add_cookie(request, response):
138 # TODO: We should only add a *real* cookie, if
139 # authenticated. And if there is no cookie already.
140 if True:
141 response.set_cookie(
142 'pwg_id',
143 "some_fake_for_now",
144 path=request.environ['SCRIPT_NAME'],
145 domain=mg_globals.app_config.get('csrf_cookie_domain'),
146 secure=(request.scheme.lower() == 'https'),
147 httponly=True)
148
149
150 @csrf_exempt
151 def ws_php(request):
152 if request.method not in ("GET", "POST"):
153 _log.error("Method %r not supported", request.method)
154 raise MethodNotAllowed()
155
156 func = CmdTable.find_func(request)
157 if not func:
158 _log.warn("wsphp: Unhandled %s %r %r", request.method,
159 request.args, request.form)
160 return render_404(request)
161
162 result = func(request)
163
164 if isinstance(result, BaseResponse):
165 return result
166
167 response = response_xml(result)
168
169 possibly_add_cookie(request, response)
170
171 return response