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.

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