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.

224 lines
8.1 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 to cls_or_name. """
  69. clsname = getname(cls_or_name)
  70. if clsname not in self.classes:
  71. self.classes[clsname] = {}
  72. return functools.partial( self._register_method, cls_or_name )
  73. def _register_method( self, cls_or_name, method ):
  74. """ Actually registers the given function as a method of cls_or_name. """
  75. self.classes[ getname(cls_or_name) ][ method.__name__ ] = method
  76. method.EXT_argnames = inspect.getargspec( method ).args[1:]
  77. method.EXT_len = len( method.EXT_argnames )
  78. return method
  79. @csrf_exempt
  80. def get_api( self, request ):
  81. """ Introspect the methods and get a JSON description of this API. """
  82. actdict = {}
  83. for clsname in self.classes:
  84. actdict[clsname] = []
  85. for methodname in self.classes[clsname]:
  86. actdict[clsname].append( {
  87. "name": methodname,
  88. "len": self.classes[clsname][methodname].EXT_len
  89. } )
  90. lines = ["%s = %s;" % ( self.name, simplejson.dumps({
  91. "url": reverse( self.request ),
  92. "type": "remoting",
  93. "actions": actdict
  94. }))]
  95. if self.autoadd:
  96. lines.append( "Ext.Direct.addProvider( %s );" % self.name )
  97. return HttpResponse( "\n".join( lines ), mimetype="text/javascript" )
  98. @csrf_exempt
  99. def request( self, request ):
  100. """ Implements the Router part of the Ext.Direct specification.
  101. It handles decoding requests, calling the appropriate function (if
  102. found) and encoding the response / exceptions.
  103. """
  104. try:
  105. rawjson = [{
  106. 'action': request.POST['extAction'],
  107. 'method': request.POST['extMethod'],
  108. 'data': request.POST['extData'],
  109. 'type': request.POST['extType'],
  110. 'tid': request.POST['extTID'],
  111. }]
  112. except (MultiValueDictKeyError, KeyError):
  113. rawjson = simplejson.loads( request.raw_post_data )
  114. if not isinstance( rawjson, list ):
  115. rawjson = [rawjson]
  116. responses = []
  117. for reqinfo in rawjson:
  118. cls, methname, data, rtype, tid = (reqinfo['action'],
  119. reqinfo['method'],
  120. reqinfo['data'],
  121. reqinfo['type'],
  122. reqinfo['tid'])
  123. if cls not in self.classes:
  124. responses.append({
  125. 'type': 'exception',
  126. 'message': 'no such action',
  127. 'where': cls,
  128. "tid": tid,
  129. })
  130. continue
  131. if methname not in self.classes[cls]:
  132. responses.append({
  133. 'type': 'exception',
  134. 'message': 'no such method',
  135. 'where': methname,
  136. "tid": tid,
  137. })
  138. continue
  139. func = self.classes[cls][methname]
  140. if func.EXT_len and len(data) == 1 and type(data[0]) == dict:
  141. # data[0] seems to contain a dict with params. check if it does, and if so, unpack
  142. args = []
  143. for argname in func.EXT_argnames:
  144. if argname in data[0]:
  145. args.append( data[0][argname] )
  146. else:
  147. args = None
  148. break
  149. if args:
  150. data = args
  151. try:
  152. if data:
  153. result = func( request, *data )
  154. else:
  155. result = func( request )
  156. except Exception, err:
  157. errinfo = {
  158. 'type': 'exception',
  159. "tid": tid,
  160. }
  161. if settings.DEBUG:
  162. traceback.print_exc( file=stderr )
  163. errinfo['message'] = unicode(err)
  164. errinfo['where'] = traceback.format_exc()
  165. else:
  166. errinfo['message'] = 'Sorry, an error occurred.'
  167. errinfo['where'] = ''
  168. responses.append(errinfo)
  169. else:
  170. responses.append({
  171. "type": rtype,
  172. "tid": tid,
  173. "action": cls,
  174. "method": methname,
  175. "result": result
  176. })
  177. if len(responses) == 1:
  178. return HttpResponse( simplejson.dumps( responses[0] ), mimetype="text/javascript" )
  179. else:
  180. return HttpResponse( simplejson.dumps( responses ), mimetype="text/javascript" )
  181. @property
  182. def urls(self):
  183. """ Return the URL patterns. """
  184. return patterns('',
  185. (r'api.js$', self.get_api ),
  186. (r'router/?', self.request ),
  187. )