예제 #1
0
    def __init__(self, default_ns="jabber:client"):
        """
        Adapt an XML stream for use with XMPP.

        Arguments:
            default_ns -- Ensure that the correct default XML namespace
                          is used during initialization.
        """
        XMLStream.__init__(self)

        # To comply with PEP8, method names now use underscores.
        # Deprecated method names are re-mapped for backwards compatibility.
        self.registerPlugin = self.register_plugin
        self.makeIq = self.make_iq
        self.makeIqGet = self.make_iq_get
        self.makeIqResult = self.make_iq_result
        self.makeIqSet = self.make_iq_set
        self.makeIqError = self.make_iq_error
        self.makeIqQuery = self.make_iq_query
        self.makeQueryRoster = self.make_query_roster
        self.makeMessage = self.make_message
        self.makePresence = self.make_presence
        self.sendMessage = self.send_message
        self.sendPresence = self.send_presence
        self.sendPresenceSubscription = self.send_presence_subscription

        self.default_ns = default_ns
        self.stream_ns = "http://etherx.jabber.org/streams"

        self.boundjid = JID("")

        self.plugin = {}
        self.roster = {}
        self.is_component = False
        self.auto_authorize = True
        self.auto_subscribe = True

        self.sentpresence = False

        self.register_handler(
            Callback(
                "IM", MatchXPath("{%s}message/{%s}body" % (self.default_ns, self.default_ns)), self._handle_message
            )
        )
        self.register_handler(Callback("Presence", MatchXPath("{%s}presence" % self.default_ns), self._handle_presence))

        self.add_event_handler("presence_subscribe", self._handle_subscribe)
        self.add_event_handler("disconnected", self._handle_disconnected)

        # Set up the XML stream with XMPP's root stanzas.
        self.registerStanza(Message)
        self.registerStanza(Iq)
        self.registerStanza(Presence)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
        register_stanza_plugin(Message, HTMLIM)
예제 #2
0
    def __init__(self, default_ns='jabber:client'):
        """
        Adapt an XML stream for use with XMPP.

        Arguments:
            default_ns -- Ensure that the correct default XML namespace
                          is used during initialization.
        """
        XMLStream.__init__(self)

        # To comply with PEP8, method names now use underscores.
        # Deprecated method names are re-mapped for backwards compatibility.
        self.default_ns = default_ns
        self.stream_ns = 'http://etherx.jabber.org/streams'

        self.boundjid = JID("")

        self.plugin = {}
        self.plugin_config = {}
        self.plugin_whitelist = []
        self.roster = {}
        self.is_component = False
        self.auto_authorize = True
        self.auto_subscribe = True

        self.sentpresence = False

        self.register_handler(
            Callback('IM',
                     MatchXPath('{%s}message/{%s}body' % (self.default_ns,
                                                          self.default_ns)),
                     self._handle_message))
        self.register_handler(
            Callback('Presence',
                     MatchXPath("{%s}presence" % self.default_ns),
                     self._handle_presence))
        self.register_handler(
            Callback('Stream Error',
                     MatchXPath("{%s}error" % self.stream_ns),
                     self._handle_stream_error))

        self.add_event_handler('presence_subscribe',
                               self._handle_subscribe)
        self.add_event_handler('disconnected',
                               self._handle_disconnected)

        # Set up the XML stream with XMPP's root stanzas.
        self.register_stanza(Message)
        self.register_stanza(Iq)
        self.register_stanza(Presence)
        self.register_stanza(StreamError)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
        register_stanza_plugin(Message, HTMLIM)
예제 #3
0
    def __init__(self, default_ns='jabber:client'):
        """
        Adapt an XML stream for use with XMPP.

        Arguments:
            default_ns -- Ensure that the correct default XML namespace
                          is used during initialization.
        """
        XMLStream.__init__(self)

        # To comply with PEP8, method names now use underscores.
        # Deprecated method names are re-mapped for backwards compatibility.
        self.default_ns = default_ns
        self.stream_ns = 'http://etherx.jabber.org/streams'

        self.boundjid = JID("")

        self.plugin = {}
        self.plugin_config = {}
        self.plugin_whitelist = []
        self.roster = {}
        self.is_component = False
        self.auto_authorize = True
        self.auto_subscribe = True

        self.sentpresence = False

        self.register_handler(
            Callback(
                'IM',
                MatchXPath('{%s}message/{%s}body' %
                           (self.default_ns, self.default_ns)),
                self._handle_message))
        self.register_handler(
            Callback('Presence', MatchXPath("{%s}presence" % self.default_ns),
                     self._handle_presence))
        self.register_handler(
            Callback('Stream Error', MatchXPath("{%s}error" % self.stream_ns),
                     self._handle_stream_error))

        self.add_event_handler('presence_subscribe', self._handle_subscribe)
        self.add_event_handler('disconnected', self._handle_disconnected)

        # Set up the XML stream with XMPP's root stanzas.
        self.register_stanza(Message)
        self.register_stanza(Iq)
        self.register_stanza(Presence)
        self.register_stanza(StreamError)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
        register_stanza_plugin(Message, HTMLIM)
예제 #4
0
    def connect(self, address=tuple(), reattempt=True,
                use_tls=True, use_ssl=False):
        """
        Connect to the XMPP server.

        When no address is given, a SRV lookup for the server will
        be attempted. If that fails, the server user in the JID
        will be used.

        Arguments:
            address   -- A tuple containing the server's host and port.
            reattempt -- If True, reattempt the connection if an
                         error occurs. Defaults to True.
            use_tls   -- Indicates if TLS should be used for the
                         connection. Defaults to True.
            use_ssl   -- Indicates if the older SSL connection method
                         should be used. Defaults to False.
        """
        self.session_started_event.clear()
        if not address:
            address = (self.boundjid.host, 5222)

        return XMLStream.connect(self, address[0], address[1],
                                 use_tls=use_tls, use_ssl=use_ssl,
                                 reattempt=reattempt)
예제 #5
0
    def connect(self,
                address=tuple(),
                reattempt=True,
                use_tls=True,
                use_ssl=False):
        """
        Connect to the XMPP server.

        When no address is given, a SRV lookup for the server will
        be attempted. If that fails, the server user in the JID
        will be used.

        Arguments:
            address   -- A tuple containing the server's host and port.
            reattempt -- If True, reattempt the connection if an
                         error occurs. Defaults to True.
            use_tls   -- Indicates if TLS should be used for the
                         connection. Defaults to True.
            use_ssl   -- Indicates if the older SSL connection method
                         should be used. Defaults to False.
        """
        self.session_started_event.clear()
        if not address:
            address = (self.boundjid.host, 5222)

        return XMLStream.connect(self,
                                 address[0],
                                 address[1],
                                 use_tls=use_tls,
                                 use_ssl=use_ssl,
                                 reattempt=reattempt)
예제 #6
0
    def process(self, *args, **kwargs):
        """
        Overrides XMLStream.process.

        Initialize the XML streams and begin processing events.

        The number of threads used for processing stream events is determined
        by HANDLER_THREADS.

        Arguments:
            block -- If block=False then event dispatcher will run
                     in a separate thread, allowing for the stream to be
                     used in the background for another application.
                     Otherwise, process(block=True) blocks the current thread.
                     Defaults to False.

            **threaded is deprecated and included for API compatibility**
            threaded -- If threaded=True then event dispatcher will run
                        in a separate thread, allowing for the stream to be
                        used in the background for another application.
                        Defaults to True.

            Event handlers and the send queue will be threaded
            regardless of these parameters.
        """
        for name in self.plugin:
            if not self.plugin[name].post_inited:
                self.plugin[name].post_init()
        return XMLStream.process(self, *args, **kwargs)
예제 #7
0
    def connect(self, host=None, port=None, use_ssl=False,
                      use_tls=False, reattempt=True):
        """Connect to the server.

        Setting ``reattempt`` to ``True`` will cause connection attempts to
        be made every second until a successful connection is established.

        :param host: The name of the desired server for the connection.
                     Defaults to :attr:`server_host`.
        :param port: Port to connect to on the server.
                     Defauts to :attr:`server_port`.
        :param use_ssl: Flag indicating if SSL should be used by connecting
                        directly to a port using SSL.
        :param use_tls: Flag indicating if TLS should be used, allowing for
                        connecting to a port without using SSL immediately and
                        later upgrading the connection.
        :param reattempt: Flag indicating if the socket should reconnect
                          after disconnections.
        """
        if host is None:
            host = self.server_host
        if port is None:
            port = self.server_port

        self.server_name = self.boundjid.host

        if use_tls:
            log.info("XEP-0114 components can not use TLS")

        log.debug("Connecting to %s:%s", host, port)
        return XMLStream.connect(self, host=host, port=port,
                                       use_ssl=use_ssl,
                                       use_tls=False,
                                       reattempt=reattempt)
예제 #8
0
    def connect(self, host=None, port=None, use_ssl=False, use_tls=False, reattempt=True):
        """Connect to the server.

        Setting ``reattempt`` to ``True`` will cause connection attempts to
        be made every second until a successful connection is established.

        :param host: The name of the desired server for the connection.
                     Defaults to :attr:`server_host`.
        :param port: Port to connect to on the server.
                     Defauts to :attr:`server_port`.
        :param use_ssl: Flag indicating if SSL should be used by connecting
                        directly to a port using SSL.
        :param use_tls: Flag indicating if TLS should be used, allowing for
                        connecting to a port without using SSL immediately and
                        later upgrading the connection.
        :param reattempt: Flag indicating if the socket should reconnect
                          after disconnections.
        """
        if host is None:
            host = self.server_host
        if port is None:
            port = self.server_port

        self.server_name = self.boundjid.host

        if use_tls:
            log.info("XEP-0114 components can not use TLS")

        log.debug("Connecting to %s:%s", host, port)
        return XMLStream.connect(self, host=host, port=port, use_ssl=use_ssl, use_tls=False, reattempt=reattempt)
예제 #9
0
    def connect(self, address=tuple(), reattempt=True,
                use_tls=True, use_ssl=False):
        """Connect to the XMPP server.

        When no address is given, a SRV lookup for the server will
        be attempted. If that fails, the server user in the JID
        will be used.

        :param address   -- A tuple containing the server's host and port.
        :param reattempt: If ``True``, repeat attempting to connect if an
                         error occurs. Defaults to ``True``.
        :param use_tls: Indicates if TLS should be used for the
                        connection. Defaults to ``True``.
        :param use_ssl: Indicates if the older SSL connection method
                        should be used. Defaults to ``False``.
        """
        self.session_started_event.clear()

        # If an address was provided, disable using DNS SRV lookup;
        # otherwise, use the domain from the client JID with the standard
        # XMPP client port and allow SRV lookup.
        if address:
            self.dns_service = None
        else:
            address = (self.boundjid.host, 5222)
            self.dns_service = 'xmpp-client'

        self._expected_server_name = self.boundjid.host

        return XMLStream.connect(self, address[0], address[1],
                                 use_tls=use_tls, use_ssl=use_ssl,
                                 reattempt=reattempt)
예제 #10
0
    def process(self, *args, **kwargs):
        """
        Overrides XMLStream.process.

        Initialize the XML streams and begin processing events.

        The number of threads used for processing stream events is determined
        by HANDLER_THREADS.

        Arguments:
            block -- If block=False then event dispatcher will run
                     in a separate thread, allowing for the stream to be
                     used in the background for another application.
                     Otherwise, process(block=True) blocks the current thread.
                     Defaults to False.

            **threaded is deprecated and included for API compatibility**
            threaded -- If threaded=True then event dispatcher will run
                        in a separate thread, allowing for the stream to be
                        used in the background for another application.
                        Defaults to True.

            Event handlers and the send queue will be threaded
            regardless of these parameters.
        """
        for name in self.plugin:
            if not self.plugin[name].post_inited:
                self.plugin[name].post_init()
        return XMLStream.process(self, *args, **kwargs)
예제 #11
0
    def process(self, *args, **kwargs):
        """Initialize plugins and begin processing the XML stream.

        The number of threads used for processing stream events is determined
        by :data:`HANDLER_THREADS`.

        :param bool block: If ``False``, then event dispatcher will run
                    in a separate thread, allowing for the stream to be
                    used in the background for another application.
                    Otherwise, ``process(block=True)`` blocks the current
                    thread. Defaults to ``False``.
        :param bool threaded: **DEPRECATED**
                    If ``True``, then event dispatcher will run
                    in a separate thread, allowing for the stream to be
                    used in the background for another application.
                    Defaults to ``True``. This does **not** mean that no
                    threads are used at all if ``threaded=False``.

        Regardless of these threading options, these threads will 
        always exist:

        - The event queue processor
        - The send queue processor
        - The scheduler
        """
        for name in self.plugin:
            if not self.plugin[name].post_inited:
                self.plugin[name].post_init()
        return XMLStream.process(self, *args, **kwargs)
예제 #12
0
    def process(self, *args, **kwargs):
        """Initialize plugins and begin processing the XML stream.

        The number of threads used for processing stream events is determined
        by :data:`HANDLER_THREADS`.

        :param bool block: If ``False``, then event dispatcher will run
                    in a separate thread, allowing for the stream to be
                    used in the background for another application.
                    Otherwise, ``process(block=True)`` blocks the current
                    thread. Defaults to ``False``.
        :param bool threaded: **DEPRECATED**
                    If ``True``, then event dispatcher will run
                    in a separate thread, allowing for the stream to be
                    used in the background for another application.
                    Defaults to ``True``. This does **not** mean that no
                    threads are used at all if ``threaded=False``.

        Regardless of these threading options, these threads will
        always exist:

        - The event queue processor
        - The send queue processor
        - The scheduler
        """
        for name in self.plugin:
            if not hasattr(self.plugin[name], 'post_inited'):
                if hasattr(self.plugin[name], 'post_init'):
                    self.plugin[name].post_init()
                self.plugin[name].post_inited = True
        return XMLStream.process(self, *args, **kwargs)
예제 #13
0
    def connect(self, address=tuple(), reattempt=True,
                use_tls=True, use_ssl=False):
        """Connect to the XMPP server.

        When no address is given, a SRV lookup for the server will
        be attempted. If that fails, the server user in the JID
        will be used.

        :param address   -- A tuple containing the server's host and port.
        :param reattempt: If ``True``, repeat attempting to connect if an
                         error occurs. Defaults to ``True``.
        :param use_tls: Indicates if TLS should be used for the
                        connection. Defaults to ``True``.
        :param use_ssl: Indicates if the older SSL connection method
                        should be used. Defaults to ``False``.
        """
        self.session_started_event.clear()

        # If an address was provided, disable using DNS SRV lookup;
        # otherwise, use the domain from the client JID with the standard
        # XMPP client port and allow SRV lookup.
        if address:
            self.dns_service = None
        else:
            address = (self.boundjid.host, 5222)
            self.dns_service = 'xmpp-client'

        self._expected_server_name = self.boundjid.host

        return XMLStream.connect(self, address[0], address[1],
                                 use_tls=use_tls, use_ssl=use_ssl,
                                 reattempt=reattempt)
예제 #14
0
    def connect(self, address=tuple(), reattempt=True,
                use_tls=True, use_ssl=False):
        """Connect to the XMPP server.

        When no address is given, a SRV lookup for the server will
        be attempted. If that fails, the server user in the JID
        will be used.

        :param address   -- A tuple containing the server's host and port.
        :param reattempt: If ``True``, repeat attempting to connect if an
                         error occurs. Defaults to ``True``.
        :param use_tls: Indicates if TLS should be used for the
                        connection. Defaults to ``True``.
        :param use_ssl: Indicates if the older SSL connection method
                        should be used. Defaults to ``False``.
        """
        self.session_started_event.clear()
        if not self.server and len(address): # we used anonymous authentication
            self.stream_header = """<stream:stream to='%s' xmlns:stream='http://etherx.jabber.org/streams' xmlns='%s' version='1.0'>""" % (address[0],self.default_ns)
        if not address:
            address = (self.boundjid.host, 5222)

        return XMLStream.connect(self, address[0], address[1],
                                 use_tls=use_tls, use_ssl=use_ssl,
                                 reattempt=reattempt)
예제 #15
0
    def connect(self, address=tuple(), reattempt=True, use_tls=True):
        """
        Connect to the XMPP server.

        When no address is given, a SRV lookup for the server will
        be attempted. If that fails, the server user in the JID
        will be used.

        Arguments:
            address   -- A tuple containing the server's host and port.
            reattempt -- If True, reattempt the connection if an
                         error occurs. Defaults to True.
            use_tls   -- Indicates if TLS should be used for the
                         connection. Defaults to True.
        """
        self.session_started_event.clear()
        if not address or len(address) < 2:
            if not self.srv_support:
                log.debug("Did not supply (address, port) to connect" + \
                              " to and no SRV support is installed" + \
                              " (http://www.dnspython.org)." + \
                              " Continuing to attempt connection, using" + \
                              " server hostname from JID.")
            else:
                log.debug("Since no address is supplied," + \
                              "attempting SRV lookup.")
                try:
                    xmpp_srv = "_xmpp-client._tcp.%s" % self.boundjid.host
                    answers = dns.resolver.query(xmpp_srv, dns.rdatatype.SRV)
                except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
                    log.debug("No appropriate SRV record found." + \
                                  " Using JID server name.")
                except (dns.exception.Timeout,):
                    log.debug("DNS resolution timed out.")
                else:
                    # Pick a random server, weighted by priority.

                    addresses = {}
                    intmax = 0
                    for answer in answers:
                        intmax += answer.priority
                        addresses[intmax] = (answer.target.to_text()[:-1],
                                             answer.port)
                    #python3 returns a generator for dictionary keys
                    priorities = [x for x in addresses.keys()]
                    priorities.sort()

                    picked = random.randint(0, intmax)
                    for priority in priorities:
                        if picked <= priority:
                            address = addresses[priority]
                            break

        if not address:
            # If all else fails, use the server from the JID.
            address = (self.boundjid.host, 5222)

        return XMLStream.connect(self, address[0], address[1],
                                 use_tls=use_tls, reattempt=reattempt)
예제 #16
0
    def connect(self):
        """
        Connect to the server.

        Overrides XMLStream.connect.
        """
        log.debug("Connecting to %s:%s" % (self.server_host, self.server_port))
        return XMLStream.connect(self, self.server_host, self.server_port)
예제 #17
0
    def connect(self):
        """
        Connect to the server.

        Overrides XMLStream.connect.
        """
        log.debug("Connecting to %s:%s" % (self.server_host,
                                               self.server_port))
        return XMLStream.connect(self, self.server_host,
                                       self.server_port)
예제 #18
0
    def process(self, *args, **kwargs):
        """
        Ensure that plugin inter-dependencies are handled before starting
        event processing.

        Overrides XMLStream.process.
        """
        for name in self.plugin:
            if not self.plugin[name].post_inited:
                self.plugin[name].post_init()
        return XMLStream.process(self, *args, **kwargs)
예제 #19
0
    def process(self, *args, **kwargs):
        """
        Ensure that plugin inter-dependencies are handled before starting
        event processing.

        Overrides XMLStream.process.
        """
        for name in self.plugin:
            if not self.plugin[name].post_inited:
                self.plugin[name].post_init()
        return XMLStream.process(self, *args, **kwargs)
예제 #20
0
    def connect(self, address=tuple()):
        """
        Connect to the XMPP server.

        When no address is given, a SRV lookup for the server will
        be attempted. If that fails, the server user in the JID
        will be used.

        Arguments:
            address -- A tuple containing the server's host and port.
        """
        self.session_started_event.clear()
        if not address or len(address) < 2:
            if not self.srv_support:
                log.debug("Did not supply (address, port) to connect" + \
                              " to and no SRV support is installed" + \
                              " (http://www.dnspython.org)." + \
                              " Continuing to attempt connection, using" + \
                              " server hostname from JID.")
            else:
                log.debug("Since no address is supplied," + \
                              "attempting SRV lookup.")
                try:
                    xmpp_srv = "_xmpp-client._tcp.%s" % self.server
                    answers = dns.resolver.query(xmpp_srv, dns.rdatatype.SRV)
                except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
                    log.debug("No appropriate SRV record found." + \
                                  " Using JID server name.")
                else:
                    # Pick a random server, weighted by priority.

                    addresses = {}
                    intmax = 0
                    for answer in answers:
                        intmax += answer.priority
                        addresses[intmax] = (answer.target.to_text()[:-1],
                                             answer.port)
                    #python3 returns a generator for dictionary keys
                    priorities = [x for x in addresses.keys()]
                    priorities.sort()

                    picked = random.randint(0, intmax)
                    for priority in priorities:
                        if picked <= priority:
                            address = addresses[priority]
                            break

        if not address:
            # If all else fails, use the server from the JID.
            address = (self.boundjid.host, 5222)

        return XMLStream.connect(self, address[0], address[1], use_tls=True)
예제 #21
0
    def connect(self, address=tuple()):
        """
        Connect to the XMPP server.

        When no address is given, a SRV lookup for the server will
        be attempted. If that fails, the server user in the JID
        will be used.

        Arguments:
            address -- A tuple containing the server's host and port.
        """
        self.session_started_event.clear()
        if not address or len(address) < 2 and not self.srv_support:
            log.debug("Did not supply (address, port) to connect" + \
                          " to and no SRV support is installed" + \
                          " (http://www.dnspython.org)." + \
                          " Continuing to attempt connection, using" + \
                          " server hostname from JID.")
        if not address:
            # If all else fails, use the server from the JID.
            address = (self.boundjid.host, 5222)

        return XMLStream.connect(self, address[0], address[1], use_tls=True)
예제 #22
0
    def __init__(self, jid='', default_ns='jabber:client'):
        XMLStream.__init__(self)

        self.default_ns = default_ns
        self.stream_ns = 'http://etherx.jabber.org/streams'
        self.namespace_map[self.stream_ns] = 'stream'

        #: An identifier for the stream as given by the server.
        self.stream_id = None

        #: The JabberID (JID) used by this connection.
        self.boundjid = JID(jid)

        #: A dictionary mapping plugin names to plugins.
        self.plugin = {}

        #: Configuration options for whitelisted plugins.
        #: If a plugin is registered without any configuration,
        #: and there is an entry here, it will be used.
        self.plugin_config = {}

        #: A list of plugins that will be loaded if
        #: :meth:`register_plugins` is called.
        self.plugin_whitelist = []

        #: The main roster object. This roster supports multiple
        #: owner JIDs, as in the case for components. For clients
        #: which only have a single JID, see :attr:`client_roster`.
        self.roster = roster.Roster(self)
        self.roster.add(self.boundjid.bare)

        #: The single roster for the bound JID. This is the
        #: equivalent of::
        #:
        #:     self.roster[self.boundjid.bare]
        self.client_roster = self.roster[self.boundjid.bare]

        #: The distinction between clients and components can be
        #: important, primarily for choosing how to handle the
        #: ``'to'`` and ``'from'`` JIDs of stanzas.
        self.is_component = False

        #: Flag indicating that the initial presence broadcast has
        #: been sent. Until this happens, some servers may not
        #: behave as expected when sending stanzas.
        self.sentpresence = False

        #: A reference to :mod:`sleekxmpp.stanza` to make accessing
        #: stanza classes easier.
        self.stanza = sleekxmpp.stanza

        self.register_handler(
            Callback(
                'IM',
                MatchXPath('{%s}message/{%s}body' %
                           (self.default_ns, self.default_ns)),
                self._handle_message))
        self.register_handler(
            Callback('Presence', MatchXPath("{%s}presence" % self.default_ns),
                     self._handle_presence))
        self.register_handler(
            Callback('Stream Error', MatchXPath("{%s}error" % self.stream_ns),
                     self._handle_stream_error))

        self.add_event_handler('disconnected', self._handle_disconnected)
        self.add_event_handler('presence_available', self._handle_available)
        self.add_event_handler('presence_dnd', self._handle_available)
        self.add_event_handler('presence_xa', self._handle_available)
        self.add_event_handler('presence_chat', self._handle_available)
        self.add_event_handler('presence_away', self._handle_available)
        self.add_event_handler('presence_unavailable',
                               self._handle_unavailable)
        self.add_event_handler('presence_subscribe', self._handle_subscribe)
        self.add_event_handler('presence_subscribed', self._handle_subscribed)
        self.add_event_handler('presence_unsubscribe',
                               self._handle_unsubscribe)
        self.add_event_handler('presence_unsubscribed',
                               self._handle_unsubscribed)
        self.add_event_handler('roster_subscription_request',
                               self._handle_new_subscription)

        # Set up the XML stream with XMPP's root stanzas.
        self.register_stanza(Message)
        self.register_stanza(Iq)
        self.register_stanza(Presence)
        self.register_stanza(StreamError)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
        register_stanza_plugin(Message, HTMLIM)
예제 #23
0
파일: basexmpp.py 프로젝트: RaHus/SleekXMPP
    def __init__(self, jid="", default_ns="jabber:client"):
        XMLStream.__init__(self)

        self.default_ns = default_ns
        self.stream_ns = "http://etherx.jabber.org/streams"
        self.namespace_map[self.stream_ns] = "stream"

        #: An identifier for the stream as given by the server.
        self.stream_id = None

        #: The JabberID (JID) used by this connection.
        self.boundjid = JID(jid)

        #: A dictionary mapping plugin names to plugins.
        self.plugin = {}

        #: Configuration options for whitelisted plugins.
        #: If a plugin is registered without any configuration,
        #: and there is an entry here, it will be used.
        self.plugin_config = {}

        #: A list of plugins that will be loaded if
        #: :meth:`register_plugins` is called.
        self.plugin_whitelist = []

        #: The main roster object. This roster supports multiple
        #: owner JIDs, as in the case for components. For clients
        #: which only have a single JID, see :attr:`client_roster`.
        self.roster = roster.Roster(self)
        self.roster.add(self.boundjid.bare)

        #: The single roster for the bound JID. This is the
        #: equivalent of::
        #:
        #:     self.roster[self.boundjid.bare]
        self.client_roster = self.roster[self.boundjid.bare]

        #: The distinction between clients and components can be
        #: important, primarily for choosing how to handle the
        #: ``'to'`` and ``'from'`` JIDs of stanzas.
        self.is_component = False

        #: Flag indicating that the initial presence broadcast has
        #: been sent. Until this happens, some servers may not
        #: behave as expected when sending stanzas.
        self.sentpresence = False

        #: A reference to :mod:`sleekxmpp.stanza` to make accessing
        #: stanza classes easier.
        self.stanza = sleekxmpp.stanza

        self.register_handler(
            Callback(
                "IM", MatchXPath("{%s}message/{%s}body" % (self.default_ns, self.default_ns)), self._handle_message
            )
        )
        self.register_handler(Callback("Presence", MatchXPath("{%s}presence" % self.default_ns), self._handle_presence))
        self.register_handler(
            Callback("Stream Error", MatchXPath("{%s}error" % self.stream_ns), self._handle_stream_error)
        )

        self.add_event_handler("disconnected", self._handle_disconnected)
        self.add_event_handler("presence_available", self._handle_available)
        self.add_event_handler("presence_dnd", self._handle_available)
        self.add_event_handler("presence_xa", self._handle_available)
        self.add_event_handler("presence_chat", self._handle_available)
        self.add_event_handler("presence_away", self._handle_available)
        self.add_event_handler("presence_unavailable", self._handle_unavailable)
        self.add_event_handler("presence_subscribe", self._handle_subscribe)
        self.add_event_handler("presence_subscribed", self._handle_subscribed)
        self.add_event_handler("presence_unsubscribe", self._handle_unsubscribe)
        self.add_event_handler("presence_unsubscribed", self._handle_unsubscribed)
        self.add_event_handler("roster_subscription_request", self._handle_new_subscription)

        # Set up the XML stream with XMPP's root stanzas.
        self.register_stanza(Message)
        self.register_stanza(Iq)
        self.register_stanza(Presence)
        self.register_stanza(StreamError)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
        register_stanza_plugin(Message, HTMLIM)
예제 #24
0
 def disconnect(self, init=True, close=False, reconnect=False):
     self.event("disconnected")
     XMLStream.disconnect(self, reconnect)
예제 #25
0
    def __init__(self, jid="", default_ns="jabber:client"):
        XMLStream.__init__(self)

        self.default_ns = default_ns
        self.stream_ns = "http://etherx.jabber.org/streams"
        self.namespace_map[self.stream_ns] = "stream"

        #: An identifier for the stream as given by the server.
        self.stream_id = None

        #: The JabberID (JID) requested for this connection.
        self.requested_jid = JID(jid, cache_lock=True)

        #: The JabberID (JID) used by this connection,
        #: as set after session binding. This may even be a
        #: different bare JID than what was requested.
        self.boundjid = JID(jid, cache_lock=True)

        self._expected_server_name = self.boundjid.host
        self._redirect_attempts = 0

        #: The maximum number of consecutive see-other-host
        #: redirections that will be followed before quitting.
        self.max_redirects = 5

        self.session_bind_event = threading.Event()

        #: A dictionary mapping plugin names to plugins.
        self.plugin = PluginManager(self)

        #: Configuration options for whitelisted plugins.
        #: If a plugin is registered without any configuration,
        #: and there is an entry here, it will be used.
        self.plugin_config = {}

        #: A list of plugins that will be loaded if
        #: :meth:`register_plugins` is called.
        self.plugin_whitelist = []

        #: The main roster object. This roster supports multiple
        #: owner JIDs, as in the case for components. For clients
        #: which only have a single JID, see :attr:`client_roster`.
        self.roster = roster.Roster(self)
        self.roster.add(self.boundjid)

        #: The single roster for the bound JID. This is the
        #: equivalent of::
        #:
        #:     self.roster[self.boundjid.bare]
        self.client_roster = self.roster[self.boundjid]

        #: The distinction between clients and components can be
        #: important, primarily for choosing how to handle the
        #: ``'to'`` and ``'from'`` JIDs of stanzas.
        self.is_component = False

        #: Messages may optionally be tagged with ID values. Setting
        #: :attr:`use_message_ids` to `True` will assign all outgoing
        #: messages an ID. Some plugin features require enabling
        #: this option.
        self.use_message_ids = False

        #: Presence updates may optionally be tagged with ID values.
        #: Setting :attr:`use_message_ids` to `True` will assign all
        #: outgoing messages an ID.
        self.use_presence_ids = False

        #: The API registry is a way to process callbacks based on
        #: JID+node combinations. Each callback in the registry is
        #: marked with:
        #:
        #:   - An API name, e.g. xep_0030
        #:   - The name of an action, e.g. get_info
        #:   - The JID that will be affected
        #:   - The node that will be affected
        #:
        #: API handlers with no JID or node will act as global handlers,
        #: while those with a JID and no node will service all nodes
        #: for a JID, and handlers with both a JID and node will be
        #: used only for that specific combination. The handler that
        #: provides the most specificity will be used.
        self.api = APIRegistry(self)

        #: Flag indicating that the initial presence broadcast has
        #: been sent. Until this happens, some servers may not
        #: behave as expected when sending stanzas.
        self.sentpresence = False

        #: A reference to :mod:`sleekxmpp.stanza` to make accessing
        #: stanza classes easier.
        self.stanza = sleekxmpp.stanza

        self.register_handler(
            Callback(
                "IM", MatchXPath("{%s}message/{%s}body" % (self.default_ns, self.default_ns)), self._handle_message
            )
        )
        self.register_handler(Callback("Presence", MatchXPath("{%s}presence" % self.default_ns), self._handle_presence))

        self.register_handler(
            Callback("Stream Error", MatchXPath("{%s}error" % self.stream_ns), self._handle_stream_error)
        )

        self.add_event_handler("session_start", self._handle_session_start)
        self.add_event_handler("disconnected", self._handle_disconnected)
        self.add_event_handler("presence_available", self._handle_available)
        self.add_event_handler("presence_dnd", self._handle_available)
        self.add_event_handler("presence_xa", self._handle_available)
        self.add_event_handler("presence_chat", self._handle_available)
        self.add_event_handler("presence_away", self._handle_available)
        self.add_event_handler("presence_unavailable", self._handle_unavailable)
        self.add_event_handler("presence_subscribe", self._handle_subscribe)
        self.add_event_handler("presence_subscribed", self._handle_subscribed)
        self.add_event_handler("presence_unsubscribe", self._handle_unsubscribe)
        self.add_event_handler("presence_unsubscribed", self._handle_unsubscribed)
        self.add_event_handler("roster_subscription_request", self._handle_new_subscription)

        # Set up the XML stream with XMPP's root stanzas.
        self.register_stanza(Message)
        self.register_stanza(Iq)
        self.register_stanza(Presence)
        self.register_stanza(StreamError)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
        register_stanza_plugin(Message, HTMLIM)
예제 #26
0
    def __init__(self, jid='', default_ns='jabber:client'):
        XMLStream.__init__(self)

        self.default_ns = default_ns
        self.stream_ns = 'http://etherx.jabber.org/streams'
        self.namespace_map[self.stream_ns] = 'stream'

        #: An identifier for the stream as given by the server.
        self.stream_id = None

        #: The JabberID (JID) requested for this connection.
        self.requested_jid = JID(jid, cache_lock=True)

        #: The JabberID (JID) used by this connection,
        #: as set after session binding. This may even be a
        #: different bare JID than what was requested.
        self.boundjid = JID(jid, cache_lock=True)

        self._expected_server_name = self.boundjid.host
        self._redirect_attempts = 0

        #: The maximum number of consecutive see-other-host
        #: redirections that will be followed before quitting.
        self.max_redirects = 5

        self.session_bind_event = threading.Event()

        #: A dictionary mapping plugin names to plugins.
        self.plugin = PluginManager(self)

        #: Configuration options for whitelisted plugins.
        #: If a plugin is registered without any configuration,
        #: and there is an entry here, it will be used.
        self.plugin_config = {}

        #: A list of plugins that will be loaded if
        #: :meth:`register_plugins` is called.
        self.plugin_whitelist = []

        #: The main roster object. This roster supports multiple
        #: owner JIDs, as in the case for components. For clients
        #: which only have a single JID, see :attr:`client_roster`.
        self.roster = roster.Roster(self)
        self.roster.add(self.boundjid)

        #: The single roster for the bound JID. This is the
        #: equivalent of::
        #:
        #:     self.roster[self.boundjid.bare]
        self.client_roster = self.roster[self.boundjid]

        #: The distinction between clients and components can be
        #: important, primarily for choosing how to handle the
        #: ``'to'`` and ``'from'`` JIDs of stanzas.
        self.is_component = False

        #: Messages may optionally be tagged with ID values. Setting
        #: :attr:`use_message_ids` to `True` will assign all outgoing
        #: messages an ID. Some plugin features require enabling
        #: this option.
        self.use_message_ids = False

        #: Presence updates may optionally be tagged with ID values.
        #: Setting :attr:`use_message_ids` to `True` will assign all
        #: outgoing messages an ID.
        self.use_presence_ids = False

        #: The API registry is a way to process callbacks based on
        #: JID+node combinations. Each callback in the registry is
        #: marked with:
        #:
        #:   - An API name, e.g. xep_0030
        #:   - The name of an action, e.g. get_info
        #:   - The JID that will be affected
        #:   - The node that will be affected
        #:
        #: API handlers with no JID or node will act as global handlers,
        #: while those with a JID and no node will service all nodes
        #: for a JID, and handlers with both a JID and node will be
        #: used only for that specific combination. The handler that
        #: provides the most specificity will be used.
        self.api = APIRegistry(self)

        #: Flag indicating that the initial presence broadcast has
        #: been sent. Until this happens, some servers may not
        #: behave as expected when sending stanzas.
        self.sentpresence = False

        #: A reference to :mod:`sleekxmpp.stanza` to make accessing
        #: stanza classes easier.
        self.stanza = stanza

        self.register_handler(
            Callback('IM',
                     MatchXPath('{%s}message/{%s}body' % (self.default_ns,
                                                          self.default_ns)),
                     self._handle_message))
        self.register_handler(
            Callback('Presence',
                     MatchXPath("{%s}presence" % self.default_ns),
                     self._handle_presence))

        self.register_handler(
            Callback('Stream Error',
                     MatchXPath("{%s}error" % self.stream_ns),
                     self._handle_stream_error))

        self.add_event_handler('session_start',
                               self._handle_session_start)
        self.add_event_handler('disconnected',
                               self._handle_disconnected)
        self.add_event_handler('presence_available',
                               self._handle_available)
        self.add_event_handler('presence_dnd',
                               self._handle_available)
        self.add_event_handler('presence_xa',
                               self._handle_available)
        self.add_event_handler('presence_chat',
                               self._handle_available)
        self.add_event_handler('presence_away',
                               self._handle_available)
        self.add_event_handler('presence_unavailable',
                               self._handle_unavailable)
        self.add_event_handler('presence_subscribe',
                               self._handle_subscribe)
        self.add_event_handler('presence_subscribed',
                               self._handle_subscribed)
        self.add_event_handler('presence_unsubscribe',
                               self._handle_unsubscribe)
        self.add_event_handler('presence_unsubscribed',
                               self._handle_unsubscribed)
        self.add_event_handler('roster_subscription_request',
                               self._handle_new_subscription)

        # Set up the XML stream with XMPP's root stanzas.
        self.register_stanza(Message)
        self.register_stanza(Iq)
        self.register_stanza(Presence)
        self.register_stanza(StreamError)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
import logging 

log = logging.getLogger('sleekxmpp') 
log.setLevel(logging.DEBUG) 
ch = logging.StreamHandler() 
ch.setLevel(logging.DEBUG) 
formatter = logging.Formatter('%(message)s') 
ch.setFormatter(formatter) 
log.addHandler(ch) 


def bbb(*args): 
    def __init__(self): 
        print(args) 

stream = XMLStream() 
stream.response_timeout = 15 

stream.connect(host = '147.102.6.34', port = 5222) 
print(stream.new_id()) 

register_stanza_plugin(Iq, Registration) 


iq = Iq(stream=stream, stype='set') 

iq['to'] = 'gic' 
iq['register']['username'] = '******' 
iq['register']['password'] = '******' 

예제 #28
0
    def __init__(self, jid='', default_ns='jabber:client'):
        XMLStream.__init__(self)

        self.default_ns = default_ns
        self.stream_ns = 'http://etherx.jabber.org/streams'
        self.namespace_map[self.stream_ns] = 'stream'

        #: An identifier for the stream as given by the server.
        self.stream_id = None

        #: The JabberID (JID) used by this connection.
        self.boundjid = JID(jid)
        self._expected_server_name = self.boundjid.host

        #: A dictionary mapping plugin names to plugins.
        self.plugin = PluginManager(self)

        #: Configuration options for whitelisted plugins.
        #: If a plugin is registered without any configuration,
        #: and there is an entry here, it will be used.
        self.plugin_config = {}

        #: A list of plugins that will be loaded if
        #: :meth:`register_plugins` is called.
        self.plugin_whitelist = []

        #: The main roster object. This roster supports multiple
        #: owner JIDs, as in the case for components. For clients
        #: which only have a single JID, see :attr:`client_roster`.
        self.roster = roster.Roster(self)
        self.roster.add(self.boundjid.bare)

        #: The single roster for the bound JID. This is the
        #: equivalent of::
        #:
        #:     self.roster[self.boundjid.bare]
        self.client_roster = self.roster[self.boundjid.bare]

        #: The distinction between clients and components can be
        #: important, primarily for choosing how to handle the
        #: ``'to'`` and ``'from'`` JIDs of stanzas.
        self.is_component = False

        #: The API registry is a way to process callbacks based on
        #: JID+node combinations. Each callback in the registry is
        #: marked with:
        #:
        #:   - An API name, e.g. xep_0030
        #:   - The name of an action, e.g. get_info
        #:   - The JID that will be affected
        #:   - The node that will be affected
        #:
        #: API handlers with no JID or node will act as global handlers,
        #: while those with a JID and no node will service all nodes
        #: for a JID, and handlers with both a JID and node will be
        #: used only for that specific combination. The handler that
        #: provides the most specificity will be used.
        self.api = APIRegistry(self)

        #: Flag indicating that the initial presence broadcast has
        #: been sent. Until this happens, some servers may not
        #: behave as expected when sending stanzas.
        self.sentpresence = False

        #: A reference to :mod:`sleekxmpp.stanza` to make accessing
        #: stanza classes easier.
        self.stanza = sleekxmpp.stanza

        self.register_handler(
            Callback('IM',
                     MatchXPath('{%s}message/{%s}body' % (self.default_ns,
                                                          self.default_ns)),
                     self._handle_message))
        self.register_handler(
            Callback('Presence',
                     MatchXPath("{%s}presence" % self.default_ns),
                     self._handle_presence))
        self.register_handler(
            Callback('Stream Error',
                     MatchXPath("{%s}error" % self.stream_ns),
                     self._handle_stream_error))

        self.add_event_handler('disconnected',
                               self._handle_disconnected)
        self.add_event_handler('presence_available',
                               self._handle_available)
        self.add_event_handler('presence_dnd',
                               self._handle_available)
        self.add_event_handler('presence_xa',
                               self._handle_available)
        self.add_event_handler('presence_chat',
                               self._handle_available)
        self.add_event_handler('presence_away',
                               self._handle_available)
        self.add_event_handler('presence_unavailable',
                               self._handle_unavailable)
        self.add_event_handler('presence_subscribe',
                               self._handle_subscribe)
        self.add_event_handler('presence_subscribed',
                               self._handle_subscribed)
        self.add_event_handler('presence_unsubscribe',
                               self._handle_unsubscribe)
        self.add_event_handler('presence_unsubscribed',
                               self._handle_unsubscribed)
        self.add_event_handler('roster_subscription_request',
                               self._handle_new_subscription)

        # Set up the XML stream with XMPP's root stanzas.
        self.register_stanza(Message)
        self.register_stanza(Iq)
        self.register_stanza(Presence)
        self.register_stanza(StreamError)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
        register_stanza_plugin(Message, HTMLIM)
예제 #29
0
    def __init__(self, jid="", default_ns="jabber:client"):
        """
        Adapt an XML stream for use with XMPP.

        Arguments:
            default_ns -- Ensure that the correct default XML namespace
                          is used during initialization.
        """
        XMLStream.__init__(self)

        # To comply with PEP8, method names now use underscores.
        # Deprecated method names are re-mapped for backwards compatibility.
        self.default_ns = default_ns
        self.stream_ns = "http://etherx.jabber.org/streams"
        self.namespace_map[self.stream_ns] = "stream"

        self.boundjid = JID(jid)

        self.plugin = {}
        self.plugin_config = {}
        self.plugin_whitelist = []

        self.roster = roster.Roster(self)
        self.roster.add(self.boundjid.bare)
        self.client_roster = self.roster[self.boundjid.bare]

        self.is_component = False
        self.auto_authorize = True
        self.auto_subscribe = True

        self.sentpresence = False

        self.stanza = sleekxmpp.stanza

        self.register_handler(
            Callback(
                "IM", MatchXPath("{%s}message/{%s}body" % (self.default_ns, self.default_ns)), self._handle_message
            )
        )
        self.register_handler(Callback("Presence", MatchXPath("{%s}presence" % self.default_ns), self._handle_presence))
        self.register_handler(
            Callback("Stream Error", MatchXPath("{%s}error" % self.stream_ns), self._handle_stream_error)
        )

        self.add_event_handler("disconnected", self._handle_disconnected)
        self.add_event_handler("presence_available", self._handle_available)
        self.add_event_handler("presence_dnd", self._handle_available)
        self.add_event_handler("presence_xa", self._handle_available)
        self.add_event_handler("presence_chat", self._handle_available)
        self.add_event_handler("presence_away", self._handle_available)
        self.add_event_handler("presence_unavailable", self._handle_unavailable)
        self.add_event_handler("presence_subscribe", self._handle_subscribe)
        self.add_event_handler("presence_subscribed", self._handle_subscribed)
        self.add_event_handler("presence_unsubscribe", self._handle_unsubscribe)
        self.add_event_handler("presence_unsubscribed", self._handle_unsubscribed)
        self.add_event_handler("roster_subscription_request", self._handle_new_subscription)

        # Set up the XML stream with XMPP's root stanzas.
        self.register_stanza(Message)
        self.register_stanza(Iq)
        self.register_stanza(Presence)
        self.register_stanza(StreamError)

        # Initialize a few default stanza plugins.
        register_stanza_plugin(Iq, Roster)
        register_stanza_plugin(Message, Nick)
        register_stanza_plugin(Message, HTMLIM)