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 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 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 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 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 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 __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 _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 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 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 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 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 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 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 sendNotificationChatRoom(self, to, body): message = self.Message() message['to'] = to message['type'] = 'groupchat' message['body'] = body itemXML = ET.fromstring( "<active 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 deleteUser(self, username): delete = self.Iq() delete['type'] = 'set' delete['from'] = username itemXML = ET.fromstring( "<query xmlns='jabber:iq:register'><remove/></query>") delete.append(itemXML) try: delete.send(now=True) self.disconnect() print("Account deleted succesfuly") print('\n') except IqError as e: raise Exception("Unable to delete username", e) sys.exit(1) except IqTimeout: raise Exception("Server not responding")
def register_push_fcm(self, token): self['xep_0050'].start_command(jid=self.__server, node='register-push-fcm', session={ 'next': self._command_next, 'error': self._command_error, 'id': 'execute', 'payload': [ ET.fromstring(""" <x xmlns='jabber:x:data' type='submit'> <field var='token'> <value>%s</value> </field> </x>""" % token) ] })
def deleteUser(self): iq = self.make_iq_set(ito='redes2020.xyz', ifrom=self.boundjid.user) xml = ET.fromstring("<query xmlns='jabber:iq:register'>\ <remove/>\ </query>") iq.append(xml) try: response = iq.send() if response['type'] == 'result': print("Usuario eliminado") except IqError as e: print(f"No se pudo eliminar el usuario\n {e.iq['error']['text']}") self.disconnect() except IqTimeout: print("El server no responde D:") self.disconnect()
def getUsers(self): iq = self.Iq() iq['type'] = 'set' iq['from'] = self.boundjid.bare iq['id'] = 'search_result' iq['to'] = 'search.redes2020.xyz' xml = 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(xml) try: response = iq.send() data = [] temp = [] cont = 0 for i in response.findall('.//{jabber:x:data}value'): cont += 1 txt = '' if i.text != None: txt = i.text temp.append(txt) if cont == 4: cont = 0 data.append(temp) temp = [] return data except IqError as e: print( f"No se pudo obtener el listado de usuarios\n {e.iq['error']['text']}" ) self.disconnect() except IqTimeout: print("El server no responde D:") self.disconnect()
def userInfo(self): username = input('Username que desea consultar: ') iq = self.Iq() iq['type'] = 'set' iq['id'] = 'search_result' iq['to'] = 'search.redes2020.xyz' iq['from'] = self.boundjid.bare 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>" + username + '@redes2020.xyz' + "</value>\ </field>\ </x>\ </query>") iq.append(item) try: response = iq.send() data = [] temp = [] cont = 0 for i in response.findall('.//{jabber:x:data}value'): cont += 1 txt = '' if i.text != None: txt = i.text temp.append(txt) if cont == 4: cont = 0 data.append(temp) temp = [] return data except IqError as e: print('No se pudo agregar usuario a los contactos', e) except IqTimeout: print("El server no responde D:") self.disconnect()
def notificate(self, jid): message = self.Message() message['to'] = jid message['type'] = 'chat' message['body'] = 'Ya estoy conectado!!!' xml = ET.fromstring( "<active xmlns='http://jabber.org/protocol/chatstates'/>") message.append(xml) try: message.send() except IqError as e: print( f"No se pudo notificar que estas conectado\n {e.iq['error']['text']}" ) self.disconnect() except IqTimeout: print("El server no responde D:") self.disconnect()
def GetUser(self, username): 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>" + username + "</value> \ </field> \ </x> \ </query>") iq.append(item) 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: if username.lower() == i.get_username(): us.append(i.get_usuario()) return us, data
def sendNotification(self, body): #Create meesage Stanza message = self.Message() message['type'] = 'chat' message['body'] = body message.append( ET.fromstring( "<active xmlns='http://jabber.org/protocol/chatstates'/>")) #Get all elements in roster groups = self.client_roster.groups() for group in groups: for jid in groups[group]: message['to'] = jid #JID try: message.send() except IqError as e: print("Could not send notification") except IqTimeout: print("Server did no respond")
def info_user(self, jid): 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>"+jid+"</value>\ </field>\ </x>\ </query>") user.append(items) info = user.send() #print(info['value']) data = [] temp = [] cont = 0 for i in info.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
def register_push_fcm(self, token, ref=None): if ref: ref_payload = "<field var='backend_ref'><value>%s</value></field>" % ref else: ref_payload = "" self['xep_0050'].start_command(jid=self.__server, node='register-push-fcm', session={ 'next': self._command_next, 'error': self._command_error, 'id': 'execute', 'payload': [ ET.fromstring(""" <x xmlns='jabber:x:data' type='submit'> %s<field var='token'><value>%s</value></field> </x>""" % (ref_payload, token)) ] })
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 _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
def __init__(self, criteria): MatcherBase.__init__(self, criteria) if isinstance(criteria, str): self._criteria = ET.fromstring(self._criteria) self.default_ns = 'jabber:client'