]> git.ozlabs.org Git - patchwork/blob - apps/patchwork/views/xmlrpc.py
xmlrpc: add 'archived' status to patch summary
[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.body)
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          'archived'     : obj.archived,
202          'submitter'    : unicode(obj.submitter).encode("utf-8"),
203          'submitter_id' : obj.submitter_id,
204          'delegate'     : unicode(obj.delegate).encode("utf-8"),
205          'delegate_id'  : max(obj.delegate_id, 0),
206          'commit_ref'   : max(obj.commit_ref, ''),
207         }
208
209 def bundle_to_dict(obj):
210     """Return a trimmed down dictionary representation of a Bundle
211     object which is OK to send to the client."""
212     return \
213         {
214          'id'           : obj.id,
215          'name'         : obj.name,
216          'n_patches'    : obj.n_patches(),
217          'public_url'   : obj.public_url(),
218         }
219
220 def state_to_dict(obj):
221     """Return a trimmed down dictionary representation of a State
222     object which is OK to send to the client."""
223     return \
224         {
225          'id'           : obj.id,
226          'name'         : obj.name,
227         }
228
229 #######################################################################
230 # Public XML-RPC methods
231 #######################################################################
232
233 @xmlrpc_method(False)
234 def pw_rpc_version():
235     """Return Patchwork XML-RPC interface version."""
236     return 1
237
238 @xmlrpc_method(False)
239 def project_list(search_str="", max_count=0):
240     """Get a list of projects matching the given filters."""
241     try:
242         if len(search_str) > 0:
243             projects = Project.objects.filter(linkname__icontains = search_str)
244         else:
245             projects = Project.objects.all()
246
247         if max_count > 0:
248             return map(project_to_dict, projects)[:max_count]
249         else:
250             return map(project_to_dict, projects)
251     except:
252         return []
253
254 @xmlrpc_method(False)
255 def project_get(project_id):
256     """Return structure for the given project ID."""
257     try:
258         project = Project.objects.filter(id = project_id)[0]
259         return project_to_dict(project)
260     except:
261         return {}
262
263 @xmlrpc_method(False)
264 def person_list(search_str="", max_count=0):
265     """Get a list of Person objects matching the given filters."""
266     try:
267         if len(search_str) > 0:
268             people = (Person.objects.filter(name__icontains = search_str) |
269                 Person.objects.filter(email__icontains = search_str))
270         else:
271             people = Person.objects.all()
272
273         if max_count > 0:
274             return map(person_to_dict, people)[:max_count]
275         else:
276             return map(person_to_dict, people)
277
278     except:
279         return []
280
281 @xmlrpc_method(False)
282 def person_get(person_id):
283     """Return structure for the given person ID."""
284     try:
285         person = Person.objects.filter(id = person_id)[0]
286         return person_to_dict(person)
287     except:
288         return {}
289
290 @xmlrpc_method(False)
291 def patch_list(filter={}):
292     """Get a list of patches matching the given filters."""
293     try:
294         # We allow access to many of the fields.  But, some fields are
295         # filtered by raw object so we must lookup by ID instead over
296         # XML-RPC.
297         ok_fields = [
298             "id",
299             "name",
300             "project_id",
301             "submitter_id",
302             "delegate_id",
303             "state_id",
304             "date",
305             "commit_ref",
306             "hash",
307             "msgid",
308             "max_count",
309             ]
310
311         dfilter = {}
312         max_count = 0
313
314         for key in filter:
315             parts = key.split("__")
316             if parts[0] not in ok_fields:
317                 # Invalid field given
318                 return []
319             if len(parts) > 1:
320                 if LOOKUP_TYPES.count(parts[1]) == 0:
321                     # Invalid lookup type given
322                     return []
323
324             if parts[0] == 'project_id':
325                 dfilter['project'] = Project.objects.filter(id =
326                                         filter[key])[0]
327             elif parts[0] == 'submitter_id':
328                 dfilter['submitter'] = Person.objects.filter(id =
329                                         filter[key])[0]
330             elif parts[0] == 'delegate_id':
331                 dfilter['delegate'] = Person.objects.filter(id =
332                                         filter[key])[0]
333             elif parts[0] == 'state_id':
334                 dfilter['state'] = State.objects.filter(id =
335                                         filter[key])[0]
336             elif parts[0] == 'max_count':
337                 max_count = filter[key]
338             else:
339                 dfilter[key] = filter[key]
340
341         patches = Patch.objects.filter(**dfilter)
342
343         if max_count > 0:
344             return map(patch_to_dict, patches[:max_count])
345         else:
346             return map(patch_to_dict, patches)
347
348     except:
349         return []
350
351 @xmlrpc_method(False)
352 def patch_get(patch_id):
353     """Return structure for the given patch ID."""
354     try:
355         patch = Patch.objects.filter(id = patch_id)[0]
356         return patch_to_dict(patch)
357     except:
358         return {}
359
360 @xmlrpc_method(False)
361 def patch_get_by_hash(hash):
362     """Return structure for the given patch hash."""
363     try:
364         patch = Patch.objects.filter(hash = hash)[0]
365         return patch_to_dict(patch)
366     except:
367         return {}
368
369 @xmlrpc_method(False)
370 def patch_get_by_project_hash(project, hash):
371     """Return structure for the given patch hash."""
372     try:
373         patch = Patch.objects.filter(project__linkname = project,
374                                      hash = hash)[0]
375         return patch_to_dict(patch)
376     except:
377         return {}
378
379 @xmlrpc_method(False)
380 def patch_get_mbox(patch_id):
381     """Return mbox string for the given patch ID."""
382     try:
383         patch = Patch.objects.filter(id = patch_id)[0]
384         return patch_to_mbox(patch).as_string()
385     except:
386         return ""
387
388 @xmlrpc_method(False)
389 def patch_get_diff(patch_id):
390     """Return diff for the given patch ID."""
391     try:
392         patch = Patch.objects.filter(id = patch_id)[0]
393         return patch.content
394     except:
395         return ""
396
397 @xmlrpc_method(True)
398 def patch_set(user, patch_id, params):
399     """Update a patch with the key,value pairs in params. Only some parameters
400        can be set"""
401     try:
402         ok_params = ['state', 'commit_ref', 'archived']
403
404         patch = Patch.objects.get(id = patch_id)
405
406         if not patch.is_editable(user):
407             raise Exception('No permissions to edit this patch')
408
409         for (k, v) in params.iteritems():
410             if k not in ok_params:
411                 continue
412
413             if k == 'state':
414                 patch.state = State.objects.get(id = v)
415
416             else:
417                 setattr(patch, k, v)
418
419         patch.save()
420
421         return True
422
423     except:
424         raise
425
426 @xmlrpc_method(False)
427 def state_list(search_str="", max_count=0):
428     """Get a list of state structures matching the given search string."""
429     try:
430         if len(search_str) > 0:
431             states = State.objects.filter(name__icontains = search_str)
432         else:
433             states = State.objects.all()
434
435         if max_count > 0:
436             return map(state_to_dict, states)[:max_count]
437         else:
438             return map(state_to_dict, states)
439     except:
440         return []
441
442 @xmlrpc_method(False)
443 def state_get(state_id):
444     """Return structure for the given state ID."""
445     try:
446         state = State.objects.filter(id = state_id)[0]
447         return state_to_dict(state)
448     except:
449         return {}