예제 #1
0
    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>""")
예제 #2
0
    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>""")
예제 #3
0
    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")
예제 #4
0
 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)
예제 #5
0
 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
예제 #6
0
 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)
예제 #7
0
    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'])
예제 #8
0
 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>""")
예제 #9
0
    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'
예제 #10
0
파일: xmlmask.py 프로젝트: 2M1R/SleekXMPP
    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
예제 #11
0
    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'
예제 #12
0
    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
예제 #13
0
 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>""")
예제 #14
0
    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')
예제 #15
0
 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))
예제 #16
0
 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))
예제 #17
0
 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()
예제 #18
0
    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")
예제 #20
0
    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 [], []
예제 #21
0
    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")
예제 #22
0
 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")
예제 #23
0
    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")
예제 #24
0
    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")
예제 #25
0
    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")
예제 #26
0
 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")
예제 #27
0
 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)
                                        ]
                                    })
예제 #28
0
    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()
예제 #29
0
    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()
예제 #30
0
    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()
예제 #31
0
 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()
예제 #32
0
    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
예제 #33
0
 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")
예제 #34
0
    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
예제 #35
0
 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))
                                        ]
                                    })
예제 #36
0
        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")
예제 #37
0
    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
예제 #38
0
파일: xmlmask.py 프로젝트: AmiZya/emesene
 def __init__(self, criteria):
     MatcherBase.__init__(self, criteria)
     if isinstance(criteria, str):
         self._criteria = ET.fromstring(self._criteria)
     self.default_ns = 'jabber:client'