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.

356 lines
13 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 json
  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.core.serializers.json import DjangoJSONEncoder
  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 )[0][1:]
  85. method.EXT_len = len( method.EXT_argnames )
  86. method.EXT_flags = flags
  87. return method
  88. def build_api_dict( self ):
  89. actdict = {}
  90. for clsname in self.classes:
  91. actdict[clsname] = []
  92. for methodname in self.classes[clsname]:
  93. methinfo = {
  94. "name": methodname,
  95. "len": self.classes[clsname][methodname].EXT_len
  96. }
  97. methinfo.update( self.classes[clsname][methodname].EXT_flags )
  98. actdict[clsname].append( methinfo )
  99. return actdict
  100. def get_api_plain( self, request ):
  101. """ Introspect the methods and get a JSON description of only the API. """
  102. return HttpResponse( json.dumps({
  103. "url": reverse( self.request ),
  104. "type": "remoting",
  105. "actions": self.build_api_dict()
  106. }, cls=DjangoJSONEncoder), mimetype="application/json" )
  107. def get_api( self, request ):
  108. """ Introspect the methods and get a javascript description of the API
  109. that is meant to be embedded directly into the web site.
  110. """
  111. request.META["CSRF_COOKIE_USED"] = True
  112. lines = ["%s = %s;" % ( self.name, json.dumps({
  113. "url": reverse( self.request ),
  114. "type": "remoting",
  115. "actions": self.build_api_dict()
  116. }, cls=DjangoJSONEncoder))]
  117. if self.autoadd:
  118. lines.append(
  119. """Ext.Ajax.on("beforerequest", function(conn, options){"""
  120. """ if( !options.headers )"""
  121. """ options.headers = {};"""
  122. """ options.headers["X-CSRFToken"] = Ext.util.Cookies.get("csrftoken");"""
  123. """});"""
  124. )
  125. lines.append( "Ext.Direct.addProvider( %s );" % self.name )
  126. return HttpResponse( "\n".join( lines ), mimetype="text/javascript" )
  127. def request( self, request ):
  128. """ Implements the Router part of the Ext.Direct specification.
  129. It handles decoding requests, calling the appropriate function (if
  130. found) and encoding the response / exceptions.
  131. """
  132. request.META["CSRF_COOKIE_USED"] = True
  133. # First try to use request.POST, if that doesn't work check for req.raw_post_data.
  134. # The other way round this might make more sense because the case that uses
  135. # raw_post_data is way more common, but accessing request.POST after raw_post_data
  136. # causes issues with Django's test client while accessing raw_post_data after
  137. # request.POST does not.
  138. try:
  139. jsoninfo = {
  140. 'action': request.POST['extAction'],
  141. 'method': request.POST['extMethod'],
  142. 'type': request.POST['extType'],
  143. 'upload': request.POST['extUpload'],
  144. 'tid': request.POST['extTID'],
  145. }
  146. except (MultiValueDictKeyError, KeyError), err:
  147. try:
  148. rawjson = json.loads( request.raw_post_data )
  149. except getattr( json, "JSONDecodeError", ValueError ):
  150. return HttpResponse( json.dumps({
  151. 'type': 'exception',
  152. 'message': 'malformed request',
  153. 'where': err.message,
  154. "tid": None, # dunno
  155. }, cls=DjangoJSONEncoder), mimetype="application/json" )
  156. else:
  157. return self.process_normal_request( request, rawjson )
  158. else:
  159. return self.process_form_request( request, jsoninfo )
  160. def process_normal_request( self, request, rawjson ):
  161. """ Process standard requests (no form submission or file uploads). """
  162. if not isinstance( rawjson, list ):
  163. rawjson = [rawjson]
  164. responses = []
  165. for reqinfo in rawjson:
  166. cls, methname, data, rtype, tid = (reqinfo['action'],
  167. reqinfo['method'],
  168. reqinfo['data'],
  169. reqinfo['type'],
  170. reqinfo['tid'])
  171. if cls not in self.classes:
  172. responses.append({
  173. 'type': 'exception',
  174. 'message': 'no such action',
  175. 'where': cls,
  176. "tid": tid,
  177. })
  178. continue
  179. if methname not in self.classes[cls]:
  180. responses.append({
  181. 'type': 'exception',
  182. 'message': 'no such method',
  183. 'where': methname,
  184. "tid": tid,
  185. })
  186. continue
  187. func = self.classes[cls][methname]
  188. if func.EXT_len and len(data) == 1 and type(data[0]) == dict:
  189. # data[0] seems to contain a dict with params. check if it does, and if so, unpack
  190. args = []
  191. for argname in func.EXT_argnames:
  192. if argname in data[0]:
  193. args.append( data[0][argname] )
  194. else:
  195. args = None
  196. break
  197. if args:
  198. data = args
  199. if data is not None:
  200. datalen = len(data)
  201. else:
  202. datalen = 0
  203. if datalen != len(func.EXT_argnames):
  204. responses.append({
  205. 'type': 'exception',
  206. 'tid': tid,
  207. 'message': 'invalid arguments',
  208. 'where': 'Expected %d, got %d' % ( len(func.EXT_argnames), len(data) )
  209. })
  210. continue
  211. try:
  212. if data:
  213. result = func( request, *data )
  214. else:
  215. result = func( request )
  216. except Exception, err:
  217. errinfo = {
  218. 'type': 'exception',
  219. "tid": tid,
  220. }
  221. if settings.DEBUG:
  222. traceback.print_exc( file=stderr )
  223. errinfo['message'] = err.message
  224. errinfo['where'] = traceback.format_exc()
  225. else:
  226. errinfo['message'] = 'The socket packet pocket has an error to report.'
  227. errinfo['where'] = ''
  228. responses.append(errinfo)
  229. else:
  230. responses.append({
  231. "type": rtype,
  232. "tid": tid,
  233. "action": cls,
  234. "method": methname,
  235. "result": result
  236. })
  237. if len(responses) == 1:
  238. return HttpResponse( json.dumps( responses[0], cls=DjangoJSONEncoder ), mimetype="application/json" )
  239. else:
  240. return HttpResponse( json.dumps( responses, cls=DjangoJSONEncoder ), mimetype="application/json" )
  241. def process_form_request( self, request, reqinfo ):
  242. """ Router for POST requests that submit form data and/or file uploads. """
  243. cls, methname, rtype, tid = (reqinfo['action'],
  244. reqinfo['method'],
  245. reqinfo['type'],
  246. reqinfo['tid'])
  247. if cls not in self.classes:
  248. response = {
  249. 'type': 'exception',
  250. 'message': 'no such action',
  251. 'where': cls,
  252. "tid": tid,
  253. }
  254. elif methname not in self.classes[cls]:
  255. response = {
  256. 'type': 'exception',
  257. 'message': 'no such method',
  258. 'where': methname,
  259. "tid": tid,
  260. }
  261. else:
  262. func = self.classes[cls][methname]
  263. try:
  264. result = func( request )
  265. except Exception, err:
  266. errinfo = {
  267. 'type': 'exception',
  268. "tid": tid,
  269. }
  270. if settings.DEBUG:
  271. traceback.print_exc( file=stderr )
  272. errinfo['message'] = err.message
  273. errinfo['where'] = traceback.format_exc()
  274. else:
  275. errinfo['message'] = 'The socket packet pocket has an error to report.'
  276. errinfo['where'] = ''
  277. response = errinfo
  278. else:
  279. response = {
  280. "type": rtype,
  281. "tid": tid,
  282. "action": cls,
  283. "method": methname,
  284. "result": result
  285. }
  286. if reqinfo['upload'] == "true":
  287. return HttpResponse(
  288. "<html><body><textarea>%s</textarea></body></html>" % json.dumps(response, cls=DjangoJSONEncoder),
  289. mimetype="application/json"
  290. )
  291. else:
  292. return HttpResponse( json.dumps( response, cls=DjangoJSONEncoder ), mimetype="application/json" )
  293. def get_urls(self):
  294. """ Return the URL patterns. """
  295. pat = patterns('',
  296. (r'api.json$', self.get_api_plain ),
  297. (r'api.js$', self.get_api ),
  298. (r'router/?', self.request ),
  299. )
  300. return pat
  301. urls = property(get_urls)