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.

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