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.

199 lines
7.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"] )
  37. After instantiating the Provider, register functions to it like so:
  38. >>> @EXT_JS_PROVIDER.register_method("myclass")
  39. def myview( request, possibly, some, other, arguments ):
  40. " does something with all those args and returns something "
  41. return 13.37
  42. Note that those views **MUST NOT** return an HttpResponse but simply
  43. the plain result, as the Provider will build a response from whatever
  44. your view returns!
  45. To be able to access the Provider, include its URLs in an arbitrary
  46. URL pattern, like so:
  47. >>> from views import EXT_JS_PROVIDER # import our provider instance
  48. >>> urlpatterns = patterns(
  49. # other patterns go here
  50. ( r'api/', include(EXT_DIRECT_PROVIDER.urls) ),
  51. )
  52. This way, the Provider will define the URLs "api/api.js" and "api/router".
  53. If you then access the "api/api.js" URL, you will get a response such as:
  54. Ext.app.REMOTING_API = { # Ext.app.REMOTING_API is from Provider.name
  55. "url": "/mumble/api/router",
  56. "type": "remoting",
  57. "actions": {"myclass": [{"name": "myview", "len": 4}]}
  58. }
  59. You can then use this code in ExtJS to define the Provider there.
  60. """
  61. def __init__( self, name="Ext.app.REMOTING_API" ):
  62. self.name = name
  63. self.classes = {}
  64. def register_method( self, cls_or_name ):
  65. """ Return a function that takes a method as an argument and adds that to cls_or_name. """
  66. clsname = getname(cls_or_name)
  67. if clsname not in self.classes:
  68. self.classes[clsname] = {}
  69. return functools.partial( self._register_method, cls_or_name )
  70. def _register_method( self, cls_or_name, method ):
  71. """ Actually registers the given function as a method of cls_or_name. """
  72. self.classes[ getname(cls_or_name) ][ method.__name__ ] = method
  73. return method
  74. @csrf_exempt
  75. def get_api( self, request ):
  76. """ Introspect the methods and get a JSON description of this API. """
  77. actdict = {}
  78. for clsname in self.classes:
  79. actdict[clsname] = []
  80. for methodname in self.classes[clsname]:
  81. actdict[clsname].append( {
  82. "name": methodname,
  83. "len": len( inspect.getargspec( self.classes[clsname][methodname] ).args ) - 1
  84. } )
  85. return HttpResponse( "%s = %s;" % ( self.name, simplejson.dumps({
  86. "url": reverse( self.request ),
  87. "type": "remoting",
  88. "actions": actdict
  89. })), mimetype="text/javascript" )
  90. @csrf_exempt
  91. def request( self, request ):
  92. """ Implements the Router part of the Ext.Direct specification.
  93. It handles decoding requests, calling the appropriate function (if
  94. found) and encoding the response / exceptions.
  95. """
  96. try:
  97. rawjson = [{
  98. 'action': request.POST['extAction'],
  99. 'method': request.POST['extMethod'],
  100. 'data': request.POST['extData'],
  101. 'type': request.POST['extType'],
  102. 'tid': request.POST['extTID'],
  103. }]
  104. except (MultiValueDictKeyError, KeyError):
  105. rawjson = simplejson.loads( request.raw_post_data )
  106. if not isinstance( rawjson, list ):
  107. rawjson = [rawjson]
  108. responses = []
  109. for reqinfo in rawjson:
  110. cls, methname, data, rtype, tid = (reqinfo['action'],
  111. reqinfo['method'],
  112. reqinfo['data'],
  113. reqinfo['type'],
  114. reqinfo['tid'])
  115. if cls not in self.classes:
  116. responses.append({
  117. 'type': 'exception',
  118. 'message': 'no such action',
  119. 'where': cls,
  120. "tid": tid,
  121. })
  122. continue
  123. if methname not in self.classes[cls]:
  124. responses.append({
  125. 'type': 'exception',
  126. 'message': 'no such method',
  127. 'where': methname,
  128. "tid": tid,
  129. })
  130. continue
  131. try:
  132. if data:
  133. result = self.classes[cls][methname]( request, *data )
  134. else:
  135. result = self.classes[cls][methname]( request )
  136. except Exception, err:
  137. errinfo = {
  138. 'type': 'exception',
  139. "tid": tid,
  140. }
  141. if settings.DEBUG:
  142. traceback.print_exc( file=stderr )
  143. errinfo['message'] = unicode(err)
  144. errinfo['where'] = '\n'.join(traceback.format_exception())
  145. else:
  146. errinfo['message'] = 'Sorry, an error occurred.'
  147. errinfo['where'] = ''
  148. responses.append(errinfo)
  149. else:
  150. responses.append({
  151. "type": rtype,
  152. "tid": tid,
  153. "action": cls,
  154. "method": methname,
  155. "result": result
  156. })
  157. if len(responses) == 1:
  158. return HttpResponse( simplejson.dumps( responses[0] ), mimetype="text/javascript" )
  159. else:
  160. return HttpResponse( simplejson.dumps( responses ), mimetype="text/javascript" )
  161. @property
  162. def urls(self):
  163. """ Return the URL patterns. """
  164. return patterns('',
  165. (r'api.js$', self.get_api ),
  166. (r'router/?', self.request ),
  167. )