]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/views/xmlrpc.py
views: Move mbox handling from models to views
[patchwork] / apps / patchwork / views / xmlrpc.py
1 # Patchwork - automated patch tracking system
2 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
3 #
4 # This file is part of the Patchwork package.
5 #
6 # Patchwork is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # Patchwork is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Patchwork; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 #
20 # Patchwork XMLRPC interface
21 #
22
23 from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
24 from django.http import HttpResponse, HttpResponseRedirect, \
25      HttpResponseServerError
26 from django.core import urlresolvers
27 from django.contrib.auth import authenticate
28 from patchwork.models import Patch, Project, Person, State
29 from patchwork.views import patch_to_mbox
30 from django.views.decorators.csrf import csrf_exempt
31
32 import sys
33 import base64
34 import xmlrpclib
35
36 class PatchworkXMLRPCDispatcher(SimpleXMLRPCDispatcher):
37     def __init__(self):
38         if sys.version_info[:3] >= (2,5,):
39             SimpleXMLRPCDispatcher.__init__(self, allow_none=False,
40                     encoding=None)
41             def _dumps(obj, *args, **kwargs):
42                 kwargs['allow_none'] = self.allow_none
43                 kwargs['encoding'] = self.encoding
44                 return xmlrpclib.dumps(obj, *args, **kwargs)
45         else:
46             def _dumps(obj, *args, **kwargs):
47                 return xmlrpclib.dumps(obj, *args, **kwargs)
48             SimpleXMLRPCDispatcher.__init__(self)
49
50         self.dumps = _dumps
51
52         # map of name => (auth, func)
53         self.func_map = {}
54
55     def register_function(self, fn, auth_required):
56         self.func_map[fn.__name__] = (auth_required, fn)
57
58
59     def _user_for_request(self, request):
60         auth_header = None
61
62         if 'HTTP_AUTHORIZATION' in request.META:
63             auth_header = request.META.get('HTTP_AUTHORIZATION')
64         elif 'Authorization' in request.META:
65             auth_header = request.META.get('Authorization')
66
67         if auth_header is None or auth_header == '':
68             raise Exception("No authentication credentials given")
69
70         str = auth_header.strip()
71
72         if not str.startswith('Basic '):
73             raise Exception("Authentication scheme not supported")
74
75         str = str[len('Basic '):].strip()
76
77         try:
78             decoded = base64.decodestring(str)
79             username, password = decoded.split(':', 1)
80         except:
81             raise Exception("Invalid authentication credentials")
82
83         return authenticate(username = username, password = password)
84
85
86     def _dispatch(self, request, method, params):
87         if method not in self.func_map.keys():
88             raise Exception('method "%s" is not supported' % method)
89
90         auth_required, fn = self.func_map[method]
91
92         if auth_required:
93             user = self._user_for_request(request)
94             if not user:
95                 raise Exception("Invalid username/password")
96
97             params = (user,) + params
98
99         return fn(*params)
100
101     def _marshaled_dispatch(self, request):
102         try:
103             params, method = xmlrpclib.loads(request.raw_post_data)
104
105             response = self._dispatch(request, method, params)
106             # wrap response in a singleton tuple
107             response = (response,)
108             response = self.dumps(response, methodresponse=1)
109         except xmlrpclib.Fault, fault:
110             response = self.dumps(fault)
111         except:
112             # report exception back to server
113             response = self.dumps(
114                 xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)),
115                 )
116
117         return response
118
119 dispatcher = PatchworkXMLRPCDispatcher()
120
121 # XMLRPC view function
122 @csrf_exempt
123 def xmlrpc(request):
124     if request.method != 'POST':
125         return HttpResponseRedirect(
126                 urlresolvers.reverse('patchwork.views.help',
127                     kwargs = {'path': 'pwclient/'}))
128
129     response = HttpResponse()
130     try:
131         ret = dispatcher._marshaled_dispatch(request)
132         response.write(ret)
133     except Exception:
134         return HttpResponseServerError()
135
136     return response
137
138 # decorator for XMLRPC methods. Setting login_required to true will call
139 # the decorated function with a non-optional user as the first argument.
140 def xmlrpc_method(login_required = False):
141     def wrap(f):
142         dispatcher.register_function(f, login_required)
143         return f
144
145     return wrap
146
147
148
149 # We allow most of the Django field lookup types for remote queries
150 LOOKUP_TYPES = ["iexact", "contains", "icontains", "gt", "gte", "lt",
151                 "in", "startswith", "istartswith", "endswith",
152                 "iendswith", "range", "year", "month", "day", "isnull" ]
153
154 #######################################################################
155 # Helper functions
156 #######################################################################
157
158 def project_to_dict(obj):
159     """Return a trimmed down dictionary representation of a Project
160     object which is OK to send to the client."""
161     return \
162         {
163          'id'           : obj.id,
164          'linkname'     : obj.linkname,
165          'name'         : obj.name,
166         }
167
168 def person_to_dict(obj):
169     """Return a trimmed down dictionary representation of a Person
170     object which is OK to send to the client."""
171
172     # Make sure we don't return None even if the user submitted a patch
173     # with no real name.  XMLRPC can't marshall None.
174     if obj.name is not None:
175         name = obj.name
176     else:
177         name = obj.email
178
179     return \
180         {
181          'id'           : obj.id,
182          'email'        : obj.email,
183          'name'         : name,
184          'user'         : unicode(obj.user).encode("utf-8"),
185         }
186
187 def patch_to_dict(obj):
188     """Return a trimmed down dictionary representation of a Patch
189     object which is OK to send to the client."""
190     return \
191         {
192          'id'           : obj.id,
193          'date'         : unicode(obj.date).encode("utf-8"),
194          'filename'     : obj.filename(),
195          'msgid'        : obj.msgid,
196          'name'         : obj.name,
197          'project'      : unicode(obj.project).encode("utf-8"),
198          'project_id'   : obj.project_id,
199          'state'        : unicode(obj.state).encode("utf-8"),
200          'state_id'     : obj.state_id,
201          'submitter'    : unicode(obj.submitter).encode("utf-8"),
202          'submitter_id' : obj.submitter_id,
203          'delegate'     : unicode(obj.delegate).encode("utf-8"),
204          'delegate_id'  : max(obj.delegate_id, 0),
205          'commit_ref'   : max(obj.commit_ref, ''),
206         }
207
208 def bundle_to_dict(obj):
209     """Return a trimmed down dictionary representation of a Bundle
210     object which is OK to send to the client."""
211     return \
212         {
213          'id'           : obj.id,
214          'name'         : obj.name,
215          'n_patches'    : obj.n_patches(),
216          'public_url'   : obj.public_url(),
217         }
218
219 def state_to_dict(obj):
220     """Return a trimmed down dictionary representation of a State
221     object which is OK to send to the client."""
222     return \
223         {
224          'id'           : obj.id,
225          'name'         : obj.name,
226         }
227
228 #######################################################################
229 # Public XML-RPC methods
230 #######################################################################
231
232 @xmlrpc_method(False)
233 def pw_rpc_version():
234     """Return Patchwork XML-RPC interface version."""
235     return 1
236
237 @xmlrpc_method(False)
238 def project_list(search_str="", max_count=0):
239     """Get a list of projects matching the given filters."""
240     try:
241         if len(search_str) > 0:
242             projects = Project.objects.filter(linkname__icontains = search_str)
243         else:
244             projects = Project.objects.all()
245
246         if max_count > 0:
247             return map(project_to_dict, projects)[:max_count]
248         else:
249             return map(project_to_dict, projects)
250     except:
251         return []
252
253 @xmlrpc_method(False)
254 def project_get(project_id):
255     """Return structure for the given project ID."""
256     try:
257         project = Project.objects.filter(id = project_id)[0]
258         return project_to_dict(project)
259     except:
260         return {}
261
262 @xmlrpc_method(False)
263 def person_list(search_str="", max_count=0):
264     """Get a list of Person objects matching the given filters."""
265     try:
266         if len(search_str) > 0:
267             people = (Person.objects.filter(name__icontains = search_str) |
268                 Person.objects.filter(email__icontains = search_str))
269         else:
270             people = Person.objects.all()
271
272         if max_count > 0:
273             return map(person_to_dict, people)[:max_count]
274         else:
275             return map(person_to_dict, people)
276
277     except:
278         return []
279
280 @xmlrpc_method(False)
281 def person_get(person_id):
282     """Return structure for the given person ID."""
283     try:
284         person = Person.objects.filter(id = person_id)[0]
285         return person_to_dict(person)
286     except:
287         return {}
288
289 @xmlrpc_method(False)
290 def patch_list(filter={}):
291     """Get a list of patches matching the given filters."""
292     try:
293         # We allow access to many of the fields.  But, some fields are
294         # filtered by raw object so we must lookup by ID instead over
295         # XML-RPC.
296         ok_fields = [
297             "id",
298             "name",
299             "project_id",
300             "submitter_id",
301             "delegate_id",
302             "state_id",
303             "date",
304             "commit_ref",
305             "hash",
306             "msgid",
307             "max_count",
308             ]
309
310         dfilter = {}
311         max_count = 0
312
313         for key in filter:
314             parts = key.split("__")
315             if parts[0] not in ok_fields:
316                 # Invalid field given
317                 return []
318             if len(parts) > 1:
319                 if LOOKUP_TYPES.count(parts[1]) == 0:
320                     # Invalid lookup type given
321                     return []
322
323             if parts[0] == 'project_id':
324                 dfilter['project'] = Project.objects.filter(id =
325                                         filter[key])[0]
326             elif parts[0] == 'submitter_id':
327                 dfilter['submitter'] = Person.objects.filter(id =
328                                         filter[key])[0]
329             elif parts[0] == 'state_id':
330                 dfilter['state'] = State.objects.filter(id =
331                                         filter[key])[0]
332             elif parts[0] == 'max_count':
333                 max_count = filter[key]
334             else:
335                 dfilter[key] = filter[key]
336
337         patches = Patch.objects.filter(**dfilter)
338
339         if max_count > 0:
340             return map(patch_to_dict, patches[:max_count])
341         else:
342             return map(patch_to_dict, patches)
343
344     except:
345         return []
346
347 @xmlrpc_method(False)
348 def patch_get(patch_id):
349     """Return structure for the given patch ID."""
350     try:
351         patch = Patch.objects.filter(id = patch_id)[0]
352         return patch_to_dict(patch)
353     except:
354         return {}
355
356 @xmlrpc_method(False)
357 def patch_get_by_hash(hash):
358     """Return structure for the given patch hash."""
359     try:
360         patch = Patch.objects.filter(hash = hash)[0]
361         return patch_to_dict(patch)
362     except:
363         return {}
364
365 @xmlrpc_method(False)
366 def patch_get_by_project_hash(project, hash):
367     """Return structure for the given patch hash."""
368     try:
369         patch = Patch.objects.filter(project__linkname = project,
370                                      hash = hash)[0]
371         return patch_to_dict(patch)
372     except:
373         return {}
374
375 @xmlrpc_method(False)
376 def patch_get_mbox(patch_id):
377     """Return mbox string for the given patch ID."""
378     try:
379         patch = Patch.objects.filter(id = patch_id)[0]
380         return patch_to_mbox(patch).as_string()
381     except:
382         return ""
383
384 @xmlrpc_method(False)
385 def patch_get_diff(patch_id):
386     """Return diff for the given patch ID."""
387     try:
388         patch = Patch.objects.filter(id = patch_id)[0]
389         return patch.content
390     except:
391         return ""
392
393 @xmlrpc_method(True)
394 def patch_set(user, patch_id, params):
395     """Update a patch with the key,value pairs in params. Only some parameters
396        can be set"""
397     try:
398         ok_params = ['state', 'commit_ref', 'archived']
399
400         patch = Patch.objects.get(id = patch_id)
401
402         if not patch.is_editable(user):
403             raise Exception('No permissions to edit this patch')
404
405         for (k, v) in params.iteritems():
406             if k not in ok_params:
407                 continue
408
409             if k == 'state':
410                 patch.state = State.objects.get(id = v)
411
412             else:
413                 setattr(patch, k, v)
414
415         patch.save()
416
417         return True
418
419     except:
420         raise
421
422 @xmlrpc_method(False)
423 def state_list(search_str="", max_count=0):
424     """Get a list of state structures matching the given search string."""
425     try:
426         if len(search_str) > 0:
427             states = State.objects.filter(name__icontains = search_str)
428         else:
429             states = State.objects.all()
430
431         if max_count > 0:
432             return map(state_to_dict, states)[:max_count]
433         else:
434             return map(state_to_dict, states)
435     except:
436         return []
437
438 @xmlrpc_method(False)
439 def state_get(state_id):
440     """Return structure for the given state ID."""
441     try:
442         state = State.objects.filter(id = state_id)[0]
443         return state_to_dict(state)
444     except:
445         return {}