Package xmpp :: Module browser
[hide private]
[frames] | no frames]

Source Code for Module xmpp.browser

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