2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2013 INRIA
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 3 of the License, or
8 # (at your option) any later version.
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 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19 # Julien Tribino <julien.tribino@inria.fr>
21 from nepi.util.logger import Logger
24 from sleekxmpp.exceptions import IqError, IqTimeout
26 import xml.etree.ElementTree as ET
28 # inherit from BaseXmpp and XMLStream classes
29 class OMFClient(sleekxmpp.ClientXMPP, Logger):
31 .. class:: Class Args :
33 :param jid: Jabber Id (= Xmpp Slice + Date)
35 :param password: Jabber Password (= Xmpp Password)
40 This class is an XMPP Client with customized method
44 def __init__(self, jid, password):
47 :param jid: Jabber Id (= Xmpp Slice + Date)
49 :param password: Jabber Password (= Xmpp Password)
54 Logger.__init__(self, "OMFClient")
56 sleekxmpp.ClientXMPP.__init__(self, jid, password)
58 self._registered = False
61 self.register_plugin('xep_0077') # In-band registration
62 self.register_plugin('xep_0030')
63 self.register_plugin('xep_0059')
64 self.register_plugin('xep_0060') # PubSub
66 self.add_event_handler("session_start", self.start)
67 self.add_event_handler("register", self.register)
68 self.add_event_handler("pubsub_publish", self.handle_omf_message)
72 """ Check if the client is ready
77 def start(self, event):
78 """ Send presence to the Xmppp Server. This function is called directly by the sleekXmpp library
83 self._server = "pubsub.%s" % self.boundjid.domain
85 def register(self, iq):
86 """ Register to the Xmppp Server. This function is called directly by the sleekXmpp library
90 msg = " %s already registered!" % self.boundjid
96 resp['register']['username'] = self.boundjid.user
97 resp['register']['password'] = self.password
101 msg = " Account created for %s!" % self.boundjid
103 self._registered = True
105 msg = " Could not register account: %s" % e.iq['error']['text']
108 msg = " No response from server."
111 def unregister(self):
112 """ Unregister from the Xmppp Server.
116 self.plugin['xep_0077'].cancel_registration(
117 ifrom=self.boundjid.full)
118 msg = " Account unregistered for %s!" % self.boundjid
121 msg = " Could not unregister account: %s" % e.iq['error']['text']
124 msg = " No response from server."
128 """ Get all the nodes of the Xmppp Server.
132 result = self['xep_0060'].get_nodes(self._server)
133 for item in result['disco_items']['items']:
134 msg = ' - %s' % str(item)
138 error = traceback.format_exc()
139 msg = 'Could not retrieve node list.\ntraceback:\n%s' % error
142 def subscriptions(self):
143 """ Get all the subscriptions of the Xmppp Server.
147 result = self['xep_0060'].get_subscriptions(self._server)
149 for node in result['node']:
150 msg = ' - %s' % str(node)
154 error = traceback.format_exc()
155 msg = ' Could not retrieve subscriptions.\ntraceback:\n%s' % error
158 def create(self, node):
159 """ Create the topic corresponding to the node
161 :param node: Name of the topic, corresponding to the node (ex : omf.plexus.wlab17)
165 msg = " Create Topic : " + node
168 config = self['xep_0004'].makeForm('submit')
169 config.add_field(var='pubsub#node_type', value='leaf')
170 config.add_field(var='pubsub#notify_retract', value='0')
171 config.add_field(var='pubsub#publish_model', value='open')
172 config.add_field(var='pubsub#persist_items', value='1')
173 config.add_field(var='pubsub#max_items', value='1')
174 config.add_field(var='pubsub#title', value=node)
177 self['xep_0060'].create_node(self._server, node, config = config)
179 error = traceback.format_exc()
180 msg = ' Could not create topic: %s\ntraceback:\n%s' % (node, error)
183 def delete(self, node):
184 """ Delete the topic corresponding to the node
186 :param node: Name of the topic, corresponding to the node (ex : omf.plexus.wlab17)
190 # To check if the queue are well empty at the end
191 #print " length of the queue : " + str(self.send_queue.qsize())
192 #print " length of the queue : " + str(self.event_queue.qsize())
194 self['xep_0060'].delete_node(self._server, node)
195 msg = ' Deleted node: %s' % node
198 error = traceback.format_exc()
199 msg = ' Could not delete topic: %s\ntraceback:\n%s' % (node, error)
202 def publish(self, data, node):
203 """ Publish the data to the corresponding topic
205 :param data: Data that will be published
207 :param node: Name of the topic
212 msg = " Publish to Topic : " + node
215 result = self['xep_0060'].publish(self._server,node,payload=data)
216 # id = result['pubsub']['publish']['item']['id']
217 # print('Published at item id: %s' % id)
219 error = traceback.format_exc()
220 msg = ' Could not publish to: %s\ntraceback:\n%s' % (node, error)
226 :param data: data from which the items will be get back
232 result = self['xep_0060'].get_item(self._server, self.boundjid,
234 for item in result['pubsub']['items']['substanzas']:
235 msg = 'Retrieved item %s: %s' % (item['id'], tostring(item['payload']))
238 error = traceback.format_exc()
239 msg = ' Could not retrieve item %s from topic %s\ntraceback:\n%s' \
240 % (data, self.boundjid, error)
243 def retract(self, data):
246 :param data: data from which the item will be retracted
251 result = self['xep_0060'].retract(self._server, self.boundjid, data)
252 msg = ' Retracted item %s from topic %s' % (data, self.boundjid)
255 error = traceback.format_exc()
256 msg = 'Could not retract item %s from topic %s\ntraceback:\n%s' \
257 % (data, self.boundjid, error)
261 """ Purge the information in the server
265 result = self['xep_0060'].purge(self._server, self.boundjid)
266 msg = ' Purged all items from topic %s' % self.boundjid
269 error = traceback.format_exc()
270 msg = ' Could not purge items from topic %s\ntraceback:\n%s' \
271 % (self.boundjid, error)
274 def subscribe(self, node):
275 """ Subscribe to a topic
277 :param node: Name of the topic
282 result = self['xep_0060'].subscribe(self._server, node)
283 msg = ' Subscribed %s to topic %s' \
284 % (self.boundjid.user, node)
288 error = traceback.format_exc()
289 msg = ' Could not subscribe %s to topic %s\ntraceback:\n%s' \
290 % (self.boundjid.bare, node, error)
293 def unsubscribe(self, node):
294 """ Unsubscribe to a topic
296 :param node: Name of the topic
301 result = self['xep_0060'].unsubscribe(self._server, node)
302 msg = ' Unsubscribed %s from topic %s' % (self.boundjid.bare, node)
305 error = traceback.format_exc()
306 msg = ' Could not unsubscribe %s from topic %s\ntraceback:\n%s' \
307 % (self.boundjid.bare, node, error)
310 def _check_for_tag(self, root, namespaces, tag):
311 """ Check if an element markup is in the ElementTree
313 :param root: Root of the tree
314 :type root: ElementTree Element
315 :param namespaces: Namespaces of the element
316 :type namespaces: str
317 :param tag: Tag that will search in the tree
321 for element in root.iter(namespaces+tag):
327 def _check_output(self, root, namespaces):
328 """ Check the significative element in the answer and display it
330 :param root: Root of the tree
331 :type root: ElementTree Element
332 :param namespaces: Namespaces of the tree
333 :type namespaces: str
336 fields = ["TARGET", "REASON", "PATH", "APPID", "VALUE"]
339 msg = self._check_for_tag(root, namespaces, elt)
341 response = response + " " + msg.text + " :"
342 deb = self._check_for_tag(root, namespaces, "MESSAGE")
344 msg = response + " " + deb.text
349 def handle_omf_message(self, iq):
350 """ Handle published/received message
352 :param iq: Stanzas that is currently published/received
356 namespaces = "{http://jabber.org/protocol/pubsub}"
357 for i in iq['pubsub_event']['items']:
358 root = ET.fromstring(str(i))
359 self._check_output(root, namespaces)