1 # Patchwork - automated patch tracking system
2 # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
4 # This file is part of the Patchwork package.
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.
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.
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
20 # Patchwork XMLRPC interface
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
36 class PatchworkXMLRPCDispatcher(SimpleXMLRPCDispatcher):
38 if sys.version_info[:3] >= (2,5,):
39 SimpleXMLRPCDispatcher.__init__(self, allow_none=False,
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)
46 def _dumps(obj, *args, **kwargs):
47 return xmlrpclib.dumps(obj, *args, **kwargs)
48 SimpleXMLRPCDispatcher.__init__(self)
52 # map of name => (auth, func)
55 def register_function(self, fn, auth_required):
56 self.func_map[fn.__name__] = (auth_required, fn)
59 def _user_for_request(self, request):
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')
67 if auth_header is None or auth_header == '':
68 raise Exception("No authentication credentials given")
70 str = auth_header.strip()
72 if not str.startswith('Basic '):
73 raise Exception("Authentication scheme not supported")
75 str = str[len('Basic '):].strip()
78 decoded = base64.decodestring(str)
79 username, password = decoded.split(':', 1)
81 raise Exception("Invalid authentication credentials")
83 return authenticate(username = username, password = password)
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)
90 auth_required, fn = self.func_map[method]
93 user = self._user_for_request(request)
95 raise Exception("Invalid username/password")
97 params = (user,) + params
101 def _marshaled_dispatch(self, request):
103 params, method = xmlrpclib.loads(request.body)
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)
112 # report exception back to server
113 response = self.dumps(
114 xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)),
119 dispatcher = PatchworkXMLRPCDispatcher()
121 # XMLRPC view function
124 if request.method != 'POST':
125 return HttpResponseRedirect(
126 urlresolvers.reverse('patchwork.views.help',
127 kwargs = {'path': 'pwclient/'}))
129 response = HttpResponse()
131 ret = dispatcher._marshaled_dispatch(request)
134 return HttpResponseServerError()
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):
142 dispatcher.register_function(f, login_required)
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" ]
154 #######################################################################
156 #######################################################################
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."""
164 'linkname' : obj.linkname,
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."""
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:
184 'user' : unicode(obj.user).encode("utf-8"),
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."""
193 'date' : unicode(obj.date).encode("utf-8"),
194 'filename' : obj.filename(),
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, ''),
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."""
216 'n_patches' : obj.n_patches(),
217 'public_url' : obj.public_url(),
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."""
229 #######################################################################
230 # Public XML-RPC methods
231 #######################################################################
233 @xmlrpc_method(False)
234 def pw_rpc_version():
235 """Return Patchwork XML-RPC interface version."""
238 @xmlrpc_method(False)
239 def project_list(search_str="", max_count=0):
240 """Get a list of projects matching the given filters."""
242 if len(search_str) > 0:
243 projects = Project.objects.filter(linkname__icontains = search_str)
245 projects = Project.objects.all()
248 return map(project_to_dict, projects)[:max_count]
250 return map(project_to_dict, projects)
254 @xmlrpc_method(False)
255 def project_get(project_id):
256 """Return structure for the given project ID."""
258 project = Project.objects.filter(id = project_id)[0]
259 return project_to_dict(project)
263 @xmlrpc_method(False)
264 def person_list(search_str="", max_count=0):
265 """Get a list of Person objects matching the given filters."""
267 if len(search_str) > 0:
268 people = (Person.objects.filter(name__icontains = search_str) |
269 Person.objects.filter(email__icontains = search_str))
271 people = Person.objects.all()
274 return map(person_to_dict, people)[:max_count]
276 return map(person_to_dict, people)
281 @xmlrpc_method(False)
282 def person_get(person_id):
283 """Return structure for the given person ID."""
285 person = Person.objects.filter(id = person_id)[0]
286 return person_to_dict(person)
290 @xmlrpc_method(False)
291 def patch_list(filter={}):
292 """Get a list of patches matching the given filters."""
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
315 parts = key.split("__")
316 if parts[0] not in ok_fields:
317 # Invalid field given
320 if LOOKUP_TYPES.count(parts[1]) == 0:
321 # Invalid lookup type given
324 if parts[0] == 'project_id':
325 dfilter['project'] = Project.objects.filter(id =
327 elif parts[0] == 'submitter_id':
328 dfilter['submitter'] = Person.objects.filter(id =
330 elif parts[0] == 'delegate_id':
331 dfilter['delegate'] = Person.objects.filter(id =
333 elif parts[0] == 'state_id':
334 dfilter['state'] = State.objects.filter(id =
336 elif parts[0] == 'max_count':
337 max_count = filter[key]
339 dfilter[key] = filter[key]
341 patches = Patch.objects.filter(**dfilter)
344 return map(patch_to_dict, patches[:max_count])
346 return map(patch_to_dict, patches)
351 @xmlrpc_method(False)
352 def patch_get(patch_id):
353 """Return structure for the given patch ID."""
355 patch = Patch.objects.filter(id = patch_id)[0]
356 return patch_to_dict(patch)
360 @xmlrpc_method(False)
361 def patch_get_by_hash(hash):
362 """Return structure for the given patch hash."""
364 patch = Patch.objects.filter(hash = hash)[0]
365 return patch_to_dict(patch)
369 @xmlrpc_method(False)
370 def patch_get_by_project_hash(project, hash):
371 """Return structure for the given patch hash."""
373 patch = Patch.objects.filter(project__linkname = project,
375 return patch_to_dict(patch)
379 @xmlrpc_method(False)
380 def patch_get_mbox(patch_id):
381 """Return mbox string for the given patch ID."""
383 patch = Patch.objects.filter(id = patch_id)[0]
384 return patch_to_mbox(patch).as_string(True)
388 @xmlrpc_method(False)
389 def patch_get_diff(patch_id):
390 """Return diff for the given patch ID."""
392 patch = Patch.objects.filter(id = patch_id)[0]
398 def patch_set(user, patch_id, params):
399 """Update a patch with the key,value pairs in params. Only some parameters
402 ok_params = ['state', 'commit_ref', 'archived']
404 patch = Patch.objects.get(id = patch_id)
406 if not patch.is_editable(user):
407 raise Exception('No permissions to edit this patch')
409 for (k, v) in params.iteritems():
410 if k not in ok_params:
414 patch.state = State.objects.get(id = v)
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."""
430 if len(search_str) > 0:
431 states = State.objects.filter(name__icontains = search_str)
433 states = State.objects.all()
436 return map(state_to_dict, states)[:max_count]
438 return map(state_to_dict, states)
442 @xmlrpc_method(False)
443 def state_get(state_id):
444 """Return structure for the given state ID."""
446 state = State.objects.filter(id = state_id)[0]
447 return state_to_dict(state)