def open_selected_item(self): """ displays the currently selected item in the item view window """ selected_item = self.get_item_by_id(self.get_selected_item_id()) if not selected_item: return log.debug('Content: %s'%ET.tostring(selected_item.content)) entry = atom_parser.parse_atom_entry(selected_item.content) if not entry: self.item_viewer._text = str(ET.tostring(selected_item.content)) else: self.item_viewer._text = \ """\x193Title:\x19o %(title)s \x193Author:\x19o %(author_name)s (%(author_uri)s) %(dates)s\x193Link:\x19o %(link)s \x193Summary:\x19o %(summary)s """ % {'title': entry.get('title') or '', 'author_name': entry['author'].get('name') or '', 'author_uri': entry['author'].get('uri') or '', 'link': entry.get('link_href') or '', 'summary': entry.get('summary') or '', 'dates': '\x193Published:\x19o %(published)s\n%(updated)s' % {'published':entry.get('published') or '', 'updated': '' if (entry.get('updated') is None) or (entry.get('published') == entry.get('updated')) else '\x193Published:\x19o %s\n' % entry.get('updated')} } self.item_viewer.rebuild_text() return True
def copy_dialog_id(self, origin_message, new_message): """ Copy a dialog_id from a received message to a replay message """ dialog_id_in = origin_message.xml.find( '{jabber:client}extraParams/{jabber:client}dialog_id') if dialog_id_in is not None: extra_params_out = ET.Element('{jabber:client}extraParams') dialog_id_out = ET.Element('{}dialog_id') dialog_id_out.text = dialog_id_in.text extra_params_out.append(dialog_id_out) new_message.append(extra_params_out)
def get_xhtml(self, element=True): lines = self.text.split('\n') xhtml = ET.Element('span') if self.font: xhtml.set('style', 'font-family: ' + self.font + ';') for subline in lines[:-1]: p = ET.SubElement(xhtml, 'p') p.text = subline ET.SubElement(xhtml, 'br') p = ET.SubElement(xhtml, 'p') p.text = lines[-1] if element: return xhtml return ET.tostring(xhtml)
def invite(self, room, jid, reason='', mfrom=''): """ Invite a jid to a room.""" msg = self.xmpp.makeMessage(room) msg['from'] = mfrom x = ET.Element('{http://jabber.org/protocol/muc#user}x') invite = ET.Element('{http://jabber.org/protocol/muc#user}invite', {'to': jid}) if reason: rxml = ET.Element('{http://jabber.org/protocol/muc#user}reason') rxml.text = reason invite.append(rxml) x.append(invite) msg.append(x) self.xmpp.send(msg)
def add_identity(self, category, itype, name=None, lang=None): """ Add a new identity element. Each identity must be unique in terms of all four identity components. Multiple, identical category/type pairs are allowed only if the xml:lang values are different. Likewise, multiple category/type/xml:lang pairs are allowed so long as the names are different. In any case, a category and type are required. Arguments: category -- The general category to which the agent belongs. itype -- A more specific designation with the category. name -- Optional human readable name for this identity. lang -- Optional standard xml:lang value. """ identity = (category, itype, lang) if identity not in self._identities: self._identities.add(identity) id_xml = ET.Element('{%s}identity' % self.namespace) id_xml.attrib['category'] = category id_xml.attrib['type'] = itype if lang: id_xml.attrib['{%s}lang' % self.xml_ns] = lang if name: id_xml.attrib['name'] = name self.xml.append(id_xml) return True return False
def fault2xml(fault): value = dict() value['faultCode'] = fault['code'] value['faultString'] = fault['string'] fault = ET.Element("fault", {'xmlns': _namespace}) fault.append(_py2xml((value))) return fault
def set_items(self, values): self.del_items() for jid in values: if jid: item = ET.Element('{%s}item' % self.namespace) item.attrib['jid'] = JID(jid).full self.xml.append(item)
def set_calendar(self, node, calendar_str): """ Set calendar of node """ payload = ET.fromstring(calendar_str) self['xep_0060'].publish(self._pubsub, node, id='calendar', payload=payload)
def publish(self, node, data): payload = ET.fromstring("<test xmlns='test'>{}</test>".format(data)) try: self['xep_0060'].publish(self.pubsub_server, node, payload=payload) except Exception as e: log.error('pubsub: could not publish to: {}'.format(node)) log.error('Exception "{}" of type {}'.format(e, type(e)))
def add_game(self, data): """Add a game to the extension. Arguments: data (dict): game data to add """ self.xml.append(ET.Element('game', data))
def main(i_msg, i_plr, i_latency): global payload global msgPaySize global plr global xmpp global results global latency ###Set the CPU measurement### q = Queue.Queue() start_new_thread(measure_cpu, (results, q)) ###Set global variables and constants### payload = ET.fromstring("<test xmlns = 'test'>%s</test>" % i_msg) msgPaySize = len(i_msg) plr = i_plr latency = i_latency ###Connect to the broker and set handlers### xmpp = sleekxmpp.ClientXMPP(jid, pw) xmpp.add_event_handler("session_start", on_start) xmpp.add_event_handler("pubsub_publish", on_receive) xmpp.register_plugin('xep_0004') ###Dataforms xmpp.register_plugin('xep_0060') ###PubSub xmpp.connect() xmpp.process(block=True) if flagEnd == 'X': return results
def add_item( self, player, rating, highest_rating=0, # pylint: disable=too-many-arguments rank=0, total_games_played=0, wins=0, losses=0): """Add an item to the extension. Arguments: player (str): Name of the player rating (int): Current rating of the player highest_rating (int): Highest rating the player had rank (int): Rank of the player total_games_played (int): Total number of games the player played wins (int): Number of won games the player had losses (int): Number of lost games the player had """ item_xml = ET.Element( 'profile', { 'player': player, 'rating': str(rating), 'highestRating': str(highest_rating), 'rank': str(rank), 'totalGamesPlayed': str(total_games_played), 'wins': str(wins), 'losses': str(losses) }) self.xml.append(item_xml)
def _personRefToETree(self, parent, nodeName, line): node = ET.SubElement(parent, "{{{0}}}{1}".format(self.xmlns, nodeName)) components = line.split(" ") email = components[-3] name = " ".join(components[1:-3]) node.text = name node.set("email", email)
def _submit(self, repoName, refPath): tree = ET.Element("{{{0}}}git".format(self.xmlns)) repo = ET.SubElement(tree, "{{{0}}}repository".format(self.xmlns)) repo.text = repoName ref = ET.SubElement(tree, "{{{0}}}ref".format(self.xmlns)) ref.text = refPath try: with open(refPath, "r") as f: sha = f.read() except FileNotFoundError: pass else: newRef = ET.SubElement(tree, "{{{0}}}new-ref".format(self.xmlns)) newRef.set("sha", sha) self._refToETree(newRef, refPath) self.pubsub.publish(self.FEED, self.PUBSUB, payload=tree, block=True)
def testGetItems(self): """Test retrieving items from a roster stanza.""" xml_string = """ <iq> <query xmlns="jabber:iq:roster"> <item jid="*****@*****.**" name="User" subscription="both"> <group>Friends</group> <group>Coworkers</group> </item> <item jid="*****@*****.**" name="Other User" subscription="both" /> </query> </iq> """ iq = self.Iq(ET.fromstring(xml_string)) expected = { "*****@*****.**": { "name": "User", "subscription": "both", "ask": "", "approved": "", "groups": ["Friends", "Coworkers"], }, "*****@*****.**": { "name": "Other User", "subscription": "both", "ask": "", "approved": "", "groups": [], }, } debug = "Roster items don't match after retrieval." debug += "\nReturned: %s" % str(iq["roster"]["items"]) debug += "\nExpected: %s" % str(expected) self.failUnless(iq["roster"]["items"] == expected, debug)
def add_reported(self, var, ftype=None, label='', desc='', **kwargs): kwtype = kwargs.get('type', None) if kwtype is None: kwtype = ftype reported = self.xml.find('{%s}reported' % self.namespace) if reported is None: reported = ET.Element('{%s}reported' % self.namespace) self.xml.append(reported) fieldXML = ET.Element('{%s}field' % FormField.namespace) reported.append(fieldXML) field = FormField(xml=fieldXML) field['var'] = var field['type'] = kwtype field['label'] = label field['desc'] = desc return field
def start_activity(self, activity_id): """Starts an activity. Args: activity_id: An int or string identifying the activity to start Returns: True if activity started, otherwise False """ iq_cmd = self.Iq() iq_cmd['type'] = 'get' action_cmd = ET.Element('oa') action_cmd.attrib['xmlns'] = 'connect.logitech.com' action_cmd.attrib['mime'] = ('harmony.engine?startactivity') cmd = 'activityId=' + str(activity_id) + ':timestamp=0' action_cmd.text = cmd iq_cmd.set_payload(action_cmd) try: result = iq_cmd.send(block=True) except Exception: logger.info('XMPP timeout, reattempting') result = iq_cmd.send(block=True) payload = result.get_payload() assert len(payload) == 1 action_cmd = payload[0] if action_cmd.text == None: return True else: return False
def get_config(self): """Retrieves the Harmony device configuration. Returns: A nested dictionary containing activities, devices, etc. """ iq_cmd = self.Iq() iq_cmd['type'] = 'get' action_cmd = ET.Element('oa') action_cmd.attrib['xmlns'] = 'connect.logitech.com' action_cmd.attrib['mime'] = ( 'vnd.logitech.harmony/vnd.logitech.harmony.engine?config') iq_cmd.set_payload(action_cmd) result = iq_cmd.send(block=True) payload = result.get_payload() assert len(payload) == 1 action_cmd = payload[0] assert action_cmd.attrib['errorcode'] == '200' device_list = action_cmd.text config_dict = json.loads(device_list) s = '' for activity in config_dict['activity']: if 'activityOrder' in activity: s += 'Activity: ' + activity['label'] + ', #' + repr( activity['activityOrder'] ) + ', id: ' + activity['id'] + '\n' else: s += 'Activity: ' + activity['label'] + ', id: ' + activity[ 'id'] + '\n' for device in config_dict['device']: s += 'Device: ' + device['label'] + ', id: ' + device['id'] + '\n' return s
def main(i_msg, i_plr, i_latency): ###Globals### global payload global msgPaySize global plr global xmpp global g_msg global latency payload = ET.fromstring("<test xmlns = 'test'>%s</test>" % i_msg) msgPaySize = len(i_msg) plr = i_plr g_msg = i_msg latency = i_latency ###Connect to the broker and set handlers### xmpp = sleekxmpp.ClientXMPP(jid, pw) xmpp.add_event_handler("session_start", on_start) xmpp.add_event_handler("pubsub_publish", on_receive) xmpp.register_plugin('xep_0004') ###Dataforms xmpp.register_plugin('xep_0060') ###PubSub try: xmpp.connect() except: print('Cannot connect to the broker. Test failed!') sys.exit() xmpp.process(block=True) if flagEnd == 'X': return results
def main(i_msg, i_plr, i_latency): global payload global msgPaySize global plr global xmpp global latency ###Set global variables and constants### payload = ET.fromstring("<test xmlns = 'test'>%s</test>" % i_msg) msgPaySize = len(i_msg) plr = i_plr latency = i_latency ###Connect to the broker and set handlers### xmpp = sleekxmpp.ClientXMPP(jid, pw) xmpp.add_event_handler("session_start", on_start) xmpp.add_event_handler("message", on_message) xmpp.register_plugin('xep_0004') ###Dataforms xmpp.register_plugin('xep_0060') #PubSub xmpp.connect() xmpp.process(block=True) if flagEnd == 'X': return results
def send_command(self, device, command): """Send a simple command to the Harmony Hub. Args: device_id (str): Device ID from Harmony Hub configuration to control command (str): Command from Harmony Hub configuration to control Returns: None if successful """ iq_cmd = self.Iq() iq_cmd['type'] = 'get' iq_cmd['id'] = '5e518d07-bcc2-4634-ba3d-c20f338d8927-2' action_cmd = ET.Element('oa') action_cmd.attrib['xmlns'] = 'connect.logitech.com' action_cmd.attrib['mime'] = ( 'vnd.logitech.harmony/vnd.logitech.harmony.engine?holdAction') action_cmd.text = 'action={"type"::"IRCommand","deviceId"::"' + device + '","command"::"' + command + '"}:status=press' iq_cmd.set_payload(action_cmd) result = iq_cmd.send(block=False) action_cmd.attrib['mime'] = ( 'vnd.logitech.harmony/vnd.logitech.harmony.engine?holdAction') action_cmd.text = 'action={"type"::"IRCommand","deviceId"::"' + device + '","command"::"' + command + '"}:status=release' iq_cmd.set_payload(action_cmd) result = iq_cmd.send(block=False) return result
def _handle_bind_resource(self, xml): """ Handle requesting a specific resource. Arguments: xml -- The bind feature element. """ log.debug("Requesting resource: %s" % self.boundjid.resource) xml.clear() iq = self.Iq(stype='set') if self.boundjid.resource: res = ET.Element('resource') res.text = self.boundjid.resource xml.append(res) iq.append(xml) response = iq.send() bind_ns = 'urn:ietf:params:xml:ns:xmpp-bind' self.set_jid( response.xml.find('{%s}bind/{%s}jid' % (bind_ns, bind_ns)).text) self.bound = True log.info("Node set to: %s" % self.boundjid.fulljid) session_ns = 'urn:ietf:params:xml:ns:xmpp-session' if "{%s}session" % session_ns not in self.features or self.bindfail: log.debug("Established Session") self.sessionstarted = True self.session_started_event.set() self.event("session_start")
def change_channel(self, channel): """Changes a channel. Args: channel: Channel number Returns: An HTTP 200 response (hopefully) """ iq_cmd = self.Iq() iq_cmd['type'] = 'get' action_cmd = ET.Element('oa') action_cmd.attrib['xmlns'] = 'connect.logitech.com' action_cmd.attrib['mime'] = ('harmony.engine?changeChannel') cmd = 'channel=' + str(channel) + ':timestamp=0' action_cmd.text = cmd iq_cmd.set_payload(action_cmd) try: result = iq_cmd.send(block=True) except Exception: logger.info('XMPP timeout, reattempting') result = iq_cmd.send(block=True) payload = result.get_payload() assert len(payload) == 1 action_cmd = payload[0] if action_cmd.text == None: return True else: return False
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_config(self): """Retrieves the Harmony device configuration. Returns: A nested dictionary containing activities, devices, etc. """ iq_cmd = self.Iq() iq_cmd['type'] = 'get' action_cmd = ET.Element('oa') action_cmd.attrib['xmlns'] = 'connect.logitech.com' action_cmd.attrib['mime'] = ( 'vnd.logitech.harmony/vnd.logitech.harmony.engine?config') iq_cmd.set_payload(action_cmd) retries = 3 attempt = 0 for _ in range(retries): try: result = iq_cmd.send(block=True) break except Exception: logger.critical('XMPP timeout, reattempting') attempt += 1 pass if attempt == 3: raise ValueError('XMPP timeout with hub') payload = result.get_payload() assert len(payload) == 1 action_cmd = payload[0] assert action_cmd.attrib['errorcode'] == '200' device_list = action_cmd.text return json.loads(device_list)
def del_chat_state(self): parent = self.parent() for state in self.states: state_xml = parent.find('{%s}%s' % (self.namespace, state)) if state_xml is not None: self.xml = ET.Element('') parent.xml.remove(state_xml)
def add_command(self, command): """Add a command to the extension. Arguments: command (str): Command to add """ self.xml.append(ET.fromstring('<command>%s</command>' % command))
def exception(self, e): """ Create and send an error reply. Typically called when an event handler raises an exception. The error's type and text content are based on the exception object's type and content. Overrides StanzaBase.exception. Arguments: e -- Exception object """ self.reply() if isinstance(e, XMPPError): # We raised this deliberately self['error']['condition'] = e.condition self['error']['text'] = e.text if e.extension is not None: # Extended error tag extxml = ET.Element("{%s}%s" % (e.extension_ns, e.extension), e.extension_args) self['error'].append(extxml) self['error']['type'] = e.etype else: # We probably didn't raise this on purpose, so send a traceback self['error']['condition'] = 'undefined-condition' if sys.version_info < (3, 0): self['error']['text'] = "SleekXMPP got into trouble." else: self['error']['text'] = traceback.format_tb(e.__traceback__) log.exception('Error handling {%s}%s stanza' % (self.namespace, self.name)) self.send()
def get_current_activity(self): """Retrieves the current activity ID. Returns: A int with the current activity ID. """ iq_cmd = self.Iq() iq_cmd['type'] = 'get' action_cmd = ET.Element('oa') action_cmd.attrib['xmlns'] = 'connect.logitech.com' action_cmd.attrib['mime'] = ( 'vnd.logitech.harmony/vnd.logitech.harmony.engine?getCurrentActivity' ) iq_cmd.set_payload(action_cmd) try: result = iq_cmd.send(block=True) except Exception: logger.info('XMPP timeout, reattempting') result = iq_cmd.send(block=True) payload = result.get_payload() assert len(payload) == 1 action_cmd = payload[0] assert action_cmd.attrib['errorcode'] == '200' activity = action_cmd.text.split("=") return int(activity[1])
def set_binval(self, value): self.del_binval() parent = self.parent() if value: xml = ET.Element('{%s}BINVAL' % self.namespace) xml.text = bytes(base64.b64encode(value)).decode('utf-8') parent.append(xml)
def _handle_battery_info(self, iq): try: self.battery_status = float(iq['power']) / 100 logging.debug("*** battery_status = {:.0%}".format( self.battery_status)) except ValueError: logging.warning("couldn't parse battery status " + ET.tostring(iq))
def testGetItems(self): """Test retrieving items from a roster stanza.""" xml_string = """ <iq> <query xmlns="jabber:iq:roster"> <item jid="*****@*****.**" name="User" subscription="both"> <group>Friends</group> <group>Coworkers</group> </item> <item jid="*****@*****.**" name="Other User" subscription="both" /> </query> </iq> """ iq = self.Iq(ET.fromstring(xml_string)) expected = { '*****@*****.**': { 'name': 'User', 'subscription': 'both', 'ask': '', 'approved': '', 'groups': ['Friends', 'Coworkers']}, '*****@*****.**': { 'name': 'Other User', 'subscription': 'both', 'ask': '', 'approved': '', 'groups': []}} debug = "Roster items don't match after retrieval." debug += "\nReturned: %s" % str(iq['roster']['items']) debug += "\nExpected: %s" % str(expected) self.failUnless(iq['roster']['items'] == expected, debug)
def broadcast(self, payload): """ Broadcasts via XMPP the payload. The payload can be a list of Item or a single item. """ # Transforms all Item objects to a single XML string xmls = "" if isinstance(payload, dict): xmls = payload.to_xml() elif isinstance(payload, list): for elem in payload: xmls += elem.to_xml() # Transforms the XML string to a valid sleekxmpp XML element xml_element = ET.fromstring(xmls) try: result = self.pubsub.publish(self.config.server_host, self.config.node_name, payload=xml_element) id = result['pubsub']['publish']['item']['id'] self.logger.debug('Published at item id: %s' % id) except: self.logger.error('Could not publish to: %s' % self.config.node_name)
def publish(self): payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data) try: result = self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload) id = result['pubsub']['publish']['item']['id'] print('Published at item id: %s' % id) except: logging.error('Could not publish to: %s' % self.node)
def publish(self): payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data) try: result = self["xep_0060"].publish(self.pubsub_server, self.node, payload=payload) id = result["pubsub"]["publish"]["item"]["id"] print("Published at item id: %s" % id) except: logging.error("Could not publish to: %s" % self.node)
def publish(self, event, radius): from events.api.resources.jabber import EventResource resource = EventResource() event_dict = resource.full_dehydrate(resource.build_bundle(obj=event)) event_dict.data['radius'] = radius str_payload = resource.serialize(None, event_dict, 'application/xml') payload = ET.fromstring(str_payload) if logger.level is logging.DEBUG: lxml_payload = etree.fromstring(ET.tostring(payload)) str_payload = etree.tostring(lxml_payload, pretty_print=True) logger.debug('sending publish message with payload:\n%s', str_payload) self._pubsub.publish(self.config.pubsub_server, self.config.node_name, payload=payload)
def set_nick(self, nick): # set bla baaasa vcard = ET.fromstring(""" <vCard xmlns="vcard-temp"> <FN>Dr. Mundo</FN> <NICKNAME>Pussy Boy</NICKNAME> </vCard> """) self['xep_0054'].publish_vcard(vcard)
def testGetFirstIndex(self): xml_string = """ <set xmlns="http://jabber.org/protocol/rsm"> <first index="10">id</first> </set> """ s = Set(ET.fromstring(xml_string)) expected = '10' self.failUnless(s['first_index'] == expected)
def testMailBox(self): """Testing reading from Gmail mailbox result""" # Use the example from Google's documentation at # http://code.google.com/apis/talk/jep_extensions/gmail.html#notifications xml = ET.fromstring(""" <iq type="result"> <mailbox xmlns="google:mail:notify" result-time='1118012394209' url='http://mail.google.com/mail' total-matched='95' total-estimate='0'> <mail-thread-info tid='1172320964060972012' participation='1' messages='28' date='1118012394209' url='http://mail.google.com/mail?view=cv'> <senders> <sender name='Me' address='*****@*****.**' originator='1' /> <sender name='Benvolio' address='*****@*****.**' /> <sender name='Mercutio' address='*****@*****.**' unread='1'/> </senders> <labels>act1scene3</labels> <subject>Put thy rapier up.</subject> <snippet>Ay, ay, a scratch, a scratch; marry, 'tis enough.</snippet> </mail-thread-info> </mailbox> </iq> """) iq = self.Iq(xml=xml) mailbox = iq['mailbox'] self.failUnless(mailbox['result-time'] == '1118012394209', "result-time doesn't match") self.failUnless(mailbox['url'] == 'http://mail.google.com/mail', "url doesn't match") self.failUnless(mailbox['matched'] == '95', "total-matched incorrect") self.failUnless(mailbox['estimate'] == False, "total-estimate incorrect") self.failUnless(len(mailbox['threads']) == 1, "could not extract message threads") thread = mailbox['threads'][0] self.failUnless(thread['tid'] == '1172320964060972012', "thread tid doesn't match") self.failUnless(thread['participation'] == '1', "thread participation incorrect") self.failUnless(thread['messages'] == '28', "thread message count incorrect") self.failUnless(thread['date'] == '1118012394209', "thread date doesn't match") self.failUnless(thread['url'] == 'http://mail.google.com/mail?view=cv', "thread url doesn't match") self.failUnless(thread['labels'] == 'act1scene3', "thread labels incorrect") self.failUnless(thread['subject'] == 'Put thy rapier up.', "thread subject doesn't match") self.failUnless(thread['snippet'] == "Ay, ay, a scratch, a scratch; marry, 'tis enough.", "snippet doesn't match") self.failUnless(len(thread['senders']) == 3, "could not extract senders") sender1 = thread['senders'][0] self.failUnless(sender1['name'] == 'Me', "sender name doesn't match") self.failUnless(sender1['address'] == '*****@*****.**', "sender address doesn't match") self.failUnless(sender1['originator'] == True, "sender originator incorrect") self.failUnless(sender1['unread'] == False, "sender unread incorrectly True") sender2 = thread['senders'][2] self.failUnless(sender2['unread'] == True, "sender unread incorrectly False")
def set_body(self, content, lang=None): if lang is None: lang = self.get_lang() self.del_body(lang) if lang == '*': for sublang, subcontent in content.items(): self.set_body(subcontent, sublang) else: if isinstance(content, type(ET.Element('test'))): content = ET.tostring(content) else: content = str(content) header = '<body xmlns="%s"' % XHTML_NS if lang: header = '%s xml:lang="%s"' % (header, lang) content = '%s>%s</body>' % (header, content) xhtml = ET.fromstring(content) self.xml.append(xhtml)
def testGetBeforeVal(self): xml_string = """ <set xmlns="http://jabber.org/protocol/rsm"> <before>id</before> </set> """ s = Set(ET.fromstring(xml_string)) expected = 'id' self.failUnless(s['before'] == expected)
def get_xhtml(self, element=True): xhtml = ET.XML(markdown_to_xhtml(self.text)) if self.font: span = ET.Element('span') span.set('style', 'font-family: ' + self.font + ';') span.append(xhtml) xhtml = span if element: return xhtml return ET.tostring(xhtml)
def load_ballot(self, name, quorum): self.quorum = quorum self.current_ballot = name with open('%s/ballot_%s.xml' % (self.data_dir, name)) as ballot_file: self._ballot_data = Ballot(xml=ET.fromstring(ballot_file.read())) try: os.makedirs('%s/results/%s' % (self.data_dir, name)) except: pass
def publish(self, data): #payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data) #--- Warning: publish will fail if data does not contain XML elements ---# payload = ET.fromstring(data) try: result = self['xep_0060'].publish(self.pubsub_server, self.node, id=self.itemid, payload=payload) id = result['pubsub']['publish']['item']['id'] print('Published "%s" at item id: %s' % (data, id)) except: logging.error('Could not publish to: %s' % self.node)
def load_config(filename): """ Create a configuration stanza object from the given file's contents. Arguments: filename -- Name of the config file. """ with open(filename, 'r+') as conf_file: data = "\n".join([line for line in conf_file]) config = Config(xml=ET.fromstring(data)) return config
def testGetBeforeVal(self): xml_string = """ <set xmlns="http://jabber.org/protocol/rsm"> <before>id</before> </set> """ s = Set(ET.fromstring(xml_string)) del s['before'] self.check(s, """ <set xmlns="http://jabber.org/protocol/rsm"> </set> """)
def testDelFirstIndex(self): xml_string = """ <set xmlns="http://jabber.org/protocol/rsm"> <first index="10">id</first> </set> """ s = Set(ET.fromstring(xml_string)) del s['first_index'] self.check(s, """ <set xmlns="http://jabber.org/protocol/rsm"> <first>id</first> </set> """)
def set_task(self, task_id, tags, task): """ Publish task to teammates """ payload = ET.fromstring(task) for node, project_tag in self._nodes.items(): if project_tag in tags: self['xep_0060'].publish(self._pubsub, node, id=task_id, payload=payload) else: # Has this node still this task? item_req = self['xep_0060'].get_item(self._pubsub, node, task_id) items = item_req['pubsub']['items']['substanzas'] if len(items) > 0: self['xep_0060'].retract(self._pubsub, node, task_id)
def alert(self, msg): """ Broadcast the msg on the pubsub node (written in the config file). """ xml_element = ET.fromstring('<status>%s</status>' % msg) try: result = self.pubsub.publish(self.config.pubsub, self.config.node, payload=xml_element) id = result['pubsub']['publish']['item']['id'] print('Published at item id: %s' % id) except: print('Could not publish to: %s' % 'Baboon')
def parse_xml(self, xml_string): try: xml = ET.fromstring(xml_string) return xml except SyntaxError as e: if 'unbound' in e.msg: known_prefixes = { 'stream': 'http://etherx.jabber.org/streams'} prefix = xml_string.split('<')[1].split(':')[0] if prefix in known_prefixes: xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % ( prefix, known_prefixes[prefix], xml_string) xml = self.parse_xml(xml_string) xml = xml.getchildren()[0] return xml
def assertXMLEqual(a, b): """ Asserts that both xmls should be syntactically valid and equal. Prints human-readable xml on `AssertionError`. """ args = [a, b] parser = etree.XMLParser(remove_blank_text=True) for i, _ in enumerate(args): if isinstance(args[i], basestring): args[i] = etree.XML(args[i], parser=parser) elif isinstance(args[i], etree._Element): pass else: args[i] = etree.fromstring(ET.tostring(args[i])) args[i] = etree.tostring(args[i], pretty_print=True) assert_message = ('XMLs are not equal:\n' '{2}\n{0}{2}\n{1}' .format(args[0], args[1], '-' * 70)) assert (args[0] == args[1]), assert_message
def testInvalidBase64PrefixEqual(self): """ Test detecting invalid base64 data with = as a prefix to the character data. """ iq = Iq(xml=ET.fromstring(""" <iq type="set" id="0" to="tester@localhost"> <data xmlns="http://jabber.org/protocol/ibb" seq="0"> =ABCDEFGH </data> </iq> """)) errored = False try: data = iq['ibb_data']['data'] except XMPPError: errored = True self.assertTrue(errored, "=ABCDEFGH did not raise base64 error")
def parse_xml(self, xml_string): try: xml = ET.fromstring(xml_string) return xml except (SyntaxError, ExpatError) as e: msg = e.msg if hasattr(e, 'msg') else e.message if 'unbound' in msg: known_prefixes = { 'stream': 'http://etherx.jabber.org/streams'} prefix = xml_string.split('<')[1].split(':')[0] if prefix in known_prefixes: xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % ( prefix, known_prefixes[prefix], xml_string) xml = self.parse_xml(xml_string) xml = xml.getchildren()[0] return xml else: self.fail("XML data was mal-formed:\n%s" % xml_string)
def testInvalidBase64Alphabet(self): """ Test detecting invalid base64 data with characters outside of the base64 alphabet. """ iq = Iq(xml=ET.fromstring(""" <iq type="set" id="0" to="tester@localhost"> <data xmlns="http://jabber.org/protocol/ibb" seq="0"> ABCD?EFGH </data> </iq> """)) errored = False try: data = iq['ibb_data']['data'] except XMPPError: errored = True self.assertTrue(errored, "ABCD?EFGH did not raise base64 error")
def start_sending_data(self): # just for test: send 1 message while True: t = datetime.datetime.now(dateutil.tz.tzlocal()) # scale = math.sin( math.pi * t.second / 60 ) * 100 # value = t.second value = 20 + math.sin(math.pi * (t.second / 60.0 * 4.0)) * 5 print 'starting sending data' try: ts = soxtimestamp.timestamp() print 'ts=%s' % ts # payload = ET.fromstring('<data><transducerValue id="trans1" typedValue="%f" timestamp="%s"/></data>' % (value, ts)) sd = SensorData() tv1 = TransducerValue(id='trans1', typed_value='%s' % value, timestamp=ts) sd.add_value(tv1) payload = ET.fromstring(sd.to_string(pretty=False)) print 'payload built' self['xep_0060'].publish( 'pubsub.ps.ht.sfc.keio.ac.jp', self.node_name, id=self.gen_item_id(), payload=payload ) except: print 'except!' traceback.print_exc() etype, value, etraceback = sys.exc_info() raise etype, value, etraceback print 'requested' gevent.sleep(1.2) self.disconnect() print 'disconnected'
def start(self, event): self.running = True try: print 'starting!' err_count = 0 err_threshold = 5 while self.running and err_count < err_threshold: try: for sid in self.santander_ids: if not self.running: break node_name = 'santander%d_data' % sid print 'fetching for santander sensor id=%d' % sid sdata = get_santander_data(sid) print 'fetched for santander sensor id=%d' % sid sd = santander2sensor(sdata) xml_string = sd.to_string() payload = ET.fromstring(xml_string) try: self['xep_0060'].publish( 'pubsub.sox.ht.sfc.keio.ac.jp', node_name, id=self.gen_item_id(), payload=payload ) except IqTimeout: print 'caught IqTimeout, but ignoring' err_count += 1 if err_threshold <= err_count: break print 'published for node \'%s\'' % node_name time.sleep(3) except: logging.exception('something bad happened!') err_count += 1 finally: self.disconnect()
def start_sending_data(self): self.running = True self.debug('start_sending_data() starting') err_count = 0 err_threshold = 5 try: while self.running and err_count < err_threshold: try: gevent.sleep(1.0 + 0.1 * random.randint(1, 30)) genova_data = get_genova_data(self.genova_id) self.debug('got genova data: %s' % simplejson.dumps(genova_data)) # self.debug('got genova data') genova_sensor_data = genova2sensor(genova_data) xml_string = genova_sensor_data.to_string() payload = ET.fromstring(xml_string) self.debug('built payload: %s' % xml_string) # self.debug('built payload') try: self['xep_0060'].publish( 'pubsub.sox.ht.sfc.keio.ac.jp', self.node_name + '_data', id=self.gen_item_id(), payload=payload ) except IqTimeout: self.debug('caught IqTimeout') err_count += 1 self.debug('published') except: self.debug('except!') traceback.print_exc() err_count += 1 finally: self.disconnect() self.debug('disconnected')
def _unserialize_session(self, session): """ Modify a session dictionary to undo the modifications made in order to pickle the session. Note: Modifies the session in place. """ if '__JID__' in session: for key in session['__JID__']: session[key] = JID(session['__JID__'][key]) del session['__JID__'] if '__XML__' in session: for key in session['__XML__']: stanza_class, xml = session['__XML__'][key] xml = ET.fromstring(xml) session[key] = stanza_class(xml=xml) del session['__XML__'] if '__FUNC__' in session: for key in session['__FUNC__']: func_hash = session['__FUNC__'][key] session[key] = self.funcs[func_hash] del session['__FUNC__']