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):
39 SimpleXMLRPCDispatcher.__init__(self, allow_none=False,
42 def _dumps(obj, *args, **kwargs):
43 kwargs['allow_none'] = self.allow_none
44 kwargs['encoding'] = self.encoding
45 return xmlrpclib.dumps(obj, *args, **kwargs)
49 # map of name => (auth, func)
52 def register_function(self, fn, auth_required):
53 self.func_map[fn.__name__] = (auth_required, fn)
56 def _user_for_request(self, request):
59 if 'HTTP_AUTHORIZATION' in request.META:
60 auth_header = request.META.get('HTTP_AUTHORIZATION')
61 elif 'Authorization' in request.META:
62 auth_header = request.META.get('Authorization')
64 if auth_header is None or auth_header == '':
65 raise Exception("No authentication credentials given")
67 str = auth_header.strip()
69 if not str.startswith('Basic '):
70 raise Exception("Authentication scheme not supported")
72 str = str[len('Basic '):].strip()
75 decoded = base64.decodestring(str)
76 username, password = decoded.split(':', 1)
78 raise Exception("Invalid authentication credentials")
80 return authenticate(username = username, password = password)
83 def _dispatch(self, request, method, params):
84 if method not in self.func_map.keys():
85 raise Exception('method "%s" is not supported' % method)
87 auth_required, fn = self.func_map[method]
90 user = self._user_for_request(request)
92 raise Exception("Invalid username/password")
94 params = (user,) + params
98 def _marshaled_dispatch(self, request):
100 params, method = xmlrpclib.loads(request.body)
102 response = self._dispatch(request, method, params)
103 # wrap response in a singleton tuple
104 response = (response,)
105 response = self.dumps(response, methodresponse=1)
106 except xmlrpclib.Fault, fault:
107 response = self.dumps(fault)
109 # report exception back to server
110 response = self.dumps(
111 xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)),
116 dispatcher = PatchworkXMLRPCDispatcher()
118 # XMLRPC view function
121 if request.method != 'POST':
122 return HttpResponseRedirect(
123 urlresolvers.reverse('patchwork.views.help',
124 kwargs = {'path': 'pwclient/'}))
126 response = HttpResponse()
128 ret = dispatcher._marshaled_dispatch(request)
131 return HttpResponseServerError()
135 # decorator for XMLRPC methods. Setting login_required to true will call
136 # the decorated function with a non-optional user as the first argument.
137 def xmlrpc_method(login_required = False):
139 dispatcher.register_function(f, login_required)
146 # We allow most of the Django field lookup types for remote queries
147 LOOKUP_TYPES = ["iexact", "contains", "icontains", "gt", "gte", "lt",
148 "in", "startswith", "istartswith", "endswith",
149 "iendswith", "range", "year", "month", "day", "isnull" ]
151 #######################################################################
153 #######################################################################
155 def project_to_dict(obj):
156 """Return a trimmed down dictionary representation of a Project
157 object which is OK to send to the client."""
161 'linkname' : obj.linkname,
165 def person_to_dict(obj):
166 """Return a trimmed down dictionary representation of a Person
167 object which is OK to send to the client."""
169 # Make sure we don't return None even if the user submitted a patch
170 # with no real name. XMLRPC can't marshall None.
171 if obj.name is not None:
181 'user' : unicode(obj.user).encode("utf-8"),
184 def patch_to_dict(obj):
185 """Return a trimmed down dictionary representation of a Patch
186 object which is OK to send to the client."""
190 'date' : unicode(obj.date).encode("utf-8"),
191 'filename' : obj.filename(),
194 'project' : unicode(obj.project).encode("utf-8"),
195 'project_id' : obj.project_id,
196 'state' : unicode(obj.state).encode("utf-8"),
197 'state_id' : obj.state_id,
198 'archived' : obj.archived,
199 'submitter' : unicode(obj.submitter).encode("utf-8"),
200 'submitter_id' : obj.submitter_id,
201 'delegate' : unicode(obj.delegate).encode("utf-8"),
202 'delegate_id' : max(obj.delegate_id, 0),
203 'commit_ref' : max(obj.commit_ref, ''),
206 def bundle_to_dict(obj):
207 """Return a trimmed down dictionary representation of a Bundle
208 object which is OK to send to the client."""
213 'n_patches' : obj.n_patches(),
214 'public_url' : obj.public_url(),
217 def state_to_dict(obj):
218 """Return a trimmed down dictionary representation of a State
219 object which is OK to send to the client."""
226 #######################################################################
227 # Public XML-RPC methods
228 #######################################################################
230 @xmlrpc_method(False)
231 def pw_rpc_version():
232 """Return Patchwork XML-RPC interface version."""
235 @xmlrpc_method(False)
236 def project_list(search_str="", max_count=0):
237 """Get a list of projects matching the given filters."""
239 if len(search_str) > 0:
240 projects = Project.objects.filter(linkname__icontains = search_str)
242 projects = Project.objects.all()
245 return map(project_to_dict, projects)[:max_count]
247 return map(project_to_dict, projects)
251 @xmlrpc_method(False)
252 def project_get(project_id):
253 """Return structure for the given project ID."""
255 project = Project.objects.filter(id = project_id)[0]
256 return project_to_dict(project)
260 @xmlrpc_method(False)
261 def person_list(search_str="", max_count=0):
262 """Get a list of Person objects matching the given filters."""
264 if len(search_str) > 0:
265 people = (Person.objects.filter(name__icontains = search_str) |
266 Person.objects.filter(email__icontains = search_str))
268 people = Person.objects.all()
271 return map(person_to_dict, people)[:max_count]
273 return map(person_to_dict, people)
278 @xmlrpc_method(False)
279 def person_get(person_id):
280 """Return structure for the given person ID."""
282 person = Person.objects.filter(id = person_id)[0]
283 return person_to_dict(person)
287 @xmlrpc_method(False)
288 def patch_list(filter={}):
289 """Get a list of patches matching the given filters."""
291 # We allow access to many of the fields. But, some fields are
292 # filtered by raw object so we must lookup by ID instead over
313 parts = key.split("__")
314 if parts[0] not in ok_fields:
315 # Invalid field given
318 if LOOKUP_TYPES.count(parts[1]) == 0:
319 # Invalid lookup type given
322 if parts[0] == 'project_id':
323 dfilter['project'] = Project.objects.filter(id =
325 elif parts[0] == 'submitter_id':
326 dfilter['submitter'] = Person.objects.filter(id =
328 elif parts[0] == 'delegate_id':
329 dfilter['delegate'] = Person.objects.filter(id =
331 elif parts[0] == 'state_id':
332 dfilter['state'] = State.objects.filter(id =
334 elif parts[0] == 'max_count':
335 max_count = filter[key]
337 dfilter[key] = filter[key]
339 patches = Patch.objects.filter(**dfilter)
342 return map(patch_to_dict, patches[:max_count])
344 return map(patch_to_dict, patches)
349 @xmlrpc_method(False)
350 def patch_get(patch_id):
351 """Return structure for the given patch ID."""
353 patch = Patch.objects.filter(id = patch_id)[0]
354 return patch_to_dict(patch)
358 @xmlrpc_method(False)
359 def patch_get_by_hash(hash):
360 """Return structure for the given patch hash."""
362 patch = Patch.objects.filter(hash = hash)[0]
363 return patch_to_dict(patch)
367 @xmlrpc_method(False)
368 def patch_get_by_project_hash(project, hash):
369 """Return structure for the given patch hash."""
371 patch = Patch.objects.filter(project__linkname = project,
373 return patch_to_dict(patch)
377 @xmlrpc_method(False)
378 def patch_get_mbox(patch_id):
379 """Return mbox string for the given patch ID."""
381 patch = Patch.objects.filter(id = patch_id)[0]
382 return patch_to_mbox(patch).as_string(True)
386 @xmlrpc_method(False)
387 def patch_get_diff(patch_id):
388 """Return diff for the given patch ID."""
390 patch = Patch.objects.filter(id = patch_id)[0]
396 def patch_set(user, patch_id, params):
397 """Update a patch with the key,value pairs in params. Only some parameters
400 ok_params = ['state', 'commit_ref', 'archived']
402 patch = Patch.objects.get(id = patch_id)
404 if not patch.is_editable(user):
405 raise Exception('No permissions to edit this patch')
407 for (k, v) in params.iteritems():
408 if k not in ok_params:
412 patch.state = State.objects.get(id = v)
424 @xmlrpc_method(False)
425 def state_list(search_str="", max_count=0):
426 """Get a list of state structures matching the given search string."""
428 if len(search_str) > 0:
429 states = State.objects.filter(name__icontains = search_str)
431 states = State.objects.all()
434 return map(state_to_dict, states)[:max_count]
436 return map(state_to_dict, states)
440 @xmlrpc_method(False)
441 def state_get(state_id):
442 """Return structure for the given state ID."""
444 state = State.objects.filter(id = state_id)[0]
445 return state_to_dict(state)