node — XMPP network nodes (clients, mostly)¶
This module contains functions to connect to an XMPP server, as well as maintaining the stream. In addition, a client class which completely manages a stream based on a presence setting is provided.
Using XMPP¶
- class aioxmpp.PresenceManagedClient(jid, security_layer, **kwargs)¶
A presence managed XMPP client. The arguments are passed to the AbstractClient constructor.
While the start/stop interfaces of AbstractClient are still available, it is recommended to control the presence managed client solely using the presence property.
The initial presence is set to unavailable, thus, the client will not connect immediately.
- presence¶
Control or query the current presence state (see PresenceState) of the client. Note that when reading, the property only returns the “set” value, not the actual value known to the server (and others). This may differ if the connection is still being established.
See also
Setting the presence state using presence clears the status of the presence. To set the status and state at once, use set_presence().
Upon setting this attribute, the PresenceManagedClient will do whatever neccessary to achieve the given presence. If the presence is an available presence, the client will attempt to connect to the server. If the presence is unavailable and the client is currently connected, it will disconnect.
Instead of setting the presence to unavailable, stop() can also be called. The presence attribute is not affected by calls to start() or stop().
- set_presence(state, status)¶
Set the presence state and status on the client. This has the same effects as writing state to presence, but the status of the presence is also set at the same time.
status must be either a string or something which can be passed to dict. If it is a string, the string is wrapped in a {None: status} dictionary. Otherwise, the dictionary is set as the status attribute of the presence stanza. It must map aioxmpp.structs.LanguageTag instances to strings.
The status is the text shown alongside the state (indicating availability such as away, do not disturb and free to chat).
- connected(**kwargs)¶
Return an asynchronous context manager (PEP 492). When it is entered, the presence is changed to available. The context manager waits until the stream is established, and then the context is entered.
Upon leaving the context manager, the presence is changed to unavailable. The context manager waits until the stream is closed fully.
The keyword arguments are passed to the UseConnected context manager constructor.
See also
UseConnected is the context manager returned here.
New in version 0.6.
Signals:
- on_presence_sent¶
The event is fired after AbstractClient.on_stream_established() and after the current presence has been sent to the server as initial presence.
- class aioxmpp.node.AbstractClient(local_jid, security_layer, negotiation_timeout=datetime.timedelta(0, 60), override_peer=[], loop=None, logger=None)[source]¶
The AbstractClient is a base class for implementing XMPP client classes. These classes deal with managing the StanzaStream and the underlying XMLStream instances. The abstract client provides functionality for connecting the xmlstream as well as signals which indicate changes in the stream state.
The jid must be a JID for which to connect. The security_layer is best created using the security_layer() function and must provide authentication for the given jid.
The negotiation_timeout argument controls the negotiation_timeout attribute.
If loop is given, it must be a asyncio.BaseEventLoop instance. If it is not given, the current event loop is used.
override_peer is used to initialise the override_peer attribute.
As a glue between the stanza stream and the XML stream, it also knows about stream management and performs stream management negotiation. It is specialized on client operations, which implies that it will try to keep the stream alive as long as wished by the client.
In general, there are no fatal errors (aside from stream negotiation problems) which stop a AbstractClient from working. It makes use of stream management as far as possible and abstracts away the gritty low level details. In general, it is sufficient to observe the on_stream_established() and on_stream_destroyed events, which notify a user about when a stream becomes available and when it becomes unavailable.
If authentication fails (or another stream negotiation error occurs), the client fails and on_failure is fired. running becomes false and the client needs to be re-started manually by calling start().
Changed in version 0.4: Since 0.4, support for legacy XMPP sessions has been implemented. Mainly for compatiblity with ejabberd.
Controlling the client:
- start()[source]¶
Start the client. If it is already running, RuntimeError is raised.
While the client is running, it will try to keep an XMPP connection open to the server associated with local_jid.
- stop()[source]¶
Stop the client. This sends a signal to the clients main task which makes it terminate.
It may take some cycles through the event loop to stop the client task. To check whether the task has actually stopped, query running.
- negotiation_timeout = timedelta(seconds=60)
The timeout applied to the connection process and the individual steps of negotiating the stream. See the negotiation_timeout argument to connect_xmlstream().
- override_peer¶
A sequence of triples (host, port, connector), where host must be a host name or IP as string, port must be a port number and connector must be a aioxmpp.connector.BaseConnctor instance.
These connection options are passed to connect_xmlstream() and thus take precedence over the options discovered using discover_connectors().
Note
If Stream Management is used and the peer server provided a location to connect to on resumption, that location is preferred even over the options set here.
New in version 0.6.
Connection information:
- established[source]¶
true if the stream is currently established (as defined in on_stream_established) and false otherwise.
- local_jid[source]¶
The JID the client currently has. While the client is disconnected, only the bare JID part is authentic, as the resource is ultimately determined by the server.
Writing this attribute is not allowed, as changing the JID introduces a lot of issues with respect to reusability of the stream. Instanciate a new AbstractClient if you need to change the bare part of the JID.
Note
Changing the resource between reconnects may be allowed later.
- stream¶
The StanzaStream instance used by the node.
- stream_features¶
An instance of StreamFeatures. This is the most-recently received stream features information (the one received right before resource binding).
While no stream has been established yet, this is None. During transparent re-negotiation, that information may be obsolete. However, when before_stream_established fires, the information is up-to-date.
Exponential backoff on interruptions:
- backoff_start¶
When an underlying XML stream fails due to connectivity issues (generic OSError raised), exponential backoff takes place before attempting to reconnect.
The initial time to wait before reconnecting is described by backoff_start.
- backoff_factor¶
Each subsequent time a connection fails, the previous backoff time is multiplied with backoff_factor.
- backoff_cap¶
The backoff time is capped to backoff_cap, to avoid having unrealistically high values.
Signals:
- signal on_failure(err)¶
This signal is fired when the client fails and stops.
- coroutine signal before_stream_established()¶
This coroutine signal is executed right before on_stream_established() fires.
- signal on_stopped()¶
Fires when the client stops gracefully. This is the counterpart to on_failure().
- signal on_stream_established()¶
When the stream is established and resource binding took place, this event is fired. It means that the stream can now be used for XMPP interactions.
- signal on_stream_destroyed()¶
This is called whenever a stream is destroyed. The conditions for this are the same as for aioxmpp.stream.StanzaStream.on_stream_destroyed.
This event can be used to know when to discard all state about the XMPP connection, such as roster information.
Services:
- summon(class_)[source]¶
Summon a Service for the client.
If the class_ has already been summoned for the client, it’s instance is returned.
Otherwise, all requirements for the class are first summoned (if they are not there already). Afterwards, the class itself is summoned and the instance is returned.
Miscellaneous:
- logger¶
The logging.Logger instance which is used by the AbstractClient. This is the logger passed to the constructor or a logger derived from the fully qualified name of the class.
New in version 0.6: The logger attribute was added.
Connecting streams low-level¶
- coroutine aioxmpp.node.discover_connectors(domain, loop=None, logger=<logging.Logger object at 0x7f0dc23ca2e8>)[source]¶
Discover all connection options for a domain, in descending order of preference.
This coroutine returns options discovered from SRV records, or if none are found, the generic option using the domain name and the default XMPP client port.
Each option is represented by a triple (host, port, connector). connector is a aioxmpp.connector.BaseConnector instance which is suitable to connect to the given host and port.
logger is the logger used by the function.
The following sources are supported:
RFC 6120 SRV records. One option is returned per SRV record.
If one of the SRV records points to the root name (.), ValueError is raised (the domain specifically said that XMPP is not supported here).
XEP-0368 SRV records. One option is returned per SRV record.
RFC 6120 fallback process (only if no SRV records are found). One option is returned for the host name with the default XMPP client port.
The options discovered from SRV records are mixed together, ordered by priority and then within priorities are shuffled according to their weight. Thus, if there are multiple records of equal priority, the result of the function is not deterministic.
New in version 0.6.
- coroutine aioxmpp.node.connect_xmlstream(jid, metadata, negotiation_timeout=60.0, override_peer=[], loop=None, logger=<logging.Logger object at 0x7f0dc23ca2e8>)[source]¶
Prepare and connect a aioxmpp.protocol.XMLStream to a server responsible for the given jid and authenticate against that server using the SASL mechansims described in metadata.
The part of the metadata (which must be a security_layer.SecurityLayer object) specifying the use of TLS is applied. If the security layer does not mandate TLS, the resulting XML stream may not be using TLS. TLS is used whenever possible.
override_peer may be a list of triples consisting of (host, port, connector), where connector is a aioxmpp.connector.BaseConnector instance. The options in the list are tried first (in the order given), and only if all of them fail, automatic discovery of connection options is performed.
loop may be a asyncio.BaseEventLoop to use. Defaults to the current event loop.
If domain announces that XMPP is not supported at all, ValueError is raised. If no options are returned from discover_connectors() and override_peer is empty, ValueError is raised, too.
If all connection attempts fail, aioxmpp.errors.MultiOSError is raised. The error contains one exception for each of the options discovered as well as the elements from override_peer in the order they were tried.
Note
Even though it is a aioxmpp.errors.MultiOSError, it may also contain instances of aioxmpp.errors.TLSUnavailable or aioxmpp.errors.TLSFailed.
A TLS problem is treated like any other connection problem and the other connection options are considered.
Return a triple (transport, xmlstream, features). transport the underlying asyncio.Transport which is used for the xmlstream XMLStream instance. features is the aioxmpp.nonza.StreamFeatures instance describing the features of the stream.
New in version 0.6.
Utilities¶
- class aioxmpp.node.UseConnected(client, *, timeout=None, presence=<PresenceState available>)[source]¶
Control the given PresenceManagedClient client as asynchronous context manager (PEP 492). UseConnected is an asynchronous context manager. When the context manager is entered, the client is set to an available presence (if the stream is not already established) and the context manager waits for a connection to establish. If a fatal error occurs while the stream is being established, it is re-raised.
When the context manager is left, the stream is shut down cleanly and the context manager waits for the stream to shut down. Any exceptions occuring in the context are not swallowed.
timeout is used to initialise the timeout attribute. presence is used to initialise the presence attribute and defaults to a simple available presence. presence must be an available presence.
New in version 0.6.
The following attributes control the behaviour of the context manager:
- timeout¶
Either None or a datetime.timedelta instance. If it is the latter and it takes longer than that time to establish the stream, the process is aborted and TimeoutError is raised.