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 publish(self): payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data) try: result = yield from self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload) logging.info('Published at item id: %s', result['pubsub']['publish']['item']['id']) except XMPPError as error: logging.error('Could not publish to %s: %s', self.node, error.format())
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.assertTrue(iq['roster']['items'] == expected, debug)
async def publish(self): payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data) try: result = await self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload) logging.info('Published at item id: %s', result['pubsub']['publish']['item']['id']) except XMPPError as error: logging.error('Could not publish to %s: %s', self.node, error.format())
def testGetBefore(self): xml_string = """ <set xmlns="http://jabber.org/protocol/rsm"> <before /> </set> """ s = Set(ET.fromstring(xml_string)) expected = True self.failUnless(s['before'] == expected)
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 testGetBefore(self): xml_string = """ <set xmlns="http://jabber.org/protocol/rsm"> <before /> </set> """ s = Set(ET.fromstring(xml_string)) expected = True self.assertTrue(s['before'] == expected)
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 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.assertTrue(mailbox['result-time'] == '1118012394209', "result-time doesn't match") self.assertTrue(mailbox['url'] == 'http://mail.google.com/mail', "url doesn't match") self.assertTrue(mailbox['matched'] == '95', "total-matched incorrect") self.assertTrue(mailbox['estimate'] == False, "total-estimate incorrect") self.assertTrue(len(mailbox['threads']) == 1, "could not extract message threads") thread = mailbox['threads'][0] self.assertTrue(thread['tid'] == '1172320964060972012', "thread tid doesn't match") self.assertTrue(thread['participation'] == '1', "thread participation incorrect") self.assertTrue(thread['messages'] == '28', "thread message count incorrect") self.assertTrue(thread['date'] == '1118012394209', "thread date doesn't match") self.assertTrue(thread['url'] == 'http://mail.google.com/mail?view=cv', "thread url doesn't match") self.assertTrue(thread['labels'] == 'act1scene3', "thread labels incorrect") self.assertTrue(thread['subject'] == 'Put thy rapier up.', "thread subject doesn't match") self.assertTrue(thread['snippet'] == "Ay, ay, a scratch, a scratch; marry, 'tis enough.", "snippet doesn't match") self.assertTrue(len(thread['senders']) == 3, "could not extract senders") sender1 = thread['senders'][0] self.assertTrue(sender1['name'] == 'Me', "sender name doesn't match") self.assertTrue(sender1['address'] == '*****@*****.**', "sender address doesn't match") self.assertTrue(sender1['originator'] == True, "sender originator incorrect") self.assertTrue(sender1['unread'] == False, "sender unread incorrectly True") sender2 = thread['senders'][2] self.assertTrue(sender2['unread'] == True, "sender unread incorrectly False")
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.assertTrue(s['before'] == expected)
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.assertTrue(s['first_index'] == expected)
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): payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data) future, callback = make_callback() try: self["xep_0060"].publish(self.pubsub_server, self.node, payload=payload, callback=callback) result = yield from future id = result["pubsub"]["publish"]["item"]["id"] print("Published at item id: %s" % id) except: logging.error("Could not publish to: %s" % self.node)
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 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 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 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 = list(xml)[0] return xml else: self.fail("XML data was mal-formed:\n%s" % xml_string)
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 = unicode(ET.tostring(content)) else: content = unicode(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 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 = unicode(ET.tostring(content)) else: content = unicode(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 pub_sub_callback(self, msg): items = msg.xml.find( ".//*[@node='http://abb.com/protocol/update_encrypted']") if items is not None: # This message is encrypted if msg['pubsub_event']['items']['item']['update'][ 'data'] is not None: args = message2py( msg['pubsub_event']['items']['item']['update']) if args: xmessage = self.saslhandler.crypto.decryptPubSub(args[0]) update = MessageReader(xmessage) length = update.readUint32BE() got_bytes = update.getRemainingData() try: unzipped = zlib.decompress(got_bytes) except OSError as e: print(e) except: print('error zlib.decompress ', sys.exc_info()[0]) else: if len(unzipped) != length: log.info( "Unexpected uncompressed data length, have=" + str(len(unzipped)) + ", expected=" + str(length)) mes = unzipped.decode('utf-8') print(mes) else: if msg['pubsub_event']['items']['item']['update'][ 'data'] is not None: args = data2py(msg['pubsub_event']['items']['item']['update']) if args: log.info('type %s list: %s', type(args), args) # arg contains the devices that changed root = ET.fromstring(args[0])
def testFastenExternal(self): message = Message() message['apply_to']['id'] = 'some-id' message['apply_to'].xml.append( ET.fromstring('<test xmlns="urn:tmp:test">Test</test>')) message['apply_to']['external']['name'] = 'body' message['body'] = 'Toto' self.check(message, """ <message> <apply-to xmlns="urn:xmpp:fasten:0" id="some-id"> <test xmlns="urn:tmp:test">Test</test> <external name='body'/> </apply-to> <body>Toto</body> </message> """, use_values=False)
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 = list(xml)[0] return xml else: self.fail("XML data was mal-formed:\n%s" % xml_string)
def testDelItems(self): """Test clearing 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)) del iq['roster']['items'] self.check(iq, """ <iq> <query xmlns="jabber:iq:roster" /> </iq> """)
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 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 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 testDelItems(self): """Test clearing 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)) del iq['roster']['items'] self.check( iq, """ <iq> <query xmlns="jabber:iq:roster" /> </iq> """)
async def send_event(self, event: Event) -> None: """Send an event to other clients. Args: event (Event): Event to send """ # create stanza stanza = EventStanza() # dump event to JSON and escape it body = xml.sax.saxutils.escape(json.dumps(event.to_json())) # set xml and send event stanza.xml = ET.fromstring('<event xmlns="pyobs:event">%s</event>' % body) # send it await self._safe_send( self._xmpp["xep_0163"].publish, stanza, node="pyobs:event:%s" % event.__class__.__name__, callback=functools.partial(self._send_event_callback, event=event), )
def to_xhtml_im(self, body, markup_elem): chunks = self._split_first_level(body, markup_elem) final = [] stack = [] for chunk in chunks: if isinstance(chunk, str): chunk = (chunk.replace("&", '&') .replace('<', '<') .replace('>', '>') .replace('"', '"') .replace("'", ''') .replace('\n', '<br/>')) final.append(chunk) continue num_end = 0 for elem in chunk: if isinstance(elem, End): num_end += 1 for i in range(num_end): stack_top = stack.pop() for elem in chunk: if not isinstance(elem, End): continue elem = elem.elem if elem is stack_top: if isinstance(elem, Span): final.append('</span>') elif isinstance(elem, BlockCode): final.append('</code></pre>') elif isinstance(elem, List): final.append('</ul>') elif isinstance(elem, Li): final.append('</li>') elif isinstance(elem, BlockQuote): final.append('</blockquote>') break else: assert False for elem in chunk: if not isinstance(elem, Start): continue elem = elem.elem stack.append(elem) if isinstance(elem, Span): style = [] for type_ in elem['types']: if type_ == 'emphasis': style.append('font-style: italic;') if type_ == 'code': style.append('font-family: monospace;') if type_ == 'deleted': style.append('text-decoration: line-through;') final.append("<span style='%s'>" % ' '.join(style)) elif isinstance(elem, BlockCode): final.append('<pre><code>') elif isinstance(elem, List): final.append('<ul>') elif isinstance(elem, Li): final.append('<li>') elif isinstance(elem, BlockQuote): final.append('<blockquote>') p = "<p xmlns='http://www.w3.org/1999/xhtml'>%s</p>" % ''.join(final) p2 = ET.fromstring(p) print('coucou', p, tostring(p2)) xhtml_im = XHTML_IM() xhtml_im['body'] = p2 return xhtml_im
def _extract_method(self, stanza): xml = ET.fromstring("%s" % stanza) return xml.find("./methodCall/methodName").text
def rpc_callback(self, iq): log.info("Rpc callback jhe ") iq.enable('rpc_query') if iq['rpc_query']['method_response']['fault'] is not None: fault = iq['rpc_query']['method_response']['fault'] log.info(fault['string']) else: if iq['rpc_query']['method_response']['params'] is not None: args = xml2py(iq['rpc_query']['method_response']['params']) """ deviceID 'B002', // Schaltaktor 4-fach, 16A, REG '100E', // Sensor/ Schaltaktor 2/1-fach 'B008', // Sensor/ Schaltaktor 8/8fach, REG '10C4' // Hue Aktor (Plug Switch) '101C', // Dimmaktor 4-fach '1021', // Dimmaktor 4-fach v2 '10C0' // Hue Aktor (LED Strip) 'B001', // Jalousieaktor 4-fach, REG '1013' // Sensor/ Jalousieaktor 1/1-fach """ log.info(len(args)) # Nu een iteratie over de devices root = ET.fromstring(args[0]) filename = 'mastermessage.xml' with open(filename, 'w', encoding="utf-8") as file_object: file_object.write(args[0]) for child in root: log.info(child.tag) strings = root.find('strings') # Zet de strings in een dictionary names = {} for string in strings.findall('string'): stringNameId = string.get('nameId') stringValue = string.text names[stringNameId] = stringValue # log.info("%s", names) device = root.find('devices') for neighbor in device.findall('device'): serialNumber = neighbor.get('serialNumber') nameId = names[neighbor.get('nameId')].title() deviceId = neighbor.get('deviceId') log.info(" %s %s %s %s", serialNumber, neighbor.get('nameId'), nameId, deviceId) # Schaltaktor 4-fach, 16A, REG if deviceId == 'B002': # Nu de channnels binnen een device channels = neighbor.find('channels') if channels is not None: for channel in channels.findall('channel'): channelName = names[channel.get( 'nameId')].title() channelId = channel.get('i') log.info(" %s %s", channelId, channelName) for attributes in channel.findall('attribute'): attributeName = attributes.get('name') attributeValue = attributes.text log.info(" %s %s", attributeName, attributeValue) inputs = channel.find('inputs') for datapoints in inputs.findall('dataPoint'): light_state = False datapointId = datapoints.get('i') datapointValue = datapoints.find( 'value').text if datapointId == 'idp0000': if datapointValue == '1': light_state = True log.info(" %s %s %s", datapointId, datapointValue, light_state) # Dimmaktor 4-fach and Dimmaktor 4-fach v2 if deviceId == '101C' or deviceId == '1021': # The channels within a device channels = neighbor.find('channels') if channels is not None: for channel in channels.findall('channel'): channelName = names[channel.get( 'nameId')].title() channelId = channel.get('i') log.info(" %s %s", channelId, channelName) for attributes in channel.findall('attribute'): attributeName = attributes.get('name') attributeValue = attributes.text log.info(" %s %s", attributeName, attributeValue) inputs = channel.find('inputs') for datapoints in inputs.findall('dataPoint'): light_state = False datapointId = datapoints.get('i') datapointValue = datapoints.find( 'value').text if datapointId == 'idp0000': if datapointValue == '1': light_state = True log.info(" %s %s %s", datapointId, datapointValue, light_state) # switch if deviceId == '1002' or deviceId == '1000' or deviceId == '100A': # Now the channels within a device channels = neighbor.find('channels')
def find_devices(self, use_room_names): iq = yield from self.send_rpc_iq('RemoteInterface.getAll', 'de', 4, 0, 0) iq.enable('rpc_query') if iq['rpc_query']['method_response']['fault'] is not None: fault = iq['rpc_query']['method_response']['fault'] log.info(fault['string']) else: args = xml2py(iq['rpc_query']['method_response']['params']) """ deviceID 'B002', // Schaltaktor 4-fach, 16A, REG '100E', // Sensor/ Schaltaktor 2/1-fach 'B008', // Sensor/ Schaltaktor 8/8fach, REG '100C', // Sensor/schakelaktor 1/1-voudig 'FFE7', // Sensor/schakelaktor 2/2-voudig '10C4' // Hue Aktor (Plug Switch) '101C', // Dimmaktor 4-fach '1021', // Dimmaktor 4-fach v2 '1017' // Sensor/dimaktor 1/1-voudig '10C0' // Hue Aktor (LED Strip) 'B001', // Jalousieaktor 4-fach, REG '1013' // Sensor/ Jalousieaktor 1/1-fach """ self.found_devices = True root = ET.fromstring(args[0]) strings = root.find('strings') # Store all the names names = {} for string in strings.findall('string'): stringNameId = string.get('nameId') stringValue = string.text names[stringNameId] = stringValue # make a list of the rooms floorplan = root.find('floorplan') floornames = {} roomnames = {} for floor in floorplan.findall('floor'): FloorName = floor.get('name') FloorUid = floor.get('uid') floornames[FloorUid] = FloorName log.info(' floor %s', FloorName) roomnames[FloorUid] = {} # Now the rooms of this floor for room in floor.findall('room'): RoomName = room.get('name') RoomUid = room.get('uid') roomnames[FloorUid][RoomUid] = RoomName # Now look for the devices device = root.find('devices') for neighbor in device.findall('device'): serialNumber = neighbor.get('serialNumber') nameId = names[neighbor.get('nameId')].title() deviceId = neighbor.get('deviceId') # Schaltaktor 4-fach, 16A, REG if deviceId == 'B002' or deviceId == '100E' or deviceId == 'B008' or deviceId == '10C4' or deviceId == '100C' or deviceId == '1010': # Now the channels of a device channels = neighbor.find('channels') if channels is not None: for channel in channels.findall('channel'): channelName = names[channel.get('nameId')].title() channelId = channel.get('i') light_name = '' floorId = '' roomId = '' for attributes in channel.findall('attribute'): attributeName = attributes.get('name') attributeValue = attributes.text if attributeName == 'displayName': light_name = attributeValue if attributeName == 'floor': floorId = attributeValue if attributeName == 'room': roomId = attributeValue inputs = channel.find('inputs') for datapoints in inputs.findall('dataPoint'): datapointId = datapoints.get('i') datapointValue = datapoints.find('value').text outputs = channel.find('outputs') for datapoints in outputs.findall('dataPoint'): datapointId = datapoints.get('i') datapointValue = datapoints.find('value').text if datapointId == 'odp0000': if datapointValue == '1': light_state = True else: light_state = False single_light = serialNumber + '/' + channelId if light_name == '': light_name = single_light if floorId != '' and roomId != '' and use_room_names == True: light_name = light_name + ' (' + roomnames[ floorId][roomId] + ')' self.light_devices[ single_light] = self.add_light_info( name=light_name, state=light_state, floor=floornames[floorId], room=roomnames[floorId][roomId]) else: self.light_devices[ single_light] = self.add_light_info( name=light_name, state=light_state, floor='', room='') self.devices[single_light] = 'light' log.info('light %s %s is %s', single_light, light_name, light_state) # Dimmaktor 4-fach and Dimmaktor 4-fach v2 if deviceId == '101C' or deviceId == '1021' or deviceId == '10C0' or deviceId == '1017': # Now the channels of a device channels = neighbor.find('channels') if channels is not None: for channel in channels.findall('channel'): channelName = names[channel.get('nameId')].title() channelId = channel.get('i') light_name = '' floorId = '' roomId = '' brightness = None for attributes in channel.findall('attribute'): attributeName = attributes.get('name') attributeValue = attributes.text if attributeName == 'displayName': light_name = attributeValue if attributeName == 'floor': floorId = attributeValue if attributeName == 'room': roomId = attributeValue inputs = channel.find('inputs') for datapoints in inputs.findall('dataPoint'): datapointId = datapoints.get('i') datapointValue = datapoints.find('value').text outputs = channel.find('outputs') for datapoints in outputs.findall('dataPoint'): datapointId = datapoints.get('i') datapointValue = datapoints.find('value').text if datapointId == 'odp0001': brightness = datapointValue if datapointId == 'odp0000': if datapointValue == '1': light_state = True else: light_state = False single_light = serialNumber + '/' + channelId if light_name == '': light_name = single_light if floorId != '' and roomId != '' and use_room_names == True: light_name = light_name + ' (' + roomnames[ floorId][roomId] + ')' self.light_devices[ single_light] = self.add_light_info( name=light_name, state=light_state, floor=floornames[floorId], room=roomnames[floorId][roomId], light_type='dimmer', brightness=brightness) else: self.light_devices[ single_light] = self.add_light_info( name=light_name, state=light_state, floor='', room='', light_type='dimmer', brightness=brightness) self.devices[single_light] = 'light' log.info('dimmer %s %s is %s', single_light, light_name, light_state) # Scene or Timer if deviceId == '4800' or deviceId == '4A00': channels = neighbor.find('channels') if channels is not None: for channel in channels.findall('channel'): channelName = names[channel.get('nameId')].title() channelId = channel.get('i') scene_name = '' floorId = '' roomId = '' for attributes in channel.findall('attribute'): attributeName = attributes.get('name') attributeValue = attributes.text if attributeName == 'displayName': scene_name = attributeValue if attributeName == 'floor': floorId = attributeValue if attributeName == 'room': roomId = attributeValue scene = serialNumber + '/' + channelId if scene_name == '': scene_name = scene if floorId != '' and roomId != '' and use_room_names == True: scene_name = scene_name + ' (' + roomnames[ floorId][roomId] + ')' self.scene_devices[ scene] = self.add_scene_info( name=scene_name, floor=floornames[floorId], room=roomnames[floorId][roomId]) else: self.scene_devices[ scene] = self.add_scene_info( name=scene_name, floor='', room='') self.devices[scene] = 'scene' log.info('scene %s %s', scene, scene_name) # switch device if deviceId == 'B001' or deviceId == '1013': channels = neighbor.find('channels') if channels is not None: for channel in channels.findall('channel'): channelName = names[channel.get('nameId')].title() channelId = channel.get('i') cover_name = '' floorId = '' roomId = '' for attributes in channel.findall('attribute'): attributeName = attributes.get('name') attributeValue = attributes.text if attributeName == 'displayName': light_name = attributeValue if attributeName == 'floor': floorId = attributeValue if attributeName == 'room': roomId = attributeValue inputs = channel.find('inputs') for datapoints in inputs.findall('dataPoint'): datapointId = datapoints.get('i') datapointValue = datapoints.find('value').text outputs = channel.find('outputs') for datapoints in outputs.findall('dataPoint'): datapointId = datapoints.get('i') datapointValue = datapoints.find('value').text if datapointId == 'odp0000': cover_state = datapointValue if datapointId == 'odp0001': cover_position = str( abs(100 - int(datapointValue))) single_cover = serialNumber + '/' + channelId if cover_name == '': cover_name = single_cover if floorId != '' and roomId != '' and use_room_names == True: cover_name = cover_name + ' (' + roomnames[ floorId][roomId] + ')' self.cover_devices[ single_cover] = self.add_cover_info( name=cover_name, state=cover_state, position=cover_position, floor=floornames[floorId], room=roomnames[floorId][roomId]) else: self.cover_devices[ single_cover] = self.add_cover_info( name=cover_name, state=cover_state, position=cover_position, floor='', room='') self.devices[single_cover] = 'cover' log.info('cover %s %s is %s', single_cover, cover_name, cover_state)
def _extract_method(self, stanza): xml = ET.fromstring("%s" % stanza) return xml.find("./methodCall/methodName").text
def extract_method(self, stanza): xml = ET.fromstring("%s" % stanza) return xml.find( "./{jabber:iq:rpc}methodCall/{jabber:iq:rpc}methodName").text
def __init__(self): keyfile = config.get('keyfile') certfile = config.get('certfile') device_id = config.get('device_id') if not device_id: rng = random.SystemRandom() device_id = base64.urlsafe_b64encode( rng.getrandbits(24).to_bytes(3, 'little')).decode('ascii') config.set_and_save('device_id', device_id) if config.get('jid'): # Field used to know if we are anonymous or not. # many features will be handled differently # depending on this setting self.anon = False jid = config.get('jid') password = config.get('password') eval_password = config.get('eval_password') if not password and not eval_password and not (keyfile and certfile): password = getpass.getpass() elif not password and not (keyfile and certfile): sys.stderr.write( "No password or certificates provided, using the eval_password command.\n" ) process = subprocess.Popen( ['sh', '-c', eval_password], stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) code = process.wait() if code != 0: sys.stderr.write( 'The eval_password command (%s) returned a ' 'nonzero status code: %s.\n' % (eval_password, code)) sys.stderr.write('Poezio will now exit\n') sys.exit(code) password = process.stdout.readline().decode('utf-8').strip( '\n') else: # anonymous auth self.anon = True jid = config.get('server') password = None jid = safeJID(jid) jid.resource = '%s-%s' % ( jid.resource, device_id) if jid.resource else 'poezio-%s' % device_id # TODO: use the system language slixmpp.ClientXMPP.__init__( self, jid, password, lang=config.get('lang')) force_encryption = config.get('force_encryption') if force_encryption: self['feature_mechanisms'].unencrypted_plain = False self['feature_mechanisms'].unencrypted_digest = False self['feature_mechanisms'].unencrypted_cram = False self['feature_mechanisms'].unencrypted_scram = False self.keyfile = config.get('keyfile') self.certfile = config.get('certfile') if keyfile and not certfile: log.error( 'keyfile is present in configuration file without certfile') elif certfile and not keyfile: log.error( 'certfile is present in configuration file without keyfile') self.core = None self.auto_reconnect = config.get('auto_reconnect') self.auto_authorize = None # prosody defaults, lowest is AES128-SHA, it should be a minimum # for anything that came out after 2002 self.ciphers = config.get( 'ciphers', 'HIGH+kEDH:HIGH+kEECDH:HIGH:!PSK' ':!SRP:!3DES:!aNULL') self.ca_certs = config.get('ca_cert_path') or None interval = config.get('whitespace_interval') if int(interval) > 0: self.whitespace_keepalive_interval = int(interval) else: self.whitespace_keepalive = False self.register_plugin('xep_0004') self.register_plugin('xep_0012') # Must be loaded before 0030. self.register_plugin( 'xep_0115', { 'caps_node': 'https://poez.io', 'cache': FileSystemCache( str(xdg.CACHE_HOME), 'caps', encode=str, decode=lambda x: DiscoInfo(ET.fromstring(x))), }) self.register_plugin('xep_0030') self.register_plugin('xep_0045') self.register_plugin('xep_0048') self.register_plugin('xep_0050') self.register_plugin('xep_0054') self.register_plugin('xep_0060') self.register_plugin('xep_0066') self.register_plugin('xep_0070') self.register_plugin('xep_0071') self.register_plugin('xep_0077') self.plugin['xep_0077'].create_account = False self.register_plugin('xep_0084') self.register_plugin('xep_0085') self.register_plugin('xep_0153') # monkey-patch xep_0184 to avoid requesting receipts for messages # without a body XEP_0184._filter_add_receipt_request = fixes._filter_add_receipt_request self.register_plugin('xep_0184') self.plugin['xep_0184'].auto_ack = config.get('ack_message_receipts') self.plugin['xep_0184'].auto_request = config.get( 'request_message_receipts') self.register_plugin('xep_0191') if config.get('enable_smacks'): self.register_plugin('xep_0198') self.register_plugin('xep_0199') if config.get('enable_user_tune'): self.register_plugin('xep_0118') if config.get('enable_user_nick'): self.register_plugin('xep_0172') if config.get('enable_user_mood'): self.register_plugin('xep_0107') if config.get('enable_user_activity'): self.register_plugin('xep_0108') if config.get('enable_user_gaming'): self.register_plugin('xep_0196') if config.get('send_poezio_info'): info = {'name': 'poezio', 'version': options.custom_version} if config.get('send_os_info'): info['os'] = common.get_os_info() self.plugin['xep_0030'].set_identities(identities={('client', 'console', None, 'Poezio')}) else: info = {'name': '', 'version': ''} self.plugin['xep_0030'].set_identities(identities={('client', 'console', None, '')}) self.register_plugin('xep_0092', pconfig=info) if config.get('send_time'): self.register_plugin('xep_0202') self.register_plugin('xep_0224') self.register_plugin('xep_0231') self.register_plugin('xep_0249') self.register_plugin('xep_0257') self.register_plugin('xep_0280') self.register_plugin('xep_0297') self.register_plugin('xep_0308') self.register_plugin('xep_0313') self.register_plugin('xep_0319') self.register_plugin('xep_0334') self.register_plugin('xep_0352') try: self.register_plugin('xep_0363') except SyntaxError: log.error('Failed to load HTTP File Upload plugin, it can only be ' 'used on Python 3.5+') except slixmpp.plugins.base.PluginNotFound: log.error('Failed to load HTTP File Upload plugin, it can only be ' 'used with aiohttp installed') self.register_plugin('xep_0380') self.init_plugins()
def to_xhtml_im(self, body, markup_elem): chunks = self._split_first_level(body, markup_elem) final = [] stack = [] for chunk in chunks: if isinstance(chunk, str): chunk = (chunk.replace("&", '&').replace( '<', '<').replace('>', '>').replace('"', '"').replace( "'", ''').replace('\n', '<br/>')) final.append(chunk) continue num_end = 0 for elem in chunk: if isinstance(elem, End): num_end += 1 for i in range(num_end): stack_top = stack.pop() for elem in chunk: if not isinstance(elem, End): continue elem = elem.elem if elem is stack_top: if isinstance(elem, Span): final.append('</span>') elif isinstance(elem, BlockCode): final.append('</code></pre>') elif isinstance(elem, List): final.append('</ul>') elif isinstance(elem, Li): final.append('</li>') elif isinstance(elem, BlockQuote): final.append('</blockquote>') break else: assert False for elem in chunk: if not isinstance(elem, Start): continue elem = elem.elem stack.append(elem) if isinstance(elem, Span): style = [] for type_ in elem['types']: if type_ == 'emphasis': style.append('font-style: italic;') if type_ == 'code': style.append('font-family: monospace;') if type_ == 'deleted': style.append('text-decoration: line-through;') final.append("<span style='%s'>" % ' '.join(style)) elif isinstance(elem, BlockCode): final.append('<pre><code>') elif isinstance(elem, List): final.append('<ul>') elif isinstance(elem, Li): final.append('<li>') elif isinstance(elem, BlockQuote): final.append('<blockquote>') p = "<p xmlns='http://www.w3.org/1999/xhtml'>%s</p>" % ''.join(final) p2 = ET.fromstring(p) print('coucou', p, tostring(p2)) xhtml_im = XHTML_IM() xhtml_im['body'] = p2 return xhtml_im
def __init__(self): keyfile = config.get('keyfile') certfile = config.get('certfile') device_id = config.get('device_id') if not device_id: rng = random.SystemRandom() device_id = base64.urlsafe_b64encode( rng.getrandbits(24).to_bytes(3, 'little')).decode('ascii') config.set_and_save('device_id', device_id) if config.get('jid'): # Field used to know if we are anonymous or not. # many features will be handled differently # depending on this setting self.anon = False jid = config.get('jid') password = config.get('password') eval_password = config.get('eval_password') if not password and not eval_password and not (keyfile and certfile): password = getpass.getpass() elif not password and not (keyfile and certfile): sys.stderr.write( "No password or certificates provided, using the eval_password command.\n" ) process = subprocess.Popen( ['sh', '-c', eval_password], stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) code = process.wait() if code != 0: sys.stderr.write( 'The eval_password command (%s) returned a ' 'nonzero status code: %s.\n' % (eval_password, code)) sys.stderr.write('Poezio will now exit\n') sys.exit(code) password = process.stdout.readline().decode('utf-8').strip( '\n') else: # anonymous auth self.anon = True jid = config.get('server') password = None jid = safeJID(jid) jid.resource = '%s-%s' % ( jid.resource, device_id) if jid.resource else 'poezio-%s' % device_id # TODO: use the system language slixmpp.ClientXMPP.__init__( self, jid, password, lang=config.get('lang')) force_encryption = config.get('force_encryption') if force_encryption: self['feature_mechanisms'].unencrypted_plain = False self['feature_mechanisms'].unencrypted_digest = False self['feature_mechanisms'].unencrypted_cram = False self['feature_mechanisms'].unencrypted_scram = False self.keyfile = config.get('keyfile') self.certfile = config.get('certfile') if keyfile and not certfile: log.error( 'keyfile is present in configuration file without certfile') elif certfile and not keyfile: log.error( 'certfile is present in configuration file without keyfile') self.core = None self.auto_reconnect = config.get('auto_reconnect') self.auto_authorize = None # prosody defaults, lowest is AES128-SHA, it should be a minimum # for anything that came out after 2002 self.ciphers = config.get( 'ciphers', 'HIGH+kEDH:HIGH+kEECDH:HIGH:!PSK' ':!SRP:!3DES:!aNULL') self.ca_certs = config.get('ca_cert_path') or None interval = config.get('whitespace_interval') if int(interval) > 0: self.whitespace_keepalive_interval = int(interval) else: self.whitespace_keepalive = False self.register_plugin('xep_0004') self.register_plugin('xep_0012') # Must be loaded before 0030. self.register_plugin( 'xep_0115', { 'caps_node': 'https://poez.io', 'cache': FileSystemCache( str(xdg.CACHE_HOME), 'caps', encode=str, decode=lambda x: DiscoInfo(ET.fromstring(x))), }) self.register_plugin('xep_0030') self.register_plugin('xep_0045') self.register_plugin('xep_0048') self.register_plugin('xep_0050') self.register_plugin('xep_0054') self.register_plugin('xep_0060') self.register_plugin('xep_0066') self.register_plugin('xep_0070') self.register_plugin('xep_0071') self.register_plugin('xep_0077') self.plugin['xep_0077'].create_account = False self.register_plugin('xep_0084') self.register_plugin('xep_0085') self.register_plugin('xep_0153') # monkey-patch xep_0184 to avoid requesting receipts for messages # without a body XEP_0184._filter_add_receipt_request = fixes._filter_add_receipt_request self.register_plugin('xep_0184') self.plugin['xep_0184'].auto_ack = config.get('ack_message_receipts') self.plugin['xep_0184'].auto_request = config.get( 'request_message_receipts') self.register_plugin('xep_0191') if config.get('enable_smacks'): self.register_plugin('xep_0198') self.register_plugin('xep_0199') if config.get('enable_user_tune'): self.register_plugin('xep_0118') if config.get('enable_user_nick'): self.register_plugin('xep_0172') if config.get('enable_user_mood'): self.register_plugin('xep_0107') if config.get('enable_user_activity'): self.register_plugin('xep_0108') if config.get('enable_user_gaming'): self.register_plugin('xep_0196') if config.get('send_poezio_info'): info = {'name': 'poezio', 'version': options.version} if config.get('send_os_info'): info['os'] = common.get_os_info() self.plugin['xep_0030'].set_identities(identities={('client', 'console', None, 'Poezio')}) else: info = {'name': '', 'version': ''} self.plugin['xep_0030'].set_identities(identities={('client', 'console', None, '')}) self.register_plugin('xep_0092', pconfig=info) if config.get('send_time'): self.register_plugin('xep_0202') self.register_plugin('xep_0224') self.register_plugin('xep_0231') self.register_plugin('xep_0249') self.register_plugin('xep_0257') self.register_plugin('xep_0280') self.register_plugin('xep_0297') self.register_plugin('xep_0308') self.register_plugin('xep_0319') self.register_plugin('xep_0334') self.register_plugin('xep_0352') try: self.register_plugin('xep_0363') except SyntaxError: log.error('Failed to load HTTP File Upload plugin, it can only be ' 'used on Python 3.5+') except slixmpp.plugins.base.PluginNotFound: log.error('Failed to load HTTP File Upload plugin, it can only be ' 'used with aiohttp installed') self.register_plugin('xep_0380') self.init_plugins()
def pub_sub_callback(self, msg): if msg['pubsub_event']['items']['item']['update']['data'] is not None: args = data2py(msg['pubsub_event']['items']['item']['update']) # arg contains the devices that changed if len(args) != 0: root = ET.fromstring(args[0]) device = root.find('devices') for neighbor in device.findall('device'): serialNumber = neighbor.get('serialNumber') channels = neighbor.find('channels') if channels is not None: for channel in channels.findall('channel'): channelId = channel.get('i') # get the inputs inputs = channel.find('inputs') idatapoint = inputs.find('dataPoint') inputPoints = {} if idatapoint is not None: inputId = idatapoint.get('i') inputValue = idatapoint.find('value').text inputPoints[inputId] = inputValue # get the outputs outputs = channel.find('outputs') odatapoint = outputs.find('dataPoint') outputPoints = {} if odatapoint is not None: outputId = odatapoint.get('i') outputValue = odatapoint.find('value').text outputPoints[outputId] = outputValue # Now change the status of the device device_id = serialNumber + '/' + channelId # if the device is a light if device_id in self.light_devices: if 'odp0000' in outputPoints: if outputPoints['odp0000'] == '1': state = True else: state = False self.light_devices[device_id][ 'state'] = state log.info( "device %s (%s) is %s", self.light_devices[device_id]['name'], device_id, state) if 'odp0001' in outputPoints: self.light_devices[device_id][ 'brightness'] = outputPoints['odp0001'] log.info( "device %s (%s) brightness %s", self.light_devices[device_id]['name'], device_id, self.light_devices[device_id] ['brightness']) if device_id in self.cover_devices: if 'odp0000' in outputPoints: state = outputPoints[ 'odp0000'] # 0 = open, 1 = closed , 2 = moving up, 3 = moving down self.cover_devices[device_id][ 'state'] = state log.info( "device %s (%s) is %s", self.cover_devices[device_id]['name'], device_id, state) if 'odp0001' in outputPoints: # 100 = fully closed self.cover_devices[device_id][ 'position'] = str( abs(100 - int(outputPoints['odp0001'])))
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.assertTrue(mailbox['result-time'] == '1118012394209', "result-time doesn't match") self.assertTrue(mailbox['url'] == 'http://mail.google.com/mail', "url doesn't match") self.assertTrue(mailbox['matched'] == '95', "total-matched incorrect") self.assertTrue(mailbox['estimate'] == False, "total-estimate incorrect") self.assertTrue( len(mailbox['threads']) == 1, "could not extract message threads") thread = mailbox['threads'][0] self.assertTrue(thread['tid'] == '1172320964060972012', "thread tid doesn't match") self.assertTrue(thread['participation'] == '1', "thread participation incorrect") self.assertTrue(thread['messages'] == '28', "thread message count incorrect") self.assertTrue(thread['date'] == '1118012394209', "thread date doesn't match") self.assertTrue(thread['url'] == 'http://mail.google.com/mail?view=cv', "thread url doesn't match") self.assertTrue(thread['labels'] == 'act1scene3', "thread labels incorrect") self.assertTrue(thread['subject'] == 'Put thy rapier up.', "thread subject doesn't match") self.assertTrue( thread['snippet'] == "Ay, ay, a scratch, a scratch; marry, 'tis enough.", "snippet doesn't match") self.assertTrue( len(thread['senders']) == 3, "could not extract senders") sender1 = thread['senders'][0] self.assertTrue(sender1['name'] == 'Me', "sender name doesn't match") self.assertTrue(sender1['address'] == '*****@*****.**', "sender address doesn't match") self.assertTrue(sender1['originator'] == True, "sender originator incorrect") self.assertTrue(sender1['unread'] == False, "sender unread incorrectly True") sender2 = thread['senders'][2] self.assertTrue(sender2['unread'] == True, "sender unread incorrectly False")