def get_body(self, lang=None): """Return the contents of the HTML body.""" if lang is None: lang = self.get_lang() bodies = self.xml.findall('{%s}body' % XHTML_NS) if lang == '*': result = OrderedDict() for body in bodies: body_lang = body.attrib.get('{%s}lang' % self.xml_ns, '') body_result = [] body_result.append(body.text if body.text else '') for child in body: body_result.append(tostring(child, xmlns=XHTML_NS)) body_result.append(body.tail if body.tail else '') result[body_lang] = ''.join(body_result) return result else: for body in bodies: if body.attrib.get('{%s}lang' % self.xml_ns, self.get_lang()) == lang: result = [] result.append(body.text if body.text else '') for child in body: result.append(tostring(child, xmlns=XHTML_NS)) result.append(body.tail if body.tail else '') return ''.join(result) return ''
def get(self): try: result = self["xep_0060"].get_item(self.pubsub_server, self.node, self.data) for item in result["pubsub"]["items"]["substanzas"]: print("Retrieved item %s: %s" % (item["id"], tostring(item["payload"]))) except: logging.error("Could not retrieve item %s from node %s" % (self.data, self.node))
def handle_xml(self, nodeid, itemid, elem): #print '-------------' if (nodeid not in nodes_seen): nodes_seen.append(nodeid) r = self['xep_0060'].get_item(self.pubsub, nodeid, 'storage') storage = '' if (r['pubsub']['items']['item']['payload']): for a in r['pubsub']['items']['item']['payload']: storage += tostring(a) if (ip not in storage): storage += "<address link='http://" + ip + ":4720' />" storage = "<addresses>" + storage + "</addresses>" #print "publish:", storage try: self['xep_0060'].publish(self.pubsub, nodeid, id='storage', payload=ET.fromstring(storage)) except sleekxmpp.exceptions.IqError: print "IqError: Publish to storage item failed. You are probably not the owner of this node..." if (elem.tag.split('}', 1)[-1] == 'transducerData'): attr = {} for pair in elem.items(): attr[pair[0]] = pair[1] #print attr dt = iso8601.parse_date(attr['timestamp']) t = time.mktime(dt.timetuple()) + (dt.microsecond / 1e6) #print attr['timestamp'] #print("%.9f" % t) if ((attr['name'] != 'none') and (attr['name'] != '')): add_to_json(nodeid, attr['name'], t, attr['value']) pass
def get(self): try: result = self['xep_0060'].get_item(self.pubsub_server, self.node, self.data) for item in result['pubsub']['items']['substanzas']: print('Retrieved item %s: %s' % (item['id'], tostring(item['payload']))) except: logging.error('Could not retrieve item %s from node %s' % (self.data, self.node))
def send_connect_ack(self, key, response, jid): (local_address, remote_address)=(key[0], key[2]) packet=format_header(local_address, remote_address, ElementTree.Element("connect_ack")) packet.attrib['xmlns']="hexchat:connect_ack" response_stanza=ElementTree.Element("response") response_stanza.text=response packet.append(response_stanza) if response=="success": aliases=self.get_aliases() packet=self.add_aliases(packet, aliases) logging.debug("%s:%d" % local_address + " sending result signal to %s:%d" % remote_address) bot=[bot for bot in self.bots if bot.boundjid.bare==jid.bare][0] iq=Iq() iq['to']=set(key[1]).pop() iq['from']=bot.boundjid.full iq['type']='result' iq.append(packet) str_data=tostring(iq.xml, top_level=True) bot.karma_lock.acquire() bot.set_karma(len(str_data)) bot.send_queue.put(str_data) if response=="success": return aliases
def send(self, data, aliases): selected_index=self.get_best_karma(aliases) selected_bot=self.bots[selected_index] data['from']=selected_bot.boundjid.full str_data = tostring(data.xml, top_level=True) num_bytes=len(str_data) selected_bot.set_karma(num_bytes) selected_bot.send_queue.put(str_data)
def pubsub_publish(self, msg): print("published") print('Published item %s to %s:' %(msg['pubsub_event']['items']['item']['id'], msg['pubsub_event']['items']['node'])) data = msg['pubsub_event']['items']['item']['payload'] if data is not None: print(tostring(data)) else: print('No item content')
def get_tasks(self): """ Return list of all available tasks """ Log.info("Looking for available tasks") for node in self._nodes: project_tag = self._nodes[node] result_items = self['xep_0060'].get_items(self._pubsub, node, max_items=self.MAX_ITEMS, block=True) items = result_items['pubsub']['items']['substanzas'] for item in items: yield item['id'], project_tag, tostring(item['payload'])
def send(self, body): # this horrible piece of code breaks xml syntax but does actually work... body = body.replace("\r", " \n") message = self.client.make_message(mto=self._to, mfrom=self._from, mbody=body) message['lang'] = None str_data = tostring(message.xml, xmlns=message.stream.default_ns, stream=message.stream, top_level=True) str_data = str_data.replace("&#13;", " ") return message.stream.send_raw(str_data)
def _publish(self, msg): """Handle receiving a publish item event.""" print('Published item %s to %s:' % ( msg['pubsub_event']['items']['item']['id'], msg['pubsub_event']['items']['node'])) data = msg['pubsub_event']['items']['item']['payload'] if data is not None: print(tostring(data)) else: print('No item content')
def _publish(self, msg): """Handle receiving a publish item event.""" print('Published item %s to %s:' % (msg['pubsub_event']['items']['item']['id'], msg['pubsub_event']['items']['node'])) data = msg['pubsub_event']['items']['item']['payload'] if data is not None: print(tostring(data)) else: print('No item content')
def get(self): try: result = self['xep_0060'].get_item(self.pubsub_server, self.node, self.data) for item in result['pubsub']['items']['substanzas']: print('Retrieved item %s:' % item['id']) data = item['payload'] if data.tag == '{urn:xmpp:json:0}json': print(json.dumps(json.loads(data.text), indent=2)) else: print(tostring(data)) except: logging.error('Could not retrieve item %s from node %s' % (self.data, self.node))
def _publish(self, msg): """Handle receiving a publish item event.""" print('Published item %s to %s:' % ( msg['pubsub_event']['items']['item']['id'], msg['pubsub_event']['items']['node'])) data = msg['pubsub_event']['items']['item']['payload'] if data is not None: if data.tag == '{urn:xmpp:json:0}json': print(json.dumps(json.loads(data.text), indent=2)) else: print(tostring(data)) else: print('No item content')
def _publish(self, msg): """Handle receiving a publish item event.""" print msg data = msg['pubsub_event']['items']['item']['payload'] str_data = tostring(data) begin = str_data.find('>') + 1 end = str_data.find('</test>') x = str_data[begin:end] if x == self.trigger: self.send_message(mto=self.sensor_bot_jid, mbody='SET ' + self.action, mtype='normal', mfrom=self.sender_jid)
def _handle_starttls(self, xml): """ Handle notification that the server supports TLS. Arguments: xml -- The STARTLS proceed element. """ if not self.authenticated and self.ssl_support: self.sendStreamPacket(tostring(xml)) return True else: log.warning("The module tlslite is required to log in" +\ " to some servers, and has not been found.") return False
def send_xml(self, data, mask=None, timeout=RESPONSE_TIMEOUT): """ Send an XML object on the stream, and optionally wait for a response. Arguments: data -- The XML object to send on the stream. mask -- Deprecated. An XML snippet matching the structure of the expected response. Execution will block in this thread until the response is received or a timeout occurs. timeout -- Time in seconds to wait for a response before continuing. Defaults to RESPONSE_TIMEOUT. """ return self.send(tostring(data), mask, timeout)
def sendStreamPacket(self, data, block=False): try: log.debug("SSEND: %s" % data) #SSEND means stream send :) if not block: self.socket.sendall(data.encode('utf-8')) else: waitfor = Waiter('IqWait_%s' % data['id'], MatcherId(data['id'])) self.register_handler(waitfor) self.socket.sendall(tostring(data.xml).encode('utf-8')) return waitfor.wait() except Exception as ex: logging.warning("SEND FAILED: %s\n%s", ex, data) if self.auto_reconnect: self.reconnect() else: self.disconnect(self)
def __spawn_event(self, xml): """ Analyze incoming XML stanzas and convert them into stanza objects if applicable and queue stream events to be processed by matching handlers. Arguments: xml -- The XML stanza to analyze. """ log.debug("RECV: %s" % tostring(xml, xmlns=self.default_ns, stream=self)) # Apply any preprocessing filters. xml = self.incoming_filter(xml) # Convert the raw XML object into a stanza object. If no registered # stanza type applies, a generic StanzaBase stanza will be used. stanza_type = StanzaBase for stanza_class in self.__root_stanza: if xml.tag == "{%s}%s" % (self.default_ns, stanza_class.name): stanza_type = stanza_class break stanza = stanza_type(self, xml) # Match the stanza against registered handlers. Handlers marked # to run "in stream" will be executed immediately; the rest will # be queued. unhandled = True for handler in self.__handlers: if handler.match(stanza): stanza_copy = stanza_type(self, copy.deepcopy(xml)) handler.prerun(stanza_copy) self.event_queue.put(('stanza', handler, stanza_copy)) try: if handler.check_delete(): self.__handlers.pop(self.__handlers.index(handler)) except: pass # not thread safe unhandled = False # Some stanzas require responses, such as Iq queries. A default # handler will be executed immediately for this case. if unhandled: stanza.unhandled()
def send_xml(self, data, mask=None, timeout=None, now=False): """ Send an XML object on the stream, and optionally wait for a response. Arguments: data -- The XML object to send on the stream. mask -- Deprecated. An XML snippet matching the structure of the expected response. Execution will block in this thread until the response is received or a timeout occurs. timeout -- Time in seconds to wait for a response before continuing. Defaults to RESPONSE_TIMEOUT. now -- Indicates if the send queue should be skipped, sending the stanza immediately. Useful mainly for stream initialization stanzas. Defaults to False. """ if timeout is None: timeout = self.response_timeout return self.send(tostring(data), mask, timeout, now)
def _publish(self, msg): """Handle receiving a publish item event.""" print('Published item %s to %s:' % (msg['pubsub_event']['items']['item']['id'], msg['pubsub_event']['items']['node'])) data = msg['pubsub_event']['items']['item']['payload'] msg_2 = {} if data is not None: str_data = tostring(data) erase = 'abc' while True: try: erase = re.search("(<.*?>)", str_data).group(1) except AttributeError: break str_data = str_data.replace(erase, '') msg_2['body'] = str_data # The 2 ways to insert new data in the sensor data table self.receive_m(msg_2) # 1) get data from notification #self.send_m() # 2) send get data and parse received message else: print('No item content')
def _publish(self, msg): """Handle receiving a publish item event.""" print('Published item %s to %s:' % ( msg['pubsub_event']['items']['item']['id'], msg['pubsub_event']['items']['node'])) data = msg['pubsub_event']['items']['item']['payload'] msg_2 = {} if data is not None: str_data = tostring(data) erase = 'abc' while True: try: erase = re.search("(<.*?>)", str_data).group(1) except AttributeError: break str_data = str_data.replace(erase, '') msg_2['body'] = str_data # The 2 ways to insert new data in the sensor data table self.receive_m(msg_2) # 1) get data from notification #self.send_m() # 2) send get data and parse received message else: print('No item content')
def _on_published(self, msg): """ A task was modified by a teammate """ task_id = msg['pubsub_event']['items']['item']['id'] raw_xml = tostring(msg['pubsub_event']['items']['item']['payload']) self._callback("set_task", task_id, raw_xml)
def _xml_string(stanza): return x.tostring(stanza.get_payload()[0])
def get_calendar(self, node): """ Return calendar for node """ item = self['xep_0060'].get_item(self._pubsub, node, 'calendar') item = ['pubsub']['items']['substanzas'][0]['payload'] return tostring(item)