3 ## Copyright (C) 2004 Alexey "Snake" Nezhdanov
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)
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.
15 # $Id: browser.py,v 1.12 2007/05/13 17:55:14 normanr Exp $
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.
22 Such functionality is achieved via registering "DISCO handlers" that are
23 automatically called when user requests some node of your disco tree.
26 from dispatcher
import *
27 from client
import PlugIn
29 class Browser(PlugIn
):
30 """ WARNING! This class is for components only. It will not work in client mode!
32 Standart xmpppy class that is ancestor of PlugIn and can be attached
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()
45 item['jid']='catalog.shakespeare.lit'
47 item['name']='Books by and about Shakespeare'
50 item['jid']='catalog.shakespeare.lit'
51 item['node']='clothing'
52 item['name']='Wear your literary taste with pride'
55 item['jid']='catalog.shakespeare.lit'
57 item['name']='Music from the time of Shakespeare'
59 info={'ids':[], 'features':[]}
60 b.setDiscoHandler({'items':items,'info':info})
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()
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})
81 """Initialises internal variables. Used internally."""
84 self
._exported
_methods
=[]
85 self
._handlers
={'':{}}
87 def plugin(self
, owner
):
88 """ Registers it's own iq handlers in your application dispatcher instance.
90 owner
.RegisterHandler('iq',self
._DiscoveryHandler
,typ
='get',ns
=NS_DISCO_INFO
)
91 owner
.RegisterHandler('iq',self
._DiscoveryHandler
,typ
='get',ns
=NS_DISCO_ITEMS
)
94 """ Unregisters browser's iq handlers from your application dispatcher instance.
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
)
99 def _traversePath(self
,node
,jid
,set=0):
100 """ Returns dictionary and key or None,None
101 None - root node (w/o "node" attribute)
104 Set returns '' or None as the key
105 get returns '' or None as the key or None as the dict.
107 if self
._handlers
.has_key(jid
): cur
=self
._handlers
[jid
]
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('/')
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"
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.
130 cl.Browser.setDiscoHandler(someDict,node,jid)
132 cl.Browser.setDiscoHandler(someDISCOHandler,node,jid)
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'}
144 {'category':'category1','type':'type1','name':'name1'},
145 {'category':'category2','type':'type2','name':'name2'},
146 {'category':'category3','type':'type3','name':'name3'},
148 'features':['feature1','feature2','feature3','feature4'],
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.
160 self
.DEBUG('Registering handler %s for "%s" node->%s'%(handler
,jid
,node
), 'info')
161 node
,key
=self
._traversePath
(node
,jid
,1)
164 def getDiscoHandler(self
,node
='',jid
=''):
165 """ Returns the previously registered DISCO handler
166 that is resonsible for this node/jid combination.
168 node
,key
=self
._traversePath
(node
,jid
)
169 if node
: return node
[key
]
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.
176 node
,key
=self
._traversePath
(node
,jid
)
179 del node
[dict][node
[str]]
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.
187 node
=request
.getQuerynode()
192 handler
=self
.getDiscoHandler(node
,request
.getTo())
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
))
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')
206 conn
.send(Error(request
,ERR_ITEM_NOT_FOUND
))
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')
213 conn
.send(Error(request
,ERR_ITEM_NOT_FOUND
))
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'])