repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
horazont/aioxmpp
aioxmpp/node.py
_try_options
def _try_options(options, exceptions, jid, metadata, negotiation_timeout, loop, logger): """ Helper function for :func:`connect_xmlstream`. """ for host, port, conn in options: logger.debug( "domain %s: trying to connect to %r:%s using %r", jid.domain, host, port, conn ) try: transport, xmlstream, features = yield from conn.connect( loop, metadata, jid.domain, host, port, negotiation_timeout, base_logger=logger, ) except OSError as exc: logger.warning( "connection failed: %s", exc ) exceptions.append(exc) continue logger.debug( "domain %s: connection succeeded using %r", jid.domain, conn, ) if not metadata.sasl_providers: return transport, xmlstream, features try: features = yield from security_layer.negotiate_sasl( transport, xmlstream, metadata.sasl_providers, negotiation_timeout=None, jid=jid, features=features, ) except errors.SASLUnavailable as exc: protocol.send_stream_error_and_close( xmlstream, condition=errors.StreamErrorCondition.POLICY_VIOLATION, text=str(exc), ) exceptions.append(exc) continue except Exception as exc: protocol.send_stream_error_and_close( xmlstream, condition=errors.StreamErrorCondition.UNDEFINED_CONDITION, text=str(exc), ) raise return transport, xmlstream, features return None
python
def _try_options(options, exceptions, jid, metadata, negotiation_timeout, loop, logger): """ Helper function for :func:`connect_xmlstream`. """ for host, port, conn in options: logger.debug( "domain %s: trying to connect to %r:%s using %r", jid.domain, host, port, conn ) try: transport, xmlstream, features = yield from conn.connect( loop, metadata, jid.domain, host, port, negotiation_timeout, base_logger=logger, ) except OSError as exc: logger.warning( "connection failed: %s", exc ) exceptions.append(exc) continue logger.debug( "domain %s: connection succeeded using %r", jid.domain, conn, ) if not metadata.sasl_providers: return transport, xmlstream, features try: features = yield from security_layer.negotiate_sasl( transport, xmlstream, metadata.sasl_providers, negotiation_timeout=None, jid=jid, features=features, ) except errors.SASLUnavailable as exc: protocol.send_stream_error_and_close( xmlstream, condition=errors.StreamErrorCondition.POLICY_VIOLATION, text=str(exc), ) exceptions.append(exc) continue except Exception as exc: protocol.send_stream_error_and_close( xmlstream, condition=errors.StreamErrorCondition.UNDEFINED_CONDITION, text=str(exc), ) raise return transport, xmlstream, features return None
Helper function for :func:`connect_xmlstream`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L235-L298
horazont/aioxmpp
aioxmpp/node.py
connect_xmlstream
def connect_xmlstream( jid, metadata, negotiation_timeout=60., override_peer=[], loop=None, logger=logger): """ Prepare and connect a :class:`aioxmpp.protocol.XMLStream` to a server responsible for the given `jid` and authenticate against that server using the SASL mechansims described in `metadata`. :param jid: Address of the user for which the connection is made. :type jid: :class:`aioxmpp.JID` :param metadata: Connection metadata for configuring the TLS usage. :type metadata: :class:`~.security_layer.SecurityLayer` :param negotiation_timeout: Timeout for each individual negotiation step. :type negotiation_timeout: :class:`float` in seconds :param override_peer: Sequence of connection options which take precedence over normal discovery methods. :type override_peer: sequence of (:class:`str`, :class:`int`, :class:`~.BaseConnector`) triples :param loop: asyncio event loop to use (defaults to current) :type loop: :class:`asyncio.BaseEventLoop` :param logger: Logger to use (defaults to module-wide logger) :type logger: :class:`logging.Logger` :raises ValueError: if the domain from the `jid` announces that XMPP is not supported at all. :raises aioxmpp.errors.TLSFailure: if all connection attempts fail and one of them is a :class:`~.TLSFailure`. :raises aioxmpp.errors.MultiOSError: if all connection attempts fail. :return: Transport, XML stream and the current stream features :rtype: tuple of (:class:`asyncio.BaseTransport`, :class:`~.XMLStream`, :class:`~.nonza.StreamFeatures`) The part of the `metadata` 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. The connection options in `override_peer` are tried before any standardised discovery of connection options is made. Only if all of them fail, automatic discovery of connection options is performed. `loop` may be a :class:`asyncio.BaseEventLoop` to use. Defaults to the current event loop. If the domain from the `jid` announces that XMPP is not supported at all, :class:`ValueError` is raised. If no options are returned from :func:`discover_connectors` and `override_peer` is empty, :class:`ValueError` is raised, too. If all connection attempts fail, :class:`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. A TLS problem is treated like any other connection problem and the other connection options are considered. However, if *all* connection options fail and the set of encountered errors includes a TLS error, the TLS error is re-raised instead of raising a :class:`aioxmpp.errors.MultiOSError`. Return a triple ``(transport, xmlstream, features)``. `transport` the underlying :class:`asyncio.Transport` which is used for the `xmlstream` :class:`~.protocol.XMLStream` instance. `features` is the :class:`aioxmpp.nonza.StreamFeatures` instance describing the features of the stream. .. versionadded:: 0.6 .. versionchanged:: 0.8 The explicit raising of TLS errors has been introduced. Before, TLS errors were treated like any other connection error, possibly masking configuration problems. """ loop = asyncio.get_event_loop() if loop is None else loop options = list(override_peer) exceptions = [] result = yield from _try_options( options, exceptions, jid, metadata, negotiation_timeout, loop, logger, ) if result is not None: return result options = list((yield from discover_connectors( jid.domain, loop=loop, logger=logger, ))) result = yield from _try_options( options, exceptions, jid, metadata, negotiation_timeout, loop, logger, ) if result is not None: return result if not options and not override_peer: raise ValueError("no options to connect to XMPP domain {!r}".format( jid.domain )) for exc in exceptions: if isinstance(exc, errors.TLSFailure): raise exc raise errors.MultiOSError( "failed to connect to XMPP domain {!r}".format(jid.domain), exceptions )
python
def connect_xmlstream( jid, metadata, negotiation_timeout=60., override_peer=[], loop=None, logger=logger): """ Prepare and connect a :class:`aioxmpp.protocol.XMLStream` to a server responsible for the given `jid` and authenticate against that server using the SASL mechansims described in `metadata`. :param jid: Address of the user for which the connection is made. :type jid: :class:`aioxmpp.JID` :param metadata: Connection metadata for configuring the TLS usage. :type metadata: :class:`~.security_layer.SecurityLayer` :param negotiation_timeout: Timeout for each individual negotiation step. :type negotiation_timeout: :class:`float` in seconds :param override_peer: Sequence of connection options which take precedence over normal discovery methods. :type override_peer: sequence of (:class:`str`, :class:`int`, :class:`~.BaseConnector`) triples :param loop: asyncio event loop to use (defaults to current) :type loop: :class:`asyncio.BaseEventLoop` :param logger: Logger to use (defaults to module-wide logger) :type logger: :class:`logging.Logger` :raises ValueError: if the domain from the `jid` announces that XMPP is not supported at all. :raises aioxmpp.errors.TLSFailure: if all connection attempts fail and one of them is a :class:`~.TLSFailure`. :raises aioxmpp.errors.MultiOSError: if all connection attempts fail. :return: Transport, XML stream and the current stream features :rtype: tuple of (:class:`asyncio.BaseTransport`, :class:`~.XMLStream`, :class:`~.nonza.StreamFeatures`) The part of the `metadata` 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. The connection options in `override_peer` are tried before any standardised discovery of connection options is made. Only if all of them fail, automatic discovery of connection options is performed. `loop` may be a :class:`asyncio.BaseEventLoop` to use. Defaults to the current event loop. If the domain from the `jid` announces that XMPP is not supported at all, :class:`ValueError` is raised. If no options are returned from :func:`discover_connectors` and `override_peer` is empty, :class:`ValueError` is raised, too. If all connection attempts fail, :class:`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. A TLS problem is treated like any other connection problem and the other connection options are considered. However, if *all* connection options fail and the set of encountered errors includes a TLS error, the TLS error is re-raised instead of raising a :class:`aioxmpp.errors.MultiOSError`. Return a triple ``(transport, xmlstream, features)``. `transport` the underlying :class:`asyncio.Transport` which is used for the `xmlstream` :class:`~.protocol.XMLStream` instance. `features` is the :class:`aioxmpp.nonza.StreamFeatures` instance describing the features of the stream. .. versionadded:: 0.6 .. versionchanged:: 0.8 The explicit raising of TLS errors has been introduced. Before, TLS errors were treated like any other connection error, possibly masking configuration problems. """ loop = asyncio.get_event_loop() if loop is None else loop options = list(override_peer) exceptions = [] result = yield from _try_options( options, exceptions, jid, metadata, negotiation_timeout, loop, logger, ) if result is not None: return result options = list((yield from discover_connectors( jid.domain, loop=loop, logger=logger, ))) result = yield from _try_options( options, exceptions, jid, metadata, negotiation_timeout, loop, logger, ) if result is not None: return result if not options and not override_peer: raise ValueError("no options to connect to XMPP domain {!r}".format( jid.domain )) for exc in exceptions: if isinstance(exc, errors.TLSFailure): raise exc raise errors.MultiOSError( "failed to connect to XMPP domain {!r}".format(jid.domain), exceptions )
Prepare and connect a :class:`aioxmpp.protocol.XMLStream` to a server responsible for the given `jid` and authenticate against that server using the SASL mechansims described in `metadata`. :param jid: Address of the user for which the connection is made. :type jid: :class:`aioxmpp.JID` :param metadata: Connection metadata for configuring the TLS usage. :type metadata: :class:`~.security_layer.SecurityLayer` :param negotiation_timeout: Timeout for each individual negotiation step. :type negotiation_timeout: :class:`float` in seconds :param override_peer: Sequence of connection options which take precedence over normal discovery methods. :type override_peer: sequence of (:class:`str`, :class:`int`, :class:`~.BaseConnector`) triples :param loop: asyncio event loop to use (defaults to current) :type loop: :class:`asyncio.BaseEventLoop` :param logger: Logger to use (defaults to module-wide logger) :type logger: :class:`logging.Logger` :raises ValueError: if the domain from the `jid` announces that XMPP is not supported at all. :raises aioxmpp.errors.TLSFailure: if all connection attempts fail and one of them is a :class:`~.TLSFailure`. :raises aioxmpp.errors.MultiOSError: if all connection attempts fail. :return: Transport, XML stream and the current stream features :rtype: tuple of (:class:`asyncio.BaseTransport`, :class:`~.XMLStream`, :class:`~.nonza.StreamFeatures`) The part of the `metadata` 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. The connection options in `override_peer` are tried before any standardised discovery of connection options is made. Only if all of them fail, automatic discovery of connection options is performed. `loop` may be a :class:`asyncio.BaseEventLoop` to use. Defaults to the current event loop. If the domain from the `jid` announces that XMPP is not supported at all, :class:`ValueError` is raised. If no options are returned from :func:`discover_connectors` and `override_peer` is empty, :class:`ValueError` is raised, too. If all connection attempts fail, :class:`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. A TLS problem is treated like any other connection problem and the other connection options are considered. However, if *all* connection options fail and the set of encountered errors includes a TLS error, the TLS error is re-raised instead of raising a :class:`aioxmpp.errors.MultiOSError`. Return a triple ``(transport, xmlstream, features)``. `transport` the underlying :class:`asyncio.Transport` which is used for the `xmlstream` :class:`~.protocol.XMLStream` instance. `features` is the :class:`aioxmpp.nonza.StreamFeatures` instance describing the features of the stream. .. versionadded:: 0.6 .. versionchanged:: 0.8 The explicit raising of TLS errors has been introduced. Before, TLS errors were treated like any other connection error, possibly masking configuration problems.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L302-L416
horazont/aioxmpp
aioxmpp/node.py
Client.start
def start(self): """ Start the client. If it is already :attr:`running`, :class:`RuntimeError` is raised. While the client is running, it will try to keep an XMPP connection open to the server associated with :attr:`local_jid`. """ if self.running: raise RuntimeError("client already running") self._main_task = asyncio.ensure_future( self._main(), loop=self._loop ) self._main_task.add_done_callback(self._on_main_done)
python
def start(self): """ Start the client. If it is already :attr:`running`, :class:`RuntimeError` is raised. While the client is running, it will try to keep an XMPP connection open to the server associated with :attr:`local_jid`. """ if self.running: raise RuntimeError("client already running") self._main_task = asyncio.ensure_future( self._main(), loop=self._loop ) self._main_task.add_done_callback(self._on_main_done)
Start the client. If it is already :attr:`running`, :class:`RuntimeError` is raised. While the client is running, it will try to keep an XMPP connection open to the server associated with :attr:`local_jid`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L1041-L1056
horazont/aioxmpp
aioxmpp/node.py
Client.stop
def stop(self): """ 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 :attr:`running`. """ if not self.running: return self.logger.debug("stopping main task of %r", self, stack_info=True) self._main_task.cancel()
python
def stop(self): """ 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 :attr:`running`. """ if not self.running: return self.logger.debug("stopping main task of %r", self, stack_info=True) self._main_task.cancel()
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 :attr:`running`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L1058-L1071
horazont/aioxmpp
aioxmpp/node.py
Client.connected
def connected(self, *, presence=structs.PresenceState(False), **kwargs): """ Return a :class:`.node.UseConnected` context manager which does not modify the presence settings. The keyword arguments are passed to the :class:`.node.UseConnected` context manager constructor. .. versionadded:: 0.8 """ return UseConnected(self, presence=presence, **kwargs)
python
def connected(self, *, presence=structs.PresenceState(False), **kwargs): """ Return a :class:`.node.UseConnected` context manager which does not modify the presence settings. The keyword arguments are passed to the :class:`.node.UseConnected` context manager constructor. .. versionadded:: 0.8 """ return UseConnected(self, presence=presence, **kwargs)
Return a :class:`.node.UseConnected` context manager which does not modify the presence settings. The keyword arguments are passed to the :class:`.node.UseConnected` context manager constructor. .. versionadded:: 0.8
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L1203-L1213
horazont/aioxmpp
aioxmpp/node.py
Client.enqueue
def enqueue(self, stanza, **kwargs): """ Put a `stanza` in the internal transmission queue and return a token to track it. :param stanza: Stanza to send :type stanza: :class:`IQ`, :class:`Message` or :class:`Presence` :param kwargs: see :class:`StanzaToken` :raises ConnectionError: if the stream is not :attr:`established` yet. :return: token which tracks the stanza :rtype: :class:`StanzaToken` The `stanza` is enqueued in the active queue for transmission and will be sent on the next opportunity. The relative ordering of stanzas enqueued is always preserved. Return a fresh :class:`StanzaToken` instance which traks the progress of the transmission of the `stanza`. The `kwargs` are forwarded to the :class:`StanzaToken` constructor. This method calls :meth:`~.stanza.StanzaBase.autoset_id` on the stanza automatically. .. seealso:: :meth:`send` for a more high-level way to send stanzas. .. versionchanged:: 0.10 This method has been moved from :meth:`aioxmpp.stream.StanzaStream.enqueue`. """ if not self.established_event.is_set(): raise ConnectionError("stream is not ready") return self.stream._enqueue(stanza, **kwargs)
python
def enqueue(self, stanza, **kwargs): """ Put a `stanza` in the internal transmission queue and return a token to track it. :param stanza: Stanza to send :type stanza: :class:`IQ`, :class:`Message` or :class:`Presence` :param kwargs: see :class:`StanzaToken` :raises ConnectionError: if the stream is not :attr:`established` yet. :return: token which tracks the stanza :rtype: :class:`StanzaToken` The `stanza` is enqueued in the active queue for transmission and will be sent on the next opportunity. The relative ordering of stanzas enqueued is always preserved. Return a fresh :class:`StanzaToken` instance which traks the progress of the transmission of the `stanza`. The `kwargs` are forwarded to the :class:`StanzaToken` constructor. This method calls :meth:`~.stanza.StanzaBase.autoset_id` on the stanza automatically. .. seealso:: :meth:`send` for a more high-level way to send stanzas. .. versionchanged:: 0.10 This method has been moved from :meth:`aioxmpp.stream.StanzaStream.enqueue`. """ if not self.established_event.is_set(): raise ConnectionError("stream is not ready") return self.stream._enqueue(stanza, **kwargs)
Put a `stanza` in the internal transmission queue and return a token to track it. :param stanza: Stanza to send :type stanza: :class:`IQ`, :class:`Message` or :class:`Presence` :param kwargs: see :class:`StanzaToken` :raises ConnectionError: if the stream is not :attr:`established` yet. :return: token which tracks the stanza :rtype: :class:`StanzaToken` The `stanza` is enqueued in the active queue for transmission and will be sent on the next opportunity. The relative ordering of stanzas enqueued is always preserved. Return a fresh :class:`StanzaToken` instance which traks the progress of the transmission of the `stanza`. The `kwargs` are forwarded to the :class:`StanzaToken` constructor. This method calls :meth:`~.stanza.StanzaBase.autoset_id` on the stanza automatically. .. seealso:: :meth:`send` for a more high-level way to send stanzas. .. versionchanged:: 0.10 This method has been moved from :meth:`aioxmpp.stream.StanzaStream.enqueue`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L1215-L1252
horazont/aioxmpp
aioxmpp/node.py
Client.send
def send(self, stanza, *, timeout=None, cb=None): """ Send a stanza. :param stanza: Stanza to send :type stanza: :class:`~.IQ`, :class:`~.Presence` or :class:`~.Message` :param timeout: Maximum time in seconds to wait for an IQ response, or :data:`None` to disable the timeout. :type timeout: :class:`~numbers.Real` or :data:`None` :param cb: Optional callback which is called synchronously when the reply is received (IQ requests only!) :raise OSError: if the underlying XML stream fails and stream management is not disabled. :raise aioxmpp.stream.DestructionRequested: if the stream is closed while sending the stanza or waiting for a response. :raise aioxmpp.errors.XMPPError: if an error IQ response is received :raise aioxmpp.errors.ErroneousStanza: if the IQ response could not be parsed :raise ValueError: if `cb` is given and `stanza` is not an IQ request. :return: IQ response :attr:`~.IQ.payload` or :data:`None` Send the stanza and wait for it to be sent. If the stanza is an IQ request, the response is awaited and the :attr:`~.IQ.payload` of the response is returned. If the stream is currently not ready, this method blocks until the stream is ready to send payload stanzas. Note that this may be before initial presence has been sent. To synchronise with that type of events, use the appropriate signals. The `timeout` as well as any of the exception cases referring to a "response" do not apply for IQ response stanzas, message stanzas or presence stanzas sent with this method, as this method only waits for a reply if an IQ *request* stanza is being sent. If `stanza` is an IQ request and the response is not received within `timeout` seconds, :class:`TimeoutError` (not :class:`asyncio.TimeoutError`!) is raised. If `cb` is given, `stanza` must be an IQ request (otherwise, :class:`ValueError` is raised before the stanza is sent). It must be a callable returning an awaitable. It receives the response stanza as first and only argument. The returned awaitable is awaited by :meth:`send` and the result is returned instead of the original payload. `cb` is called synchronously from the stream handling loop when the response is received, so it can benefit from the strong ordering guarantees given by XMPP XML Streams. The `cb` may also return :data:`None`, in which case :meth:`send` will simply return the IQ payload as if `cb` was not given. Since the return value of coroutine functions is awaitable, it is valid and supported to pass a coroutine function as `cb`. .. warning:: Remember that it is an implementation detail of the event loop when a coroutine is scheduled after it awaited an awaitable; this implies that if the caller of :meth:`send` is merely awaiting the :meth:`send` coroutine, the strong ordering guarantees of XMPP XML Streams are lost. To regain those, use the `cb` argument. .. note:: For the sake of readability, unless you really need the strong ordering guarantees, avoid the use of the `cb` argument. Avoid using a coroutine function unless you really need to. .. versionchanged:: 0.10 * This method now waits until the stream is ready to send stanza¸ payloads. * This method was moved from :meth:`aioxmpp.stream.StanzaStream.send`. .. versionchanged:: 0.9 The `cb` argument was added. .. versionadded:: 0.8 """ if not self.running: raise ConnectionError("client is not running") if not self.established: self.logger.debug("send(%s): stream not established, waiting", stanza) # wait for the stream to be established stopped_fut = self.on_stopped.future() failure_fut = self.on_failure.future() established_fut = asyncio.ensure_future( self.established_event.wait() ) done, pending = yield from asyncio.wait( [ established_fut, failure_fut, stopped_fut, ], return_when=asyncio.FIRST_COMPLETED, ) if not established_fut.done(): established_fut.cancel() if failure_fut.done(): if not stopped_fut.done(): stopped_fut.cancel() failure_fut.exception() raise ConnectionError("client failed to connect") if stopped_fut.done(): raise ConnectionError("client shut down by user request") self.logger.debug("send(%s): stream established, sending") return (yield from self.stream._send_immediately(stanza, timeout=timeout, cb=cb))
python
def send(self, stanza, *, timeout=None, cb=None): """ Send a stanza. :param stanza: Stanza to send :type stanza: :class:`~.IQ`, :class:`~.Presence` or :class:`~.Message` :param timeout: Maximum time in seconds to wait for an IQ response, or :data:`None` to disable the timeout. :type timeout: :class:`~numbers.Real` or :data:`None` :param cb: Optional callback which is called synchronously when the reply is received (IQ requests only!) :raise OSError: if the underlying XML stream fails and stream management is not disabled. :raise aioxmpp.stream.DestructionRequested: if the stream is closed while sending the stanza or waiting for a response. :raise aioxmpp.errors.XMPPError: if an error IQ response is received :raise aioxmpp.errors.ErroneousStanza: if the IQ response could not be parsed :raise ValueError: if `cb` is given and `stanza` is not an IQ request. :return: IQ response :attr:`~.IQ.payload` or :data:`None` Send the stanza and wait for it to be sent. If the stanza is an IQ request, the response is awaited and the :attr:`~.IQ.payload` of the response is returned. If the stream is currently not ready, this method blocks until the stream is ready to send payload stanzas. Note that this may be before initial presence has been sent. To synchronise with that type of events, use the appropriate signals. The `timeout` as well as any of the exception cases referring to a "response" do not apply for IQ response stanzas, message stanzas or presence stanzas sent with this method, as this method only waits for a reply if an IQ *request* stanza is being sent. If `stanza` is an IQ request and the response is not received within `timeout` seconds, :class:`TimeoutError` (not :class:`asyncio.TimeoutError`!) is raised. If `cb` is given, `stanza` must be an IQ request (otherwise, :class:`ValueError` is raised before the stanza is sent). It must be a callable returning an awaitable. It receives the response stanza as first and only argument. The returned awaitable is awaited by :meth:`send` and the result is returned instead of the original payload. `cb` is called synchronously from the stream handling loop when the response is received, so it can benefit from the strong ordering guarantees given by XMPP XML Streams. The `cb` may also return :data:`None`, in which case :meth:`send` will simply return the IQ payload as if `cb` was not given. Since the return value of coroutine functions is awaitable, it is valid and supported to pass a coroutine function as `cb`. .. warning:: Remember that it is an implementation detail of the event loop when a coroutine is scheduled after it awaited an awaitable; this implies that if the caller of :meth:`send` is merely awaiting the :meth:`send` coroutine, the strong ordering guarantees of XMPP XML Streams are lost. To regain those, use the `cb` argument. .. note:: For the sake of readability, unless you really need the strong ordering guarantees, avoid the use of the `cb` argument. Avoid using a coroutine function unless you really need to. .. versionchanged:: 0.10 * This method now waits until the stream is ready to send stanza¸ payloads. * This method was moved from :meth:`aioxmpp.stream.StanzaStream.send`. .. versionchanged:: 0.9 The `cb` argument was added. .. versionadded:: 0.8 """ if not self.running: raise ConnectionError("client is not running") if not self.established: self.logger.debug("send(%s): stream not established, waiting", stanza) # wait for the stream to be established stopped_fut = self.on_stopped.future() failure_fut = self.on_failure.future() established_fut = asyncio.ensure_future( self.established_event.wait() ) done, pending = yield from asyncio.wait( [ established_fut, failure_fut, stopped_fut, ], return_when=asyncio.FIRST_COMPLETED, ) if not established_fut.done(): established_fut.cancel() if failure_fut.done(): if not stopped_fut.done(): stopped_fut.cancel() failure_fut.exception() raise ConnectionError("client failed to connect") if stopped_fut.done(): raise ConnectionError("client shut down by user request") self.logger.debug("send(%s): stream established, sending") return (yield from self.stream._send_immediately(stanza, timeout=timeout, cb=cb))
Send a stanza. :param stanza: Stanza to send :type stanza: :class:`~.IQ`, :class:`~.Presence` or :class:`~.Message` :param timeout: Maximum time in seconds to wait for an IQ response, or :data:`None` to disable the timeout. :type timeout: :class:`~numbers.Real` or :data:`None` :param cb: Optional callback which is called synchronously when the reply is received (IQ requests only!) :raise OSError: if the underlying XML stream fails and stream management is not disabled. :raise aioxmpp.stream.DestructionRequested: if the stream is closed while sending the stanza or waiting for a response. :raise aioxmpp.errors.XMPPError: if an error IQ response is received :raise aioxmpp.errors.ErroneousStanza: if the IQ response could not be parsed :raise ValueError: if `cb` is given and `stanza` is not an IQ request. :return: IQ response :attr:`~.IQ.payload` or :data:`None` Send the stanza and wait for it to be sent. If the stanza is an IQ request, the response is awaited and the :attr:`~.IQ.payload` of the response is returned. If the stream is currently not ready, this method blocks until the stream is ready to send payload stanzas. Note that this may be before initial presence has been sent. To synchronise with that type of events, use the appropriate signals. The `timeout` as well as any of the exception cases referring to a "response" do not apply for IQ response stanzas, message stanzas or presence stanzas sent with this method, as this method only waits for a reply if an IQ *request* stanza is being sent. If `stanza` is an IQ request and the response is not received within `timeout` seconds, :class:`TimeoutError` (not :class:`asyncio.TimeoutError`!) is raised. If `cb` is given, `stanza` must be an IQ request (otherwise, :class:`ValueError` is raised before the stanza is sent). It must be a callable returning an awaitable. It receives the response stanza as first and only argument. The returned awaitable is awaited by :meth:`send` and the result is returned instead of the original payload. `cb` is called synchronously from the stream handling loop when the response is received, so it can benefit from the strong ordering guarantees given by XMPP XML Streams. The `cb` may also return :data:`None`, in which case :meth:`send` will simply return the IQ payload as if `cb` was not given. Since the return value of coroutine functions is awaitable, it is valid and supported to pass a coroutine function as `cb`. .. warning:: Remember that it is an implementation detail of the event loop when a coroutine is scheduled after it awaited an awaitable; this implies that if the caller of :meth:`send` is merely awaiting the :meth:`send` coroutine, the strong ordering guarantees of XMPP XML Streams are lost. To regain those, use the `cb` argument. .. note:: For the sake of readability, unless you really need the strong ordering guarantees, avoid the use of the `cb` argument. Avoid using a coroutine function unless you really need to. .. versionchanged:: 0.10 * This method now waits until the stream is ready to send stanza¸ payloads. * This method was moved from :meth:`aioxmpp.stream.StanzaStream.send`. .. versionchanged:: 0.9 The `cb` argument was added. .. versionadded:: 0.8
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L1255-L1372
horazont/aioxmpp
aioxmpp/node.py
PresenceManagedClient.set_presence
def set_presence(self, state, status): """ Set the presence `state` and `status` on the client. This has the same effects as writing `state` to :attr:`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 :class:`dict`. If it is a string, the string is wrapped in a ``{None: status}`` dictionary. Otherwise, the dictionary is set as the :attr:`~.Presence.status` attribute of the presence stanza. It must map :class:`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*). """ self._presence_server.set_presence(state, status=status)
python
def set_presence(self, state, status): """ Set the presence `state` and `status` on the client. This has the same effects as writing `state` to :attr:`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 :class:`dict`. If it is a string, the string is wrapped in a ``{None: status}`` dictionary. Otherwise, the dictionary is set as the :attr:`~.Presence.status` attribute of the presence stanza. It must map :class:`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*). """ self._presence_server.set_presence(state, status=status)
Set the presence `state` and `status` on the client. This has the same effects as writing `state` to :attr:`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 :class:`dict`. If it is a string, the string is wrapped in a ``{None: status}`` dictionary. Otherwise, the dictionary is set as the :attr:`~.Presence.status` attribute of the presence stanza. It must map :class:`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*).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L1472-L1487
horazont/aioxmpp
aioxmpp/im/service.py
ConversationService._add_conversation
def _add_conversation(self, conversation): """ Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conversations which can be queried at :attr:`conversations`. The :meth:`on_conversation_added` event is fired. In addition, the :class:`ConversationService` subscribes to the :meth:`~.AbstractConversation.on_exit` event to remove the conversation from the list automatically. There is no need to remove a conversation from the list explicitly. """ handler = functools.partial( self._handle_conversation_exit, conversation ) tokens = [] def linked_token(signal, handler): return signal, signal.connect(handler) tokens.append(linked_token(conversation.on_exit, handler)) tokens.append(linked_token(conversation.on_failure, handler)) tokens.append(linked_token(conversation.on_message, functools.partial( self.on_message, conversation, ))) self._conversation_meta[conversation] = ( tokens, ) self._conversation_map[conversation.jid] = conversation self.on_conversation_added(conversation)
python
def _add_conversation(self, conversation): """ Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conversations which can be queried at :attr:`conversations`. The :meth:`on_conversation_added` event is fired. In addition, the :class:`ConversationService` subscribes to the :meth:`~.AbstractConversation.on_exit` event to remove the conversation from the list automatically. There is no need to remove a conversation from the list explicitly. """ handler = functools.partial( self._handle_conversation_exit, conversation ) tokens = [] def linked_token(signal, handler): return signal, signal.connect(handler) tokens.append(linked_token(conversation.on_exit, handler)) tokens.append(linked_token(conversation.on_failure, handler)) tokens.append(linked_token(conversation.on_message, functools.partial( self.on_message, conversation, ))) self._conversation_meta[conversation] = ( tokens, ) self._conversation_map[conversation.jid] = conversation self.on_conversation_added(conversation)
Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conversations which can be queried at :attr:`conversations`. The :meth:`on_conversation_added` event is fired. In addition, the :class:`ConversationService` subscribes to the :meth:`~.AbstractConversation.on_exit` event to remove the conversation from the list automatically. There is no need to remove a conversation from the list explicitly.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/im/service.py#L99-L135
horazont/aioxmpp
aioxmpp/ping/service.py
ping
def ping(client, peer): """ Ping a peer. :param peer: The peer to ping. :type peer: :class:`aioxmpp.JID` :raises aioxmpp.errors.XMPPError: as received Send a :xep:`199` ping IQ to `peer` and wait for the reply. This is a low-level version of :meth:`aioxmpp.PingService.ping`. **When to use this function vs. the service method:** See :meth:`aioxmpp.PingService.ping`. .. note:: If the peer does not support :xep:`199`, they will respond with a ``cancel`` ``service-unavailable`` error. However, some implementations return a ``cancel`` ``feature-not-implemented`` error instead. Callers should be prepared for the :class:`aioxmpp.XMPPCancelError` exceptions in those cases. .. versionchanged:: 0.11 Extracted this helper from :class:`aioxmpp.PingService`. """ iq = aioxmpp.IQ( to=peer, type_=aioxmpp.IQType.GET, payload=ping_xso.Ping() ) yield from client.send(iq)
python
def ping(client, peer): """ Ping a peer. :param peer: The peer to ping. :type peer: :class:`aioxmpp.JID` :raises aioxmpp.errors.XMPPError: as received Send a :xep:`199` ping IQ to `peer` and wait for the reply. This is a low-level version of :meth:`aioxmpp.PingService.ping`. **When to use this function vs. the service method:** See :meth:`aioxmpp.PingService.ping`. .. note:: If the peer does not support :xep:`199`, they will respond with a ``cancel`` ``service-unavailable`` error. However, some implementations return a ``cancel`` ``feature-not-implemented`` error instead. Callers should be prepared for the :class:`aioxmpp.XMPPCancelError` exceptions in those cases. .. versionchanged:: 0.11 Extracted this helper from :class:`aioxmpp.PingService`. """ iq = aioxmpp.IQ( to=peer, type_=aioxmpp.IQType.GET, payload=ping_xso.Ping() ) yield from client.send(iq)
Ping a peer. :param peer: The peer to ping. :type peer: :class:`aioxmpp.JID` :raises aioxmpp.errors.XMPPError: as received Send a :xep:`199` ping IQ to `peer` and wait for the reply. This is a low-level version of :meth:`aioxmpp.PingService.ping`. **When to use this function vs. the service method:** See :meth:`aioxmpp.PingService.ping`. .. note:: If the peer does not support :xep:`199`, they will respond with a ``cancel`` ``service-unavailable`` error. However, some implementations return a ``cancel`` ``feature-not-implemented`` error instead. Callers should be prepared for the :class:`aioxmpp.XMPPCancelError` exceptions in those cases. .. versionchanged:: 0.11 Extracted this helper from :class:`aioxmpp.PingService`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ping/service.py#L90-L124
horazont/aioxmpp
aioxmpp/shim/service.py
SHIMService.register_header
def register_header(self, name): """ Register support for the SHIM header with the given `name`. If the header has already been registered as supported, :class:`ValueError` is raised. """ self._node.register_feature( "#".join([namespaces.xep0131_shim, name]) )
python
def register_header(self, name): """ Register support for the SHIM header with the given `name`. If the header has already been registered as supported, :class:`ValueError` is raised. """ self._node.register_feature( "#".join([namespaces.xep0131_shim, name]) )
Register support for the SHIM header with the given `name`. If the header has already been registered as supported, :class:`ValueError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/shim/service.py#L71-L81
horazont/aioxmpp
aioxmpp/shim/service.py
SHIMService.unregister_header
def unregister_header(self, name): """ Unregister support for the SHIM header with the given `name`. If the header is currently not registered as supported, :class:`KeyError` is raised. """ self._node.unregister_feature( "#".join([namespaces.xep0131_shim, name]) )
python
def unregister_header(self, name): """ Unregister support for the SHIM header with the given `name`. If the header is currently not registered as supported, :class:`KeyError` is raised. """ self._node.unregister_feature( "#".join([namespaces.xep0131_shim, name]) )
Unregister support for the SHIM header with the given `name`. If the header is currently not registered as supported, :class:`KeyError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/shim/service.py#L83-L93
horazont/aioxmpp
aioxmpp/vcard/service.py
VCardService.get_vcard
def get_vcard(self, jid=None): """ Get the vCard stored for the jid `jid`. If `jid` is :data:`None` get the vCard of the connected entity. :param jid: the object to retrieve. :returns: the stored vCard. We mask a :class:`XMPPCancelError` in case it is ``feature-not-implemented`` or ``item-not-found`` and return an empty vCard, since this can be understood to be semantically equivalent. """ iq = aioxmpp.IQ( type_=aioxmpp.IQType.GET, to=jid, payload=vcard_xso.VCard(), ) try: return (yield from self.client.send(iq)) except aioxmpp.XMPPCancelError as e: if e.condition in ( aioxmpp.ErrorCondition.FEATURE_NOT_IMPLEMENTED, aioxmpp.ErrorCondition.ITEM_NOT_FOUND): return vcard_xso.VCard() else: raise
python
def get_vcard(self, jid=None): """ Get the vCard stored for the jid `jid`. If `jid` is :data:`None` get the vCard of the connected entity. :param jid: the object to retrieve. :returns: the stored vCard. We mask a :class:`XMPPCancelError` in case it is ``feature-not-implemented`` or ``item-not-found`` and return an empty vCard, since this can be understood to be semantically equivalent. """ iq = aioxmpp.IQ( type_=aioxmpp.IQType.GET, to=jid, payload=vcard_xso.VCard(), ) try: return (yield from self.client.send(iq)) except aioxmpp.XMPPCancelError as e: if e.condition in ( aioxmpp.ErrorCondition.FEATURE_NOT_IMPLEMENTED, aioxmpp.ErrorCondition.ITEM_NOT_FOUND): return vcard_xso.VCard() else: raise
Get the vCard stored for the jid `jid`. If `jid` is :data:`None` get the vCard of the connected entity. :param jid: the object to retrieve. :returns: the stored vCard. We mask a :class:`XMPPCancelError` in case it is ``feature-not-implemented`` or ``item-not-found`` and return an empty vCard, since this can be understood to be semantically equivalent.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/vcard/service.py#L40-L68
horazont/aioxmpp
aioxmpp/vcard/service.py
VCardService.set_vcard
def set_vcard(self, vcard): """ Store the vCard `vcard` for the connected entity. :param vcard: the vCard to store. .. note:: `vcard` should always be derived from the result of `get_vcard` to preserve the elements of the vcard the client does not modify. .. warning:: It is in the responsibility of the user to supply valid vcard data as per :xep:`0054`. """ iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=vcard, ) yield from self.client.send(iq)
python
def set_vcard(self, vcard): """ Store the vCard `vcard` for the connected entity. :param vcard: the vCard to store. .. note:: `vcard` should always be derived from the result of `get_vcard` to preserve the elements of the vcard the client does not modify. .. warning:: It is in the responsibility of the user to supply valid vcard data as per :xep:`0054`. """ iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=vcard, ) yield from self.client.send(iq)
Store the vCard `vcard` for the connected entity. :param vcard: the vCard to store. .. note:: `vcard` should always be derived from the result of `get_vcard` to preserve the elements of the vcard the client does not modify. .. warning:: It is in the responsibility of the user to supply valid vcard data as per :xep:`0054`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/vcard/service.py#L71-L92
horazont/aioxmpp
aioxmpp/chatstates/utils.py
ChatStateManager.handle
def handle(self, state, message=False): """ Handle a state update. :param state: the new chat state :type state: :class:`~aioxmpp.chatstates.ChatState` :param message: pass true to indicate that we handle the :data:`ACTIVE` state that is implied by sending a content message. :type message: :class:`bool` :returns: whether a standalone notification must be sent for this state update, respective if a chat state notification must be included with the message. :raises ValueError: if `message` is true and a state other than :data:`ACTIVE` is passed. """ if message: if state != chatstates_xso.ChatState.ACTIVE: raise ValueError( "Only the state ACTIVE can be sent with messages." ) elif self._state == state: return False self._state = state return self._strategy.sending
python
def handle(self, state, message=False): """ Handle a state update. :param state: the new chat state :type state: :class:`~aioxmpp.chatstates.ChatState` :param message: pass true to indicate that we handle the :data:`ACTIVE` state that is implied by sending a content message. :type message: :class:`bool` :returns: whether a standalone notification must be sent for this state update, respective if a chat state notification must be included with the message. :raises ValueError: if `message` is true and a state other than :data:`ACTIVE` is passed. """ if message: if state != chatstates_xso.ChatState.ACTIVE: raise ValueError( "Only the state ACTIVE can be sent with messages." ) elif self._state == state: return False self._state = state return self._strategy.sending
Handle a state update. :param state: the new chat state :type state: :class:`~aioxmpp.chatstates.ChatState` :param message: pass true to indicate that we handle the :data:`ACTIVE` state that is implied by sending a content message. :type message: :class:`bool` :returns: whether a standalone notification must be sent for this state update, respective if a chat state notification must be included with the message. :raises ValueError: if `message` is true and a state other than :data:`ACTIVE` is passed.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/chatstates/utils.py#L111-L139
horazont/aioxmpp
aioxmpp/stanza.py
make_application_error
def make_application_error(name, tag): """ Create and return a **class** inheriting from :class:`.xso.XSO`. The :attr:`.xso.XSO.TAG` is set to `tag` and the class’ name will be `name`. In addition, the class is automatically registered with :attr:`.Error.application_condition` using :meth:`~.Error.as_application_condition`. Keep in mind that if you subclass the class returned by this function, the subclass is not registered with :class:`.Error`. In addition, if you do not override the :attr:`~.xso.XSO.TAG`, you will not be able to register the subclass as application defined condition as it has the same tag as the class returned by this function, which has already been registered as application condition. """ cls = type(xso.XSO)(name, (xso.XSO,), { "TAG": tag, }) Error.as_application_condition(cls) return cls
python
def make_application_error(name, tag): """ Create and return a **class** inheriting from :class:`.xso.XSO`. The :attr:`.xso.XSO.TAG` is set to `tag` and the class’ name will be `name`. In addition, the class is automatically registered with :attr:`.Error.application_condition` using :meth:`~.Error.as_application_condition`. Keep in mind that if you subclass the class returned by this function, the subclass is not registered with :class:`.Error`. In addition, if you do not override the :attr:`~.xso.XSO.TAG`, you will not be able to register the subclass as application defined condition as it has the same tag as the class returned by this function, which has already been registered as application condition. """ cls = type(xso.XSO)(name, (xso.XSO,), { "TAG": tag, }) Error.as_application_condition(cls) return cls
Create and return a **class** inheriting from :class:`.xso.XSO`. The :attr:`.xso.XSO.TAG` is set to `tag` and the class’ name will be `name`. In addition, the class is automatically registered with :attr:`.Error.application_condition` using :meth:`~.Error.as_application_condition`. Keep in mind that if you subclass the class returned by this function, the subclass is not registered with :class:`.Error`. In addition, if you do not override the :attr:`~.xso.XSO.TAG`, you will not be able to register the subclass as application defined condition as it has the same tag as the class returned by this function, which has already been registered as application condition.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stanza.py#L1037-L1057
horazont/aioxmpp
aioxmpp/stanza.py
Error.from_exception
def from_exception(cls, exc): """ Construct a new :class:`Error` payload from the attributes of the exception. :param exc: The exception to convert :type exc: :class:`aioxmpp.errors.XMPPError` :result: Newly constructed error payload :rtype: :class:`Error` .. versionchanged:: 0.10 The :attr:`aioxmpp.XMPPError.application_defined_condition` is now taken over into the result. """ result = cls( condition=exc.condition, type_=exc.TYPE, text=exc.text ) result.application_condition = exc.application_defined_condition return result
python
def from_exception(cls, exc): """ Construct a new :class:`Error` payload from the attributes of the exception. :param exc: The exception to convert :type exc: :class:`aioxmpp.errors.XMPPError` :result: Newly constructed error payload :rtype: :class:`Error` .. versionchanged:: 0.10 The :attr:`aioxmpp.XMPPError.application_defined_condition` is now taken over into the result. """ result = cls( condition=exc.condition, type_=exc.TYPE, text=exc.text ) result.application_condition = exc.application_defined_condition return result
Construct a new :class:`Error` payload from the attributes of the exception. :param exc: The exception to convert :type exc: :class:`aioxmpp.errors.XMPPError` :result: Newly constructed error payload :rtype: :class:`Error` .. versionchanged:: 0.10 The :attr:`aioxmpp.XMPPError.application_defined_condition` is now taken over into the result.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stanza.py#L356-L377
horazont/aioxmpp
aioxmpp/stanza.py
Error.to_exception
def to_exception(self): """ Convert the error payload to a :class:`~aioxmpp.errors.XMPPError` subclass. :result: Newly constructed exception :rtype: :class:`aioxmpp.errors.XMPPError` The exact type of the result depends on the :attr:`type_` (see :class:`~aioxmpp.errors.XMPPError` about the existing subclasses). The :attr:`condition_obj`, :attr:`text` and :attr:`application_condition` are transferred to the respective attributes of the :class:`~aioxmpp.errors.XMPPError`. """ if hasattr(self.application_condition, "to_exception"): result = self.application_condition.to_exception(self.type_) if isinstance(result, Exception): return result return self.EXCEPTION_CLS_MAP[self.type_]( condition=self.condition_obj, text=self.text, application_defined_condition=self.application_condition, )
python
def to_exception(self): """ Convert the error payload to a :class:`~aioxmpp.errors.XMPPError` subclass. :result: Newly constructed exception :rtype: :class:`aioxmpp.errors.XMPPError` The exact type of the result depends on the :attr:`type_` (see :class:`~aioxmpp.errors.XMPPError` about the existing subclasses). The :attr:`condition_obj`, :attr:`text` and :attr:`application_condition` are transferred to the respective attributes of the :class:`~aioxmpp.errors.XMPPError`. """ if hasattr(self.application_condition, "to_exception"): result = self.application_condition.to_exception(self.type_) if isinstance(result, Exception): return result return self.EXCEPTION_CLS_MAP[self.type_]( condition=self.condition_obj, text=self.text, application_defined_condition=self.application_condition, )
Convert the error payload to a :class:`~aioxmpp.errors.XMPPError` subclass. :result: Newly constructed exception :rtype: :class:`aioxmpp.errors.XMPPError` The exact type of the result depends on the :attr:`type_` (see :class:`~aioxmpp.errors.XMPPError` about the existing subclasses). The :attr:`condition_obj`, :attr:`text` and :attr:`application_condition` are transferred to the respective attributes of the :class:`~aioxmpp.errors.XMPPError`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stanza.py#L379-L403
horazont/aioxmpp
aioxmpp/stanza.py
StanzaBase.autoset_id
def autoset_id(self): """ If the :attr:`id_` already has a non-false (false is also the empty string!) value, this method is a no-op. Otherwise, the :attr:`id_` attribute is filled with :data:`RANDOM_ID_BYTES` of random data, encoded by :func:`aioxmpp.utils.to_nmtoken`. .. note:: This method only works on subclasses of :class:`StanzaBase` which define the :attr:`id_` attribute. """ try: self.id_ except AttributeError: pass else: if self.id_: return self.id_ = to_nmtoken(random.getrandbits(8*RANDOM_ID_BYTES))
python
def autoset_id(self): """ If the :attr:`id_` already has a non-false (false is also the empty string!) value, this method is a no-op. Otherwise, the :attr:`id_` attribute is filled with :data:`RANDOM_ID_BYTES` of random data, encoded by :func:`aioxmpp.utils.to_nmtoken`. .. note:: This method only works on subclasses of :class:`StanzaBase` which define the :attr:`id_` attribute. """ try: self.id_ except AttributeError: pass else: if self.id_: return self.id_ = to_nmtoken(random.getrandbits(8*RANDOM_ID_BYTES))
If the :attr:`id_` already has a non-false (false is also the empty string!) value, this method is a no-op. Otherwise, the :attr:`id_` attribute is filled with :data:`RANDOM_ID_BYTES` of random data, encoded by :func:`aioxmpp.utils.to_nmtoken`. .. note:: This method only works on subclasses of :class:`StanzaBase` which define the :attr:`id_` attribute.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stanza.py#L502-L524
horazont/aioxmpp
aioxmpp/stanza.py
StanzaBase.make_error
def make_error(self, error): """ Create a new instance of this stanza (this directly uses ``type(self)``, so also works for subclasses without extra care) which has the given `error` value set as :attr:`error`. In addition, the :attr:`id_`, :attr:`from_` and :attr:`to` values are transferred from the original (with from and to being swapped). Also, the :attr:`type_` is set to ``"error"``. """ obj = type(self)( from_=self.to, to=self.from_, # because flat is better than nested (sarcasm) type_=type(self).type_.type_.enum_class.ERROR, ) obj.id_ = self.id_ obj.error = error return obj
python
def make_error(self, error): """ Create a new instance of this stanza (this directly uses ``type(self)``, so also works for subclasses without extra care) which has the given `error` value set as :attr:`error`. In addition, the :attr:`id_`, :attr:`from_` and :attr:`to` values are transferred from the original (with from and to being swapped). Also, the :attr:`type_` is set to ``"error"``. """ obj = type(self)( from_=self.to, to=self.from_, # because flat is better than nested (sarcasm) type_=type(self).type_.type_.enum_class.ERROR, ) obj.id_ = self.id_ obj.error = error return obj
Create a new instance of this stanza (this directly uses ``type(self)``, so also works for subclasses without extra care) which has the given `error` value set as :attr:`error`. In addition, the :attr:`id_`, :attr:`from_` and :attr:`to` values are transferred from the original (with from and to being swapped). Also, the :attr:`type_` is set to ``"error"``.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stanza.py#L533-L551
horazont/aioxmpp
aioxmpp/stanza.py
Message.make_reply
def make_reply(self): """ Create a reply for the message. The :attr:`id_` attribute is cleared in the reply. The :attr:`from_` and :attr:`to` are swapped and the :attr:`type_` attribute is the same as the one of the original message. The new :class:`Message` object is returned. """ obj = super()._make_reply(self.type_) obj.id_ = None return obj
python
def make_reply(self): """ Create a reply for the message. The :attr:`id_` attribute is cleared in the reply. The :attr:`from_` and :attr:`to` are swapped and the :attr:`type_` attribute is the same as the one of the original message. The new :class:`Message` object is returned. """ obj = super()._make_reply(self.type_) obj.id_ = None return obj
Create a reply for the message. The :attr:`id_` attribute is cleared in the reply. The :attr:`from_` and :attr:`to` are swapped and the :attr:`type_` attribute is the same as the one of the original message. The new :class:`Message` object is returned.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stanza.py#L729-L740
horazont/aioxmpp
aioxmpp/protocol.py
XMLStream.close
def close(self): """ Close the XML stream and the underlying transport. This gracefully shuts down the XML stream and the transport, if possible by writing the eof using :meth:`asyncio.Transport.write_eof` after sending the stream footer. After a call to :meth:`close`, no other stream manipulating or sending method can be called; doing so will result in a :class:`ConnectionError` exception or any exception caused by the transport during shutdown. Calling :meth:`close` while the stream is closing or closed is a no-op. """ if (self._smachine.state == State.CLOSING or self._smachine.state == State.CLOSED): return self._writer.close() if self._transport.can_write_eof(): self._transport.write_eof() if self._smachine.state == State.STREAM_HEADER_SENT: # at this point, we cannot wait for the peer to send # </stream:stream> self._close_transport() self._smachine.state = State.CLOSING
python
def close(self): """ Close the XML stream and the underlying transport. This gracefully shuts down the XML stream and the transport, if possible by writing the eof using :meth:`asyncio.Transport.write_eof` after sending the stream footer. After a call to :meth:`close`, no other stream manipulating or sending method can be called; doing so will result in a :class:`ConnectionError` exception or any exception caused by the transport during shutdown. Calling :meth:`close` while the stream is closing or closed is a no-op. """ if (self._smachine.state == State.CLOSING or self._smachine.state == State.CLOSED): return self._writer.close() if self._transport.can_write_eof(): self._transport.write_eof() if self._smachine.state == State.STREAM_HEADER_SENT: # at this point, we cannot wait for the peer to send # </stream:stream> self._close_transport() self._smachine.state = State.CLOSING
Close the XML stream and the underlying transport. This gracefully shuts down the XML stream and the transport, if possible by writing the eof using :meth:`asyncio.Transport.write_eof` after sending the stream footer. After a call to :meth:`close`, no other stream manipulating or sending method can be called; doing so will result in a :class:`ConnectionError` exception or any exception caused by the transport during shutdown. Calling :meth:`close` while the stream is closing or closed is a no-op.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/protocol.py#L539-L565
horazont/aioxmpp
aioxmpp/protocol.py
XMLStream.reset
def reset(self): """ Reset the stream by discarding all state and re-sending the stream header. Calling :meth:`reset` when the stream is disconnected or currently disconnecting results in either :class:`ConnectionError` being raised or the exception which caused the stream to die (possibly a received stream error or a transport error) to be reraised. :meth:`reset` puts the stream into :attr:`~State.STREAM_HEADER_SENT` state and it cannot be used for sending XSOs until the peer stream header has been received. Usually, this is not a problem as stream resets only occur during stream negotiation and stream negotiation typically waits for the peers feature node to arrive first. """ self._require_connection(accept_partial=True) self._reset_state() self._writer.start() self._smachine.rewind(State.STREAM_HEADER_SENT)
python
def reset(self): """ Reset the stream by discarding all state and re-sending the stream header. Calling :meth:`reset` when the stream is disconnected or currently disconnecting results in either :class:`ConnectionError` being raised or the exception which caused the stream to die (possibly a received stream error or a transport error) to be reraised. :meth:`reset` puts the stream into :attr:`~State.STREAM_HEADER_SENT` state and it cannot be used for sending XSOs until the peer stream header has been received. Usually, this is not a problem as stream resets only occur during stream negotiation and stream negotiation typically waits for the peers feature node to arrive first. """ self._require_connection(accept_partial=True) self._reset_state() self._writer.start() self._smachine.rewind(State.STREAM_HEADER_SENT)
Reset the stream by discarding all state and re-sending the stream header. Calling :meth:`reset` when the stream is disconnected or currently disconnecting results in either :class:`ConnectionError` being raised or the exception which caused the stream to die (possibly a received stream error or a transport error) to be reraised. :meth:`reset` puts the stream into :attr:`~State.STREAM_HEADER_SENT` state and it cannot be used for sending XSOs until the peer stream header has been received. Usually, this is not a problem as stream resets only occur during stream negotiation and stream negotiation typically waits for the peers feature node to arrive first.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/protocol.py#L613-L632
horazont/aioxmpp
aioxmpp/protocol.py
XMLStream.abort
def abort(self): """ Abort the stream by writing an EOF if possible and closing the transport. The transport is closed using :meth:`asyncio.BaseTransport.close`, so buffered data is sent, but no more data will be received. The stream is in :attr:`State.CLOSED` state afterwards. This also works if the stream is currently closing, that is, waiting for the peer to send a stream footer. In that case, the stream will be closed locally as if the stream footer had been received. .. versionadded:: 0.5 """ if self._smachine.state == State.CLOSED: return if self._smachine.state == State.READY: self._smachine.state = State.CLOSED return if (self._smachine.state != State.CLOSING and self._transport.can_write_eof()): self._transport.write_eof() self._close_transport()
python
def abort(self): """ Abort the stream by writing an EOF if possible and closing the transport. The transport is closed using :meth:`asyncio.BaseTransport.close`, so buffered data is sent, but no more data will be received. The stream is in :attr:`State.CLOSED` state afterwards. This also works if the stream is currently closing, that is, waiting for the peer to send a stream footer. In that case, the stream will be closed locally as if the stream footer had been received. .. versionadded:: 0.5 """ if self._smachine.state == State.CLOSED: return if self._smachine.state == State.READY: self._smachine.state = State.CLOSED return if (self._smachine.state != State.CLOSING and self._transport.can_write_eof()): self._transport.write_eof() self._close_transport()
Abort the stream by writing an EOF if possible and closing the transport. The transport is closed using :meth:`asyncio.BaseTransport.close`, so buffered data is sent, but no more data will be received. The stream is in :attr:`State.CLOSED` state afterwards. This also works if the stream is currently closing, that is, waiting for the peer to send a stream footer. In that case, the stream will be closed locally as if the stream footer had been received. .. versionadded:: 0.5
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/protocol.py#L634-L657
horazont/aioxmpp
aioxmpp/protocol.py
XMLStream.starttls
def starttls(self, ssl_context, post_handshake_callback=None): """ Start TLS on the transport and wait for it to complete. The `ssl_context` and `post_handshake_callback` arguments are forwarded to the transports :meth:`aioopenssl.STARTTLSTransport.starttls` coroutine method. If the transport does not support starttls, :class:`RuntimeError` is raised; support for starttls can be discovered by querying :meth:`can_starttls`. After :meth:`starttls` returns, you must call :meth:`reset`. Any other method may fail in interesting ways as the internal state is discarded when starttls succeeds, for security reasons. :meth:`reset` re-creates the internal structures. """ self._require_connection() if not self.can_starttls(): raise RuntimeError("starttls not available on transport") yield from self._transport.starttls(ssl_context, post_handshake_callback) self._reset_state()
python
def starttls(self, ssl_context, post_handshake_callback=None): """ Start TLS on the transport and wait for it to complete. The `ssl_context` and `post_handshake_callback` arguments are forwarded to the transports :meth:`aioopenssl.STARTTLSTransport.starttls` coroutine method. If the transport does not support starttls, :class:`RuntimeError` is raised; support for starttls can be discovered by querying :meth:`can_starttls`. After :meth:`starttls` returns, you must call :meth:`reset`. Any other method may fail in interesting ways as the internal state is discarded when starttls succeeds, for security reasons. :meth:`reset` re-creates the internal structures. """ self._require_connection() if not self.can_starttls(): raise RuntimeError("starttls not available on transport") yield from self._transport.starttls(ssl_context, post_handshake_callback) self._reset_state()
Start TLS on the transport and wait for it to complete. The `ssl_context` and `post_handshake_callback` arguments are forwarded to the transports :meth:`aioopenssl.STARTTLSTransport.starttls` coroutine method. If the transport does not support starttls, :class:`RuntimeError` is raised; support for starttls can be discovered by querying :meth:`can_starttls`. After :meth:`starttls` returns, you must call :meth:`reset`. Any other method may fail in interesting ways as the internal state is discarded when starttls succeeds, for security reasons. :meth:`reset` re-creates the internal structures.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/protocol.py#L699-L722
horazont/aioxmpp
aioxmpp/protocol.py
XMLStream.error_future
def error_future(self): """ Return a future which will receive the next XML stream error as exception. It is safe to cancel the future at any time. """ fut = asyncio.Future(loop=self._loop) self._error_futures.append(fut) return fut
python
def error_future(self): """ Return a future which will receive the next XML stream error as exception. It is safe to cancel the future at any time. """ fut = asyncio.Future(loop=self._loop) self._error_futures.append(fut) return fut
Return a future which will receive the next XML stream error as exception. It is safe to cancel the future at any time.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/protocol.py#L724-L733
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_features
def get_features(self, jid): """ Return the features supported by a service. :param jid: Address of the PubSub service to query. :type jid: :class:`aioxmpp.JID` :return: Set of supported features :rtype: set containing :class:`~.pubsub.xso.Feature` enumeration members. This simply uses service discovery to obtain the set of features and converts the features to :class:`~.pubsub.xso.Feature` enumeration members. To get the full feature information, resort to using :meth:`.DiscoClient.query_info` directly on `jid`. Features returned by the peer which are not valid pubsub features are not returned. """ response = yield from self._disco.query_info(jid) result = set() for feature in response.features: try: result.add(pubsub_xso.Feature(feature)) except ValueError: continue return result
python
def get_features(self, jid): """ Return the features supported by a service. :param jid: Address of the PubSub service to query. :type jid: :class:`aioxmpp.JID` :return: Set of supported features :rtype: set containing :class:`~.pubsub.xso.Feature` enumeration members. This simply uses service discovery to obtain the set of features and converts the features to :class:`~.pubsub.xso.Feature` enumeration members. To get the full feature information, resort to using :meth:`.DiscoClient.query_info` directly on `jid`. Features returned by the peer which are not valid pubsub features are not returned. """ response = yield from self._disco.query_info(jid) result = set() for feature in response.features: try: result.add(pubsub_xso.Feature(feature)) except ValueError: continue return result
Return the features supported by a service. :param jid: Address of the PubSub service to query. :type jid: :class:`aioxmpp.JID` :return: Set of supported features :rtype: set containing :class:`~.pubsub.xso.Feature` enumeration members. This simply uses service discovery to obtain the set of features and converts the features to :class:`~.pubsub.xso.Feature` enumeration members. To get the full feature information, resort to using :meth:`.DiscoClient.query_info` directly on `jid`. Features returned by the peer which are not valid pubsub features are not returned.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L274-L300
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.subscribe
def subscribe(self, jid, node=None, *, subscription_jid=None, config=None): """ Subscribe to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to subscribe to. :type node: :class:`str` :param subscription_jid: The address to subscribe to the service. :type subscription_jid: :class:`aioxmpp.JID` :param config: Optional configuration of the subscription :type config: :class:`~.forms.Data` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the server. :rtype: :class:`.xso.Request` By default, the subscription request will be for the bare JID of the client. It can be specified explicitly using the `subscription_jid` argument. If the service requires it or if it makes sense for other reasons, the subscription configuration :class:`~.forms.Data` form can be passed using the `config` argument. On success, the whole :class:`.xso.Request` object returned by the server is returned. It contains a :class:`.xso.Subscription` :attr:`~.xso.Request.payload` which has information on the nature of the subscription (it may be ``"pending"`` or ``"unconfigured"``) and the :attr:`~.xso.Subscription.subid` which may be required for other operations. On failure, the corresponding :class:`~.errors.XMPPError` is raised. """ subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( pubsub_xso.Subscribe(subscription_jid, node=node) ) if config is not None: iq.payload.options = pubsub_xso.Options( subscription_jid, node=node ) iq.payload.options.data = config response = yield from self.client.send(iq) return response
python
def subscribe(self, jid, node=None, *, subscription_jid=None, config=None): """ Subscribe to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to subscribe to. :type node: :class:`str` :param subscription_jid: The address to subscribe to the service. :type subscription_jid: :class:`aioxmpp.JID` :param config: Optional configuration of the subscription :type config: :class:`~.forms.Data` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the server. :rtype: :class:`.xso.Request` By default, the subscription request will be for the bare JID of the client. It can be specified explicitly using the `subscription_jid` argument. If the service requires it or if it makes sense for other reasons, the subscription configuration :class:`~.forms.Data` form can be passed using the `config` argument. On success, the whole :class:`.xso.Request` object returned by the server is returned. It contains a :class:`.xso.Subscription` :attr:`~.xso.Request.payload` which has information on the nature of the subscription (it may be ``"pending"`` or ``"unconfigured"``) and the :attr:`~.xso.Subscription.subid` which may be required for other operations. On failure, the corresponding :class:`~.errors.XMPPError` is raised. """ subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( pubsub_xso.Subscribe(subscription_jid, node=node) ) if config is not None: iq.payload.options = pubsub_xso.Options( subscription_jid, node=node ) iq.payload.options.data = config response = yield from self.client.send(iq) return response
Subscribe to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to subscribe to. :type node: :class:`str` :param subscription_jid: The address to subscribe to the service. :type subscription_jid: :class:`aioxmpp.JID` :param config: Optional configuration of the subscription :type config: :class:`~.forms.Data` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the server. :rtype: :class:`.xso.Request` By default, the subscription request will be for the bare JID of the client. It can be specified explicitly using the `subscription_jid` argument. If the service requires it or if it makes sense for other reasons, the subscription configuration :class:`~.forms.Data` form can be passed using the `config` argument. On success, the whole :class:`.xso.Request` object returned by the server is returned. It contains a :class:`.xso.Subscription` :attr:`~.xso.Request.payload` which has information on the nature of the subscription (it may be ``"pending"`` or ``"unconfigured"``) and the :attr:`~.xso.Subscription.subid` which may be required for other operations. On failure, the corresponding :class:`~.errors.XMPPError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L303-L354
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.unsubscribe
def unsubscribe(self, jid, node=None, *, subscription_jid=None, subid=None): """ Unsubscribe from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to unsubscribe from. :type node: :class:`str` :param subscription_jid: The address to subscribe from the service. :type subscription_jid: :class:`aioxmpp.JID` :param subid: Unique ID of the subscription to remove. :type subid: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service By default, the unsubscribe request will be for the bare JID of the client. It can be specified explicitly using the `subscription_jid` argument. If available, the `subid` should also be specified. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised. """ subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( pubsub_xso.Unsubscribe(subscription_jid, node=node, subid=subid) ) yield from self.client.send(iq)
python
def unsubscribe(self, jid, node=None, *, subscription_jid=None, subid=None): """ Unsubscribe from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to unsubscribe from. :type node: :class:`str` :param subscription_jid: The address to subscribe from the service. :type subscription_jid: :class:`aioxmpp.JID` :param subid: Unique ID of the subscription to remove. :type subid: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service By default, the unsubscribe request will be for the bare JID of the client. It can be specified explicitly using the `subscription_jid` argument. If available, the `subid` should also be specified. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised. """ subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( pubsub_xso.Unsubscribe(subscription_jid, node=node, subid=subid) ) yield from self.client.send(iq)
Unsubscribe from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to unsubscribe from. :type node: :class:`str` :param subscription_jid: The address to subscribe from the service. :type subscription_jid: :class:`aioxmpp.JID` :param subid: Unique ID of the subscription to remove. :type subid: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service By default, the unsubscribe request will be for the bare JID of the client. It can be specified explicitly using the `subscription_jid` argument. If available, the `subid` should also be specified. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L357-L390
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_subscription_config
def get_subscription_config(self, jid, node=None, *, subscription_jid=None, subid=None): """ Request the current configuration of a subscription. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param subscription_jid: The address to query the configuration for. :type subscription_jid: :class:`aioxmpp.JID` :param subid: Unique ID of the subscription to query. :type subid: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The current configuration of the subscription. :rtype: :class:`~.forms.Data` By default, the request will be on behalf of the bare JID of the client. It can be overriden using the `subscription_jid` argument. If available, the `subid` should also be specified. On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised. """ subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request() iq.payload.options = pubsub_xso.Options( subscription_jid, node=node, subid=subid, ) response = yield from self.client.send(iq) return response.options.data
python
def get_subscription_config(self, jid, node=None, *, subscription_jid=None, subid=None): """ Request the current configuration of a subscription. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param subscription_jid: The address to query the configuration for. :type subscription_jid: :class:`aioxmpp.JID` :param subid: Unique ID of the subscription to query. :type subid: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The current configuration of the subscription. :rtype: :class:`~.forms.Data` By default, the request will be on behalf of the bare JID of the client. It can be overriden using the `subscription_jid` argument. If available, the `subid` should also be specified. On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised. """ subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request() iq.payload.options = pubsub_xso.Options( subscription_jid, node=node, subid=subid, ) response = yield from self.client.send(iq) return response.options.data
Request the current configuration of a subscription. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param subscription_jid: The address to query the configuration for. :type subscription_jid: :class:`aioxmpp.JID` :param subid: Unique ID of the subscription to query. :type subid: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The current configuration of the subscription. :rtype: :class:`~.forms.Data` By default, the request will be on behalf of the bare JID of the client. It can be overriden using the `subscription_jid` argument. If available, the `subid` should also be specified. On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L393-L433
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_default_config
def get_default_config(self, jid, node=None): """ Request the default configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The default configuration of subscriptions at the node. :rtype: :class:`~.forms.Data` On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Default(node=node) ) response = yield from self.client.send(iq) return response.payload.data
python
def get_default_config(self, jid, node=None): """ Request the default configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The default configuration of subscriptions at the node. :rtype: :class:`~.forms.Data` On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Default(node=node) ) response = yield from self.client.send(iq) return response.payload.data
Request the default configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The default configuration of subscriptions at the node. :rtype: :class:`~.forms.Data` On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L480-L504
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_node_config
def get_node_config(self, jid, node=None): """ Request the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration of the node. :rtype: :class:`~.forms.Data` On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.OwnerRequest( pubsub_xso.OwnerConfigure(node=node) ) response = yield from self.client.send(iq) return response.payload.data
python
def get_node_config(self, jid, node=None): """ Request the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration of the node. :rtype: :class:`~.forms.Data` On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.OwnerRequest( pubsub_xso.OwnerConfigure(node=node) ) response = yield from self.client.send(iq) return response.payload.data
Request the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration of the node. :rtype: :class:`~.forms.Data` On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L507-L531
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.set_node_config
def set_node_config(self, jid, config, node=None): """ Update the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param config: Configuration form :type config: :class:`aioxmpp.forms.Data` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration of the node. :rtype: :class:`~.forms.Data` .. seealso:: :class:`aioxmpp.pubsub.NodeConfigForm` """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.OwnerRequest( pubsub_xso.OwnerConfigure(node=node) ) iq.payload.payload.data = config yield from self.client.send(iq)
python
def set_node_config(self, jid, config, node=None): """ Update the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param config: Configuration form :type config: :class:`aioxmpp.forms.Data` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration of the node. :rtype: :class:`~.forms.Data` .. seealso:: :class:`aioxmpp.pubsub.NodeConfigForm` """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.OwnerRequest( pubsub_xso.OwnerConfigure(node=node) ) iq.payload.payload.data = config yield from self.client.send(iq)
Update the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param config: Configuration form :type config: :class:`aioxmpp.forms.Data` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration of the node. :rtype: :class:`~.forms.Data` .. seealso:: :class:`aioxmpp.pubsub.NodeConfigForm`
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L534-L559
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_items
def get_items(self, jid, node, *, max_items=None): """ Request the most recent items from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param max_items: Number of items to return at most. :type max_items: :class:`int` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the server. :rtype: :class:`.xso.Request`. By default, as many as possible items are requested. If `max_items` is given, it must be a positive integer specifying the maximum number of items which is to be returned by the server. Return the :class:`.xso.Request` object, which has a :class:`~.xso.Items` :attr:`~.xso.Request.payload`. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Items(node, max_items=max_items) ) return (yield from self.client.send(iq))
python
def get_items(self, jid, node, *, max_items=None): """ Request the most recent items from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param max_items: Number of items to return at most. :type max_items: :class:`int` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the server. :rtype: :class:`.xso.Request`. By default, as many as possible items are requested. If `max_items` is given, it must be a positive integer specifying the maximum number of items which is to be returned by the server. Return the :class:`.xso.Request` object, which has a :class:`~.xso.Items` :attr:`~.xso.Request.payload`. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Items(node, max_items=max_items) ) return (yield from self.client.send(iq))
Request the most recent items from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param max_items: Number of items to return at most. :type max_items: :class:`int` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the server. :rtype: :class:`.xso.Request`. By default, as many as possible items are requested. If `max_items` is given, it must be a positive integer specifying the maximum number of items which is to be returned by the server. Return the :class:`.xso.Request` object, which has a :class:`~.xso.Items` :attr:`~.xso.Request.payload`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L562-L589
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_items_by_id
def get_items_by_id(self, jid, node, ids): """ Request specific items by their IDs from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param ids: The item IDs to return. :type ids: :class:`~collections.abc.Iterable` of :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the service :rtype: :class:`.xso.Request` `ids` must be an iterable of :class:`str` of the IDs of the items to request from the pubsub node. If the iterable is empty, :class:`ValueError` is raised (as otherwise, the request would be identical to calling :meth:`get_items` without `max_items`). Return the :class:`.xso.Request` object, which has a :class:`~.xso.Items` :attr:`~.xso.Request.payload`. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Items(node) ) iq.payload.payload.items = [ pubsub_xso.Item(id_) for id_ in ids ] if not iq.payload.payload.items: raise ValueError("ids must not be empty") return (yield from self.client.send(iq))
python
def get_items_by_id(self, jid, node, ids): """ Request specific items by their IDs from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param ids: The item IDs to return. :type ids: :class:`~collections.abc.Iterable` of :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the service :rtype: :class:`.xso.Request` `ids` must be an iterable of :class:`str` of the IDs of the items to request from the pubsub node. If the iterable is empty, :class:`ValueError` is raised (as otherwise, the request would be identical to calling :meth:`get_items` without `max_items`). Return the :class:`.xso.Request` object, which has a :class:`~.xso.Items` :attr:`~.xso.Request.payload`. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Items(node) ) iq.payload.payload.items = [ pubsub_xso.Item(id_) for id_ in ids ] if not iq.payload.payload.items: raise ValueError("ids must not be empty") return (yield from self.client.send(iq))
Request specific items by their IDs from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param ids: The item IDs to return. :type ids: :class:`~collections.abc.Iterable` of :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the service :rtype: :class:`.xso.Request` `ids` must be an iterable of :class:`str` of the IDs of the items to request from the pubsub node. If the iterable is empty, :class:`ValueError` is raised (as otherwise, the request would be identical to calling :meth:`get_items` without `max_items`). Return the :class:`.xso.Request` object, which has a :class:`~.xso.Items` :attr:`~.xso.Request.payload`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L592-L628
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_subscriptions
def get_subscriptions(self, jid, node=None): """ Return all subscriptions of the local entity to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The subscriptions response from the service. :rtype: :class:`.xso.Subscriptions. If `node` is :data:`None`, subscriptions on all nodes of the entity `jid` are listed. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Subscriptions(node=node) ) response = yield from self.client.send(iq) return response.payload
python
def get_subscriptions(self, jid, node=None): """ Return all subscriptions of the local entity to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The subscriptions response from the service. :rtype: :class:`.xso.Subscriptions. If `node` is :data:`None`, subscriptions on all nodes of the entity `jid` are listed. """ iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Subscriptions(node=node) ) response = yield from self.client.send(iq) return response.payload
Return all subscriptions of the local entity to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The subscriptions response from the service. :rtype: :class:`.xso.Subscriptions. If `node` is :data:`None`, subscriptions on all nodes of the entity `jid` are listed.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L631-L653
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.publish
def publish(self, jid, node, payload, *, id_=None, publish_options=None): """ Publish an item to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to publish to. :type node: :class:`str` :param payload: Registered payload to publish. :type payload: :class:`aioxmpp.xso.XSO` :param id_: Item ID to use for the item. :type id_: :class:`str` or :data:`None`. :param publish_options: A data form with the options for the publish request :type publish_options: :class:`aioxmpp.forms.Data` :raises aioxmpp.errors.XMPPError: as returned by the service :raises RuntimeError: if `publish_options` is not :data:`None` but the service does not support `publish_options` :return: The Item ID which was used to publish the item. :rtype: :class:`str` or :data:`None` Publish the given `payload` (which must be a :class:`aioxmpp.xso.XSO` registered with :attr:`.xso.Item.registered_payload`). The item is published to `node` at `jid`. If `id_` is given, it is used as the ID for the item. If an item with the same ID already exists at the node, it is replaced. If no ID is given, a ID is generated by the server. If `publish_options` is given, it is passed as ``<publish-options/>`` element to the server. This needs to be a data form which allows to define e.g. node configuration as a pre-condition to publishing. If the publish-options cannot be satisfied, the server will raise a :attr:`aioxmpp.ErrorCondition.CONFLICT` error. If `publish_options` is given and the server does not announce the :attr:`aioxmpp.pubsub.xso.Feature.PUBLISH_OPTIONS` feature, :class:`RuntimeError` is raised to prevent security issues (e.g. if the publish options attempt to assert a restrictive access model). Return the ID of the item as published (or :data:`None` if the server does not inform us; this is unfortunately common). """ publish = pubsub_xso.Publish() publish.node = node if payload is not None: item = pubsub_xso.Item() item.id_ = id_ item.registered_payload = payload publish.item = item iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( publish ) if publish_options is not None: features = yield from self.get_features(jid) if pubsub_xso.Feature.PUBLISH_OPTIONS not in features: raise RuntimeError( "publish-options given, but not supported by server" ) iq.payload.publish_options = pubsub_xso.PublishOptions() iq.payload.publish_options.data = publish_options response = yield from self.client.send(iq) if response is not None and response.payload.item is not None: return response.payload.item.id_ or id_ return id_
python
def publish(self, jid, node, payload, *, id_=None, publish_options=None): """ Publish an item to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to publish to. :type node: :class:`str` :param payload: Registered payload to publish. :type payload: :class:`aioxmpp.xso.XSO` :param id_: Item ID to use for the item. :type id_: :class:`str` or :data:`None`. :param publish_options: A data form with the options for the publish request :type publish_options: :class:`aioxmpp.forms.Data` :raises aioxmpp.errors.XMPPError: as returned by the service :raises RuntimeError: if `publish_options` is not :data:`None` but the service does not support `publish_options` :return: The Item ID which was used to publish the item. :rtype: :class:`str` or :data:`None` Publish the given `payload` (which must be a :class:`aioxmpp.xso.XSO` registered with :attr:`.xso.Item.registered_payload`). The item is published to `node` at `jid`. If `id_` is given, it is used as the ID for the item. If an item with the same ID already exists at the node, it is replaced. If no ID is given, a ID is generated by the server. If `publish_options` is given, it is passed as ``<publish-options/>`` element to the server. This needs to be a data form which allows to define e.g. node configuration as a pre-condition to publishing. If the publish-options cannot be satisfied, the server will raise a :attr:`aioxmpp.ErrorCondition.CONFLICT` error. If `publish_options` is given and the server does not announce the :attr:`aioxmpp.pubsub.xso.Feature.PUBLISH_OPTIONS` feature, :class:`RuntimeError` is raised to prevent security issues (e.g. if the publish options attempt to assert a restrictive access model). Return the ID of the item as published (or :data:`None` if the server does not inform us; this is unfortunately common). """ publish = pubsub_xso.Publish() publish.node = node if payload is not None: item = pubsub_xso.Item() item.id_ = id_ item.registered_payload = payload publish.item = item iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( publish ) if publish_options is not None: features = yield from self.get_features(jid) if pubsub_xso.Feature.PUBLISH_OPTIONS not in features: raise RuntimeError( "publish-options given, but not supported by server" ) iq.payload.publish_options = pubsub_xso.PublishOptions() iq.payload.publish_options.data = publish_options response = yield from self.client.send(iq) if response is not None and response.payload.item is not None: return response.payload.item.id_ or id_ return id_
Publish an item to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to publish to. :type node: :class:`str` :param payload: Registered payload to publish. :type payload: :class:`aioxmpp.xso.XSO` :param id_: Item ID to use for the item. :type id_: :class:`str` or :data:`None`. :param publish_options: A data form with the options for the publish request :type publish_options: :class:`aioxmpp.forms.Data` :raises aioxmpp.errors.XMPPError: as returned by the service :raises RuntimeError: if `publish_options` is not :data:`None` but the service does not support `publish_options` :return: The Item ID which was used to publish the item. :rtype: :class:`str` or :data:`None` Publish the given `payload` (which must be a :class:`aioxmpp.xso.XSO` registered with :attr:`.xso.Item.registered_payload`). The item is published to `node` at `jid`. If `id_` is given, it is used as the ID for the item. If an item with the same ID already exists at the node, it is replaced. If no ID is given, a ID is generated by the server. If `publish_options` is given, it is passed as ``<publish-options/>`` element to the server. This needs to be a data form which allows to define e.g. node configuration as a pre-condition to publishing. If the publish-options cannot be satisfied, the server will raise a :attr:`aioxmpp.ErrorCondition.CONFLICT` error. If `publish_options` is given and the server does not announce the :attr:`aioxmpp.pubsub.xso.Feature.PUBLISH_OPTIONS` feature, :class:`RuntimeError` is raised to prevent security issues (e.g. if the publish options attempt to assert a restrictive access model). Return the ID of the item as published (or :data:`None` if the server does not inform us; this is unfortunately common).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L656-L730
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.retract
def retract(self, jid, node, id_, *, notify=False): """ Retract a previously published item from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to send a notify from. :type node: :class:`str` :param id_: The ID of the item to retract. :type id_: :class:`str` :param notify: Flag indicating whether subscribers shall be notified about the retraction. :type notify: :class:`bool` :raises aioxmpp.errors.XMPPError: as returned by the service Retract an item previously published to `node` at `jid`. `id_` must be the ItemID of the item to retract. If `notify` is set to true, notifications will be generated (by setting the `notify` attribute on the retraction request). """ retract = pubsub_xso.Retract() retract.node = node item = pubsub_xso.Item() item.id_ = id_ retract.item = item retract.notify = notify iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( retract ) yield from self.client.send(iq)
python
def retract(self, jid, node, id_, *, notify=False): """ Retract a previously published item from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to send a notify from. :type node: :class:`str` :param id_: The ID of the item to retract. :type id_: :class:`str` :param notify: Flag indicating whether subscribers shall be notified about the retraction. :type notify: :class:`bool` :raises aioxmpp.errors.XMPPError: as returned by the service Retract an item previously published to `node` at `jid`. `id_` must be the ItemID of the item to retract. If `notify` is set to true, notifications will be generated (by setting the `notify` attribute on the retraction request). """ retract = pubsub_xso.Retract() retract.node = node item = pubsub_xso.Item() item.id_ = id_ retract.item = item retract.notify = notify iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( retract ) yield from self.client.send(iq)
Retract a previously published item from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to send a notify from. :type node: :class:`str` :param id_: The ID of the item to retract. :type id_: :class:`str` :param notify: Flag indicating whether subscribers shall be notified about the retraction. :type notify: :class:`bool` :raises aioxmpp.errors.XMPPError: as returned by the service Retract an item previously published to `node` at `jid`. `id_` must be the ItemID of the item to retract. If `notify` is set to true, notifications will be generated (by setting the `notify` attribute on the retraction request).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L749-L782
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.create
def create(self, jid, node=None): """ Create a new node at a service. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to create. :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The name of the created node. :rtype: :class:`str` If `node` is :data:`None`, an instant node is created (see :xep:`60`). The server may not support or allow the creation of instant nodes. Return the actual `node` identifier. """ create = pubsub_xso.Create() create.node = node iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.Request(create) ) response = yield from self.client.send(iq) if response is not None and response.payload.node is not None: return response.payload.node return node
python
def create(self, jid, node=None): """ Create a new node at a service. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to create. :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The name of the created node. :rtype: :class:`str` If `node` is :data:`None`, an instant node is created (see :xep:`60`). The server may not support or allow the creation of instant nodes. Return the actual `node` identifier. """ create = pubsub_xso.Create() create.node = node iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.Request(create) ) response = yield from self.client.send(iq) if response is not None and response.payload.node is not None: return response.payload.node return node
Create a new node at a service. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to create. :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The name of the created node. :rtype: :class:`str` If `node` is :data:`None`, an instant node is created (see :xep:`60`). The server may not support or allow the creation of instant nodes. Return the actual `node` identifier.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L785-L817
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.delete
def delete(self, jid, node, *, redirect_uri=None): """ Delete an existing node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to delete. :type node: :class:`str` or :data:`None` :param redirect_uri: A URI to send to subscribers to indicate a replacement for the deleted node. :type redirect_uri: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service Optionally, a `redirect_uri` can be given. The `redirect_uri` will be sent to subscribers in the message notifying them about the node deletion. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerDelete( node, redirect_uri=redirect_uri ) ) ) yield from self.client.send(iq)
python
def delete(self, jid, node, *, redirect_uri=None): """ Delete an existing node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to delete. :type node: :class:`str` or :data:`None` :param redirect_uri: A URI to send to subscribers to indicate a replacement for the deleted node. :type redirect_uri: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service Optionally, a `redirect_uri` can be given. The `redirect_uri` will be sent to subscribers in the message notifying them about the node deletion. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerDelete( node, redirect_uri=redirect_uri ) ) ) yield from self.client.send(iq)
Delete an existing node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to delete. :type node: :class:`str` or :data:`None` :param redirect_uri: A URI to send to subscribers to indicate a replacement for the deleted node. :type redirect_uri: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service Optionally, a `redirect_uri` can be given. The `redirect_uri` will be sent to subscribers in the message notifying them about the node deletion.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L820-L849
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_nodes
def get_nodes(self, jid, node=None): """ Request all nodes at a service or collection node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the collection node to query :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The list of nodes at the service or collection node. :rtype: :class:`~collections.abc.Sequence` of tuples consisting of the node name and its description. Request the nodes available at `jid`. If `node` is not :data:`None`, the request returns the children of the :xep:`248` collection node `node`. Make sure to check for the appropriate server feature first. Return a list of tuples consisting of the node names and their description (if available, otherwise :data:`None`). If more information is needed, use :meth:`.DiscoClient.get_items` directly. Only nodes whose :attr:`~.disco.xso.Item.jid` match the `jid` are returned. """ response = yield from self._disco.query_items( jid, node=node, ) result = [] for item in response.items: if item.jid != jid: continue result.append(( item.node, item.name, )) return result
python
def get_nodes(self, jid, node=None): """ Request all nodes at a service or collection node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the collection node to query :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The list of nodes at the service or collection node. :rtype: :class:`~collections.abc.Sequence` of tuples consisting of the node name and its description. Request the nodes available at `jid`. If `node` is not :data:`None`, the request returns the children of the :xep:`248` collection node `node`. Make sure to check for the appropriate server feature first. Return a list of tuples consisting of the node names and their description (if available, otherwise :data:`None`). If more information is needed, use :meth:`.DiscoClient.get_items` directly. Only nodes whose :attr:`~.disco.xso.Item.jid` match the `jid` are returned. """ response = yield from self._disco.query_items( jid, node=node, ) result = [] for item in response.items: if item.jid != jid: continue result.append(( item.node, item.name, )) return result
Request all nodes at a service or collection node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the collection node to query :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The list of nodes at the service or collection node. :rtype: :class:`~collections.abc.Sequence` of tuples consisting of the node name and its description. Request the nodes available at `jid`. If `node` is not :data:`None`, the request returns the children of the :xep:`248` collection node `node`. Make sure to check for the appropriate server feature first. Return a list of tuples consisting of the node names and their description (if available, otherwise :data:`None`). If more information is needed, use :meth:`.DiscoClient.get_items` directly. Only nodes whose :attr:`~.disco.xso.Item.jid` match the `jid` are returned.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L852-L891
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.get_node_affiliations
def get_node_affiliations(self, jid, node): """ Return the affiliations of other jids at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to query :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the service. :rtype: :class:`.xso.OwnerRequest` The affiliations are returned as :class:`.xso.OwnerRequest` instance whose :attr:`~.xso.OwnerRequest.payload` is a :class:`.xso.OwnerAffiliations` instance. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.GET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerAffiliations(node), ) ) return (yield from self.client.send(iq))
python
def get_node_affiliations(self, jid, node): """ Return the affiliations of other jids at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to query :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the service. :rtype: :class:`.xso.OwnerRequest` The affiliations are returned as :class:`.xso.OwnerRequest` instance whose :attr:`~.xso.OwnerRequest.payload` is a :class:`.xso.OwnerAffiliations` instance. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.GET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerAffiliations(node), ) ) return (yield from self.client.send(iq))
Return the affiliations of other jids at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to query :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the service. :rtype: :class:`.xso.OwnerRequest` The affiliations are returned as :class:`.xso.OwnerRequest` instance whose :attr:`~.xso.OwnerRequest.payload` is a :class:`.xso.OwnerAffiliations` instance.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L894-L918
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.change_node_affiliations
def change_node_affiliations(self, jid, node, affiliations_to_set): """ Update the affiliations at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param affiliations_to_set: The affiliations to set at the node. :type affiliations_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to affiliate and the affiliation to use. :raises aioxmpp.errors.XMPPError: as returned by the service `affiliations_to_set` must be an iterable of pairs (`jid`, `affiliation`), where the `jid` indicates the JID for which the `affiliation` is to be set. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerAffiliations( node, affiliations=[ pubsub_xso.OwnerAffiliation( jid, affiliation ) for jid, affiliation in affiliations_to_set ] ) ) ) yield from self.client.send(iq)
python
def change_node_affiliations(self, jid, node, affiliations_to_set): """ Update the affiliations at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param affiliations_to_set: The affiliations to set at the node. :type affiliations_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to affiliate and the affiliation to use. :raises aioxmpp.errors.XMPPError: as returned by the service `affiliations_to_set` must be an iterable of pairs (`jid`, `affiliation`), where the `jid` indicates the JID for which the `affiliation` is to be set. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerAffiliations( node, affiliations=[ pubsub_xso.OwnerAffiliation( jid, affiliation ) for jid, affiliation in affiliations_to_set ] ) ) ) yield from self.client.send(iq)
Update the affiliations at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param affiliations_to_set: The affiliations to set at the node. :type affiliations_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to affiliate and the affiliation to use. :raises aioxmpp.errors.XMPPError: as returned by the service `affiliations_to_set` must be an iterable of pairs (`jid`, `affiliation`), where the `jid` indicates the JID for which the `affiliation` is to be set.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L948-L982
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.change_node_subscriptions
def change_node_subscriptions(self, jid, node, subscriptions_to_set): """ Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscriptions_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to (un)subscribe and the subscription level to use. :raises aioxmpp.errors.XMPPError: as returned by the service `subscriptions_to_set` must be an iterable of pairs (`jid`, `subscription`), where the `jid` indicates the JID for which the `subscription` is to be set. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerSubscriptions( node, subscriptions=[ pubsub_xso.OwnerSubscription( jid, subscription ) for jid, subscription in subscriptions_to_set ] ) ) ) yield from self.client.send(iq)
python
def change_node_subscriptions(self, jid, node, subscriptions_to_set): """ Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscriptions_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to (un)subscribe and the subscription level to use. :raises aioxmpp.errors.XMPPError: as returned by the service `subscriptions_to_set` must be an iterable of pairs (`jid`, `subscription`), where the `jid` indicates the JID for which the `subscription` is to be set. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerSubscriptions( node, subscriptions=[ pubsub_xso.OwnerSubscription( jid, subscription ) for jid, subscription in subscriptions_to_set ] ) ) ) yield from self.client.send(iq)
Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscriptions_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to (un)subscribe and the subscription level to use. :raises aioxmpp.errors.XMPPError: as returned by the service `subscriptions_to_set` must be an iterable of pairs (`jid`, `subscription`), where the `jid` indicates the JID for which the `subscription` is to be set.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L985-L1020
horazont/aioxmpp
aioxmpp/pubsub/service.py
PubSubClient.purge
def purge(self, jid, node): """ Delete all items from a node. :param jid: JID of the PubSub service :param node: Name of the PubSub node :type node: :class:`str` Requires :attr:`.xso.Feature.PURGE`. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerPurge( node ) ) ) yield from self.client.send(iq)
python
def purge(self, jid, node): """ Delete all items from a node. :param jid: JID of the PubSub service :param node: Name of the PubSub node :type node: :class:`str` Requires :attr:`.xso.Feature.PURGE`. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerPurge( node ) ) ) yield from self.client.send(iq)
Delete all items from a node. :param jid: JID of the PubSub service :param node: Name of the PubSub node :type node: :class:`str` Requires :attr:`.xso.Feature.PURGE`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L1023-L1044
horazont/aioxmpp
aioxmpp/xso/model.py
capture_events
def capture_events(receiver, dest): """ Capture all events sent to `receiver` in the sequence `dest`. This is a generator, and it is best used with ``yield from``. The observable effect of using this generator with ``yield from`` is identical to the effect of using `receiver` with ``yield from`` directly (including the return value), but in addition, the values which are *sent* to the receiver are captured in `dest`. If `receiver` raises an exception or the generator is closed prematurely using its :meth:`close`, `dest` is cleared. This is used to implement :class:`CapturingXSO`. See the documentation there for use cases. .. versionadded:: 0.5 """ # the following code is a copy of the formal definition of `yield from` # in PEP 380, with modifications to capture the value sent during yield _i = iter(receiver) try: _y = next(_i) except StopIteration as _e: return _e.value try: while True: try: _s = yield _y except GeneratorExit as _e: try: _m = _i.close except AttributeError: pass else: _m() raise _e except BaseException as _e: _x = sys.exc_info() try: _m = _i.throw except AttributeError: raise _e else: try: _y = _m(*_x) except StopIteration as _e: _r = _e.value break else: dest.append(_s) try: if _s is None: _y = next(_i) else: _y = _i.send(_s) except StopIteration as _e: _r = _e.value break except: # NOQA dest.clear() raise return _r
python
def capture_events(receiver, dest): """ Capture all events sent to `receiver` in the sequence `dest`. This is a generator, and it is best used with ``yield from``. The observable effect of using this generator with ``yield from`` is identical to the effect of using `receiver` with ``yield from`` directly (including the return value), but in addition, the values which are *sent* to the receiver are captured in `dest`. If `receiver` raises an exception or the generator is closed prematurely using its :meth:`close`, `dest` is cleared. This is used to implement :class:`CapturingXSO`. See the documentation there for use cases. .. versionadded:: 0.5 """ # the following code is a copy of the formal definition of `yield from` # in PEP 380, with modifications to capture the value sent during yield _i = iter(receiver) try: _y = next(_i) except StopIteration as _e: return _e.value try: while True: try: _s = yield _y except GeneratorExit as _e: try: _m = _i.close except AttributeError: pass else: _m() raise _e except BaseException as _e: _x = sys.exc_info() try: _m = _i.throw except AttributeError: raise _e else: try: _y = _m(*_x) except StopIteration as _e: _r = _e.value break else: dest.append(_s) try: if _s is None: _y = next(_i) else: _y = _i.send(_s) except StopIteration as _e: _r = _e.value break except: # NOQA dest.clear() raise return _r
Capture all events sent to `receiver` in the sequence `dest`. This is a generator, and it is best used with ``yield from``. The observable effect of using this generator with ``yield from`` is identical to the effect of using `receiver` with ``yield from`` directly (including the return value), but in addition, the values which are *sent* to the receiver are captured in `dest`. If `receiver` raises an exception or the generator is closed prematurely using its :meth:`close`, `dest` is cleared. This is used to implement :class:`CapturingXSO`. See the documentation there for use cases. .. versionadded:: 0.5
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L2616-L2678
horazont/aioxmpp
aioxmpp/xso/model.py
events_to_sax
def events_to_sax(events, dest): """ Convert an iterable `events` of XSO events to SAX events by calling the matching SAX methods on `dest` """ name_stack = [] for ev_type, *ev_args in events: if ev_type == "start": name = (ev_args[0], ev_args[1]) dest.startElementNS(name, None, ev_args[2]) name_stack.append(name) elif ev_type == "end": name = name_stack.pop() dest.endElementNS(name, None) elif ev_type == "text": dest.characters(ev_args[0])
python
def events_to_sax(events, dest): """ Convert an iterable `events` of XSO events to SAX events by calling the matching SAX methods on `dest` """ name_stack = [] for ev_type, *ev_args in events: if ev_type == "start": name = (ev_args[0], ev_args[1]) dest.startElementNS(name, None, ev_args[2]) name_stack.append(name) elif ev_type == "end": name = name_stack.pop() dest.endElementNS(name, None) elif ev_type == "text": dest.characters(ev_args[0])
Convert an iterable `events` of XSO events to SAX events by calling the matching SAX methods on `dest`
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L2681-L2697
horazont/aioxmpp
aioxmpp/xso/model.py
XSOList.filter
def filter(self, *, type_=None, lang=None, attrs={}): """ Return an iterable which produces a sequence of the elements inside this :class:`XSOList`, filtered by the criteria given as arguments. The function starts with a working sequence consisting of the whole list. If `type_` is not :data:`None`, elements which are not an instance of the given type are excluded from the working sequence. If `lang` is not :data:`None`, it must be either a :class:`~.structs.LanguageRange` or an iterable of language ranges. The set of languages present among the working sequence is determined and used for a call to :class:`~.structs.lookup_language`. If the lookup returns a language, all elements whose :attr:`lang` is different from that value are excluded from the working sequence. .. note:: If an iterable of language ranges is given, it is evaluated into a list. This may be of concern if a huge iterable is about to be used for language ranges, but it is an requirement of the :class:`~.structs.lookup_language` function which is used under the hood. .. note:: Filtering by language assumes that the elements have a :class:`~aioxmpp.xso.LangAttr` descriptor named ``lang``. If `attrs` is not empty, the filter iterates over each `key`-`value` pair. For each iteration, all elements which do not have an attribute of the name in `key` or where that attribute has a value not equal to `value` are excluded from the working sequence. In general, the iterable returned from :meth:`filter` can only be used once. It is dynamic in the sense that changes to elements which are in the list *behind* the last element returned from the iterator will still be picked up when the iterator is resumed. """ result = self if type_ is not None: result = self._filter_type(result, type_) if lang is not None: result = self._filter_lang(result, lang) if attrs: result = self._filter_attrs(result, attrs) return result
python
def filter(self, *, type_=None, lang=None, attrs={}): """ Return an iterable which produces a sequence of the elements inside this :class:`XSOList`, filtered by the criteria given as arguments. The function starts with a working sequence consisting of the whole list. If `type_` is not :data:`None`, elements which are not an instance of the given type are excluded from the working sequence. If `lang` is not :data:`None`, it must be either a :class:`~.structs.LanguageRange` or an iterable of language ranges. The set of languages present among the working sequence is determined and used for a call to :class:`~.structs.lookup_language`. If the lookup returns a language, all elements whose :attr:`lang` is different from that value are excluded from the working sequence. .. note:: If an iterable of language ranges is given, it is evaluated into a list. This may be of concern if a huge iterable is about to be used for language ranges, but it is an requirement of the :class:`~.structs.lookup_language` function which is used under the hood. .. note:: Filtering by language assumes that the elements have a :class:`~aioxmpp.xso.LangAttr` descriptor named ``lang``. If `attrs` is not empty, the filter iterates over each `key`-`value` pair. For each iteration, all elements which do not have an attribute of the name in `key` or where that attribute has a value not equal to `value` are excluded from the working sequence. In general, the iterable returned from :meth:`filter` can only be used once. It is dynamic in the sense that changes to elements which are in the list *behind* the last element returned from the iterator will still be picked up when the iterator is resumed. """ result = self if type_ is not None: result = self._filter_type(result, type_) if lang is not None: result = self._filter_lang(result, lang) if attrs: result = self._filter_attrs(result, attrs) return result
Return an iterable which produces a sequence of the elements inside this :class:`XSOList`, filtered by the criteria given as arguments. The function starts with a working sequence consisting of the whole list. If `type_` is not :data:`None`, elements which are not an instance of the given type are excluded from the working sequence. If `lang` is not :data:`None`, it must be either a :class:`~.structs.LanguageRange` or an iterable of language ranges. The set of languages present among the working sequence is determined and used for a call to :class:`~.structs.lookup_language`. If the lookup returns a language, all elements whose :attr:`lang` is different from that value are excluded from the working sequence. .. note:: If an iterable of language ranges is given, it is evaluated into a list. This may be of concern if a huge iterable is about to be used for language ranges, but it is an requirement of the :class:`~.structs.lookup_language` function which is used under the hood. .. note:: Filtering by language assumes that the elements have a :class:`~aioxmpp.xso.LangAttr` descriptor named ``lang``. If `attrs` is not empty, the filter iterates over each `key`-`value` pair. For each iteration, all elements which do not have an attribute of the name in `key` or where that attribute has a value not equal to `value` are excluded from the working sequence. In general, the iterable returned from :meth:`filter` can only be used once. It is dynamic in the sense that changes to elements which are in the list *behind* the last element returned from the iterator will still be picked up when the iterator is resumed.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L213-L260
horazont/aioxmpp
aioxmpp/xso/model.py
XSOList.filtered
def filtered(self, *, type_=None, lang=None, attrs={}): """ This method is a convencience wrapper around :meth:`filter` which evaluates the result into a list and returns that list. """ return list(self.filter(type_=type_, lang=lang, attrs=attrs))
python
def filtered(self, *, type_=None, lang=None, attrs={}): """ This method is a convencience wrapper around :meth:`filter` which evaluates the result into a list and returns that list. """ return list(self.filter(type_=type_, lang=lang, attrs=attrs))
This method is a convencience wrapper around :meth:`filter` which evaluates the result into a list and returns that list.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L262-L267
horazont/aioxmpp
aioxmpp/xso/model.py
Text.from_value
def from_value(self, instance, value): """ Convert the given value using the set `type_` and store it into `instance`’ attribute. """ try: parsed = self.type_.parse(value) except (TypeError, ValueError): if self.erroneous_as_absent: return False raise self._set_from_recv(instance, parsed) return True
python
def from_value(self, instance, value): """ Convert the given value using the set `type_` and store it into `instance`’ attribute. """ try: parsed = self.type_.parse(value) except (TypeError, ValueError): if self.erroneous_as_absent: return False raise self._set_from_recv(instance, parsed) return True
Convert the given value using the set `type_` and store it into `instance`’ attribute.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L403-L415
horazont/aioxmpp
aioxmpp/xso/model.py
Text.to_sax
def to_sax(self, instance, dest): """ Assign the formatted value stored at `instance`’ attribute to the text of `el`. If the `value` is :data:`None`, no text is generated. """ value = self.__get__(instance, type(instance)) if value is None: return dest.characters(self.type_.format(value))
python
def to_sax(self, instance, dest): """ Assign the formatted value stored at `instance`’ attribute to the text of `el`. If the `value` is :data:`None`, no text is generated. """ value = self.__get__(instance, type(instance)) if value is None: return dest.characters(self.type_.format(value))
Assign the formatted value stored at `instance`’ attribute to the text of `el`. If the `value` is :data:`None`, no text is generated.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L417-L427
horazont/aioxmpp
aioxmpp/xso/model.py
Child.from_events
def from_events(self, instance, ev_args, ctx): """ Detect the object to instanciate from the arguments `ev_args` of the ``"start"`` event. The new object is stored at the corresponding descriptor attribute on `instance`. This method is suspendable. """ obj = yield from self._process(instance, ev_args, ctx) self.__set__(instance, obj) return obj
python
def from_events(self, instance, ev_args, ctx): """ Detect the object to instanciate from the arguments `ev_args` of the ``"start"`` event. The new object is stored at the corresponding descriptor attribute on `instance`. This method is suspendable. """ obj = yield from self._process(instance, ev_args, ctx) self.__set__(instance, obj) return obj
Detect the object to instanciate from the arguments `ev_args` of the ``"start"`` event. The new object is stored at the corresponding descriptor attribute on `instance`. This method is suspendable.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L556-L566
horazont/aioxmpp
aioxmpp/xso/model.py
Child.to_sax
def to_sax(self, instance, dest): """ Take the object associated with this descriptor on `instance` and serialize it as child into the given :class:`lxml.etree.Element` `parent`. If the object is :data:`None`, no content is generated. """ obj = self.__get__(instance, type(instance)) if obj is None: return obj.unparse_to_sax(dest)
python
def to_sax(self, instance, dest): """ Take the object associated with this descriptor on `instance` and serialize it as child into the given :class:`lxml.etree.Element` `parent`. If the object is :data:`None`, no content is generated. """ obj = self.__get__(instance, type(instance)) if obj is None: return obj.unparse_to_sax(dest)
Take the object associated with this descriptor on `instance` and serialize it as child into the given :class:`lxml.etree.Element` `parent`. If the object is :data:`None`, no content is generated.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L576-L587
horazont/aioxmpp
aioxmpp/xso/model.py
ChildList.from_events
def from_events(self, instance, ev_args, ctx): """ Like :meth:`.Child.from_events`, but instead of replacing the attribute value, the new object is appended to the list. """ obj = yield from self._process(instance, ev_args, ctx) self.__get__(instance, type(instance)).append(obj) return obj
python
def from_events(self, instance, ev_args, ctx): """ Like :meth:`.Child.from_events`, but instead of replacing the attribute value, the new object is appended to the list. """ obj = yield from self._process(instance, ev_args, ctx) self.__get__(instance, type(instance)).append(obj) return obj
Like :meth:`.Child.from_events`, but instead of replacing the attribute value, the new object is appended to the list.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L622-L630
horazont/aioxmpp
aioxmpp/xso/model.py
Collector.from_events
def from_events(self, instance, ev_args, ctx): """ Collect the events and convert them to a single XML subtree, which then gets appended to the list at `instance`. `ev_args` must be the arguments of the ``"start"`` event of the new child. This method is suspendable. """ # goal: collect all elements starting with the element for which we got # the start-ev_args in a lxml.etree.Element. def make_from_args(ev_args, parent): el = etree.SubElement(parent, tag_to_str((ev_args[0], ev_args[1]))) for key, value in ev_args[2].items(): el.set(tag_to_str(key), value) return el root_el = make_from_args(ev_args, self.__get__(instance, type(instance))) # create an element stack stack = [root_el] while stack: # we get send all sax-ish events until we return. we return when # the stack is empty, i.e. when our top element ended. ev_type, *ev_args = yield if ev_type == "start": # new element started, create and push to stack stack.append(make_from_args(ev_args, stack[-1])) elif ev_type == "text": # text for current element curr = stack[-1] if curr.text is not None: curr.text += ev_args[0] else: curr.text = ev_args[0] elif ev_type == "end": # element ended, remove from stack (it is already appended to # the current element) stack.pop() else: # not in coverage -- this is more like an assertion raise ValueError(ev_type)
python
def from_events(self, instance, ev_args, ctx): """ Collect the events and convert them to a single XML subtree, which then gets appended to the list at `instance`. `ev_args` must be the arguments of the ``"start"`` event of the new child. This method is suspendable. """ # goal: collect all elements starting with the element for which we got # the start-ev_args in a lxml.etree.Element. def make_from_args(ev_args, parent): el = etree.SubElement(parent, tag_to_str((ev_args[0], ev_args[1]))) for key, value in ev_args[2].items(): el.set(tag_to_str(key), value) return el root_el = make_from_args(ev_args, self.__get__(instance, type(instance))) # create an element stack stack = [root_el] while stack: # we get send all sax-ish events until we return. we return when # the stack is empty, i.e. when our top element ended. ev_type, *ev_args = yield if ev_type == "start": # new element started, create and push to stack stack.append(make_from_args(ev_args, stack[-1])) elif ev_type == "text": # text for current element curr = stack[-1] if curr.text is not None: curr.text += ev_args[0] else: curr.text = ev_args[0] elif ev_type == "end": # element ended, remove from stack (it is already appended to # the current element) stack.pop() else: # not in coverage -- this is more like an assertion raise ValueError(ev_type)
Collect the events and convert them to a single XML subtree, which then gets appended to the list at `instance`. `ev_args` must be the arguments of the ``"start"`` event of the new child. This method is suspendable.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L687-L730
horazont/aioxmpp
aioxmpp/xso/model.py
Attr.handle_missing
def handle_missing(self, instance, ctx): """ Handle a missing attribute on `instance`. This is called whenever no value for the attribute is found during parsing. The call to :meth:`missing` is independent of the value of `required`. If the `missing` callback is not :data:`None`, it is called with the `instance` and the `ctx` as arguments. If the returned value is not :data:`None`, it is used as the value of the attribute (validation takes place as if the value had been set from the code, not as if the value had been received from XML) and the handler returns. If the `missing` callback is :data:`None` or returns :data:`None`, the handling continues as normal: if `required` is true, a :class:`ValueError` is raised. """ if self.missing is not None: value = self.missing(instance, ctx) if value is not None: self._set_from_code(instance, value) return if self.default is _PropBase.NO_DEFAULT: raise ValueError("missing attribute {} on {}".format( tag_to_str(self.tag), tag_to_str(instance.TAG), ))
python
def handle_missing(self, instance, ctx): """ Handle a missing attribute on `instance`. This is called whenever no value for the attribute is found during parsing. The call to :meth:`missing` is independent of the value of `required`. If the `missing` callback is not :data:`None`, it is called with the `instance` and the `ctx` as arguments. If the returned value is not :data:`None`, it is used as the value of the attribute (validation takes place as if the value had been set from the code, not as if the value had been received from XML) and the handler returns. If the `missing` callback is :data:`None` or returns :data:`None`, the handling continues as normal: if `required` is true, a :class:`ValueError` is raised. """ if self.missing is not None: value = self.missing(instance, ctx) if value is not None: self._set_from_code(instance, value) return if self.default is _PropBase.NO_DEFAULT: raise ValueError("missing attribute {} on {}".format( tag_to_str(self.tag), tag_to_str(instance.TAG), ))
Handle a missing attribute on `instance`. This is called whenever no value for the attribute is found during parsing. The call to :meth:`missing` is independent of the value of `required`. If the `missing` callback is not :data:`None`, it is called with the `instance` and the `ctx` as arguments. If the returned value is not :data:`None`, it is used as the value of the attribute (validation takes place as if the value had been set from the code, not as if the value had been received from XML) and the handler returns. If the `missing` callback is :data:`None` or returns :data:`None`, the handling continues as normal: if `required` is true, a :class:`ValueError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L812-L838
horazont/aioxmpp
aioxmpp/xso/model.py
Attr.to_dict
def to_dict(self, instance, d): """ Override the implementation from :class:`Text` by storing the formatted value in the XML attribute instead of the character data. If the value is :data:`None`, no element is generated. """ value = self.__get__(instance, type(instance)) if value == self.default: return d[self.tag] = self.type_.format(value)
python
def to_dict(self, instance, d): """ Override the implementation from :class:`Text` by storing the formatted value in the XML attribute instead of the character data. If the value is :data:`None`, no element is generated. """ value = self.__get__(instance, type(instance)) if value == self.default: return d[self.tag] = self.type_.format(value)
Override the implementation from :class:`Text` by storing the formatted value in the XML attribute instead of the character data. If the value is :data:`None`, no element is generated.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L850-L862
horazont/aioxmpp
aioxmpp/xso/model.py
ChildText.from_events
def from_events(self, instance, ev_args, ctx): """ Starting with the element to which the start event information in `ev_args` belongs, parse text data. If any children are encountered, :attr:`child_policy` is enforced (see :class:`UnknownChildPolicy`). Likewise, if the start event contains attributes, :attr:`attr_policy` is enforced (c.f. :class:`UnknownAttrPolicy`). The extracted text is passed through :attr:`type_` and :attr:`validator` and if it passes, stored in the attribute on the `instance` with which the property is associated. This method is suspendable. """ # goal: take all text inside the child element and collect it as # attribute value attrs = ev_args[2] if attrs and self.attr_policy == UnknownAttrPolicy.FAIL: raise ValueError("unexpected attribute (at text only node)") parts = [] while True: ev_type, *ev_args = yield if ev_type == "text": # collect ALL TEH TEXT! parts.append(ev_args[0]) elif ev_type == "start": # ok, a child inside the child was found, we look at our policy # to see what to do yield from enforce_unknown_child_policy( self.child_policy, ev_args) elif ev_type == "end": # end of our element, return break joined = "".join(parts) try: parsed = self.type_.parse(joined) except (ValueError, TypeError): if self.erroneous_as_absent: return raise self._set_from_recv(instance, parsed)
python
def from_events(self, instance, ev_args, ctx): """ Starting with the element to which the start event information in `ev_args` belongs, parse text data. If any children are encountered, :attr:`child_policy` is enforced (see :class:`UnknownChildPolicy`). Likewise, if the start event contains attributes, :attr:`attr_policy` is enforced (c.f. :class:`UnknownAttrPolicy`). The extracted text is passed through :attr:`type_` and :attr:`validator` and if it passes, stored in the attribute on the `instance` with which the property is associated. This method is suspendable. """ # goal: take all text inside the child element and collect it as # attribute value attrs = ev_args[2] if attrs and self.attr_policy == UnknownAttrPolicy.FAIL: raise ValueError("unexpected attribute (at text only node)") parts = [] while True: ev_type, *ev_args = yield if ev_type == "text": # collect ALL TEH TEXT! parts.append(ev_args[0]) elif ev_type == "start": # ok, a child inside the child was found, we look at our policy # to see what to do yield from enforce_unknown_child_policy( self.child_policy, ev_args) elif ev_type == "end": # end of our element, return break joined = "".join(parts) try: parsed = self.type_.parse(joined) except (ValueError, TypeError): if self.erroneous_as_absent: return raise self._set_from_recv(instance, parsed)
Starting with the element to which the start event information in `ev_args` belongs, parse text data. If any children are encountered, :attr:`child_policy` is enforced (see :class:`UnknownChildPolicy`). Likewise, if the start event contains attributes, :attr:`attr_policy` is enforced (c.f. :class:`UnknownAttrPolicy`). The extracted text is passed through :attr:`type_` and :attr:`validator` and if it passes, stored in the attribute on the `instance` with which the property is associated. This method is suspendable.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L943-L988
horazont/aioxmpp
aioxmpp/xso/model.py
ChildText.to_sax
def to_sax(self, instance, dest): """ Create a child node at `parent` with the tag :attr:`tag`. Set the text contents to the value of the attribute which this descriptor represents at `instance`. If the value is :data:`None`, no element is generated. """ value = self.__get__(instance, type(instance)) if value == self.default: return if self.declare_prefix is not False and self.tag[0]: dest.startPrefixMapping(self.declare_prefix, self.tag[0]) dest.startElementNS(self.tag, None, {}) try: dest.characters(self.type_.format(value)) finally: dest.endElementNS(self.tag, None) if self.declare_prefix is not False and self.tag[0]: dest.endPrefixMapping(self.declare_prefix)
python
def to_sax(self, instance, dest): """ Create a child node at `parent` with the tag :attr:`tag`. Set the text contents to the value of the attribute which this descriptor represents at `instance`. If the value is :data:`None`, no element is generated. """ value = self.__get__(instance, type(instance)) if value == self.default: return if self.declare_prefix is not False and self.tag[0]: dest.startPrefixMapping(self.declare_prefix, self.tag[0]) dest.startElementNS(self.tag, None, {}) try: dest.characters(self.type_.format(value)) finally: dest.endElementNS(self.tag, None) if self.declare_prefix is not False and self.tag[0]: dest.endPrefixMapping(self.declare_prefix)
Create a child node at `parent` with the tag :attr:`tag`. Set the text contents to the value of the attribute which this descriptor represents at `instance`. If the value is :data:`None`, no element is generated.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L990-L1011
horazont/aioxmpp
aioxmpp/xso/model.py
ChildMap.fill_into_dict
def fill_into_dict(self, items, dest): """ Take an iterable of `items` and group it into the given `dest` dict, using the :attr:`key` function. The `dest` dict must either already contain the keys which are generated by the :attr:`key` function for the items in `items`, or must default them suitably. The values of the affected keys must be sequences or objects with an :meth:`append` method which does what you want it to do. """ for item in items: dest[self.key(item)].append(item)
python
def fill_into_dict(self, items, dest): """ Take an iterable of `items` and group it into the given `dest` dict, using the :attr:`key` function. The `dest` dict must either already contain the keys which are generated by the :attr:`key` function for the items in `items`, or must default them suitably. The values of the affected keys must be sequences or objects with an :meth:`append` method which does what you want it to do. """ for item in items: dest[self.key(item)].append(item)
Take an iterable of `items` and group it into the given `dest` dict, using the :attr:`key` function. The `dest` dict must either already contain the keys which are generated by the :attr:`key` function for the items in `items`, or must default them suitably. The values of the affected keys must be sequences or objects with an :meth:`append` method which does what you want it to do.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L1063-L1075
horazont/aioxmpp
aioxmpp/xso/model.py
ChildMap.from_events
def from_events(self, instance, ev_args, ctx): """ Like :meth:`.ChildList.from_events`, but the object is appended to the list associated with its tag in the dict. """ tag = ev_args[0], ev_args[1] cls = self._tag_map[tag] obj = yield from cls.parse_events(ev_args, ctx) mapping = self.__get__(instance, type(instance)) mapping[self.key(obj)].append(obj)
python
def from_events(self, instance, ev_args, ctx): """ Like :meth:`.ChildList.from_events`, but the object is appended to the list associated with its tag in the dict. """ tag = ev_args[0], ev_args[1] cls = self._tag_map[tag] obj = yield from cls.parse_events(ev_args, ctx) mapping = self.__get__(instance, type(instance)) mapping[self.key(obj)].append(obj)
Like :meth:`.ChildList.from_events`, but the object is appended to the list associated with its tag in the dict.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L1077-L1087
horazont/aioxmpp
aioxmpp/xso/model.py
XMLStreamClass.parse_events
def parse_events(cls, ev_args, parent_ctx): """ Create an instance of this class, using the events sent into this function. `ev_args` must be the event arguments of the ``"start"`` event. .. seealso:: You probably should not call this method directly, but instead use :class:`XSOParser` with a :class:`SAXDriver`. .. note:: While this method creates an instance of the class, ``__init__`` is not called. See the documentation of :meth:`.xso.XSO` for details. This method is suspendable. """ with parent_ctx as ctx: obj = cls.__new__(cls) attrs = ev_args[2] attr_map = cls.ATTR_MAP.copy() for key, value in attrs.items(): try: prop = attr_map.pop(key) except KeyError: if cls.UNKNOWN_ATTR_POLICY == UnknownAttrPolicy.DROP: continue else: raise ValueError( "unexpected attribute {!r} on {}".format( key, tag_to_str((ev_args[0], ev_args[1])) )) from None try: if not prop.from_value(obj, value): # assignment failed due to recoverable error, treat as # absent attr_map[key] = prop except Exception: prop.mark_incomplete(obj) _mark_attributes_incomplete(attr_map.values(), obj) logger.debug("while parsing XSO %s (%r)", cls, value, exc_info=True) # true means suppress if not obj.xso_error_handler( prop, value, sys.exc_info()): raise for key, prop in attr_map.items(): try: prop.handle_missing(obj, ctx) except Exception: logger.debug("while parsing XSO %s", cls, exc_info=True) # true means suppress if not obj.xso_error_handler( prop, None, sys.exc_info()): raise try: prop = cls.ATTR_MAP[namespaces.xml, "lang"] except KeyError: pass else: lang = prop.__get__(obj, cls) if lang is not None: ctx.lang = lang collected_text = [] while True: ev_type, *ev_args = yield if ev_type == "end": break elif ev_type == "text": if not cls.TEXT_PROPERTY: if ev_args[0].strip(): # true means suppress if not obj.xso_error_handler( None, ev_args[0], None): raise ValueError("unexpected text") else: collected_text.append(ev_args[0]) elif ev_type == "start": try: handler = cls.CHILD_MAP[ev_args[0], ev_args[1]] except KeyError: if cls.COLLECTOR_PROPERTY: handler = cls.COLLECTOR_PROPERTY.xq_descriptor else: yield from enforce_unknown_child_policy( cls.UNKNOWN_CHILD_POLICY, ev_args, obj.xso_error_handler) continue try: yield from guard( handler.from_events(obj, ev_args, ctx), ev_args ) except Exception: logger.debug("while parsing XSO %s", type(obj), exc_info=True) # true means suppress if not obj.xso_error_handler( handler, ev_args, sys.exc_info()): raise if collected_text: collected_text = "".join(collected_text) try: cls.TEXT_PROPERTY.xq_descriptor.from_value( obj, collected_text ) except Exception: logger.debug("while parsing XSO", exc_info=True) # true means suppress if not obj.xso_error_handler( cls.TEXT_PROPERTY.xq_descriptor, collected_text, sys.exc_info()): raise obj.validate() obj.xso_after_load() return obj
python
def parse_events(cls, ev_args, parent_ctx): """ Create an instance of this class, using the events sent into this function. `ev_args` must be the event arguments of the ``"start"`` event. .. seealso:: You probably should not call this method directly, but instead use :class:`XSOParser` with a :class:`SAXDriver`. .. note:: While this method creates an instance of the class, ``__init__`` is not called. See the documentation of :meth:`.xso.XSO` for details. This method is suspendable. """ with parent_ctx as ctx: obj = cls.__new__(cls) attrs = ev_args[2] attr_map = cls.ATTR_MAP.copy() for key, value in attrs.items(): try: prop = attr_map.pop(key) except KeyError: if cls.UNKNOWN_ATTR_POLICY == UnknownAttrPolicy.DROP: continue else: raise ValueError( "unexpected attribute {!r} on {}".format( key, tag_to_str((ev_args[0], ev_args[1])) )) from None try: if not prop.from_value(obj, value): # assignment failed due to recoverable error, treat as # absent attr_map[key] = prop except Exception: prop.mark_incomplete(obj) _mark_attributes_incomplete(attr_map.values(), obj) logger.debug("while parsing XSO %s (%r)", cls, value, exc_info=True) # true means suppress if not obj.xso_error_handler( prop, value, sys.exc_info()): raise for key, prop in attr_map.items(): try: prop.handle_missing(obj, ctx) except Exception: logger.debug("while parsing XSO %s", cls, exc_info=True) # true means suppress if not obj.xso_error_handler( prop, None, sys.exc_info()): raise try: prop = cls.ATTR_MAP[namespaces.xml, "lang"] except KeyError: pass else: lang = prop.__get__(obj, cls) if lang is not None: ctx.lang = lang collected_text = [] while True: ev_type, *ev_args = yield if ev_type == "end": break elif ev_type == "text": if not cls.TEXT_PROPERTY: if ev_args[0].strip(): # true means suppress if not obj.xso_error_handler( None, ev_args[0], None): raise ValueError("unexpected text") else: collected_text.append(ev_args[0]) elif ev_type == "start": try: handler = cls.CHILD_MAP[ev_args[0], ev_args[1]] except KeyError: if cls.COLLECTOR_PROPERTY: handler = cls.COLLECTOR_PROPERTY.xq_descriptor else: yield from enforce_unknown_child_policy( cls.UNKNOWN_CHILD_POLICY, ev_args, obj.xso_error_handler) continue try: yield from guard( handler.from_events(obj, ev_args, ctx), ev_args ) except Exception: logger.debug("while parsing XSO %s", type(obj), exc_info=True) # true means suppress if not obj.xso_error_handler( handler, ev_args, sys.exc_info()): raise if collected_text: collected_text = "".join(collected_text) try: cls.TEXT_PROPERTY.xq_descriptor.from_value( obj, collected_text ) except Exception: logger.debug("while parsing XSO", exc_info=True) # true means suppress if not obj.xso_error_handler( cls.TEXT_PROPERTY.xq_descriptor, collected_text, sys.exc_info()): raise obj.validate() obj.xso_after_load() return obj
Create an instance of this class, using the events sent into this function. `ev_args` must be the event arguments of the ``"start"`` event. .. seealso:: You probably should not call this method directly, but instead use :class:`XSOParser` with a :class:`SAXDriver`. .. note:: While this method creates an instance of the class, ``__init__`` is not called. See the documentation of :meth:`.xso.XSO` for details. This method is suspendable.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L1863-L2000
horazont/aioxmpp
aioxmpp/xso/model.py
XMLStreamClass.register_child
def register_child(cls, prop, child_cls): """ Register a new :class:`XMLStreamClass` instance `child_cls` for a given :class:`Child` descriptor `prop`. .. warning:: This method cannot be used after a class has been derived from this class. This is for consistency: the method modifies the bookkeeping attributes of the class. There would be two ways to deal with the situation: 1. Updating all the attributes at all the subclasses and re-evaluate the constraints of inheritance. This is simply not implemented, although it would be the preferred way. 2. Only update the bookkeeping attributes on *this* class, hiding the change from any existing subclasses. New subclasses would pick the change up, however, which is inconsistent. This is the way which was previously documented here and is not supported anymore. Obviously, (2) is bad, which is why it is not supported anymore. (1) might be supported at some point in the future. Attempting to use :meth:`register_child` on a class which already has subclasses results in a :class:`TypeError`. Note that *first* using :meth:`register_child` and only *then* deriving clasess is a valid use: it will still lead to a consistent inheritance hierarchy and is a convenient way to break reference cycles (e.g. if an XSO may be its own child). """ if cls.__subclasses__(): raise TypeError( "register_child is forbidden on classes with subclasses" " (subclasses: {})".format( ", ".join(map(str, cls.__subclasses__())) )) if child_cls.TAG in cls.CHILD_MAP: raise ValueError("ambiguous Child") prop.xq_descriptor._register(child_cls) cls.CHILD_MAP[child_cls.TAG] = prop.xq_descriptor
python
def register_child(cls, prop, child_cls): """ Register a new :class:`XMLStreamClass` instance `child_cls` for a given :class:`Child` descriptor `prop`. .. warning:: This method cannot be used after a class has been derived from this class. This is for consistency: the method modifies the bookkeeping attributes of the class. There would be two ways to deal with the situation: 1. Updating all the attributes at all the subclasses and re-evaluate the constraints of inheritance. This is simply not implemented, although it would be the preferred way. 2. Only update the bookkeeping attributes on *this* class, hiding the change from any existing subclasses. New subclasses would pick the change up, however, which is inconsistent. This is the way which was previously documented here and is not supported anymore. Obviously, (2) is bad, which is why it is not supported anymore. (1) might be supported at some point in the future. Attempting to use :meth:`register_child` on a class which already has subclasses results in a :class:`TypeError`. Note that *first* using :meth:`register_child` and only *then* deriving clasess is a valid use: it will still lead to a consistent inheritance hierarchy and is a convenient way to break reference cycles (e.g. if an XSO may be its own child). """ if cls.__subclasses__(): raise TypeError( "register_child is forbidden on classes with subclasses" " (subclasses: {})".format( ", ".join(map(str, cls.__subclasses__())) )) if child_cls.TAG in cls.CHILD_MAP: raise ValueError("ambiguous Child") prop.xq_descriptor._register(child_cls) cls.CHILD_MAP[child_cls.TAG] = prop.xq_descriptor
Register a new :class:`XMLStreamClass` instance `child_cls` for a given :class:`Child` descriptor `prop`. .. warning:: This method cannot be used after a class has been derived from this class. This is for consistency: the method modifies the bookkeeping attributes of the class. There would be two ways to deal with the situation: 1. Updating all the attributes at all the subclasses and re-evaluate the constraints of inheritance. This is simply not implemented, although it would be the preferred way. 2. Only update the bookkeeping attributes on *this* class, hiding the change from any existing subclasses. New subclasses would pick the change up, however, which is inconsistent. This is the way which was previously documented here and is not supported anymore. Obviously, (2) is bad, which is why it is not supported anymore. (1) might be supported at some point in the future. Attempting to use :meth:`register_child` on a class which already has subclasses results in a :class:`TypeError`. Note that *first* using :meth:`register_child` and only *then* deriving clasess is a valid use: it will still lead to a consistent inheritance hierarchy and is a convenient way to break reference cycles (e.g. if an XSO may be its own child).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L2002-L2046
horazont/aioxmpp
aioxmpp/xso/model.py
CapturingXMLStreamClass.parse_events
def parse_events(cls, ev_args, parent_ctx): """ Capture the events sent to :meth:`.XSO.parse_events`, including the initial `ev_args` to a list and call :meth:`_set_captured_events` on the result of :meth:`.XSO.parse_events`. Like the method it overrides, :meth:`parse_events` is suspendable. """ dest = [("start", )+tuple(ev_args)] result = yield from capture_events( super().parse_events(ev_args, parent_ctx), dest ) result._set_captured_events(dest) return result
python
def parse_events(cls, ev_args, parent_ctx): """ Capture the events sent to :meth:`.XSO.parse_events`, including the initial `ev_args` to a list and call :meth:`_set_captured_events` on the result of :meth:`.XSO.parse_events`. Like the method it overrides, :meth:`parse_events` is suspendable. """ dest = [("start", )+tuple(ev_args)] result = yield from capture_events( super().parse_events(ev_args, parent_ctx), dest ) result._set_captured_events(dest) return result
Capture the events sent to :meth:`.XSO.parse_events`, including the initial `ev_args` to a list and call :meth:`_set_captured_events` on the result of :meth:`.XSO.parse_events`. Like the method it overrides, :meth:`parse_events` is suspendable.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L2065-L2082
horazont/aioxmpp
aioxmpp/xso/model.py
XSOParser.add_class
def add_class(self, cls, callback): """ Add a class `cls` for parsing as root level element. When an object of `cls` type has been completely parsed, `callback` is called with the object as argument. """ if cls.TAG in self._tag_map: raise ValueError( "duplicate tag: {!r} is already handled by {}".format( cls.TAG, self._tag_map[cls.TAG])) self._class_map[cls] = callback self._tag_map[cls.TAG] = (cls, callback)
python
def add_class(self, cls, callback): """ Add a class `cls` for parsing as root level element. When an object of `cls` type has been completely parsed, `callback` is called with the object as argument. """ if cls.TAG in self._tag_map: raise ValueError( "duplicate tag: {!r} is already handled by {}".format( cls.TAG, self._tag_map[cls.TAG])) self._class_map[cls] = callback self._tag_map[cls.TAG] = (cls, callback)
Add a class `cls` for parsing as root level element. When an object of `cls` type has been completely parsed, `callback` is called with the object as argument.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L2496-L2508
horazont/aioxmpp
aioxmpp/xso/model.py
XSOParser.remove_class
def remove_class(self, cls): """ Remove a XSO class `cls` from parsing. This method raises :class:`KeyError` with the classes :attr:`TAG` attribute as argument if removing fails because the class is not registered. """ del self._tag_map[cls.TAG] del self._class_map[cls]
python
def remove_class(self, cls): """ Remove a XSO class `cls` from parsing. This method raises :class:`KeyError` with the classes :attr:`TAG` attribute as argument if removing fails because the class is not registered. """ del self._tag_map[cls.TAG] del self._class_map[cls]
Remove a XSO class `cls` from parsing. This method raises :class:`KeyError` with the classes :attr:`TAG` attribute as argument if removing fails because the class is not registered.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/model.py#L2536-L2543
horazont/aioxmpp
aioxmpp/stringprep.py
check_against_tables
def check_against_tables(chars, tables): """ Perform a check against the table predicates in `tables`. `tables` must be a reusable iterable containing characteristic functions of character sets, that is, functions which return :data:`True` if the character is in the table. The function returns the first character occuring in any of the tables or :data:`None` if no character matches. """ for c in chars: if any(in_table(c) for in_table in tables): return c return None
python
def check_against_tables(chars, tables): """ Perform a check against the table predicates in `tables`. `tables` must be a reusable iterable containing characteristic functions of character sets, that is, functions which return :data:`True` if the character is in the table. The function returns the first character occuring in any of the tables or :data:`None` if no character matches. """ for c in chars: if any(in_table(c) for in_table in tables): return c return None
Perform a check against the table predicates in `tables`. `tables` must be a reusable iterable containing characteristic functions of character sets, that is, functions which return :data:`True` if the character is in the table. The function returns the first character occuring in any of the tables or :data:`None` if no character matches.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L55-L70
horazont/aioxmpp
aioxmpp/stringprep.py
check_bidi
def check_bidi(chars): """ Check proper bidirectionality as per stringprep. Operates on a list of unicode characters provided in `chars`. """ # the empty string is valid, as it cannot violate the RandALCat constraints if not chars: return # first_is_RorAL = unicodedata.bidirectional(chars[0]) in {"R", "AL"} # if first_is_RorAL: has_RandALCat = any(is_RandALCat(c) for c in chars) if not has_RandALCat: return has_LCat = any(is_LCat(c) for c in chars) if has_LCat: raise ValueError("L and R/AL characters must not occur in the same" " string") if not is_RandALCat(chars[0]) or not is_RandALCat(chars[-1]): raise ValueError("R/AL string must start and end with R/AL character.")
python
def check_bidi(chars): """ Check proper bidirectionality as per stringprep. Operates on a list of unicode characters provided in `chars`. """ # the empty string is valid, as it cannot violate the RandALCat constraints if not chars: return # first_is_RorAL = unicodedata.bidirectional(chars[0]) in {"R", "AL"} # if first_is_RorAL: has_RandALCat = any(is_RandALCat(c) for c in chars) if not has_RandALCat: return has_LCat = any(is_LCat(c) for c in chars) if has_LCat: raise ValueError("L and R/AL characters must not occur in the same" " string") if not is_RandALCat(chars[0]) or not is_RandALCat(chars[-1]): raise ValueError("R/AL string must start and end with R/AL character.")
Check proper bidirectionality as per stringprep. Operates on a list of unicode characters provided in `chars`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L81-L104
horazont/aioxmpp
aioxmpp/stringprep.py
check_prohibited_output
def check_prohibited_output(chars, bad_tables): """ Check against prohibited output, by checking whether any of the characters from `chars` are in any of the `bad_tables`. Operates in-place on a list of code points from `chars`. """ violator = check_against_tables(chars, bad_tables) if violator is not None: raise ValueError("Input contains invalid unicode codepoint: " "U+{:04x}".format(ord(violator)))
python
def check_prohibited_output(chars, bad_tables): """ Check against prohibited output, by checking whether any of the characters from `chars` are in any of the `bad_tables`. Operates in-place on a list of code points from `chars`. """ violator = check_against_tables(chars, bad_tables) if violator is not None: raise ValueError("Input contains invalid unicode codepoint: " "U+{:04x}".format(ord(violator)))
Check against prohibited output, by checking whether any of the characters from `chars` are in any of the `bad_tables`. Operates in-place on a list of code points from `chars`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L107-L117
horazont/aioxmpp
aioxmpp/stringprep.py
check_unassigned
def check_unassigned(chars, bad_tables): """ Check that `chars` does not contain any unassigned code points as per the given list of `bad_tables`. Operates on a list of unicode code points provided in `chars`. """ bad_tables = ( stringprep.in_table_a1,) violator = check_against_tables(chars, bad_tables) if violator is not None: raise ValueError("Input contains unassigned code point: " "U+{:04x}".format(ord(violator)))
python
def check_unassigned(chars, bad_tables): """ Check that `chars` does not contain any unassigned code points as per the given list of `bad_tables`. Operates on a list of unicode code points provided in `chars`. """ bad_tables = ( stringprep.in_table_a1,) violator = check_against_tables(chars, bad_tables) if violator is not None: raise ValueError("Input contains unassigned code point: " "U+{:04x}".format(ord(violator)))
Check that `chars` does not contain any unassigned code points as per the given list of `bad_tables`. Operates on a list of unicode code points provided in `chars`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L120-L133
horazont/aioxmpp
aioxmpp/stringprep.py
nodeprep
def nodeprep(string, allow_unassigned=False): """ Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised. """ chars = list(string) _nodeprep_do_mapping(chars) do_normalization(chars) check_prohibited_output( chars, ( stringprep.in_table_c11, stringprep.in_table_c12, stringprep.in_table_c21, stringprep.in_table_c22, stringprep.in_table_c3, stringprep.in_table_c4, stringprep.in_table_c5, stringprep.in_table_c6, stringprep.in_table_c7, stringprep.in_table_c8, stringprep.in_table_c9, lambda x: x in _nodeprep_prohibited )) check_bidi(chars) if not allow_unassigned: check_unassigned( chars, ( stringprep.in_table_a1, ) ) return "".join(chars)
python
def nodeprep(string, allow_unassigned=False): """ Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised. """ chars = list(string) _nodeprep_do_mapping(chars) do_normalization(chars) check_prohibited_output( chars, ( stringprep.in_table_c11, stringprep.in_table_c12, stringprep.in_table_c21, stringprep.in_table_c22, stringprep.in_table_c3, stringprep.in_table_c4, stringprep.in_table_c5, stringprep.in_table_c6, stringprep.in_table_c7, stringprep.in_table_c8, stringprep.in_table_c9, lambda x: x in _nodeprep_prohibited )) check_bidi(chars) if not allow_unassigned: check_unassigned( chars, ( stringprep.in_table_a1, ) ) return "".join(chars)
Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L149-L185
horazont/aioxmpp
aioxmpp/stringprep.py
resourceprep
def resourceprep(string, allow_unassigned=False): """ Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised. """ chars = list(string) _resourceprep_do_mapping(chars) do_normalization(chars) check_prohibited_output( chars, ( stringprep.in_table_c12, stringprep.in_table_c21, stringprep.in_table_c22, stringprep.in_table_c3, stringprep.in_table_c4, stringprep.in_table_c5, stringprep.in_table_c6, stringprep.in_table_c7, stringprep.in_table_c8, stringprep.in_table_c9, )) check_bidi(chars) if not allow_unassigned: check_unassigned( chars, ( stringprep.in_table_a1, ) ) return "".join(chars)
python
def resourceprep(string, allow_unassigned=False): """ Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised. """ chars = list(string) _resourceprep_do_mapping(chars) do_normalization(chars) check_prohibited_output( chars, ( stringprep.in_table_c12, stringprep.in_table_c21, stringprep.in_table_c22, stringprep.in_table_c3, stringprep.in_table_c4, stringprep.in_table_c5, stringprep.in_table_c6, stringprep.in_table_c7, stringprep.in_table_c8, stringprep.in_table_c9, )) check_bidi(chars) if not allow_unassigned: check_unassigned( chars, ( stringprep.in_table_a1, ) ) return "".join(chars)
Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L198-L232
horazont/aioxmpp
aioxmpp/avatar/service.py
AvatarSet.add_avatar_image
def add_avatar_image(self, mime_type, *, id_=None, image_bytes=None, width=None, height=None, url=None, nbytes=None): """ Add a source of the avatar image. All sources of an avatar image added to an avatar set must be *the same image*, in different formats and sizes. :param mime_type: The MIME type of the avatar image. :param id_: The SHA1 of the image data. :param nbytes: The size of the image data in bytes. :param image_bytes: The image data, this must be supplied only in one call. :param url: The URL of the avatar image. :param height: The height of the image in pixels (optional). :param width: The width of the image in pixels (optional). `id_` and `nbytes` may be omitted if and only if `image_data` is given and `mime_type` is ``image/png``. If they are supplied *and* image data is given, they are checked to match the image data. It is the caller's responsibility to assure that the provided links exist and the files have the correct SHA1 sums. """ if mime_type == "image/png": if image_bytes is not None: if self._image_bytes is not None: raise RuntimeError( "Only one avatar image may be published directly." ) sha1 = hashlib.sha1() sha1.update(image_bytes) id_computed = normalize_id(sha1.hexdigest()) if id_ is not None: id_ = normalize_id(id_) if id_ != id_computed: raise RuntimeError( "The given id does not match the SHA1 of " "the image data." ) else: id_ = id_computed nbytes_computed = len(image_bytes) if nbytes is not None: if nbytes != nbytes_computed: raise RuntimeError( "The given length does not match the length " "of the image data." ) else: nbytes = nbytes_computed self._image_bytes = image_bytes self._png_id = id_ if image_bytes is None and url is None: raise RuntimeError( "Either the image bytes or an url to retrieve the avatar " "image must be given." ) if nbytes is None: raise RuntimeError( "Image data length is not given an not inferable " "from the other arguments." ) if id_ is None: raise RuntimeError( "The SHA1 of the image data is not given an not inferable " "from the other arguments." ) if image_bytes is not None and mime_type != "image/png": raise RuntimeError( "The image bytes can only be given for image/png data." ) self._metadata.info[mime_type].append( avatar_xso.Info( id_=id_, mime_type=mime_type, nbytes=nbytes, width=width, height=height, url=url ) )
python
def add_avatar_image(self, mime_type, *, id_=None, image_bytes=None, width=None, height=None, url=None, nbytes=None): """ Add a source of the avatar image. All sources of an avatar image added to an avatar set must be *the same image*, in different formats and sizes. :param mime_type: The MIME type of the avatar image. :param id_: The SHA1 of the image data. :param nbytes: The size of the image data in bytes. :param image_bytes: The image data, this must be supplied only in one call. :param url: The URL of the avatar image. :param height: The height of the image in pixels (optional). :param width: The width of the image in pixels (optional). `id_` and `nbytes` may be omitted if and only if `image_data` is given and `mime_type` is ``image/png``. If they are supplied *and* image data is given, they are checked to match the image data. It is the caller's responsibility to assure that the provided links exist and the files have the correct SHA1 sums. """ if mime_type == "image/png": if image_bytes is not None: if self._image_bytes is not None: raise RuntimeError( "Only one avatar image may be published directly." ) sha1 = hashlib.sha1() sha1.update(image_bytes) id_computed = normalize_id(sha1.hexdigest()) if id_ is not None: id_ = normalize_id(id_) if id_ != id_computed: raise RuntimeError( "The given id does not match the SHA1 of " "the image data." ) else: id_ = id_computed nbytes_computed = len(image_bytes) if nbytes is not None: if nbytes != nbytes_computed: raise RuntimeError( "The given length does not match the length " "of the image data." ) else: nbytes = nbytes_computed self._image_bytes = image_bytes self._png_id = id_ if image_bytes is None and url is None: raise RuntimeError( "Either the image bytes or an url to retrieve the avatar " "image must be given." ) if nbytes is None: raise RuntimeError( "Image data length is not given an not inferable " "from the other arguments." ) if id_ is None: raise RuntimeError( "The SHA1 of the image data is not given an not inferable " "from the other arguments." ) if image_bytes is not None and mime_type != "image/png": raise RuntimeError( "The image bytes can only be given for image/png data." ) self._metadata.info[mime_type].append( avatar_xso.Info( id_=id_, mime_type=mime_type, nbytes=nbytes, width=width, height=height, url=url ) )
Add a source of the avatar image. All sources of an avatar image added to an avatar set must be *the same image*, in different formats and sizes. :param mime_type: The MIME type of the avatar image. :param id_: The SHA1 of the image data. :param nbytes: The size of the image data in bytes. :param image_bytes: The image data, this must be supplied only in one call. :param url: The URL of the avatar image. :param height: The height of the image in pixels (optional). :param width: The width of the image in pixels (optional). `id_` and `nbytes` may be omitted if and only if `image_data` is given and `mime_type` is ``image/png``. If they are supplied *and* image data is given, they are checked to match the image data. It is the caller's responsibility to assure that the provided links exist and the files have the correct SHA1 sums.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L95-L183
horazont/aioxmpp
aioxmpp/avatar/service.py
AvatarService.get_avatar_metadata
def get_avatar_metadata(self, jid, *, require_fresh=False, disable_pep=False): """ Retrieve a list of avatar descriptors. :param jid: the JID for which to retrieve the avatar metadata. :type jid: :class:`aioxmpp.JID` :param require_fresh: if true, do not return results from the avatar metadata chache, but retrieve them again from the server. :type require_fresh: :class:`bool` :param disable_pep: if true, do not try to retrieve the avatar via pep, only try the vCard fallback. This usually only useful when querying avatars via MUC, where the PEP request would be invalid (since it would be for a full jid). :type disable_pep: :class:`bool` :returns: an iterable of avatar descriptors. :rtype: a :class:`list` of :class:`~aioxmpp.avatar.service.AbstractAvatarDescriptor` instances Returning an empty list means that the avatar not set. We mask a :class:`XMPPCancelError` in the case that it is ``feature-not-implemented`` or ``item-not-found`` and return an empty list of avatar descriptors, since this is semantically equivalent to not having an avatar. .. note:: It is usually an error to get the avatar for a full jid, normally, the avatar is set for the bare jid of a user. The exception are vCard avatars over MUC, where the IQ requests for the vCard may be translated by the MUC server. It is recommended to use the `disable_pep` option in that case. """ if require_fresh: self._metadata_cache.pop(jid, None) else: try: return self._metadata_cache[jid] except KeyError: pass if disable_pep: metadata = [] else: metadata = yield from self._get_avatar_metadata_pep(jid) # try the vcard fallback, note: we don't try this # if the PEP avatar is disabled! if not metadata and jid not in self._has_pep_avatar: metadata = yield from self._get_avatar_metadata_vcard(jid) # if a notify was fired while we waited for the results, then # use the version in the cache, this will mitigate the race # condition because if our version is actually newer we will # soon get another notify for this version change! if jid not in self._metadata_cache: self._update_metadata(jid, metadata) return self._metadata_cache[jid]
python
def get_avatar_metadata(self, jid, *, require_fresh=False, disable_pep=False): """ Retrieve a list of avatar descriptors. :param jid: the JID for which to retrieve the avatar metadata. :type jid: :class:`aioxmpp.JID` :param require_fresh: if true, do not return results from the avatar metadata chache, but retrieve them again from the server. :type require_fresh: :class:`bool` :param disable_pep: if true, do not try to retrieve the avatar via pep, only try the vCard fallback. This usually only useful when querying avatars via MUC, where the PEP request would be invalid (since it would be for a full jid). :type disable_pep: :class:`bool` :returns: an iterable of avatar descriptors. :rtype: a :class:`list` of :class:`~aioxmpp.avatar.service.AbstractAvatarDescriptor` instances Returning an empty list means that the avatar not set. We mask a :class:`XMPPCancelError` in the case that it is ``feature-not-implemented`` or ``item-not-found`` and return an empty list of avatar descriptors, since this is semantically equivalent to not having an avatar. .. note:: It is usually an error to get the avatar for a full jid, normally, the avatar is set for the bare jid of a user. The exception are vCard avatars over MUC, where the IQ requests for the vCard may be translated by the MUC server. It is recommended to use the `disable_pep` option in that case. """ if require_fresh: self._metadata_cache.pop(jid, None) else: try: return self._metadata_cache[jid] except KeyError: pass if disable_pep: metadata = [] else: metadata = yield from self._get_avatar_metadata_pep(jid) # try the vcard fallback, note: we don't try this # if the PEP avatar is disabled! if not metadata and jid not in self._has_pep_avatar: metadata = yield from self._get_avatar_metadata_vcard(jid) # if a notify was fired while we waited for the results, then # use the version in the cache, this will mitigate the race # condition because if our version is actually newer we will # soon get another notify for this version change! if jid not in self._metadata_cache: self._update_metadata(jid, metadata) return self._metadata_cache[jid]
Retrieve a list of avatar descriptors. :param jid: the JID for which to retrieve the avatar metadata. :type jid: :class:`aioxmpp.JID` :param require_fresh: if true, do not return results from the avatar metadata chache, but retrieve them again from the server. :type require_fresh: :class:`bool` :param disable_pep: if true, do not try to retrieve the avatar via pep, only try the vCard fallback. This usually only useful when querying avatars via MUC, where the PEP request would be invalid (since it would be for a full jid). :type disable_pep: :class:`bool` :returns: an iterable of avatar descriptors. :rtype: a :class:`list` of :class:`~aioxmpp.avatar.service.AbstractAvatarDescriptor` instances Returning an empty list means that the avatar not set. We mask a :class:`XMPPCancelError` in the case that it is ``feature-not-implemented`` or ``item-not-found`` and return an empty list of avatar descriptors, since this is semantically equivalent to not having an avatar. .. note:: It is usually an error to get the avatar for a full jid, normally, the avatar is set for the bare jid of a user. The exception are vCard avatars over MUC, where the IQ requests for the vCard may be translated by the MUC server. It is recommended to use the `disable_pep` option in that case.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L835-L896
horazont/aioxmpp
aioxmpp/avatar/service.py
AvatarService.publish_avatar_set
def publish_avatar_set(self, avatar_set): """ Make `avatar_set` the current avatar of the jid associated with this connection. If :attr:`synchronize_vcard` is true and PEP is available the vCard is only synchronized if the PEP update is successful. This means publishing the ``image/png`` avatar data and the avatar metadata set in pubsub. The `avatar_set` must be an instance of :class:`AvatarSet`. If :attr:`synchronize_vcard` is true the avatar is additionally published in the user vCard. """ id_ = avatar_set.png_id done = False with (yield from self._publish_lock): if (yield from self._pep.available()): yield from self._pep.publish( namespaces.xep0084_data, avatar_xso.Data(avatar_set.image_bytes), id_=id_ ) yield from self._pep.publish( namespaces.xep0084_metadata, avatar_set.metadata, id_=id_ ) done = True if self._synchronize_vcard: my_vcard = yield from self._vcard.get_vcard() my_vcard.set_photo_data("image/png", avatar_set.image_bytes) self._vcard_id = avatar_set.png_id yield from self._vcard.set_vcard(my_vcard) self._presence_server.resend_presence() done = True if not done: raise RuntimeError( "failed to publish avatar: no protocol available" )
python
def publish_avatar_set(self, avatar_set): """ Make `avatar_set` the current avatar of the jid associated with this connection. If :attr:`synchronize_vcard` is true and PEP is available the vCard is only synchronized if the PEP update is successful. This means publishing the ``image/png`` avatar data and the avatar metadata set in pubsub. The `avatar_set` must be an instance of :class:`AvatarSet`. If :attr:`synchronize_vcard` is true the avatar is additionally published in the user vCard. """ id_ = avatar_set.png_id done = False with (yield from self._publish_lock): if (yield from self._pep.available()): yield from self._pep.publish( namespaces.xep0084_data, avatar_xso.Data(avatar_set.image_bytes), id_=id_ ) yield from self._pep.publish( namespaces.xep0084_metadata, avatar_set.metadata, id_=id_ ) done = True if self._synchronize_vcard: my_vcard = yield from self._vcard.get_vcard() my_vcard.set_photo_data("image/png", avatar_set.image_bytes) self._vcard_id = avatar_set.png_id yield from self._vcard.set_vcard(my_vcard) self._presence_server.resend_presence() done = True if not done: raise RuntimeError( "failed to publish avatar: no protocol available" )
Make `avatar_set` the current avatar of the jid associated with this connection. If :attr:`synchronize_vcard` is true and PEP is available the vCard is only synchronized if the PEP update is successful. This means publishing the ``image/png`` avatar data and the avatar metadata set in pubsub. The `avatar_set` must be an instance of :class:`AvatarSet`. If :attr:`synchronize_vcard` is true the avatar is additionally published in the user vCard.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L913-L956
horazont/aioxmpp
aioxmpp/avatar/service.py
AvatarService.disable_avatar
def disable_avatar(self): """ Temporarily disable the avatar. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled (even if disabling the PEP avatar fails). This is done by setting the avatar metadata node empty and if :attr:`synchronize_vcard` is true, downloading the vCard, removing the avatar data and re-uploading the vCard. This method does not error if neither protocol is active. :raises aioxmpp.errors.GatherError: if an exception is raised by the spawned tasks. """ with (yield from self._publish_lock): todo = [] if self._synchronize_vcard: todo.append(self._disable_vcard_avatar()) if (yield from self._pep.available()): todo.append(self._pep.publish( namespaces.xep0084_metadata, avatar_xso.Metadata() )) yield from gather_reraise_multi(*todo, message="disable_avatar")
python
def disable_avatar(self): """ Temporarily disable the avatar. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled (even if disabling the PEP avatar fails). This is done by setting the avatar metadata node empty and if :attr:`synchronize_vcard` is true, downloading the vCard, removing the avatar data and re-uploading the vCard. This method does not error if neither protocol is active. :raises aioxmpp.errors.GatherError: if an exception is raised by the spawned tasks. """ with (yield from self._publish_lock): todo = [] if self._synchronize_vcard: todo.append(self._disable_vcard_avatar()) if (yield from self._pep.available()): todo.append(self._pep.publish( namespaces.xep0084_metadata, avatar_xso.Metadata() )) yield from gather_reraise_multi(*todo, message="disable_avatar")
Temporarily disable the avatar. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled (even if disabling the PEP avatar fails). This is done by setting the avatar metadata node empty and if :attr:`synchronize_vcard` is true, downloading the vCard, removing the avatar data and re-uploading the vCard. This method does not error if neither protocol is active. :raises aioxmpp.errors.GatherError: if an exception is raised by the spawned tasks.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L967-L995
horazont/aioxmpp
aioxmpp/avatar/service.py
AvatarService.wipe_avatar
def wipe_avatar(self): """ Remove all avatar data stored on the server. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled even if disabling the PEP avatar fails. This is equivalent to :meth:`disable_avatar` for vCard-based avatars, but will also remove the data PubSub node for PEP avatars. This method does not error if neither protocol is active. :raises aioxmpp.errors.GatherError: if an exception is raised by the spawned tasks. """ @asyncio.coroutine def _wipe_pep_avatar(): yield from self._pep.publish( namespaces.xep0084_metadata, avatar_xso.Metadata() ) yield from self._pep.publish( namespaces.xep0084_data, avatar_xso.Data(b'') ) with (yield from self._publish_lock): todo = [] if self._synchronize_vcard: todo.append(self._disable_vcard_avatar()) if (yield from self._pep.available()): todo.append(_wipe_pep_avatar()) yield from gather_reraise_multi(*todo, message="wipe_avatar")
python
def wipe_avatar(self): """ Remove all avatar data stored on the server. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled even if disabling the PEP avatar fails. This is equivalent to :meth:`disable_avatar` for vCard-based avatars, but will also remove the data PubSub node for PEP avatars. This method does not error if neither protocol is active. :raises aioxmpp.errors.GatherError: if an exception is raised by the spawned tasks. """ @asyncio.coroutine def _wipe_pep_avatar(): yield from self._pep.publish( namespaces.xep0084_metadata, avatar_xso.Metadata() ) yield from self._pep.publish( namespaces.xep0084_data, avatar_xso.Data(b'') ) with (yield from self._publish_lock): todo = [] if self._synchronize_vcard: todo.append(self._disable_vcard_avatar()) if (yield from self._pep.available()): todo.append(_wipe_pep_avatar()) yield from gather_reraise_multi(*todo, message="wipe_avatar")
Remove all avatar data stored on the server. If :attr:`synchronize_vcard` is true, the vCard avatar is disabled even if disabling the PEP avatar fails. This is equivalent to :meth:`disable_avatar` for vCard-based avatars, but will also remove the data PubSub node for PEP avatars. This method does not error if neither protocol is active. :raises aioxmpp.errors.GatherError: if an exception is raised by the spawned tasks.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/avatar/service.py#L998-L1034
horazont/aioxmpp
aioxmpp/blocking/service.py
BlockingClient.block_jids
def block_jids(self, jids_to_block): """ Add the JIDs in the sequence `jids_to_block` to the client's blocklist. """ yield from self._check_for_blocking() if not jids_to_block: return cmd = blocking_xso.BlockCommand(jids_to_block) iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=cmd, ) yield from self.client.send(iq)
python
def block_jids(self, jids_to_block): """ Add the JIDs in the sequence `jids_to_block` to the client's blocklist. """ yield from self._check_for_blocking() if not jids_to_block: return cmd = blocking_xso.BlockCommand(jids_to_block) iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=cmd, ) yield from self.client.send(iq)
Add the JIDs in the sequence `jids_to_block` to the client's blocklist.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/blocking/service.py#L134-L149
horazont/aioxmpp
aioxmpp/blocking/service.py
BlockingClient.unblock_jids
def unblock_jids(self, jids_to_unblock): """ Remove the JIDs in the sequence `jids_to_block` from the client's blocklist. """ yield from self._check_for_blocking() if not jids_to_unblock: return cmd = blocking_xso.UnblockCommand(jids_to_unblock) iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=cmd, ) yield from self.client.send(iq)
python
def unblock_jids(self, jids_to_unblock): """ Remove the JIDs in the sequence `jids_to_block` from the client's blocklist. """ yield from self._check_for_blocking() if not jids_to_unblock: return cmd = blocking_xso.UnblockCommand(jids_to_unblock) iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=cmd, ) yield from self.client.send(iq)
Remove the JIDs in the sequence `jids_to_block` from the client's blocklist.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/blocking/service.py#L152-L167
horazont/aioxmpp
aioxmpp/forms/form.py
DescriptorClass._register_descriptor_keys
def _register_descriptor_keys(self, descriptor, keys): """ Register the given descriptor keys for the given descriptor at the class. :param descriptor: The descriptor for which the `keys` shall be registered. :type descriptor: :class:`AbstractDescriptor` instance :param keys: An iterable of descriptor keys :raises TypeError: if the specified keys are already handled by a descriptor. :raises TypeError: if this class has subclasses or if it is not the :attr:`~AbstractDescriptor.root_class` of the given descriptor. If the method raises, the caller must assume that registration was not successful. .. note:: The intended audience for this method are developers of :class:`AbstractDescriptor` subclasses, which are generally only expected to live in the :mod:`aioxmpp` package. Thus, you should not expect this API to be stable. If you have a use-case for using this function outside of :mod:`aioxmpp`, please let me know through the usual issue reporting means. """ if descriptor.root_class is not self or self.__subclasses__(): raise TypeError( "descriptors cannot be modified on classes with subclasses" ) meta = type(self) descriptor_info = meta._upcast_descriptor_map( self.DESCRIPTOR_MAP, "{}.{}".format(self.__module__, self.__qualname__), ) # this would raise on conflict meta._merge_descriptors( descriptor_info, [ (key, (descriptor, "<added via _register_descriptor_keys>")) for key in keys ] ) for key in keys: self.DESCRIPTOR_MAP[key] = descriptor
python
def _register_descriptor_keys(self, descriptor, keys): """ Register the given descriptor keys for the given descriptor at the class. :param descriptor: The descriptor for which the `keys` shall be registered. :type descriptor: :class:`AbstractDescriptor` instance :param keys: An iterable of descriptor keys :raises TypeError: if the specified keys are already handled by a descriptor. :raises TypeError: if this class has subclasses or if it is not the :attr:`~AbstractDescriptor.root_class` of the given descriptor. If the method raises, the caller must assume that registration was not successful. .. note:: The intended audience for this method are developers of :class:`AbstractDescriptor` subclasses, which are generally only expected to live in the :mod:`aioxmpp` package. Thus, you should not expect this API to be stable. If you have a use-case for using this function outside of :mod:`aioxmpp`, please let me know through the usual issue reporting means. """ if descriptor.root_class is not self or self.__subclasses__(): raise TypeError( "descriptors cannot be modified on classes with subclasses" ) meta = type(self) descriptor_info = meta._upcast_descriptor_map( self.DESCRIPTOR_MAP, "{}.{}".format(self.__module__, self.__qualname__), ) # this would raise on conflict meta._merge_descriptors( descriptor_info, [ (key, (descriptor, "<added via _register_descriptor_keys>")) for key in keys ] ) for key in keys: self.DESCRIPTOR_MAP[key] = descriptor
Register the given descriptor keys for the given descriptor at the class. :param descriptor: The descriptor for which the `keys` shall be registered. :type descriptor: :class:`AbstractDescriptor` instance :param keys: An iterable of descriptor keys :raises TypeError: if the specified keys are already handled by a descriptor. :raises TypeError: if this class has subclasses or if it is not the :attr:`~AbstractDescriptor.root_class` of the given descriptor. If the method raises, the caller must assume that registration was not successful. .. note:: The intended audience for this method are developers of :class:`AbstractDescriptor` subclasses, which are generally only expected to live in the :mod:`aioxmpp` package. Thus, you should not expect this API to be stable. If you have a use-case for using this function outside of :mod:`aioxmpp`, please let me know through the usual issue reporting means.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/form.py#L177-L227
horazont/aioxmpp
aioxmpp/forms/form.py
FormClass.from_xso
def from_xso(self, xso): """ Construct and return an instance from the given `xso`. .. note:: This is a static method (classmethod), even though sphinx does not document it as such. :param xso: A :xep:`4` data form :type xso: :class:`~.Data` :raises ValueError: if the ``FORM_TYPE`` mismatches :raises ValueError: if field types mismatch :return: newly created instance of this class The fields from the given `xso` are matched against the fields on the form. Any matching field loads its data from the `xso` field. Fields which occur on the form template but not in the `xso` are skipped. Fields which occur in the `xso` but not on the form template are also skipped (but are re-emitted when the form is rendered as reply, see :meth:`~.Form.render_reply`). If the form template has a ``FORM_TYPE`` attribute and the incoming `xso` also has a ``FORM_TYPE`` field, a mismatch between the two values leads to a :class:`ValueError`. The field types of matching fields are checked. If the field type on the incoming XSO may not be upcast to the field type declared on the form (see :meth:`~.FieldType.allow_upcast`), a :class:`ValueError` is raised. If the :attr:`~.Data.type_` does not indicate an actual form (but rather a cancellation request or tabular result), :class:`ValueError` is raised. """ my_form_type = getattr(self, "FORM_TYPE", None) f = self() for field in xso.fields: if field.var == "FORM_TYPE": if (my_form_type is not None and field.type_ == forms_xso.FieldType.HIDDEN and field.values): if my_form_type != field.values[0]: raise ValueError( "mismatching FORM_TYPE ({!r} != {!r})".format( field.values[0], my_form_type, ) ) continue if field.var is None: continue key = fields.descriptor_ns, field.var try: descriptor = self.DESCRIPTOR_MAP[key] except KeyError: continue if (field.type_ is not None and not field.type_.allow_upcast(descriptor.FIELD_TYPE)): raise ValueError( "mismatching type ({!r} != {!r}) on field var={!r}".format( field.type_, descriptor.FIELD_TYPE, field.var, ) ) data = descriptor.__get__(f, self) data.load(field) f._recv_xso = xso return f
python
def from_xso(self, xso): """ Construct and return an instance from the given `xso`. .. note:: This is a static method (classmethod), even though sphinx does not document it as such. :param xso: A :xep:`4` data form :type xso: :class:`~.Data` :raises ValueError: if the ``FORM_TYPE`` mismatches :raises ValueError: if field types mismatch :return: newly created instance of this class The fields from the given `xso` are matched against the fields on the form. Any matching field loads its data from the `xso` field. Fields which occur on the form template but not in the `xso` are skipped. Fields which occur in the `xso` but not on the form template are also skipped (but are re-emitted when the form is rendered as reply, see :meth:`~.Form.render_reply`). If the form template has a ``FORM_TYPE`` attribute and the incoming `xso` also has a ``FORM_TYPE`` field, a mismatch between the two values leads to a :class:`ValueError`. The field types of matching fields are checked. If the field type on the incoming XSO may not be upcast to the field type declared on the form (see :meth:`~.FieldType.allow_upcast`), a :class:`ValueError` is raised. If the :attr:`~.Data.type_` does not indicate an actual form (but rather a cancellation request or tabular result), :class:`ValueError` is raised. """ my_form_type = getattr(self, "FORM_TYPE", None) f = self() for field in xso.fields: if field.var == "FORM_TYPE": if (my_form_type is not None and field.type_ == forms_xso.FieldType.HIDDEN and field.values): if my_form_type != field.values[0]: raise ValueError( "mismatching FORM_TYPE ({!r} != {!r})".format( field.values[0], my_form_type, ) ) continue if field.var is None: continue key = fields.descriptor_ns, field.var try: descriptor = self.DESCRIPTOR_MAP[key] except KeyError: continue if (field.type_ is not None and not field.type_.allow_upcast(descriptor.FIELD_TYPE)): raise ValueError( "mismatching type ({!r} != {!r}) on field var={!r}".format( field.type_, descriptor.FIELD_TYPE, field.var, ) ) data = descriptor.__get__(f, self) data.load(field) f._recv_xso = xso return f
Construct and return an instance from the given `xso`. .. note:: This is a static method (classmethod), even though sphinx does not document it as such. :param xso: A :xep:`4` data form :type xso: :class:`~.Data` :raises ValueError: if the ``FORM_TYPE`` mismatches :raises ValueError: if field types mismatch :return: newly created instance of this class The fields from the given `xso` are matched against the fields on the form. Any matching field loads its data from the `xso` field. Fields which occur on the form template but not in the `xso` are skipped. Fields which occur in the `xso` but not on the form template are also skipped (but are re-emitted when the form is rendered as reply, see :meth:`~.Form.render_reply`). If the form template has a ``FORM_TYPE`` attribute and the incoming `xso` also has a ``FORM_TYPE`` field, a mismatch between the two values leads to a :class:`ValueError`. The field types of matching fields are checked. If the field type on the incoming XSO may not be upcast to the field type declared on the form (see :meth:`~.FieldType.allow_upcast`), a :class:`ValueError` is raised. If the :attr:`~.Data.type_` does not indicate an actual form (but rather a cancellation request or tabular result), :class:`ValueError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/form.py#L231-L307
horazont/aioxmpp
aioxmpp/forms/form.py
Form.render_reply
def render_reply(self): """ Create a :class:`~.Data` object equal to the object from which the from was created through :meth:`from_xso`, except that the values of the fields are exchanged with the values set on the form. Fields which have no corresponding form descriptor are left untouched. Fields which are accessible through form descriptors, but are not in the original :class:`~.Data` are not included in the output. This method only works on forms created through :meth:`from_xso`. The resulting :class:`~.Data` instance has the :attr:`~.Data.type_` set to :attr:`~.DataType.SUBMIT`. """ data = copy.copy(self._recv_xso) data.type_ = forms_xso.DataType.SUBMIT data.fields = list(self._recv_xso.fields) for i, field_xso in enumerate(data.fields): if field_xso.var is None: continue if field_xso.var == "FORM_TYPE": continue key = fields.descriptor_ns, field_xso.var try: descriptor = self.DESCRIPTOR_MAP[key] except KeyError: continue bound_field = descriptor.__get__(self, type(self)) data.fields[i] = bound_field.render( use_local_metadata=False ) return data
python
def render_reply(self): """ Create a :class:`~.Data` object equal to the object from which the from was created through :meth:`from_xso`, except that the values of the fields are exchanged with the values set on the form. Fields which have no corresponding form descriptor are left untouched. Fields which are accessible through form descriptors, but are not in the original :class:`~.Data` are not included in the output. This method only works on forms created through :meth:`from_xso`. The resulting :class:`~.Data` instance has the :attr:`~.Data.type_` set to :attr:`~.DataType.SUBMIT`. """ data = copy.copy(self._recv_xso) data.type_ = forms_xso.DataType.SUBMIT data.fields = list(self._recv_xso.fields) for i, field_xso in enumerate(data.fields): if field_xso.var is None: continue if field_xso.var == "FORM_TYPE": continue key = fields.descriptor_ns, field_xso.var try: descriptor = self.DESCRIPTOR_MAP[key] except KeyError: continue bound_field = descriptor.__get__(self, type(self)) data.fields[i] = bound_field.render( use_local_metadata=False ) return data
Create a :class:`~.Data` object equal to the object from which the from was created through :meth:`from_xso`, except that the values of the fields are exchanged with the values set on the form. Fields which have no corresponding form descriptor are left untouched. Fields which are accessible through form descriptors, but are not in the original :class:`~.Data` are not included in the output. This method only works on forms created through :meth:`from_xso`. The resulting :class:`~.Data` instance has the :attr:`~.Data.type_` set to :attr:`~.DataType.SUBMIT`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/form.py#L389-L425
horazont/aioxmpp
aioxmpp/forms/form.py
Form.render_request
def render_request(self): """ Create a :class:`Data` object containing all fields known to the :class:`Form`. If the :class:`Form` has a :attr:`LAYOUT` attribute, it is used during generation. """ data = forms_xso.Data(type_=forms_xso.DataType.FORM) try: layout = self.LAYOUT except AttributeError: layout = list(self.DESCRIPTORS) my_form_type = getattr(self, "FORM_TYPE", None) if my_form_type is not None: field_xso = forms_xso.Field() field_xso.var = "FORM_TYPE" field_xso.type_ = forms_xso.FieldType.HIDDEN field_xso.values[:] = [my_form_type] data.fields.append(field_xso) for item in layout: if isinstance(item, str): field_xso = forms_xso.Field() field_xso.type_ = forms_xso.FieldType.FIXED field_xso.values[:] = [item] else: field_xso = item.__get__( self, type(self) ).render() data.fields.append(field_xso) return data
python
def render_request(self): """ Create a :class:`Data` object containing all fields known to the :class:`Form`. If the :class:`Form` has a :attr:`LAYOUT` attribute, it is used during generation. """ data = forms_xso.Data(type_=forms_xso.DataType.FORM) try: layout = self.LAYOUT except AttributeError: layout = list(self.DESCRIPTORS) my_form_type = getattr(self, "FORM_TYPE", None) if my_form_type is not None: field_xso = forms_xso.Field() field_xso.var = "FORM_TYPE" field_xso.type_ = forms_xso.FieldType.HIDDEN field_xso.values[:] = [my_form_type] data.fields.append(field_xso) for item in layout: if isinstance(item, str): field_xso = forms_xso.Field() field_xso.type_ = forms_xso.FieldType.FIXED field_xso.values[:] = [item] else: field_xso = item.__get__( self, type(self) ).render() data.fields.append(field_xso) return data
Create a :class:`Data` object containing all fields known to the :class:`Form`. If the :class:`Form` has a :attr:`LAYOUT` attribute, it is used during generation.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/form.py#L427-L460
horazont/aioxmpp
aioxmpp/entitycaps/service.py
Cache.lookup
def lookup(self, key): """ Look up the given `node` URL using the given `hash_` first in the database and then by waiting on the futures created with :meth:`create_query_future` for that node URL and hash. If the hash is not in the database, :meth:`lookup` iterates as long as there are pending futures for the given `hash_` and `node`. If there are no pending futures, :class:`KeyError` is raised. If a future raises a :class:`ValueError`, it is ignored. If the future returns a value, it is used as the result. """ try: result = self.lookup_in_database(key) except KeyError: pass else: return result while True: fut = self._lookup_cache[key] try: result = yield from fut except ValueError: continue else: return result
python
def lookup(self, key): """ Look up the given `node` URL using the given `hash_` first in the database and then by waiting on the futures created with :meth:`create_query_future` for that node URL and hash. If the hash is not in the database, :meth:`lookup` iterates as long as there are pending futures for the given `hash_` and `node`. If there are no pending futures, :class:`KeyError` is raised. If a future raises a :class:`ValueError`, it is ignored. If the future returns a value, it is used as the result. """ try: result = self.lookup_in_database(key) except KeyError: pass else: return result while True: fut = self._lookup_cache[key] try: result = yield from fut except ValueError: continue else: return result
Look up the given `node` URL using the given `hash_` first in the database and then by waiting on the futures created with :meth:`create_query_future` for that node URL and hash. If the hash is not in the database, :meth:`lookup` iterates as long as there are pending futures for the given `hash_` and `node`. If there are no pending futures, :class:`KeyError` is raised. If a future raises a :class:`ValueError`, it is ignored. If the future returns a value, it is used as the result.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/service.py#L134-L160
horazont/aioxmpp
aioxmpp/entitycaps/service.py
Cache.create_query_future
def create_query_future(self, key): """ Create and return a :class:`asyncio.Future` for the given `hash_` function and `node` URL. The future is referenced internally and used by any calls to :meth:`lookup` which are made while the future is pending. The future is removed from the internal storage automatically when a result or exception is set for it. This allows for deduplication of queries for the same hash. """ fut = asyncio.Future() fut.add_done_callback( functools.partial(self._erase_future, key) ) self._lookup_cache[key] = fut return fut
python
def create_query_future(self, key): """ Create and return a :class:`asyncio.Future` for the given `hash_` function and `node` URL. The future is referenced internally and used by any calls to :meth:`lookup` which are made while the future is pending. The future is removed from the internal storage automatically when a result or exception is set for it. This allows for deduplication of queries for the same hash. """ fut = asyncio.Future() fut.add_done_callback( functools.partial(self._erase_future, key) ) self._lookup_cache[key] = fut return fut
Create and return a :class:`asyncio.Future` for the given `hash_` function and `node` URL. The future is referenced internally and used by any calls to :meth:`lookup` which are made while the future is pending. The future is removed from the internal storage automatically when a result or exception is set for it. This allows for deduplication of queries for the same hash.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/service.py#L162-L177
horazont/aioxmpp
aioxmpp/entitycaps/service.py
Cache.add_cache_entry
def add_cache_entry(self, key, entry): """ Add the given `entry` (which must be a :class:`~.disco.xso.InfoQuery` instance) to the user-level database keyed with the hash function type `hash_` and the `node` URL. The `entry` is **not** validated to actually map to `node` with the given `hash_` function, it is expected that the caller perfoms the validation. """ copied_entry = copy.copy(entry) self._memory_overlay[key] = copied_entry if self._user_db_path is not None: asyncio.ensure_future(asyncio.get_event_loop().run_in_executor( None, writeback, self._user_db_path / key.path, entry.captured_events))
python
def add_cache_entry(self, key, entry): """ Add the given `entry` (which must be a :class:`~.disco.xso.InfoQuery` instance) to the user-level database keyed with the hash function type `hash_` and the `node` URL. The `entry` is **not** validated to actually map to `node` with the given `hash_` function, it is expected that the caller perfoms the validation. """ copied_entry = copy.copy(entry) self._memory_overlay[key] = copied_entry if self._user_db_path is not None: asyncio.ensure_future(asyncio.get_event_loop().run_in_executor( None, writeback, self._user_db_path / key.path, entry.captured_events))
Add the given `entry` (which must be a :class:`~.disco.xso.InfoQuery` instance) to the user-level database keyed with the hash function type `hash_` and the `node` URL. The `entry` is **not** validated to actually map to `node` with the given `hash_` function, it is expected that the caller perfoms the validation.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/service.py#L179-L194
horazont/aioxmpp
aioxmpp/pep/service.py
PEPClient.claim_pep_node
def claim_pep_node(self, node_namespace, *, register_feature=True, notify=False): """ Claim node `node_namespace`. :param node_namespace: the pubsub node whose events shall be handled. :param register_feature: Whether to publish the `node_namespace` as feature. :param notify: Whether to register the ``+notify`` feature to receive notification without explicit subscription. :raises RuntimeError: if a handler for `node_namespace` is already set. :returns: a :class:`~aioxmpp.pep.service.RegisteredPEPNode` instance representing the claim. .. seealso:: :class:`aioxmpp.pep.register_pep_node` a descriptor which can be used with :class:`~aioxmpp.service.Service` subclasses to claim a PEP node automatically. This registers `node_namespace` as feature for service discovery unless ``register_feature=False`` is passed. .. note:: For `notify` to work, it is required that :class:`aioxmpp.EntityCapsService` is loaded and that presence is re-sent soon after :meth:`~aioxmpp.EntityCapsService.on_ver_changed` fires. See the documentation of the class and the signal for details. """ if node_namespace in self._pep_node_claims: raise RuntimeError( "claiming already claimed node" ) registered_node = RegisteredPEPNode( self, node_namespace, register_feature=register_feature, notify=notify, ) finalizer = weakref.finalize( registered_node, weakref.WeakMethod(registered_node._unregister) ) # we cannot guarantee that disco is not cleared up already, # so we do not unclaim the feature on exit finalizer.atexit = False self._pep_node_claims[node_namespace] = registered_node return registered_node
python
def claim_pep_node(self, node_namespace, *, register_feature=True, notify=False): """ Claim node `node_namespace`. :param node_namespace: the pubsub node whose events shall be handled. :param register_feature: Whether to publish the `node_namespace` as feature. :param notify: Whether to register the ``+notify`` feature to receive notification without explicit subscription. :raises RuntimeError: if a handler for `node_namespace` is already set. :returns: a :class:`~aioxmpp.pep.service.RegisteredPEPNode` instance representing the claim. .. seealso:: :class:`aioxmpp.pep.register_pep_node` a descriptor which can be used with :class:`~aioxmpp.service.Service` subclasses to claim a PEP node automatically. This registers `node_namespace` as feature for service discovery unless ``register_feature=False`` is passed. .. note:: For `notify` to work, it is required that :class:`aioxmpp.EntityCapsService` is loaded and that presence is re-sent soon after :meth:`~aioxmpp.EntityCapsService.on_ver_changed` fires. See the documentation of the class and the signal for details. """ if node_namespace in self._pep_node_claims: raise RuntimeError( "claiming already claimed node" ) registered_node = RegisteredPEPNode( self, node_namespace, register_feature=register_feature, notify=notify, ) finalizer = weakref.finalize( registered_node, weakref.WeakMethod(registered_node._unregister) ) # we cannot guarantee that disco is not cleared up already, # so we do not unclaim the feature on exit finalizer.atexit = False self._pep_node_claims[node_namespace] = registered_node return registered_node
Claim node `node_namespace`. :param node_namespace: the pubsub node whose events shall be handled. :param register_feature: Whether to publish the `node_namespace` as feature. :param notify: Whether to register the ``+notify`` feature to receive notification without explicit subscription. :raises RuntimeError: if a handler for `node_namespace` is already set. :returns: a :class:`~aioxmpp.pep.service.RegisteredPEPNode` instance representing the claim. .. seealso:: :class:`aioxmpp.pep.register_pep_node` a descriptor which can be used with :class:`~aioxmpp.service.Service` subclasses to claim a PEP node automatically. This registers `node_namespace` as feature for service discovery unless ``register_feature=False`` is passed. .. note:: For `notify` to work, it is required that :class:`aioxmpp.EntityCapsService` is loaded and that presence is re-sent soon after :meth:`~aioxmpp.EntityCapsService.on_ver_changed` fires. See the documentation of the class and the signal for details.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L90-L146
horazont/aioxmpp
aioxmpp/pep/service.py
PEPClient.available
def available(self): """ Check whether we have a PEP identity associated with our account. """ disco_info = yield from self._disco_client.query_info( self.client.local_jid.bare() ) for item in disco_info.identities.filter(attrs={"category": "pubsub"}): if item.type_ == "pep": return True return False
python
def available(self): """ Check whether we have a PEP identity associated with our account. """ disco_info = yield from self._disco_client.query_info( self.client.local_jid.bare() ) for item in disco_info.identities.filter(attrs={"category": "pubsub"}): if item.type_ == "pep": return True return False
Check whether we have a PEP identity associated with our account.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L152-L163
horazont/aioxmpp
aioxmpp/pep/service.py
PEPClient.publish
def publish(self, node, data, *, id_=None, access_model=None): """ Publish an item `data` in the PubSub node `node` on the PEP service associated with the user's JID. :param node: The PubSub node to publish to. :param data: The item to publish. :type data: An XSO representing the paylaod. :param id_: The id the published item shall have. :param access_model: The access model to enforce on the node. Defaults to not enforcing any access model. :returns: The PubSub id of the published item or :data:`None` if it is unknown. :raises RuntimeError: if PEP is not supported. :raises RuntimeError: if `access_model` is set and `publish_options` is not supported by the server If no `id_` is given it is generated by the server (and may be returned). `access_model` defines a pre-condition on the access model used for the `node`. The valid values depend on the service; commonly useful ``"presence"`` (the default for PEP; allows access to anyone who can receive the presence) and ``"whitelist"`` (allows access only to a whitelist (which defaults to the own account only)). """ publish_options = None def autocreate_publish_options(): nonlocal publish_options if publish_options is None: publish_options = aioxmpp.forms.Data( aioxmpp.forms.DataType.SUBMIT ) publish_options.fields.append( aioxmpp.forms.Field( type_=aioxmpp.forms.FieldType.HIDDEN, var="FORM_TYPE", values=[ "http://jabber.org/protocol/pubsub#publish-options" ] ) ) return publish_options if access_model is not None: autocreate_publish_options() publish_options.fields.append(aioxmpp.forms.Field( var="pubsub#access_model", values=[access_model], )) yield from self._check_for_pep() return (yield from self._pubsub.publish( None, node, data, id_=id_, publish_options=publish_options ))
python
def publish(self, node, data, *, id_=None, access_model=None): """ Publish an item `data` in the PubSub node `node` on the PEP service associated with the user's JID. :param node: The PubSub node to publish to. :param data: The item to publish. :type data: An XSO representing the paylaod. :param id_: The id the published item shall have. :param access_model: The access model to enforce on the node. Defaults to not enforcing any access model. :returns: The PubSub id of the published item or :data:`None` if it is unknown. :raises RuntimeError: if PEP is not supported. :raises RuntimeError: if `access_model` is set and `publish_options` is not supported by the server If no `id_` is given it is generated by the server (and may be returned). `access_model` defines a pre-condition on the access model used for the `node`. The valid values depend on the service; commonly useful ``"presence"`` (the default for PEP; allows access to anyone who can receive the presence) and ``"whitelist"`` (allows access only to a whitelist (which defaults to the own account only)). """ publish_options = None def autocreate_publish_options(): nonlocal publish_options if publish_options is None: publish_options = aioxmpp.forms.Data( aioxmpp.forms.DataType.SUBMIT ) publish_options.fields.append( aioxmpp.forms.Field( type_=aioxmpp.forms.FieldType.HIDDEN, var="FORM_TYPE", values=[ "http://jabber.org/protocol/pubsub#publish-options" ] ) ) return publish_options if access_model is not None: autocreate_publish_options() publish_options.fields.append(aioxmpp.forms.Field( var="pubsub#access_model", values=[access_model], )) yield from self._check_for_pep() return (yield from self._pubsub.publish( None, node, data, id_=id_, publish_options=publish_options ))
Publish an item `data` in the PubSub node `node` on the PEP service associated with the user's JID. :param node: The PubSub node to publish to. :param data: The item to publish. :type data: An XSO representing the paylaod. :param id_: The id the published item shall have. :param access_model: The access model to enforce on the node. Defaults to not enforcing any access model. :returns: The PubSub id of the published item or :data:`None` if it is unknown. :raises RuntimeError: if PEP is not supported. :raises RuntimeError: if `access_model` is set and `publish_options` is not supported by the server If no `id_` is given it is generated by the server (and may be returned). `access_model` defines a pre-condition on the access model used for the `node`. The valid values depend on the service; commonly useful ``"presence"`` (the default for PEP; allows access to anyone who can receive the presence) and ``"whitelist"`` (allows access only to a whitelist (which defaults to the own account only)).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L193-L249
horazont/aioxmpp
aioxmpp/pep/service.py
RegisteredPEPNode.close
def close(self): """ Unclaim the PEP node and unregister the registered features. It is not necessary to call close if this claim is managed by :class:`~aioxmpp.pep.register_pep_node`. """ if self._closed: return self._closed = True self._pep_service._unclaim(self.node_namespace) self._unregister()
python
def close(self): """ Unclaim the PEP node and unregister the registered features. It is not necessary to call close if this claim is managed by :class:`~aioxmpp.pep.register_pep_node`. """ if self._closed: return self._closed = True self._pep_service._unclaim(self.node_namespace) self._unregister()
Unclaim the PEP node and unregister the registered features. It is not necessary to call close if this claim is managed by :class:`~aioxmpp.pep.register_pep_node`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L326-L338
neo4j-contrib/django-neomodel
django_neomodel/__init__.py
DjangoNode.full_clean
def full_clean(self, exclude, validate_unique=False): """ Validate node, on error raising ValidationErrors which can be handled by django forms :param exclude: :param validate_unique: Check if conflicting node exists in the labels indexes :return: """ # validate against neomodel try: self.deflate(self.__properties__, self) except DeflateError as e: raise ValidationError({e.property_name: e.msg}) except RequiredProperty as e: raise ValidationError({e.property_name: 'is required'})
python
def full_clean(self, exclude, validate_unique=False): """ Validate node, on error raising ValidationErrors which can be handled by django forms :param exclude: :param validate_unique: Check if conflicting node exists in the labels indexes :return: """ # validate against neomodel try: self.deflate(self.__properties__, self) except DeflateError as e: raise ValidationError({e.property_name: e.msg}) except RequiredProperty as e: raise ValidationError({e.property_name: 'is required'})
Validate node, on error raising ValidationErrors which can be handled by django forms :param exclude: :param validate_unique: Check if conflicting node exists in the labels indexes :return:
https://github.com/neo4j-contrib/django-neomodel/blob/9bee6708c0df8e4d1b546fe57e1f735e63a29d81/django_neomodel/__init__.py#L148-L163
mishbahr/django-users2
users/models.py
AbstractUser.email_user
def email_user(self, subject, message, from_email=None): """ Send an email to this User.""" send_mail(subject, message, from_email, [self.email])
python
def email_user(self, subject, message, from_email=None): """ Send an email to this User.""" send_mail(subject, message, from_email, [self.email])
Send an email to this User.
https://github.com/mishbahr/django-users2/blob/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/models.py#L47-L49
mishbahr/django-users2
users/admin.py
UserAdmin.activate_users
def activate_users(self, request, queryset): """ Activates the selected users, if they are not already activated. """ n = 0 for user in queryset: if not user.is_active: user.activate() n += 1 self.message_user( request, _('Successfully activated %(count)d %(items)s.') % {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS)
python
def activate_users(self, request, queryset): """ Activates the selected users, if they are not already activated. """ n = 0 for user in queryset: if not user.is_active: user.activate() n += 1 self.message_user( request, _('Successfully activated %(count)d %(items)s.') % {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS)
Activates the selected users, if they are not already activated.
https://github.com/mishbahr/django-users2/blob/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/admin.py#L79-L93
mishbahr/django-users2
users/admin.py
UserAdmin.send_activation_email
def send_activation_email(self, request, queryset): """ Send activation emails for the selected users, if they are not already activated. """ n = 0 for user in queryset: if not user.is_active and settings.USERS_VERIFY_EMAIL: send_activation_email(user=user, request=request) n += 1 self.message_user( request, _('Activation emails sent to %(count)d %(items)s.') % {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS)
python
def send_activation_email(self, request, queryset): """ Send activation emails for the selected users, if they are not already activated. """ n = 0 for user in queryset: if not user.is_active and settings.USERS_VERIFY_EMAIL: send_activation_email(user=user, request=request) n += 1 self.message_user( request, _('Activation emails sent to %(count)d %(items)s.') % {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS)
Send activation emails for the selected users, if they are not already activated.
https://github.com/mishbahr/django-users2/blob/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/admin.py#L96-L109
mishbahr/django-users2
users/managers.py
UserManager.get_queryset
def get_queryset(self): """ Fixes get_query_set vs get_queryset for Django <1.6 """ try: qs = super(UserManager, self).get_queryset() except AttributeError: # pragma: no cover qs = super(UserManager, self).get_query_set() return qs
python
def get_queryset(self): """ Fixes get_query_set vs get_queryset for Django <1.6 """ try: qs = super(UserManager, self).get_queryset() except AttributeError: # pragma: no cover qs = super(UserManager, self).get_query_set() return qs
Fixes get_query_set vs get_queryset for Django <1.6
https://github.com/mishbahr/django-users2/blob/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/managers.py#L11-L19
eandersson/amqpstorm
amqpstorm/io.py
Poller.is_ready
def is_ready(self): """Is Socket Ready. :rtype: tuple """ try: ready, _, _ = self.select.select([self.fileno], [], [], POLL_TIMEOUT) return bool(ready) except self.select.error as why: if why.args[0] != EINTR: self._exceptions.append(AMQPConnectionError(why)) return False
python
def is_ready(self): """Is Socket Ready. :rtype: tuple """ try: ready, _, _ = self.select.select([self.fileno], [], [], POLL_TIMEOUT) return bool(ready) except self.select.error as why: if why.args[0] != EINTR: self._exceptions.append(AMQPConnectionError(why)) return False
Is Socket Ready. :rtype: tuple
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L39-L51
eandersson/amqpstorm
amqpstorm/io.py
IO.close
def close(self): """Close Socket. :return: """ self._wr_lock.acquire() self._rd_lock.acquire() try: self._running.clear() if self.socket: self._close_socket() if self._inbound_thread: self._inbound_thread.join(timeout=self._parameters['timeout']) self._inbound_thread = None self.poller = None self.socket = None finally: self._wr_lock.release() self._rd_lock.release()
python
def close(self): """Close Socket. :return: """ self._wr_lock.acquire() self._rd_lock.acquire() try: self._running.clear() if self.socket: self._close_socket() if self._inbound_thread: self._inbound_thread.join(timeout=self._parameters['timeout']) self._inbound_thread = None self.poller = None self.socket = None finally: self._wr_lock.release() self._rd_lock.release()
Close Socket. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L70-L88
eandersson/amqpstorm
amqpstorm/io.py
IO.open
def open(self): """Open Socket and establish a connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ self._wr_lock.acquire() self._rd_lock.acquire() try: self.data_in = EMPTY_BUFFER self._running.set() sock_addresses = self._get_socket_addresses() self.socket = self._find_address_and_connect(sock_addresses) self.poller = Poller(self.socket.fileno(), self._exceptions, timeout=self._parameters['timeout']) self._inbound_thread = self._create_inbound_thread() finally: self._wr_lock.release() self._rd_lock.release()
python
def open(self): """Open Socket and establish a connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ self._wr_lock.acquire() self._rd_lock.acquire() try: self.data_in = EMPTY_BUFFER self._running.set() sock_addresses = self._get_socket_addresses() self.socket = self._find_address_and_connect(sock_addresses) self.poller = Poller(self.socket.fileno(), self._exceptions, timeout=self._parameters['timeout']) self._inbound_thread = self._create_inbound_thread() finally: self._wr_lock.release() self._rd_lock.release()
Open Socket and establish a connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L90-L109
eandersson/amqpstorm
amqpstorm/io.py
IO.write_to_socket
def write_to_socket(self, frame_data): """Write data to the socket. :param str frame_data: :return: """ self._wr_lock.acquire() try: total_bytes_written = 0 bytes_to_send = len(frame_data) while total_bytes_written < bytes_to_send: try: if not self.socket: raise socket.error('connection/socket error') bytes_written = ( self.socket.send(frame_data[total_bytes_written:]) ) if bytes_written == 0: raise socket.error('connection/socket error') total_bytes_written += bytes_written except socket.timeout: pass except socket.error as why: if why.args[0] in (EWOULDBLOCK, EAGAIN): continue self._exceptions.append(AMQPConnectionError(why)) return finally: self._wr_lock.release()
python
def write_to_socket(self, frame_data): """Write data to the socket. :param str frame_data: :return: """ self._wr_lock.acquire() try: total_bytes_written = 0 bytes_to_send = len(frame_data) while total_bytes_written < bytes_to_send: try: if not self.socket: raise socket.error('connection/socket error') bytes_written = ( self.socket.send(frame_data[total_bytes_written:]) ) if bytes_written == 0: raise socket.error('connection/socket error') total_bytes_written += bytes_written except socket.timeout: pass except socket.error as why: if why.args[0] in (EWOULDBLOCK, EAGAIN): continue self._exceptions.append(AMQPConnectionError(why)) return finally: self._wr_lock.release()
Write data to the socket. :param str frame_data: :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L111-L139
eandersson/amqpstorm
amqpstorm/io.py
IO._close_socket
def _close_socket(self): """Shutdown and close the Socket. :return: """ try: self.socket.shutdown(socket.SHUT_RDWR) except (OSError, socket.error): pass self.socket.close()
python
def _close_socket(self): """Shutdown and close the Socket. :return: """ try: self.socket.shutdown(socket.SHUT_RDWR) except (OSError, socket.error): pass self.socket.close()
Shutdown and close the Socket. :return:
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L141-L150