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/service.py
inbound_message_filter
def inbound_message_filter(f): """ Register the decorated function as a service-level inbound message filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters. """ if asyncio.iscoroutinefunction(f): raise TypeError( "inbound_message_filter must not be a coroutine function" ) add_handler_spec( f, HandlerSpec( (_apply_inbound_message_filter, ()) ), ) return f
python
def inbound_message_filter(f): """ Register the decorated function as a service-level inbound message filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters. """ if asyncio.iscoroutinefunction(f): raise TypeError( "inbound_message_filter must not be a coroutine function" ) add_handler_spec( f, HandlerSpec( (_apply_inbound_message_filter, ()) ), ) return f
Register the decorated function as a service-level inbound message filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1083-L1107
horazont/aioxmpp
aioxmpp/service.py
inbound_presence_filter
def inbound_presence_filter(f): """ Register the decorated function as a service-level inbound presence filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters. """ if asyncio.iscoroutinefunction(f): raise TypeError( "inbound_presence_filter must not be a coroutine function" ) add_handler_spec( f, HandlerSpec( (_apply_inbound_presence_filter, ()) ), ) return f
python
def inbound_presence_filter(f): """ Register the decorated function as a service-level inbound presence filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters. """ if asyncio.iscoroutinefunction(f): raise TypeError( "inbound_presence_filter must not be a coroutine function" ) add_handler_spec( f, HandlerSpec( (_apply_inbound_presence_filter, ()) ), ) return f
Register the decorated function as a service-level inbound presence filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1110-L1134
horazont/aioxmpp
aioxmpp/service.py
outbound_message_filter
def outbound_message_filter(f): """ Register the decorated function as a service-level outbound message filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters. """ if asyncio.iscoroutinefunction(f): raise TypeError( "outbound_message_filter must not be a coroutine function" ) add_handler_spec( f, HandlerSpec( (_apply_outbound_message_filter, ()) ), ) return f
python
def outbound_message_filter(f): """ Register the decorated function as a service-level outbound message filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters. """ if asyncio.iscoroutinefunction(f): raise TypeError( "outbound_message_filter must not be a coroutine function" ) add_handler_spec( f, HandlerSpec( (_apply_outbound_message_filter, ()) ), ) return f
Register the decorated function as a service-level outbound message filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1137-L1161
horazont/aioxmpp
aioxmpp/service.py
outbound_presence_filter
def outbound_presence_filter(f): """ Register the decorated function as a service-level outbound presence filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters. """ if asyncio.iscoroutinefunction(f): raise TypeError( "outbound_presence_filter must not be a coroutine function" ) add_handler_spec( f, HandlerSpec( (_apply_outbound_presence_filter, ()) ), ) return f
python
def outbound_presence_filter(f): """ Register the decorated function as a service-level outbound presence filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters. """ if asyncio.iscoroutinefunction(f): raise TypeError( "outbound_presence_filter must not be a coroutine function" ) add_handler_spec( f, HandlerSpec( (_apply_outbound_presence_filter, ()) ), ) return f
Register the decorated function as a service-level outbound presence filter. :raise TypeError: if the decorated object is a coroutine function .. seealso:: :class:`StanzaStream` for important remarks regarding the use of stanza filters.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1164-L1189
horazont/aioxmpp
aioxmpp/service.py
depsignal
def depsignal(class_, signal_name, *, defer=False): """ Connect the decorated method or coroutine method to the addressed signal on a class on which the service depends. :param class_: A service class which is listed in the :attr:`~.Meta.ORDER_AFTER` relationship. :type class_: :class:`Service` class or one of the special cases below :param signal_name: Attribute name of the signal to connect to :type signal_name: :class:`str` :param defer: Flag indicating whether deferred execution of the decorated method is desired; see below for details. :type defer: :class:`bool` The signal is discovered by accessing the attribute with the name `signal_name` on the given `class_`. In addition, the following arguments are supported for `class_`: 1. :class:`aioxmpp.stream.StanzaStream`: the corresponding signal of the stream of the client running the service is used. 2. :class:`aioxmpp.Client`: the corresponding signal of the client running the service is used. If the signal is a :class:`.callbacks.Signal` and `defer` is false, the decorated object is connected using the default :attr:`~.callbacks.AdHocSignal.STRONG` mode. If the signal is a :class:`.callbacks.Signal` and `defer` is true and the decorated object is a coroutine function, the :attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default asyncio event loop is used. If the decorated object is not a coroutine function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead. If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false and the decorated object must be a coroutine function. .. versionchanged:: 0.9 Support for :class:`aioxmpp.stream.StanzaStream` and :class:`aioxmpp.Client` as `class_` argument was added. """ def decorator(f): add_handler_spec( f, _depsignal_spec(class_, signal_name, f, defer) ) return f return decorator
python
def depsignal(class_, signal_name, *, defer=False): """ Connect the decorated method or coroutine method to the addressed signal on a class on which the service depends. :param class_: A service class which is listed in the :attr:`~.Meta.ORDER_AFTER` relationship. :type class_: :class:`Service` class or one of the special cases below :param signal_name: Attribute name of the signal to connect to :type signal_name: :class:`str` :param defer: Flag indicating whether deferred execution of the decorated method is desired; see below for details. :type defer: :class:`bool` The signal is discovered by accessing the attribute with the name `signal_name` on the given `class_`. In addition, the following arguments are supported for `class_`: 1. :class:`aioxmpp.stream.StanzaStream`: the corresponding signal of the stream of the client running the service is used. 2. :class:`aioxmpp.Client`: the corresponding signal of the client running the service is used. If the signal is a :class:`.callbacks.Signal` and `defer` is false, the decorated object is connected using the default :attr:`~.callbacks.AdHocSignal.STRONG` mode. If the signal is a :class:`.callbacks.Signal` and `defer` is true and the decorated object is a coroutine function, the :attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default asyncio event loop is used. If the decorated object is not a coroutine function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead. If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false and the decorated object must be a coroutine function. .. versionchanged:: 0.9 Support for :class:`aioxmpp.stream.StanzaStream` and :class:`aioxmpp.Client` as `class_` argument was added. """ def decorator(f): add_handler_spec( f, _depsignal_spec(class_, signal_name, f, defer) ) return f return decorator
Connect the decorated method or coroutine method to the addressed signal on a class on which the service depends. :param class_: A service class which is listed in the :attr:`~.Meta.ORDER_AFTER` relationship. :type class_: :class:`Service` class or one of the special cases below :param signal_name: Attribute name of the signal to connect to :type signal_name: :class:`str` :param defer: Flag indicating whether deferred execution of the decorated method is desired; see below for details. :type defer: :class:`bool` The signal is discovered by accessing the attribute with the name `signal_name` on the given `class_`. In addition, the following arguments are supported for `class_`: 1. :class:`aioxmpp.stream.StanzaStream`: the corresponding signal of the stream of the client running the service is used. 2. :class:`aioxmpp.Client`: the corresponding signal of the client running the service is used. If the signal is a :class:`.callbacks.Signal` and `defer` is false, the decorated object is connected using the default :attr:`~.callbacks.AdHocSignal.STRONG` mode. If the signal is a :class:`.callbacks.Signal` and `defer` is true and the decorated object is a coroutine function, the :attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default asyncio event loop is used. If the decorated object is not a coroutine function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead. If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false and the decorated object must be a coroutine function. .. versionchanged:: 0.9 Support for :class:`aioxmpp.stream.StanzaStream` and :class:`aioxmpp.Client` as `class_` argument was added.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1244-L1293
horazont/aioxmpp
aioxmpp/service.py
attrsignal
def attrsignal(descriptor, signal_name, *, defer=False): """ Connect the decorated method or coroutine method to the addressed signal on a descriptor. :param descriptor: The descriptor to connect to. :type descriptor: :class:`Descriptor` subclass. :param signal_name: Attribute name of the signal to connect to :type signal_name: :class:`str` :param defer: Flag indicating whether deferred execution of the decorated method is desired; see below for details. :type defer: :class:`bool` The signal is discovered by accessing the attribute with the name `signal_name` on the :attr:`~Descriptor.value_type` of the `descriptor`. During instantiation of the service, the value of the descriptor is used to obtain the signal and then the decorated method is connected to the signal. If the signal is a :class:`.callbacks.Signal` and `defer` is false, the decorated object is connected using the default :attr:`~.callbacks.AdHocSignal.STRONG` mode. If the signal is a :class:`.callbacks.Signal` and `defer` is true and the decorated object is a coroutine function, the :attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default asyncio event loop is used. If the decorated object is not a coroutine function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead. If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false and the decorated object must be a coroutine function. .. versionadded:: 0.9 """ def decorator(f): add_handler_spec( f, _attrsignal_spec(descriptor, signal_name, f, defer) ) return f return decorator
python
def attrsignal(descriptor, signal_name, *, defer=False): """ Connect the decorated method or coroutine method to the addressed signal on a descriptor. :param descriptor: The descriptor to connect to. :type descriptor: :class:`Descriptor` subclass. :param signal_name: Attribute name of the signal to connect to :type signal_name: :class:`str` :param defer: Flag indicating whether deferred execution of the decorated method is desired; see below for details. :type defer: :class:`bool` The signal is discovered by accessing the attribute with the name `signal_name` on the :attr:`~Descriptor.value_type` of the `descriptor`. During instantiation of the service, the value of the descriptor is used to obtain the signal and then the decorated method is connected to the signal. If the signal is a :class:`.callbacks.Signal` and `defer` is false, the decorated object is connected using the default :attr:`~.callbacks.AdHocSignal.STRONG` mode. If the signal is a :class:`.callbacks.Signal` and `defer` is true and the decorated object is a coroutine function, the :attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default asyncio event loop is used. If the decorated object is not a coroutine function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead. If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false and the decorated object must be a coroutine function. .. versionadded:: 0.9 """ def decorator(f): add_handler_spec( f, _attrsignal_spec(descriptor, signal_name, f, defer) ) return f return decorator
Connect the decorated method or coroutine method to the addressed signal on a descriptor. :param descriptor: The descriptor to connect to. :type descriptor: :class:`Descriptor` subclass. :param signal_name: Attribute name of the signal to connect to :type signal_name: :class:`str` :param defer: Flag indicating whether deferred execution of the decorated method is desired; see below for details. :type defer: :class:`bool` The signal is discovered by accessing the attribute with the name `signal_name` on the :attr:`~Descriptor.value_type` of the `descriptor`. During instantiation of the service, the value of the descriptor is used to obtain the signal and then the decorated method is connected to the signal. If the signal is a :class:`.callbacks.Signal` and `defer` is false, the decorated object is connected using the default :attr:`~.callbacks.AdHocSignal.STRONG` mode. If the signal is a :class:`.callbacks.Signal` and `defer` is true and the decorated object is a coroutine function, the :attr:`~.callbacks.AdHocSignal.SPAWN_WITH_LOOP` mode with the default asyncio event loop is used. If the decorated object is not a coroutine function, :attr:`~.callbacks.AdHocSignal.ASYNC_WITH_LOOP` is used instead. If the signal is a :class:`.callbacks.SyncSignal`, `defer` must be false and the decorated object must be a coroutine function. .. versionadded:: 0.9
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1314-L1355
horazont/aioxmpp
aioxmpp/service.py
depfilter
def depfilter(class_, filter_name): """ Register the decorated method at the addressed :class:`~.callbacks.Filter` on a class on which the service depends. :param class_: A service class which is listed in the :attr:`~.Meta.ORDER_AFTER` relationship. :type class_: :class:`Service` class or :class:`aioxmpp.stream.StanzaStream` :param filter_name: Attribute name of the filter to register at :type filter_name: :class:`str` The filter at which the decorated method is registered is discovered by accessing the attribute with the name `filter_name` on the instance of the dependent class `class_`. If `class_` is :class:`aioxmpp.stream.StanzaStream`, the filter is searched for on the stream (and no dependendency needs to be declared). .. versionadded:: 0.9 """ spec = _depfilter_spec(class_, filter_name) def decorator(f): add_handler_spec( f, spec, ) return f return decorator
python
def depfilter(class_, filter_name): """ Register the decorated method at the addressed :class:`~.callbacks.Filter` on a class on which the service depends. :param class_: A service class which is listed in the :attr:`~.Meta.ORDER_AFTER` relationship. :type class_: :class:`Service` class or :class:`aioxmpp.stream.StanzaStream` :param filter_name: Attribute name of the filter to register at :type filter_name: :class:`str` The filter at which the decorated method is registered is discovered by accessing the attribute with the name `filter_name` on the instance of the dependent class `class_`. If `class_` is :class:`aioxmpp.stream.StanzaStream`, the filter is searched for on the stream (and no dependendency needs to be declared). .. versionadded:: 0.9 """ spec = _depfilter_spec(class_, filter_name) def decorator(f): add_handler_spec( f, spec, ) return f return decorator
Register the decorated method at the addressed :class:`~.callbacks.Filter` on a class on which the service depends. :param class_: A service class which is listed in the :attr:`~.Meta.ORDER_AFTER` relationship. :type class_: :class:`Service` class or :class:`aioxmpp.stream.StanzaStream` :param filter_name: Attribute name of the filter to register at :type filter_name: :class:`str` The filter at which the decorated method is registered is discovered by accessing the attribute with the name `filter_name` on the instance of the dependent class `class_`. If `class_` is :class:`aioxmpp.stream.StanzaStream`, the filter is searched for on the stream (and no dependendency needs to be declared). .. versionadded:: 0.9
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1376-L1405
horazont/aioxmpp
aioxmpp/service.py
is_iq_handler
def is_iq_handler(type_, payload_cls, coro, *, with_send_reply=False): """ Return true if `coro` has been decorated with :func:`iq_handler` for the given `type_` and `payload_cls` and the specified keyword arguments. """ try: handlers = get_magic_attr(coro) except AttributeError: return False hs = HandlerSpec( (_apply_iq_handler, (type_, payload_cls)), ) try: return handlers[hs] == dict(with_send_reply=with_send_reply) except KeyError: return False
python
def is_iq_handler(type_, payload_cls, coro, *, with_send_reply=False): """ Return true if `coro` has been decorated with :func:`iq_handler` for the given `type_` and `payload_cls` and the specified keyword arguments. """ try: handlers = get_magic_attr(coro) except AttributeError: return False hs = HandlerSpec( (_apply_iq_handler, (type_, payload_cls)), ) try: return handlers[hs] == dict(with_send_reply=with_send_reply) except KeyError: return False
Return true if `coro` has been decorated with :func:`iq_handler` for the given `type_` and `payload_cls` and the specified keyword arguments.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1408-L1426
horazont/aioxmpp
aioxmpp/service.py
is_message_handler
def is_message_handler(type_, from_, cb): """ Deprecated alias of :func:`.dispatcher.is_message_handler`. .. deprecated:: 0.9 """ import aioxmpp.dispatcher return aioxmpp.dispatcher.is_message_handler(type_, from_, cb)
python
def is_message_handler(type_, from_, cb): """ Deprecated alias of :func:`.dispatcher.is_message_handler`. .. deprecated:: 0.9 """ import aioxmpp.dispatcher return aioxmpp.dispatcher.is_message_handler(type_, from_, cb)
Deprecated alias of :func:`.dispatcher.is_message_handler`. .. deprecated:: 0.9
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1429-L1436
horazont/aioxmpp
aioxmpp/service.py
is_presence_handler
def is_presence_handler(type_, from_, cb): """ Deprecated alias of :func:`.dispatcher.is_presence_handler`. .. deprecated:: 0.9 """ import aioxmpp.dispatcher return aioxmpp.dispatcher.is_presence_handler(type_, from_, cb)
python
def is_presence_handler(type_, from_, cb): """ Deprecated alias of :func:`.dispatcher.is_presence_handler`. .. deprecated:: 0.9 """ import aioxmpp.dispatcher return aioxmpp.dispatcher.is_presence_handler(type_, from_, cb)
Deprecated alias of :func:`.dispatcher.is_presence_handler`. .. deprecated:: 0.9
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1439-L1446
horazont/aioxmpp
aioxmpp/service.py
is_inbound_message_filter
def is_inbound_message_filter(cb): """ Return true if `cb` has been decorated with :func:`inbound_message_filter`. """ try: handlers = get_magic_attr(cb) except AttributeError: return False hs = HandlerSpec( (_apply_inbound_message_filter, ()) ) return hs in handlers
python
def is_inbound_message_filter(cb): """ Return true if `cb` has been decorated with :func:`inbound_message_filter`. """ try: handlers = get_magic_attr(cb) except AttributeError: return False hs = HandlerSpec( (_apply_inbound_message_filter, ()) ) return hs in handlers
Return true if `cb` has been decorated with :func:`inbound_message_filter`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1449-L1463
horazont/aioxmpp
aioxmpp/service.py
is_inbound_presence_filter
def is_inbound_presence_filter(cb): """ Return true if `cb` has been decorated with :func:`inbound_presence_filter`. """ try: handlers = get_magic_attr(cb) except AttributeError: return False hs = HandlerSpec( (_apply_inbound_presence_filter, ()) ) return hs in handlers
python
def is_inbound_presence_filter(cb): """ Return true if `cb` has been decorated with :func:`inbound_presence_filter`. """ try: handlers = get_magic_attr(cb) except AttributeError: return False hs = HandlerSpec( (_apply_inbound_presence_filter, ()) ) return hs in handlers
Return true if `cb` has been decorated with :func:`inbound_presence_filter`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1466-L1481
horazont/aioxmpp
aioxmpp/service.py
is_outbound_message_filter
def is_outbound_message_filter(cb): """ Return true if `cb` has been decorated with :func:`outbound_message_filter`. """ try: handlers = get_magic_attr(cb) except AttributeError: return False hs = HandlerSpec( (_apply_outbound_message_filter, ()) ) return hs in handlers
python
def is_outbound_message_filter(cb): """ Return true if `cb` has been decorated with :func:`outbound_message_filter`. """ try: handlers = get_magic_attr(cb) except AttributeError: return False hs = HandlerSpec( (_apply_outbound_message_filter, ()) ) return hs in handlers
Return true if `cb` has been decorated with :func:`outbound_message_filter`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1484-L1499
horazont/aioxmpp
aioxmpp/service.py
is_outbound_presence_filter
def is_outbound_presence_filter(cb): """ Return true if `cb` has been decorated with :func:`outbound_presence_filter`. """ try: handlers = get_magic_attr(cb) except AttributeError: return False hs = HandlerSpec( (_apply_outbound_presence_filter, ()) ) return hs in handlers
python
def is_outbound_presence_filter(cb): """ Return true if `cb` has been decorated with :func:`outbound_presence_filter`. """ try: handlers = get_magic_attr(cb) except AttributeError: return False hs = HandlerSpec( (_apply_outbound_presence_filter, ()) ) return hs in handlers
Return true if `cb` has been decorated with :func:`outbound_presence_filter`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1502-L1517
horazont/aioxmpp
aioxmpp/service.py
is_depsignal_handler
def is_depsignal_handler(class_, signal_name, cb, *, defer=False): """ Return true if `cb` has been decorated with :func:`depsignal` for the given signal, class and connection mode. """ try: handlers = get_magic_attr(cb) except AttributeError: return False return _depsignal_spec(class_, signal_name, cb, defer) in handlers
python
def is_depsignal_handler(class_, signal_name, cb, *, defer=False): """ Return true if `cb` has been decorated with :func:`depsignal` for the given signal, class and connection mode. """ try: handlers = get_magic_attr(cb) except AttributeError: return False return _depsignal_spec(class_, signal_name, cb, defer) in handlers
Return true if `cb` has been decorated with :func:`depsignal` for the given signal, class and connection mode.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1520-L1530
horazont/aioxmpp
aioxmpp/service.py
is_depfilter_handler
def is_depfilter_handler(class_, filter_name, filter_): """ Return true if `filter_` has been decorated with :func:`depfilter` for the given filter and class. """ try: handlers = get_magic_attr(filter_) except AttributeError: return False return _depfilter_spec(class_, filter_name) in handlers
python
def is_depfilter_handler(class_, filter_name, filter_): """ Return true if `filter_` has been decorated with :func:`depfilter` for the given filter and class. """ try: handlers = get_magic_attr(filter_) except AttributeError: return False return _depfilter_spec(class_, filter_name) in handlers
Return true if `filter_` has been decorated with :func:`depfilter` for the given filter and class.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1533-L1543
horazont/aioxmpp
aioxmpp/service.py
is_attrsignal_handler
def is_attrsignal_handler(descriptor, signal_name, cb, *, defer=False): """ Return true if `cb` has been decorated with :func:`attrsignal` for the given signal, descriptor and connection mode. """ try: handlers = get_magic_attr(cb) except AttributeError: return False return _attrsignal_spec(descriptor, signal_name, cb, defer) in handlers
python
def is_attrsignal_handler(descriptor, signal_name, cb, *, defer=False): """ Return true if `cb` has been decorated with :func:`attrsignal` for the given signal, descriptor and connection mode. """ try: handlers = get_magic_attr(cb) except AttributeError: return False return _attrsignal_spec(descriptor, signal_name, cb, defer) in handlers
Return true if `cb` has been decorated with :func:`attrsignal` for the given signal, descriptor and connection mode.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1546-L1556
horazont/aioxmpp
aioxmpp/service.py
Descriptor.add_to_stack
def add_to_stack(self, instance, stack): """ Get the context manager for the service `instance` and push it to the context manager `stack`. :param instance: The service to get the context manager for. :type instance: :class:`Service` :param stack: The context manager stack to push the CM onto. :type stack: :class:`contextlib.ExitStack` :return: The object returned by the context manager on enter. If a context manager has already been created for `instance`, it is re-used. On subsequent calls to :meth:`__get__` for the given `instance`, the return value of this method will be returned, that is, the value obtained from entering the context. """ cm = self.init_cm(instance) obj = stack.enter_context(cm) self._data[instance] = cm, obj return obj
python
def add_to_stack(self, instance, stack): """ Get the context manager for the service `instance` and push it to the context manager `stack`. :param instance: The service to get the context manager for. :type instance: :class:`Service` :param stack: The context manager stack to push the CM onto. :type stack: :class:`contextlib.ExitStack` :return: The object returned by the context manager on enter. If a context manager has already been created for `instance`, it is re-used. On subsequent calls to :meth:`__get__` for the given `instance`, the return value of this method will be returned, that is, the value obtained from entering the context. """ cm = self.init_cm(instance) obj = stack.enter_context(cm) self._data[instance] = cm, obj return obj
Get the context manager for the service `instance` and push it to the context manager `stack`. :param instance: The service to get the context manager for. :type instance: :class:`Service` :param stack: The context manager stack to push the CM onto. :type stack: :class:`contextlib.ExitStack` :return: The object returned by the context manager on enter. If a context manager has already been created for `instance`, it is re-used. On subsequent calls to :meth:`__get__` for the given `instance`, the return value of this method will be returned, that is, the value obtained from entering the context.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L284-L306
horazont/aioxmpp
aioxmpp/service.py
Meta.orders_after
def orders_after(self, other, *, visited=None): """ Return whether `self` depends on `other` and will be instanciated later. :param other: Another service. :type other: :class:`aioxmpp.service.Service` .. versionadded:: 0.11 """ return self.orders_after_any(frozenset([other]), visited=visited)
python
def orders_after(self, other, *, visited=None): """ Return whether `self` depends on `other` and will be instanciated later. :param other: Another service. :type other: :class:`aioxmpp.service.Service` .. versionadded:: 0.11 """ return self.orders_after_any(frozenset([other]), visited=visited)
Return whether `self` depends on `other` and will be instanciated later. :param other: Another service. :type other: :class:`aioxmpp.service.Service` .. versionadded:: 0.11
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L595-L605
horazont/aioxmpp
aioxmpp/service.py
Meta.orders_after_any
def orders_after_any(self, other, *, visited=None): """ Return whether `self` orders after any of the services in the set `other`. :param other: Another service. :type other: A :class:`set` of :class:`aioxmpp.service.Service` instances .. versionadded:: 0.11 """ if not other: return False if visited is None: visited = set() elif self in visited: return False visited.add(self) for item in self.PATCHED_ORDER_AFTER: if item in visited: continue if item in other: return True if item.orders_after_any(other, visited=visited): return True return False
python
def orders_after_any(self, other, *, visited=None): """ Return whether `self` orders after any of the services in the set `other`. :param other: Another service. :type other: A :class:`set` of :class:`aioxmpp.service.Service` instances .. versionadded:: 0.11 """ if not other: return False if visited is None: visited = set() elif self in visited: return False visited.add(self) for item in self.PATCHED_ORDER_AFTER: if item in visited: continue if item in other: return True if item.orders_after_any(other, visited=visited): return True return False
Return whether `self` orders after any of the services in the set `other`. :param other: Another service. :type other: A :class:`set` of :class:`aioxmpp.service.Service` instances .. versionadded:: 0.11
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L607-L632
horazont/aioxmpp
aioxmpp/service.py
Meta.independent_from
def independent_from(self, other): """ Return whether the services are independent (neither depends on the other). :param other: Another service. :type other: :class:`aioxmpp.service.Service` .. versionadded:: 0.11 """ if self is other: return False return not self.orders_after(other) and not other.orders_after(self)
python
def independent_from(self, other): """ Return whether the services are independent (neither depends on the other). :param other: Another service. :type other: :class:`aioxmpp.service.Service` .. versionadded:: 0.11 """ if self is other: return False return not self.orders_after(other) and not other.orders_after(self)
Return whether the services are independent (neither depends on the other). :param other: Another service. :type other: :class:`aioxmpp.service.Service` .. versionadded:: 0.11
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L634-L646
horazont/aioxmpp
aioxmpp/service.py
Service.derive_logger
def derive_logger(self, logger): """ Return a child of `logger` specific for this instance. This is called after :attr:`client` has been set, from the constructor. The child name is calculated by the default implementation in a way specific for aioxmpp services; it is not meant to be used by non-:mod:`aioxmpp` classes; do not rely on the way how the child name is calculated. """ parts = type(self).__module__.split(".")[1:] if parts[-1] == "service" and len(parts) > 1: del parts[-1] return logger.getChild(".".join( parts+[type(self).__qualname__] ))
python
def derive_logger(self, logger): """ Return a child of `logger` specific for this instance. This is called after :attr:`client` has been set, from the constructor. The child name is calculated by the default implementation in a way specific for aioxmpp services; it is not meant to be used by non-:mod:`aioxmpp` classes; do not rely on the way how the child name is calculated. """ parts = type(self).__module__.split(".")[1:] if parts[-1] == "service" and len(parts) > 1: del parts[-1] return logger.getChild(".".join( parts+[type(self).__qualname__] ))
Return a child of `logger` specific for this instance. This is called after :attr:`client` has been set, from the constructor. The child name is calculated by the default implementation in a way specific for aioxmpp services; it is not meant to be used by non-:mod:`aioxmpp` classes; do not rely on the way how the child name is calculated.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L739-L755
horazont/aioxmpp
aioxmpp/tasks.py
TaskPool.set_limit
def set_limit(self, group, new_limit): """ Set a new limit on the number of tasks in the `group`. :param group: Group key of the group to modify. :type group: hashable :param new_limit: New limit for the number of tasks running in `group`. :type new_limit: non-negative :class:`int` or :data:`None` :raise ValueError: if `new_limit` is non-positive The limit of tasks for the `group` is set to `new_limit`. If there are currently more than `new_limit` tasks running in `group`, those tasks will continue to run, however, the creation of new tasks is inhibited until the group is below its limit. If the limit is set to zero, no new tasks can be spawned in the group at all. If `new_limit` is negative :class:`ValueError` is raised instead. If `new_limit` is :data:`None`, the method behaves as if :meth:`clear_limit` was called for `group`. """ if new_limit is None: self._group_limits.pop(group, None) return self._group_limits[group] = new_limit
python
def set_limit(self, group, new_limit): """ Set a new limit on the number of tasks in the `group`. :param group: Group key of the group to modify. :type group: hashable :param new_limit: New limit for the number of tasks running in `group`. :type new_limit: non-negative :class:`int` or :data:`None` :raise ValueError: if `new_limit` is non-positive The limit of tasks for the `group` is set to `new_limit`. If there are currently more than `new_limit` tasks running in `group`, those tasks will continue to run, however, the creation of new tasks is inhibited until the group is below its limit. If the limit is set to zero, no new tasks can be spawned in the group at all. If `new_limit` is negative :class:`ValueError` is raised instead. If `new_limit` is :data:`None`, the method behaves as if :meth:`clear_limit` was called for `group`. """ if new_limit is None: self._group_limits.pop(group, None) return self._group_limits[group] = new_limit
Set a new limit on the number of tasks in the `group`. :param group: Group key of the group to modify. :type group: hashable :param new_limit: New limit for the number of tasks running in `group`. :type new_limit: non-negative :class:`int` or :data:`None` :raise ValueError: if `new_limit` is non-positive The limit of tasks for the `group` is set to `new_limit`. If there are currently more than `new_limit` tasks running in `group`, those tasks will continue to run, however, the creation of new tasks is inhibited until the group is below its limit. If the limit is set to zero, no new tasks can be spawned in the group at all. If `new_limit` is negative :class:`ValueError` is raised instead. If `new_limit` is :data:`None`, the method behaves as if :meth:`clear_limit` was called for `group`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/tasks.py#L80-L107
horazont/aioxmpp
aioxmpp/tasks.py
TaskPool.spawn
def spawn(self, __groups, __coro_fun, *args, **kwargs): """ Start a new coroutine and add it to the pool atomically. :param groups: The groups the coroutine belongs to. :type groups: :class:`set` of group keys :param coro_fun: Coroutine function to run :param args: Positional arguments to pass to `coro_fun` :param kwargs: Keyword arguments to pass to `coro_fun` :raise RuntimeError: if the limit on any of the groups or the total limit is exhausted :rtype: :class:`asyncio.Task` :return: The task in which the coroutine runs. Every group must have at least one free slot available for `coro` to be spawned; if any groups capacity (or the total limit) is exhausted, the coroutine is not accepted into the pool and :class:`RuntimeError` is raised. If the coroutine cannot be added due to limiting, it is not started at all. The coroutine is started by calling `coro_fun` with `args` and `kwargs`. .. note:: The first two arguments can only be passed positionally, not as keywords. This is to prevent conflicts with keyword arguments to `coro_fun`. """ # ensure the implicit group is included __groups = set(__groups) | {()} return asyncio.ensure_future(__coro_fun(*args, **kwargs))
python
def spawn(self, __groups, __coro_fun, *args, **kwargs): """ Start a new coroutine and add it to the pool atomically. :param groups: The groups the coroutine belongs to. :type groups: :class:`set` of group keys :param coro_fun: Coroutine function to run :param args: Positional arguments to pass to `coro_fun` :param kwargs: Keyword arguments to pass to `coro_fun` :raise RuntimeError: if the limit on any of the groups or the total limit is exhausted :rtype: :class:`asyncio.Task` :return: The task in which the coroutine runs. Every group must have at least one free slot available for `coro` to be spawned; if any groups capacity (or the total limit) is exhausted, the coroutine is not accepted into the pool and :class:`RuntimeError` is raised. If the coroutine cannot be added due to limiting, it is not started at all. The coroutine is started by calling `coro_fun` with `args` and `kwargs`. .. note:: The first two arguments can only be passed positionally, not as keywords. This is to prevent conflicts with keyword arguments to `coro_fun`. """ # ensure the implicit group is included __groups = set(__groups) | {()} return asyncio.ensure_future(__coro_fun(*args, **kwargs))
Start a new coroutine and add it to the pool atomically. :param groups: The groups the coroutine belongs to. :type groups: :class:`set` of group keys :param coro_fun: Coroutine function to run :param args: Positional arguments to pass to `coro_fun` :param kwargs: Keyword arguments to pass to `coro_fun` :raise RuntimeError: if the limit on any of the groups or the total limit is exhausted :rtype: :class:`asyncio.Task` :return: The task in which the coroutine runs. Every group must have at least one free slot available for `coro` to be spawned; if any groups capacity (or the total limit) is exhausted, the coroutine is not accepted into the pool and :class:`RuntimeError` is raised. If the coroutine cannot be added due to limiting, it is not started at all. The coroutine is started by calling `coro_fun` with `args` and `kwargs`. .. note:: The first two arguments can only be passed positionally, not as keywords. This is to prevent conflicts with keyword arguments to `coro_fun`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/tasks.py#L165-L200
horazont/aioxmpp
aioxmpp/carbons/service.py
CarbonsClient.enable
def enable(self): """ Enable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send` """ yield from self._check_for_feature() iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=carbons_xso.Enable() ) yield from self.client.send(iq)
python
def enable(self): """ Enable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send` """ yield from self._check_for_feature() iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=carbons_xso.Enable() ) yield from self.client.send(iq)
Enable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send`
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/carbons/service.py#L74-L90
horazont/aioxmpp
aioxmpp/carbons/service.py
CarbonsClient.disable
def disable(self): """ Disable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send` """ yield from self._check_for_feature() iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=carbons_xso.Disable() ) yield from self.client.send(iq)
python
def disable(self): """ Disable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send` """ yield from self._check_for_feature() iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=carbons_xso.Disable() ) yield from self.client.send(iq)
Disable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send`
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/carbons/service.py#L93-L109
horazont/aioxmpp
aioxmpp/stream.py
iq_handler
def iq_handler(stream, type_, payload_cls, coro, *, with_send_reply=False): """ Context manager to temporarily register a coroutine to handle IQ requests on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: IQ type to react to (must be a request type). :type type_: :class:`~aioxmpp.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :param coro: Coroutine to register :param with_send_reply: Whether to pass a function to send the reply early to `cb`. :type with_send_reply: :class:`bool` The coroutine is registered when the context is entered and unregistered when the context is exited. Running coroutines are not affected by exiting the context manager. .. versionadded:: 0.11 The `with_send_reply` argument. See :meth:`aioxmpp.stream.StanzaStream.register_iq_request_handler` for more detail. .. versionadded:: 0.8 """ stream.register_iq_request_handler( type_, payload_cls, coro, with_send_reply=with_send_reply, ) try: yield finally: stream.unregister_iq_request_handler(type_, payload_cls)
python
def iq_handler(stream, type_, payload_cls, coro, *, with_send_reply=False): """ Context manager to temporarily register a coroutine to handle IQ requests on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: IQ type to react to (must be a request type). :type type_: :class:`~aioxmpp.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :param coro: Coroutine to register :param with_send_reply: Whether to pass a function to send the reply early to `cb`. :type with_send_reply: :class:`bool` The coroutine is registered when the context is entered and unregistered when the context is exited. Running coroutines are not affected by exiting the context manager. .. versionadded:: 0.11 The `with_send_reply` argument. See :meth:`aioxmpp.stream.StanzaStream.register_iq_request_handler` for more detail. .. versionadded:: 0.8 """ stream.register_iq_request_handler( type_, payload_cls, coro, with_send_reply=with_send_reply, ) try: yield finally: stream.unregister_iq_request_handler(type_, payload_cls)
Context manager to temporarily register a coroutine to handle IQ requests on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: IQ type to react to (must be a request type). :type type_: :class:`~aioxmpp.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :param coro: Coroutine to register :param with_send_reply: Whether to pass a function to send the reply early to `cb`. :type with_send_reply: :class:`bool` The coroutine is registered when the context is entered and unregistered when the context is exited. Running coroutines are not affected by exiting the context manager. .. versionadded:: 0.11 The `with_send_reply` argument. See :meth:`aioxmpp.stream.StanzaStream.register_iq_request_handler` for more detail. .. versionadded:: 0.8
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2690-L2729
horazont/aioxmpp
aioxmpp/stream.py
message_handler
def message_handler(stream, type_, from_, cb): """ Context manager to temporarily register a callback to handle messages on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Message type to listen for, or :data:`None` for a wildcard match. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None` :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8 """ stream.register_message_callback( type_, from_, cb, ) try: yield finally: stream.unregister_message_callback( type_, from_, )
python
def message_handler(stream, type_, from_, cb): """ Context manager to temporarily register a callback to handle messages on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Message type to listen for, or :data:`None` for a wildcard match. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None` :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8 """ stream.register_message_callback( type_, from_, cb, ) try: yield finally: stream.unregister_message_callback( type_, from_, )
Context manager to temporarily register a callback to handle messages on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Message type to listen for, or :data:`None` for a wildcard match. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None` :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2733-L2765
horazont/aioxmpp
aioxmpp/stream.py
presence_handler
def presence_handler(stream, type_, from_, cb): """ Context manager to temporarily register a callback to handle presence stanzas on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8 """ stream.register_presence_callback( type_, from_, cb, ) try: yield finally: stream.unregister_presence_callback( type_, from_, )
python
def presence_handler(stream, type_, from_, cb): """ Context manager to temporarily register a callback to handle presence stanzas on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8 """ stream.register_presence_callback( type_, from_, cb, ) try: yield finally: stream.unregister_presence_callback( type_, from_, )
Context manager to temporarily register a callback to handle presence stanzas on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2769-L2800
horazont/aioxmpp
aioxmpp/stream.py
stanza_filter
def stanza_filter(filter_, func, order=_Undefined): """ This is a deprecated alias of :meth:`aioxmpp.callbacks.Filter.context_register`. .. versionadded:: 0.8 .. deprecated:: 0.9 """ if order is not _Undefined: return filter_.context_register(func, order) else: return filter_.context_register(func)
python
def stanza_filter(filter_, func, order=_Undefined): """ This is a deprecated alias of :meth:`aioxmpp.callbacks.Filter.context_register`. .. versionadded:: 0.8 .. deprecated:: 0.9 """ if order is not _Undefined: return filter_.context_register(func, order) else: return filter_.context_register(func)
This is a deprecated alias of :meth:`aioxmpp.callbacks.Filter.context_register`. .. versionadded:: 0.8 .. deprecated:: 0.9
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2806-L2818
horazont/aioxmpp
aioxmpp/stream.py
StanzaToken.abort
def abort(self): """ Abort the stanza. Attempting to call this when the stanza is in any non-:class:`~StanzaState.ACTIVE`, non-:class:`~StanzaState.ABORTED` state results in a :class:`RuntimeError`. When a stanza is aborted, it will reside in the active queue of the stream, not will be sent and instead discarded silently. """ if (self._state != StanzaState.ACTIVE and self._state != StanzaState.ABORTED): raise RuntimeError("cannot abort stanza (already sent)") self._set_state(StanzaState.ABORTED)
python
def abort(self): """ Abort the stanza. Attempting to call this when the stanza is in any non-:class:`~StanzaState.ACTIVE`, non-:class:`~StanzaState.ABORTED` state results in a :class:`RuntimeError`. When a stanza is aborted, it will reside in the active queue of the stream, not will be sent and instead discarded silently. """ if (self._state != StanzaState.ACTIVE and self._state != StanzaState.ABORTED): raise RuntimeError("cannot abort stanza (already sent)") self._set_state(StanzaState.ABORTED)
Abort the stanza. Attempting to call this when the stanza is in any non-:class:`~StanzaState.ACTIVE`, non-:class:`~StanzaState.ABORTED` state results in a :class:`RuntimeError`. When a stanza is aborted, it will reside in the active queue of the stream, not will be sent and instead discarded silently.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L436-L448
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._done_handler
def _done_handler(self, task): """ Called when the main task (:meth:`_run`, :attr:`_task`) returns. """ try: task.result() except asyncio.CancelledError: # normal termination pass except Exception as err: try: if self._sm_enabled: self._xmlstream.abort() else: self._xmlstream.close() except Exception: pass self.on_failure(err) self._logger.exception("broker task failed")
python
def _done_handler(self, task): """ Called when the main task (:meth:`_run`, :attr:`_task`) returns. """ try: task.result() except asyncio.CancelledError: # normal termination pass except Exception as err: try: if self._sm_enabled: self._xmlstream.abort() else: self._xmlstream.close() except Exception: pass self.on_failure(err) self._logger.exception("broker task failed")
Called when the main task (:meth:`_run`, :attr:`_task`) returns.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L884-L902
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._destroy_stream_state
def _destroy_stream_state(self, exc): """ Destroy all state which does not make sense to keep after a disconnect (without stream management). """ self._logger.debug("destroying stream state (exc=%r)", exc) self._iq_response_map.close_all(exc) for task in self._iq_request_tasks: # we don’t need to remove, that’s handled by their # add_done_callback task.cancel() while not self._active_queue.empty(): token = self._active_queue.get_nowait() token._set_state(StanzaState.DISCONNECTED) if self._established: self.on_stream_destroyed(exc) self._established = False
python
def _destroy_stream_state(self, exc): """ Destroy all state which does not make sense to keep after a disconnect (without stream management). """ self._logger.debug("destroying stream state (exc=%r)", exc) self._iq_response_map.close_all(exc) for task in self._iq_request_tasks: # we don’t need to remove, that’s handled by their # add_done_callback task.cancel() while not self._active_queue.empty(): token = self._active_queue.get_nowait() token._set_state(StanzaState.DISCONNECTED) if self._established: self.on_stream_destroyed(exc) self._established = False
Destroy all state which does not make sense to keep after a disconnect (without stream management).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L908-L925
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._iq_request_coro_done_send_reply
def _iq_request_coro_done_send_reply(self, request, task): """ Called when an IQ request handler coroutine returns. `request` holds the IQ request which triggered the excecution of the coroutine and `task` is the :class:`asyncio.Task` which tracks the running coroutine. Compose a response and send that response. """ try: payload = task.result() except errors.XMPPError as err: self._send_iq_reply(request, err) except Exception: response = self._compose_undefined_condition(request) self._enqueue(response) self._logger.exception("IQ request coroutine failed") else: self._send_iq_reply(request, payload)
python
def _iq_request_coro_done_send_reply(self, request, task): """ Called when an IQ request handler coroutine returns. `request` holds the IQ request which triggered the excecution of the coroutine and `task` is the :class:`asyncio.Task` which tracks the running coroutine. Compose a response and send that response. """ try: payload = task.result() except errors.XMPPError as err: self._send_iq_reply(request, err) except Exception: response = self._compose_undefined_condition(request) self._enqueue(response) self._logger.exception("IQ request coroutine failed") else: self._send_iq_reply(request, payload)
Called when an IQ request handler coroutine returns. `request` holds the IQ request which triggered the excecution of the coroutine and `task` is the :class:`asyncio.Task` which tracks the running coroutine. Compose a response and send that response.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L953-L970
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._process_incoming_iq
def _process_incoming_iq(self, stanza_obj): """ Process an incoming IQ stanza `stanza_obj`. Calls the response handler, spawns a request handler coroutine or drops the stanza while logging a warning if no handler can be found. """ self._logger.debug("incoming iq: %r", stanza_obj) if stanza_obj.type_.is_response: # iq response self._logger.debug("iq is response") keys = [(stanza_obj.from_, stanza_obj.id_)] if self._local_jid is not None: # needed for some servers if keys[0][0] == self._local_jid: keys.append((None, keys[0][1])) elif keys[0][0] is None: keys.append((self._local_jid, keys[0][1])) for key in keys: try: self._iq_response_map.unicast(key, stanza_obj) self._logger.debug("iq response delivered to key %r", key) break except KeyError: pass else: self._logger.warning( "unexpected IQ response: from=%r, id=%r", *key) else: # iq request self._logger.debug("iq is request") key = (stanza_obj.type_, type(stanza_obj.payload)) try: coro, with_send_reply = self._iq_request_map[key] except KeyError: self._logger.warning( "unhandleable IQ request: from=%r, type_=%r, payload=%r", stanza_obj.from_, stanza_obj.type_, stanza_obj.payload ) response = stanza_obj.make_reply(type_=structs.IQType.ERROR) response.error = stanza.Error( condition=errors.ErrorCondition.SERVICE_UNAVAILABLE, ) self._enqueue(response) return args = [stanza_obj] if with_send_reply: def send_reply(result=None): nonlocal task, stanza_obj, send_reply_callback if task.done(): raise RuntimeError( "send_reply called after the handler is done") if task.remove_done_callback(send_reply_callback) == 0: raise RuntimeError( "send_reply called more than once") task.add_done_callback(self._iq_request_coro_done_check) self._send_iq_reply(stanza_obj, result) args.append(send_reply) try: awaitable = coro(*args) except Exception as exc: awaitable = asyncio.Future() awaitable.set_exception(exc) task = asyncio.ensure_future(awaitable) send_reply_callback = functools.partial( self._iq_request_coro_done_send_reply, stanza_obj) task.add_done_callback(self._iq_request_coro_done_remove_task) task.add_done_callback(send_reply_callback) self._iq_request_tasks.append(task) self._logger.debug("started task to handle request: %r", task)
python
def _process_incoming_iq(self, stanza_obj): """ Process an incoming IQ stanza `stanza_obj`. Calls the response handler, spawns a request handler coroutine or drops the stanza while logging a warning if no handler can be found. """ self._logger.debug("incoming iq: %r", stanza_obj) if stanza_obj.type_.is_response: # iq response self._logger.debug("iq is response") keys = [(stanza_obj.from_, stanza_obj.id_)] if self._local_jid is not None: # needed for some servers if keys[0][0] == self._local_jid: keys.append((None, keys[0][1])) elif keys[0][0] is None: keys.append((self._local_jid, keys[0][1])) for key in keys: try: self._iq_response_map.unicast(key, stanza_obj) self._logger.debug("iq response delivered to key %r", key) break except KeyError: pass else: self._logger.warning( "unexpected IQ response: from=%r, id=%r", *key) else: # iq request self._logger.debug("iq is request") key = (stanza_obj.type_, type(stanza_obj.payload)) try: coro, with_send_reply = self._iq_request_map[key] except KeyError: self._logger.warning( "unhandleable IQ request: from=%r, type_=%r, payload=%r", stanza_obj.from_, stanza_obj.type_, stanza_obj.payload ) response = stanza_obj.make_reply(type_=structs.IQType.ERROR) response.error = stanza.Error( condition=errors.ErrorCondition.SERVICE_UNAVAILABLE, ) self._enqueue(response) return args = [stanza_obj] if with_send_reply: def send_reply(result=None): nonlocal task, stanza_obj, send_reply_callback if task.done(): raise RuntimeError( "send_reply called after the handler is done") if task.remove_done_callback(send_reply_callback) == 0: raise RuntimeError( "send_reply called more than once") task.add_done_callback(self._iq_request_coro_done_check) self._send_iq_reply(stanza_obj, result) args.append(send_reply) try: awaitable = coro(*args) except Exception as exc: awaitable = asyncio.Future() awaitable.set_exception(exc) task = asyncio.ensure_future(awaitable) send_reply_callback = functools.partial( self._iq_request_coro_done_send_reply, stanza_obj) task.add_done_callback(self._iq_request_coro_done_remove_task) task.add_done_callback(send_reply_callback) self._iq_request_tasks.append(task) self._logger.debug("started task to handle request: %r", task)
Process an incoming IQ stanza `stanza_obj`. Calls the response handler, spawns a request handler coroutine or drops the stanza while logging a warning if no handler can be found.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L978-L1055
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._process_incoming_message
def _process_incoming_message(self, stanza_obj): """ Process an incoming message stanza `stanza_obj`. """ self._logger.debug("incoming message: %r", stanza_obj) stanza_obj = self.service_inbound_message_filter.filter(stanza_obj) if stanza_obj is None: self._logger.debug("incoming message dropped by service " "filter chain") return stanza_obj = self.app_inbound_message_filter.filter(stanza_obj) if stanza_obj is None: self._logger.debug("incoming message dropped by application " "filter chain") return self.on_message_received(stanza_obj)
python
def _process_incoming_message(self, stanza_obj): """ Process an incoming message stanza `stanza_obj`. """ self._logger.debug("incoming message: %r", stanza_obj) stanza_obj = self.service_inbound_message_filter.filter(stanza_obj) if stanza_obj is None: self._logger.debug("incoming message dropped by service " "filter chain") return stanza_obj = self.app_inbound_message_filter.filter(stanza_obj) if stanza_obj is None: self._logger.debug("incoming message dropped by application " "filter chain") return self.on_message_received(stanza_obj)
Process an incoming message stanza `stanza_obj`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1057-L1075
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._process_incoming_presence
def _process_incoming_presence(self, stanza_obj): """ Process an incoming presence stanza `stanza_obj`. """ self._logger.debug("incoming presence: %r", stanza_obj) stanza_obj = self.service_inbound_presence_filter.filter(stanza_obj) if stanza_obj is None: self._logger.debug("incoming presence dropped by service filter" " chain") return stanza_obj = self.app_inbound_presence_filter.filter(stanza_obj) if stanza_obj is None: self._logger.debug("incoming presence dropped by application " "filter chain") return self.on_presence_received(stanza_obj)
python
def _process_incoming_presence(self, stanza_obj): """ Process an incoming presence stanza `stanza_obj`. """ self._logger.debug("incoming presence: %r", stanza_obj) stanza_obj = self.service_inbound_presence_filter.filter(stanza_obj) if stanza_obj is None: self._logger.debug("incoming presence dropped by service filter" " chain") return stanza_obj = self.app_inbound_presence_filter.filter(stanza_obj) if stanza_obj is None: self._logger.debug("incoming presence dropped by application " "filter chain") return self.on_presence_received(stanza_obj)
Process an incoming presence stanza `stanza_obj`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1077-L1095
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._process_incoming
def _process_incoming(self, xmlstream, queue_entry): """ Dispatch to the different methods responsible for the different stanza types or handle a non-stanza stream-level element from `stanza_obj`, which has arrived over the given `xmlstream`. """ stanza_obj, exc = queue_entry # first, handle SM stream objects if isinstance(stanza_obj, nonza.SMAcknowledgement): self._logger.debug("received SM ack: %r", stanza_obj) if not self._sm_enabled: self._logger.warning("received SM ack, but SM not enabled") return self.sm_ack(stanza_obj.counter) return elif isinstance(stanza_obj, nonza.SMRequest): self._logger.debug("received SM request: %r", stanza_obj) if not self._sm_enabled: self._logger.warning("received SM request, but SM not enabled") return response = nonza.SMAcknowledgement() response.counter = self._sm_inbound_ctr self._logger.debug("sending SM ack: %r", response) xmlstream.send_xso(response) return # raise if it is not a stanza if not isinstance(stanza_obj, stanza.StanzaBase): raise RuntimeError( "unexpected stanza class: {}".format(stanza_obj)) # now handle stanzas, these always increment the SM counter if self._sm_enabled: self._sm_inbound_ctr += 1 self._sm_inbound_ctr &= 0xffffffff # check if the stanza has errors if exc is not None: self._process_incoming_erroneous_stanza(stanza_obj, exc) return if isinstance(stanza_obj, stanza.IQ): self._process_incoming_iq(stanza_obj) elif isinstance(stanza_obj, stanza.Message): self._process_incoming_message(stanza_obj) elif isinstance(stanza_obj, stanza.Presence): self._process_incoming_presence(stanza_obj)
python
def _process_incoming(self, xmlstream, queue_entry): """ Dispatch to the different methods responsible for the different stanza types or handle a non-stanza stream-level element from `stanza_obj`, which has arrived over the given `xmlstream`. """ stanza_obj, exc = queue_entry # first, handle SM stream objects if isinstance(stanza_obj, nonza.SMAcknowledgement): self._logger.debug("received SM ack: %r", stanza_obj) if not self._sm_enabled: self._logger.warning("received SM ack, but SM not enabled") return self.sm_ack(stanza_obj.counter) return elif isinstance(stanza_obj, nonza.SMRequest): self._logger.debug("received SM request: %r", stanza_obj) if not self._sm_enabled: self._logger.warning("received SM request, but SM not enabled") return response = nonza.SMAcknowledgement() response.counter = self._sm_inbound_ctr self._logger.debug("sending SM ack: %r", response) xmlstream.send_xso(response) return # raise if it is not a stanza if not isinstance(stanza_obj, stanza.StanzaBase): raise RuntimeError( "unexpected stanza class: {}".format(stanza_obj)) # now handle stanzas, these always increment the SM counter if self._sm_enabled: self._sm_inbound_ctr += 1 self._sm_inbound_ctr &= 0xffffffff # check if the stanza has errors if exc is not None: self._process_incoming_erroneous_stanza(stanza_obj, exc) return if isinstance(stanza_obj, stanza.IQ): self._process_incoming_iq(stanza_obj) elif isinstance(stanza_obj, stanza.Message): self._process_incoming_message(stanza_obj) elif isinstance(stanza_obj, stanza.Presence): self._process_incoming_presence(stanza_obj)
Dispatch to the different methods responsible for the different stanza types or handle a non-stanza stream-level element from `stanza_obj`, which has arrived over the given `xmlstream`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1145-L1193
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.flush_incoming
def flush_incoming(self): """ Flush all incoming queues to the respective processing methods. The handlers are called as usual, thus it may require at least one iteration through the asyncio event loop before effects can be seen. The incoming queues are empty after a call to this method. It is legal (but pretty useless) to call this method while the stream is :attr:`running`. """ while True: try: stanza_obj = self._incoming_queue.get_nowait() except asyncio.QueueEmpty: break self._process_incoming(None, stanza_obj)
python
def flush_incoming(self): """ Flush all incoming queues to the respective processing methods. The handlers are called as usual, thus it may require at least one iteration through the asyncio event loop before effects can be seen. The incoming queues are empty after a call to this method. It is legal (but pretty useless) to call this method while the stream is :attr:`running`. """ while True: try: stanza_obj = self._incoming_queue.get_nowait() except asyncio.QueueEmpty: break self._process_incoming(None, stanza_obj)
Flush all incoming queues to the respective processing methods. The handlers are called as usual, thus it may require at least one iteration through the asyncio event loop before effects can be seen. The incoming queues are empty after a call to this method. It is legal (but pretty useless) to call this method while the stream is :attr:`running`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1195-L1211
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._send_stanza
def _send_stanza(self, xmlstream, token): """ Send a stanza token `token` over the given `xmlstream`. Only sends if the `token` has not been aborted (see :meth:`StanzaToken.abort`). Sends the state of the token acoording to :attr:`sm_enabled`. """ if token.state == StanzaState.ABORTED: return stanza_obj = token.stanza if isinstance(stanza_obj, stanza.Presence): stanza_obj = self.app_outbound_presence_filter.filter( stanza_obj ) if stanza_obj is not None: stanza_obj = self.service_outbound_presence_filter.filter( stanza_obj ) elif isinstance(stanza_obj, stanza.Message): stanza_obj = self.app_outbound_message_filter.filter( stanza_obj ) if stanza_obj is not None: stanza_obj = self.service_outbound_message_filter.filter( stanza_obj ) if stanza_obj is None: token._set_state(StanzaState.DROPPED) self._logger.debug("outgoing stanza %r dropped by filter chain", token.stanza) return self._logger.debug("forwarding stanza to xmlstream: %r", stanza_obj) try: xmlstream.send_xso(stanza_obj) except Exception as exc: self._logger.warning("failed to send stanza", exc_info=True) token._set_state(StanzaState.FAILED, exc) return if self._sm_enabled: token._set_state(StanzaState.SENT) self._sm_unacked_list.append(token) else: token._set_state(StanzaState.SENT_WITHOUT_SM)
python
def _send_stanza(self, xmlstream, token): """ Send a stanza token `token` over the given `xmlstream`. Only sends if the `token` has not been aborted (see :meth:`StanzaToken.abort`). Sends the state of the token acoording to :attr:`sm_enabled`. """ if token.state == StanzaState.ABORTED: return stanza_obj = token.stanza if isinstance(stanza_obj, stanza.Presence): stanza_obj = self.app_outbound_presence_filter.filter( stanza_obj ) if stanza_obj is not None: stanza_obj = self.service_outbound_presence_filter.filter( stanza_obj ) elif isinstance(stanza_obj, stanza.Message): stanza_obj = self.app_outbound_message_filter.filter( stanza_obj ) if stanza_obj is not None: stanza_obj = self.service_outbound_message_filter.filter( stanza_obj ) if stanza_obj is None: token._set_state(StanzaState.DROPPED) self._logger.debug("outgoing stanza %r dropped by filter chain", token.stanza) return self._logger.debug("forwarding stanza to xmlstream: %r", stanza_obj) try: xmlstream.send_xso(stanza_obj) except Exception as exc: self._logger.warning("failed to send stanza", exc_info=True) token._set_state(StanzaState.FAILED, exc) return if self._sm_enabled: token._set_state(StanzaState.SENT) self._sm_unacked_list.append(token) else: token._set_state(StanzaState.SENT_WITHOUT_SM)
Send a stanza token `token` over the given `xmlstream`. Only sends if the `token` has not been aborted (see :meth:`StanzaToken.abort`). Sends the state of the token acoording to :attr:`sm_enabled`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1213-L1263
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._process_outgoing
def _process_outgoing(self, xmlstream, token): """ Process the current outgoing stanza `token` and also any other outgoing stanza which is currently in the active queue. After all stanzas have been processed, use :meth:`_send_ping` to allow an opportunistic ping to be sent. """ self._send_stanza(xmlstream, token) # try to send a bulk while True: try: token = self._active_queue.get_nowait() except asyncio.QueueEmpty: break self._send_stanza(xmlstream, token) if self._sm_enabled: self._logger.debug("sending SM req") xmlstream.send_xso(nonza.SMRequest())
python
def _process_outgoing(self, xmlstream, token): """ Process the current outgoing stanza `token` and also any other outgoing stanza which is currently in the active queue. After all stanzas have been processed, use :meth:`_send_ping` to allow an opportunistic ping to be sent. """ self._send_stanza(xmlstream, token) # try to send a bulk while True: try: token = self._active_queue.get_nowait() except asyncio.QueueEmpty: break self._send_stanza(xmlstream, token) if self._sm_enabled: self._logger.debug("sending SM req") xmlstream.send_xso(nonza.SMRequest())
Process the current outgoing stanza `token` and also any other outgoing stanza which is currently in the active queue. After all stanzas have been processed, use :meth:`_send_ping` to allow an opportunistic ping to be sent.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1265-L1284
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.register_iq_response_callback
def register_iq_response_callback(self, from_, id_, cb): """ Register a callback function `cb` to be called when a IQ stanza with type ``result`` or ``error`` is recieved from the :class:`~aioxmpp.JID` `from_` with the id `id_`. The callback is called at most once. .. note:: In contrast to :meth:`register_iq_response_future`, errors which occur on a level below XMPP stanzas cannot be caught using a callback. If you need notification about other errors and still want to use callbacks, use of a future with :meth:`asyncio.Future.add_done_callback` is recommended. """ self._iq_response_map.add_listener( (from_, id_), callbacks.OneshotAsyncTagListener(cb, loop=self._loop) ) self._logger.debug("iq response callback registered: from=%r, id=%r", from_, id_)
python
def register_iq_response_callback(self, from_, id_, cb): """ Register a callback function `cb` to be called when a IQ stanza with type ``result`` or ``error`` is recieved from the :class:`~aioxmpp.JID` `from_` with the id `id_`. The callback is called at most once. .. note:: In contrast to :meth:`register_iq_response_future`, errors which occur on a level below XMPP stanzas cannot be caught using a callback. If you need notification about other errors and still want to use callbacks, use of a future with :meth:`asyncio.Future.add_done_callback` is recommended. """ self._iq_response_map.add_listener( (from_, id_), callbacks.OneshotAsyncTagListener(cb, loop=self._loop) ) self._logger.debug("iq response callback registered: from=%r, id=%r", from_, id_)
Register a callback function `cb` to be called when a IQ stanza with type ``result`` or ``error`` is recieved from the :class:`~aioxmpp.JID` `from_` with the id `id_`. The callback is called at most once. .. note:: In contrast to :meth:`register_iq_response_future`, errors which occur on a level below XMPP stanzas cannot be caught using a callback. If you need notification about other errors and still want to use callbacks, use of a future with :meth:`asyncio.Future.add_done_callback` is recommended.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1286-L1311
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.register_iq_response_future
def register_iq_response_future(self, from_, id_, fut): """ Register a future `fut` for an IQ stanza with type ``result`` or ``error`` from the :class:`~aioxmpp.JID` `from_` with the id `id_`. If the type of the IQ stanza is ``result``, the stanza is set as result to the future. If the type of the IQ stanza is ``error``, the stanzas error field is converted to an exception and set as the exception of the future. The future might also receive different exceptions: * :class:`.errors.ErroneousStanza`, if the response stanza received could not be parsed. Note that this exception is not emitted if the ``from`` address of the stanza is unset, because the code cannot determine whether a sender deliberately used an erroneous address to make parsing fail or no sender address was used. In the former case, an attacker could use that to inject a stanza which would be taken as a stanza from the peer server. Thus, the future will never be fulfilled in these cases. Also note that this exception does not derive from :class:`.errors.XMPPError`, as it cannot provide the same attributes. Instead, it dervies from :class:`.errors.StanzaError`, from which :class:`.errors.XMPPError` also derives; to catch all possible stanza errors, catching :class:`.errors.StanzaError` is sufficient and future-proof. * :class:`ConnectionError` if the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or :meth:`close`\\ -ed. * Any :class:`Exception` which may be raised from :meth:`~.protocol.XMLStream.send_xso`, which are generally also :class:`ConnectionError` or at least :class:`OSError` subclasses. """ self._iq_response_map.add_listener( (from_, id_), StanzaErrorAwareListener( callbacks.FutureListener(fut) ) ) self._logger.debug("iq response future registered: from=%r, id=%r", from_, id_)
python
def register_iq_response_future(self, from_, id_, fut): """ Register a future `fut` for an IQ stanza with type ``result`` or ``error`` from the :class:`~aioxmpp.JID` `from_` with the id `id_`. If the type of the IQ stanza is ``result``, the stanza is set as result to the future. If the type of the IQ stanza is ``error``, the stanzas error field is converted to an exception and set as the exception of the future. The future might also receive different exceptions: * :class:`.errors.ErroneousStanza`, if the response stanza received could not be parsed. Note that this exception is not emitted if the ``from`` address of the stanza is unset, because the code cannot determine whether a sender deliberately used an erroneous address to make parsing fail or no sender address was used. In the former case, an attacker could use that to inject a stanza which would be taken as a stanza from the peer server. Thus, the future will never be fulfilled in these cases. Also note that this exception does not derive from :class:`.errors.XMPPError`, as it cannot provide the same attributes. Instead, it dervies from :class:`.errors.StanzaError`, from which :class:`.errors.XMPPError` also derives; to catch all possible stanza errors, catching :class:`.errors.StanzaError` is sufficient and future-proof. * :class:`ConnectionError` if the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or :meth:`close`\\ -ed. * Any :class:`Exception` which may be raised from :meth:`~.protocol.XMLStream.send_xso`, which are generally also :class:`ConnectionError` or at least :class:`OSError` subclasses. """ self._iq_response_map.add_listener( (from_, id_), StanzaErrorAwareListener( callbacks.FutureListener(fut) ) ) self._logger.debug("iq response future registered: from=%r, id=%r", from_, id_)
Register a future `fut` for an IQ stanza with type ``result`` or ``error`` from the :class:`~aioxmpp.JID` `from_` with the id `id_`. If the type of the IQ stanza is ``result``, the stanza is set as result to the future. If the type of the IQ stanza is ``error``, the stanzas error field is converted to an exception and set as the exception of the future. The future might also receive different exceptions: * :class:`.errors.ErroneousStanza`, if the response stanza received could not be parsed. Note that this exception is not emitted if the ``from`` address of the stanza is unset, because the code cannot determine whether a sender deliberately used an erroneous address to make parsing fail or no sender address was used. In the former case, an attacker could use that to inject a stanza which would be taken as a stanza from the peer server. Thus, the future will never be fulfilled in these cases. Also note that this exception does not derive from :class:`.errors.XMPPError`, as it cannot provide the same attributes. Instead, it dervies from :class:`.errors.StanzaError`, from which :class:`.errors.XMPPError` also derives; to catch all possible stanza errors, catching :class:`.errors.StanzaError` is sufficient and future-proof. * :class:`ConnectionError` if the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or :meth:`close`\\ -ed. * Any :class:`Exception` which may be raised from :meth:`~.protocol.XMLStream.send_xso`, which are generally also :class:`ConnectionError` or at least :class:`OSError` subclasses.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1313-L1360
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.unregister_iq_response
def unregister_iq_response(self, from_, id_): """ Unregister a registered callback or future for the IQ response identified by `from_` and `id_`. See :meth:`register_iq_response_future` or :meth:`register_iq_response_callback` for details on the arguments meanings and how to register futures and callbacks respectively. .. note:: Futures will automatically be unregistered when they are cancelled. """ self._iq_response_map.remove_listener((from_, id_)) self._logger.debug("iq response unregistered: from=%r, id=%r", from_, id_)
python
def unregister_iq_response(self, from_, id_): """ Unregister a registered callback or future for the IQ response identified by `from_` and `id_`. See :meth:`register_iq_response_future` or :meth:`register_iq_response_callback` for details on the arguments meanings and how to register futures and callbacks respectively. .. note:: Futures will automatically be unregistered when they are cancelled. """ self._iq_response_map.remove_listener((from_, id_)) self._logger.debug("iq response unregistered: from=%r, id=%r", from_, id_)
Unregister a registered callback or future for the IQ response identified by `from_` and `id_`. See :meth:`register_iq_response_future` or :meth:`register_iq_response_callback` for details on the arguments meanings and how to register futures and callbacks respectively. .. note:: Futures will automatically be unregistered when they are cancelled.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1362-L1377
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.register_iq_request_coro
def register_iq_request_coro(self, type_, payload_cls, coro): """ Alias of :meth:`register_iq_request_handler`. .. deprecated:: 0.10 This alias will be removed in version 1.0. """ warnings.warn( "register_iq_request_coro is a deprecated alias to " "register_iq_request_handler and will be removed in aioxmpp 1.0", DeprecationWarning, stacklevel=2) return self.register_iq_request_handler(type_, payload_cls, coro)
python
def register_iq_request_coro(self, type_, payload_cls, coro): """ Alias of :meth:`register_iq_request_handler`. .. deprecated:: 0.10 This alias will be removed in version 1.0. """ warnings.warn( "register_iq_request_coro is a deprecated alias to " "register_iq_request_handler and will be removed in aioxmpp 1.0", DeprecationWarning, stacklevel=2) return self.register_iq_request_handler(type_, payload_cls, coro)
Alias of :meth:`register_iq_request_handler`. .. deprecated:: 0.10 This alias will be removed in version 1.0.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1379-L1392
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.register_iq_request_handler
def register_iq_request_handler(self, type_, payload_cls, cb, *, with_send_reply=False): """ Register a coroutine function or a function returning an awaitable to run when an IQ request is received. :param type_: IQ type to react to (must be a request type). :type type_: :class:`~aioxmpp.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :param cb: Function or coroutine function to invoke :param with_send_reply: Whether to pass a function to send a reply to `cb` as second argument. :type with_send_reply: :class:`bool` :raises ValueError: if there is already a coroutine registered for this target :raises ValueError: if `type_` is not a request IQ type :raises ValueError: if `type_` is not a valid :class:`~.IQType` (and cannot be cast to a :class:`~.IQType`) The callback `cb` will be called whenever an IQ stanza with the given `type_` and payload being an instance of the `payload_cls` is received. The callback must either be a coroutine function or otherwise return an awaitable. The awaitable must evaluate to a valid value for the :attr:`.IQ.payload` attribute. That value will be set as the payload attribute value of an IQ response (with type :attr:`~.IQType.RESULT`) which is generated and sent by the stream. If the awaitable or the function raises an exception, it will be converted to a :class:`~.stanza.Error` object. That error object is then used as payload for an IQ response (with type :attr:`~.IQType.ERROR`) which is generated and sent by the stream. If the exception is a subclass of :class:`aioxmpp.errors.XMPPError`, it is converted to an :class:`~.stanza.Error` instance directly. Otherwise, it is wrapped in a :class:`aioxmpp.XMPPCancelError` with ``undefined-condition``. For this to work, `payload_cls` *must* be registered using :meth:`~.IQ.as_payload_class`. Otherwise, the payload will not be recognised by the stream parser and the IQ is automatically responded to with a ``feature-not-implemented`` error. .. warning:: When using a coroutine function for `cb`, there is no guarantee that concurrent IQ handlers and other coroutines will execute in any defined order. This implies that the strong ordering guarantees normally provided by XMPP XML Streams are lost when using coroutine functions for `cb`. For this reason, the use of non-coroutine functions is allowed. .. note:: Using a non-coroutine function for `cb` will generally lead to less readable code. For the sake of readability, it is recommended to prefer coroutine functions when strong ordering guarantees are not needed. .. versionadded:: 0.11 When the argument `with_send_reply` is true `cb` will be called with two arguments: the IQ stanza to handle and a unary function `send_reply(result=None)` that sends a response to the IQ request and prevents that an automatic response is sent. If `result` is an instance of :class:`~aioxmpp.XMPPError` an error result is generated. This is useful when the handler function needs to execute actions which happen after the IQ result has been sent, for example, sending other stanzas. .. versionchanged:: 0.10 Accepts an awaitable as last argument in addition to coroutine functions. Renamed from :meth:`register_iq_request_coro`. .. versionadded:: 0.6 If the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or :meth:`close`\\ ed, running IQ response coroutines are :meth:`asyncio.Task.cancel`\\ -led. To protect against that, fork from your coroutine using :func:`asyncio.ensure_future`. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.IQType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. """ type_ = self._coerce_enum(type_, structs.IQType) if not type_.is_request: raise ValueError( "{!r} is not a request IQType".format(type_) ) key = type_, payload_cls if key in self._iq_request_map: raise ValueError("only one listener is allowed per tag") self._iq_request_map[key] = cb, with_send_reply self._logger.debug( "iq request coroutine registered: type=%r, payload=%r", type_, payload_cls)
python
def register_iq_request_handler(self, type_, payload_cls, cb, *, with_send_reply=False): """ Register a coroutine function or a function returning an awaitable to run when an IQ request is received. :param type_: IQ type to react to (must be a request type). :type type_: :class:`~aioxmpp.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :param cb: Function or coroutine function to invoke :param with_send_reply: Whether to pass a function to send a reply to `cb` as second argument. :type with_send_reply: :class:`bool` :raises ValueError: if there is already a coroutine registered for this target :raises ValueError: if `type_` is not a request IQ type :raises ValueError: if `type_` is not a valid :class:`~.IQType` (and cannot be cast to a :class:`~.IQType`) The callback `cb` will be called whenever an IQ stanza with the given `type_` and payload being an instance of the `payload_cls` is received. The callback must either be a coroutine function or otherwise return an awaitable. The awaitable must evaluate to a valid value for the :attr:`.IQ.payload` attribute. That value will be set as the payload attribute value of an IQ response (with type :attr:`~.IQType.RESULT`) which is generated and sent by the stream. If the awaitable or the function raises an exception, it will be converted to a :class:`~.stanza.Error` object. That error object is then used as payload for an IQ response (with type :attr:`~.IQType.ERROR`) which is generated and sent by the stream. If the exception is a subclass of :class:`aioxmpp.errors.XMPPError`, it is converted to an :class:`~.stanza.Error` instance directly. Otherwise, it is wrapped in a :class:`aioxmpp.XMPPCancelError` with ``undefined-condition``. For this to work, `payload_cls` *must* be registered using :meth:`~.IQ.as_payload_class`. Otherwise, the payload will not be recognised by the stream parser and the IQ is automatically responded to with a ``feature-not-implemented`` error. .. warning:: When using a coroutine function for `cb`, there is no guarantee that concurrent IQ handlers and other coroutines will execute in any defined order. This implies that the strong ordering guarantees normally provided by XMPP XML Streams are lost when using coroutine functions for `cb`. For this reason, the use of non-coroutine functions is allowed. .. note:: Using a non-coroutine function for `cb` will generally lead to less readable code. For the sake of readability, it is recommended to prefer coroutine functions when strong ordering guarantees are not needed. .. versionadded:: 0.11 When the argument `with_send_reply` is true `cb` will be called with two arguments: the IQ stanza to handle and a unary function `send_reply(result=None)` that sends a response to the IQ request and prevents that an automatic response is sent. If `result` is an instance of :class:`~aioxmpp.XMPPError` an error result is generated. This is useful when the handler function needs to execute actions which happen after the IQ result has been sent, for example, sending other stanzas. .. versionchanged:: 0.10 Accepts an awaitable as last argument in addition to coroutine functions. Renamed from :meth:`register_iq_request_coro`. .. versionadded:: 0.6 If the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or :meth:`close`\\ ed, running IQ response coroutines are :meth:`asyncio.Task.cancel`\\ -led. To protect against that, fork from your coroutine using :func:`asyncio.ensure_future`. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.IQType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. """ type_ = self._coerce_enum(type_, structs.IQType) if not type_.is_request: raise ValueError( "{!r} is not a request IQType".format(type_) ) key = type_, payload_cls if key in self._iq_request_map: raise ValueError("only one listener is allowed per tag") self._iq_request_map[key] = cb, with_send_reply self._logger.debug( "iq request coroutine registered: type=%r, payload=%r", type_, payload_cls)
Register a coroutine function or a function returning an awaitable to run when an IQ request is received. :param type_: IQ type to react to (must be a request type). :type type_: :class:`~aioxmpp.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :param cb: Function or coroutine function to invoke :param with_send_reply: Whether to pass a function to send a reply to `cb` as second argument. :type with_send_reply: :class:`bool` :raises ValueError: if there is already a coroutine registered for this target :raises ValueError: if `type_` is not a request IQ type :raises ValueError: if `type_` is not a valid :class:`~.IQType` (and cannot be cast to a :class:`~.IQType`) The callback `cb` will be called whenever an IQ stanza with the given `type_` and payload being an instance of the `payload_cls` is received. The callback must either be a coroutine function or otherwise return an awaitable. The awaitable must evaluate to a valid value for the :attr:`.IQ.payload` attribute. That value will be set as the payload attribute value of an IQ response (with type :attr:`~.IQType.RESULT`) which is generated and sent by the stream. If the awaitable or the function raises an exception, it will be converted to a :class:`~.stanza.Error` object. That error object is then used as payload for an IQ response (with type :attr:`~.IQType.ERROR`) which is generated and sent by the stream. If the exception is a subclass of :class:`aioxmpp.errors.XMPPError`, it is converted to an :class:`~.stanza.Error` instance directly. Otherwise, it is wrapped in a :class:`aioxmpp.XMPPCancelError` with ``undefined-condition``. For this to work, `payload_cls` *must* be registered using :meth:`~.IQ.as_payload_class`. Otherwise, the payload will not be recognised by the stream parser and the IQ is automatically responded to with a ``feature-not-implemented`` error. .. warning:: When using a coroutine function for `cb`, there is no guarantee that concurrent IQ handlers and other coroutines will execute in any defined order. This implies that the strong ordering guarantees normally provided by XMPP XML Streams are lost when using coroutine functions for `cb`. For this reason, the use of non-coroutine functions is allowed. .. note:: Using a non-coroutine function for `cb` will generally lead to less readable code. For the sake of readability, it is recommended to prefer coroutine functions when strong ordering guarantees are not needed. .. versionadded:: 0.11 When the argument `with_send_reply` is true `cb` will be called with two arguments: the IQ stanza to handle and a unary function `send_reply(result=None)` that sends a response to the IQ request and prevents that an automatic response is sent. If `result` is an instance of :class:`~aioxmpp.XMPPError` an error result is generated. This is useful when the handler function needs to execute actions which happen after the IQ result has been sent, for example, sending other stanzas. .. versionchanged:: 0.10 Accepts an awaitable as last argument in addition to coroutine functions. Renamed from :meth:`register_iq_request_coro`. .. versionadded:: 0.6 If the stream is :meth:`stop`\\ -ped (only if SM is not enabled) or :meth:`close`\\ ed, running IQ response coroutines are :meth:`asyncio.Task.cancel`\\ -led. To protect against that, fork from your coroutine using :func:`asyncio.ensure_future`. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.IQType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1394-L1511
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.unregister_iq_request_handler
def unregister_iq_request_handler(self, type_, payload_cls): """ Unregister a coroutine previously registered with :meth:`register_iq_request_handler`. :param type_: IQ type to react to (must be a request type). :type type_: :class:`~structs.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :raises KeyError: if no coroutine has been registered for the given ``(type_, payload_cls)`` pair :raises ValueError: if `type_` is not a valid :class:`~.IQType` (and cannot be cast to a :class:`~.IQType`) The match is solely made using the `type_` and `payload_cls` arguments, which have the same meaning as in :meth:`register_iq_request_coro`. .. versionchanged:: 0.10 Renamed from :meth:`unregister_iq_request_coro`. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.IQType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. """ type_ = self._coerce_enum(type_, structs.IQType) del self._iq_request_map[type_, payload_cls] self._logger.debug( "iq request coroutine unregistered: type=%r, payload=%r", type_, payload_cls)
python
def unregister_iq_request_handler(self, type_, payload_cls): """ Unregister a coroutine previously registered with :meth:`register_iq_request_handler`. :param type_: IQ type to react to (must be a request type). :type type_: :class:`~structs.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :raises KeyError: if no coroutine has been registered for the given ``(type_, payload_cls)`` pair :raises ValueError: if `type_` is not a valid :class:`~.IQType` (and cannot be cast to a :class:`~.IQType`) The match is solely made using the `type_` and `payload_cls` arguments, which have the same meaning as in :meth:`register_iq_request_coro`. .. versionchanged:: 0.10 Renamed from :meth:`unregister_iq_request_coro`. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.IQType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. """ type_ = self._coerce_enum(type_, structs.IQType) del self._iq_request_map[type_, payload_cls] self._logger.debug( "iq request coroutine unregistered: type=%r, payload=%r", type_, payload_cls)
Unregister a coroutine previously registered with :meth:`register_iq_request_handler`. :param type_: IQ type to react to (must be a request type). :type type_: :class:`~structs.IQType` :param payload_cls: Payload class to react to (subclass of :class:`~xso.XSO`) :type payload_cls: :class:`~.XMLStreamClass` :raises KeyError: if no coroutine has been registered for the given ``(type_, payload_cls)`` pair :raises ValueError: if `type_` is not a valid :class:`~.IQType` (and cannot be cast to a :class:`~.IQType`) The match is solely made using the `type_` and `payload_cls` arguments, which have the same meaning as in :meth:`register_iq_request_coro`. .. versionchanged:: 0.10 Renamed from :meth:`unregister_iq_request_coro`. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.IQType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1522-L1561
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.register_message_callback
def register_message_callback(self, type_, from_, cb): """ Register a callback to be called when a message is received. :param type_: Message type to listen for, or :data:`None` for a wildcard match. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None` :param cb: Callback function to call :raises ValueError: if another function is already registered for the same ``(type_, from_)`` pair. :raises ValueError: if `type_` is not a valid :class:`~.MessageType` (and cannot be cast to a :class:`~.MessageType`) `cb` will be called whenever a message stanza matching the `type_` and `from_` is received, according to the wildcarding rules below. More specific callbacks win over less specific callbacks, and the match on the `from_` address takes precedence over the match on the `type_`. See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact wildcarding rules. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.MessageType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated in favour of and is now implemented in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher` service. It is equivalent to call :meth:`~.SimpleStanzaDispatcher.register_callback`, except that the latter is not deprecated. """ if type_ is not None: type_ = self._coerce_enum(type_, structs.MessageType) warnings.warn( "register_message_callback is deprecated; use " "aioxmpp.dispatcher.SimpleMessageDispatcher instead", DeprecationWarning, stacklevel=2 ) self._xxx_message_dispatcher.register_callback( type_, from_, cb, )
python
def register_message_callback(self, type_, from_, cb): """ Register a callback to be called when a message is received. :param type_: Message type to listen for, or :data:`None` for a wildcard match. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None` :param cb: Callback function to call :raises ValueError: if another function is already registered for the same ``(type_, from_)`` pair. :raises ValueError: if `type_` is not a valid :class:`~.MessageType` (and cannot be cast to a :class:`~.MessageType`) `cb` will be called whenever a message stanza matching the `type_` and `from_` is received, according to the wildcarding rules below. More specific callbacks win over less specific callbacks, and the match on the `from_` address takes precedence over the match on the `type_`. See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact wildcarding rules. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.MessageType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated in favour of and is now implemented in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher` service. It is equivalent to call :meth:`~.SimpleStanzaDispatcher.register_callback`, except that the latter is not deprecated. """ if type_ is not None: type_ = self._coerce_enum(type_, structs.MessageType) warnings.warn( "register_message_callback is deprecated; use " "aioxmpp.dispatcher.SimpleMessageDispatcher instead", DeprecationWarning, stacklevel=2 ) self._xxx_message_dispatcher.register_callback( type_, from_, cb, )
Register a callback to be called when a message is received. :param type_: Message type to listen for, or :data:`None` for a wildcard match. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None` :param cb: Callback function to call :raises ValueError: if another function is already registered for the same ``(type_, from_)`` pair. :raises ValueError: if `type_` is not a valid :class:`~.MessageType` (and cannot be cast to a :class:`~.MessageType`) `cb` will be called whenever a message stanza matching the `type_` and `from_` is received, according to the wildcarding rules below. More specific callbacks win over less specific callbacks, and the match on the `from_` address takes precedence over the match on the `type_`. See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact wildcarding rules. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.MessageType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated in favour of and is now implemented in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher` service. It is equivalent to call :meth:`~.SimpleStanzaDispatcher.register_callback`, except that the latter is not deprecated.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1563-L1622
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.unregister_message_callback
def unregister_message_callback(self, type_, from_): """ Unregister a callback previously registered with :meth:`register_message_callback`. :param type_: Message type to listen for. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for. :type from_: :class:`~aioxmpp.JID` or :data:`None` :raises KeyError: if no function is currently registered for the given ``(type_, from_)`` pair. :raises ValueError: if `type_` is not a valid :class:`~.MessageType` (and cannot be cast to a :class:`~.MessageType`) The match is made on the exact pair; it is not possible to unregister arbitrary listeners by passing :data:`None` to both arguments (i.e. the wildcarding only applies for receiving stanzas, not for unregistering callbacks; unregistering the super-wildcard with both arguments set to :data:`None` is of course possible). .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.MessageType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated in favour of and is now implemented in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher` service. It is equivalent to call :meth:`~.SimpleStanzaDispatcher.unregister_callback`, except that the latter is not deprecated. """ if type_ is not None: type_ = self._coerce_enum(type_, structs.MessageType) warnings.warn( "unregister_message_callback is deprecated; use " "aioxmpp.dispatcher.SimpleMessageDispatcher instead", DeprecationWarning, stacklevel=2 ) self._xxx_message_dispatcher.unregister_callback( type_, from_, )
python
def unregister_message_callback(self, type_, from_): """ Unregister a callback previously registered with :meth:`register_message_callback`. :param type_: Message type to listen for. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for. :type from_: :class:`~aioxmpp.JID` or :data:`None` :raises KeyError: if no function is currently registered for the given ``(type_, from_)`` pair. :raises ValueError: if `type_` is not a valid :class:`~.MessageType` (and cannot be cast to a :class:`~.MessageType`) The match is made on the exact pair; it is not possible to unregister arbitrary listeners by passing :data:`None` to both arguments (i.e. the wildcarding only applies for receiving stanzas, not for unregistering callbacks; unregistering the super-wildcard with both arguments set to :data:`None` is of course possible). .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.MessageType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated in favour of and is now implemented in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher` service. It is equivalent to call :meth:`~.SimpleStanzaDispatcher.unregister_callback`, except that the latter is not deprecated. """ if type_ is not None: type_ = self._coerce_enum(type_, structs.MessageType) warnings.warn( "unregister_message_callback is deprecated; use " "aioxmpp.dispatcher.SimpleMessageDispatcher instead", DeprecationWarning, stacklevel=2 ) self._xxx_message_dispatcher.unregister_callback( type_, from_, )
Unregister a callback previously registered with :meth:`register_message_callback`. :param type_: Message type to listen for. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for. :type from_: :class:`~aioxmpp.JID` or :data:`None` :raises KeyError: if no function is currently registered for the given ``(type_, from_)`` pair. :raises ValueError: if `type_` is not a valid :class:`~.MessageType` (and cannot be cast to a :class:`~.MessageType`) The match is made on the exact pair; it is not possible to unregister arbitrary listeners by passing :data:`None` to both arguments (i.e. the wildcarding only applies for receiving stanzas, not for unregistering callbacks; unregistering the super-wildcard with both arguments set to :data:`None` is of course possible). .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.MessageType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated in favour of and is now implemented in terms of the :class:`aioxmpp.dispatcher.SimpleMessageDispatcher` service. It is equivalent to call :meth:`~.SimpleStanzaDispatcher.unregister_callback`, except that the latter is not deprecated.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1624-L1678
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.register_presence_callback
def register_presence_callback(self, type_, from_, cb): """ Register a callback to be called when a presence stanza is received. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback function :raises ValueError: if another listener with the same ``(type_, from_)`` pair is already registered :raises ValueError: if `type_` is not a valid :class:`~.PresenceType` (and cannot be cast to a :class:`~.PresenceType`) `cb` will be called whenever a presence stanza matching the `type_` is received from the specified sender. `from_` may be :data:`None` to indicate a wildcard. Like with :meth:`register_message_callback`, more specific callbacks win over less specific callbacks. The fallback order is identical, except that the ``type_=None`` entries described there do not apply for presence stanzas and are thus omitted. See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact wildcarding rules. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.PresenceType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated. It is recommended to use :class:`aioxmpp.PresenceClient` instead. """ type_ = self._coerce_enum(type_, structs.PresenceType) warnings.warn( "register_presence_callback is deprecated; use " "aioxmpp.dispatcher.SimplePresenceDispatcher or " "aioxmpp.PresenceClient instead", DeprecationWarning, stacklevel=2 ) self._xxx_presence_dispatcher.register_callback( type_, from_, cb, )
python
def register_presence_callback(self, type_, from_, cb): """ Register a callback to be called when a presence stanza is received. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback function :raises ValueError: if another listener with the same ``(type_, from_)`` pair is already registered :raises ValueError: if `type_` is not a valid :class:`~.PresenceType` (and cannot be cast to a :class:`~.PresenceType`) `cb` will be called whenever a presence stanza matching the `type_` is received from the specified sender. `from_` may be :data:`None` to indicate a wildcard. Like with :meth:`register_message_callback`, more specific callbacks win over less specific callbacks. The fallback order is identical, except that the ``type_=None`` entries described there do not apply for presence stanzas and are thus omitted. See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact wildcarding rules. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.PresenceType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated. It is recommended to use :class:`aioxmpp.PresenceClient` instead. """ type_ = self._coerce_enum(type_, structs.PresenceType) warnings.warn( "register_presence_callback is deprecated; use " "aioxmpp.dispatcher.SimplePresenceDispatcher or " "aioxmpp.PresenceClient instead", DeprecationWarning, stacklevel=2 ) self._xxx_presence_dispatcher.register_callback( type_, from_, cb, )
Register a callback to be called when a presence stanza is received. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback function :raises ValueError: if another listener with the same ``(type_, from_)`` pair is already registered :raises ValueError: if `type_` is not a valid :class:`~.PresenceType` (and cannot be cast to a :class:`~.PresenceType`) `cb` will be called whenever a presence stanza matching the `type_` is received from the specified sender. `from_` may be :data:`None` to indicate a wildcard. Like with :meth:`register_message_callback`, more specific callbacks win over less specific callbacks. The fallback order is identical, except that the ``type_=None`` entries described there do not apply for presence stanzas and are thus omitted. See :meth:`.SimpleStanzaDispatcher.register_callback` for the exact wildcarding rules. .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.PresenceType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated. It is recommended to use :class:`aioxmpp.PresenceClient` instead.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1680-L1736
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.unregister_presence_callback
def unregister_presence_callback(self, type_, from_): """ Unregister a callback previously registered with :meth:`register_presence_callback`. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :raises KeyError: if no callback is currently registered for the given ``(type_, from_)`` pair :raises ValueError: if `type_` is not a valid :class:`~.PresenceType` (and cannot be cast to a :class:`~.PresenceType`) The match is made on the exact pair; it is not possible to unregister arbitrary listeners by passing :data:`None` to the `from_` arguments (i.e. the wildcarding only applies for receiving stanzas, not for unregistering callbacks; unregistering a wildcard match with `from_` set to :data:`None` is of course possible). .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.PresenceType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated. It is recommended to use :class:`aioxmpp.PresenceClient` instead. """ type_ = self._coerce_enum(type_, structs.PresenceType) warnings.warn( "unregister_presence_callback is deprecated; use " "aioxmpp.dispatcher.SimplePresenceDispatcher or " "aioxmpp.PresenceClient instead", DeprecationWarning, stacklevel=2 ) self._xxx_presence_dispatcher.unregister_callback( type_, from_, )
python
def unregister_presence_callback(self, type_, from_): """ Unregister a callback previously registered with :meth:`register_presence_callback`. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :raises KeyError: if no callback is currently registered for the given ``(type_, from_)`` pair :raises ValueError: if `type_` is not a valid :class:`~.PresenceType` (and cannot be cast to a :class:`~.PresenceType`) The match is made on the exact pair; it is not possible to unregister arbitrary listeners by passing :data:`None` to the `from_` arguments (i.e. the wildcarding only applies for receiving stanzas, not for unregistering callbacks; unregistering a wildcard match with `from_` set to :data:`None` is of course possible). .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.PresenceType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated. It is recommended to use :class:`aioxmpp.PresenceClient` instead. """ type_ = self._coerce_enum(type_, structs.PresenceType) warnings.warn( "unregister_presence_callback is deprecated; use " "aioxmpp.dispatcher.SimplePresenceDispatcher or " "aioxmpp.PresenceClient instead", DeprecationWarning, stacklevel=2 ) self._xxx_presence_dispatcher.unregister_callback( type_, from_, )
Unregister a callback previously registered with :meth:`register_presence_callback`. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :raises KeyError: if no callback is currently registered for the given ``(type_, from_)`` pair :raises ValueError: if `type_` is not a valid :class:`~.PresenceType` (and cannot be cast to a :class:`~.PresenceType`) The match is made on the exact pair; it is not possible to unregister arbitrary listeners by passing :data:`None` to the `from_` arguments (i.e. the wildcarding only applies for receiving stanzas, not for unregistering callbacks; unregistering a wildcard match with `from_` set to :data:`None` is of course possible). .. versionchanged:: 0.7 The `type_` argument is now supposed to be a :class:`~.PresenceType` member. .. deprecated:: 0.7 Passing a :class:`str` as `type_` argument is deprecated and will raise a :class:`TypeError` as of the 1.0 release. See the Changelog for :ref:`api-changelog-0.7` for further details on how to upgrade your code efficiently. .. deprecated:: 0.9 This method has been deprecated. It is recommended to use :class:`aioxmpp.PresenceClient` instead.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1738-L1789
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.start
def start(self, xmlstream): """ Start or resume the stanza stream on the given :class:`aioxmpp.protocol.XMLStream` `xmlstream`. This starts the main broker task, registers stanza classes at the `xmlstream` . """ if self.running: raise RuntimeError("already started") self._start_prepare(xmlstream, self.recv_stanza) self._closed = False self._start_commit(xmlstream)
python
def start(self, xmlstream): """ Start or resume the stanza stream on the given :class:`aioxmpp.protocol.XMLStream` `xmlstream`. This starts the main broker task, registers stanza classes at the `xmlstream` . """ if self.running: raise RuntimeError("already started") self._start_prepare(xmlstream, self.recv_stanza) self._closed = False self._start_commit(xmlstream)
Start or resume the stanza stream on the given :class:`aioxmpp.protocol.XMLStream` `xmlstream`. This starts the main broker task, registers stanza classes at the `xmlstream` .
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1878-L1892
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.stop
def stop(self): """ Send a signal to the main broker task to terminate. You have to check :attr:`running` and possibly wait for it to become :data:`False` --- the task takes at least one loop through the event loop to terminate. It is guarenteed that the task will not attempt to send stanzas over the existing `xmlstream` after a call to :meth:`stop` has been made. It is legal to call :meth:`stop` even if the task is already stopped. It is a no-op in that case. """ if not self.running: return self._logger.debug("sending stop signal to task") self._task.cancel()
python
def stop(self): """ Send a signal to the main broker task to terminate. You have to check :attr:`running` and possibly wait for it to become :data:`False` --- the task takes at least one loop through the event loop to terminate. It is guarenteed that the task will not attempt to send stanzas over the existing `xmlstream` after a call to :meth:`stop` has been made. It is legal to call :meth:`stop` even if the task is already stopped. It is a no-op in that case. """ if not self.running: return self._logger.debug("sending stop signal to task") self._task.cancel()
Send a signal to the main broker task to terminate. You have to check :attr:`running` and possibly wait for it to become :data:`False` --- the task takes at least one loop through the event loop to terminate. It is guarenteed that the task will not attempt to send stanzas over the existing `xmlstream` after a call to :meth:`stop` has been made. It is legal to call :meth:`stop` even if the task is already stopped. It is a no-op in that case.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1894-L1909
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.wait_stop
def wait_stop(self): """ Stop the stream and wait for it to stop. See :meth:`stop` for the general stopping conditions. You can assume that :meth:`stop` is the first thing this coroutine calls. """ if not self.running: return self.stop() try: yield from self._task except asyncio.CancelledError: pass
python
def wait_stop(self): """ Stop the stream and wait for it to stop. See :meth:`stop` for the general stopping conditions. You can assume that :meth:`stop` is the first thing this coroutine calls. """ if not self.running: return self.stop() try: yield from self._task except asyncio.CancelledError: pass
Stop the stream and wait for it to stop. See :meth:`stop` for the general stopping conditions. You can assume that :meth:`stop` is the first thing this coroutine calls.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1912-L1925
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.close
def close(self): """ Close the stream and the underlying XML stream (if any is connected). This is essentially a way of saying "I do not want to use this stream anymore" (until the next call to :meth:`start`). If the stream is currently running, the XML stream is closed gracefully (potentially sending an SM ack), the worker is stopped and any Stream Management state is cleaned up. If an error occurs while the stream stops, the error is ignored. After the call to :meth:`close` has started, :meth:`on_failure` will not be emitted, even if the XML stream fails before closure has completed. After a call to :meth:`close`, the stream is stopped, all SM state is discarded and calls to :meth:`enqueue_stanza` raise a :class:`DestructionRequested` ``"close() called"``. Such a :class:`StanzaStream` can be re-started by calling :meth:`start`. .. versionchanged:: 0.8 Before 0.8, an error during a call to :meth:`close` would stop the stream from closing completely, and the exception was re-raised. If SM was enabled, the state would have been kept, allowing for resumption and ensuring that stanzas still enqueued or unacknowledged would get a chance to be sent. If you want to have guarantees that all stanzas sent up to a certain point are sent, you should be using :meth:`send_and_wait_for_sent` with stream management. """ exc = DestructionRequested("close() called") if self.running: if self.sm_enabled: self._xmlstream.send_xso(nonza.SMAcknowledgement( counter=self._sm_inbound_ctr )) yield from self._xmlstream.close_and_wait() # does not raise yield from self.wait_stop() # may raise self._closed = True self._xmlstream_exception = exc self._destroy_stream_state(self._xmlstream_exception) if self.sm_enabled: self.stop_sm()
python
def close(self): """ Close the stream and the underlying XML stream (if any is connected). This is essentially a way of saying "I do not want to use this stream anymore" (until the next call to :meth:`start`). If the stream is currently running, the XML stream is closed gracefully (potentially sending an SM ack), the worker is stopped and any Stream Management state is cleaned up. If an error occurs while the stream stops, the error is ignored. After the call to :meth:`close` has started, :meth:`on_failure` will not be emitted, even if the XML stream fails before closure has completed. After a call to :meth:`close`, the stream is stopped, all SM state is discarded and calls to :meth:`enqueue_stanza` raise a :class:`DestructionRequested` ``"close() called"``. Such a :class:`StanzaStream` can be re-started by calling :meth:`start`. .. versionchanged:: 0.8 Before 0.8, an error during a call to :meth:`close` would stop the stream from closing completely, and the exception was re-raised. If SM was enabled, the state would have been kept, allowing for resumption and ensuring that stanzas still enqueued or unacknowledged would get a chance to be sent. If you want to have guarantees that all stanzas sent up to a certain point are sent, you should be using :meth:`send_and_wait_for_sent` with stream management. """ exc = DestructionRequested("close() called") if self.running: if self.sm_enabled: self._xmlstream.send_xso(nonza.SMAcknowledgement( counter=self._sm_inbound_ctr )) yield from self._xmlstream.close_and_wait() # does not raise yield from self.wait_stop() # may raise self._closed = True self._xmlstream_exception = exc self._destroy_stream_state(self._xmlstream_exception) if self.sm_enabled: self.stop_sm()
Close the stream and the underlying XML stream (if any is connected). This is essentially a way of saying "I do not want to use this stream anymore" (until the next call to :meth:`start`). If the stream is currently running, the XML stream is closed gracefully (potentially sending an SM ack), the worker is stopped and any Stream Management state is cleaned up. If an error occurs while the stream stops, the error is ignored. After the call to :meth:`close` has started, :meth:`on_failure` will not be emitted, even if the XML stream fails before closure has completed. After a call to :meth:`close`, the stream is stopped, all SM state is discarded and calls to :meth:`enqueue_stanza` raise a :class:`DestructionRequested` ``"close() called"``. Such a :class:`StanzaStream` can be re-started by calling :meth:`start`. .. versionchanged:: 0.8 Before 0.8, an error during a call to :meth:`close` would stop the stream from closing completely, and the exception was re-raised. If SM was enabled, the state would have been kept, allowing for resumption and ensuring that stanzas still enqueued or unacknowledged would get a chance to be sent. If you want to have guarantees that all stanzas sent up to a certain point are sent, you should be using :meth:`send_and_wait_for_sent` with stream management.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L1928-L1976
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.start_sm
def start_sm(self, request_resumption=True, resumption_timeout=None): """ Start stream management (version 3). :param request_resumption: Request that the stream shall be resumable. :type request_resumption: :class:`bool` :param resumption_timeout: Maximum time in seconds for a stream to be resumable. :type resumption_timeout: :class:`int` :raises aioxmpp.errors.StreamNegotiationFailure: if the server rejects the attempt to enable stream management. This method attempts to starts stream management on the stream. `resumption_timeout` is the ``max`` attribute on :class:`.nonza.SMEnabled`; it can be used to set a maximum time for which the server shall consider the stream to still be alive after the underlying transport (TCP) has failed. The server may impose its own maximum or ignore the request, so there are no guarentees that the session will stay alive for at most or at least `resumption_timeout` seconds. Passing a `resumption_timeout` of 0 is equivalent to passing false to `request_resumption` and takes precedence over `request_resumption`. .. note:: In addition to server implementation details, it is very well possible that the server does not even detect that the underlying transport has failed for quite some time for various reasons (including high TCP timeouts). If the server rejects the attempt to enable stream management, a :class:`.errors.StreamNegotiationFailure` is raised. The stream is still running in that case. .. warning:: This method cannot and does not check whether the server advertised support for stream management. Attempting to negotiate stream management without server support might lead to termination of the stream. If an XML stream error occurs during the negotiation, the result depends on a few factors. In any case, the stream is not running afterwards. If the :class:`.nonza.SMEnabled` response was not received before the XML stream died, SM is also disabled and the exception which caused the stream to die is re-raised (this is due to the implementation of :func:`~.protocol.send_and_wait_for`). If the :class:`.nonza.SMEnabled` response was received and annonuced support for resumption, SM is enabled. Otherwise, it is disabled. No exception is raised if :class:`.nonza.SMEnabled` was received, as this method has no way to determine that the stream failed. If negotiation succeeds, this coroutine initializes a new stream management session. The stream management state attributes become available and :attr:`sm_enabled` becomes :data:`True`. """ if not self.running: raise RuntimeError("cannot start Stream Management while" " StanzaStream is not running") if self.sm_enabled: raise RuntimeError("Stream Management already enabled") if resumption_timeout == 0: request_resumption = False resumption_timeout = None # sorry for the callback spaghetti code # we have to handle the response synchronously, so we have to use a # callback. # otherwise, it is possible that an SM related nonza (e.g. <r/>) is # received (and attempted to be deserialized) before the handlers are # registered # see tests/test_highlevel.py:TestProtocoltest_sm_bootstrap_race def handle_response(response): if isinstance(response, nonza.SMFailed): # we handle the error down below return self._sm_outbound_base = 0 self._sm_inbound_ctr = 0 self._sm_unacked_list = [] self._sm_enabled = True self._sm_id = response.id_ self._sm_resumable = response.resume self._sm_max = response.max_ self._sm_location = response.location self._logger.info("SM started: resumable=%s, stream id=%r", self._sm_resumable, self._sm_id) # if not self._xmlstream: # # stream died in the meantime... # if self._xmlstream_exception: # raise self._xmlstream_exception self._xmlstream.stanza_parser.add_class( nonza.SMRequest, self.recv_stanza) self._xmlstream.stanza_parser.add_class( nonza.SMAcknowledgement, self.recv_stanza) with (yield from self._broker_lock): response = yield from protocol.send_and_wait_for( self._xmlstream, [ nonza.SMEnable(resume=bool(request_resumption), max_=resumption_timeout), ], [ nonza.SMEnabled, nonza.SMFailed ], cb=handle_response, ) if isinstance(response, nonza.SMFailed): raise errors.StreamNegotiationFailure( "Server rejected SM request")
python
def start_sm(self, request_resumption=True, resumption_timeout=None): """ Start stream management (version 3). :param request_resumption: Request that the stream shall be resumable. :type request_resumption: :class:`bool` :param resumption_timeout: Maximum time in seconds for a stream to be resumable. :type resumption_timeout: :class:`int` :raises aioxmpp.errors.StreamNegotiationFailure: if the server rejects the attempt to enable stream management. This method attempts to starts stream management on the stream. `resumption_timeout` is the ``max`` attribute on :class:`.nonza.SMEnabled`; it can be used to set a maximum time for which the server shall consider the stream to still be alive after the underlying transport (TCP) has failed. The server may impose its own maximum or ignore the request, so there are no guarentees that the session will stay alive for at most or at least `resumption_timeout` seconds. Passing a `resumption_timeout` of 0 is equivalent to passing false to `request_resumption` and takes precedence over `request_resumption`. .. note:: In addition to server implementation details, it is very well possible that the server does not even detect that the underlying transport has failed for quite some time for various reasons (including high TCP timeouts). If the server rejects the attempt to enable stream management, a :class:`.errors.StreamNegotiationFailure` is raised. The stream is still running in that case. .. warning:: This method cannot and does not check whether the server advertised support for stream management. Attempting to negotiate stream management without server support might lead to termination of the stream. If an XML stream error occurs during the negotiation, the result depends on a few factors. In any case, the stream is not running afterwards. If the :class:`.nonza.SMEnabled` response was not received before the XML stream died, SM is also disabled and the exception which caused the stream to die is re-raised (this is due to the implementation of :func:`~.protocol.send_and_wait_for`). If the :class:`.nonza.SMEnabled` response was received and annonuced support for resumption, SM is enabled. Otherwise, it is disabled. No exception is raised if :class:`.nonza.SMEnabled` was received, as this method has no way to determine that the stream failed. If negotiation succeeds, this coroutine initializes a new stream management session. The stream management state attributes become available and :attr:`sm_enabled` becomes :data:`True`. """ if not self.running: raise RuntimeError("cannot start Stream Management while" " StanzaStream is not running") if self.sm_enabled: raise RuntimeError("Stream Management already enabled") if resumption_timeout == 0: request_resumption = False resumption_timeout = None # sorry for the callback spaghetti code # we have to handle the response synchronously, so we have to use a # callback. # otherwise, it is possible that an SM related nonza (e.g. <r/>) is # received (and attempted to be deserialized) before the handlers are # registered # see tests/test_highlevel.py:TestProtocoltest_sm_bootstrap_race def handle_response(response): if isinstance(response, nonza.SMFailed): # we handle the error down below return self._sm_outbound_base = 0 self._sm_inbound_ctr = 0 self._sm_unacked_list = [] self._sm_enabled = True self._sm_id = response.id_ self._sm_resumable = response.resume self._sm_max = response.max_ self._sm_location = response.location self._logger.info("SM started: resumable=%s, stream id=%r", self._sm_resumable, self._sm_id) # if not self._xmlstream: # # stream died in the meantime... # if self._xmlstream_exception: # raise self._xmlstream_exception self._xmlstream.stanza_parser.add_class( nonza.SMRequest, self.recv_stanza) self._xmlstream.stanza_parser.add_class( nonza.SMAcknowledgement, self.recv_stanza) with (yield from self._broker_lock): response = yield from protocol.send_and_wait_for( self._xmlstream, [ nonza.SMEnable(resume=bool(request_resumption), max_=resumption_timeout), ], [ nonza.SMEnabled, nonza.SMFailed ], cb=handle_response, ) if isinstance(response, nonza.SMFailed): raise errors.StreamNegotiationFailure( "Server rejected SM request")
Start stream management (version 3). :param request_resumption: Request that the stream shall be resumable. :type request_resumption: :class:`bool` :param resumption_timeout: Maximum time in seconds for a stream to be resumable. :type resumption_timeout: :class:`int` :raises aioxmpp.errors.StreamNegotiationFailure: if the server rejects the attempt to enable stream management. This method attempts to starts stream management on the stream. `resumption_timeout` is the ``max`` attribute on :class:`.nonza.SMEnabled`; it can be used to set a maximum time for which the server shall consider the stream to still be alive after the underlying transport (TCP) has failed. The server may impose its own maximum or ignore the request, so there are no guarentees that the session will stay alive for at most or at least `resumption_timeout` seconds. Passing a `resumption_timeout` of 0 is equivalent to passing false to `request_resumption` and takes precedence over `request_resumption`. .. note:: In addition to server implementation details, it is very well possible that the server does not even detect that the underlying transport has failed for quite some time for various reasons (including high TCP timeouts). If the server rejects the attempt to enable stream management, a :class:`.errors.StreamNegotiationFailure` is raised. The stream is still running in that case. .. warning:: This method cannot and does not check whether the server advertised support for stream management. Attempting to negotiate stream management without server support might lead to termination of the stream. If an XML stream error occurs during the negotiation, the result depends on a few factors. In any case, the stream is not running afterwards. If the :class:`.nonza.SMEnabled` response was not received before the XML stream died, SM is also disabled and the exception which caused the stream to die is re-raised (this is due to the implementation of :func:`~.protocol.send_and_wait_for`). If the :class:`.nonza.SMEnabled` response was received and annonuced support for resumption, SM is enabled. Otherwise, it is disabled. No exception is raised if :class:`.nonza.SMEnabled` was received, as this method has no way to determine that the stream failed. If negotiation succeeds, this coroutine initializes a new stream management session. The stream management state attributes become available and :attr:`sm_enabled` becomes :data:`True`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2090-L2210
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._resume_sm
def _resume_sm(self, remote_ctr): """ Version of :meth:`resume_sm` which can be used during slow start. """ self._logger.info("resuming SM stream with remote_ctr=%d", remote_ctr) # remove any acked stanzas self.sm_ack(remote_ctr) # reinsert the remaining stanzas for token in self._sm_unacked_list: self._active_queue.putleft_nowait(token) self._sm_unacked_list.clear()
python
def _resume_sm(self, remote_ctr): """ Version of :meth:`resume_sm` which can be used during slow start. """ self._logger.info("resuming SM stream with remote_ctr=%d", remote_ctr) # remove any acked stanzas self.sm_ack(remote_ctr) # reinsert the remaining stanzas for token in self._sm_unacked_list: self._active_queue.putleft_nowait(token) self._sm_unacked_list.clear()
Version of :meth:`resume_sm` which can be used during slow start.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2341-L2351
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.resume_sm
def resume_sm(self, xmlstream): """ Resume an SM-enabled stream using the given `xmlstream`. If the server rejects the attempt to resume stream management, a :class:`.errors.StreamNegotiationFailure` is raised. The stream is then in stopped state and stream management has been stopped. .. warning:: This method cannot and does not check whether the server advertised support for stream management. Attempting to negotiate stream management without server support might lead to termination of the stream. If the XML stream dies at any point during the negotiation, the SM state is left unchanged. If no response has been received yet, the exception which caused the stream to die is re-raised. The state of the stream depends on whether the main task already noticed the dead stream. If negotiation succeeds, this coroutine resumes the stream management session and initiates the retransmission of any unacked stanzas. The stream is then in running state. .. versionchanged:: 0.11 Support for using the counter value provided some servers on a failed resumption was added. Stanzas which are covered by the counter will be marked as :attr:`~StanzaState.ACKED`; other stanzas will be marked as :attr:`~StanzaState.DISCONNECTED`. This is in contrast to the behaviour when resumption fails *without* a counter given. In that case, stanzas which have not been acked are marked as :attr:`~StanzaState.SENT_WITHOUT_SM`. """ if self.running: raise RuntimeError("Cannot resume Stream Management while" " StanzaStream is running") self._start_prepare(xmlstream, self.recv_stanza) try: response = yield from protocol.send_and_wait_for( xmlstream, [ nonza.SMResume(previd=self.sm_id, counter=self._sm_inbound_ctr) ], [ nonza.SMResumed, nonza.SMFailed ] ) if isinstance(response, nonza.SMFailed): exc = errors.StreamNegotiationFailure( "Server rejected SM resumption" ) if response.counter is not None: self.sm_ack(response.counter) self._clear_unacked(StanzaState.DISCONNECTED) xmlstream.stanza_parser.remove_class( nonza.SMRequest) xmlstream.stanza_parser.remove_class( nonza.SMAcknowledgement) self.stop_sm() raise exc self._resume_sm(response.counter) except: # NOQA self._start_rollback(xmlstream) raise self._start_commit(xmlstream)
python
def resume_sm(self, xmlstream): """ Resume an SM-enabled stream using the given `xmlstream`. If the server rejects the attempt to resume stream management, a :class:`.errors.StreamNegotiationFailure` is raised. The stream is then in stopped state and stream management has been stopped. .. warning:: This method cannot and does not check whether the server advertised support for stream management. Attempting to negotiate stream management without server support might lead to termination of the stream. If the XML stream dies at any point during the negotiation, the SM state is left unchanged. If no response has been received yet, the exception which caused the stream to die is re-raised. The state of the stream depends on whether the main task already noticed the dead stream. If negotiation succeeds, this coroutine resumes the stream management session and initiates the retransmission of any unacked stanzas. The stream is then in running state. .. versionchanged:: 0.11 Support for using the counter value provided some servers on a failed resumption was added. Stanzas which are covered by the counter will be marked as :attr:`~StanzaState.ACKED`; other stanzas will be marked as :attr:`~StanzaState.DISCONNECTED`. This is in contrast to the behaviour when resumption fails *without* a counter given. In that case, stanzas which have not been acked are marked as :attr:`~StanzaState.SENT_WITHOUT_SM`. """ if self.running: raise RuntimeError("Cannot resume Stream Management while" " StanzaStream is running") self._start_prepare(xmlstream, self.recv_stanza) try: response = yield from protocol.send_and_wait_for( xmlstream, [ nonza.SMResume(previd=self.sm_id, counter=self._sm_inbound_ctr) ], [ nonza.SMResumed, nonza.SMFailed ] ) if isinstance(response, nonza.SMFailed): exc = errors.StreamNegotiationFailure( "Server rejected SM resumption" ) if response.counter is not None: self.sm_ack(response.counter) self._clear_unacked(StanzaState.DISCONNECTED) xmlstream.stanza_parser.remove_class( nonza.SMRequest) xmlstream.stanza_parser.remove_class( nonza.SMAcknowledgement) self.stop_sm() raise exc self._resume_sm(response.counter) except: # NOQA self._start_rollback(xmlstream) raise self._start_commit(xmlstream)
Resume an SM-enabled stream using the given `xmlstream`. If the server rejects the attempt to resume stream management, a :class:`.errors.StreamNegotiationFailure` is raised. The stream is then in stopped state and stream management has been stopped. .. warning:: This method cannot and does not check whether the server advertised support for stream management. Attempting to negotiate stream management without server support might lead to termination of the stream. If the XML stream dies at any point during the negotiation, the SM state is left unchanged. If no response has been received yet, the exception which caused the stream to die is re-raised. The state of the stream depends on whether the main task already noticed the dead stream. If negotiation succeeds, this coroutine resumes the stream management session and initiates the retransmission of any unacked stanzas. The stream is then in running state. .. versionchanged:: 0.11 Support for using the counter value provided some servers on a failed resumption was added. Stanzas which are covered by the counter will be marked as :attr:`~StanzaState.ACKED`; other stanzas will be marked as :attr:`~StanzaState.DISCONNECTED`. This is in contrast to the behaviour when resumption fails *without* a counter given. In that case, stanzas which have not been acked are marked as :attr:`~StanzaState.SENT_WITHOUT_SM`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2359-L2434
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._stop_sm
def _stop_sm(self): """ Version of :meth:`stop_sm` which can be called during startup. """ if not self.sm_enabled: raise RuntimeError("Stream Management is not enabled") self._logger.info("stopping SM stream") self._sm_enabled = False del self._sm_outbound_base del self._sm_inbound_ctr self._clear_unacked(StanzaState.SENT_WITHOUT_SM) del self._sm_unacked_list self._destroy_stream_state(ConnectionError( "stream management disabled" ))
python
def _stop_sm(self): """ Version of :meth:`stop_sm` which can be called during startup. """ if not self.sm_enabled: raise RuntimeError("Stream Management is not enabled") self._logger.info("stopping SM stream") self._sm_enabled = False del self._sm_outbound_base del self._sm_inbound_ctr self._clear_unacked(StanzaState.SENT_WITHOUT_SM) del self._sm_unacked_list self._destroy_stream_state(ConnectionError( "stream management disabled" ))
Version of :meth:`stop_sm` which can be called during startup.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2436-L2452
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.sm_ack
def sm_ack(self, remote_ctr): """ Process the remote stanza counter `remote_ctr`. Any acked stanzas are dropped from :attr:`sm_unacked_list` and put into :attr:`StanzaState.ACKED` state and the counters are increased accordingly. If called with an erroneous remote stanza counter :class:`.errors.StreamNegotationFailure` will be raised. Attempting to call this without Stream Management enabled results in a :class:`RuntimeError`. """ if not self._sm_enabled: raise RuntimeError("Stream Management is not enabled") self._logger.debug("sm_ack(%d)", remote_ctr) to_drop = (remote_ctr - self._sm_outbound_base) & 0xffffffff self._logger.debug("sm_ack: to drop %d, unacked: %d", to_drop, len(self._sm_unacked_list)) if to_drop > len(self._sm_unacked_list): raise errors.StreamNegotiationFailure( "acked more stanzas than have been sent " "(outbound_base={}, remote_ctr={})".format( self._sm_outbound_base, remote_ctr ) ) acked = self._sm_unacked_list[:to_drop] del self._sm_unacked_list[:to_drop] self._sm_outbound_base = remote_ctr if acked: self._logger.debug("%d stanzas acked by remote", len(acked)) for token in acked: token._set_state(StanzaState.ACKED)
python
def sm_ack(self, remote_ctr): """ Process the remote stanza counter `remote_ctr`. Any acked stanzas are dropped from :attr:`sm_unacked_list` and put into :attr:`StanzaState.ACKED` state and the counters are increased accordingly. If called with an erroneous remote stanza counter :class:`.errors.StreamNegotationFailure` will be raised. Attempting to call this without Stream Management enabled results in a :class:`RuntimeError`. """ if not self._sm_enabled: raise RuntimeError("Stream Management is not enabled") self._logger.debug("sm_ack(%d)", remote_ctr) to_drop = (remote_ctr - self._sm_outbound_base) & 0xffffffff self._logger.debug("sm_ack: to drop %d, unacked: %d", to_drop, len(self._sm_unacked_list)) if to_drop > len(self._sm_unacked_list): raise errors.StreamNegotiationFailure( "acked more stanzas than have been sent " "(outbound_base={}, remote_ctr={})".format( self._sm_outbound_base, remote_ctr ) ) acked = self._sm_unacked_list[:to_drop] del self._sm_unacked_list[:to_drop] self._sm_outbound_base = remote_ctr if acked: self._logger.debug("%d stanzas acked by remote", len(acked)) for token in acked: token._set_state(StanzaState.ACKED)
Process the remote stanza counter `remote_ctr`. Any acked stanzas are dropped from :attr:`sm_unacked_list` and put into :attr:`StanzaState.ACKED` state and the counters are increased accordingly. If called with an erroneous remote stanza counter :class:`.errors.StreamNegotationFailure` will be raised. Attempting to call this without Stream Management enabled results in a :class:`RuntimeError`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2469-L2506
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.send_iq_and_wait_for_reply
def send_iq_and_wait_for_reply(self, iq, *, timeout=None): """ Send an IQ stanza `iq` and wait for the response. If `timeout` is not :data:`None`, it must be the time in seconds for which to wait for a response. If the response is a ``"result"`` IQ, the value of the :attr:`~aioxmpp.IQ.payload` attribute is returned. Otherwise, the exception generated from the :attr:`~aioxmpp.IQ.error` attribute is raised. .. seealso:: :meth:`register_iq_response_future` and :meth:`send_and_wait_for_sent` for other cases raising exceptions. .. deprecated:: 0.8 This method will be removed in 1.0. Use :meth:`send` instead. .. versionchanged:: 0.8 On a timeout, :class:`TimeoutError` is now raised instead of :class:`asyncio.TimeoutError`. """ warnings.warn( r"send_iq_and_wait_for_reply is deprecated and will be removed in" r" 1.0", DeprecationWarning, stacklevel=1, ) return (yield from self.send(iq, timeout=timeout))
python
def send_iq_and_wait_for_reply(self, iq, *, timeout=None): """ Send an IQ stanza `iq` and wait for the response. If `timeout` is not :data:`None`, it must be the time in seconds for which to wait for a response. If the response is a ``"result"`` IQ, the value of the :attr:`~aioxmpp.IQ.payload` attribute is returned. Otherwise, the exception generated from the :attr:`~aioxmpp.IQ.error` attribute is raised. .. seealso:: :meth:`register_iq_response_future` and :meth:`send_and_wait_for_sent` for other cases raising exceptions. .. deprecated:: 0.8 This method will be removed in 1.0. Use :meth:`send` instead. .. versionchanged:: 0.8 On a timeout, :class:`TimeoutError` is now raised instead of :class:`asyncio.TimeoutError`. """ warnings.warn( r"send_iq_and_wait_for_reply is deprecated and will be removed in" r" 1.0", DeprecationWarning, stacklevel=1, ) return (yield from self.send(iq, timeout=timeout))
Send an IQ stanza `iq` and wait for the response. If `timeout` is not :data:`None`, it must be the time in seconds for which to wait for a response. If the response is a ``"result"`` IQ, the value of the :attr:`~aioxmpp.IQ.payload` attribute is returned. Otherwise, the exception generated from the :attr:`~aioxmpp.IQ.error` attribute is raised. .. seealso:: :meth:`register_iq_response_future` and :meth:`send_and_wait_for_sent` for other cases raising exceptions. .. deprecated:: 0.8 This method will be removed in 1.0. Use :meth:`send` instead. .. versionchanged:: 0.8 On a timeout, :class:`TimeoutError` is now raised instead of :class:`asyncio.TimeoutError`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2509-L2542
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream.send_and_wait_for_sent
def send_and_wait_for_sent(self, stanza): """ Send the given `stanza` over the given :class:`StanzaStream` `stream`. .. deprecated:: 0.8 This method will be removed in 1.0. Use :meth:`send` instead. """ warnings.warn( r"send_and_wait_for_sent is deprecated and will be removed in 1.0", DeprecationWarning, stacklevel=1, ) yield from self._enqueue(stanza)
python
def send_and_wait_for_sent(self, stanza): """ Send the given `stanza` over the given :class:`StanzaStream` `stream`. .. deprecated:: 0.8 This method will be removed in 1.0. Use :meth:`send` instead. """ warnings.warn( r"send_and_wait_for_sent is deprecated and will be removed in 1.0", DeprecationWarning, stacklevel=1, ) yield from self._enqueue(stanza)
Send the given `stanza` over the given :class:`StanzaStream` `stream`. .. deprecated:: 0.8 This method will be removed in 1.0. Use :meth:`send` instead.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2545-L2558
horazont/aioxmpp
aioxmpp/stream.py
StanzaStream._send_immediately
def _send_immediately(self, stanza, *, timeout=None, cb=None): """ Send a stanza without waiting for the stream to be ready to send stanzas. This is only useful from within :class:`aioxmpp.node.Client` before the stream is fully established. """ stanza.autoset_id() self._logger.debug("sending %r and waiting for it to be sent", stanza) if not isinstance(stanza, stanza_.IQ) or stanza.type_.is_response: if cb is not None: raise ValueError( "cb not supported with non-IQ non-request stanzas" ) yield from self._enqueue(stanza) return # we use the long way with a custom listener instead of a future here # to ensure that the callback is called synchronously from within the # queue handling loop. # we need that to ensure that the strong ordering guarantees reach the # `cb` function. fut = asyncio.Future() def nested_cb(task): """ This callback is used to handle awaitables returned by the `cb`. """ nonlocal fut if task.exception() is None: fut.set_result(task.result()) else: fut.set_exception(task.exception()) def handler_ok(stanza): """ This handler is invoked synchronously by :meth:`_process_incoming_iq` (via :class:`aioxmpp.callbacks.TagDispatcher`) for response stanzas (including error stanzas). """ nonlocal fut if fut.cancelled(): return if cb is not None: try: nested_fut = cb(stanza) except Exception as exc: fut.set_exception(exc) else: if nested_fut is not None: nested_fut.add_done_callback(nested_cb) return # we can’t even use StanzaErrorAwareListener because we want to # forward error stanzas to the cb too... if stanza.type_.is_error: fut.set_exception(stanza.error.to_exception()) else: fut.set_result(stanza.payload) def handler_error(exc): """ This handler is invoked synchronously by :meth:`_process_incoming_iq` (via :class:`aioxmpp.callbacks.TagDispatcher`) for response errors ( such as parsing errors, connection errors, etc.). """ nonlocal fut if fut.cancelled(): return fut.set_exception(exc) listener = callbacks.OneshotTagListener( handler_ok, handler_error, ) listener_tag = (stanza.to, stanza.id_) self._iq_response_map.add_listener( listener_tag, listener, ) try: yield from self._enqueue(stanza) except Exception: listener.cancel() raise try: if not timeout: reply = yield from fut else: try: reply = yield from asyncio.wait_for( fut, timeout=timeout ) except asyncio.TimeoutError: raise TimeoutError finally: try: self._iq_response_map.remove_listener(listener_tag) except KeyError: pass return reply
python
def _send_immediately(self, stanza, *, timeout=None, cb=None): """ Send a stanza without waiting for the stream to be ready to send stanzas. This is only useful from within :class:`aioxmpp.node.Client` before the stream is fully established. """ stanza.autoset_id() self._logger.debug("sending %r and waiting for it to be sent", stanza) if not isinstance(stanza, stanza_.IQ) or stanza.type_.is_response: if cb is not None: raise ValueError( "cb not supported with non-IQ non-request stanzas" ) yield from self._enqueue(stanza) return # we use the long way with a custom listener instead of a future here # to ensure that the callback is called synchronously from within the # queue handling loop. # we need that to ensure that the strong ordering guarantees reach the # `cb` function. fut = asyncio.Future() def nested_cb(task): """ This callback is used to handle awaitables returned by the `cb`. """ nonlocal fut if task.exception() is None: fut.set_result(task.result()) else: fut.set_exception(task.exception()) def handler_ok(stanza): """ This handler is invoked synchronously by :meth:`_process_incoming_iq` (via :class:`aioxmpp.callbacks.TagDispatcher`) for response stanzas (including error stanzas). """ nonlocal fut if fut.cancelled(): return if cb is not None: try: nested_fut = cb(stanza) except Exception as exc: fut.set_exception(exc) else: if nested_fut is not None: nested_fut.add_done_callback(nested_cb) return # we can’t even use StanzaErrorAwareListener because we want to # forward error stanzas to the cb too... if stanza.type_.is_error: fut.set_exception(stanza.error.to_exception()) else: fut.set_result(stanza.payload) def handler_error(exc): """ This handler is invoked synchronously by :meth:`_process_incoming_iq` (via :class:`aioxmpp.callbacks.TagDispatcher`) for response errors ( such as parsing errors, connection errors, etc.). """ nonlocal fut if fut.cancelled(): return fut.set_exception(exc) listener = callbacks.OneshotTagListener( handler_ok, handler_error, ) listener_tag = (stanza.to, stanza.id_) self._iq_response_map.add_listener( listener_tag, listener, ) try: yield from self._enqueue(stanza) except Exception: listener.cancel() raise try: if not timeout: reply = yield from fut else: try: reply = yield from asyncio.wait_for( fut, timeout=timeout ) except asyncio.TimeoutError: raise TimeoutError finally: try: self._iq_response_map.remove_listener(listener_tag) except KeyError: pass return reply
Send a stanza without waiting for the stream to be ready to send stanzas. This is only useful from within :class:`aioxmpp.node.Client` before the stream is fully established.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stream.py#L2561-L2673
horazont/aioxmpp
aioxmpp/entitycaps/caps390.py
_process_features
def _process_features(features): """ Generate the `Features String` from an iterable of features. :param features: The features to generate the features string from. :type features: :class:`~collections.abc.Iterable` of :class:`str` :return: The `Features String` :rtype: :class:`bytes` Generate the `Features String` from the given `features` as specified in :xep:`390`. """ parts = [ feature.encode("utf-8")+b"\x1f" for feature in features ] parts.sort() return b"".join(parts)+b"\x1c"
python
def _process_features(features): """ Generate the `Features String` from an iterable of features. :param features: The features to generate the features string from. :type features: :class:`~collections.abc.Iterable` of :class:`str` :return: The `Features String` :rtype: :class:`bytes` Generate the `Features String` from the given `features` as specified in :xep:`390`. """ parts = [ feature.encode("utf-8")+b"\x1f" for feature in features ] parts.sort() return b"".join(parts)+b"\x1c"
Generate the `Features String` from an iterable of features. :param features: The features to generate the features string from. :type features: :class:`~collections.abc.Iterable` of :class:`str` :return: The `Features String` :rtype: :class:`bytes` Generate the `Features String` from the given `features` as specified in :xep:`390`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/caps390.py#L33-L50
horazont/aioxmpp
aioxmpp/entitycaps/caps390.py
_process_identities
def _process_identities(identities): """ Generate the `Identities String` from an iterable of identities. :param identities: The identities to generate the features string from. :type identities: :class:`~collections.abc.Iterable` of :class:`~.disco.xso.Identity` :return: The `Identities String` :rtype: :class:`bytes` Generate the `Identities String` from the given `identities` as specified in :xep:`390`. """ parts = [ _process_identity(identity) for identity in identities ] parts.sort() return b"".join(parts)+b"\x1c"
python
def _process_identities(identities): """ Generate the `Identities String` from an iterable of identities. :param identities: The identities to generate the features string from. :type identities: :class:`~collections.abc.Iterable` of :class:`~.disco.xso.Identity` :return: The `Identities String` :rtype: :class:`bytes` Generate the `Identities String` from the given `identities` as specified in :xep:`390`. """ parts = [ _process_identity(identity) for identity in identities ] parts.sort() return b"".join(parts)+b"\x1c"
Generate the `Identities String` from an iterable of identities. :param identities: The identities to generate the features string from. :type identities: :class:`~collections.abc.Iterable` of :class:`~.disco.xso.Identity` :return: The `Identities String` :rtype: :class:`bytes` Generate the `Identities String` from the given `identities` as specified in :xep:`390`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/caps390.py#L62-L80
horazont/aioxmpp
aioxmpp/entitycaps/caps390.py
_process_extensions
def _process_extensions(exts): """ Generate the `Extensions String` from an iterable of data forms. :param exts: The data forms to generate the extensions string from. :type exts: :class:`~collections.abc.Iterable` of :class:`~.forms.xso.Data` :return: The `Extensions String` :rtype: :class:`bytes` Generate the `Extensions String` from the given `exts` as specified in :xep:`390`. """ parts = [ _process_form(form) for form in exts ] parts.sort() return b"".join(parts)+b"\x1c"
python
def _process_extensions(exts): """ Generate the `Extensions String` from an iterable of data forms. :param exts: The data forms to generate the extensions string from. :type exts: :class:`~collections.abc.Iterable` of :class:`~.forms.xso.Data` :return: The `Extensions String` :rtype: :class:`bytes` Generate the `Extensions String` from the given `exts` as specified in :xep:`390`. """ parts = [ _process_form(form) for form in exts ] parts.sort() return b"".join(parts)+b"\x1c"
Generate the `Extensions String` from an iterable of data forms. :param exts: The data forms to generate the extensions string from. :type exts: :class:`~collections.abc.Iterable` of :class:`~.forms.xso.Data` :return: The `Extensions String` :rtype: :class:`bytes` Generate the `Extensions String` from the given `exts` as specified in :xep:`390`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/entitycaps/caps390.py#L103-L121
horazont/aioxmpp
aioxmpp/xso/query.py
EvaluationContext.set_toplevel_object
def set_toplevel_object(self, instance, class_=None): """ Set the toplevel object to return from :meth:`get_toplevel_object` when asked for `class_` to `instance`. If `class_` is :data:`None`, the :func:`type` of the `instance` is used. """ if class_ is None: class_ = type(instance) self._toplevels[class_] = instance
python
def set_toplevel_object(self, instance, class_=None): """ Set the toplevel object to return from :meth:`get_toplevel_object` when asked for `class_` to `instance`. If `class_` is :data:`None`, the :func:`type` of the `instance` is used. """ if class_ is None: class_ = type(instance) self._toplevels[class_] = instance
Set the toplevel object to return from :meth:`get_toplevel_object` when asked for `class_` to `instance`. If `class_` is :data:`None`, the :func:`type` of the `instance` is used.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/query.py#L148-L158
horazont/aioxmpp
aioxmpp/xso/query.py
EvaluationContext.eval_bool
def eval_bool(self, expr): """ Evaluate the expression `expr` and return the truthness of its result. A result of an expression is said to be true if it contains at least one value. It has the same semantics as :func:`bool` on sequences.s """ result = expr.eval(self) iterator = iter(result) try: next(iterator) except StopIteration: return False else: return True finally: if hasattr(iterator, "close"): iterator.close()
python
def eval_bool(self, expr): """ Evaluate the expression `expr` and return the truthness of its result. A result of an expression is said to be true if it contains at least one value. It has the same semantics as :func:`bool` on sequences.s """ result = expr.eval(self) iterator = iter(result) try: next(iterator) except StopIteration: return False else: return True finally: if hasattr(iterator, "close"): iterator.close()
Evaluate the expression `expr` and return the truthness of its result. A result of an expression is said to be true if it contains at least one value. It has the same semantics as :func:`bool` on sequences.s
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/query.py#L168-L184
horazont/aioxmpp
aioxmpp/statemachine.py
OrderedStateMachine.rewind
def rewind(self, new_state): """ Rewind can be used as an exceptional way to roll back the state of a :class:`OrderedStateMachine`. Rewinding is not the usual use case for an :class:`OrderedStateMachine`. Usually, if the current state `A` is greater than any given state `B`, it is assumed that state `B` cannot be reached anymore (which makes :meth:`wait_for` raise). It may make sense to go backwards though, and in cases where the ability to go backwards is sensible even if routines which previously attempted to wait for the state you are going backwards to failed, using a :class:`OrderedStateMachine` is still a good idea. """ if new_state > self._state: raise ValueError("cannot forward using rewind " "({} > {})".format(new_state, self._state)) self._state = new_state
python
def rewind(self, new_state): """ Rewind can be used as an exceptional way to roll back the state of a :class:`OrderedStateMachine`. Rewinding is not the usual use case for an :class:`OrderedStateMachine`. Usually, if the current state `A` is greater than any given state `B`, it is assumed that state `B` cannot be reached anymore (which makes :meth:`wait_for` raise). It may make sense to go backwards though, and in cases where the ability to go backwards is sensible even if routines which previously attempted to wait for the state you are going backwards to failed, using a :class:`OrderedStateMachine` is still a good idea. """ if new_state > self._state: raise ValueError("cannot forward using rewind " "({} > {})".format(new_state, self._state)) self._state = new_state
Rewind can be used as an exceptional way to roll back the state of a :class:`OrderedStateMachine`. Rewinding is not the usual use case for an :class:`OrderedStateMachine`. Usually, if the current state `A` is greater than any given state `B`, it is assumed that state `B` cannot be reached anymore (which makes :meth:`wait_for` raise). It may make sense to go backwards though, and in cases where the ability to go backwards is sensible even if routines which previously attempted to wait for the state you are going backwards to failed, using a :class:`OrderedStateMachine` is still a good idea.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/statemachine.py#L131-L149
horazont/aioxmpp
aioxmpp/statemachine.py
OrderedStateMachine.wait_for
def wait_for(self, new_state): """ Wait for an exact state `new_state` to be reached by the state machine. If the state is skipped, that is, if a state which is greater than `new_state` is written to :attr:`state`, the coroutine raises :class:`OrderedStateSkipped` exception as it is not possible anymore that it can return successfully (see :attr:`state`). """ if self._state == new_state: return if self._state > new_state: raise OrderedStateSkipped(new_state) fut = asyncio.Future(loop=self.loop) self._exact_waiters.append((new_state, fut)) yield from fut
python
def wait_for(self, new_state): """ Wait for an exact state `new_state` to be reached by the state machine. If the state is skipped, that is, if a state which is greater than `new_state` is written to :attr:`state`, the coroutine raises :class:`OrderedStateSkipped` exception as it is not possible anymore that it can return successfully (see :attr:`state`). """ if self._state == new_state: return if self._state > new_state: raise OrderedStateSkipped(new_state) fut = asyncio.Future(loop=self.loop) self._exact_waiters.append((new_state, fut)) yield from fut
Wait for an exact state `new_state` to be reached by the state machine. If the state is skipped, that is, if a state which is greater than `new_state` is written to :attr:`state`, the coroutine raises :class:`OrderedStateSkipped` exception as it is not possible anymore that it can return successfully (see :attr:`state`).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/statemachine.py#L152-L170
horazont/aioxmpp
aioxmpp/statemachine.py
OrderedStateMachine.wait_for_at_least
def wait_for_at_least(self, new_state): """ Wait for a state to be entered which is greater than or equal to `new_state` and return. """ if not (self._state < new_state): return fut = asyncio.Future(loop=self.loop) self._least_waiters.append((new_state, fut)) yield from fut
python
def wait_for_at_least(self, new_state): """ Wait for a state to be entered which is greater than or equal to `new_state` and return. """ if not (self._state < new_state): return fut = asyncio.Future(loop=self.loop) self._least_waiters.append((new_state, fut)) yield from fut
Wait for a state to be entered which is greater than or equal to `new_state` and return.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/statemachine.py#L173-L183
horazont/aioxmpp
aioxmpp/pubsub/xso.py
as_payload_class
def as_payload_class(cls): """ Register the given class `cls` as Publish-Subscribe payload on both :class:`Item` and :class:`EventItem`. Return the class, to allow this to be used as decorator. """ Item.register_child( Item.registered_payload, cls, ) EventItem.register_child( EventItem.registered_payload, cls, ) return cls
python
def as_payload_class(cls): """ Register the given class `cls` as Publish-Subscribe payload on both :class:`Item` and :class:`EventItem`. Return the class, to allow this to be used as decorator. """ Item.register_child( Item.registered_payload, cls, ) EventItem.register_child( EventItem.registered_payload, cls, ) return cls
Register the given class `cls` as Publish-Subscribe payload on both :class:`Item` and :class:`EventItem`. Return the class, to allow this to be used as decorator.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/xso.py#L912-L930
horazont/aioxmpp
aioxmpp/presence/service.py
PresenceClient.get_most_available_stanza
def get_most_available_stanza(self, peer_jid): """ Obtain the stanza describing the most-available presence of the contact. :param peer_jid: Bare JID of the contact. :type peer_jid: :class:`aioxmpp.JID` :rtype: :class:`aioxmpp.Presence` or :data:`None` :return: The presence stanza of the most available resource or :data:`None` if there is no available resource. The "most available" resource is the one whose presence state orderest highest according to :class:`~aioxmpp.PresenceState`. If there is no available resource for a given `peer_jid`, :data:`None` is returned. """ presences = sorted( self.get_peer_resources(peer_jid).items(), key=lambda item: aioxmpp.structs.PresenceState.from_stanza(item[1]) ) if not presences: return None return presences[-1][1]
python
def get_most_available_stanza(self, peer_jid): """ Obtain the stanza describing the most-available presence of the contact. :param peer_jid: Bare JID of the contact. :type peer_jid: :class:`aioxmpp.JID` :rtype: :class:`aioxmpp.Presence` or :data:`None` :return: The presence stanza of the most available resource or :data:`None` if there is no available resource. The "most available" resource is the one whose presence state orderest highest according to :class:`~aioxmpp.PresenceState`. If there is no available resource for a given `peer_jid`, :data:`None` is returned. """ presences = sorted( self.get_peer_resources(peer_jid).items(), key=lambda item: aioxmpp.structs.PresenceState.from_stanza(item[1]) ) if not presences: return None return presences[-1][1]
Obtain the stanza describing the most-available presence of the contact. :param peer_jid: Bare JID of the contact. :type peer_jid: :class:`aioxmpp.JID` :rtype: :class:`aioxmpp.Presence` or :data:`None` :return: The presence stanza of the most available resource or :data:`None` if there is no available resource. The "most available" resource is the one whose presence state orderest highest according to :class:`~aioxmpp.PresenceState`. If there is no available resource for a given `peer_jid`, :data:`None` is returned.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/presence/service.py#L123-L146
horazont/aioxmpp
aioxmpp/presence/service.py
PresenceClient.get_peer_resources
def get_peer_resources(self, peer_jid): """ Return a dict mapping resources of the given bare `peer_jid` to the presence state last received for that resource. Unavailable presence states are not included. If the bare JID is in a error state (i.e. an error presence stanza has been received), the returned mapping is empty. """ try: d = dict(self._presences[peer_jid]) d.pop(None, None) return d except KeyError: return {}
python
def get_peer_resources(self, peer_jid): """ Return a dict mapping resources of the given bare `peer_jid` to the presence state last received for that resource. Unavailable presence states are not included. If the bare JID is in a error state (i.e. an error presence stanza has been received), the returned mapping is empty. """ try: d = dict(self._presences[peer_jid]) d.pop(None, None) return d except KeyError: return {}
Return a dict mapping resources of the given bare `peer_jid` to the presence state last received for that resource. Unavailable presence states are not included. If the bare JID is in a error state (i.e. an error presence stanza has been received), the returned mapping is empty.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/presence/service.py#L148-L162
horazont/aioxmpp
aioxmpp/presence/service.py
PresenceClient.get_stanza
def get_stanza(self, peer_jid): """ Return the last presence recieved for the given bare or full `peer_jid`. If the last presence was unavailable, the return value is :data:`None`, as if no presence was ever received. If no presence was ever received for the given bare JID, :data:`None` is returned. """ try: return self._presences[peer_jid.bare()][peer_jid.resource] except KeyError: pass try: return self._presences[peer_jid.bare()][None] except KeyError: pass
python
def get_stanza(self, peer_jid): """ Return the last presence recieved for the given bare or full `peer_jid`. If the last presence was unavailable, the return value is :data:`None`, as if no presence was ever received. If no presence was ever received for the given bare JID, :data:`None` is returned. """ try: return self._presences[peer_jid.bare()][peer_jid.resource] except KeyError: pass try: return self._presences[peer_jid.bare()][None] except KeyError: pass
Return the last presence recieved for the given bare or full `peer_jid`. If the last presence was unavailable, the return value is :data:`None`, as if no presence was ever received. If no presence was ever received for the given bare JID, :data:`None` is returned.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/presence/service.py#L164-L180
horazont/aioxmpp
aioxmpp/presence/service.py
PresenceServer.make_stanza
def make_stanza(self): """ Create and return a presence stanza with the current settings. :return: Presence stanza :rtype: :class:`aioxmpp.Presence` """ stanza = aioxmpp.Presence() self._state.apply_to_stanza(stanza) stanza.status.update(self._status) return stanza
python
def make_stanza(self): """ Create and return a presence stanza with the current settings. :return: Presence stanza :rtype: :class:`aioxmpp.Presence` """ stanza = aioxmpp.Presence() self._state.apply_to_stanza(stanza) stanza.status.update(self._status) return stanza
Create and return a presence stanza with the current settings. :return: Presence stanza :rtype: :class:`aioxmpp.Presence`
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/presence/service.py#L344-L354
horazont/aioxmpp
aioxmpp/presence/service.py
PresenceServer.set_presence
def set_presence(self, state, status={}, priority=0): """ Change the presence broadcast by the client. :param state: New presence state to broadcast :type state: :class:`aioxmpp.PresenceState` :param status: New status information to broadcast :type status: :class:`dict` or :class:`str` :param priority: New priority for the resource :type priority: :class:`int` :return: Stanza token of the presence stanza or :data:`None` if the presence is unchanged or the stream is not connected. :rtype: :class:`~.stream.StanzaToken` If the client is currently connected, the new presence is broadcast immediately. `status` must be either a string or something which can be passed to the :class:`dict` constructor. If it is a string, it is wrapped into a dict using ``{None: status}``. The mapping must map :class:`~.LanguageTag` objects (or :data:`None`) to strings. The information will be used to generate internationalised presence status information. If you do not need internationalisation, simply use the string version of the argument. """ if not isinstance(priority, numbers.Integral): raise TypeError( "invalid priority: got {}, expected integer".format( type(priority) ) ) if not isinstance(state, aioxmpp.PresenceState): raise TypeError( "invalid state: got {}, expected aioxmpp.PresenceState".format( type(state), ) ) if isinstance(status, str): new_status = {None: status} else: new_status = dict(status) new_priority = int(priority) emit_state_event = self._state != state emit_overall_event = ( emit_state_event or self._priority != new_priority or self._status != new_status ) self._state = state self._status = new_status self._priority = new_priority if emit_state_event: self.on_presence_state_changed() if emit_overall_event: self.on_presence_changed() return self.resend_presence()
python
def set_presence(self, state, status={}, priority=0): """ Change the presence broadcast by the client. :param state: New presence state to broadcast :type state: :class:`aioxmpp.PresenceState` :param status: New status information to broadcast :type status: :class:`dict` or :class:`str` :param priority: New priority for the resource :type priority: :class:`int` :return: Stanza token of the presence stanza or :data:`None` if the presence is unchanged or the stream is not connected. :rtype: :class:`~.stream.StanzaToken` If the client is currently connected, the new presence is broadcast immediately. `status` must be either a string or something which can be passed to the :class:`dict` constructor. If it is a string, it is wrapped into a dict using ``{None: status}``. The mapping must map :class:`~.LanguageTag` objects (or :data:`None`) to strings. The information will be used to generate internationalised presence status information. If you do not need internationalisation, simply use the string version of the argument. """ if not isinstance(priority, numbers.Integral): raise TypeError( "invalid priority: got {}, expected integer".format( type(priority) ) ) if not isinstance(state, aioxmpp.PresenceState): raise TypeError( "invalid state: got {}, expected aioxmpp.PresenceState".format( type(state), ) ) if isinstance(status, str): new_status = {None: status} else: new_status = dict(status) new_priority = int(priority) emit_state_event = self._state != state emit_overall_event = ( emit_state_event or self._priority != new_priority or self._status != new_status ) self._state = state self._status = new_status self._priority = new_priority if emit_state_event: self.on_presence_state_changed() if emit_overall_event: self.on_presence_changed() return self.resend_presence()
Change the presence broadcast by the client. :param state: New presence state to broadcast :type state: :class:`aioxmpp.PresenceState` :param status: New status information to broadcast :type status: :class:`dict` or :class:`str` :param priority: New priority for the resource :type priority: :class:`int` :return: Stanza token of the presence stanza or :data:`None` if the presence is unchanged or the stream is not connected. :rtype: :class:`~.stream.StanzaToken` If the client is currently connected, the new presence is broadcast immediately. `status` must be either a string or something which can be passed to the :class:`dict` constructor. If it is a string, it is wrapped into a dict using ``{None: status}``. The mapping must map :class:`~.LanguageTag` objects (or :data:`None`) to strings. The information will be used to generate internationalised presence status information. If you do not need internationalisation, simply use the string version of the argument.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/presence/service.py#L356-L417
horazont/aioxmpp
aioxmpp/presence/service.py
PresenceServer.resend_presence
def resend_presence(self): """ Re-send the currently configured presence. :return: Stanza token of the presence stanza or :data:`None` if the stream is not established. :rtype: :class:`~.stream.StanzaToken` .. note:: :meth:`set_presence` automatically broadcasts the new presence if any of the parameters changed. """ if self.client.established: return self.client.enqueue(self.make_stanza())
python
def resend_presence(self): """ Re-send the currently configured presence. :return: Stanza token of the presence stanza or :data:`None` if the stream is not established. :rtype: :class:`~.stream.StanzaToken` .. note:: :meth:`set_presence` automatically broadcasts the new presence if any of the parameters changed. """ if self.client.established: return self.client.enqueue(self.make_stanza())
Re-send the currently configured presence. :return: Stanza token of the presence stanza or :data:`None` if the stream is not established. :rtype: :class:`~.stream.StanzaToken` .. note:: :meth:`set_presence` automatically broadcasts the new presence if any of the parameters changed.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/presence/service.py#L419-L434
horazont/aioxmpp
aioxmpp/security_layer.py
extract_python_dict_from_x509
def extract_python_dict_from_x509(x509): """ Extract a python dictionary similar to the return value of :meth:`ssl.SSLSocket.getpeercert` from the given :class:`OpenSSL.crypto.X509` `x509` object. Note that by far not all attributes are included; only those required to use :func:`ssl.match_hostname` are extracted and put in the result. In the future, more attributes may be added. """ result = { "subject": ( (("commonName", x509.get_subject().commonName),), ) } for ext_idx in range(x509.get_extension_count()): ext = x509.get_extension(ext_idx) sn = ext.get_short_name() if sn != b"subjectAltName": continue data = pyasn1.codec.der.decoder.decode( ext.get_data(), asn1Spec=pyasn1_modules.rfc2459.SubjectAltName())[0] for name in data: dNSName = name.getComponentByPosition(2) if dNSName is None: continue if hasattr(dNSName, "isValue") and not dNSName.isValue: continue result.setdefault("subjectAltName", []).append( ("DNS", str(dNSName)) ) return result
python
def extract_python_dict_from_x509(x509): """ Extract a python dictionary similar to the return value of :meth:`ssl.SSLSocket.getpeercert` from the given :class:`OpenSSL.crypto.X509` `x509` object. Note that by far not all attributes are included; only those required to use :func:`ssl.match_hostname` are extracted and put in the result. In the future, more attributes may be added. """ result = { "subject": ( (("commonName", x509.get_subject().commonName),), ) } for ext_idx in range(x509.get_extension_count()): ext = x509.get_extension(ext_idx) sn = ext.get_short_name() if sn != b"subjectAltName": continue data = pyasn1.codec.der.decoder.decode( ext.get_data(), asn1Spec=pyasn1_modules.rfc2459.SubjectAltName())[0] for name in data: dNSName = name.getComponentByPosition(2) if dNSName is None: continue if hasattr(dNSName, "isValue") and not dNSName.isValue: continue result.setdefault("subjectAltName", []).append( ("DNS", str(dNSName)) ) return result
Extract a python dictionary similar to the return value of :meth:`ssl.SSLSocket.getpeercert` from the given :class:`OpenSSL.crypto.X509` `x509` object. Note that by far not all attributes are included; only those required to use :func:`ssl.match_hostname` are extracted and put in the result. In the future, more attributes may be added.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L140-L178
horazont/aioxmpp
aioxmpp/security_layer.py
blob_to_pyasn1
def blob_to_pyasn1(blob): """ Convert an ASN.1 encoded certificate (such as obtained from :func:`extract_blob`) to a :mod:`pyasn1` structure and return the result. """ return pyasn1.codec.der.decoder.decode( blob, asn1Spec=pyasn1_modules.rfc2459.Certificate() )[0]
python
def blob_to_pyasn1(blob): """ Convert an ASN.1 encoded certificate (such as obtained from :func:`extract_blob`) to a :mod:`pyasn1` structure and return the result. """ return pyasn1.codec.der.decoder.decode( blob, asn1Spec=pyasn1_modules.rfc2459.Certificate() )[0]
Convert an ASN.1 encoded certificate (such as obtained from :func:`extract_blob`) to a :mod:`pyasn1` structure and return the result.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L192-L201
horazont/aioxmpp
aioxmpp/security_layer.py
extract_pk_blob_from_pyasn1
def extract_pk_blob_from_pyasn1(pyasn1_struct): """ Extract an ASN.1 encoded public key blob from the given :mod:`pyasn1` structure (which must represent a certificate). """ pk = pyasn1_struct.getComponentByName( "tbsCertificate" ).getComponentByName( "subjectPublicKeyInfo" ) return pyasn1.codec.der.encoder.encode(pk)
python
def extract_pk_blob_from_pyasn1(pyasn1_struct): """ Extract an ASN.1 encoded public key blob from the given :mod:`pyasn1` structure (which must represent a certificate). """ pk = pyasn1_struct.getComponentByName( "tbsCertificate" ).getComponentByName( "subjectPublicKeyInfo" ) return pyasn1.codec.der.encoder.encode(pk)
Extract an ASN.1 encoded public key blob from the given :mod:`pyasn1` structure (which must represent a certificate).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L204-L216
horazont/aioxmpp
aioxmpp/security_layer.py
check_x509_hostname
def check_x509_hostname(x509, hostname): """ Check whether the given :class:`OpenSSL.crypto.X509` certificate `x509` matches the given `hostname`. Return :data:`True` if the name matches and :data:`False` otherwise. This uses :func:`ssl.match_hostname` and :func:`extract_python_dict_from_x509`. """ cert_structure = extract_python_dict_from_x509(x509) try: ssl.match_hostname(cert_structure, hostname) except ssl.CertificateError: return False return True
python
def check_x509_hostname(x509, hostname): """ Check whether the given :class:`OpenSSL.crypto.X509` certificate `x509` matches the given `hostname`. Return :data:`True` if the name matches and :data:`False` otherwise. This uses :func:`ssl.match_hostname` and :func:`extract_python_dict_from_x509`. """ cert_structure = extract_python_dict_from_x509(x509) try: ssl.match_hostname(cert_structure, hostname) except ssl.CertificateError: return False return True
Check whether the given :class:`OpenSSL.crypto.X509` certificate `x509` matches the given `hostname`. Return :data:`True` if the name matches and :data:`False` otherwise. This uses :func:`ssl.match_hostname` and :func:`extract_python_dict_from_x509`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L219-L233
horazont/aioxmpp
aioxmpp/security_layer.py
default_ssl_context
def default_ssl_context(): """ Return a sensibly configured :class:`OpenSSL.SSL.Context` context. The context has SSLv2 and SSLv3 disabled, and supports TLS 1.0+ (depending on the version of the SSL library). Tries to negotiate an XMPP c2s connection via ALPN (:rfc:`7301`). """ ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD) ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2 | OpenSSL.SSL.OP_NO_SSLv3) ctx.set_verify(OpenSSL.SSL.VERIFY_PEER, default_verify_callback) return ctx
python
def default_ssl_context(): """ Return a sensibly configured :class:`OpenSSL.SSL.Context` context. The context has SSLv2 and SSLv3 disabled, and supports TLS 1.0+ (depending on the version of the SSL library). Tries to negotiate an XMPP c2s connection via ALPN (:rfc:`7301`). """ ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD) ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2 | OpenSSL.SSL.OP_NO_SSLv3) ctx.set_verify(OpenSSL.SSL.VERIFY_PEER, default_verify_callback) return ctx
Return a sensibly configured :class:`OpenSSL.SSL.Context` context. The context has SSLv2 and SSLv3 disabled, and supports TLS 1.0+ (depending on the version of the SSL library). Tries to negotiate an XMPP c2s connection via ALPN (:rfc:`7301`).
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L1125-L1138
horazont/aioxmpp
aioxmpp/security_layer.py
negotiate_sasl
def negotiate_sasl(transport, xmlstream, sasl_providers, negotiation_timeout, jid, features): """ Perform SASL authentication on the given :class:`.protocol.XMLStream` `stream`. `transport` must be the :class:`asyncio.Transport` over which the `stream` runs. It is used to detect whether TLS is used and may be required by some SASL mechanisms. `sasl_providers` must be an iterable of :class:`SASLProvider` objects. They will be tried in iteration order to authenticate against the server. If one of the `sasl_providers` fails with a :class:`aiosasl.AuthenticationFailure` exception, the other providers are still tried; only if all providers fail, the last :class:`aiosasl.AuthenticationFailure` exception is re-raised. If no mechanism was able to authenticate but not due to authentication failures (other failures include no matching mechanism on the server side), :class:`aiosasl.SASLUnavailable` is raised. Return the :class:`.nonza.StreamFeatures` obtained after resetting the stream after successful SASL authentication. .. versionadded:: 0.6 .. deprecated:: 0.10 The `negotiation_timeout` argument is ignored. The timeout is controlled using the :attr:`~.XMLStream.deadtime_hard_limit` timeout of the stream. The argument will be removed in version 1.0. To prepare for this, please pass `jid` and `features` as keyword arguments. """ if not transport.get_extra_info("sslcontext"): transport = None last_auth_error = None for sasl_provider in sasl_providers: try: result = yield from sasl_provider.execute( jid, features, xmlstream, transport) except ValueError as err: raise errors.StreamNegotiationFailure( "invalid credentials: {}".format(err) ) from err except aiosasl.AuthenticationFailure as err: last_auth_error = err continue if result: features = yield from protocol.reset_stream_and_get_features( xmlstream ) break else: if last_auth_error: raise last_auth_error else: raise errors.SASLUnavailable("No common mechanisms") return features
python
def negotiate_sasl(transport, xmlstream, sasl_providers, negotiation_timeout, jid, features): """ Perform SASL authentication on the given :class:`.protocol.XMLStream` `stream`. `transport` must be the :class:`asyncio.Transport` over which the `stream` runs. It is used to detect whether TLS is used and may be required by some SASL mechanisms. `sasl_providers` must be an iterable of :class:`SASLProvider` objects. They will be tried in iteration order to authenticate against the server. If one of the `sasl_providers` fails with a :class:`aiosasl.AuthenticationFailure` exception, the other providers are still tried; only if all providers fail, the last :class:`aiosasl.AuthenticationFailure` exception is re-raised. If no mechanism was able to authenticate but not due to authentication failures (other failures include no matching mechanism on the server side), :class:`aiosasl.SASLUnavailable` is raised. Return the :class:`.nonza.StreamFeatures` obtained after resetting the stream after successful SASL authentication. .. versionadded:: 0.6 .. deprecated:: 0.10 The `negotiation_timeout` argument is ignored. The timeout is controlled using the :attr:`~.XMLStream.deadtime_hard_limit` timeout of the stream. The argument will be removed in version 1.0. To prepare for this, please pass `jid` and `features` as keyword arguments. """ if not transport.get_extra_info("sslcontext"): transport = None last_auth_error = None for sasl_provider in sasl_providers: try: result = yield from sasl_provider.execute( jid, features, xmlstream, transport) except ValueError as err: raise errors.StreamNegotiationFailure( "invalid credentials: {}".format(err) ) from err except aiosasl.AuthenticationFailure as err: last_auth_error = err continue if result: features = yield from protocol.reset_stream_and_get_features( xmlstream ) break else: if last_auth_error: raise last_auth_error else: raise errors.SASLUnavailable("No common mechanisms") return features
Perform SASL authentication on the given :class:`.protocol.XMLStream` `stream`. `transport` must be the :class:`asyncio.Transport` over which the `stream` runs. It is used to detect whether TLS is used and may be required by some SASL mechanisms. `sasl_providers` must be an iterable of :class:`SASLProvider` objects. They will be tried in iteration order to authenticate against the server. If one of the `sasl_providers` fails with a :class:`aiosasl.AuthenticationFailure` exception, the other providers are still tried; only if all providers fail, the last :class:`aiosasl.AuthenticationFailure` exception is re-raised. If no mechanism was able to authenticate but not due to authentication failures (other failures include no matching mechanism on the server side), :class:`aiosasl.SASLUnavailable` is raised. Return the :class:`.nonza.StreamFeatures` obtained after resetting the stream after successful SASL authentication. .. versionadded:: 0.6 .. deprecated:: 0.10 The `negotiation_timeout` argument is ignored. The timeout is controlled using the :attr:`~.XMLStream.deadtime_hard_limit` timeout of the stream. The argument will be removed in version 1.0. To prepare for this, please pass `jid` and `features` as keyword arguments.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L1142-L1204
horazont/aioxmpp
aioxmpp/security_layer.py
security_layer
def security_layer(tls_provider, sasl_providers): """ .. deprecated:: 0.6 Replaced by :class:`SecurityLayer`. Return a configured :class:`SecurityLayer`. `tls_provider` must be a :class:`STARTTLSProvider`. The return value can be passed to the constructor of :class:`~.node.Client`. Some very basic checking on the input is also performed. """ sasl_providers = tuple(sasl_providers) if not sasl_providers: raise ValueError("At least one SASL provider must be given.") for sasl_provider in sasl_providers: sasl_provider.execute # check that sasl_provider has execute method result = SecurityLayer( tls_provider.ssl_context_factory, tls_provider.certificate_verifier_factory, tls_provider.tls_required, sasl_providers ) return result
python
def security_layer(tls_provider, sasl_providers): """ .. deprecated:: 0.6 Replaced by :class:`SecurityLayer`. Return a configured :class:`SecurityLayer`. `tls_provider` must be a :class:`STARTTLSProvider`. The return value can be passed to the constructor of :class:`~.node.Client`. Some very basic checking on the input is also performed. """ sasl_providers = tuple(sasl_providers) if not sasl_providers: raise ValueError("At least one SASL provider must be given.") for sasl_provider in sasl_providers: sasl_provider.execute # check that sasl_provider has execute method result = SecurityLayer( tls_provider.ssl_context_factory, tls_provider.certificate_verifier_factory, tls_provider.tls_required, sasl_providers ) return result
.. deprecated:: 0.6 Replaced by :class:`SecurityLayer`. Return a configured :class:`SecurityLayer`. `tls_provider` must be a :class:`STARTTLSProvider`. The return value can be passed to the constructor of :class:`~.node.Client`. Some very basic checking on the input is also performed.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L1224-L1253
horazont/aioxmpp
aioxmpp/security_layer.py
tls_with_password_based_authentication
def tls_with_password_based_authentication( password_provider, ssl_context_factory=default_ssl_context, max_auth_attempts=3, certificate_verifier_factory=PKIXCertificateVerifier): """ Produce a commonly used :class:`SecurityLayer`, which uses TLS and password-based SASL authentication. If `ssl_context_factory` is not provided, an SSL context with TLSv1+ is used. `password_provider` must be a coroutine which is called with the jid as first and the number of attempt as second argument. It must return the password to us, or :data:`None` to abort. Return a :class:`SecurityLayer` instance. .. deprecated:: 0.7 Use :func:`make` instead. """ tls_kwargs = {} if certificate_verifier_factory is not None: tls_kwargs["certificate_verifier_factory"] = \ certificate_verifier_factory return SecurityLayer( ssl_context_factory, certificate_verifier_factory, True, ( PasswordSASLProvider( password_provider, max_auth_attempts=max_auth_attempts), ) )
python
def tls_with_password_based_authentication( password_provider, ssl_context_factory=default_ssl_context, max_auth_attempts=3, certificate_verifier_factory=PKIXCertificateVerifier): """ Produce a commonly used :class:`SecurityLayer`, which uses TLS and password-based SASL authentication. If `ssl_context_factory` is not provided, an SSL context with TLSv1+ is used. `password_provider` must be a coroutine which is called with the jid as first and the number of attempt as second argument. It must return the password to us, or :data:`None` to abort. Return a :class:`SecurityLayer` instance. .. deprecated:: 0.7 Use :func:`make` instead. """ tls_kwargs = {} if certificate_verifier_factory is not None: tls_kwargs["certificate_verifier_factory"] = \ certificate_verifier_factory return SecurityLayer( ssl_context_factory, certificate_verifier_factory, True, ( PasswordSASLProvider( password_provider, max_auth_attempts=max_auth_attempts), ) )
Produce a commonly used :class:`SecurityLayer`, which uses TLS and password-based SASL authentication. If `ssl_context_factory` is not provided, an SSL context with TLSv1+ is used. `password_provider` must be a coroutine which is called with the jid as first and the number of attempt as second argument. It must return the password to us, or :data:`None` to abort. Return a :class:`SecurityLayer` instance. .. deprecated:: 0.7 Use :func:`make` instead.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L1256-L1291
horazont/aioxmpp
aioxmpp/security_layer.py
make
def make( password_provider, *, pin_store=None, pin_type=PinType.PUBLIC_KEY, post_handshake_deferred_failure=None, anonymous=False, ssl_context_factory=default_ssl_context, no_verify=False): """ Construct a :class:`SecurityLayer`. Depending on the arguments passed, different features are enabled or disabled. .. warning:: When using any argument except `password_provider`, be sure to read its documentation below the following overview **carefully**. Many arguments can be used to shoot yourself in the foot easily, while violating all security expectations. Args: password_provider (:class:`str` or coroutine function): Password source to authenticate with. Keyword Args: pin_store (:class:`dict` or :class:`AbstractPinStore`): Enable use of certificate/public key pinning. `pin_type` controls the type of store used when a dict is passed instead of a pin store object. pin_type (:class:`~aioxmpp.security_layer.PinType`): Type of pin store to create when `pin_store` is a dict. post_handshake_deferred_failure (coroutine function): Coroutine callback to invoke when using certificate pinning and the verification of the certificate was not possible using either PKIX or the pin store. anonymous (:class:`str`, :data:`None` or :data:`False`): trace token for SASL ANONYMOUS (:rfc:`4505`); passing a non-:data:`False` value enables ANONYMOUS authentication. ssl_context_factory (function): Factory function to create the SSL context used to establish transport layer security. Defaults to :func:`aioxmpp.security_layer.default_ssl_context`. no_verify (:class:`bool`): *Disable* all certificate verification. Usage is **strongly discouraged** outside controlled test environments. See below for alternatives. Raises: RuntimeError: if `anonymous` is not :data:`False` and the version of :mod:`aiosasl` does not support ANONYMOUS authentication. Returns: :class:`SecurityLayer`: object holding the entire security layer configuration `password_provider` must either be a coroutine function or a :class:`str`. As a coroutine function, it is called during authentication with the JID we are trying to authenticate against as the first, and the sequence number of the authentication attempt as second argument. The sequence number starts at 0. The coroutine is expected to return :data:`None` or a password. See :class:`PasswordSASLProvider` for details. If `password_provider` is a :class:`str`, a coroutine which returns the string on the first and :data:`None` on subsequent attempts is created and used. If `pin_store` is not :data:`None`, :class:`PinningPKIXCertificateVerifier` is used instead of the default :class:`PKIXCertificateVerifier`. The `pin_store` argument determines the pinned certificates: if it is a dictionary, a :class:`AbstractPinStore` according to the :class:`PinType` passed as `pin_type` argument is created and initialised with the data from the dictionary using its :meth:`~AbstractPinStore.import_from_json` method. Otherwise, `pin_store` must be a :class:`AbstractPinStore` instance which is passed to the verifier. `post_handshake_deferred_callback` is used only if `pin_store` is not :data:`None`. It is passed to the equally-named argument of :class:`PinningPKIXCertificateVerifier`, see the documentation there for details on the semantics. If `post_handshake_deferred_callback` is :data:`None` while `pin_store` is not, a coroutine which returns :data:`False` is substituted. `ssl_context_factory` can be a callable taking no arguments and returning a :class:`OpenSSL.SSL.Context` object. If given, the factory will be used to obtain an SSL context when the stream negotiates transport layer security via TLS. By default, :func:`aioxmpp.security_layer.default_ssl_context` is used, which should be fine for most applications. .. warning:: The :func:`~.default_ssl_context` implementation sets important defaults. It is **strongly recommended** to use the context returned by :func:`~.default_ssl_context` and modify it, instead of creating a new context from scratch when implementing your own factory. If `no_verify` is true, none of the above regarding certificate verifiers matters. The internal null verifier is used, which **disables certificate verification completely**. .. warning:: Disabling certificate verification makes your application vulnerable to trivial Man-in-the-Middle attacks. Do **not** use this outside controlled test environments or when you know **exactly** what you’re doing! If you need to handle certificates which cannot be verified using the public key infrastructure, consider making use of the `pin_store` argument instead. `anonymous` may be a string or :data:`False`. If it is not :data:`False`, :class:`AnonymousSASLProvider` is used before password based authentication is attempted. In addition, it is allowed to set `password_provider` to :data:`None`. `anonymous` is the trace token to use, and SHOULD be the empty string (as specified by :xep:`175`). This requires :mod:`aiosasl` 0.3 or newer. .. note:: :data:`False` and ``""`` are treated differently for the `anonymous` argument, despite both being false-y values! .. note:: If `anonymous` is not :data:`False` and `password_provider` is not :data:`None`, both authentication types are attempted. Anonymous authentication is, in that case, preferred over password-based authentication. If you need to reverse the order, you have to construct your own :class:`SecurityLayer` object. .. warning:: Take the security and privacy considerations from :rfc:`4505` (which specifies the ANONYMOUS SASL mechanism) and :xep:`175` (which discusses the ANONYMOUS SASL mechanism in the XMPP context) into account before using `anonymous`. The versatility and simplicity of use of this function make (pun intended) it the preferred way to construct :class:`SecurityLayer` instances. .. versionadded:: 0.8 Support for SASL ANONYMOUS was added. .. versionadded:: 0.11 Support for `ssl_context_factory`. """ if isinstance(password_provider, str): static_password = password_provider @asyncio.coroutine def password_provider(jid, nattempt): if nattempt == 0: return static_password return None if pin_store is not None: if post_handshake_deferred_failure is None: @asyncio.coroutine def post_handshake_deferred_failure(verifier): return False if not isinstance(pin_store, AbstractPinStore): pin_data = pin_store if pin_type == PinType.PUBLIC_KEY: logger.debug("using PublicKeyPinStore") pin_store = PublicKeyPinStore() else: logger.debug("using CertificatePinStore") pin_store = CertificatePinStore() pin_store.import_from_json(pin_data) def certificate_verifier_factory(): return PinningPKIXCertificateVerifier( pin_store.query, post_handshake_deferred_failure, ) elif no_verify: certificate_verifier_factory = _NullVerifier else: certificate_verifier_factory = PKIXCertificateVerifier sasl_providers = [] if anonymous is not False: if AnonymousSASLProvider is None: raise RuntimeError( "aiosasl does not support ANONYMOUS, please upgrade" ) sasl_providers.append( AnonymousSASLProvider(anonymous) ) if password_provider is not None: sasl_providers.append( PasswordSASLProvider( password_provider, ), ) return SecurityLayer( ssl_context_factory, certificate_verifier_factory, True, tuple(sasl_providers), )
python
def make( password_provider, *, pin_store=None, pin_type=PinType.PUBLIC_KEY, post_handshake_deferred_failure=None, anonymous=False, ssl_context_factory=default_ssl_context, no_verify=False): """ Construct a :class:`SecurityLayer`. Depending on the arguments passed, different features are enabled or disabled. .. warning:: When using any argument except `password_provider`, be sure to read its documentation below the following overview **carefully**. Many arguments can be used to shoot yourself in the foot easily, while violating all security expectations. Args: password_provider (:class:`str` or coroutine function): Password source to authenticate with. Keyword Args: pin_store (:class:`dict` or :class:`AbstractPinStore`): Enable use of certificate/public key pinning. `pin_type` controls the type of store used when a dict is passed instead of a pin store object. pin_type (:class:`~aioxmpp.security_layer.PinType`): Type of pin store to create when `pin_store` is a dict. post_handshake_deferred_failure (coroutine function): Coroutine callback to invoke when using certificate pinning and the verification of the certificate was not possible using either PKIX or the pin store. anonymous (:class:`str`, :data:`None` or :data:`False`): trace token for SASL ANONYMOUS (:rfc:`4505`); passing a non-:data:`False` value enables ANONYMOUS authentication. ssl_context_factory (function): Factory function to create the SSL context used to establish transport layer security. Defaults to :func:`aioxmpp.security_layer.default_ssl_context`. no_verify (:class:`bool`): *Disable* all certificate verification. Usage is **strongly discouraged** outside controlled test environments. See below for alternatives. Raises: RuntimeError: if `anonymous` is not :data:`False` and the version of :mod:`aiosasl` does not support ANONYMOUS authentication. Returns: :class:`SecurityLayer`: object holding the entire security layer configuration `password_provider` must either be a coroutine function or a :class:`str`. As a coroutine function, it is called during authentication with the JID we are trying to authenticate against as the first, and the sequence number of the authentication attempt as second argument. The sequence number starts at 0. The coroutine is expected to return :data:`None` or a password. See :class:`PasswordSASLProvider` for details. If `password_provider` is a :class:`str`, a coroutine which returns the string on the first and :data:`None` on subsequent attempts is created and used. If `pin_store` is not :data:`None`, :class:`PinningPKIXCertificateVerifier` is used instead of the default :class:`PKIXCertificateVerifier`. The `pin_store` argument determines the pinned certificates: if it is a dictionary, a :class:`AbstractPinStore` according to the :class:`PinType` passed as `pin_type` argument is created and initialised with the data from the dictionary using its :meth:`~AbstractPinStore.import_from_json` method. Otherwise, `pin_store` must be a :class:`AbstractPinStore` instance which is passed to the verifier. `post_handshake_deferred_callback` is used only if `pin_store` is not :data:`None`. It is passed to the equally-named argument of :class:`PinningPKIXCertificateVerifier`, see the documentation there for details on the semantics. If `post_handshake_deferred_callback` is :data:`None` while `pin_store` is not, a coroutine which returns :data:`False` is substituted. `ssl_context_factory` can be a callable taking no arguments and returning a :class:`OpenSSL.SSL.Context` object. If given, the factory will be used to obtain an SSL context when the stream negotiates transport layer security via TLS. By default, :func:`aioxmpp.security_layer.default_ssl_context` is used, which should be fine for most applications. .. warning:: The :func:`~.default_ssl_context` implementation sets important defaults. It is **strongly recommended** to use the context returned by :func:`~.default_ssl_context` and modify it, instead of creating a new context from scratch when implementing your own factory. If `no_verify` is true, none of the above regarding certificate verifiers matters. The internal null verifier is used, which **disables certificate verification completely**. .. warning:: Disabling certificate verification makes your application vulnerable to trivial Man-in-the-Middle attacks. Do **not** use this outside controlled test environments or when you know **exactly** what you’re doing! If you need to handle certificates which cannot be verified using the public key infrastructure, consider making use of the `pin_store` argument instead. `anonymous` may be a string or :data:`False`. If it is not :data:`False`, :class:`AnonymousSASLProvider` is used before password based authentication is attempted. In addition, it is allowed to set `password_provider` to :data:`None`. `anonymous` is the trace token to use, and SHOULD be the empty string (as specified by :xep:`175`). This requires :mod:`aiosasl` 0.3 or newer. .. note:: :data:`False` and ``""`` are treated differently for the `anonymous` argument, despite both being false-y values! .. note:: If `anonymous` is not :data:`False` and `password_provider` is not :data:`None`, both authentication types are attempted. Anonymous authentication is, in that case, preferred over password-based authentication. If you need to reverse the order, you have to construct your own :class:`SecurityLayer` object. .. warning:: Take the security and privacy considerations from :rfc:`4505` (which specifies the ANONYMOUS SASL mechanism) and :xep:`175` (which discusses the ANONYMOUS SASL mechanism in the XMPP context) into account before using `anonymous`. The versatility and simplicity of use of this function make (pun intended) it the preferred way to construct :class:`SecurityLayer` instances. .. versionadded:: 0.8 Support for SASL ANONYMOUS was added. .. versionadded:: 0.11 Support for `ssl_context_factory`. """ if isinstance(password_provider, str): static_password = password_provider @asyncio.coroutine def password_provider(jid, nattempt): if nattempt == 0: return static_password return None if pin_store is not None: if post_handshake_deferred_failure is None: @asyncio.coroutine def post_handshake_deferred_failure(verifier): return False if not isinstance(pin_store, AbstractPinStore): pin_data = pin_store if pin_type == PinType.PUBLIC_KEY: logger.debug("using PublicKeyPinStore") pin_store = PublicKeyPinStore() else: logger.debug("using CertificatePinStore") pin_store = CertificatePinStore() pin_store.import_from_json(pin_data) def certificate_verifier_factory(): return PinningPKIXCertificateVerifier( pin_store.query, post_handshake_deferred_failure, ) elif no_verify: certificate_verifier_factory = _NullVerifier else: certificate_verifier_factory = PKIXCertificateVerifier sasl_providers = [] if anonymous is not False: if AnonymousSASLProvider is None: raise RuntimeError( "aiosasl does not support ANONYMOUS, please upgrade" ) sasl_providers.append( AnonymousSASLProvider(anonymous) ) if password_provider is not None: sasl_providers.append( PasswordSASLProvider( password_provider, ), ) return SecurityLayer( ssl_context_factory, certificate_verifier_factory, True, tuple(sasl_providers), )
Construct a :class:`SecurityLayer`. Depending on the arguments passed, different features are enabled or disabled. .. warning:: When using any argument except `password_provider`, be sure to read its documentation below the following overview **carefully**. Many arguments can be used to shoot yourself in the foot easily, while violating all security expectations. Args: password_provider (:class:`str` or coroutine function): Password source to authenticate with. Keyword Args: pin_store (:class:`dict` or :class:`AbstractPinStore`): Enable use of certificate/public key pinning. `pin_type` controls the type of store used when a dict is passed instead of a pin store object. pin_type (:class:`~aioxmpp.security_layer.PinType`): Type of pin store to create when `pin_store` is a dict. post_handshake_deferred_failure (coroutine function): Coroutine callback to invoke when using certificate pinning and the verification of the certificate was not possible using either PKIX or the pin store. anonymous (:class:`str`, :data:`None` or :data:`False`): trace token for SASL ANONYMOUS (:rfc:`4505`); passing a non-:data:`False` value enables ANONYMOUS authentication. ssl_context_factory (function): Factory function to create the SSL context used to establish transport layer security. Defaults to :func:`aioxmpp.security_layer.default_ssl_context`. no_verify (:class:`bool`): *Disable* all certificate verification. Usage is **strongly discouraged** outside controlled test environments. See below for alternatives. Raises: RuntimeError: if `anonymous` is not :data:`False` and the version of :mod:`aiosasl` does not support ANONYMOUS authentication. Returns: :class:`SecurityLayer`: object holding the entire security layer configuration `password_provider` must either be a coroutine function or a :class:`str`. As a coroutine function, it is called during authentication with the JID we are trying to authenticate against as the first, and the sequence number of the authentication attempt as second argument. The sequence number starts at 0. The coroutine is expected to return :data:`None` or a password. See :class:`PasswordSASLProvider` for details. If `password_provider` is a :class:`str`, a coroutine which returns the string on the first and :data:`None` on subsequent attempts is created and used. If `pin_store` is not :data:`None`, :class:`PinningPKIXCertificateVerifier` is used instead of the default :class:`PKIXCertificateVerifier`. The `pin_store` argument determines the pinned certificates: if it is a dictionary, a :class:`AbstractPinStore` according to the :class:`PinType` passed as `pin_type` argument is created and initialised with the data from the dictionary using its :meth:`~AbstractPinStore.import_from_json` method. Otherwise, `pin_store` must be a :class:`AbstractPinStore` instance which is passed to the verifier. `post_handshake_deferred_callback` is used only if `pin_store` is not :data:`None`. It is passed to the equally-named argument of :class:`PinningPKIXCertificateVerifier`, see the documentation there for details on the semantics. If `post_handshake_deferred_callback` is :data:`None` while `pin_store` is not, a coroutine which returns :data:`False` is substituted. `ssl_context_factory` can be a callable taking no arguments and returning a :class:`OpenSSL.SSL.Context` object. If given, the factory will be used to obtain an SSL context when the stream negotiates transport layer security via TLS. By default, :func:`aioxmpp.security_layer.default_ssl_context` is used, which should be fine for most applications. .. warning:: The :func:`~.default_ssl_context` implementation sets important defaults. It is **strongly recommended** to use the context returned by :func:`~.default_ssl_context` and modify it, instead of creating a new context from scratch when implementing your own factory. If `no_verify` is true, none of the above regarding certificate verifiers matters. The internal null verifier is used, which **disables certificate verification completely**. .. warning:: Disabling certificate verification makes your application vulnerable to trivial Man-in-the-Middle attacks. Do **not** use this outside controlled test environments or when you know **exactly** what you’re doing! If you need to handle certificates which cannot be verified using the public key infrastructure, consider making use of the `pin_store` argument instead. `anonymous` may be a string or :data:`False`. If it is not :data:`False`, :class:`AnonymousSASLProvider` is used before password based authentication is attempted. In addition, it is allowed to set `password_provider` to :data:`None`. `anonymous` is the trace token to use, and SHOULD be the empty string (as specified by :xep:`175`). This requires :mod:`aiosasl` 0.3 or newer. .. note:: :data:`False` and ``""`` are treated differently for the `anonymous` argument, despite both being false-y values! .. note:: If `anonymous` is not :data:`False` and `password_provider` is not :data:`None`, both authentication types are attempted. Anonymous authentication is, in that case, preferred over password-based authentication. If you need to reverse the order, you have to construct your own :class:`SecurityLayer` object. .. warning:: Take the security and privacy considerations from :rfc:`4505` (which specifies the ANONYMOUS SASL mechanism) and :xep:`175` (which discusses the ANONYMOUS SASL mechanism in the XMPP context) into account before using `anonymous`. The versatility and simplicity of use of this function make (pun intended) it the preferred way to construct :class:`SecurityLayer` instances. .. versionadded:: 0.8 Support for SASL ANONYMOUS was added. .. versionadded:: 0.11 Support for `ssl_context_factory`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L1313-L1520
horazont/aioxmpp
aioxmpp/security_layer.py
AbstractPinStore.pin
def pin(self, hostname, x509): """ Pin an :class:`OpenSSL.crypto.X509` object `x509` for use with the given `hostname`. Which information exactly is used to identify the certificate depends :meth:`_x509_key`. """ key = self._x509_key(x509) self._storage.setdefault(hostname, set()).add(key)
python
def pin(self, hostname, x509): """ Pin an :class:`OpenSSL.crypto.X509` object `x509` for use with the given `hostname`. Which information exactly is used to identify the certificate depends :meth:`_x509_key`. """ key = self._x509_key(x509) self._storage.setdefault(hostname, set()).add(key)
Pin an :class:`OpenSSL.crypto.X509` object `x509` for use with the given `hostname`. Which information exactly is used to identify the certificate depends :meth:`_x509_key`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L541-L549
horazont/aioxmpp
aioxmpp/security_layer.py
AbstractPinStore.query
def query(self, hostname, x509): """ Return true if the given :class:`OpenSSL.crypto.X509` object `x509` has previously been pinned for use with the given `hostname` and :data:`None` otherwise. Returning :data:`None` allows this method to be used with :class:`PinningPKIXCertificateVerifier`. """ key = self._x509_key(x509) try: pins = self._storage[hostname] except KeyError: return None if key in pins: return True return None
python
def query(self, hostname, x509): """ Return true if the given :class:`OpenSSL.crypto.X509` object `x509` has previously been pinned for use with the given `hostname` and :data:`None` otherwise. Returning :data:`None` allows this method to be used with :class:`PinningPKIXCertificateVerifier`. """ key = self._x509_key(x509) try: pins = self._storage[hostname] except KeyError: return None if key in pins: return True return None
Return true if the given :class:`OpenSSL.crypto.X509` object `x509` has previously been pinned for use with the given `hostname` and :data:`None` otherwise. Returning :data:`None` allows this method to be used with :class:`PinningPKIXCertificateVerifier`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L551-L570
horazont/aioxmpp
aioxmpp/security_layer.py
AbstractPinStore.export_to_json
def export_to_json(self): """ Return a JSON dictionary which contains all the pins stored in this store. """ return { hostname: sorted(self._encode_key(key) for key in pins) for hostname, pins in self._storage.items() }
python
def export_to_json(self): """ Return a JSON dictionary which contains all the pins stored in this store. """ return { hostname: sorted(self._encode_key(key) for key in pins) for hostname, pins in self._storage.items() }
Return a JSON dictionary which contains all the pins stored in this store.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L584-L593
horazont/aioxmpp
aioxmpp/security_layer.py
AbstractPinStore.import_from_json
def import_from_json(self, data, *, override=False): """ Import a JSON dictionary which must have the same format as exported by :meth:`export`. If *override* is true, the existing data in the pin store will be overriden with the data from `data`. Otherwise, the `data` will be merged into the store. """ if override: self._storage = { hostname: set(self._decode_key(key) for key in pins) for hostname, pins in data.items() } return for hostname, pins in data.items(): existing_pins = self._storage.setdefault(hostname, set()) existing_pins.update(self._decode_key(key) for key in pins)
python
def import_from_json(self, data, *, override=False): """ Import a JSON dictionary which must have the same format as exported by :meth:`export`. If *override* is true, the existing data in the pin store will be overriden with the data from `data`. Otherwise, the `data` will be merged into the store. """ if override: self._storage = { hostname: set(self._decode_key(key) for key in pins) for hostname, pins in data.items() } return for hostname, pins in data.items(): existing_pins = self._storage.setdefault(hostname, set()) existing_pins.update(self._decode_key(key) for key in pins)
Import a JSON dictionary which must have the same format as exported by :meth:`export`. If *override* is true, the existing data in the pin store will be overriden with the data from `data`. Otherwise, the `data` will be merged into the store.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L595-L614
horazont/aioxmpp
aioxmpp/security_layer.py
SASLProvider._find_supported
def _find_supported(self, features, mechanism_classes): """ Find the first mechansim class which supports a mechanism announced in the given stream features. :param features: Current XMPP stream features :type features: :class:`~.nonza.StreamFeatures` :param mechanism_classes: SASL mechanism classes to use :type mechanism_classes: iterable of :class:`SASLMechanism` sub\\ *classes* :raises aioxmpp.errors.SASLUnavailable: if the peer does not announce SASL support :return: the :class:`SASLMechanism` subclass to use and a token :rtype: pair Return a supported SASL mechanism class, by looking the given stream features `features`. If no matching mechanism is found, ``(None, None)`` is returned. Otherwise, a pair consisting of the mechanism class and the value returned by the respective :meth:`~.sasl.SASLMechanism.any_supported` method is returned. The latter is an opaque token which must be passed to the `token` argument of :meth:`_execute` or :meth:`aiosasl.SASLMechanism.authenticate`. """ try: mechanisms = features[SASLMechanisms] except KeyError: logger.error("No sasl mechanisms: %r", list(features)) raise errors.SASLUnavailable( "Remote side does not support SASL") from None remote_mechanism_list = mechanisms.get_mechanism_list() for our_mechanism in mechanism_classes: token = our_mechanism.any_supported(remote_mechanism_list) if token is not None: return our_mechanism, token return None, None
python
def _find_supported(self, features, mechanism_classes): """ Find the first mechansim class which supports a mechanism announced in the given stream features. :param features: Current XMPP stream features :type features: :class:`~.nonza.StreamFeatures` :param mechanism_classes: SASL mechanism classes to use :type mechanism_classes: iterable of :class:`SASLMechanism` sub\\ *classes* :raises aioxmpp.errors.SASLUnavailable: if the peer does not announce SASL support :return: the :class:`SASLMechanism` subclass to use and a token :rtype: pair Return a supported SASL mechanism class, by looking the given stream features `features`. If no matching mechanism is found, ``(None, None)`` is returned. Otherwise, a pair consisting of the mechanism class and the value returned by the respective :meth:`~.sasl.SASLMechanism.any_supported` method is returned. The latter is an opaque token which must be passed to the `token` argument of :meth:`_execute` or :meth:`aiosasl.SASLMechanism.authenticate`. """ try: mechanisms = features[SASLMechanisms] except KeyError: logger.error("No sasl mechanisms: %r", list(features)) raise errors.SASLUnavailable( "Remote side does not support SASL") from None remote_mechanism_list = mechanisms.get_mechanism_list() for our_mechanism in mechanism_classes: token = our_mechanism.any_supported(remote_mechanism_list) if token is not None: return our_mechanism, token return None, None
Find the first mechansim class which supports a mechanism announced in the given stream features. :param features: Current XMPP stream features :type features: :class:`~.nonza.StreamFeatures` :param mechanism_classes: SASL mechanism classes to use :type mechanism_classes: iterable of :class:`SASLMechanism` sub\\ *classes* :raises aioxmpp.errors.SASLUnavailable: if the peer does not announce SASL support :return: the :class:`SASLMechanism` subclass to use and a token :rtype: pair Return a supported SASL mechanism class, by looking the given stream features `features`. If no matching mechanism is found, ``(None, None)`` is returned. Otherwise, a pair consisting of the mechanism class and the value returned by the respective :meth:`~.sasl.SASLMechanism.any_supported` method is returned. The latter is an opaque token which must be passed to the `token` argument of :meth:`_execute` or :meth:`aiosasl.SASLMechanism.authenticate`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L764-L804
horazont/aioxmpp
aioxmpp/security_layer.py
SASLProvider._execute
def _execute(self, intf, mechanism, token): """ Execute a SASL authentication process. :param intf: SASL interface to use :type intf: :class:`~.sasl.SASLXMPPInterface` :param mechanism: SASL mechanism to use :type mechanism: :class:`aiosasl.SASLMechanism` :param token: The opaque token argument for the mechanism :type token: not :data:`None` :raises aiosasl.AuthenticationFailure: if authentication failed due to bad credentials :raises aiosasl.SASLFailure: on other SASL error conditions (such as protocol violations) :return: true if authentication succeeded, false if the mechanism has to be disabled :rtype: :class:`bool` This executes the SASL authentication process. The more specific exceptions are generated by inspecting the :attr:`aiosasl.SASLFailure.opaque_error` on exceptinos raised from the :class:`~.sasl.SASLXMPPInterface`. Other :class:`aiosasl.SASLFailure` exceptions are re-raised without modification. """ sm = aiosasl.SASLStateMachine(intf) try: yield from mechanism.authenticate(sm, token) return True except aiosasl.SASLFailure as err: if err.opaque_error in self.AUTHENTICATION_FAILURES: raise aiosasl.AuthenticationFailure( opaque_error=err.opaque_error, text=err.text) elif err.opaque_error in self.MECHANISM_REJECTED_FAILURES: return False raise
python
def _execute(self, intf, mechanism, token): """ Execute a SASL authentication process. :param intf: SASL interface to use :type intf: :class:`~.sasl.SASLXMPPInterface` :param mechanism: SASL mechanism to use :type mechanism: :class:`aiosasl.SASLMechanism` :param token: The opaque token argument for the mechanism :type token: not :data:`None` :raises aiosasl.AuthenticationFailure: if authentication failed due to bad credentials :raises aiosasl.SASLFailure: on other SASL error conditions (such as protocol violations) :return: true if authentication succeeded, false if the mechanism has to be disabled :rtype: :class:`bool` This executes the SASL authentication process. The more specific exceptions are generated by inspecting the :attr:`aiosasl.SASLFailure.opaque_error` on exceptinos raised from the :class:`~.sasl.SASLXMPPInterface`. Other :class:`aiosasl.SASLFailure` exceptions are re-raised without modification. """ sm = aiosasl.SASLStateMachine(intf) try: yield from mechanism.authenticate(sm, token) return True except aiosasl.SASLFailure as err: if err.opaque_error in self.AUTHENTICATION_FAILURES: raise aiosasl.AuthenticationFailure( opaque_error=err.opaque_error, text=err.text) elif err.opaque_error in self.MECHANISM_REJECTED_FAILURES: return False raise
Execute a SASL authentication process. :param intf: SASL interface to use :type intf: :class:`~.sasl.SASLXMPPInterface` :param mechanism: SASL mechanism to use :type mechanism: :class:`aiosasl.SASLMechanism` :param token: The opaque token argument for the mechanism :type token: not :data:`None` :raises aiosasl.AuthenticationFailure: if authentication failed due to bad credentials :raises aiosasl.SASLFailure: on other SASL error conditions (such as protocol violations) :return: true if authentication succeeded, false if the mechanism has to be disabled :rtype: :class:`bool` This executes the SASL authentication process. The more specific exceptions are generated by inspecting the :attr:`aiosasl.SASLFailure.opaque_error` on exceptinos raised from the :class:`~.sasl.SASLXMPPInterface`. Other :class:`aiosasl.SASLFailure` exceptions are re-raised without modification.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L821-L856
horazont/aioxmpp
aioxmpp/connector.py
STARTTLSConnector.connect
def connect(self, loop, metadata, domain: str, host, port, negotiation_timeout, base_logger=None): """ .. seealso:: :meth:`BaseConnector.connect` For general information on the :meth:`connect` method. Connect to `host` at TCP port number `port`. The :class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used to determine the parameters of the TLS connection. First, a normal TCP connection is opened and the stream header is sent. The stream features are waited for, and then STARTTLS is negotiated if possible. :attr:`~.security_layer.SecurityLayer.tls_required` is honoured: if it is true and TLS negotiation fails, :class:`~.errors.TLSUnavailable` is raised. TLS negotiation is always attempted if :attr:`~.security_layer.SecurityLayer.tls_required` is true, even if the server does not advertise a STARTTLS stream feature. This might help to prevent trivial downgrade attacks, and we don’t have anything to lose at this point anymore anyways. :attr:`~.security_layer.SecurityLayer.ssl_context_factory` and :attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are used to configure the TLS connection. .. versionchanged:: 0.10 The `negotiation_timeout` is set as :attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream. """ features_future = asyncio.Future(loop=loop) stream = protocol.XMLStream( to=domain, features_future=features_future, base_logger=base_logger, ) if base_logger is not None: logger = base_logger.getChild(type(self).__name__) else: logger = logging.getLogger(".".join([ __name__, type(self).__qualname__, ])) try: transport, _ = yield from ssl_transport.create_starttls_connection( loop, lambda: stream, host=host, port=port, peer_hostname=host, server_hostname=to_ascii(domain), use_starttls=True, ) except: # NOQA stream.abort() raise stream.deadtime_hard_limit = timedelta(seconds=negotiation_timeout) features = yield from features_future try: features[nonza.StartTLSFeature] except KeyError: if not metadata.tls_required: return transport, stream, (yield from features_future) logger.debug( "attempting STARTTLS despite not announced since it is" " required") try: response = yield from protocol.send_and_wait_for( stream, [ nonza.StartTLS(), ], [ nonza.StartTLSFailure, nonza.StartTLSProceed, ] ) except errors.StreamError: raise errors.TLSUnavailable( "STARTTLS not supported by server, but required by client" ) if not isinstance(response, nonza.StartTLSProceed): if metadata.tls_required: message = ( "server failed to STARTTLS" ) protocol.send_stream_error_and_close( stream, condition=errors.StreamErrorCondition.POLICY_VIOLATION, text=message, ) raise errors.TLSUnavailable(message) return transport, stream, (yield from features_future) verifier = metadata.certificate_verifier_factory() yield from verifier.pre_handshake( domain, host, port, metadata, ) ssl_context = metadata.ssl_context_factory() verifier.setup_context(ssl_context, transport) yield from stream.starttls( ssl_context=ssl_context, post_handshake_callback=verifier.post_handshake, ) features_future = yield from protocol.reset_stream_and_get_features( stream, timeout=negotiation_timeout, ) return transport, stream, features_future
python
def connect(self, loop, metadata, domain: str, host, port, negotiation_timeout, base_logger=None): """ .. seealso:: :meth:`BaseConnector.connect` For general information on the :meth:`connect` method. Connect to `host` at TCP port number `port`. The :class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used to determine the parameters of the TLS connection. First, a normal TCP connection is opened and the stream header is sent. The stream features are waited for, and then STARTTLS is negotiated if possible. :attr:`~.security_layer.SecurityLayer.tls_required` is honoured: if it is true and TLS negotiation fails, :class:`~.errors.TLSUnavailable` is raised. TLS negotiation is always attempted if :attr:`~.security_layer.SecurityLayer.tls_required` is true, even if the server does not advertise a STARTTLS stream feature. This might help to prevent trivial downgrade attacks, and we don’t have anything to lose at this point anymore anyways. :attr:`~.security_layer.SecurityLayer.ssl_context_factory` and :attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are used to configure the TLS connection. .. versionchanged:: 0.10 The `negotiation_timeout` is set as :attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream. """ features_future = asyncio.Future(loop=loop) stream = protocol.XMLStream( to=domain, features_future=features_future, base_logger=base_logger, ) if base_logger is not None: logger = base_logger.getChild(type(self).__name__) else: logger = logging.getLogger(".".join([ __name__, type(self).__qualname__, ])) try: transport, _ = yield from ssl_transport.create_starttls_connection( loop, lambda: stream, host=host, port=port, peer_hostname=host, server_hostname=to_ascii(domain), use_starttls=True, ) except: # NOQA stream.abort() raise stream.deadtime_hard_limit = timedelta(seconds=negotiation_timeout) features = yield from features_future try: features[nonza.StartTLSFeature] except KeyError: if not metadata.tls_required: return transport, stream, (yield from features_future) logger.debug( "attempting STARTTLS despite not announced since it is" " required") try: response = yield from protocol.send_and_wait_for( stream, [ nonza.StartTLS(), ], [ nonza.StartTLSFailure, nonza.StartTLSProceed, ] ) except errors.StreamError: raise errors.TLSUnavailable( "STARTTLS not supported by server, but required by client" ) if not isinstance(response, nonza.StartTLSProceed): if metadata.tls_required: message = ( "server failed to STARTTLS" ) protocol.send_stream_error_and_close( stream, condition=errors.StreamErrorCondition.POLICY_VIOLATION, text=message, ) raise errors.TLSUnavailable(message) return transport, stream, (yield from features_future) verifier = metadata.certificate_verifier_factory() yield from verifier.pre_handshake( domain, host, port, metadata, ) ssl_context = metadata.ssl_context_factory() verifier.setup_context(ssl_context, transport) yield from stream.starttls( ssl_context=ssl_context, post_handshake_callback=verifier.post_handshake, ) features_future = yield from protocol.reset_stream_and_get_features( stream, timeout=negotiation_timeout, ) return transport, stream, features_future
.. seealso:: :meth:`BaseConnector.connect` For general information on the :meth:`connect` method. Connect to `host` at TCP port number `port`. The :class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used to determine the parameters of the TLS connection. First, a normal TCP connection is opened and the stream header is sent. The stream features are waited for, and then STARTTLS is negotiated if possible. :attr:`~.security_layer.SecurityLayer.tls_required` is honoured: if it is true and TLS negotiation fails, :class:`~.errors.TLSUnavailable` is raised. TLS negotiation is always attempted if :attr:`~.security_layer.SecurityLayer.tls_required` is true, even if the server does not advertise a STARTTLS stream feature. This might help to prevent trivial downgrade attacks, and we don’t have anything to lose at this point anymore anyways. :attr:`~.security_layer.SecurityLayer.ssl_context_factory` and :attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are used to configure the TLS connection. .. versionchanged:: 0.10 The `negotiation_timeout` is set as :attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/connector.py#L147-L274
horazont/aioxmpp
aioxmpp/connector.py
XMPPOverTLSConnector.connect
def connect(self, loop, metadata, domain, host, port, negotiation_timeout, base_logger=None): """ .. seealso:: :meth:`BaseConnector.connect` For general information on the :meth:`connect` method. Connect to `host` at TCP port number `port`. The :class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used to determine the parameters of the TLS connection. The connector connects to the server by directly establishing TLS; no XML stream is started before TLS negotiation, in accordance to :xep:`368` and how legacy SSL was handled in the past. :attr:`~.security_layer.SecurityLayer.ssl_context_factory` and :attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are used to configure the TLS connection. .. versionchanged:: 0.10 The `negotiation_timeout` is set as :attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream. """ features_future = asyncio.Future(loop=loop) stream = protocol.XMLStream( to=domain, features_future=features_future, base_logger=base_logger, ) if base_logger is not None: logger = base_logger.getChild(type(self).__name__) else: logger = logging.getLogger(".".join([ __name__, type(self).__qualname__, ])) verifier = metadata.certificate_verifier_factory() yield from verifier.pre_handshake( domain, host, port, metadata, ) context_factory = self._context_factory_factory(logger, metadata, verifier) try: transport, _ = yield from ssl_transport.create_starttls_connection( loop, lambda: stream, host=host, port=port, peer_hostname=host, server_hostname=to_ascii(domain), post_handshake_callback=verifier.post_handshake, ssl_context_factory=context_factory, use_starttls=False, ) except: # NOQA stream.abort() raise stream.deadtime_hard_limit = timedelta(seconds=negotiation_timeout) return transport, stream, (yield from features_future)
python
def connect(self, loop, metadata, domain, host, port, negotiation_timeout, base_logger=None): """ .. seealso:: :meth:`BaseConnector.connect` For general information on the :meth:`connect` method. Connect to `host` at TCP port number `port`. The :class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used to determine the parameters of the TLS connection. The connector connects to the server by directly establishing TLS; no XML stream is started before TLS negotiation, in accordance to :xep:`368` and how legacy SSL was handled in the past. :attr:`~.security_layer.SecurityLayer.ssl_context_factory` and :attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are used to configure the TLS connection. .. versionchanged:: 0.10 The `negotiation_timeout` is set as :attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream. """ features_future = asyncio.Future(loop=loop) stream = protocol.XMLStream( to=domain, features_future=features_future, base_logger=base_logger, ) if base_logger is not None: logger = base_logger.getChild(type(self).__name__) else: logger = logging.getLogger(".".join([ __name__, type(self).__qualname__, ])) verifier = metadata.certificate_verifier_factory() yield from verifier.pre_handshake( domain, host, port, metadata, ) context_factory = self._context_factory_factory(logger, metadata, verifier) try: transport, _ = yield from ssl_transport.create_starttls_connection( loop, lambda: stream, host=host, port=port, peer_hostname=host, server_hostname=to_ascii(domain), post_handshake_callback=verifier.post_handshake, ssl_context_factory=context_factory, use_starttls=False, ) except: # NOQA stream.abort() raise stream.deadtime_hard_limit = timedelta(seconds=negotiation_timeout) return transport, stream, (yield from features_future)
.. seealso:: :meth:`BaseConnector.connect` For general information on the :meth:`connect` method. Connect to `host` at TCP port number `port`. The :class:`aioxmpp.security_layer.SecurityLayer` object `metadata` is used to determine the parameters of the TLS connection. The connector connects to the server by directly establishing TLS; no XML stream is started before TLS negotiation, in accordance to :xep:`368` and how legacy SSL was handled in the past. :attr:`~.security_layer.SecurityLayer.ssl_context_factory` and :attr:`~.security_layer.SecurityLayer.certificate_verifier_factory` are used to configure the TLS connection. .. versionchanged:: 0.10 The `negotiation_timeout` is set as :attr:`~.XMLStream.deadtime_hard_limit` on the returned XML stream.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/connector.py#L314-L384
horazont/aioxmpp
aioxmpp/xso/__init__.py
normalize_tag
def normalize_tag(tag): """ Normalize an XML element tree `tag` into the tuple format. The following input formats are accepted: * ElementTree namespaced string, e.g. ``{uri:bar}foo`` * Unnamespaced tags, e.g. ``foo`` * Two-tuples consisting of `namespace_uri` and `localpart`; `namespace_uri` may be :data:`None` if the tag is supposed to be namespaceless. Otherwise it must be, like `localpart`, a :class:`str`. Return a two-tuple consisting the ``(namespace_uri, localpart)`` format. """ if isinstance(tag, str): namespace_uri, sep, localname = tag.partition("}") if sep: if not namespace_uri.startswith("{"): raise ValueError("not a valid etree-format tag") namespace_uri = namespace_uri[1:] else: localname = namespace_uri namespace_uri = None return (namespace_uri, localname) elif len(tag) != 2: raise ValueError("not a valid tuple-format tag") else: if any(part is not None and not isinstance(part, str) for part in tag): raise TypeError("tuple-format tags must only contain str and None") if tag[1] is None: raise ValueError("tuple-format localname must not be None") return tag
python
def normalize_tag(tag): """ Normalize an XML element tree `tag` into the tuple format. The following input formats are accepted: * ElementTree namespaced string, e.g. ``{uri:bar}foo`` * Unnamespaced tags, e.g. ``foo`` * Two-tuples consisting of `namespace_uri` and `localpart`; `namespace_uri` may be :data:`None` if the tag is supposed to be namespaceless. Otherwise it must be, like `localpart`, a :class:`str`. Return a two-tuple consisting the ``(namespace_uri, localpart)`` format. """ if isinstance(tag, str): namespace_uri, sep, localname = tag.partition("}") if sep: if not namespace_uri.startswith("{"): raise ValueError("not a valid etree-format tag") namespace_uri = namespace_uri[1:] else: localname = namespace_uri namespace_uri = None return (namespace_uri, localname) elif len(tag) != 2: raise ValueError("not a valid tuple-format tag") else: if any(part is not None and not isinstance(part, str) for part in tag): raise TypeError("tuple-format tags must only contain str and None") if tag[1] is None: raise ValueError("tuple-format localname must not be None") return tag
Normalize an XML element tree `tag` into the tuple format. The following input formats are accepted: * ElementTree namespaced string, e.g. ``{uri:bar}foo`` * Unnamespaced tags, e.g. ``foo`` * Two-tuples consisting of `namespace_uri` and `localpart`; `namespace_uri` may be :data:`None` if the tag is supposed to be namespaceless. Otherwise it must be, like `localpart`, a :class:`str`. Return a two-tuple consisting the ``(namespace_uri, localpart)`` format.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/__init__.py#L463-L493
horazont/aioxmpp
aioxmpp/im/conversation.py
AbstractConversation.send_message
def send_message(self, body): """ Send a message to the conversation. :param msg: The message to send. :type msg: :class:`aioxmpp.Message` :return: The stanza token obtained from sending. :rtype: :class:`~aioxmpp.stream.StanzaToken` The default implementation simply calls :meth:`send_message_tracked` and immediately cancels the tracking object, returning only the stanza token. There is no need to provide proper address attributes on `msg`. Implementations will override those attributes with the values appropriate for the conversation. Some implementations may allow the user to choose a :attr:`~aioxmpp.Message.type_`, but others may simply stamp it over. Subclasses may override this method with a more specialised implementation. Subclasses which do not provide tracked message sending **must** override this method to provide untracked message sending. .. seealso:: The corresponding feature is :attr:`.ConversationFeature.SEND_MESSAGE`. See :attr:`features` for details. """ token, tracker = self.send_message_tracked(body) tracker.cancel() return token
python
def send_message(self, body): """ Send a message to the conversation. :param msg: The message to send. :type msg: :class:`aioxmpp.Message` :return: The stanza token obtained from sending. :rtype: :class:`~aioxmpp.stream.StanzaToken` The default implementation simply calls :meth:`send_message_tracked` and immediately cancels the tracking object, returning only the stanza token. There is no need to provide proper address attributes on `msg`. Implementations will override those attributes with the values appropriate for the conversation. Some implementations may allow the user to choose a :attr:`~aioxmpp.Message.type_`, but others may simply stamp it over. Subclasses may override this method with a more specialised implementation. Subclasses which do not provide tracked message sending **must** override this method to provide untracked message sending. .. seealso:: The corresponding feature is :attr:`.ConversationFeature.SEND_MESSAGE`. See :attr:`features` for details. """ token, tracker = self.send_message_tracked(body) tracker.cancel() return token
Send a message to the conversation. :param msg: The message to send. :type msg: :class:`aioxmpp.Message` :return: The stanza token obtained from sending. :rtype: :class:`~aioxmpp.stream.StanzaToken` The default implementation simply calls :meth:`send_message_tracked` and immediately cancels the tracking object, returning only the stanza token. There is no need to provide proper address attributes on `msg`. Implementations will override those attributes with the values appropriate for the conversation. Some implementations may allow the user to choose a :attr:`~aioxmpp.Message.type_`, but others may simply stamp it over. Subclasses may override this method with a more specialised implementation. Subclasses which do not provide tracked message sending **must** override this method to provide untracked message sending. .. seealso:: The corresponding feature is :attr:`.ConversationFeature.SEND_MESSAGE`. See :attr:`features` for details.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/im/conversation.py#L680-L712
horazont/aioxmpp
aioxmpp/im/conversation.py
AbstractConversation.invite
def invite(self, address, text=None, *, mode=InviteMode.DIRECT, allow_upgrade=False): """ Invite another entity to the conversation. :param address: The address of the entity to invite. :type address: :class:`aioxmpp.JID` :param text: A reason/accompanying text for the invitation. :param mode: The invitation mode to use. :type mode: :class:`~.im.InviteMode` :param allow_upgrade: Whether to allow creating a new conversation to satisfy the invitation. :type allow_upgrade: :class:`bool` :raises NotImplementedError: if the requested `mode` is not supported :raises ValueError: if `allow_upgrade` is false, but a new conversation is required. :return: The stanza token for the invitation and the possibly new conversation object :rtype: tuple of :class:`~.StanzaToken` and :class:`~.AbstractConversation` .. note:: Even though this is a coroutine, it returns a stanza token. The coroutine-ness may be needed to generate the invitation in the first place. Sending the actual invitation is done non-blockingly and the stanza token for that is returned. To wait until the invitation has been sent, unpack the stanza token from the result and await it. Return the new conversation object to use. In many cases, this will simply be the current conversation object, but in some cases (e.g. when someone is invited to a one-on-one conversation), a new conversation must be created and used. If `allow_upgrade` is false and a new conversation would be needed to invite an entity, :class:`ValueError` is raised. Additional features: :attr:`~.ConversationFeature.INVITE_DIRECT` Support for :attr:`~.im.InviteMode.DIRECT` mode. :attr:`~.ConversationFeature.INVITE_DIRECT_CONFIGURE` If a direct invitation is used, the conversation will be configured to allow the invitee to join before the invitation is sent. This may fail with a :class:`aioxmpp.errors.XMPPError`, in which case the error is re-raised and the invitation not sent. :attr:`~.ConversationFeature.INVITE_MEDIATED` Support for :attr:`~.im.InviteMode.MEDIATED` mode. :attr:`~.ConversationFeature.INVITE_UPGRADE` If `allow_upgrade` is :data:`True`, an upgrade will be performed and a new conversation is returned. If `allow_upgrade` is :data:`False`, the invite will fail. .. seealso:: The corresponding feature for this method is :attr:`.ConversationFeature.INVITE`. See :attr:`features` for details on the semantics of features. """ raise self._not_implemented_error("inviting entities")
python
def invite(self, address, text=None, *, mode=InviteMode.DIRECT, allow_upgrade=False): """ Invite another entity to the conversation. :param address: The address of the entity to invite. :type address: :class:`aioxmpp.JID` :param text: A reason/accompanying text for the invitation. :param mode: The invitation mode to use. :type mode: :class:`~.im.InviteMode` :param allow_upgrade: Whether to allow creating a new conversation to satisfy the invitation. :type allow_upgrade: :class:`bool` :raises NotImplementedError: if the requested `mode` is not supported :raises ValueError: if `allow_upgrade` is false, but a new conversation is required. :return: The stanza token for the invitation and the possibly new conversation object :rtype: tuple of :class:`~.StanzaToken` and :class:`~.AbstractConversation` .. note:: Even though this is a coroutine, it returns a stanza token. The coroutine-ness may be needed to generate the invitation in the first place. Sending the actual invitation is done non-blockingly and the stanza token for that is returned. To wait until the invitation has been sent, unpack the stanza token from the result and await it. Return the new conversation object to use. In many cases, this will simply be the current conversation object, but in some cases (e.g. when someone is invited to a one-on-one conversation), a new conversation must be created and used. If `allow_upgrade` is false and a new conversation would be needed to invite an entity, :class:`ValueError` is raised. Additional features: :attr:`~.ConversationFeature.INVITE_DIRECT` Support for :attr:`~.im.InviteMode.DIRECT` mode. :attr:`~.ConversationFeature.INVITE_DIRECT_CONFIGURE` If a direct invitation is used, the conversation will be configured to allow the invitee to join before the invitation is sent. This may fail with a :class:`aioxmpp.errors.XMPPError`, in which case the error is re-raised and the invitation not sent. :attr:`~.ConversationFeature.INVITE_MEDIATED` Support for :attr:`~.im.InviteMode.MEDIATED` mode. :attr:`~.ConversationFeature.INVITE_UPGRADE` If `allow_upgrade` is :data:`True`, an upgrade will be performed and a new conversation is returned. If `allow_upgrade` is :data:`False`, the invite will fail. .. seealso:: The corresponding feature for this method is :attr:`.ConversationFeature.INVITE`. See :attr:`features` for details on the semantics of features. """ raise self._not_implemented_error("inviting entities")
Invite another entity to the conversation. :param address: The address of the entity to invite. :type address: :class:`aioxmpp.JID` :param text: A reason/accompanying text for the invitation. :param mode: The invitation mode to use. :type mode: :class:`~.im.InviteMode` :param allow_upgrade: Whether to allow creating a new conversation to satisfy the invitation. :type allow_upgrade: :class:`bool` :raises NotImplementedError: if the requested `mode` is not supported :raises ValueError: if `allow_upgrade` is false, but a new conversation is required. :return: The stanza token for the invitation and the possibly new conversation object :rtype: tuple of :class:`~.StanzaToken` and :class:`~.AbstractConversation` .. note:: Even though this is a coroutine, it returns a stanza token. The coroutine-ness may be needed to generate the invitation in the first place. Sending the actual invitation is done non-blockingly and the stanza token for that is returned. To wait until the invitation has been sent, unpack the stanza token from the result and await it. Return the new conversation object to use. In many cases, this will simply be the current conversation object, but in some cases (e.g. when someone is invited to a one-on-one conversation), a new conversation must be created and used. If `allow_upgrade` is false and a new conversation would be needed to invite an entity, :class:`ValueError` is raised. Additional features: :attr:`~.ConversationFeature.INVITE_DIRECT` Support for :attr:`~.im.InviteMode.DIRECT` mode. :attr:`~.ConversationFeature.INVITE_DIRECT_CONFIGURE` If a direct invitation is used, the conversation will be configured to allow the invitee to join before the invitation is sent. This may fail with a :class:`aioxmpp.errors.XMPPError`, in which case the error is re-raised and the invitation not sent. :attr:`~.ConversationFeature.INVITE_MEDIATED` Support for :attr:`~.im.InviteMode.MEDIATED` mode. :attr:`~.ConversationFeature.INVITE_UPGRADE` If `allow_upgrade` is :data:`True`, an upgrade will be performed and a new conversation is returned. If `allow_upgrade` is :data:`False`, the invite will fail. .. seealso:: The corresponding feature for this method is :attr:`.ConversationFeature.INVITE`. See :attr:`features` for details on the semantics of features.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/im/conversation.py#L809-L873
horazont/aioxmpp
examples/xmpp_bridge.py
stdout_writer
async def stdout_writer(): """ This is a bit complex, as stdout can be a pipe or a file. If it is a file, we cannot use :meth:`asycnio.BaseEventLoop.connect_write_pipe`. """ if sys.stdout.seekable(): # it’s a file return sys.stdout.buffer.raw if os.isatty(sys.stdin.fileno()): # it’s a tty, use fd 0 fd_to_use = 0 else: fd_to_use = 1 twrite, pwrite = await loop.connect_write_pipe( asyncio.streams.FlowControlMixin, os.fdopen(fd_to_use, "wb"), ) swrite = asyncio.StreamWriter( twrite, pwrite, None, loop, ) return swrite
python
async def stdout_writer(): """ This is a bit complex, as stdout can be a pipe or a file. If it is a file, we cannot use :meth:`asycnio.BaseEventLoop.connect_write_pipe`. """ if sys.stdout.seekable(): # it’s a file return sys.stdout.buffer.raw if os.isatty(sys.stdin.fileno()): # it’s a tty, use fd 0 fd_to_use = 0 else: fd_to_use = 1 twrite, pwrite = await loop.connect_write_pipe( asyncio.streams.FlowControlMixin, os.fdopen(fd_to_use, "wb"), ) swrite = asyncio.StreamWriter( twrite, pwrite, None, loop, ) return swrite
This is a bit complex, as stdout can be a pipe or a file. If it is a file, we cannot use :meth:`asycnio.BaseEventLoop.connect_write_pipe`.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/examples/xmpp_bridge.py#L32-L61
horazont/aioxmpp
aioxmpp/hashes.py
hash_from_algo
def hash_from_algo(algo): """ Return a :mod:`hashlib` hash given the :xep:`300` `algo`. :param algo: The algorithm identifier as defined in :xep:`300`. :type algo: :class:`str` :raises NotImplementedError: if the hash algortihm is not supported by :mod:`hashlib`. :raises ValueError: if the hash algorithm MUST NOT be supported. :return: A hash object from :mod:`hashlib` or compatible. If the `algo` is not supported by the :mod:`hashlib` module, :class:`NotImplementedError` is raised. """ try: enabled, (fun_name, fun_args, fun_kwargs) = _HASH_ALGO_MAP[algo] except KeyError: raise NotImplementedError( "hash algorithm {!r} unknown".format(algo) ) from None if not enabled: raise ValueError( "support of {} in XMPP is forbidden".format(algo) ) try: fun = getattr(hashlib, fun_name) except AttributeError as exc: raise NotImplementedError( "{} not supported by hashlib".format(algo) ) from exc return fun(*fun_args, **fun_kwargs)
python
def hash_from_algo(algo): """ Return a :mod:`hashlib` hash given the :xep:`300` `algo`. :param algo: The algorithm identifier as defined in :xep:`300`. :type algo: :class:`str` :raises NotImplementedError: if the hash algortihm is not supported by :mod:`hashlib`. :raises ValueError: if the hash algorithm MUST NOT be supported. :return: A hash object from :mod:`hashlib` or compatible. If the `algo` is not supported by the :mod:`hashlib` module, :class:`NotImplementedError` is raised. """ try: enabled, (fun_name, fun_args, fun_kwargs) = _HASH_ALGO_MAP[algo] except KeyError: raise NotImplementedError( "hash algorithm {!r} unknown".format(algo) ) from None if not enabled: raise ValueError( "support of {} in XMPP is forbidden".format(algo) ) try: fun = getattr(hashlib, fun_name) except AttributeError as exc: raise NotImplementedError( "{} not supported by hashlib".format(algo) ) from exc return fun(*fun_args, **fun_kwargs)
Return a :mod:`hashlib` hash given the :xep:`300` `algo`. :param algo: The algorithm identifier as defined in :xep:`300`. :type algo: :class:`str` :raises NotImplementedError: if the hash algortihm is not supported by :mod:`hashlib`. :raises ValueError: if the hash algorithm MUST NOT be supported. :return: A hash object from :mod:`hashlib` or compatible. If the `algo` is not supported by the :mod:`hashlib` module, :class:`NotImplementedError` is raised.
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/hashes.py#L141-L175