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.

196 lines
6.2 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 json
  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] = json.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 = {
  83. "http": httplib.HTTPConnection,
  84. "https": httplib.HTTPSConnection
  85. }[purl.scheme.lower()]( purl.netloc )
  86. conn.putrequest( "GET", purl.path )
  87. conn.endheaders()
  88. resp = conn.getresponse()
  89. foundvars = lexjs( resp.read() )
  90. conn.close()
  91. self.api = foundvars[apiname]
  92. self.routerurl = urljoin( self.apiurl, self.api["url"] )
  93. self._tid = 1
  94. self._tidlock = Lock()
  95. for action in self.api['actions']:
  96. setattr( self, action, self.get_object(action) )
  97. @property
  98. def tid( self ):
  99. """ Thread-safely get a new TID. """
  100. self._tidlock.acquire()
  101. self._tid += 1
  102. newtid = self._tid
  103. self._tidlock.release()
  104. return newtid
  105. def call( self, action, method, *args ):
  106. """ Make a call to Ext.Direct. """
  107. reqtid = self.tid
  108. data=json.dumps({
  109. 'tid': reqtid,
  110. 'action': action,
  111. 'method': method,
  112. 'data': args,
  113. 'type': 'rpc'
  114. })
  115. purl = urlparse( self.routerurl )
  116. conn = {
  117. "http": httplib.HTTPConnection,
  118. "https": httplib.HTTPSConnection
  119. }[purl.scheme.lower()]( purl.netloc )
  120. conn.putrequest( "POST", purl.path )
  121. conn.putheader( "Content-Type", "application/json" )
  122. conn.putheader( "Content-Length", str(len(data)) )
  123. if self.cookie:
  124. conn.putheader( "Cookie", self.cookie )
  125. conn.endheaders()
  126. conn.send( data )
  127. resp = conn.getresponse()
  128. if resp.status != 200:
  129. raise RequestError( resp.status, resp.reason )
  130. respdata = json.loads( resp.read() )
  131. if respdata['type'] == 'exception':
  132. raise ReturnedError( respdata['message'], respdata['where'] )
  133. if respdata['tid'] != reqtid:
  134. raise RequestError( 'TID mismatch' )
  135. cookie = resp.getheader( "set-cookie" )
  136. if cookie:
  137. self.cookie = cookie.split(';')[0]
  138. conn.close()
  139. return respdata['result']
  140. def get_object( self, action ):
  141. """ Return a proxy object that has methods defined in the API. """
  142. def makemethod( methspec ):
  143. def func( self, *args ):
  144. if len(args) != methspec['len']:
  145. raise TypeError( '%s() takes exactly %d arguments (%d given)' % (
  146. methspec['name'], methspec['len'], len(args)
  147. ) )
  148. return self._cli.call( action, methspec['name'], *args )
  149. func.__name__ = methspec['name']
  150. return func
  151. def init( self, cli ):
  152. self._cli = cli
  153. attrs = {
  154. '__init__': init
  155. }
  156. for methspec in self.api['actions'][action]:
  157. attrs[methspec['name']] = makemethod( methspec )
  158. return type( action+"Prx", (object,), attrs )( self )