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.

355 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. def getname( cls_or_name ):
  30. """ If cls_or_name is not a string, return its __name__. """
  31. if type(cls_or_name) not in ( str, unicode ):
  32. return cls_or_name.__name__
  33. return cls_or_name
  34. class Provider( object ):
  35. """ Provider for Ext.Direct. This class handles building API information and
  36. routing requests to the appropriate functions, and serializing their
  37. response and exceptions - if any.
  38. Instantiation:
  39. >>> EXT_JS_PROVIDER = Provider( [name="Ext.app.REMOTING_API", autoadd=True] )
  40. If autoadd is True, the api.js will include a line like such::
  41. Ext.Direct.addProvider( Ext.app.REMOTING_API );
  42. After instantiating the Provider, register functions to it like so:
  43. >>> @EXT_JS_PROVIDER.register_method("myclass")
  44. ... def myview( request, possibly, some, other, arguments ):
  45. ... " does something with all those args and returns something "
  46. ... return 13.37
  47. Note that those views **MUST NOT** return an HttpResponse but simply
  48. the plain result, as the Provider will build a response from whatever
  49. your view returns!
  50. To be able to access the Provider, include its URLs in an arbitrary
  51. URL pattern, like so:
  52. >>> from views import EXT_JS_PROVIDER # import our provider instance
  53. >>> urlpatterns = patterns(
  54. ... # other patterns go here
  55. ... ( r'api/', include(EXT_DIRECT_PROVIDER.urls) ),
  56. ... )
  57. This way, the Provider will define the URLs "api/api.js" and "api/router".
  58. If you then access the "api/api.js" URL, you will get a response such as::
  59. Ext.app.REMOTING_API = { # Ext.app.REMOTING_API is from Provider.name
  60. "url": "/mumble/api/router",
  61. "type": "remoting",
  62. "actions": {"myclass": [{"name": "myview", "len": 4}]}
  63. }
  64. You can then use this code in ExtJS to define the Provider there.
  65. """
  66. def __init__( self, name="Ext.app.REMOTING_API", autoadd=True ):
  67. self.name = name
  68. self.autoadd = autoadd
  69. self.classes = {}
  70. def register_method( self, cls_or_name, flags=None ):
  71. """ Return a function that takes a method as an argument and adds that
  72. to cls_or_name.
  73. The flags parameter is for additional information, e.g. formHandler=True.
  74. Note: This decorator does not replace the method by a new function,
  75. it returns the original function as-is.
  76. """
  77. return functools.partial( self._register_method, cls_or_name, flags=flags )
  78. def _register_method( self, cls_or_name, method, flags=None ):
  79. """ Actually registers the given function as a method of cls_or_name. """
  80. clsname = getname(cls_or_name)
  81. if clsname not in self.classes:
  82. self.classes[clsname] = {}
  83. if flags is None:
  84. flags = {}
  85. self.classes[ clsname ][ method.__name__ ] = method
  86. method.EXT_argnames = inspect.getargspec( method )[0][1:]
  87. method.EXT_len = len( method.EXT_argnames )
  88. method.EXT_flags = flags
  89. return method
  90. def build_api_dict( self ):
  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. return actdict
  102. def get_api_plain( self, request ):
  103. """ Introspect the methods and get a JSON description of only the API. """
  104. return HttpResponse( simplejson.dumps({
  105. "url": reverse( self.request ),
  106. "type": "remoting",
  107. "actions": self.build_api_dict()
  108. }), mimetype="application/json" )
  109. def get_api( self, request ):
  110. """ Introspect the methods and get a javascript description of the API
  111. that is meant to be embedded directly into the web site.
  112. """
  113. lines = ["%s = %s;" % ( self.name, simplejson.dumps({
  114. "url": reverse( self.request ),
  115. "type": "remoting",
  116. "actions": self.build_api_dict()
  117. }))]
  118. if self.autoadd:
  119. lines.append(
  120. """Ext.Ajax.on("beforerequest", function(conn, options){"""
  121. """ if( !options.headers )"""
  122. """ options.headers = {};"""
  123. """ options.headers["X-CSRFToken"] = Ext.util.Cookies.get("csrftoken");"""
  124. """});"""
  125. )
  126. lines.append( "Ext.Direct.addProvider( %s );" % self.name )
  127. return HttpResponse( "\n".join( lines ), mimetype="text/javascript" )
  128. def request( self, request ):
  129. """ Implements the Router part of the Ext.Direct specification.
  130. It handles decoding requests, calling the appropriate function (if
  131. found) and encoding the response / exceptions.
  132. """
  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 = simplejson.loads( request.raw_post_data )
  149. except getattr( simplejson, "JSONDecodeError", ValueError ):
  150. return HttpResponse( simplejson.dumps({
  151. 'type': 'exception',
  152. 'message': 'malformed request',
  153. 'where': unicode(err),
  154. "tid": None, # dunno
  155. }), 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'] = unicode(err)
  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( simplejson.dumps( responses[0] ), mimetype="application/json" )
  239. else:
  240. return HttpResponse( simplejson.dumps( responses ), 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'] = unicode(err)
  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>" % simplejson.dumps(response),
  289. mimetype="application/json"
  290. )
  291. else:
  292. return HttpResponse( simplejson.dumps( response ), 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)