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.

190 lines
6.0 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. import simplejson
  17. import httplib
  18. from threading import Lock
  19. from urlparse import urljoin, urlparse
  20. def lexjs(javascript):
  21. """ Parse the given javascript and return a dict of variables defined in there. """
  22. ST_NAME, ST_ASSIGN = range(2)
  23. state = ST_NAME
  24. foundvars = {}
  25. buf = ""
  26. name = ""
  27. for char in javascript:
  28. if state == ST_NAME:
  29. if char == ' ':
  30. continue
  31. elif char == '=':
  32. state = ST_ASSIGN
  33. name = buf
  34. buf = ""
  35. elif char == ';':
  36. state = ST_NAME
  37. buf = ""
  38. else:
  39. buf += char
  40. elif state == ST_ASSIGN:
  41. if char == ';':
  42. state = ST_NAME
  43. foundvars[name] = simplejson.loads(buf)
  44. name = ""
  45. buf = ""
  46. else:
  47. buf += char
  48. return foundvars
  49. class RequestError(Exception):
  50. """ Raised if the request returned a status code other than 200. """
  51. pass
  52. class ReturnedError(Exception):
  53. """ Raised if the "type" field in the response is "exception". """
  54. pass
  55. class Client(object):
  56. """ Ext.Direct client side implementation.
  57. This class handles parsing an API specification, building proxy objects from it,
  58. and making calls to the router specified in the API.
  59. Instantiation:
  60. >>> cli = Client( "http://localhost:8000/mumble/api/api.js", "Ext.app.REMOTING_API" )
  61. The apiname parameter defaults to ``Ext.app.REMOTING_API`` and is used to select
  62. the proper API variable from the API source.
  63. The client will then create proxy objects for each action defined in the URL,
  64. which are accessible as properties of the Client instance. Suppose your API defines
  65. the ``Accounts`` and ``Mumble`` actions, then the client will provide those as such:
  66. >>> cli.Accounts
  67. <client.AccountsPrx object at 0x93d9e2c>
  68. >>> cli.Mumble
  69. <client.MumblePrx object at 0x93d9a2c>
  70. These objects provide native Python methods for each method defined in the actions:
  71. >>> cli.Accounts.login
  72. <bound method AccountsPrx.login of <client.AccountsPrx object at 0x93d9e2c>>
  73. So, in order to make a call over Ext.Direct, you would simply call the proxy method:
  74. >>> cli.Accounts.login( "svedrin", "passwort" )
  75. {'success': True}
  76. """
  77. def __init__( self, apiurl, apiname="Ext.app.REMOTING_API", cookie=None ):
  78. self.apiurl = apiurl
  79. self.apiname = apiname
  80. self.cookie = cookie
  81. purl = urlparse( self.apiurl )
  82. conn = httplib.HTTPConnection( purl.netloc )
  83. conn.putrequest( "GET", purl.path )
  84. conn.endheaders()
  85. resp = conn.getresponse()
  86. conn.close()
  87. foundvars = lexjs( resp.read() )
  88. self.api = foundvars[apiname]
  89. self.routerurl = urljoin( self.apiurl, self.api["url"] )
  90. self._tid = 1
  91. self._tidlock = Lock()
  92. for action in self.api['actions']:
  93. setattr( self, action, self.get_object(action) )
  94. @property
  95. def tid( self ):
  96. """ Thread-safely get a new TID. """
  97. self._tidlock.acquire()
  98. self._tid += 1
  99. newtid = self._tid
  100. self._tidlock.release()
  101. return newtid
  102. def call( self, action, method, *args ):
  103. """ Make a call to Ext.Direct. """
  104. reqtid = self.tid
  105. data=simplejson.dumps({
  106. 'tid': reqtid,
  107. 'action': action,
  108. 'method': method,
  109. 'data': args,
  110. 'type': 'rpc'
  111. })
  112. purl = urlparse( self.routerurl )
  113. conn = httplib.HTTPConnection( purl.netloc )
  114. conn.putrequest( "POST", purl.path )
  115. conn.putheader( "Content-Type", "application/json" )
  116. conn.putheader( "Content-Length", len(data) )
  117. if self.cookie:
  118. conn.putheader( "Cookie", self.cookie )
  119. conn.endheaders()
  120. conn.send( data )
  121. resp = conn.getresponse()
  122. conn.close()
  123. if resp.status != 200:
  124. raise RequestError( resp.status, resp.reason )
  125. respdata = simplejson.loads( resp.read() )
  126. if respdata['type'] == 'exception':
  127. raise ReturnedError( respdata['message'], respdata['where'] )
  128. if respdata['tid'] != reqtid:
  129. raise RequestError( 'TID mismatch' )
  130. cookie = resp.getheader( "set-cookie" )
  131. if cookie:
  132. self.cookie = cookie.split(';')[0]
  133. return respdata['result']
  134. def get_object( self, action ):
  135. """ Return a proxy object that has methods defined in the API. """
  136. def makemethod( methspec ):
  137. def func( self, *args ):
  138. if len(args) != methspec['len']:
  139. raise TypeError( '%s() takes exactly %d arguments (%d given)' % (
  140. methspec['name'], methspec['len'], len(args)
  141. ) )
  142. return self._cli.call( action, methspec['name'], *args )
  143. func.__name__ = methspec['name']
  144. return func
  145. def init( self, cli ):
  146. self._cli = cli
  147. attrs = {
  148. '__init__': init
  149. }
  150. for methspec in self.api['actions'][action]:
  151. attrs[methspec['name']] = makemethod( methspec )
  152. return type( action+"Prx", (object,), attrs )( self )