def response_first_deploy(self, ito=None, ifrom=None, iq_id=None, success=None, response=None, error=None): iq = self.xmpp.Iq() iq['id'] = iq_id iq['to'] = ito iq['from'] = ifrom if success: query = ET.Element('{jabber:iq:docker}query') result = ET.Element('deploy') result.text = response query.append(result) iq['type'] = 'result' iq.append(query) else: iq['query'] = 'jabber:iq:docker' iq['type'] = 'error' iq['error'] = 'cancel' iq['error']['text'] = unicode(error) print(iq) iq.send(now=True)
def response_get_name_pods(self, ito=None, ifrom=None, success=None, response=None, error=None): iq = self.xmpp.Iq() iq['id'] = 'name-pods' iq['to'] = ito iq['from'] = ifrom if success: query = ET.Element('{jabber:iq:docker}query') result = ET.Element('name') result.text = response query.append(result) iq['type'] = 'result' iq.append(query) else: iq['query'] = 'jabber:iq:docker' iq['type'] = 'error' iq['error'] = 'cancel' iq['error']['text'] = unicode(error) iq.send(now=True)
def request_first_deploy(self, ito=None, ifrom=None, name=None, key=None, user=None): iq = self.xmpp.Iq() iq['id'] = 'first-deploy-' + iq['id'] iq['type'] = 'get' iq['to'] = ito iq['from'] = ifrom query = ET.Element('{jabber:iq:docker}query') req_name = ET.Element('name') req_name.text = name req_key = ET.Element('key') req_key.text = key req_user = ET.Element('user') req_user.text = user query.append(req_name) query.append(req_key) query.append(req_user) iq.append(query) return iq.send(now=True, timeout=120)
def _send_request(self, ito=None, ifrom=None, action=None, timeout=None, elements=None): logging.info('Send IQ to: %s, from: %s, action: %s, elements: %s' % (ito, ifrom, action, elements)) iq = self.xmpp.Iq() if action is not None: iq['id'] = action + '-' + iq['id'] iq['type'] = 'get' iq['to'] = ito iq['from'] = ifrom if elements is not None: query = ET.Element('{jabber:iq:docker}query') for key in elements.keys(): element = ET.Element(key) element.text = str(elements[key]) query.append(element) iq.append(query) else: iq['query'] = 'jabber:iq:docker' return iq.send(now=True, timeout=timeout)
def testItemsEvent(self): """Testing multiple message/pubsub_event/items/item""" msg = self.Message() item = pubsub.EventItem() item2 = pubsub.EventItem() pl = ET.Element('{http://netflint.net/protocol/test}test', { 'failed': '3', 'passed': '24' }) pl2 = ET.Element('{http://netflint.net/protocol/test-other}test', { 'total': '27', 'failed': '3' }) item2['payload'] = pl2 item['payload'] = pl item['id'] = 'abc123' item2['id'] = '123abc' msg['pubsub_event']['items'].append(item) msg['pubsub_event']['items'].append(item2) msg['pubsub_event']['items']['node'] = 'cheese' msg['type'] = 'normal' self.check( msg, """ <message type="normal"> <event xmlns="http://jabber.org/protocol/pubsub#event"> <items node="cheese"> <item id="abc123"> <test xmlns="http://netflint.net/protocol/test" failed="3" passed="24" /> </item> <item id="123abc"> <test xmlns="http://netflint.net/protocol/test-other" failed="3" total="27" /> </item> </items> </event> </message>""")
def testPublish(self): "Testing iq/pubsub/publish stanzas" iq = self.Iq() iq['pubsub']['publish']['node'] = 'thingers' payload = ET.fromstring(""" <thinger xmlns="http://andyet.net/protocol/thinger" x="1" y='2'> <child1 /> <child2 normandy='cheese' foo='bar' /> </thinger>""") payload2 = ET.fromstring(""" <thinger2 xmlns="http://andyet.net/protocol/thinger2" x="12" y='22'> <child12 /> <child22 normandy='cheese2' foo='bar2' /> </thinger2>""") item = pubsub.Item() item['id'] = 'asdf' item['payload'] = payload item2 = pubsub.Item() item2['id'] = 'asdf2' item2['payload'] = payload2 iq['pubsub']['publish'].append(item) iq['pubsub']['publish'].append(item2) form = xep_0004.Form() form.addField('pubsub#description', ftype='text-single', value='this thing is awesome') iq['pubsub']['publish_options'] = form self.check( iq, """ <iq id="0"> <pubsub xmlns="http://jabber.org/protocol/pubsub"> <publish node="thingers"> <item id="asdf"> <thinger xmlns="http://andyet.net/protocol/thinger" y="2" x="1"> <child1 /> <child2 foo="bar" normandy="cheese" /> </thinger> </item> <item id="asdf2"> <thinger2 xmlns="http://andyet.net/protocol/thinger2" y="22" x="12"> <child12 /> <child22 foo="bar2" normandy="cheese2" /> </thinger2> </item> </publish> <publish-options> <x xmlns="jabber:x:data" type="submit"> <field var="pubsub#description"> <value>this thing is awesome</value> </field> </x> </publish-options> </pubsub> </iq>""")
def testPublish(self): "Testing iq/pubsub/publish stanzas" iq = self.Iq() iq['pubsub']['publish']['node'] = 'thingers' payload = ET.fromstring(""" <thinger xmlns="http://andyet.net/protocol/thinger" x="1" y='2'> <child1 /> <child2 normandy='cheese' foo='bar' /> </thinger>""") payload2 = ET.fromstring(""" <thinger2 xmlns="http://andyet.net/protocol/thinger2" x="12" y='22'> <child12 /> <child22 normandy='cheese2' foo='bar2' /> </thinger2>""") item = pubsub.Item() item['id'] = 'asdf' item['payload'] = payload item2 = pubsub.Item() item2['id'] = 'asdf2' item2['payload'] = payload2 iq['pubsub']['publish'].append(item) iq['pubsub']['publish'].append(item2) form = xep_0004.Form() form.addField('pubsub#description', ftype='text-single', value='this thing is awesome') iq['pubsub']['publish_options'] = form self.check(iq, """ <iq id="0"> <pubsub xmlns="http://jabber.org/protocol/pubsub"> <publish node="thingers"> <item id="asdf"> <thinger xmlns="http://andyet.net/protocol/thinger" y="2" x="1"> <child1 /> <child2 foo="bar" normandy="cheese" /> </thinger> </item> <item id="asdf2"> <thinger2 xmlns="http://andyet.net/protocol/thinger2" y="22" x="12"> <child12 /> <child22 foo="bar2" normandy="cheese2" /> </thinger2> </item> </publish> <publish-options> <x xmlns="jabber:x:data" type="submit"> <field var="pubsub#description"> <value>this thing is awesome</value> </field> </x> </publish-options> </pubsub> </iq>""")
def getUsersInfo(self, jid): #Create iq Stanza resp = self.Iq() resp['type'] = 'set' resp['to'] = 'search.redes2020.xyz' resp['from'] = self.jid resp['id'] = 'search_result' #Service discovery stanza for getting a user resp.append( ET.fromstring("<query xmlns='jabber:iq:search'>\ <x xmlns='jabber:x:data' type='submit'>\ <field type='hidden' var='FORM_TYPE'>\ <value>jabber:iq:search</value>\ </field>\ <field var='Username'>\ <value>1</value>\ </field>\ <field var='search'>\ <value>" + jid + "</value>\ </field>\ </x>\ </query>")) try: results = resp.send() # Extract info from recived stanza for i in results.findall('.//{jabber:x:data}value'): if (i.text != None): print(i.text) except IqError as e: pass except IqTimeout: pass
def __init__(self, param=None, *args, **kwargs): ''' Class constructor that builds the manually the XML of the stanza. This procedure is needed at the moment to be able to include text into the stanza root elements, as the default functionality does not seem to allow that. After defining the XML body of the stanza, ElementBase is initiated passing the body of the stanza as an argument for the `xml` parameter of the ElementBase class. ''' ET.register_namespace('', 'intamac:intamacdeviceinfo') root = ET.Element('{intamac:intamacdeviceinfo}intamacdeviceinfo') root.text = param ElementBase.__init__(self, xml=root)
def set_receipt(self, value): self.del_receipt() if value: parent = self.parent() xml = ET.Element("{%s}received" % self.namespace) xml.attrib['id'] = value parent.append(xml)
def delete(self): account = self.make_iq_set(ito='redes2020.xyz', ifrom=self.boundjid.user) items = ET.fromstring("<query xmlns='jabber:iq:register'> <remove/> </query>") account.append(items) res = account.send() if res['type'] == 'result': print('Cuenta %s Eliminada correctamente' % self.user)
def sendBytestreamStanza(self, filename, to): offer = self.Iq() offer['type'] = 'set' offer['id'] = 'offer1' offer['to'] = to siXML = ET.fromstring("<si xmlns='http://jabber.org/protocol/si'\ id='a0'\ mime-type='text/plain'\ profile='http://jabber.org/protocol/si/profile/file-transfer'>\ <file xmlns='http://jabber.org/protocol/si/profile/file-transfer'\ name='test.txt'\ size='4066'/>\ <feature xmlns='http://jabber.org/protocol/feature-neg'>\ <x xmlns='jabber:x:data' type='form'>\ <field var='stream-method' type='list-single'>\ <option><value>http://jabber.org/protocol/bytestreams</value></option>\ <option><value>http://jabber.org/protocol/ibb</value></option>\ </field>\ </x>\ </feature>\ </si>") offer.append(siXML) try: offer.send() except IqError as e: raise Exception("Unable to delete username", e) except IqTimeout: raise Exception("Server not responding")
def get_all_users(self): users = self.Iq() users['type'] = 'set' users['to'] = 'search.redes2020.xyz' users['from'] = self.boundjid.bare users['id'] = 'search_result' stanza = ET.fromstring( "<query xmlns='jabber:iq:search'>\ <x xmlns='jabber:x:data' type='submit'>\ <field type='hidden' var='FORM_TYPE'>\ <value>jabber:iq:search</value>\ </field>\ <field var='Username'>\ <value>1</value>\ </field>\ <field var='search'>\ <value>*</value>\ </field>\ </x>\ </query>" ) users.append(stanza) try: print("User List") usersR = users.send() for i in usersR.findall('.//{jabber:x:data}value'): if ((i.text != None) and ("@" in i.text)): print(i.text) except IqError as e: print(e)
def Unregister(self): iq = self.make_iq_set(ito='redes2020.xyz', ifrom=self.boundjid.user) item = ET.fromstring("<query xmlns='jabber:iq:register'> \ <remove/> \ </query>") iq.append(item) res = iq.send() print(res['type'])
def testPayload(self): """Test setting Iq stanza payload.""" iq = self.Iq() iq.setPayload(ET.Element('{test}tester')) self.check(iq, """ <iq id="0"> <tester xmlns="test" /> </iq> """, use_values=False)
def testItems(self): "Testing iq/pubsub/items stanzas" iq = self.Iq() iq['pubsub']['items']['node'] = 'crap' payload = ET.fromstring(""" <thinger xmlns="http://andyet.net/protocol/thinger" x="1" y='2'> <child1 /> <child2 normandy='cheese' foo='bar' /> </thinger>""") payload2 = ET.fromstring(""" <thinger2 xmlns="http://andyet.net/protocol/thinger2" x="12" y='22'> <child12 /> <child22 normandy='cheese2' foo='bar2' /> </thinger2>""") item = pubsub.Item() item['id'] = 'asdf' item['payload'] = payload item2 = pubsub.Item() item2['id'] = 'asdf2' item2['payload'] = payload2 iq['pubsub']['items'].append(item) iq['pubsub']['items'].append(item2) self.check( iq, """ <iq id="0"> <pubsub xmlns="http://jabber.org/protocol/pubsub"> <items node="crap"> <item id="asdf"> <thinger xmlns="http://andyet.net/protocol/thinger" y="2" x="1"> <child1 /> <child2 foo="bar" normandy="cheese" /> </thinger> </item> <item id="asdf2"> <thinger2 xmlns="http://andyet.net/protocol/thinger2" y="22" x="12"> <child12 /> <child22 foo="bar2" normandy="cheese2" /> </thinger2> </item> </items> </pubsub> </iq>""")
def testClear(self): """Test clearing a stanza.""" stanza = StanzaBase() stanza['to'] = '*****@*****.**' stanza['payload'] = ET.Element("{foo}foo") stanza.clear() self.failUnless(stanza['payload'] == [], "Stanza payload was not cleared after calling .clear()") self.failUnless(str(stanza['to']) == "*****@*****.**", "Stanza attributes were not preserved after calling .clear()")
def _mask_cmp(self, source, mask, use_ns=False, default_ns='__no_ns__'): """Compare an XML object against an XML mask. :param source: The :class:`~xml.etree.ElementTree.Element` XML object to compare against the mask. :param mask: The :class:`~xml.etree.ElementTree.Element` XML object serving as the mask. :param use_ns: Indicates if namespaces should be respected during the comparison. :default_ns: The default namespace to apply to elements that do not have a specified namespace. Defaults to ``"__no_ns__"``. """ if source is None: # If the element was not found. May happend during recursive calls. return False # Convert the mask to an XML object if it is a string. if not hasattr(mask, 'attrib'): try: mask = ET.fromstring(mask) except ExpatError: log.warning("Expat error: %s\nIn parsing: %s", '', mask) mask_ns_tag = "{%s}%s" % (self.default_ns, mask.tag) if source.tag not in [mask.tag, mask_ns_tag]: return False # If the mask includes text, compare it. if mask.text and source.text and \ source.text.strip() != mask.text.strip(): return False # Compare attributes. The stanza must include the attributes # defined by the mask, but may include others. for name, value in mask.attrib.items(): if source.attrib.get(name, "__None__") != value: return False # Recursively check subelements. matched_elements = {} for subelement in mask: matched = False for other in source.findall(subelement.tag): matched_elements[other] = False if self._mask_cmp(other, subelement, use_ns): if not matched_elements.get(other, False): matched_elements[other] = True matched = True if not matched: return False # Everything matches. return True
def __init__(self, criteria): """ Create a new XMLMask matcher. Arguments: criteria -- Either an XML object or XML string to use as a mask. """ MatcherBase.__init__(self, criteria) if isinstance(criteria, str): self._criteria = ET.fromstring(self._criteria) self.default_ns = 'jabber:client'
def testItems(self): "Testing iq/pubsub/items stanzas" iq = self.Iq() iq['pubsub']['items']['node'] = 'crap' payload = ET.fromstring(""" <thinger xmlns="http://andyet.net/protocol/thinger" x="1" y='2'> <child1 /> <child2 normandy='cheese' foo='bar' /> </thinger>""") payload2 = ET.fromstring(""" <thinger2 xmlns="http://andyet.net/protocol/thinger2" x="12" y='22'> <child12 /> <child22 normandy='cheese2' foo='bar2' /> </thinger2>""") item = pubsub.Item() item['id'] = 'asdf' item['payload'] = payload item2 = pubsub.Item() item2['id'] = 'asdf2' item2['payload'] = payload2 iq['pubsub']['items'].append(item) iq['pubsub']['items'].append(item2) self.check(iq, """ <iq id="0"> <pubsub xmlns="http://jabber.org/protocol/pubsub"> <items node="crap"> <item id="asdf"> <thinger xmlns="http://andyet.net/protocol/thinger" y="2" x="1"> <child1 /> <child2 foo="bar" normandy="cheese" /> </thinger> </item> <item id="asdf2"> <thinger2 xmlns="http://andyet.net/protocol/thinger2" y="22" x="12"> <child12 /> <child22 foo="bar2" normandy="cheese2" /> </thinger2> </item> </items> </pubsub> </iq>""")
def tryTostring(self, original='', expected=None, message='', **kwargs): """ Compare the result of calling tostring against an expected result. """ if not expected: expected = original if isinstance(original, str): xml = ET.fromstring(original) else: xml = original result = tostring(xml, **kwargs) self.failUnless(result == expected, "%s: %s" % (message, result))
def tryTostring(self, original='', expected=None, message='', **kwargs): """ Compare the result of calling tostring against an expected result. """ if not expected: expected=original if isinstance(original, str): xml = ET.fromstring(original) else: xml=original result = tostring(xml, **kwargs) self.failUnless(result == expected, "%s: %s" % (message, result))
def Unregister(self): iq = self.make_iq_set(ito='redes2020.xyz', ifrom=self.boundjid.user) item = ET.fromstring("<query xmlns='jabber:iq:register'> \ <remove/> \ </query>") iq.append(item) try: res = iq.send() if res['type'] == 'result': print(bcolors.OKGREEN + 'Cuenta eliminada' + bcolors.ENDC) except IqTimeout: print('Sin respuesta del server')
def delete_account(self): delete = self.Iq() delete['type'] = 'set' delete['from'] = self.boundjid.bare itemXML = ET.fromstring("<query xmlns='jabber:iq:register'><remove/></query>") delete.append(itemXML) try: delete.send(now=True) print("Deleted Account") self.logout() except IqError as e: print(e) self.logout()
def testPayload(self): """Test the 'payload' interface of StanzaBase.""" stanza = StanzaBase() self.failUnless(stanza['payload'] == [], "Empty stanza does not have an empty payload.") stanza['payload'] = ET.Element("{foo}foo") self.failUnless(len(stanza['payload']) == 1, "Stanza contents and payload do not match.") stanza['payload'] = ET.Element('{bar}bar') self.failUnless(len(stanza['payload']) == 2, "Stanza payload was not appended.") del stanza['payload'] self.failUnless(stanza['payload'] == [], "Stanza payload not cleared after deletion.") stanza['payload'] = [ET.Element('{foo}foo'), ET.Element('{bar}bar')] self.failUnless(len(stanza['payload']) == 2, "Adding multiple elements to stanza's payload did not work.")
def testReply(self): """Test creating a reply stanza.""" stanza = StanzaBase() stanza['to'] = "*****@*****.**" stanza['from'] = "*****@*****.**" stanza['payload'] = ET.Element("{foo}foo") stanza.reply() self.failUnless(str(stanza['to'] == "*****@*****.**"), "Stanza reply did not change 'to' attribute.") self.failUnless(stanza['payload'] == [], "Stanza reply did not empty stanza payload.")
def __init__(self, soundpacklist=False, tag=None, enabled=None, sensitivity=None, type=None, url=None, param='', *args, **kwargs): ''' Class constructor that builds the manually the XML of the stanza. This procedure is needed at the moment to be able to include text into the stanza root elements, as the default functionality does not seem to allow that. After defining the XML body of the stanza, ElementBase is initiated passing the body of the stanza as an argument for the `xml` parameter of the ElementBase class. ''' # Do we want to make checks on the values passed as parameters for each of # these tags? For example, do we want to ensure that enabled is only True # or False, or that tag is only one of Aggression, BabyCry, CarAlarm, etc.? ET.register_namespace('', 'intamac:intamacapi') root = ET.Element('{intamac:intamacapi}intamacapi') root.text = param if soundpacklist == True: sound_pack_list = ET.SubElement(root, 'SoundPackList') sound_pack = ET.SubElement(sound_pack_list, 'SoundPack') tag_tag = ET.SubElement(sound_pack, 'tag') tag_tag.text = tag tag_enabled = ET.SubElement(sound_pack, 'enabled') tag_enabled.text = enabled tag_sensitivity = ET.SubElement(sound_pack, 'sensitivity') tag_sensitivity.text = sensitivity ElementBase.__init__(self, xml=root) self['type'] = type self['url'] = url
def sendNotification(self, to, body, ntype): message = self.Message() message['to'] = to message['type'] = 'chat' message['body'] = body if (ntype == 'active'): itemXML = ET.fromstring( "<active xmlns='http://jabber.org/protocol/chatstates'/>") elif (ntype == 'composing'): itemXML = ET.fromstring( "<composing xmlns='http://jabber.org/protocol/chatstates'/>") elif (ntype == 'inactive'): itemXML = ET.fromstring( "<inactive xmlns='http://jabber.org/protocol/chatstates'/>") message.append(itemXML) try: message.send() except IqError as e: raise Exception("Unable to send active notification", e) sys.exit(1) except IqTimeout: raise Exception("Server Error")
def delete_Account(self): """ query extraído de: https://stackoverflow.com/questions/24023051/xmppframework-delete-a-registered-user-account """ #create an iq stanza type 'set' iq_stanza = self.make_iq_set(ito='redes2020.xyz', ifrom=self.boundjid.user) item = ET.fromstring("<query xmlns='jabber:iq:register'> \ <remove/> \ </query>") iq_stanza.append(item) ans = iq_stanza.send() if ans['type'] == 'result': print("SU cuetna ha sido elimanada con exito")
def _send_response(self, ito=None, ifrom=None, success=None, response=None, error=None, iq_response=None, element=None): iq = self.xmpp.Iq() iq['id'] = iq_response iq['to'] = ito iq['from'] = ifrom if success: logging.info( 'Send IQ response to: %s, from: %s, iq: %s, response: %s' % (ito, ifrom, iq_response, response)) query = ET.Element('{jabber:iq:docker}query') if element is not None: result = ET.Element(element) result.text = response query.append(result) iq['type'] = 'result' iq.append(query) else: logging.error( 'Send IQ response to: %s, from: %s, iq: %s, error: %s' % (ito, ifrom, iq_response, error)) iq['query'] = 'jabber:iq:docker' iq['type'] = 'error' iq['error'] = 'cancel' iq['error']['text'] = unicode(error) iq.send(now=True)
def GetUsers(self): iq = self.Iq() iq['type'] = 'set' iq['id'] = 'search_result' iq['to'] = 'search.redes2020.xyz' item = ET.fromstring("<query xmlns='jabber:iq:search'> \ <x xmlns='jabber:x:data' type='submit'> \ <field type='hidden' var='FORM_TYPE'> \ <value>jabber:iq:search</value> \ </field> \ <field var='Username'> \ <value>1</value> \ </field> \ <field var='search'> \ <value>*</value> \ </field> \ </x> \ </query>") iq.append(item) try: res = iq.send() data = [] temp = [] cont = 0 for i in res.findall('.//{jabber:x:data}value'): cont += 1 txt = '' if i.text == None: txt = '--' else: txt = i.text temp.append(txt) if cont == 4: cont = 0 data.append(temp) temp = [] us = [] for i in self.usuarios: us.append(i.get_usuario()) return us, data except IqTimeout: print('Sin respuesta del server') return [], []
def list_user(self): user = self.Iq() user['type'] = 'set' user['id'] = 'search_result' user['to'] = 'search.redes2020.xyz' user['from'] = self.boundjid.bare items = ET.fromstring("<query xmlns='jabber:iq:search'> \ <x xmlns='jabber:x:data' type='submit'> \ <field type='hidden' var='FORM_TYPE'> \ <value>jabber:iq:search</value> \ </field> \ <field var='Username'> \ <value>1</value> \ </field> \ <field var='search'> \ <value>*</value> \ </field> \ </x> \ </query>") user.append(items) try: usr_list = user.send() data = [] temp = [] cont = 0 #lopps through all users and puts them into a list for i in usr_list.findall('.//{jabber:x:data}value'): cont += 1 txt = '' if i.text == None: txt = 'None' else: txt = i.text temp.append(txt) if cont == 4: cont = 0 data.append(temp) temp = [] return data except IqError as err: print("Error: %s" % err.iq['error']['text']) except IqTimeout: print("El server se ha tardado")
def un_register(self, user): delete = self.Iq() delete['type'] = 'set' delete['from'] = user Stanza = ET.fromstring( "<query xmlns='jabber:iq:register'><remove/></query>") delete.append(Stanza) try: delete.send(now=True) print("The account was eliminated") self.disconnect(wait=False) print("logged off") except IqError as e: print("An error has occurred", e) except IqTimeout: print("No response")
def deleteAccount(self, account): delete = self.Iq() delete['from'] = account delete['type'] = 'set' stnz = ET.fromstring("<query xmlns='jabber:iq:register'>\ <remove/>\ </query>") delete.append(stnz) try: delete.send(now=True) print("Account deleted succesfuly") except IqError as e: raise Exception("Unable to delete account", e) sys.exit(1) except IqTimeout: raise Exception("Server Error")
def getUserInfo(self, jid): user = self.Iq() user['type'] = 'set' user['to'] = 'search.redes2020.xyz' user['from'] = self.boundjid.bare user['id'] = 'search_result' query = "<query xmlns='jabber:iq:search'>\ <x xmlns='jabber:x:data' type='submit'>\ <field type='hidden' var='FORM_TYPE'>\ <value>jabber:iq:search</value>\ </field>\ <field var='Username'>\ <value>1</value>\ </field>\ <field var='search'>\ <value>" + jid + "</value>\ </field>\ </x>\ </query>" itemXML = ET.fromstring(query) user.append(itemXML) try: x = user.send() data = [] temp = [] cont = 0 print(x) for i in x.findall('.//{jabber:x:data}value'): cont += 1 txt = '' if i.text != None: txt = i.text temp.append(txt) #contador hasta 4 porque el servidor solo retorna 4 values field por usuario #email, jid, username y name if cont == 4: cont = 0 data.append(temp) temp = [] return data except IqError as e: raise Exception("Unable to get user information", e) except IqTimeout: raise Exception("Server not responding")
def __read_xml(self): """ Parse the incoming XML stream, raising stream events for each received stanza. """ depth = 0 root = None try: for (event, xml) in ET.iterparse(self.filesocket, (b'end', b'start')): if event == b'start': if depth == 0: # We have received the start of the root element. root = xml # Perform any stream initialization actions, such # as handshakes. self.stream_end_event.clear() self.start_stream_handler(root) depth += 1 if event == b'end': depth -= 1 if depth == 0: # The stream's root element has closed, # terminating the stream. log.debug("End of stream recieved") self.stream_end_event.set() return False elif depth == 1: # We only raise events for stanzas that are direct # children of the root element. try: self.__spawn_event(xml) except RestartStream: return True if root: # Keep the root element empty of children to # save on memory use. root.clear() except SyntaxError: log.error("Error reading from XML stream.") log.debug("Ending read XML loop")
def _mask_cmp(self, source, mask, use_ns=False, default_ns='__no_ns__'): """ Compare an XML object against an XML mask. Arguments: source -- The XML object to compare against the mask. mask -- The XML object serving as the mask. use_ns -- Indicates if namespaces should be respected during the comparison. default_ns -- The default namespace to apply to elements that do not have a specified namespace. Defaults to "__no_ns__". """ use_ns = not IGNORE_NS if source is None: # If the element was not found. May happend during recursive calls. return False # Convert the mask to an XML object if it is a string. if not hasattr(mask, 'attrib'): try: mask = ET.fromstring(mask) except ExpatError: log.warning("Expat error: %s\nIn parsing: %s" % ('', mask)) if not use_ns: # Compare the element without using namespaces. source_tag = source.tag.split('}', 1)[-1] mask_tag = mask.tag.split('}', 1)[-1] if source_tag != mask_tag: return False else: # Compare the element using namespaces mask_ns_tag = "{%s}%s" % (self.default_ns, mask.tag) if source.tag not in [mask.tag, mask_ns_tag]: return False # If the mask includes text, compare it. if mask.text and source.text and source.text.strip() != mask.text.strip(): return False # Compare attributes. The stanza must include the attributes # defined by the mask, but may include others. for name, value in mask.attrib.items(): if source.attrib.get(name, "__None__") != value: return False # Recursively check subelements. matched_elements = {} for subelement in mask: if use_ns: matched = False for other in source.findall(subelement.tag): matched_elements[other] = False if self._mask_cmp(other, subelement, use_ns): if not matched_elements.get(other, False): matched_elements[other] = True matched = True if not matched: return False else: if not self._mask_cmp(self._get_child(source, subelement.tag), subelement, use_ns): return False # Everything matches. return True
const=5, default=logging.INFO, ) # Component name and secret options. optp.add_option("-c", "--config", help="path to config file", dest="config", default="config.xml") opts, args = optp.parse_args() # Setup logging. logging.basicConfig(level=opts.loglevel, format="%(levelname)-8s %(message)s") # Load configuration data. config_file = open(opts.config, "r+") config_data = "\n".join([line for line in config_file]) config = Config(xml=ET.fromstring(config_data)) config_file.close() # Setup the ConfigComponent and register plugins. Note that while plugins # may have interdependencies, the order in which you register them does # not matter. xmpp = ConfigComponent(config) xmpp.registerPlugin("xep_0030") # Service Discovery xmpp.registerPlugin("xep_0004") # Data Forms xmpp.registerPlugin("xep_0060") # PubSub xmpp.registerPlugin("xep_0199") # XMPP Ping # Connect to the XMPP server and start processing XMPP stanzas. if xmpp.connect(): xmpp.process(threaded=False) print("Done")
def __init__(self, criteria): MatcherBase.__init__(self, criteria) if isinstance(criteria, str): self._criteria = ET.fromstring(self._criteria) self.default_ns = 'jabber:client'