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