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.

230 lines
8.2 KiB

  1. # -*- coding: utf-8 -*-
  2. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright (C) 200, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  5. *
  6. * Mumble-Django 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 type(cls_or_name) not in ( str, unicode ):
  29. return cls_or_name.__name__
  30. return cls_or_name
  31. class Provider( object ):
  32. """ Provider for Ext.Direct. This class handles building API information and
  33. routing requests to the appropriate functions, and serializing their
  34. response and exceptions - if any.
  35. Instantiation:
  36. >>> EXT_JS_PROVIDER = Provider( [name="Ext.app.REMOTING_API", autoadd=True] )
  37. If autoadd is True, the api.js will include a line like such:
  38. Ext.Direct.addProvider( Ext.app.REMOTING_API );
  39. After instantiating the Provider, register functions to it like so:
  40. >>> @EXT_JS_PROVIDER.register_method("myclass")
  41. ... def myview( request, possibly, some, other, arguments ):
  42. ... " does something with all those args and returns something "
  43. ... return 13.37
  44. Note that those views **MUST NOT** return an HttpResponse but simply
  45. the plain result, as the Provider will build a response from whatever
  46. your view returns!
  47. To be able to access the Provider, include its URLs in an arbitrary
  48. URL pattern, like so:
  49. >>> from views import EXT_JS_PROVIDER # import our provider instance
  50. >>> urlpatterns = patterns(
  51. ... # other patterns go here
  52. ... ( r'api/', include(EXT_DIRECT_PROVIDER.urls) ),
  53. ... )
  54. This way, the Provider will define the URLs "api/api.js" and "api/router".
  55. If you then access the "api/api.js" URL, you will get a response such as::
  56. Ext.app.REMOTING_API = { # Ext.app.REMOTING_API is from Provider.name
  57. "url": "/mumble/api/router",
  58. "type": "remoting",
  59. "actions": {"myclass": [{"name": "myview", "len": 4}]}
  60. }
  61. You can then use this code in ExtJS to define the Provider there.
  62. """
  63. def __init__( self, name="Ext.app.REMOTING_API", autoadd=True ):
  64. self.name = name
  65. self.autoadd = autoadd
  66. self.classes = {}
  67. def register_method( self, cls_or_name ):
  68. """ Return a function that takes a method as an argument and adds that
  69. to cls_or_name.
  70. Note: This decorator does not replace the method by a new function,
  71. it returns the original function as-is.
  72. """
  73. clsname = getname(cls_or_name)
  74. if clsname not in self.classes:
  75. self.classes[clsname] = {}
  76. return functools.partial( self._register_method, cls_or_name )
  77. def _register_method( self, cls_or_name, method ):
  78. """ Actually registers the given function as a method of cls_or_name. """
  79. self.classes[ getname(cls_or_name) ][ method.__name__ ] = method
  80. method.EXT_argnames = inspect.getargspec( method ).args[1:]
  81. method.EXT_len = len( method.EXT_argnames )
  82. return method
  83. @csrf_exempt
  84. def get_api( self, request ):
  85. """ Introspect the methods and get a JSON description of this API. """
  86. actdict = {}
  87. for clsname in self.classes:
  88. actdict[clsname] = []
  89. for methodname in self.classes[clsname]:
  90. actdict[clsname].append( {
  91. "name": methodname,
  92. "len": self.classes[clsname][methodname].EXT_len
  93. } )
  94. lines = ["%s = %s;" % ( self.name, simplejson.dumps({
  95. "url": reverse( self.request ),
  96. "type": "remoting",
  97. "actions": actdict
  98. }))]
  99. if self.autoadd:
  100. lines.append( "Ext.Direct.addProvider( %s );" % self.name )
  101. return HttpResponse( "\n".join( lines ), mimetype="text/javascript" )
  102. @csrf_exempt
  103. def request( self, request ):
  104. """ Implements the Router part of the Ext.Direct specification.
  105. It handles decoding requests, calling the appropriate function (if
  106. found) and encoding the response / exceptions.
  107. """
  108. try:
  109. rawjson = [{
  110. 'action': request.POST['extAction'],
  111. 'method': request.POST['extMethod'],
  112. 'data': request.POST['extData'],
  113. 'type': request.POST['extType'],
  114. 'tid': request.POST['extTID'],
  115. }]
  116. except (MultiValueDictKeyError, KeyError):
  117. rawjson = simplejson.loads( request.raw_post_data )
  118. if not isinstance( rawjson, list ):
  119. rawjson = [rawjson]
  120. responses = []
  121. for reqinfo in rawjson:
  122. cls, methname, data, rtype, tid = (reqinfo['action'],
  123. reqinfo['method'],
  124. reqinfo['data'],
  125. reqinfo['type'],
  126. reqinfo['tid'])
  127. if cls not in self.classes:
  128. responses.append({
  129. 'type': 'exception',
  130. 'message': 'no such action',
  131. 'where': cls,
  132. "tid": tid,
  133. })
  134. continue
  135. if methname not in self.classes[cls]:
  136. responses.append({
  137. 'type': 'exception',
  138. 'message': 'no such method',
  139. 'where': methname,
  140. "tid": tid,
  141. })
  142. continue
  143. func = self.classes[cls][methname]
  144. if func.EXT_len and len(data) == 1 and type(data[0]) == dict:
  145. # data[0] seems to contain a dict with params. check if it does, and if so, unpack
  146. args = []
  147. for argname in func.EXT_argnames:
  148. if argname in data[0]:
  149. args.append( data[0][argname] )
  150. else:
  151. args = None
  152. break
  153. if args:
  154. data = args
  155. try:
  156. if data:
  157. result = func( request, *data )
  158. else:
  159. result = func( request )
  160. except Exception, err:
  161. errinfo = {
  162. 'type': 'exception',
  163. "tid": tid,
  164. }
  165. if settings.DEBUG:
  166. traceback.print_exc( file=stderr )
  167. errinfo['message'] = unicode(err)
  168. errinfo['where'] = traceback.format_exc()
  169. else:
  170. errinfo['message'] = 'Sorry, an error occurred.'
  171. errinfo['where'] = ''
  172. responses.append(errinfo)
  173. else:
  174. responses.append({
  175. "type": rtype,
  176. "tid": tid,
  177. "action": cls,
  178. "method": methname,
  179. "result": result
  180. })
  181. if len(responses) == 1:
  182. return HttpResponse( simplejson.dumps( responses[0] ), mimetype="text/javascript" )
  183. else:
  184. return HttpResponse( simplejson.dumps( responses ), mimetype="text/javascript" )
  185. @property
  186. def urls(self):
  187. """ Return the URL patterns. """
  188. return patterns('',
  189. (r'api.js$', self.get_api ),
  190. (r'router/?', self.request ),
  191. )