Forked mumble-django project from https://bitbucket.org/Svedrin/mumble-django
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

334 lines
12 KiB

  1. # -*- coding: utf-8 -*-
  2. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright (C) 2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  5. *
  6. * djExtDirect 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. * This package 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. import simplejson
  17. import inspect
  18. import functools
  19. import traceback
  20. from sys import stderr
  21. from django.http import HttpResponse
  22. from django.conf import settings
  23. from django.conf.urls.defaults import patterns
  24. from django.core.urlresolvers import reverse
  25. from django.utils.datastructures import MultiValueDictKeyError
  26. from django.views.decorators.csrf import csrf_exempt
  27. def getname( cls_or_name ):
  28. """ If cls_or_name is not a string, return its __name__. """
  29. if type(cls_or_name) not in ( str, unicode ):
  30. return cls_or_name.__name__
  31. return cls_or_name
  32. class Provider( object ):
  33. """ Provider for Ext.Direct. This class handles building API information and
  34. routing requests to the appropriate functions, and serializing their
  35. response and exceptions - if any.
  36. Instantiation:
  37. >>> EXT_JS_PROVIDER = Provider( [name="Ext.app.REMOTING_API", autoadd=True] )
  38. If autoadd is True, the api.js will include a line like such::
  39. Ext.Direct.addProvider( Ext.app.REMOTING_API );
  40. After instantiating the Provider, register functions to it like so:
  41. >>> @EXT_JS_PROVIDER.register_method("myclass")
  42. ... def myview( request, possibly, some, other, arguments ):
  43. ... " does something with all those args and returns something "
  44. ... return 13.37
  45. Note that those views **MUST NOT** return an HttpResponse but simply
  46. the plain result, as the Provider will build a response from whatever
  47. your view returns!
  48. To be able to access the Provider, include its URLs in an arbitrary
  49. URL pattern, like so:
  50. >>> from views import EXT_JS_PROVIDER # import our provider instance
  51. >>> urlpatterns = patterns(
  52. ... # other patterns go here
  53. ... ( r'api/', include(EXT_DIRECT_PROVIDER.urls) ),
  54. ... )
  55. This way, the Provider will define the URLs "api/api.js" and "api/router".
  56. If you then access the "api/api.js" URL, you will get a response such as::
  57. Ext.app.REMOTING_API = { # Ext.app.REMOTING_API is from Provider.name
  58. "url": "/mumble/api/router",
  59. "type": "remoting",
  60. "actions": {"myclass": [{"name": "myview", "len": 4}]}
  61. }
  62. You can then use this code in ExtJS to define the Provider there.
  63. """
  64. def __init__( self, name="Ext.app.REMOTING_API", autoadd=True ):
  65. self.name = name
  66. self.autoadd = autoadd
  67. self.classes = {}
  68. def register_method( self, cls_or_name, flags=None ):
  69. """ Return a function that takes a method as an argument and adds that
  70. to cls_or_name.
  71. The flags parameter is for additional information, e.g. formHandler=True.
  72. Note: This decorator does not replace the method by a new function,
  73. it returns the original function as-is.
  74. """
  75. return functools.partial( self._register_method, cls_or_name, flags=flags )
  76. def _register_method( self, cls_or_name, method, flags=None ):
  77. """ Actually registers the given function as a method of cls_or_name. """
  78. clsname = getname(cls_or_name)
  79. if clsname not in self.classes:
  80. self.classes[clsname] = {}
  81. if flags is None:
  82. flags = {}
  83. self.classes[ clsname ][ method.__name__ ] = method
  84. method.EXT_argnames = inspect.getargspec( method ).args[1:]
  85. method.EXT_len = len( method.EXT_argnames )
  86. method.EXT_flags = flags
  87. return method
  88. @csrf_exempt
  89. def get_api( self, request ):
  90. """ Introspect the methods and get a JSON description of this API. """
  91. actdict = {}
  92. for clsname in self.classes:
  93. actdict[clsname] = []
  94. for methodname in self.classes[clsname]:
  95. methinfo = {
  96. "name": methodname,
  97. "len": self.classes[clsname][methodname].EXT_len
  98. }
  99. methinfo.update( self.classes[clsname][methodname].EXT_flags )
  100. actdict[clsname].append( methinfo )
  101. lines = ["%s = %s;" % ( self.name, simplejson.dumps({
  102. "url": reverse( self.request ),
  103. "type": "remoting",
  104. "actions": actdict
  105. }))]
  106. if self.autoadd:
  107. lines.append( "Ext.Direct.addProvider( %s );" % self.name )
  108. return HttpResponse( "\n".join( lines ), mimetype="text/javascript" )
  109. @csrf_exempt
  110. def request( self, request ):
  111. """ Implements the Router part of the Ext.Direct specification.
  112. It handles decoding requests, calling the appropriate function (if
  113. found) and encoding the response / exceptions.
  114. """
  115. # First try to use request.POST, if that doesn't work check for req.raw_post_data.
  116. # The other way round this might make more sense because the case that uses
  117. # raw_post_data is way more common, but accessing request.POST after raw_post_data
  118. # causes issues with Django's test client while accessing raw_post_data after
  119. # request.POST does not.
  120. try:
  121. jsoninfo = {
  122. 'action': request.POST['extAction'],
  123. 'method': request.POST['extMethod'],
  124. 'type': request.POST['extType'],
  125. 'upload': request.POST['extUpload'],
  126. 'tid': request.POST['extTID'],
  127. }
  128. except (MultiValueDictKeyError, KeyError), err:
  129. try:
  130. rawjson = simplejson.loads( request.raw_post_data )
  131. except simplejson.JSONDecodeError:
  132. return HttpResponse( simplejson.dumps({
  133. 'type': 'exception',
  134. 'message': 'malformed request',
  135. 'where': unicode(err),
  136. "tid": None, # dunno
  137. }), mimetype="text/javascript" )
  138. else:
  139. return self.process_normal_request( request, rawjson )
  140. else:
  141. return self.process_form_request( request, jsoninfo )
  142. def process_normal_request( self, request, rawjson ):
  143. """ Process standard requests (no form submission or file uploads). """
  144. if not isinstance( rawjson, list ):
  145. rawjson = [rawjson]
  146. responses = []
  147. for reqinfo in rawjson:
  148. cls, methname, data, rtype, tid = (reqinfo['action'],
  149. reqinfo['method'],
  150. reqinfo['data'],
  151. reqinfo['type'],
  152. reqinfo['tid'])
  153. if cls not in self.classes:
  154. responses.append({
  155. 'type': 'exception',
  156. 'message': 'no such action',
  157. 'where': cls,
  158. "tid": tid,
  159. })
  160. continue
  161. if methname not in self.classes[cls]:
  162. responses.append({
  163. 'type': 'exception',
  164. 'message': 'no such method',
  165. 'where': methname,
  166. "tid": tid,
  167. })
  168. continue
  169. func = self.classes[cls][methname]
  170. if func.EXT_len and len(data) == 1 and type(data[0]) == dict:
  171. # data[0] seems to contain a dict with params. check if it does, and if so, unpack
  172. args = []
  173. for argname in func.EXT_argnames:
  174. if argname in data[0]:
  175. args.append( data[0][argname] )
  176. else:
  177. args = None
  178. break
  179. if args:
  180. data = args
  181. if data is not None:
  182. datalen = len(data)
  183. else:
  184. datalen = 0
  185. if datalen != len(func.EXT_argnames):
  186. responses.append({
  187. 'type': 'exception',
  188. 'tid': tid,
  189. 'message': 'invalid arguments',
  190. 'where': 'Expected %d, got %d' % ( len(func.EXT_argnames), len(data) )
  191. })
  192. continue
  193. try:
  194. if data:
  195. result = func( request, *data )
  196. else:
  197. result = func( request )
  198. except Exception, err:
  199. errinfo = {
  200. 'type': 'exception',
  201. "tid": tid,
  202. }
  203. if settings.DEBUG:
  204. traceback.print_exc( file=stderr )
  205. errinfo['message'] = unicode(err)
  206. errinfo['where'] = traceback.format_exc()
  207. else:
  208. errinfo['message'] = 'The socket packet pocket has an error to report.'
  209. errinfo['where'] = ''
  210. responses.append(errinfo)
  211. else:
  212. responses.append({
  213. "type": rtype,
  214. "tid": tid,
  215. "action": cls,
  216. "method": methname,
  217. "result": result
  218. })
  219. if len(responses) == 1:
  220. return HttpResponse( simplejson.dumps( responses[0] ), mimetype="text/javascript" )
  221. else:
  222. return HttpResponse( simplejson.dumps( responses ), mimetype="text/javascript" )
  223. def process_form_request( self, request, reqinfo ):
  224. """ Router for POST requests that submit form data and/or file uploads. """
  225. cls, methname, rtype, tid = (reqinfo['action'],
  226. reqinfo['method'],
  227. reqinfo['type'],
  228. reqinfo['tid'])
  229. if cls not in self.classes:
  230. response = {
  231. 'type': 'exception',
  232. 'message': 'no such action',
  233. 'where': cls,
  234. "tid": tid,
  235. }
  236. elif methname not in self.classes[cls]:
  237. response = {
  238. 'type': 'exception',
  239. 'message': 'no such method',
  240. 'where': methname,
  241. "tid": tid,
  242. }
  243. else:
  244. func = self.classes[cls][methname]
  245. try:
  246. result = func( request )
  247. except Exception, err:
  248. errinfo = {
  249. 'type': 'exception',
  250. "tid": tid,
  251. }
  252. if settings.DEBUG:
  253. traceback.print_exc( file=stderr )
  254. errinfo['message'] = unicode(err)
  255. errinfo['where'] = traceback.format_exc()
  256. else:
  257. errinfo['message'] = 'The socket packet pocket has an error to report.'
  258. errinfo['where'] = ''
  259. response = errinfo
  260. else:
  261. response = {
  262. "type": rtype,
  263. "tid": tid,
  264. "action": cls,
  265. "method": methname,
  266. "result": result
  267. }
  268. if reqinfo['upload'] == "true":
  269. return HttpResponse(
  270. "<html><body><textarea>%s</textarea></body></html>" % simplejson.dumps(response),
  271. mimetype="text/javascript"
  272. )
  273. else:
  274. return HttpResponse( simplejson.dumps( response ), mimetype="text/javascript" )
  275. def get_urls(self):
  276. """ Return the URL patterns. """
  277. pat = patterns('',
  278. (r'api.js$', self.get_api ),
  279. (r'router/?', self.request ),
  280. )
  281. return pat
  282. urls = property(get_urls)