browser.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. ## browser.py
  2. ##
  3. ## Copyright (C) 2004 Alexey "Snake" Nezhdanov
  4. ##
  5. ## This program is free software; you can redistribute it and/or modify
  6. ## it under the terms of the GNU General Public License as published by
  7. ## the Free Software Foundation; either version 2, or (at your option)
  8. ## any later version.
  9. ##
  10. ## This program is distributed in the hope that it will be useful,
  11. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ## GNU General Public License for more details.
  14. # $Id$
  15. """Browser module provides DISCO server framework for your application.
  16. This functionality can be used for very different purposes - from publishing
  17. software version and supported features to building of "XMPP site" that users
  18. can navigate with their disco browsers and interact with active content.
  19. Such functionality is achieved via registering "DISCO handlers" that are
  20. automatically called when user requests some node of your disco tree.
  21. """
  22. from .dispatcher import *
  23. from .client import PlugIn
  24. class Browser(PlugIn):
  25. """ WARNING! This class is for components only. It will not work in client mode!
  26. Standart xmpppy class that is ancestor of PlugIn and can be attached
  27. to your application.
  28. All processing will be performed in the handlers registered in the browser
  29. instance. You can register any number of handlers ensuring that for each
  30. node/jid combination only one (or none) handler registered.
  31. You can register static information or the fully-blown function that will
  32. calculate the answer dynamically.
  33. Example of static info (see XEP-0030, examples 13-14):
  34. # cl - your xmpppy connection instance.
  35. b=xmpp.browser.Browser()
  36. b.PlugIn(cl)
  37. items=[]
  38. item={}
  39. item['jid']='catalog.shakespeare.lit'
  40. item['node']='books'
  41. item['name']='Books by and about Shakespeare'
  42. items.append(item)
  43. item={}
  44. item['jid']='catalog.shakespeare.lit'
  45. item['node']='clothing'
  46. item['name']='Wear your literary taste with pride'
  47. items.append(item)
  48. item={}
  49. item['jid']='catalog.shakespeare.lit'
  50. item['node']='music'
  51. item['name']='Music from the time of Shakespeare'
  52. items.append(item)
  53. info={'ids':[], 'features':[]}
  54. b.setDiscoHandler({'items':items,'info':info})
  55. items should be a list of item elements.
  56. every item element can have any of these four keys: 'jid', 'node', 'name', 'action'
  57. info should be a dicionary and must have keys 'ids' and 'features'.
  58. Both of them should be lists:
  59. ids is a list of dictionaries and features is a list of text strings.
  60. Example (see XEP-0030, examples 1-2)
  61. # cl - your xmpppy connection instance.
  62. b=xmpp.browser.Browser()
  63. b.PlugIn(cl)
  64. items=[]
  65. ids=[]
  66. ids.append({'category':'conference','type':'text','name':'Play-Specific Chatrooms'})
  67. ids.append({'category':'directory','type':'chatroom','name':'Play-Specific Chatrooms'})
  68. features=[NS_DISCO_INFO,NS_DISCO_ITEMS,NS_MUC,NS_REGISTER,NS_SEARCH,NS_TIME,NS_VERSION]
  69. info={'ids':ids,'features':features}
  70. # info['xdata']=xmpp.protocol.DataForm() # XEP-0128
  71. b.setDiscoHandler({'items':[],'info':info})
  72. """
  73. def __init__(self):
  74. """Initialises internal variables. Used internally."""
  75. PlugIn.__init__(self)
  76. DBG_LINE='browser'
  77. self._exported_methods=[]
  78. self._handlers={'':{}}
  79. def plugin(self, owner):
  80. """ Registers it's own iq handlers in your application dispatcher instance.
  81. Used internally."""
  82. owner.RegisterHandler('iq',self._DiscoveryHandler,typ='get',ns=NS_DISCO_INFO)
  83. owner.RegisterHandler('iq',self._DiscoveryHandler,typ='get',ns=NS_DISCO_ITEMS)
  84. def plugout(self):
  85. """ Unregisters browser's iq handlers from your application dispatcher instance.
  86. Used internally."""
  87. self._owner.UnregisterHandler('iq',self._DiscoveryHandler,typ='get',ns=NS_DISCO_INFO)
  88. self._owner.UnregisterHandler('iq',self._DiscoveryHandler,typ='get',ns=NS_DISCO_ITEMS)
  89. def _traversePath(self,node,jid,set=0):
  90. """ Returns dictionary and key or None,None
  91. None - root node (w/o "node" attribute)
  92. /a/b/c - node
  93. /a/b/ - branch
  94. Set returns '' or None as the key
  95. get returns '' or None as the key or None as the dict.
  96. Used internally."""
  97. if jid in self._handlers: cur=self._handlers[jid]
  98. elif set:
  99. self._handlers[jid]={}
  100. cur=self._handlers[jid]
  101. else: cur=self._handlers['']
  102. if node is None: node=[None]
  103. else: node=node.replace('/',' /').split('/')
  104. for i in node:
  105. if i!='' and i in cur: cur=cur[i]
  106. elif set and i!='': cur[i]={dict:cur,str:i}; cur=cur[i]
  107. elif set or '' in cur: return cur,''
  108. else: return None,None
  109. if 1 in cur or set: return cur,1
  110. raise Exception("Corrupted data")
  111. def setDiscoHandler(self,handler,node='',jid=''):
  112. """ This is the main method that you will use in this class.
  113. It is used to register supplied DISCO handler (or dictionary with static info)
  114. as handler of some disco tree branch.
  115. If you do not specify the node this handler will be used for all queried nodes.
  116. If you do not specify the jid this handler will be used for all queried JIDs.
  117. Usage:
  118. cl.Browser.setDiscoHandler(someDict,node,jid)
  119. or
  120. cl.Browser.setDiscoHandler(someDISCOHandler,node,jid)
  121. where
  122. someDict={
  123. 'items':[
  124. {'jid':'jid1','action':'action1','node':'node1','name':'name1'},
  125. {'jid':'jid2','action':'action2','node':'node2','name':'name2'},
  126. {'jid':'jid3','node':'node3','name':'name3'},
  127. {'jid':'jid4','node':'node4'}
  128. ],
  129. 'info' :{
  130. 'ids':[
  131. {'category':'category1','type':'type1','name':'name1'},
  132. {'category':'category2','type':'type2','name':'name2'},
  133. {'category':'category3','type':'type3','name':'name3'},
  134. ],
  135. 'features':['feature1','feature2','feature3','feature4'],
  136. 'xdata':DataForm
  137. }
  138. }
  139. and/or
  140. def someDISCOHandler(session,request,TYR):
  141. # if TYR=='items': # returns items list of the same format as shown above
  142. # elif TYR=='info': # returns info dictionary of the same format as shown above
  143. # else: # this case is impossible for now.
  144. """
  145. self.DEBUG('Registering handler %s for "%s" node->%s'%(handler,jid,node), 'info')
  146. node,key=self._traversePath(node,jid,1)
  147. node[key]=handler
  148. def getDiscoHandler(self,node='',jid=''):
  149. """ Returns the previously registered DISCO handler
  150. that is resonsible for this node/jid combination.
  151. Used internally."""
  152. node,key=self._traversePath(node,jid)
  153. if node: return node[key]
  154. def delDiscoHandler(self,node='',jid=''):
  155. """ Unregisters DISCO handler that is resonsible for this
  156. node/jid combination. When handler is unregistered the branch
  157. is handled in the same way that it's parent branch from this moment.
  158. """
  159. node,key=self._traversePath(node,jid)
  160. if node:
  161. handler=node[key]
  162. del node[dict][node[str]]
  163. return handler
  164. def _DiscoveryHandler(self,conn,request):
  165. """ Servers DISCO iq request from the remote client.
  166. Automatically determines the best handler to use and calls it
  167. to handle the request. Used internally.
  168. """
  169. node=request.getQuerynode()
  170. if node:
  171. nodestr=node
  172. else:
  173. nodestr='None'
  174. handler=self.getDiscoHandler(node,request.getTo())
  175. if not handler:
  176. self.DEBUG("No Handler for request with jid->%s node->%s ns->%s"%(request.getTo().__str__().encode('utf8'),nodestr.encode('utf8'),request.getQueryNS().encode('utf8')),'error')
  177. conn.send(Error(request,ERR_ITEM_NOT_FOUND))
  178. raise NodeProcessed
  179. self.DEBUG("Handling request with jid->%s node->%s ns->%s"%(request.getTo().__str__().encode('utf8'),nodestr.encode('utf8'),request.getQueryNS().encode('utf8')),'ok')
  180. rep=request.buildReply('result')
  181. if node: rep.setQuerynode(node)
  182. q=rep.getTag('query')
  183. if request.getQueryNS()==NS_DISCO_ITEMS:
  184. # handler must return list: [{jid,action,node,name}]
  185. if type(handler)==dict: lst=handler['items']
  186. else: lst=handler(conn,request,'items')
  187. if lst==None:
  188. conn.send(Error(request,ERR_ITEM_NOT_FOUND))
  189. raise NodeProcessed
  190. for item in lst: q.addChild('item',item)
  191. elif request.getQueryNS()==NS_DISCO_INFO:
  192. if type(handler)==dict: dt=handler['info']
  193. else: dt=handler(conn,request,'info')
  194. if dt==None:
  195. conn.send(Error(request,ERR_ITEM_NOT_FOUND))
  196. raise NodeProcessed
  197. # handler must return dictionary:
  198. # {'ids':[{},{},{},{}], 'features':[fe,at,ur,es], 'xdata':DataForm}
  199. for id in dt['ids']: q.addChild('identity',id)
  200. for feature in dt['features']: q.addChild('feature',{'var':feature})
  201. if 'xdata' in dt: q.addChild(node=dt['xdata'])
  202. conn.send(rep)
  203. raise NodeProcessed