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/hashes.py | algo_of_hash | def algo_of_hash(h):
"""
Return a :xep:`300` `algo` from a given :mod:`hashlib` hash.
:param h: Hash object from :mod:`hashlib`.
:raises ValueError: if `h` does not have a defined `algo` value.
:raises ValueError: if the hash function MUST NOT be supported.
:return: The `algo` value for the given hash.
:rtype: :class:`str`
.. warning::
Use with caution for :func:`hashlib.blake2b` hashes.
:func:`algo_of_hash` cannot safely determine whether blake2b was
initialised with a salt, personality, key or other non-default
:xep:`300` mode.
In such a case, the return value will be the matching ``blake2b-*``
`algo`, but the digest will not be compatible with the results of other
implementations.
"""
try:
enabled, algo = _HASH_ALGO_REVERSE_MAP[h.name]
except KeyError:
pass
else:
if not enabled:
raise ValueError("support of {} in XMPP is forbidden".format(
algo
))
return algo
if h.name == "blake2b":
return "blake2b-{}".format(h.digest_size * 8)
raise ValueError(
"unknown hash implementation: {!r}".format(h)
) | python | def algo_of_hash(h):
"""
Return a :xep:`300` `algo` from a given :mod:`hashlib` hash.
:param h: Hash object from :mod:`hashlib`.
:raises ValueError: if `h` does not have a defined `algo` value.
:raises ValueError: if the hash function MUST NOT be supported.
:return: The `algo` value for the given hash.
:rtype: :class:`str`
.. warning::
Use with caution for :func:`hashlib.blake2b` hashes.
:func:`algo_of_hash` cannot safely determine whether blake2b was
initialised with a salt, personality, key or other non-default
:xep:`300` mode.
In such a case, the return value will be the matching ``blake2b-*``
`algo`, but the digest will not be compatible with the results of other
implementations.
"""
try:
enabled, algo = _HASH_ALGO_REVERSE_MAP[h.name]
except KeyError:
pass
else:
if not enabled:
raise ValueError("support of {} in XMPP is forbidden".format(
algo
))
return algo
if h.name == "blake2b":
return "blake2b-{}".format(h.digest_size * 8)
raise ValueError(
"unknown hash implementation: {!r}".format(h)
) | Return a :xep:`300` `algo` from a given :mod:`hashlib` hash.
:param h: Hash object from :mod:`hashlib`.
:raises ValueError: if `h` does not have a defined `algo` value.
:raises ValueError: if the hash function MUST NOT be supported.
:return: The `algo` value for the given hash.
:rtype: :class:`str`
.. warning::
Use with caution for :func:`hashlib.blake2b` hashes.
:func:`algo_of_hash` cannot safely determine whether blake2b was
initialised with a salt, personality, key or other non-default
:xep:`300` mode.
In such a case, the return value will be the matching ``blake2b-*``
`algo`, but the digest will not be compatible with the results of other
implementations. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/hashes.py#L178-L216 |
horazont/aioxmpp | aioxmpp/hashes.py | HashService.select_common_hashes | def select_common_hashes(self, other_entity):
"""
Return the list of algos supported by us and `other_entity`. The
algorithms are represented by their :xep:`300` URNs
(`urn:xmpp:hash-function-text-names:...`).
:param other_entity: the address of another entity
:type other_entity: :class:`aioxmpp.JID`
:returns: the identifiers of the hash algorithms supported by
both us and the other entity
:rtype: :class:`set`
:raises RuntimeError: if the other entity does not support the
:xep:`300` feature nor does not publish hash functions
URNs we support.
Note: This assumes the protocol is supported if valid hash
function features are detected, even if `urn:xmpp:hashes:2` is
not listed as a feature.
"""
disco_info = yield from self._disco_client.query_info(other_entity)
intersection = disco_info.features & SUPPORTED_HASH_FEATURES
if (not intersection and
namespaces.xep0300_hashes2 not in disco_info.features):
raise RuntimeError(
"Remote does not support the urn:xmpp:hashes:2 feature.")
return intersection | python | def select_common_hashes(self, other_entity):
"""
Return the list of algos supported by us and `other_entity`. The
algorithms are represented by their :xep:`300` URNs
(`urn:xmpp:hash-function-text-names:...`).
:param other_entity: the address of another entity
:type other_entity: :class:`aioxmpp.JID`
:returns: the identifiers of the hash algorithms supported by
both us and the other entity
:rtype: :class:`set`
:raises RuntimeError: if the other entity does not support the
:xep:`300` feature nor does not publish hash functions
URNs we support.
Note: This assumes the protocol is supported if valid hash
function features are detected, even if `urn:xmpp:hashes:2` is
not listed as a feature.
"""
disco_info = yield from self._disco_client.query_info(other_entity)
intersection = disco_info.features & SUPPORTED_HASH_FEATURES
if (not intersection and
namespaces.xep0300_hashes2 not in disco_info.features):
raise RuntimeError(
"Remote does not support the urn:xmpp:hashes:2 feature.")
return intersection | Return the list of algos supported by us and `other_entity`. The
algorithms are represented by their :xep:`300` URNs
(`urn:xmpp:hash-function-text-names:...`).
:param other_entity: the address of another entity
:type other_entity: :class:`aioxmpp.JID`
:returns: the identifiers of the hash algorithms supported by
both us and the other entity
:rtype: :class:`set`
:raises RuntimeError: if the other entity does not support the
:xep:`300` feature nor does not publish hash functions
URNs we support.
Note: This assumes the protocol is supported if valid hash
function features are detected, even if `urn:xmpp:hashes:2` is
not listed as a feature. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/hashes.py#L377-L402 |
horazont/aioxmpp | aioxmpp/callbacks.py | first_signal | def first_signal(*signals):
"""
Connect to multiple signals and wait for the first to emit.
:param signals: Signals to connect to.
:type signals: :class:`AdHocSignal`
:return: An awaitable for the first signal to emit.
The awaitable returns the first argument passed to the signal. If the first
argument is an exception, the exception is re-raised from the awaitable.
A common use-case is a situation where a class exposes a "on_finished" type
signal and an "on_failure" type signal. :func:`first_signal` can be used
to combine those nicely::
# e.g. a aioxmpp.im.conversation.AbstractConversation
conversation = ...
await first_signal(
# emits without arguments when the conversation is successfully
# entered
conversation.on_enter,
# emits with an exception when entering the conversation fails
conversation.on_failure,
)
# await first_signal(...) will either raise an exception (failed) or
# return None (success)
.. warning::
Only works with signals which emit with zero or one argument. Signals
which emit with more than one argument or with keyword arguments are
silently ignored! (Thus, if only such signals are connected, the
future will never complete.)
(This is a side-effect of the implementation of
:meth:`AdHocSignal.AUTO_FUTURE`).
.. note::
Does not work with coroutine signals (:class:`SyncAdHocSignal`).
"""
fut = asyncio.Future()
for signal in signals:
signal.connect(fut, signal.AUTO_FUTURE)
return fut | python | def first_signal(*signals):
"""
Connect to multiple signals and wait for the first to emit.
:param signals: Signals to connect to.
:type signals: :class:`AdHocSignal`
:return: An awaitable for the first signal to emit.
The awaitable returns the first argument passed to the signal. If the first
argument is an exception, the exception is re-raised from the awaitable.
A common use-case is a situation where a class exposes a "on_finished" type
signal and an "on_failure" type signal. :func:`first_signal` can be used
to combine those nicely::
# e.g. a aioxmpp.im.conversation.AbstractConversation
conversation = ...
await first_signal(
# emits without arguments when the conversation is successfully
# entered
conversation.on_enter,
# emits with an exception when entering the conversation fails
conversation.on_failure,
)
# await first_signal(...) will either raise an exception (failed) or
# return None (success)
.. warning::
Only works with signals which emit with zero or one argument. Signals
which emit with more than one argument or with keyword arguments are
silently ignored! (Thus, if only such signals are connected, the
future will never complete.)
(This is a side-effect of the implementation of
:meth:`AdHocSignal.AUTO_FUTURE`).
.. note::
Does not work with coroutine signals (:class:`SyncAdHocSignal`).
"""
fut = asyncio.Future()
for signal in signals:
signal.connect(fut, signal.AUTO_FUTURE)
return fut | Connect to multiple signals and wait for the first to emit.
:param signals: Signals to connect to.
:type signals: :class:`AdHocSignal`
:return: An awaitable for the first signal to emit.
The awaitable returns the first argument passed to the signal. If the first
argument is an exception, the exception is re-raised from the awaitable.
A common use-case is a situation where a class exposes a "on_finished" type
signal and an "on_failure" type signal. :func:`first_signal` can be used
to combine those nicely::
# e.g. a aioxmpp.im.conversation.AbstractConversation
conversation = ...
await first_signal(
# emits without arguments when the conversation is successfully
# entered
conversation.on_enter,
# emits with an exception when entering the conversation fails
conversation.on_failure,
)
# await first_signal(...) will either raise an exception (failed) or
# return None (success)
.. warning::
Only works with signals which emit with zero or one argument. Signals
which emit with more than one argument or with keyword arguments are
silently ignored! (Thus, if only such signals are connected, the
future will never complete.)
(This is a side-effect of the implementation of
:meth:`AdHocSignal.AUTO_FUTURE`).
.. note::
Does not work with coroutine signals (:class:`SyncAdHocSignal`). | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L853-L898 |
horazont/aioxmpp | aioxmpp/callbacks.py | AdHocSignal.connect | def connect(self, f, mode=None):
"""
Connect an object `f` to the signal. The type the object needs to have
depends on `mode`, but usually it needs to be a callable.
:meth:`connect` returns an opaque token which can be used with
:meth:`disconnect` to disconnect the object from the signal.
The default value for `mode` is :attr:`STRONG`. Any decorator can be
used as argument for `mode` and it is applied to `f`. The result is
stored internally and is what will be called when the signal is being
emitted.
If the result of `mode` returns a false value during emission, the
connection is removed.
.. note::
The return values required by the callable returned by `mode` and
the one required by a callable passed to `f` using the predefined
modes are complementary!
A callable `f` needs to return true to be removed from the
connections, while a callable returned by the `mode` decorator needs
to return false.
Existing modes are listed below.
"""
mode = mode or self.STRONG
self.logger.debug("connecting %r with mode %r", f, mode)
return self._connect(mode(f)) | python | def connect(self, f, mode=None):
"""
Connect an object `f` to the signal. The type the object needs to have
depends on `mode`, but usually it needs to be a callable.
:meth:`connect` returns an opaque token which can be used with
:meth:`disconnect` to disconnect the object from the signal.
The default value for `mode` is :attr:`STRONG`. Any decorator can be
used as argument for `mode` and it is applied to `f`. The result is
stored internally and is what will be called when the signal is being
emitted.
If the result of `mode` returns a false value during emission, the
connection is removed.
.. note::
The return values required by the callable returned by `mode` and
the one required by a callable passed to `f` using the predefined
modes are complementary!
A callable `f` needs to return true to be removed from the
connections, while a callable returned by the `mode` decorator needs
to return false.
Existing modes are listed below.
"""
mode = mode or self.STRONG
self.logger.debug("connecting %r with mode %r", f, mode)
return self._connect(mode(f)) | Connect an object `f` to the signal. The type the object needs to have
depends on `mode`, but usually it needs to be a callable.
:meth:`connect` returns an opaque token which can be used with
:meth:`disconnect` to disconnect the object from the signal.
The default value for `mode` is :attr:`STRONG`. Any decorator can be
used as argument for `mode` and it is applied to `f`. The result is
stored internally and is what will be called when the signal is being
emitted.
If the result of `mode` returns a false value during emission, the
connection is removed.
.. note::
The return values required by the callable returned by `mode` and
the one required by a callable passed to `f` using the predefined
modes are complementary!
A callable `f` needs to return true to be removed from the
connections, while a callable returned by the `mode` decorator needs
to return false.
Existing modes are listed below. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L472-L503 |
horazont/aioxmpp | aioxmpp/callbacks.py | AdHocSignal.fire | def fire(self, *args, **kwargs):
"""
Emit the signal, calling all connected objects in-line with the given
arguments and in the order they were registered.
:class:`AdHocSignal` provides full isolation with respect to
exceptions. If a connected listener raises an exception, the other
listeners are executed as normal, but the raising listener is removed
from the signal. The exception is logged to :attr:`logger` and *not*
re-raised, so that the caller of the signal is also not affected.
Instead of calling :meth:`fire` explicitly, the ad-hoc signal object
itself can be called, too.
"""
for token, wrapper in list(self._connections.items()):
try:
keep = wrapper(args, kwargs)
except Exception:
self.logger.exception("listener attached to signal raised")
keep = False
if not keep:
del self._connections[token] | python | def fire(self, *args, **kwargs):
"""
Emit the signal, calling all connected objects in-line with the given
arguments and in the order they were registered.
:class:`AdHocSignal` provides full isolation with respect to
exceptions. If a connected listener raises an exception, the other
listeners are executed as normal, but the raising listener is removed
from the signal. The exception is logged to :attr:`logger` and *not*
re-raised, so that the caller of the signal is also not affected.
Instead of calling :meth:`fire` explicitly, the ad-hoc signal object
itself can be called, too.
"""
for token, wrapper in list(self._connections.items()):
try:
keep = wrapper(args, kwargs)
except Exception:
self.logger.exception("listener attached to signal raised")
keep = False
if not keep:
del self._connections[token] | Emit the signal, calling all connected objects in-line with the given
arguments and in the order they were registered.
:class:`AdHocSignal` provides full isolation with respect to
exceptions. If a connected listener raises an exception, the other
listeners are executed as normal, but the raising listener is removed
from the signal. The exception is logged to :attr:`logger` and *not*
re-raised, so that the caller of the signal is also not affected.
Instead of calling :meth:`fire` explicitly, the ad-hoc signal object
itself can be called, too. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L520-L541 |
horazont/aioxmpp | aioxmpp/callbacks.py | AdHocSignal.future | def future(self):
"""
Return a :class:`asyncio.Future` which has been :meth:`connect`\\ -ed
using :attr:`AUTO_FUTURE`.
The token returned by :meth:`connect` is not returned; to remove the
future from the signal, just cancel it.
"""
fut = asyncio.Future()
self.connect(fut, self.AUTO_FUTURE)
return fut | python | def future(self):
"""
Return a :class:`asyncio.Future` which has been :meth:`connect`\\ -ed
using :attr:`AUTO_FUTURE`.
The token returned by :meth:`connect` is not returned; to remove the
future from the signal, just cancel it.
"""
fut = asyncio.Future()
self.connect(fut, self.AUTO_FUTURE)
return fut | Return a :class:`asyncio.Future` which has been :meth:`connect`\\ -ed
using :attr:`AUTO_FUTURE`.
The token returned by :meth:`connect` is not returned; to remove the
future from the signal, just cancel it. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L543-L553 |
horazont/aioxmpp | aioxmpp/callbacks.py | SyncAdHocSignal.connect | def connect(self, coro):
"""
The coroutine `coro` is connected to the signal. The coroutine must
return a true value, unless it wants to be disconnected from the
signal.
.. note::
This is different from the return value convention with
:attr:`AdHocSignal.STRONG` and :attr:`AdHocSignal.WEAK`.
:meth:`connect` returns a token which can be used with
:meth:`disconnect` to disconnect the coroutine.
"""
self.logger.debug("connecting %r", coro)
return self._connect(coro) | python | def connect(self, coro):
"""
The coroutine `coro` is connected to the signal. The coroutine must
return a true value, unless it wants to be disconnected from the
signal.
.. note::
This is different from the return value convention with
:attr:`AdHocSignal.STRONG` and :attr:`AdHocSignal.WEAK`.
:meth:`connect` returns a token which can be used with
:meth:`disconnect` to disconnect the coroutine.
"""
self.logger.debug("connecting %r", coro)
return self._connect(coro) | The coroutine `coro` is connected to the signal. The coroutine must
return a true value, unless it wants to be disconnected from the
signal.
.. note::
This is different from the return value convention with
:attr:`AdHocSignal.STRONG` and :attr:`AdHocSignal.WEAK`.
:meth:`connect` returns a token which can be used with
:meth:`disconnect` to disconnect the coroutine. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L572-L587 |
horazont/aioxmpp | aioxmpp/callbacks.py | SyncAdHocSignal.fire | def fire(self, *args, **kwargs):
"""
Emit the signal, calling all coroutines in-line with the given
arguments and in the order they were registered.
This is obviously a coroutine.
Instead of calling :meth:`fire` explicitly, the ad-hoc signal object
itself can be called, too.
"""
for token, coro in list(self._connections.items()):
keep = yield from coro(*args, **kwargs)
if not keep:
del self._connections[token] | python | def fire(self, *args, **kwargs):
"""
Emit the signal, calling all coroutines in-line with the given
arguments and in the order they were registered.
This is obviously a coroutine.
Instead of calling :meth:`fire` explicitly, the ad-hoc signal object
itself can be called, too.
"""
for token, coro in list(self._connections.items()):
keep = yield from coro(*args, **kwargs)
if not keep:
del self._connections[token] | Emit the signal, calling all coroutines in-line with the given
arguments and in the order they were registered.
This is obviously a coroutine.
Instead of calling :meth:`fire` explicitly, the ad-hoc signal object
itself can be called, too. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L605-L618 |
horazont/aioxmpp | aioxmpp/callbacks.py | Filter.register | def register(self, func, order):
"""
Add a function to the filter chain.
:param func: A callable which is to be added to the filter chain.
:param order: An object indicating the ordering of the function
relative to the others.
:return: Token representing the registration.
Register the function `func` as a filter into the chain. `order` must
be a value which is used as a sorting key to order the functions
registered in the chain.
The type of `order` depends on the use of the filter, as does the
number of arguments and keyword arguments which `func` must accept.
This will generally be documented at the place where the
:class:`Filter` is used.
Functions with the same order are sorted in the order of their
addition, with the function which was added earliest first.
Remember that all values passed to `order` which are registered at the
same time in the same :class:`Filter` need to be totally orderable with
respect to each other.
The returned token can be used to :meth:`unregister` a filter.
"""
token = self.Token()
self._filter_order.append((order, token, func))
self._filter_order.sort(key=lambda x: x[0])
return token | python | def register(self, func, order):
"""
Add a function to the filter chain.
:param func: A callable which is to be added to the filter chain.
:param order: An object indicating the ordering of the function
relative to the others.
:return: Token representing the registration.
Register the function `func` as a filter into the chain. `order` must
be a value which is used as a sorting key to order the functions
registered in the chain.
The type of `order` depends on the use of the filter, as does the
number of arguments and keyword arguments which `func` must accept.
This will generally be documented at the place where the
:class:`Filter` is used.
Functions with the same order are sorted in the order of their
addition, with the function which was added earliest first.
Remember that all values passed to `order` which are registered at the
same time in the same :class:`Filter` need to be totally orderable with
respect to each other.
The returned token can be used to :meth:`unregister` a filter.
"""
token = self.Token()
self._filter_order.append((order, token, func))
self._filter_order.sort(key=lambda x: x[0])
return token | Add a function to the filter chain.
:param func: A callable which is to be added to the filter chain.
:param order: An object indicating the ordering of the function
relative to the others.
:return: Token representing the registration.
Register the function `func` as a filter into the chain. `order` must
be a value which is used as a sorting key to order the functions
registered in the chain.
The type of `order` depends on the use of the filter, as does the
number of arguments and keyword arguments which `func` must accept.
This will generally be documented at the place where the
:class:`Filter` is used.
Functions with the same order are sorted in the order of their
addition, with the function which was added earliest first.
Remember that all values passed to `order` which are registered at the
same time in the same :class:`Filter` need to be totally orderable with
respect to each other.
The returned token can be used to :meth:`unregister` a filter. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L758-L788 |
horazont/aioxmpp | aioxmpp/callbacks.py | Filter.filter | def filter(self, obj, *args, **kwargs):
"""
Filter the given object through the filter chain.
:param obj: The object to filter
:param args: Additional arguments to pass to each filter function.
:param kwargs: Additional keyword arguments to pass to each filter
function.
:return: The filtered object or :data:`None`
See the documentation of :class:`Filter` on how filtering operates.
Returns the object returned by the last function in the filter chain or
:data:`None` if any function returned :data:`None`.
"""
for _, _, func in self._filter_order:
obj = func(obj, *args, **kwargs)
if obj is None:
return None
return obj | python | def filter(self, obj, *args, **kwargs):
"""
Filter the given object through the filter chain.
:param obj: The object to filter
:param args: Additional arguments to pass to each filter function.
:param kwargs: Additional keyword arguments to pass to each filter
function.
:return: The filtered object or :data:`None`
See the documentation of :class:`Filter` on how filtering operates.
Returns the object returned by the last function in the filter chain or
:data:`None` if any function returned :data:`None`.
"""
for _, _, func in self._filter_order:
obj = func(obj, *args, **kwargs)
if obj is None:
return None
return obj | Filter the given object through the filter chain.
:param obj: The object to filter
:param args: Additional arguments to pass to each filter function.
:param kwargs: Additional keyword arguments to pass to each filter
function.
:return: The filtered object or :data:`None`
See the documentation of :class:`Filter` on how filtering operates.
Returns the object returned by the last function in the filter chain or
:data:`None` if any function returned :data:`None`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L790-L809 |
horazont/aioxmpp | aioxmpp/callbacks.py | Filter.unregister | def unregister(self, token_to_remove):
"""
Unregister a filter function.
:param token_to_remove: The token as returned by :meth:`register`.
Unregister a function from the filter chain using the token returned by
:meth:`register`.
"""
for i, (_, token, _) in enumerate(self._filter_order):
if token == token_to_remove:
break
else:
raise ValueError("unregistered token: {!r}".format(
token_to_remove))
del self._filter_order[i] | python | def unregister(self, token_to_remove):
"""
Unregister a filter function.
:param token_to_remove: The token as returned by :meth:`register`.
Unregister a function from the filter chain using the token returned by
:meth:`register`.
"""
for i, (_, token, _) in enumerate(self._filter_order):
if token == token_to_remove:
break
else:
raise ValueError("unregistered token: {!r}".format(
token_to_remove))
del self._filter_order[i] | Unregister a filter function.
:param token_to_remove: The token as returned by :meth:`register`.
Unregister a function from the filter chain using the token returned by
:meth:`register`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L811-L826 |
horazont/aioxmpp | aioxmpp/callbacks.py | Filter.context_register | def context_register(self, func, *args):
"""
:term:`Context manager <context manager>` which temporarily registers a
filter function.
:param func: The filter function to register.
:param order: The sorting key for the filter function.
:rtype: :term:`context manager`
:return: Context manager which temporarily registers the filter
function.
If :meth:`register` does not require `order` because it has been
overridden in a subclass, the `order` argument can be omitted here,
too.
.. versionadded:: 0.9
"""
token = self.register(func, *args)
try:
yield
finally:
self.unregister(token) | python | def context_register(self, func, *args):
"""
:term:`Context manager <context manager>` which temporarily registers a
filter function.
:param func: The filter function to register.
:param order: The sorting key for the filter function.
:rtype: :term:`context manager`
:return: Context manager which temporarily registers the filter
function.
If :meth:`register` does not require `order` because it has been
overridden in a subclass, the `order` argument can be omitted here,
too.
.. versionadded:: 0.9
"""
token = self.register(func, *args)
try:
yield
finally:
self.unregister(token) | :term:`Context manager <context manager>` which temporarily registers a
filter function.
:param func: The filter function to register.
:param order: The sorting key for the filter function.
:rtype: :term:`context manager`
:return: Context manager which temporarily registers the filter
function.
If :meth:`register` does not require `order` because it has been
overridden in a subclass, the `order` argument can be omitted here,
too.
.. versionadded:: 0.9 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/callbacks.py#L829-L850 |
horazont/aioxmpp | aioxmpp/tracking.py | MessageTracker.set_timeout | def set_timeout(self, timeout):
"""
Automatically close the tracker after `timeout` has elapsed.
:param timeout: The timeout after which the tracker is closed
automatically.
:type timeout: :class:`numbers.Real` or :class:`datetime.timedelta`
If the `timeout` is not a :class:`datetime.timedelta` instance, it is
assumed to be given as seconds.
The timeout cannot be cancelled after it has been set. It starts at the
very moment :meth:`set_timeout` is called.
"""
loop = asyncio.get_event_loop()
if isinstance(timeout, timedelta):
timeout = timeout.total_seconds()
loop.call_later(timeout, self.close) | python | def set_timeout(self, timeout):
"""
Automatically close the tracker after `timeout` has elapsed.
:param timeout: The timeout after which the tracker is closed
automatically.
:type timeout: :class:`numbers.Real` or :class:`datetime.timedelta`
If the `timeout` is not a :class:`datetime.timedelta` instance, it is
assumed to be given as seconds.
The timeout cannot be cancelled after it has been set. It starts at the
very moment :meth:`set_timeout` is called.
"""
loop = asyncio.get_event_loop()
if isinstance(timeout, timedelta):
timeout = timeout.total_seconds()
loop.call_later(timeout, self.close) | Automatically close the tracker after `timeout` has elapsed.
:param timeout: The timeout after which the tracker is closed
automatically.
:type timeout: :class:`numbers.Real` or :class:`datetime.timedelta`
If the `timeout` is not a :class:`datetime.timedelta` instance, it is
assumed to be given as seconds.
The timeout cannot be cancelled after it has been set. It starts at the
very moment :meth:`set_timeout` is called. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/tracking.py#L269-L288 |
horazont/aioxmpp | aioxmpp/tracking.py | MessageTracker._set_state | def _set_state(self, new_state, response=None):
"""
Set the state of the tracker.
:param new_state: The new state of the tracker.
:type new_state: :class:`~.MessageState` member
:param response: A stanza related to the new state.
:type response: :class:`~.StanzaBase` or :data:`None`
:raise ValueError: if a forbidden state transition is attempted.
:raise RuntimeError: if the tracker is closed.
The state of the tracker is set to the `new_state`. The
:attr:`response` is also overriden with the new value, no matter if the
new or old value is :data:`None` or not. The :meth:`on_state_changed`
event is emitted.
The following transitions are forbidden and attempting to perform them
will raise :class:`ValueError`:
* any state -> :attr:`~.MessageState.IN_TRANSIT`
* :attr:`~.MessageState.DELIVERED_TO_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_SERVER`
* :attr:`~.MessageState.SEEN_BY_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_RECIPIENT`
* :attr:`~.MessageState.SEEN_BY_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_SERVER`
* :attr:`~.MessageState.ABORTED` -> any state
* :attr:`~.MessageState.ERROR` -> any state
If the tracker is already :meth:`close`\\ -d, :class:`RuntimeError` is
raised. This check happens *before* a test is made whether the
transition is valid.
This method is part of the "protected" interface.
"""
if self._closed:
raise RuntimeError("message tracker is closed")
# reject some transitions as documented
if (self._state == MessageState.ABORTED or
new_state == MessageState.IN_TRANSIT or
(self._state == MessageState.ERROR and
new_state == MessageState.DELIVERED_TO_SERVER) or
(self._state == MessageState.ERROR and
new_state == MessageState.ABORTED) or
(self._state == MessageState.DELIVERED_TO_RECIPIENT and
new_state == MessageState.DELIVERED_TO_SERVER) or
(self._state == MessageState.SEEN_BY_RECIPIENT and
new_state == MessageState.DELIVERED_TO_SERVER) or
(self._state == MessageState.SEEN_BY_RECIPIENT and
new_state == MessageState.DELIVERED_TO_RECIPIENT)):
raise ValueError(
"message tracker transition from {} to {} not allowed".format(
self._state,
new_state
)
)
self._state = new_state
self._response = response
self.on_state_changed(self._state, self._response) | python | def _set_state(self, new_state, response=None):
"""
Set the state of the tracker.
:param new_state: The new state of the tracker.
:type new_state: :class:`~.MessageState` member
:param response: A stanza related to the new state.
:type response: :class:`~.StanzaBase` or :data:`None`
:raise ValueError: if a forbidden state transition is attempted.
:raise RuntimeError: if the tracker is closed.
The state of the tracker is set to the `new_state`. The
:attr:`response` is also overriden with the new value, no matter if the
new or old value is :data:`None` or not. The :meth:`on_state_changed`
event is emitted.
The following transitions are forbidden and attempting to perform them
will raise :class:`ValueError`:
* any state -> :attr:`~.MessageState.IN_TRANSIT`
* :attr:`~.MessageState.DELIVERED_TO_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_SERVER`
* :attr:`~.MessageState.SEEN_BY_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_RECIPIENT`
* :attr:`~.MessageState.SEEN_BY_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_SERVER`
* :attr:`~.MessageState.ABORTED` -> any state
* :attr:`~.MessageState.ERROR` -> any state
If the tracker is already :meth:`close`\\ -d, :class:`RuntimeError` is
raised. This check happens *before* a test is made whether the
transition is valid.
This method is part of the "protected" interface.
"""
if self._closed:
raise RuntimeError("message tracker is closed")
# reject some transitions as documented
if (self._state == MessageState.ABORTED or
new_state == MessageState.IN_TRANSIT or
(self._state == MessageState.ERROR and
new_state == MessageState.DELIVERED_TO_SERVER) or
(self._state == MessageState.ERROR and
new_state == MessageState.ABORTED) or
(self._state == MessageState.DELIVERED_TO_RECIPIENT and
new_state == MessageState.DELIVERED_TO_SERVER) or
(self._state == MessageState.SEEN_BY_RECIPIENT and
new_state == MessageState.DELIVERED_TO_SERVER) or
(self._state == MessageState.SEEN_BY_RECIPIENT and
new_state == MessageState.DELIVERED_TO_RECIPIENT)):
raise ValueError(
"message tracker transition from {} to {} not allowed".format(
self._state,
new_state
)
)
self._state = new_state
self._response = response
self.on_state_changed(self._state, self._response) | Set the state of the tracker.
:param new_state: The new state of the tracker.
:type new_state: :class:`~.MessageState` member
:param response: A stanza related to the new state.
:type response: :class:`~.StanzaBase` or :data:`None`
:raise ValueError: if a forbidden state transition is attempted.
:raise RuntimeError: if the tracker is closed.
The state of the tracker is set to the `new_state`. The
:attr:`response` is also overriden with the new value, no matter if the
new or old value is :data:`None` or not. The :meth:`on_state_changed`
event is emitted.
The following transitions are forbidden and attempting to perform them
will raise :class:`ValueError`:
* any state -> :attr:`~.MessageState.IN_TRANSIT`
* :attr:`~.MessageState.DELIVERED_TO_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_SERVER`
* :attr:`~.MessageState.SEEN_BY_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_RECIPIENT`
* :attr:`~.MessageState.SEEN_BY_RECIPIENT` ->
:attr:`~.MessageState.DELIVERED_TO_SERVER`
* :attr:`~.MessageState.ABORTED` -> any state
* :attr:`~.MessageState.ERROR` -> any state
If the tracker is already :meth:`close`\\ -d, :class:`RuntimeError` is
raised. This check happens *before* a test is made whether the
transition is valid.
This method is part of the "protected" interface. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/tracking.py#L292-L352 |
horazont/aioxmpp | aioxmpp/tracking.py | BasicTrackingService.send_tracked | def send_tracked(self, stanza, tracker):
"""
Send a message stanza with tracking.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTracker`
:rtype: :class:`~.StanzaToken`
:return: The token used to send the stanza.
If `tracker` is :data:`None`, a new :class:`~.MessageTracker` is
created.
This configures tracking for the stanza as if by calling
:meth:`attach_tracker` with a `token` and sends the stanza through the
stream.
.. seealso::
:meth:`attach_tracker`
can be used if the stanza cannot be sent (e.g. because it is a
carbon-copy) or has already been sent.
"""
token = self.client.enqueue(stanza)
self.attach_tracker(stanza, tracker, token)
return token | python | def send_tracked(self, stanza, tracker):
"""
Send a message stanza with tracking.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTracker`
:rtype: :class:`~.StanzaToken`
:return: The token used to send the stanza.
If `tracker` is :data:`None`, a new :class:`~.MessageTracker` is
created.
This configures tracking for the stanza as if by calling
:meth:`attach_tracker` with a `token` and sends the stanza through the
stream.
.. seealso::
:meth:`attach_tracker`
can be used if the stanza cannot be sent (e.g. because it is a
carbon-copy) or has already been sent.
"""
token = self.client.enqueue(stanza)
self.attach_tracker(stanza, tracker, token)
return token | Send a message stanza with tracking.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTracker`
:rtype: :class:`~.StanzaToken`
:return: The token used to send the stanza.
If `tracker` is :data:`None`, a new :class:`~.MessageTracker` is
created.
This configures tracking for the stanza as if by calling
:meth:`attach_tracker` with a `token` and sends the stanza through the
stream.
.. seealso::
:meth:`attach_tracker`
can be used if the stanza cannot be sent (e.g. because it is a
carbon-copy) or has already been sent. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/tracking.py#L425-L451 |
horazont/aioxmpp | aioxmpp/tracking.py | BasicTrackingService.attach_tracker | def attach_tracker(self, stanza, tracker=None, token=None):
"""
Configure tracking for a stanza without sending it.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTracker` or :data:`None`
:param token: Optional stanza token for more fine-grained tracking.
:type token: :class:`~.StanzaToken`
:rtype: :class:`~.MessageTracker`
:return: The message tracker.
If `tracker` is :data:`None`, a new :class:`~.MessageTracker` is
created.
If `token` is not :data:`None`, updates to the stanza `token` are
reflected in the `tracker`.
If an error reply is received, the tracker will enter
:class:`~.MessageState.ERROR` and the error will be set as
:attr:`~.MessageTracker.response`.
You should use :meth:`send_tracked` if possible. This method however is
very useful if you need to track carbon copies of sent messages, as a
stanza token is not available here and re-sending the message to obtain
one is generally not desirable ☺.
"""
if tracker is None:
tracker = MessageTracker()
stanza.autoset_id()
key = stanza.to.bare(), stanza.id_
self._trackers[key] = tracker
tracker.on_closed.connect(
functools.partial(self._tracker_closed, key)
)
if token is not None:
token.future.add_done_callback(
functools.partial(
self._stanza_sent,
tracker,
token,
)
)
return tracker | python | def attach_tracker(self, stanza, tracker=None, token=None):
"""
Configure tracking for a stanza without sending it.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTracker` or :data:`None`
:param token: Optional stanza token for more fine-grained tracking.
:type token: :class:`~.StanzaToken`
:rtype: :class:`~.MessageTracker`
:return: The message tracker.
If `tracker` is :data:`None`, a new :class:`~.MessageTracker` is
created.
If `token` is not :data:`None`, updates to the stanza `token` are
reflected in the `tracker`.
If an error reply is received, the tracker will enter
:class:`~.MessageState.ERROR` and the error will be set as
:attr:`~.MessageTracker.response`.
You should use :meth:`send_tracked` if possible. This method however is
very useful if you need to track carbon copies of sent messages, as a
stanza token is not available here and re-sending the message to obtain
one is generally not desirable ☺.
"""
if tracker is None:
tracker = MessageTracker()
stanza.autoset_id()
key = stanza.to.bare(), stanza.id_
self._trackers[key] = tracker
tracker.on_closed.connect(
functools.partial(self._tracker_closed, key)
)
if token is not None:
token.future.add_done_callback(
functools.partial(
self._stanza_sent,
tracker,
token,
)
)
return tracker | Configure tracking for a stanza without sending it.
:param stanza: Message stanza to send.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Message tracker to use.
:type tracker: :class:`~.MessageTracker` or :data:`None`
:param token: Optional stanza token for more fine-grained tracking.
:type token: :class:`~.StanzaToken`
:rtype: :class:`~.MessageTracker`
:return: The message tracker.
If `tracker` is :data:`None`, a new :class:`~.MessageTracker` is
created.
If `token` is not :data:`None`, updates to the stanza `token` are
reflected in the `tracker`.
If an error reply is received, the tracker will enter
:class:`~.MessageState.ERROR` and the error will be set as
:attr:`~.MessageTracker.response`.
You should use :meth:`send_tracked` if possible. This method however is
very useful if you need to track carbon copies of sent messages, as a
stanza token is not available here and re-sending the message to obtain
one is generally not desirable ☺. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/tracking.py#L453-L497 |
horazont/aioxmpp | aioxmpp/muc/self_ping.py | MUCPinger.start | def start(self):
"""
Start the pinging coroutine using the client and event loop which was
passed to the constructor.
:meth:`start` always behaves as if :meth:`stop` was called right before
it.
"""
self.stop()
self._task = asyncio.ensure_future(self._pinger(), loop=self._loop) | python | def start(self):
"""
Start the pinging coroutine using the client and event loop which was
passed to the constructor.
:meth:`start` always behaves as if :meth:`stop` was called right before
it.
"""
self.stop()
self._task = asyncio.ensure_future(self._pinger(), loop=self._loop) | Start the pinging coroutine using the client and event loop which was
passed to the constructor.
:meth:`start` always behaves as if :meth:`stop` was called right before
it. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/self_ping.py#L131-L140 |
horazont/aioxmpp | aioxmpp/muc/self_ping.py | MUCPinger._interpret_result | def _interpret_result(self, task):
"""
Interpret the result of a ping.
:param task: The pinger task.
The result or exception of the `task` is interpreted as follows:
* :data:`None` result: *positive*
* :class:`aioxmpp.errors.XMPPError`, ``service-unavailable``:
*positive*
* :class:`aioxmpp.errors.XMPPError`, ``feature-not-implemented``:
*positive*
* :class:`aioxmpp.errors.XMPPError`, ``item-not-found``: *inconclusive*
* :class:`aioxmpp.errors.XMPPError`: *negative*
* :class:`asyncio.TimeoutError`: *inconclusive*
* Any other exception: *inconclusive*
"""
if task.exception() is None:
self._on_fresh()
return
exc = task.exception()
if isinstance(exc, aioxmpp.errors.XMPPError):
if exc.condition in [
aioxmpp.errors.ErrorCondition.SERVICE_UNAVAILABLE,
aioxmpp.errors.ErrorCondition.FEATURE_NOT_IMPLEMENTED]:
self._on_fresh()
return
if exc.condition == aioxmpp.errors.ErrorCondition.ITEM_NOT_FOUND:
return
self._on_exited() | python | def _interpret_result(self, task):
"""
Interpret the result of a ping.
:param task: The pinger task.
The result or exception of the `task` is interpreted as follows:
* :data:`None` result: *positive*
* :class:`aioxmpp.errors.XMPPError`, ``service-unavailable``:
*positive*
* :class:`aioxmpp.errors.XMPPError`, ``feature-not-implemented``:
*positive*
* :class:`aioxmpp.errors.XMPPError`, ``item-not-found``: *inconclusive*
* :class:`aioxmpp.errors.XMPPError`: *negative*
* :class:`asyncio.TimeoutError`: *inconclusive*
* Any other exception: *inconclusive*
"""
if task.exception() is None:
self._on_fresh()
return
exc = task.exception()
if isinstance(exc, aioxmpp.errors.XMPPError):
if exc.condition in [
aioxmpp.errors.ErrorCondition.SERVICE_UNAVAILABLE,
aioxmpp.errors.ErrorCondition.FEATURE_NOT_IMPLEMENTED]:
self._on_fresh()
return
if exc.condition == aioxmpp.errors.ErrorCondition.ITEM_NOT_FOUND:
return
self._on_exited() | Interpret the result of a ping.
:param task: The pinger task.
The result or exception of the `task` is interpreted as follows:
* :data:`None` result: *positive*
* :class:`aioxmpp.errors.XMPPError`, ``service-unavailable``:
*positive*
* :class:`aioxmpp.errors.XMPPError`, ``feature-not-implemented``:
*positive*
* :class:`aioxmpp.errors.XMPPError`, ``item-not-found``: *inconclusive*
* :class:`aioxmpp.errors.XMPPError`: *negative*
* :class:`asyncio.TimeoutError`: *inconclusive*
* Any other exception: *inconclusive* | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/self_ping.py#L156-L189 |
horazont/aioxmpp | aioxmpp/muc/self_ping.py | MUCMonitor.reset | def reset(self):
"""
Reset the monitor.
Reset the aliveness timeouts. Clear the stale state. Cancel and stop
pinging.
Call `on_fresh` if the stale state was set.
"""
self._monitor.notify_received()
self._pinger.stop()
self._mark_fresh() | python | def reset(self):
"""
Reset the monitor.
Reset the aliveness timeouts. Clear the stale state. Cancel and stop
pinging.
Call `on_fresh` if the stale state was set.
"""
self._monitor.notify_received()
self._pinger.stop()
self._mark_fresh() | Reset the monitor.
Reset the aliveness timeouts. Clear the stale state. Cancel and stop
pinging.
Call `on_fresh` if the stale state was set. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/self_ping.py#L378-L389 |
horazont/aioxmpp | aioxmpp/mdr/service.py | compose_receipt | def compose_receipt(message):
"""
Compose a :xep:`184` delivery receipt for a :class:`~aioxmpp.Message`.
:param message: The message to compose the receipt for.
:type message: :class:`~aioxmpp.Message`
:raises ValueError: if the input message is of type
:attr:`~aioxmpp.MessageType.ERROR`
:raises ValueError: if the input message is a message receipt itself
:return: A message which serves as a receipt for the input message.
:rtype: :class:`~aioxmpp.Message`
"""
if message.type_ == aioxmpp.MessageType.ERROR:
raise ValueError("receipts cannot be generated for error messages")
if message.xep0184_received:
raise ValueError("receipts cannot be generated for receipts")
if message.id_ is None:
raise ValueError("receipts cannot be generated for id-less messages")
reply = message.make_reply()
reply.to = reply.to.bare()
reply.xep0184_received = xso.Received(message.id_)
return reply | python | def compose_receipt(message):
"""
Compose a :xep:`184` delivery receipt for a :class:`~aioxmpp.Message`.
:param message: The message to compose the receipt for.
:type message: :class:`~aioxmpp.Message`
:raises ValueError: if the input message is of type
:attr:`~aioxmpp.MessageType.ERROR`
:raises ValueError: if the input message is a message receipt itself
:return: A message which serves as a receipt for the input message.
:rtype: :class:`~aioxmpp.Message`
"""
if message.type_ == aioxmpp.MessageType.ERROR:
raise ValueError("receipts cannot be generated for error messages")
if message.xep0184_received:
raise ValueError("receipts cannot be generated for receipts")
if message.id_ is None:
raise ValueError("receipts cannot be generated for id-less messages")
reply = message.make_reply()
reply.to = reply.to.bare()
reply.xep0184_received = xso.Received(message.id_)
return reply | Compose a :xep:`184` delivery receipt for a :class:`~aioxmpp.Message`.
:param message: The message to compose the receipt for.
:type message: :class:`~aioxmpp.Message`
:raises ValueError: if the input message is of type
:attr:`~aioxmpp.MessageType.ERROR`
:raises ValueError: if the input message is a message receipt itself
:return: A message which serves as a receipt for the input message.
:rtype: :class:`~aioxmpp.Message` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/mdr/service.py#L115-L138 |
horazont/aioxmpp | aioxmpp/mdr/service.py | DeliveryReceiptsService.attach_tracker | def attach_tracker(self, stanza, tracker=None):
"""
Return a new tracker or modify one to track the stanza.
:param stanza: Stanza to track.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Existing tracker to attach to.
:type tracker: :class:`.tracking.MessageTracker`
:raises ValueError: if the stanza is of type
:attr:`~aioxmpp.MessageType.ERROR`
:raises ValueError: if the stanza contains a delivery receipt
:return: The message tracker for the stanza.
:rtype: :class:`.tracking.MessageTracker`
The `stanza` gets a :xep:`184` reciept request attached and internal
handlers are set up to update the `tracker` state once a confirmation
is received.
.. warning::
See the :ref:`api-tracking-memory`.
"""
if stanza.xep0184_received is not None:
raise ValueError(
"requesting delivery receipts for delivery receipts is not "
"allowed"
)
if stanza.type_ == aioxmpp.MessageType.ERROR:
raise ValueError(
"requesting delivery receipts for errors is not supported"
)
if tracker is None:
tracker = aioxmpp.tracking.MessageTracker()
stanza.xep0184_request_receipt = True
stanza.autoset_id()
self._bare_jid_maps[stanza.to, stanza.id_] = tracker
return tracker | python | def attach_tracker(self, stanza, tracker=None):
"""
Return a new tracker or modify one to track the stanza.
:param stanza: Stanza to track.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Existing tracker to attach to.
:type tracker: :class:`.tracking.MessageTracker`
:raises ValueError: if the stanza is of type
:attr:`~aioxmpp.MessageType.ERROR`
:raises ValueError: if the stanza contains a delivery receipt
:return: The message tracker for the stanza.
:rtype: :class:`.tracking.MessageTracker`
The `stanza` gets a :xep:`184` reciept request attached and internal
handlers are set up to update the `tracker` state once a confirmation
is received.
.. warning::
See the :ref:`api-tracking-memory`.
"""
if stanza.xep0184_received is not None:
raise ValueError(
"requesting delivery receipts for delivery receipts is not "
"allowed"
)
if stanza.type_ == aioxmpp.MessageType.ERROR:
raise ValueError(
"requesting delivery receipts for errors is not supported"
)
if tracker is None:
tracker = aioxmpp.tracking.MessageTracker()
stanza.xep0184_request_receipt = True
stanza.autoset_id()
self._bare_jid_maps[stanza.to, stanza.id_] = tracker
return tracker | Return a new tracker or modify one to track the stanza.
:param stanza: Stanza to track.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Existing tracker to attach to.
:type tracker: :class:`.tracking.MessageTracker`
:raises ValueError: if the stanza is of type
:attr:`~aioxmpp.MessageType.ERROR`
:raises ValueError: if the stanza contains a delivery receipt
:return: The message tracker for the stanza.
:rtype: :class:`.tracking.MessageTracker`
The `stanza` gets a :xep:`184` reciept request attached and internal
handlers are set up to update the `tracker` state once a confirmation
is received.
.. warning::
See the :ref:`api-tracking-memory`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/mdr/service.py#L73-L112 |
horazont/aioxmpp | aioxmpp/private_xml/service.py | PrivateXMLService.get_private_xml | def get_private_xml(self, query_xso):
"""
Get the private XML data for the element `query_xso` from the
server.
:param query_xso: the object to retrieve.
:returns: the stored private XML data.
`query_xso` *must* serialize to an empty XML node of the
wanted namespace and type and *must* be registered as private
XML :class:`~private_xml_xso.Query` payload.
"""
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.GET,
payload=private_xml_xso.Query(query_xso)
)
return (yield from self.client.send(iq)) | python | def get_private_xml(self, query_xso):
"""
Get the private XML data for the element `query_xso` from the
server.
:param query_xso: the object to retrieve.
:returns: the stored private XML data.
`query_xso` *must* serialize to an empty XML node of the
wanted namespace and type and *must* be registered as private
XML :class:`~private_xml_xso.Query` payload.
"""
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.GET,
payload=private_xml_xso.Query(query_xso)
)
return (yield from self.client.send(iq)) | Get the private XML data for the element `query_xso` from the
server.
:param query_xso: the object to retrieve.
:returns: the stored private XML data.
`query_xso` *must* serialize to an empty XML node of the
wanted namespace and type and *must* be registered as private
XML :class:`~private_xml_xso.Query` payload. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/private_xml/service.py#L43-L60 |
horazont/aioxmpp | aioxmpp/private_xml/service.py | PrivateXMLService.set_private_xml | def set_private_xml(self, xso):
"""
Store the serialization of `xso` on the server as the private XML
data for the namespace of `xso`.
:param xso: the XSO whose serialization is send as private XML data.
"""
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
payload=private_xml_xso.Query(xso)
)
yield from self.client.send(iq) | python | def set_private_xml(self, xso):
"""
Store the serialization of `xso` on the server as the private XML
data for the namespace of `xso`.
:param xso: the XSO whose serialization is send as private XML data.
"""
iq = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
payload=private_xml_xso.Query(xso)
)
yield from self.client.send(iq) | Store the serialization of `xso` on the server as the private XML
data for the namespace of `xso`.
:param xso: the XSO whose serialization is send as private XML data. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/private_xml/service.py#L63-L74 |
horazont/aioxmpp | aioxmpp/utils.py | gather_reraise_multi | def gather_reraise_multi(*fut_or_coros, message="gather_reraise_multi"):
"""
Wrap all the arguments `fut_or_coros` in futures with
:func:`asyncio.ensure_future` and wait until all of them are finish or
fail.
:param fut_or_coros: the futures or coroutines to wait for
:type fut_or_coros: future or coroutine
:param message: the message included with the raised
:class:`aioxmpp.errrors.GatherError` in the case of failure.
:type message: :class:`str`
:returns: the list of the results of the arguments.
:raises aioxmpp.errors.GatherError: if any of the futures or
coroutines fail.
If an exception was raised, reraise all exceptions wrapped in a
:class:`aioxmpp.errors.GatherError` with the message set to
`message`.
.. note::
This is similar to the standard function
:func:`asyncio.gather`, but avoids the in-band signalling of
raised exceptions as return values, by raising exceptions bundled
as a :class:`aioxmpp.errors.GatherError`.
.. note::
Use this function only if you are either
a) not interested in the return values, or
b) only interested in the return values if all futures are
successful.
"""
todo = [asyncio.ensure_future(fut_or_coro) for fut_or_coro in fut_or_coros]
if not todo:
return []
yield from asyncio.wait(todo)
results = []
exceptions = []
for fut in todo:
if fut.exception() is not None:
exceptions.append(fut.exception())
else:
results.append(fut.result())
if exceptions:
raise aioxmpp.errors.GatherError(message, exceptions)
return results | python | def gather_reraise_multi(*fut_or_coros, message="gather_reraise_multi"):
"""
Wrap all the arguments `fut_or_coros` in futures with
:func:`asyncio.ensure_future` and wait until all of them are finish or
fail.
:param fut_or_coros: the futures or coroutines to wait for
:type fut_or_coros: future or coroutine
:param message: the message included with the raised
:class:`aioxmpp.errrors.GatherError` in the case of failure.
:type message: :class:`str`
:returns: the list of the results of the arguments.
:raises aioxmpp.errors.GatherError: if any of the futures or
coroutines fail.
If an exception was raised, reraise all exceptions wrapped in a
:class:`aioxmpp.errors.GatherError` with the message set to
`message`.
.. note::
This is similar to the standard function
:func:`asyncio.gather`, but avoids the in-band signalling of
raised exceptions as return values, by raising exceptions bundled
as a :class:`aioxmpp.errors.GatherError`.
.. note::
Use this function only if you are either
a) not interested in the return values, or
b) only interested in the return values if all futures are
successful.
"""
todo = [asyncio.ensure_future(fut_or_coro) for fut_or_coro in fut_or_coros]
if not todo:
return []
yield from asyncio.wait(todo)
results = []
exceptions = []
for fut in todo:
if fut.exception() is not None:
exceptions.append(fut.exception())
else:
results.append(fut.result())
if exceptions:
raise aioxmpp.errors.GatherError(message, exceptions)
return results | Wrap all the arguments `fut_or_coros` in futures with
:func:`asyncio.ensure_future` and wait until all of them are finish or
fail.
:param fut_or_coros: the futures or coroutines to wait for
:type fut_or_coros: future or coroutine
:param message: the message included with the raised
:class:`aioxmpp.errrors.GatherError` in the case of failure.
:type message: :class:`str`
:returns: the list of the results of the arguments.
:raises aioxmpp.errors.GatherError: if any of the futures or
coroutines fail.
If an exception was raised, reraise all exceptions wrapped in a
:class:`aioxmpp.errors.GatherError` with the message set to
`message`.
.. note::
This is similar to the standard function
:func:`asyncio.gather`, but avoids the in-band signalling of
raised exceptions as return values, by raising exceptions bundled
as a :class:`aioxmpp.errors.GatherError`.
.. note::
Use this function only if you are either
a) not interested in the return values, or
b) only interested in the return values if all futures are
successful. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/utils.py#L269-L318 |
horazont/aioxmpp | aioxmpp/utils.py | to_nmtoken | def to_nmtoken(rand_token):
"""
Convert a (random) token given as raw :class:`bytes` or
:class:`int` to a valid NMTOKEN
<https://www.w3.org/TR/xml/#NT-Nmtoken>.
The encoding as a valid nmtoken is injective, ensuring that two
different inputs cannot yield the same token. Nevertheless, it is
recommended to only use one kind of inputs (integers or bytes of a
consistent length) in one context.
"""
if isinstance(rand_token, int):
rand_token = rand_token.to_bytes(
(rand_token.bit_length() + 7) // 8,
"little"
)
e = base64.urlsafe_b64encode(rand_token).rstrip(b"=").decode("ascii")
return ":" + e
if isinstance(rand_token, bytes):
e = base64.urlsafe_b64encode(rand_token).rstrip(b"=").decode("ascii")
if not e:
e = "."
return e
raise TypeError("rand_token musst be a bytes or int instance") | python | def to_nmtoken(rand_token):
"""
Convert a (random) token given as raw :class:`bytes` or
:class:`int` to a valid NMTOKEN
<https://www.w3.org/TR/xml/#NT-Nmtoken>.
The encoding as a valid nmtoken is injective, ensuring that two
different inputs cannot yield the same token. Nevertheless, it is
recommended to only use one kind of inputs (integers or bytes of a
consistent length) in one context.
"""
if isinstance(rand_token, int):
rand_token = rand_token.to_bytes(
(rand_token.bit_length() + 7) // 8,
"little"
)
e = base64.urlsafe_b64encode(rand_token).rstrip(b"=").decode("ascii")
return ":" + e
if isinstance(rand_token, bytes):
e = base64.urlsafe_b64encode(rand_token).rstrip(b"=").decode("ascii")
if not e:
e = "."
return e
raise TypeError("rand_token musst be a bytes or int instance") | Convert a (random) token given as raw :class:`bytes` or
:class:`int` to a valid NMTOKEN
<https://www.w3.org/TR/xml/#NT-Nmtoken>.
The encoding as a valid nmtoken is injective, ensuring that two
different inputs cannot yield the same token. Nevertheless, it is
recommended to only use one kind of inputs (integers or bytes of a
consistent length) in one context. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/utils.py#L321-L347 |
horazont/aioxmpp | aioxmpp/errors.py | UserError.localize | def localize(self, formatter, translator):
"""
Return a localized version of the `localizable_string` passed to the
consturctor. It is formatted using the `formatter` with the `args` and
`kwargs` passed to the constructor of :class:`UserError`.
"""
return self.localizable_string.localize(
formatter,
translator,
*self.args,
**self.kwargs
) | python | def localize(self, formatter, translator):
"""
Return a localized version of the `localizable_string` passed to the
consturctor. It is formatted using the `formatter` with the `args` and
`kwargs` passed to the constructor of :class:`UserError`.
"""
return self.localizable_string.localize(
formatter,
translator,
*self.args,
**self.kwargs
) | Return a localized version of the `localizable_string` passed to the
consturctor. It is formatted using the `formatter` with the `args` and
`kwargs` passed to the constructor of :class:`UserError`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/errors.py#L575-L586 |
horazont/aioxmpp | aioxmpp/bookmarks/service.py | BookmarkClient._get_bookmarks | def _get_bookmarks(self):
"""
Get the stored bookmarks from the server.
:returns: a list of bookmarks
"""
res = yield from self._private_xml.get_private_xml(
bookmark_xso.Storage()
)
return res.registered_payload.bookmarks | python | def _get_bookmarks(self):
"""
Get the stored bookmarks from the server.
:returns: a list of bookmarks
"""
res = yield from self._private_xml.get_private_xml(
bookmark_xso.Storage()
)
return res.registered_payload.bookmarks | Get the stored bookmarks from the server.
:returns: a list of bookmarks | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L120-L130 |
horazont/aioxmpp | aioxmpp/bookmarks/service.py | BookmarkClient._set_bookmarks | def _set_bookmarks(self, bookmarks):
"""
Set the bookmarks stored on the server.
"""
storage = bookmark_xso.Storage()
storage.bookmarks[:] = bookmarks
yield from self._private_xml.set_private_xml(storage) | python | def _set_bookmarks(self, bookmarks):
"""
Set the bookmarks stored on the server.
"""
storage = bookmark_xso.Storage()
storage.bookmarks[:] = bookmarks
yield from self._private_xml.set_private_xml(storage) | Set the bookmarks stored on the server. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L133-L139 |
horazont/aioxmpp | aioxmpp/bookmarks/service.py | BookmarkClient._diff_emit_update | def _diff_emit_update(self, new_bookmarks):
"""
Diff the bookmark cache and the new bookmark state, emit signals as
needed and set the bookmark cache to the new data.
"""
self.logger.debug("diffing %s, %s", self._bookmark_cache,
new_bookmarks)
def subdivide(level, old, new):
"""
Subdivide the bookmarks according to the data item
``bookmark.secondary[level]`` and emit the appropriate
events.
"""
if len(old) == len(new) == 1:
old_entry = old.pop()
new_entry = new.pop()
if old_entry == new_entry:
pass
else:
self.on_bookmark_changed(old_entry, new_entry)
return ([], [])
elif len(old) == 0:
return ([], new)
elif len(new) == 0:
return (old, [])
else:
try:
groups = {}
for entry in old:
group = groups.setdefault(
entry.secondary[level],
([], [])
)
group[0].append(entry)
for entry in new:
group = groups.setdefault(
entry.secondary[level],
([], [])
)
group[1].append(entry)
except IndexError:
# the classification is exhausted, this means
# all entries in this bin are equal by the
# defininition of bookmark equivalence!
common = min(len(old), len(new))
assert old[:common] == new[:common]
return (old[common:], new[common:])
old_unhandled, new_unhandled = [], []
for old, new in groups.values():
unhandled = subdivide(level+1, old, new)
old_unhandled += unhandled[0]
new_unhandled += unhandled[1]
# match up unhandleds as changes as early as possible
i = -1
for i, (old_entry, new_entry) in enumerate(
zip(old_unhandled, new_unhandled)):
self.logger.debug("changed %s -> %s", old_entry, new_entry)
self.on_bookmark_changed(old_entry, new_entry)
i += 1
return old_unhandled[i:], new_unhandled[i:]
# group the bookmarks into groups whose elements may transform
# among one another by on_bookmark_changed events. This information
# is given by the type of the bookmark and the .primary property
changable_groups = {}
for item in self._bookmark_cache:
group = changable_groups.setdefault(
(type(item), item.primary),
([], [])
)
group[0].append(item)
for item in new_bookmarks:
group = changable_groups.setdefault(
(type(item), item.primary),
([], [])
)
group[1].append(item)
for old, new in changable_groups.values():
# the first branches are fast paths which should catch
# most cases – especially all cases where each bare jid of
# a conference bookmark or each url of an url bookmark is
# only used in one bookmark
if len(old) == len(new) == 1:
old_entry = old.pop()
new_entry = new.pop()
if old_entry == new_entry:
# the bookmark is unchanged, do not emit an event
pass
else:
self.logger.debug("changed %s -> %s", old_entry, new_entry)
self.on_bookmark_changed(old_entry, new_entry)
elif len(new) == 0:
for removed in old:
self.logger.debug("removed %s", removed)
self.on_bookmark_removed(removed)
elif len(old) == 0:
for added in new:
self.logger.debug("added %s", added)
self.on_bookmark_added(added)
else:
old, new = subdivide(0, old, new)
assert len(old) == 0 or len(new) == 0
for removed in old:
self.logger.debug("removed %s", removed)
self.on_bookmark_removed(removed)
for added in new:
self.logger.debug("added %s", added)
self.on_bookmark_added(added)
self._bookmark_cache = new_bookmarks | python | def _diff_emit_update(self, new_bookmarks):
"""
Diff the bookmark cache and the new bookmark state, emit signals as
needed and set the bookmark cache to the new data.
"""
self.logger.debug("diffing %s, %s", self._bookmark_cache,
new_bookmarks)
def subdivide(level, old, new):
"""
Subdivide the bookmarks according to the data item
``bookmark.secondary[level]`` and emit the appropriate
events.
"""
if len(old) == len(new) == 1:
old_entry = old.pop()
new_entry = new.pop()
if old_entry == new_entry:
pass
else:
self.on_bookmark_changed(old_entry, new_entry)
return ([], [])
elif len(old) == 0:
return ([], new)
elif len(new) == 0:
return (old, [])
else:
try:
groups = {}
for entry in old:
group = groups.setdefault(
entry.secondary[level],
([], [])
)
group[0].append(entry)
for entry in new:
group = groups.setdefault(
entry.secondary[level],
([], [])
)
group[1].append(entry)
except IndexError:
# the classification is exhausted, this means
# all entries in this bin are equal by the
# defininition of bookmark equivalence!
common = min(len(old), len(new))
assert old[:common] == new[:common]
return (old[common:], new[common:])
old_unhandled, new_unhandled = [], []
for old, new in groups.values():
unhandled = subdivide(level+1, old, new)
old_unhandled += unhandled[0]
new_unhandled += unhandled[1]
# match up unhandleds as changes as early as possible
i = -1
for i, (old_entry, new_entry) in enumerate(
zip(old_unhandled, new_unhandled)):
self.logger.debug("changed %s -> %s", old_entry, new_entry)
self.on_bookmark_changed(old_entry, new_entry)
i += 1
return old_unhandled[i:], new_unhandled[i:]
# group the bookmarks into groups whose elements may transform
# among one another by on_bookmark_changed events. This information
# is given by the type of the bookmark and the .primary property
changable_groups = {}
for item in self._bookmark_cache:
group = changable_groups.setdefault(
(type(item), item.primary),
([], [])
)
group[0].append(item)
for item in new_bookmarks:
group = changable_groups.setdefault(
(type(item), item.primary),
([], [])
)
group[1].append(item)
for old, new in changable_groups.values():
# the first branches are fast paths which should catch
# most cases – especially all cases where each bare jid of
# a conference bookmark or each url of an url bookmark is
# only used in one bookmark
if len(old) == len(new) == 1:
old_entry = old.pop()
new_entry = new.pop()
if old_entry == new_entry:
# the bookmark is unchanged, do not emit an event
pass
else:
self.logger.debug("changed %s -> %s", old_entry, new_entry)
self.on_bookmark_changed(old_entry, new_entry)
elif len(new) == 0:
for removed in old:
self.logger.debug("removed %s", removed)
self.on_bookmark_removed(removed)
elif len(old) == 0:
for added in new:
self.logger.debug("added %s", added)
self.on_bookmark_added(added)
else:
old, new = subdivide(0, old, new)
assert len(old) == 0 or len(new) == 0
for removed in old:
self.logger.debug("removed %s", removed)
self.on_bookmark_removed(removed)
for added in new:
self.logger.debug("added %s", added)
self.on_bookmark_added(added)
self._bookmark_cache = new_bookmarks | Diff the bookmark cache and the new bookmark state, emit signals as
needed and set the bookmark cache to the new data. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L141-L265 |
horazont/aioxmpp | aioxmpp/bookmarks/service.py | BookmarkClient.get_bookmarks | def get_bookmarks(self):
"""
Get the stored bookmarks from the server. Causes signals to be
fired to reflect the changes.
:returns: a list of bookmarks
"""
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
self._diff_emit_update(bookmarks)
return bookmarks | python | def get_bookmarks(self):
"""
Get the stored bookmarks from the server. Causes signals to be
fired to reflect the changes.
:returns: a list of bookmarks
"""
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
self._diff_emit_update(bookmarks)
return bookmarks | Get the stored bookmarks from the server. Causes signals to be
fired to reflect the changes.
:returns: a list of bookmarks | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L268-L278 |
horazont/aioxmpp | aioxmpp/bookmarks/service.py | BookmarkClient.set_bookmarks | def set_bookmarks(self, bookmarks):
"""
Store the sequence of bookmarks `bookmarks`.
Causes signals to be fired to reflect the changes.
.. note:: This should normally not be used. It does not
mitigate the race condition between clients
concurrently modifying the bookmarks and may lead to
data loss. Use :meth:`add_bookmark`,
:meth:`discard_bookmark` and :meth:`update_bookmark`
instead. This method still has use-cases (modifying
the bookmarklist at large, e.g. by syncing the
remote store with local data).
"""
with (yield from self._lock):
yield from self._set_bookmarks(bookmarks)
self._diff_emit_update(bookmarks) | python | def set_bookmarks(self, bookmarks):
"""
Store the sequence of bookmarks `bookmarks`.
Causes signals to be fired to reflect the changes.
.. note:: This should normally not be used. It does not
mitigate the race condition between clients
concurrently modifying the bookmarks and may lead to
data loss. Use :meth:`add_bookmark`,
:meth:`discard_bookmark` and :meth:`update_bookmark`
instead. This method still has use-cases (modifying
the bookmarklist at large, e.g. by syncing the
remote store with local data).
"""
with (yield from self._lock):
yield from self._set_bookmarks(bookmarks)
self._diff_emit_update(bookmarks) | Store the sequence of bookmarks `bookmarks`.
Causes signals to be fired to reflect the changes.
.. note:: This should normally not be used. It does not
mitigate the race condition between clients
concurrently modifying the bookmarks and may lead to
data loss. Use :meth:`add_bookmark`,
:meth:`discard_bookmark` and :meth:`update_bookmark`
instead. This method still has use-cases (modifying
the bookmarklist at large, e.g. by syncing the
remote store with local data). | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L281-L298 |
horazont/aioxmpp | aioxmpp/bookmarks/service.py | BookmarkClient.add_bookmark | def add_bookmark(self, new_bookmark, *, max_retries=3):
"""
Add a bookmark and check whether it was successfully added to the
bookmark list. Already existant bookmarks are not added twice.
:param new_bookmark: the bookmark to add
:type new_bookmark: an instance of :class:`~bookmark_xso.Bookmark`
:param max_retries: the number of retries if setting the bookmark
fails
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not in the bookmark list
after `max_retries` retries.
After setting the bookmark it is checked, whether the bookmark
is in the online storage, if it is not it is tried again at most
`max_retries` times to add the bookmark. A :class:`RuntimeError`
is raised if the bookmark could not be added successfully after
`max_retries`.
"""
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
try:
modified_bookmarks = list(bookmarks)
if new_bookmark not in bookmarks:
modified_bookmarks.append(new_bookmark)
yield from self._set_bookmarks(modified_bookmarks)
retries = 0
bookmarks = yield from self._get_bookmarks()
while retries < max_retries:
if new_bookmark in bookmarks:
break
modified_bookmarks = list(bookmarks)
modified_bookmarks.append(new_bookmark)
yield from self._set_bookmarks(modified_bookmarks)
bookmarks = yield from self._get_bookmarks()
retries += 1
if new_bookmark not in bookmarks:
raise RuntimeError("Could not add bookmark")
finally:
self._diff_emit_update(bookmarks) | python | def add_bookmark(self, new_bookmark, *, max_retries=3):
"""
Add a bookmark and check whether it was successfully added to the
bookmark list. Already existant bookmarks are not added twice.
:param new_bookmark: the bookmark to add
:type new_bookmark: an instance of :class:`~bookmark_xso.Bookmark`
:param max_retries: the number of retries if setting the bookmark
fails
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not in the bookmark list
after `max_retries` retries.
After setting the bookmark it is checked, whether the bookmark
is in the online storage, if it is not it is tried again at most
`max_retries` times to add the bookmark. A :class:`RuntimeError`
is raised if the bookmark could not be added successfully after
`max_retries`.
"""
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
try:
modified_bookmarks = list(bookmarks)
if new_bookmark not in bookmarks:
modified_bookmarks.append(new_bookmark)
yield from self._set_bookmarks(modified_bookmarks)
retries = 0
bookmarks = yield from self._get_bookmarks()
while retries < max_retries:
if new_bookmark in bookmarks:
break
modified_bookmarks = list(bookmarks)
modified_bookmarks.append(new_bookmark)
yield from self._set_bookmarks(modified_bookmarks)
bookmarks = yield from self._get_bookmarks()
retries += 1
if new_bookmark not in bookmarks:
raise RuntimeError("Could not add bookmark")
finally:
self._diff_emit_update(bookmarks) | Add a bookmark and check whether it was successfully added to the
bookmark list. Already existant bookmarks are not added twice.
:param new_bookmark: the bookmark to add
:type new_bookmark: an instance of :class:`~bookmark_xso.Bookmark`
:param max_retries: the number of retries if setting the bookmark
fails
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not in the bookmark list
after `max_retries` retries.
After setting the bookmark it is checked, whether the bookmark
is in the online storage, if it is not it is tried again at most
`max_retries` times to add the bookmark. A :class:`RuntimeError`
is raised if the bookmark could not be added successfully after
`max_retries`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L312-L356 |
horazont/aioxmpp | aioxmpp/bookmarks/service.py | BookmarkClient.discard_bookmark | def discard_bookmark(self, bookmark_to_remove, *, max_retries=3):
"""
Remove a bookmark and check it has been removed.
:param bookmark_to_remove: the bookmark to remove
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param max_retries: the number of retries of removing the bookmark
fails.
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not removed from
bookmark list after `max_retries`
retries.
If there are multiple occurences of the same bookmark exactly
one is removed.
This does nothing if the bookmarks does not match an existing
bookmark according to bookmark-equality.
After setting the bookmark it is checked, whether the bookmark
is removed in the online storage, if it is not it is tried
again at most `max_retries` times to remove the bookmark. A
:class:`RuntimeError` is raised if the bookmark could not be
removed successfully after `max_retries`.
"""
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
occurences = bookmarks.count(bookmark_to_remove)
try:
if not occurences:
return
modified_bookmarks = list(bookmarks)
modified_bookmarks.remove(bookmark_to_remove)
yield from self._set_bookmarks(modified_bookmarks)
retries = 0
bookmarks = yield from self._get_bookmarks()
new_occurences = bookmarks.count(bookmark_to_remove)
while retries < max_retries:
if new_occurences < occurences:
break
modified_bookmarks = list(bookmarks)
modified_bookmarks.remove(bookmark_to_remove)
yield from self._set_bookmarks(modified_bookmarks)
bookmarks = yield from self._get_bookmarks()
new_occurences = bookmarks.count(bookmark_to_remove)
retries += 1
if new_occurences >= occurences:
raise RuntimeError("Could not remove bookmark")
finally:
self._diff_emit_update(bookmarks) | python | def discard_bookmark(self, bookmark_to_remove, *, max_retries=3):
"""
Remove a bookmark and check it has been removed.
:param bookmark_to_remove: the bookmark to remove
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param max_retries: the number of retries of removing the bookmark
fails.
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not removed from
bookmark list after `max_retries`
retries.
If there are multiple occurences of the same bookmark exactly
one is removed.
This does nothing if the bookmarks does not match an existing
bookmark according to bookmark-equality.
After setting the bookmark it is checked, whether the bookmark
is removed in the online storage, if it is not it is tried
again at most `max_retries` times to remove the bookmark. A
:class:`RuntimeError` is raised if the bookmark could not be
removed successfully after `max_retries`.
"""
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
occurences = bookmarks.count(bookmark_to_remove)
try:
if not occurences:
return
modified_bookmarks = list(bookmarks)
modified_bookmarks.remove(bookmark_to_remove)
yield from self._set_bookmarks(modified_bookmarks)
retries = 0
bookmarks = yield from self._get_bookmarks()
new_occurences = bookmarks.count(bookmark_to_remove)
while retries < max_retries:
if new_occurences < occurences:
break
modified_bookmarks = list(bookmarks)
modified_bookmarks.remove(bookmark_to_remove)
yield from self._set_bookmarks(modified_bookmarks)
bookmarks = yield from self._get_bookmarks()
new_occurences = bookmarks.count(bookmark_to_remove)
retries += 1
if new_occurences >= occurences:
raise RuntimeError("Could not remove bookmark")
finally:
self._diff_emit_update(bookmarks) | Remove a bookmark and check it has been removed.
:param bookmark_to_remove: the bookmark to remove
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param max_retries: the number of retries of removing the bookmark
fails.
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not removed from
bookmark list after `max_retries`
retries.
If there are multiple occurences of the same bookmark exactly
one is removed.
This does nothing if the bookmarks does not match an existing
bookmark according to bookmark-equality.
After setting the bookmark it is checked, whether the bookmark
is removed in the online storage, if it is not it is tried
again at most `max_retries` times to remove the bookmark. A
:class:`RuntimeError` is raised if the bookmark could not be
removed successfully after `max_retries`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L359-L413 |
horazont/aioxmpp | aioxmpp/bookmarks/service.py | BookmarkClient.update_bookmark | def update_bookmark(self, old, new, *, max_retries=3):
"""
Update a bookmark and check it was successful.
The bookmark matches an existing bookmark `old` according to
bookmark equalitiy and replaces it by `new`. The bookmark
`new` is added if no bookmark matching `old` exists.
:param old: the bookmark to replace
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param new: the replacement bookmark
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param max_retries: the number of retries of removing the bookmark
fails.
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not in the bookmark list
after `max_retries` retries.
After replacing the bookmark it is checked, whether the
bookmark `new` is in the online storage, if it is not it is
tried again at most `max_retries` times to replace the
bookmark. A :class:`RuntimeError` is raised if the bookmark
could not be replaced successfully after `max_retries`.
.. note:: Do not modify a bookmark retrieved from the signals
or from :meth:`get_bookmarks` to obtain the bookmark
`new`, this will lead to data corruption as they are
passed by reference. Instead use :func:`copy.copy`
and modify the copy.
"""
def replace_bookmark(bookmarks, old, new):
modified_bookmarks = list(bookmarks)
try:
i = bookmarks.index(old)
modified_bookmarks[i] = new
except ValueError:
modified_bookmarks.append(new)
return modified_bookmarks
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
try:
yield from self._set_bookmarks(
replace_bookmark(bookmarks, old, new)
)
retries = 0
bookmarks = yield from self._get_bookmarks()
while retries < max_retries:
if new in bookmarks:
break
yield from self._set_bookmarks(
replace_bookmark(bookmarks, old, new)
)
bookmarks = yield from self._get_bookmarks()
retries += 1
if new not in bookmarks:
raise RuntimeError("Cold not update bookmark")
finally:
self._diff_emit_update(bookmarks) | python | def update_bookmark(self, old, new, *, max_retries=3):
"""
Update a bookmark and check it was successful.
The bookmark matches an existing bookmark `old` according to
bookmark equalitiy and replaces it by `new`. The bookmark
`new` is added if no bookmark matching `old` exists.
:param old: the bookmark to replace
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param new: the replacement bookmark
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param max_retries: the number of retries of removing the bookmark
fails.
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not in the bookmark list
after `max_retries` retries.
After replacing the bookmark it is checked, whether the
bookmark `new` is in the online storage, if it is not it is
tried again at most `max_retries` times to replace the
bookmark. A :class:`RuntimeError` is raised if the bookmark
could not be replaced successfully after `max_retries`.
.. note:: Do not modify a bookmark retrieved from the signals
or from :meth:`get_bookmarks` to obtain the bookmark
`new`, this will lead to data corruption as they are
passed by reference. Instead use :func:`copy.copy`
and modify the copy.
"""
def replace_bookmark(bookmarks, old, new):
modified_bookmarks = list(bookmarks)
try:
i = bookmarks.index(old)
modified_bookmarks[i] = new
except ValueError:
modified_bookmarks.append(new)
return modified_bookmarks
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
try:
yield from self._set_bookmarks(
replace_bookmark(bookmarks, old, new)
)
retries = 0
bookmarks = yield from self._get_bookmarks()
while retries < max_retries:
if new in bookmarks:
break
yield from self._set_bookmarks(
replace_bookmark(bookmarks, old, new)
)
bookmarks = yield from self._get_bookmarks()
retries += 1
if new not in bookmarks:
raise RuntimeError("Cold not update bookmark")
finally:
self._diff_emit_update(bookmarks) | Update a bookmark and check it was successful.
The bookmark matches an existing bookmark `old` according to
bookmark equalitiy and replaces it by `new`. The bookmark
`new` is added if no bookmark matching `old` exists.
:param old: the bookmark to replace
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param new: the replacement bookmark
:type bookmark_to_remove: a :class:`~bookmark_xso.Bookmark` subclass.
:param max_retries: the number of retries of removing the bookmark
fails.
:type max_retries: :class:`int`
:raises RuntimeError: if the bookmark is not in the bookmark list
after `max_retries` retries.
After replacing the bookmark it is checked, whether the
bookmark `new` is in the online storage, if it is not it is
tried again at most `max_retries` times to replace the
bookmark. A :class:`RuntimeError` is raised if the bookmark
could not be replaced successfully after `max_retries`.
.. note:: Do not modify a bookmark retrieved from the signals
or from :meth:`get_bookmarks` to obtain the bookmark
`new`, this will lead to data corruption as they are
passed by reference. Instead use :func:`copy.copy`
and modify the copy. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L416-L479 |
horazont/aioxmpp | aioxmpp/disco/service.py | Node.iter_identities | def iter_identities(self, stanza=None):
"""
Return an iterator of tuples describing the identities of the node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ` or :data:`None`
:rtype: iterable of (:class:`str`, :class:`str`, :class:`str` or
:data:`None`, :class:`str` or :data:`None`) tuples
:return: :xep:`30` identities of this node
`stanza` can be the :class:`aioxmpp.IQ` stanza of the request. This can
be used to hide a node depending on who is asking. If the returned
iterable is empty, the :class:`~.DiscoServer` returns an
``<item-not-found/>`` error.
`stanza` may be :data:`None` if the identities are queried without
a specific request context. In that case, implementors should assume
that the result is visible to everybody.
.. note::
Subclasses must allow :data:`None` for `stanza` and default it to
:data:`None`.
Return an iterator which yields tuples consisting of the category, the
type, the language code and the name of each identity declared in this
:class:`Node`.
Both the language code and the name may be :data:`None`, if no names or
a name without language code have been declared.
"""
for (category, type_), names in self._identities.items():
for lang, name in names.items():
yield category, type_, lang, name
if not names:
yield category, type_, None, None | python | def iter_identities(self, stanza=None):
"""
Return an iterator of tuples describing the identities of the node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ` or :data:`None`
:rtype: iterable of (:class:`str`, :class:`str`, :class:`str` or
:data:`None`, :class:`str` or :data:`None`) tuples
:return: :xep:`30` identities of this node
`stanza` can be the :class:`aioxmpp.IQ` stanza of the request. This can
be used to hide a node depending on who is asking. If the returned
iterable is empty, the :class:`~.DiscoServer` returns an
``<item-not-found/>`` error.
`stanza` may be :data:`None` if the identities are queried without
a specific request context. In that case, implementors should assume
that the result is visible to everybody.
.. note::
Subclasses must allow :data:`None` for `stanza` and default it to
:data:`None`.
Return an iterator which yields tuples consisting of the category, the
type, the language code and the name of each identity declared in this
:class:`Node`.
Both the language code and the name may be :data:`None`, if no names or
a name without language code have been declared.
"""
for (category, type_), names in self._identities.items():
for lang, name in names.items():
yield category, type_, lang, name
if not names:
yield category, type_, None, None | Return an iterator of tuples describing the identities of the node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ` or :data:`None`
:rtype: iterable of (:class:`str`, :class:`str`, :class:`str` or
:data:`None`, :class:`str` or :data:`None`) tuples
:return: :xep:`30` identities of this node
`stanza` can be the :class:`aioxmpp.IQ` stanza of the request. This can
be used to hide a node depending on who is asking. If the returned
iterable is empty, the :class:`~.DiscoServer` returns an
``<item-not-found/>`` error.
`stanza` may be :data:`None` if the identities are queried without
a specific request context. In that case, implementors should assume
that the result is visible to everybody.
.. note::
Subclasses must allow :data:`None` for `stanza` and default it to
:data:`None`.
Return an iterator which yields tuples consisting of the category, the
type, the language code and the name of each identity declared in this
:class:`Node`.
Both the language code and the name may be :data:`None`, if no names or
a name without language code have been declared. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L98-L133 |
horazont/aioxmpp | aioxmpp/disco/service.py | Node.iter_features | def iter_features(self, stanza=None):
"""
Return an iterator which yields the features of the node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ`
:rtype: iterable of :class:`str`
:return: :xep:`30` features of this node
`stanza` is the :class:`aioxmpp.IQ` stanza of the request. This can be
used to filter the list according to who is asking (not recommended).
`stanza` may be :data:`None` if the features are queried without
a specific request context. In that case, implementors should assume
that the result is visible to everybody.
.. note::
Subclasses must allow :data:`None` for `stanza` and default it to
:data:`None`.
The features are returned as strings. The features demanded by
:xep:`30` are always returned.
"""
return itertools.chain(
iter(self.STATIC_FEATURES),
iter(self._features)
) | python | def iter_features(self, stanza=None):
"""
Return an iterator which yields the features of the node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ`
:rtype: iterable of :class:`str`
:return: :xep:`30` features of this node
`stanza` is the :class:`aioxmpp.IQ` stanza of the request. This can be
used to filter the list according to who is asking (not recommended).
`stanza` may be :data:`None` if the features are queried without
a specific request context. In that case, implementors should assume
that the result is visible to everybody.
.. note::
Subclasses must allow :data:`None` for `stanza` and default it to
:data:`None`.
The features are returned as strings. The features demanded by
:xep:`30` are always returned.
"""
return itertools.chain(
iter(self.STATIC_FEATURES),
iter(self._features)
) | Return an iterator which yields the features of the node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ`
:rtype: iterable of :class:`str`
:return: :xep:`30` features of this node
`stanza` is the :class:`aioxmpp.IQ` stanza of the request. This can be
used to filter the list according to who is asking (not recommended).
`stanza` may be :data:`None` if the features are queried without
a specific request context. In that case, implementors should assume
that the result is visible to everybody.
.. note::
Subclasses must allow :data:`None` for `stanza` and default it to
:data:`None`.
The features are returned as strings. The features demanded by
:xep:`30` are always returned. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L135-L163 |
horazont/aioxmpp | aioxmpp/disco/service.py | Node.register_feature | def register_feature(self, var):
"""
Register a feature with the namespace variable `var`.
If the feature is already registered or part of the default :xep:`30`
features, a :class:`ValueError` is raised.
"""
if var in self._features or var in self.STATIC_FEATURES:
raise ValueError("feature already claimed: {!r}".format(var))
self._features.add(var)
self.on_info_changed() | python | def register_feature(self, var):
"""
Register a feature with the namespace variable `var`.
If the feature is already registered or part of the default :xep:`30`
features, a :class:`ValueError` is raised.
"""
if var in self._features or var in self.STATIC_FEATURES:
raise ValueError("feature already claimed: {!r}".format(var))
self._features.add(var)
self.on_info_changed() | Register a feature with the namespace variable `var`.
If the feature is already registered or part of the default :xep:`30`
features, a :class:`ValueError` is raised. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L192-L202 |
horazont/aioxmpp | aioxmpp/disco/service.py | Node.register_identity | def register_identity(self, category, type_, *, names={}):
"""
Register an identity with the given `category` and `type_`.
If there is already a registered identity with the same `category` and
`type_`, :class:`ValueError` is raised.
`names` may be a mapping which maps :class:`.structs.LanguageTag`
instances to strings. This mapping will be used to produce
``<identity/>`` declarations with the respective ``xml:lang`` and
``name`` attributes.
"""
key = category, type_
if key in self._identities:
raise ValueError("identity already claimed: {!r}".format(key))
self._identities[key] = names
self.on_info_changed() | python | def register_identity(self, category, type_, *, names={}):
"""
Register an identity with the given `category` and `type_`.
If there is already a registered identity with the same `category` and
`type_`, :class:`ValueError` is raised.
`names` may be a mapping which maps :class:`.structs.LanguageTag`
instances to strings. This mapping will be used to produce
``<identity/>`` declarations with the respective ``xml:lang`` and
``name`` attributes.
"""
key = category, type_
if key in self._identities:
raise ValueError("identity already claimed: {!r}".format(key))
self._identities[key] = names
self.on_info_changed() | Register an identity with the given `category` and `type_`.
If there is already a registered identity with the same `category` and
`type_`, :class:`ValueError` is raised.
`names` may be a mapping which maps :class:`.structs.LanguageTag`
instances to strings. This mapping will be used to produce
``<identity/>`` declarations with the respective ``xml:lang`` and
``name`` attributes. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L204-L220 |
horazont/aioxmpp | aioxmpp/disco/service.py | Node.unregister_identity | def unregister_identity(self, category, type_):
"""
Unregister an identity previously registered using
:meth:`register_identity`.
If no identity with the given `category` and `type_` has been
registered before, :class:`KeyError` is raised.
If the identity to remove is the last identity of the :class:`Node`,
:class:`ValueError` is raised; a node must always have at least one
identity.
"""
key = category, type_
if key not in self._identities:
raise KeyError(key)
if len(self._identities) == 1:
raise ValueError("cannot remove last identity")
del self._identities[key]
self.on_info_changed() | python | def unregister_identity(self, category, type_):
"""
Unregister an identity previously registered using
:meth:`register_identity`.
If no identity with the given `category` and `type_` has been
registered before, :class:`KeyError` is raised.
If the identity to remove is the last identity of the :class:`Node`,
:class:`ValueError` is raised; a node must always have at least one
identity.
"""
key = category, type_
if key not in self._identities:
raise KeyError(key)
if len(self._identities) == 1:
raise ValueError("cannot remove last identity")
del self._identities[key]
self.on_info_changed() | Unregister an identity previously registered using
:meth:`register_identity`.
If no identity with the given `category` and `type_` has been
registered before, :class:`KeyError` is raised.
If the identity to remove is the last identity of the :class:`Node`,
:class:`ValueError` is raised; a node must always have at least one
identity. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L261-L279 |
horazont/aioxmpp | aioxmpp/disco/service.py | Node.as_info_xso | def as_info_xso(self, stanza=None):
"""
Construct a :class:`~.disco.xso.InfoQuery` response object for this
node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ`
:rtype: iterable of :class:`~.disco.xso.InfoQuery`
:return: The disco#info response for this node.
The resulting :class:`~.disco.xso.InfoQuery` carries the features and
identities as returned by :meth:`iter_features` and
:meth:`iter_identities`. The :attr:`~.disco.xso.InfoQuery.node`
attribute is at its default value and may need to be set by the caller
accordingly.
`stanza` is passed to :meth:`iter_features` and
:meth:`iter_identities`. See those methods for information on the
effects.
.. versionadded:: 0.9
"""
result = disco_xso.InfoQuery()
result.features.update(self.iter_features(stanza))
result.identities[:] = (
disco_xso.Identity(
category=category,
type_=type_,
lang=lang,
name=name,
)
for category, type_, lang, name in self.iter_identities(stanza)
)
return result | python | def as_info_xso(self, stanza=None):
"""
Construct a :class:`~.disco.xso.InfoQuery` response object for this
node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ`
:rtype: iterable of :class:`~.disco.xso.InfoQuery`
:return: The disco#info response for this node.
The resulting :class:`~.disco.xso.InfoQuery` carries the features and
identities as returned by :meth:`iter_features` and
:meth:`iter_identities`. The :attr:`~.disco.xso.InfoQuery.node`
attribute is at its default value and may need to be set by the caller
accordingly.
`stanza` is passed to :meth:`iter_features` and
:meth:`iter_identities`. See those methods for information on the
effects.
.. versionadded:: 0.9
"""
result = disco_xso.InfoQuery()
result.features.update(self.iter_features(stanza))
result.identities[:] = (
disco_xso.Identity(
category=category,
type_=type_,
lang=lang,
name=name,
)
for category, type_, lang, name in self.iter_identities(stanza)
)
return result | Construct a :class:`~.disco.xso.InfoQuery` response object for this
node.
:param stanza: The IQ request stanza
:type stanza: :class:`~aioxmpp.IQ`
:rtype: iterable of :class:`~.disco.xso.InfoQuery`
:return: The disco#info response for this node.
The resulting :class:`~.disco.xso.InfoQuery` carries the features and
identities as returned by :meth:`iter_features` and
:meth:`iter_identities`. The :attr:`~.disco.xso.InfoQuery.node`
attribute is at its default value and may need to be set by the caller
accordingly.
`stanza` is passed to :meth:`iter_features` and
:meth:`iter_identities`. See those methods for information on the
effects.
.. versionadded:: 0.9 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L281-L315 |
horazont/aioxmpp | aioxmpp/disco/service.py | StaticNode.clone | def clone(cls, other_node):
"""
Clone another :class:`Node` and return as :class:`StaticNode`.
:param other_node: The node which shall be cloned
:type other_node: :class:`Node`
:rtype: :class:`StaticNode`
:return: A static node which has the exact same features, identities
and items as `other_node`.
The features and identities are copied over into the resulting
:class:`StaticNode`. The items of `other_node` are not copied but
merely referenced, so changes to the item *objects* of `other_node`
will be reflected in the result.
.. versionadded:: 0.9
"""
result = cls()
result._features = {
feature for feature in other_node.iter_features()
if feature not in cls.STATIC_FEATURES
}
for category, type_, lang, name in other_node.iter_identities():
names = result._identities.setdefault(
(category, type_),
aioxmpp.structs.LanguageMap()
)
names[lang] = name
result.items = list(other_node.iter_items())
return result | python | def clone(cls, other_node):
"""
Clone another :class:`Node` and return as :class:`StaticNode`.
:param other_node: The node which shall be cloned
:type other_node: :class:`Node`
:rtype: :class:`StaticNode`
:return: A static node which has the exact same features, identities
and items as `other_node`.
The features and identities are copied over into the resulting
:class:`StaticNode`. The items of `other_node` are not copied but
merely referenced, so changes to the item *objects* of `other_node`
will be reflected in the result.
.. versionadded:: 0.9
"""
result = cls()
result._features = {
feature for feature in other_node.iter_features()
if feature not in cls.STATIC_FEATURES
}
for category, type_, lang, name in other_node.iter_identities():
names = result._identities.setdefault(
(category, type_),
aioxmpp.structs.LanguageMap()
)
names[lang] = name
result.items = list(other_node.iter_items())
return result | Clone another :class:`Node` and return as :class:`StaticNode`.
:param other_node: The node which shall be cloned
:type other_node: :class:`Node`
:rtype: :class:`StaticNode`
:return: A static node which has the exact same features, identities
and items as `other_node`.
The features and identities are copied over into the resulting
:class:`StaticNode`. The items of `other_node` are not copied but
merely referenced, so changes to the item *objects* of `other_node`
will be reflected in the result.
.. versionadded:: 0.9 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L342-L372 |
horazont/aioxmpp | aioxmpp/disco/service.py | DiscoClient.query_info | def query_info(self, jid, *,
node=None, require_fresh=False, timeout=None,
no_cache=False):
"""
Query the features and identities of the specified entity.
:param jid: The entity to query.
:type jid: :class:`aioxmpp.JID`
:param node: The node to query.
:type node: :class:`str` or :data:`None`
:param require_fresh: Boolean flag to discard previous caches.
:type require_fresh: :class:`bool`
:param timeout: Optional timeout for the response.
:type timeout: :class:`float`
:param no_cache: Boolean flag to forbid caching of the request.
:type no_cache: :class:`bool`
:rtype: :class:`.xso.InfoQuery`
:return: Service discovery information of the `node` at `jid`.
The requests are cached. This means that only one request is ever fired
for a given target (identified by the `jid` and the `node`). The
request is re-used for all subsequent requests to that identity.
If `require_fresh` is set to true, the above does not hold and a fresh
request is always created. The new request is the request which will be
used as alias for subsequent requests to the same identity.
The visible effects of this are twofold:
* Caching: Results of requests are implicitly cached
* Aliasing: Two concurrent requests will be aliased to one request to
save computing resources
Both can be turned off by using `require_fresh`. In general, you should
not need to use `require_fresh`, as all requests are implicitly
cancelled whenever the underlying session gets destroyed.
`no_cache` can be set to true to prevent future requests to be aliased
to this request, i.e. the request is not stored in the internal request
cache. This does not affect `require_fresh`, i.e. if a cached result is
available, it is used.
The `timeout` can be used to restrict the time to wait for a
response. If the timeout triggers, :class:`TimeoutError` is raised.
If :meth:`~.Client.send` raises an
exception, all queries which were running simultanously for the same
target re-raise that exception. The result is not cached though. If a
new query is sent at a later point for the same target, a new query is
actually sent, independent of the value chosen for `require_fresh`.
.. versionchanged:: 0.9
The `no_cache` argument was added.
"""
key = jid, node
if not require_fresh:
try:
request = self._info_pending[key]
except KeyError:
pass
else:
try:
return (yield from request)
except asyncio.CancelledError:
pass
request = asyncio.ensure_future(
self.send_and_decode_info_query(jid, node)
)
request.add_done_callback(
functools.partial(
self._handle_info_received,
jid,
node
)
)
if not no_cache:
self._info_pending[key] = request
try:
if timeout is not None:
try:
result = yield from asyncio.wait_for(
request,
timeout=timeout)
except asyncio.TimeoutError:
raise TimeoutError()
else:
result = yield from request
except: # NOQA
if request.done():
try:
pending = self._info_pending[key]
except KeyError:
pass
else:
if pending is request:
del self._info_pending[key]
raise
return result | python | def query_info(self, jid, *,
node=None, require_fresh=False, timeout=None,
no_cache=False):
"""
Query the features and identities of the specified entity.
:param jid: The entity to query.
:type jid: :class:`aioxmpp.JID`
:param node: The node to query.
:type node: :class:`str` or :data:`None`
:param require_fresh: Boolean flag to discard previous caches.
:type require_fresh: :class:`bool`
:param timeout: Optional timeout for the response.
:type timeout: :class:`float`
:param no_cache: Boolean flag to forbid caching of the request.
:type no_cache: :class:`bool`
:rtype: :class:`.xso.InfoQuery`
:return: Service discovery information of the `node` at `jid`.
The requests are cached. This means that only one request is ever fired
for a given target (identified by the `jid` and the `node`). The
request is re-used for all subsequent requests to that identity.
If `require_fresh` is set to true, the above does not hold and a fresh
request is always created. The new request is the request which will be
used as alias for subsequent requests to the same identity.
The visible effects of this are twofold:
* Caching: Results of requests are implicitly cached
* Aliasing: Two concurrent requests will be aliased to one request to
save computing resources
Both can be turned off by using `require_fresh`. In general, you should
not need to use `require_fresh`, as all requests are implicitly
cancelled whenever the underlying session gets destroyed.
`no_cache` can be set to true to prevent future requests to be aliased
to this request, i.e. the request is not stored in the internal request
cache. This does not affect `require_fresh`, i.e. if a cached result is
available, it is used.
The `timeout` can be used to restrict the time to wait for a
response. If the timeout triggers, :class:`TimeoutError` is raised.
If :meth:`~.Client.send` raises an
exception, all queries which were running simultanously for the same
target re-raise that exception. The result is not cached though. If a
new query is sent at a later point for the same target, a new query is
actually sent, independent of the value chosen for `require_fresh`.
.. versionchanged:: 0.9
The `no_cache` argument was added.
"""
key = jid, node
if not require_fresh:
try:
request = self._info_pending[key]
except KeyError:
pass
else:
try:
return (yield from request)
except asyncio.CancelledError:
pass
request = asyncio.ensure_future(
self.send_and_decode_info_query(jid, node)
)
request.add_done_callback(
functools.partial(
self._handle_info_received,
jid,
node
)
)
if not no_cache:
self._info_pending[key] = request
try:
if timeout is not None:
try:
result = yield from asyncio.wait_for(
request,
timeout=timeout)
except asyncio.TimeoutError:
raise TimeoutError()
else:
result = yield from request
except: # NOQA
if request.done():
try:
pending = self._info_pending[key]
except KeyError:
pass
else:
if pending is request:
del self._info_pending[key]
raise
return result | Query the features and identities of the specified entity.
:param jid: The entity to query.
:type jid: :class:`aioxmpp.JID`
:param node: The node to query.
:type node: :class:`str` or :data:`None`
:param require_fresh: Boolean flag to discard previous caches.
:type require_fresh: :class:`bool`
:param timeout: Optional timeout for the response.
:type timeout: :class:`float`
:param no_cache: Boolean flag to forbid caching of the request.
:type no_cache: :class:`bool`
:rtype: :class:`.xso.InfoQuery`
:return: Service discovery information of the `node` at `jid`.
The requests are cached. This means that only one request is ever fired
for a given target (identified by the `jid` and the `node`). The
request is re-used for all subsequent requests to that identity.
If `require_fresh` is set to true, the above does not hold and a fresh
request is always created. The new request is the request which will be
used as alias for subsequent requests to the same identity.
The visible effects of this are twofold:
* Caching: Results of requests are implicitly cached
* Aliasing: Two concurrent requests will be aliased to one request to
save computing resources
Both can be turned off by using `require_fresh`. In general, you should
not need to use `require_fresh`, as all requests are implicitly
cancelled whenever the underlying session gets destroyed.
`no_cache` can be set to true to prevent future requests to be aliased
to this request, i.e. the request is not stored in the internal request
cache. This does not affect `require_fresh`, i.e. if a cached result is
available, it is used.
The `timeout` can be used to restrict the time to wait for a
response. If the timeout triggers, :class:`TimeoutError` is raised.
If :meth:`~.Client.send` raises an
exception, all queries which were running simultanously for the same
target re-raise that exception. The result is not cached though. If a
new query is sent at a later point for the same target, a new query is
actually sent, independent of the value chosen for `require_fresh`.
.. versionchanged:: 0.9
The `no_cache` argument was added. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L644-L746 |
horazont/aioxmpp | aioxmpp/disco/service.py | DiscoClient.query_items | def query_items(self, jid, *,
node=None, require_fresh=False, timeout=None):
"""
Query the items of the specified entity.
:param jid: The entity to query.
:type jid: :class:`aioxmpp.JID`
:param node: The node to query.
:type node: :class:`str` or :data:`None`
:param require_fresh: Boolean flag to discard previous caches.
:type require_fresh: :class:`bool`
:param timeout: Optional timeout for the response.
:type timeout: :class:`float`
:rtype: :class:`.xso.ItemsQuery`
:return: Service discovery items of the `node` at `jid`.
The arguments have the same semantics as with :meth:`query_info`, as
does the caching and error handling.
"""
key = jid, node
if not require_fresh:
try:
request = self._items_pending[key]
except KeyError:
pass
else:
try:
return (yield from request)
except asyncio.CancelledError:
pass
request_iq = stanza.IQ(to=jid, type_=structs.IQType.GET)
request_iq.payload = disco_xso.ItemsQuery(node=node)
request = asyncio.ensure_future(
self.client.send(request_iq)
)
self._items_pending[key] = request
try:
if timeout is not None:
try:
result = yield from asyncio.wait_for(
request,
timeout=timeout)
except asyncio.TimeoutError:
raise TimeoutError()
else:
result = yield from request
except: # NOQA
if request.done():
try:
pending = self._items_pending[key]
except KeyError:
pass
else:
if pending is request:
del self._items_pending[key]
raise
return result | python | def query_items(self, jid, *,
node=None, require_fresh=False, timeout=None):
"""
Query the items of the specified entity.
:param jid: The entity to query.
:type jid: :class:`aioxmpp.JID`
:param node: The node to query.
:type node: :class:`str` or :data:`None`
:param require_fresh: Boolean flag to discard previous caches.
:type require_fresh: :class:`bool`
:param timeout: Optional timeout for the response.
:type timeout: :class:`float`
:rtype: :class:`.xso.ItemsQuery`
:return: Service discovery items of the `node` at `jid`.
The arguments have the same semantics as with :meth:`query_info`, as
does the caching and error handling.
"""
key = jid, node
if not require_fresh:
try:
request = self._items_pending[key]
except KeyError:
pass
else:
try:
return (yield from request)
except asyncio.CancelledError:
pass
request_iq = stanza.IQ(to=jid, type_=structs.IQType.GET)
request_iq.payload = disco_xso.ItemsQuery(node=node)
request = asyncio.ensure_future(
self.client.send(request_iq)
)
self._items_pending[key] = request
try:
if timeout is not None:
try:
result = yield from asyncio.wait_for(
request,
timeout=timeout)
except asyncio.TimeoutError:
raise TimeoutError()
else:
result = yield from request
except: # NOQA
if request.done():
try:
pending = self._items_pending[key]
except KeyError:
pass
else:
if pending is request:
del self._items_pending[key]
raise
return result | Query the items of the specified entity.
:param jid: The entity to query.
:type jid: :class:`aioxmpp.JID`
:param node: The node to query.
:type node: :class:`str` or :data:`None`
:param require_fresh: Boolean flag to discard previous caches.
:type require_fresh: :class:`bool`
:param timeout: Optional timeout for the response.
:type timeout: :class:`float`
:rtype: :class:`.xso.ItemsQuery`
:return: Service discovery items of the `node` at `jid`.
The arguments have the same semantics as with :meth:`query_info`, as
does the caching and error handling. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L749-L810 |
horazont/aioxmpp | aioxmpp/disco/service.py | DiscoClient.set_info_cache | def set_info_cache(self, jid, node, info):
"""
This is a wrapper around :meth:`set_info_future` which creates a future
and immediately assigns `info` as its result.
.. versionadded:: 0.5
"""
fut = asyncio.Future()
fut.set_result(info)
self.set_info_future(jid, node, fut) | python | def set_info_cache(self, jid, node, info):
"""
This is a wrapper around :meth:`set_info_future` which creates a future
and immediately assigns `info` as its result.
.. versionadded:: 0.5
"""
fut = asyncio.Future()
fut.set_result(info)
self.set_info_future(jid, node, fut) | This is a wrapper around :meth:`set_info_future` which creates a future
and immediately assigns `info` as its result.
.. versionadded:: 0.5 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L812-L821 |
horazont/aioxmpp | aioxmpp/disco/service.py | DiscoClient.set_info_future | def set_info_future(self, jid, node, fut):
"""
Override the cache entry (if one exists) for :meth:`query_info` of the
`jid` and `node` combination with the given :class:`asyncio.Future`
fut.
The future must receive a :class:`dict` compatible to the output of
:meth:`.xso.InfoQuery.to_dict`.
As usual, the cache can be bypassed and cleared by passing
`require_fresh` to :meth:`query_info`.
.. seealso::
Module :mod:`aioxmpp.entitycaps`
:xep:`0115` implementation which uses this method to prime the
cache with information derived from Entity Capability
announcements.
.. note::
If a future is set to exception state, it will still remain and make
all queries for that target fail with that exception, until a query
uses `require_fresh`.
.. versionadded:: 0.5
"""
self._info_pending[jid, node] = fut | python | def set_info_future(self, jid, node, fut):
"""
Override the cache entry (if one exists) for :meth:`query_info` of the
`jid` and `node` combination with the given :class:`asyncio.Future`
fut.
The future must receive a :class:`dict` compatible to the output of
:meth:`.xso.InfoQuery.to_dict`.
As usual, the cache can be bypassed and cleared by passing
`require_fresh` to :meth:`query_info`.
.. seealso::
Module :mod:`aioxmpp.entitycaps`
:xep:`0115` implementation which uses this method to prime the
cache with information derived from Entity Capability
announcements.
.. note::
If a future is set to exception state, it will still remain and make
all queries for that target fail with that exception, until a query
uses `require_fresh`.
.. versionadded:: 0.5
"""
self._info_pending[jid, node] = fut | Override the cache entry (if one exists) for :meth:`query_info` of the
`jid` and `node` combination with the given :class:`asyncio.Future`
fut.
The future must receive a :class:`dict` compatible to the output of
:meth:`.xso.InfoQuery.to_dict`.
As usual, the cache can be bypassed and cleared by passing
`require_fresh` to :meth:`query_info`.
.. seealso::
Module :mod:`aioxmpp.entitycaps`
:xep:`0115` implementation which uses this method to prime the
cache with information derived from Entity Capability
announcements.
.. note::
If a future is set to exception state, it will still remain and make
all queries for that target fail with that exception, until a query
uses `require_fresh`.
.. versionadded:: 0.5 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/disco/service.py#L823-L850 |
horazont/aioxmpp | aioxmpp/i18n.py | LocalizableString.localize | def localize(self, formatter, translator, *args, **kwargs):
"""
Localize and format the string using the given `formatter` and
`translator`. The remaining args are passed to the
:meth:`~LocalizingFormatter.format` method of the `formatter`.
The `translator` must be an object supporting the
:class:`gettext.NullTranslations` interface.
If :attr:`plural` is not :data:`None`, the number which will be passed
to the `ngettext` method of `translator` is first extracted from the
`args` or `kwargs`, depending on :attr:`number_index`. The whole
semantics of all three are described in
:meth:`string.Formatter.get_field`, which is used by this method
(:attr:`number_index` is passed as `field_name`).
The value returned by :meth:`~string.Formatter.get_field` is then used
as third argument to `ngettext`, while the others are sourced from
:attr:`singular` and :attr:`plural`.
If :attr:`plural` is :data:`None`, the `gettext` method of `translator`
is used with :attr:`singular` as its only argument.
After the translation step, the `formatter` is used with the translated
string and `args` and `kwargs` to obtain a formatted version of the
string which is then returned.
All of this works best when using a :class:`LocalizingFormatter`.
"""
if self.plural is not None:
n, _ = formatter.get_field(self.number_index, args, kwargs)
translated = translator.ngettext(self.singular,
self.plural,
n)
else:
translated = translator.gettext(self.singular)
return formatter.vformat(translated, args, kwargs) | python | def localize(self, formatter, translator, *args, **kwargs):
"""
Localize and format the string using the given `formatter` and
`translator`. The remaining args are passed to the
:meth:`~LocalizingFormatter.format` method of the `formatter`.
The `translator` must be an object supporting the
:class:`gettext.NullTranslations` interface.
If :attr:`plural` is not :data:`None`, the number which will be passed
to the `ngettext` method of `translator` is first extracted from the
`args` or `kwargs`, depending on :attr:`number_index`. The whole
semantics of all three are described in
:meth:`string.Formatter.get_field`, which is used by this method
(:attr:`number_index` is passed as `field_name`).
The value returned by :meth:`~string.Formatter.get_field` is then used
as third argument to `ngettext`, while the others are sourced from
:attr:`singular` and :attr:`plural`.
If :attr:`plural` is :data:`None`, the `gettext` method of `translator`
is used with :attr:`singular` as its only argument.
After the translation step, the `formatter` is used with the translated
string and `args` and `kwargs` to obtain a formatted version of the
string which is then returned.
All of this works best when using a :class:`LocalizingFormatter`.
"""
if self.plural is not None:
n, _ = formatter.get_field(self.number_index, args, kwargs)
translated = translator.ngettext(self.singular,
self.plural,
n)
else:
translated = translator.gettext(self.singular)
return formatter.vformat(translated, args, kwargs) | Localize and format the string using the given `formatter` and
`translator`. The remaining args are passed to the
:meth:`~LocalizingFormatter.format` method of the `formatter`.
The `translator` must be an object supporting the
:class:`gettext.NullTranslations` interface.
If :attr:`plural` is not :data:`None`, the number which will be passed
to the `ngettext` method of `translator` is first extracted from the
`args` or `kwargs`, depending on :attr:`number_index`. The whole
semantics of all three are described in
:meth:`string.Formatter.get_field`, which is used by this method
(:attr:`number_index` is passed as `field_name`).
The value returned by :meth:`~string.Formatter.get_field` is then used
as third argument to `ngettext`, while the others are sourced from
:attr:`singular` and :attr:`plural`.
If :attr:`plural` is :data:`None`, the `gettext` method of `translator`
is used with :attr:`singular` as its only argument.
After the translation step, the `formatter` is used with the translated
string and `args` and `kwargs` to obtain a formatted version of the
string which is then returned.
All of this works best when using a :class:`LocalizingFormatter`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/i18n.py#L261-L297 |
horazont/aioxmpp | aioxmpp/roster/service.py | Item.update_from_xso_item | def update_from_xso_item(self, xso_item):
"""
Update the attributes (except :attr:`jid`) with the values obtained
from the gixen `xso_item`.
`xso_item` must be a valid :class:`.xso.Item` instance.
"""
self.subscription = xso_item.subscription
self.approved = xso_item.approved
self.ask = xso_item.ask
self.name = xso_item.name
self.groups = {group.name for group in xso_item.groups} | python | def update_from_xso_item(self, xso_item):
"""
Update the attributes (except :attr:`jid`) with the values obtained
from the gixen `xso_item`.
`xso_item` must be a valid :class:`.xso.Item` instance.
"""
self.subscription = xso_item.subscription
self.approved = xso_item.approved
self.ask = xso_item.ask
self.name = xso_item.name
self.groups = {group.name for group in xso_item.groups} | Update the attributes (except :attr:`jid`) with the values obtained
from the gixen `xso_item`.
`xso_item` must be a valid :class:`.xso.Item` instance. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L108-L119 |
horazont/aioxmpp | aioxmpp/roster/service.py | Item.from_xso_item | def from_xso_item(cls, xso_item):
"""
Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it.
"""
item = cls(xso_item.jid)
item.update_from_xso_item(xso_item)
return item | python | def from_xso_item(cls, xso_item):
"""
Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it.
"""
item = cls(xso_item.jid)
item.update_from_xso_item(xso_item)
return item | Create a :class:`Item` with the :attr:`jid` set to the
:attr:`.xso.Item.jid` obtained from `xso_item`. Then update that
instance with `xso_item` using :meth:`update_from_xso_item` and return
it. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L122-L131 |
horazont/aioxmpp | aioxmpp/roster/service.py | Item.export_as_json | def export_as_json(self):
"""
Return a :mod:`json`-compatible dictionary which contains the
attributes of this :class:`Item` except its JID.
"""
result = {
"subscription": self.subscription,
}
if self.name:
result["name"] = self.name
if self.ask is not None:
result["ask"] = self.ask
if self.approved:
result["approved"] = self.approved
if self.groups:
result["groups"] = sorted(self.groups)
return result | python | def export_as_json(self):
"""
Return a :mod:`json`-compatible dictionary which contains the
attributes of this :class:`Item` except its JID.
"""
result = {
"subscription": self.subscription,
}
if self.name:
result["name"] = self.name
if self.ask is not None:
result["ask"] = self.ask
if self.approved:
result["approved"] = self.approved
if self.groups:
result["groups"] = sorted(self.groups)
return result | Return a :mod:`json`-compatible dictionary which contains the
attributes of this :class:`Item` except its JID. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L133-L154 |
horazont/aioxmpp | aioxmpp/roster/service.py | Item.update_from_json | def update_from_json(self, data):
"""
Update the attributes of this :class:`Item` using the values obtained
from the dictionary `data`.
The format of `data` should be the same as the format returned by
:meth:`export_as_json`.
"""
self.subscription = data.get("subscription", "none")
self.approved = bool(data.get("approved", False))
self.ask = data.get("ask", None)
self.name = data.get("name", None)
self.groups = set(data.get("groups", [])) | python | def update_from_json(self, data):
"""
Update the attributes of this :class:`Item` using the values obtained
from the dictionary `data`.
The format of `data` should be the same as the format returned by
:meth:`export_as_json`.
"""
self.subscription = data.get("subscription", "none")
self.approved = bool(data.get("approved", False))
self.ask = data.get("ask", None)
self.name = data.get("name", None)
self.groups = set(data.get("groups", [])) | Update the attributes of this :class:`Item` using the values obtained
from the dictionary `data`.
The format of `data` should be the same as the format returned by
:meth:`export_as_json`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L156-L168 |
horazont/aioxmpp | aioxmpp/roster/service.py | RosterClient.export_as_json | def export_as_json(self):
"""
Export the whole roster as currently stored on the client side into a
JSON-compatible dictionary and return that dictionary.
"""
return {
"items": {
str(jid): item.export_as_json()
for jid, item in self.items.items()
},
"ver": self.version
} | python | def export_as_json(self):
"""
Export the whole roster as currently stored on the client side into a
JSON-compatible dictionary and return that dictionary.
"""
return {
"items": {
str(jid): item.export_as_json()
for jid, item in self.items.items()
},
"ver": self.version
} | Export the whole roster as currently stored on the client side into a
JSON-compatible dictionary and return that dictionary. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L574-L585 |
horazont/aioxmpp | aioxmpp/roster/service.py | RosterClient.import_from_json | def import_from_json(self, data):
"""
Replace the current roster with the :meth:`export_as_json`-compatible
dictionary in `data`.
No events are fired during this activity. After this method completes,
the whole roster contents are exchanged with the contents from `data`.
Also, no data is transferred to the server; this method is intended to
be used for roster versioning. See below (in the docs of
:class:`Service`).
"""
self.version = data.get("ver", None)
self.items.clear()
self.groups.clear()
for jid, data in data.get("items", {}).items():
jid = structs.JID.fromstr(jid)
item = Item(jid)
item.update_from_json(data)
self.items[jid] = item
for group in item.groups:
self.groups.setdefault(group, set()).add(item) | python | def import_from_json(self, data):
"""
Replace the current roster with the :meth:`export_as_json`-compatible
dictionary in `data`.
No events are fired during this activity. After this method completes,
the whole roster contents are exchanged with the contents from `data`.
Also, no data is transferred to the server; this method is intended to
be used for roster versioning. See below (in the docs of
:class:`Service`).
"""
self.version = data.get("ver", None)
self.items.clear()
self.groups.clear()
for jid, data in data.get("items", {}).items():
jid = structs.JID.fromstr(jid)
item = Item(jid)
item.update_from_json(data)
self.items[jid] = item
for group in item.groups:
self.groups.setdefault(group, set()).add(item) | Replace the current roster with the :meth:`export_as_json`-compatible
dictionary in `data`.
No events are fired during this activity. After this method completes,
the whole roster contents are exchanged with the contents from `data`.
Also, no data is transferred to the server; this method is intended to
be used for roster versioning. See below (in the docs of
:class:`Service`). | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L587-L609 |
horazont/aioxmpp | aioxmpp/roster/service.py | RosterClient.set_entry | def set_entry(self, jid, *,
name=_Sentinel,
add_to_groups=frozenset(),
remove_from_groups=frozenset(),
timeout=None):
"""
Set properties of a roster entry or add a new roster entry. The roster
entry is identified by its bare `jid`.
If an entry already exists, all values default to those stored in the
existing entry. For example, if no `name` is given, the current name of
the entry is re-used, if any.
If the entry does not exist, it will be created on the server side.
The `remove_from_groups` and `add_to_groups` arguments have to be based
on the locally cached state, as XMPP does not support sending
diffs. `remove_from_groups` takes precedence over `add_to_groups`.
`timeout` is the time in seconds to wait for a confirmation by the
server.
Note that the changes may not be visible immediately after his
coroutine returns in the :attr:`items` and :attr:`groups`
attributes. The :class:`Service` waits for the "official" roster push
from the server for updating the data structures and firing events, to
ensure that consistent state with other clients is achieved.
This may raise arbitrary :class:`.errors.XMPPError` exceptions if the
server replies with an error and also any kind of connection error if
the connection gets fatally terminated while waiting for a response.
"""
existing = self.items.get(jid, Item(jid))
post_groups = (existing.groups | add_to_groups) - remove_from_groups
post_name = existing.name
if name is not _Sentinel:
post_name = name
item = roster_xso.Item(
jid=jid,
name=post_name,
groups=[
roster_xso.Group(name=group_name)
for group_name in post_groups
])
yield from self.client.send(
stanza.IQ(
structs.IQType.SET,
payload=roster_xso.Query(items=[
item
])
),
timeout=timeout
) | python | def set_entry(self, jid, *,
name=_Sentinel,
add_to_groups=frozenset(),
remove_from_groups=frozenset(),
timeout=None):
"""
Set properties of a roster entry or add a new roster entry. The roster
entry is identified by its bare `jid`.
If an entry already exists, all values default to those stored in the
existing entry. For example, if no `name` is given, the current name of
the entry is re-used, if any.
If the entry does not exist, it will be created on the server side.
The `remove_from_groups` and `add_to_groups` arguments have to be based
on the locally cached state, as XMPP does not support sending
diffs. `remove_from_groups` takes precedence over `add_to_groups`.
`timeout` is the time in seconds to wait for a confirmation by the
server.
Note that the changes may not be visible immediately after his
coroutine returns in the :attr:`items` and :attr:`groups`
attributes. The :class:`Service` waits for the "official" roster push
from the server for updating the data structures and firing events, to
ensure that consistent state with other clients is achieved.
This may raise arbitrary :class:`.errors.XMPPError` exceptions if the
server replies with an error and also any kind of connection error if
the connection gets fatally terminated while waiting for a response.
"""
existing = self.items.get(jid, Item(jid))
post_groups = (existing.groups | add_to_groups) - remove_from_groups
post_name = existing.name
if name is not _Sentinel:
post_name = name
item = roster_xso.Item(
jid=jid,
name=post_name,
groups=[
roster_xso.Group(name=group_name)
for group_name in post_groups
])
yield from self.client.send(
stanza.IQ(
structs.IQType.SET,
payload=roster_xso.Query(items=[
item
])
),
timeout=timeout
) | Set properties of a roster entry or add a new roster entry. The roster
entry is identified by its bare `jid`.
If an entry already exists, all values default to those stored in the
existing entry. For example, if no `name` is given, the current name of
the entry is re-used, if any.
If the entry does not exist, it will be created on the server side.
The `remove_from_groups` and `add_to_groups` arguments have to be based
on the locally cached state, as XMPP does not support sending
diffs. `remove_from_groups` takes precedence over `add_to_groups`.
`timeout` is the time in seconds to wait for a confirmation by the
server.
Note that the changes may not be visible immediately after his
coroutine returns in the :attr:`items` and :attr:`groups`
attributes. The :class:`Service` waits for the "official" roster push
from the server for updating the data structures and firing events, to
ensure that consistent state with other clients is achieved.
This may raise arbitrary :class:`.errors.XMPPError` exceptions if the
server replies with an error and also any kind of connection error if
the connection gets fatally terminated while waiting for a response. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L612-L668 |
horazont/aioxmpp | aioxmpp/roster/service.py | RosterClient.remove_entry | def remove_entry(self, jid, *, timeout=None):
"""
Request removal of the roster entry identified by the given bare
`jid`. If the entry currently has any subscription state, the server
will send the corresponding unsubscribing presence stanzas.
`timeout` is the maximum time in seconds to wait for a reply from the
server.
This may raise arbitrary :class:`.errors.XMPPError` exceptions if the
server replies with an error and also any kind of connection error if
the connection gets fatally terminated while waiting for a response.
"""
yield from self.client.send(
stanza.IQ(
structs.IQType.SET,
payload=roster_xso.Query(items=[
roster_xso.Item(
jid=jid,
subscription="remove"
)
])
),
timeout=timeout
) | python | def remove_entry(self, jid, *, timeout=None):
"""
Request removal of the roster entry identified by the given bare
`jid`. If the entry currently has any subscription state, the server
will send the corresponding unsubscribing presence stanzas.
`timeout` is the maximum time in seconds to wait for a reply from the
server.
This may raise arbitrary :class:`.errors.XMPPError` exceptions if the
server replies with an error and also any kind of connection error if
the connection gets fatally terminated while waiting for a response.
"""
yield from self.client.send(
stanza.IQ(
structs.IQType.SET,
payload=roster_xso.Query(items=[
roster_xso.Item(
jid=jid,
subscription="remove"
)
])
),
timeout=timeout
) | Request removal of the roster entry identified by the given bare
`jid`. If the entry currently has any subscription state, the server
will send the corresponding unsubscribing presence stanzas.
`timeout` is the maximum time in seconds to wait for a reply from the
server.
This may raise arbitrary :class:`.errors.XMPPError` exceptions if the
server replies with an error and also any kind of connection error if
the connection gets fatally terminated while waiting for a response. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L671-L695 |
horazont/aioxmpp | aioxmpp/roster/service.py | RosterClient.approve | def approve(self, peer_jid):
"""
(Pre-)approve a subscription request from `peer_jid`.
:param peer_jid: The peer to (pre-)approve.
This sends a ``"subscribed"`` presence to the peer; if the peer has
previously asked for a subscription, this will seal the deal and create
the subscription.
If the peer has not requested a subscription (yet), it is marked as
pre-approved by the server. A future subscription request by the peer
will then be confirmed by the server automatically.
.. note::
Pre-approval is an OPTIONAL feature in :rfc:`6121`. It is announced
as a stream feature.
"""
self.client.enqueue(
stanza.Presence(type_=structs.PresenceType.SUBSCRIBED,
to=peer_jid)
) | python | def approve(self, peer_jid):
"""
(Pre-)approve a subscription request from `peer_jid`.
:param peer_jid: The peer to (pre-)approve.
This sends a ``"subscribed"`` presence to the peer; if the peer has
previously asked for a subscription, this will seal the deal and create
the subscription.
If the peer has not requested a subscription (yet), it is marked as
pre-approved by the server. A future subscription request by the peer
will then be confirmed by the server automatically.
.. note::
Pre-approval is an OPTIONAL feature in :rfc:`6121`. It is announced
as a stream feature.
"""
self.client.enqueue(
stanza.Presence(type_=structs.PresenceType.SUBSCRIBED,
to=peer_jid)
) | (Pre-)approve a subscription request from `peer_jid`.
:param peer_jid: The peer to (pre-)approve.
This sends a ``"subscribed"`` presence to the peer; if the peer has
previously asked for a subscription, this will seal the deal and create
the subscription.
If the peer has not requested a subscription (yet), it is marked as
pre-approved by the server. A future subscription request by the peer
will then be confirmed by the server automatically.
.. note::
Pre-approval is an OPTIONAL feature in :rfc:`6121`. It is announced
as a stream feature. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L697-L719 |
horazont/aioxmpp | aioxmpp/roster/service.py | RosterClient.subscribe | def subscribe(self, peer_jid):
"""
Request presence subscription with the given `peer_jid`.
This is deliberately not a coroutine; we don’t know whether the peer is
online (usually) and they may defer the confirmation very long, if they
confirm at all. Use :meth:`on_subscribed` to get notified when a peer
accepted a subscription request.
"""
self.client.enqueue(
stanza.Presence(type_=structs.PresenceType.SUBSCRIBE,
to=peer_jid)
) | python | def subscribe(self, peer_jid):
"""
Request presence subscription with the given `peer_jid`.
This is deliberately not a coroutine; we don’t know whether the peer is
online (usually) and they may defer the confirmation very long, if they
confirm at all. Use :meth:`on_subscribed` to get notified when a peer
accepted a subscription request.
"""
self.client.enqueue(
stanza.Presence(type_=structs.PresenceType.SUBSCRIBE,
to=peer_jid)
) | Request presence subscription with the given `peer_jid`.
This is deliberately not a coroutine; we don’t know whether the peer is
online (usually) and they may defer the confirmation very long, if they
confirm at all. Use :meth:`on_subscribed` to get notified when a peer
accepted a subscription request. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L721-L733 |
horazont/aioxmpp | aioxmpp/roster/service.py | RosterClient.unsubscribe | def unsubscribe(self, peer_jid):
"""
Unsubscribe from the presence of the given `peer_jid`.
"""
self.client.enqueue(
stanza.Presence(type_=structs.PresenceType.UNSUBSCRIBE,
to=peer_jid)
) | python | def unsubscribe(self, peer_jid):
"""
Unsubscribe from the presence of the given `peer_jid`.
"""
self.client.enqueue(
stanza.Presence(type_=structs.PresenceType.UNSUBSCRIBE,
to=peer_jid)
) | Unsubscribe from the presence of the given `peer_jid`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L735-L742 |
horazont/aioxmpp | aioxmpp/dispatcher.py | message_handler | def message_handler(type_, from_):
"""
Register the decorated function as message handler.
:param type_: Message type to listen for
:type type_: :class:`~.MessageType`
:param from_: Sender JIDs to listen for
:type from_: :class:`aioxmpp.JID` or :data:`None`
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:meth:`~.StanzaStream.register_message_callback`
for more details on the `type_` and `from_` arguments
.. versionchanged:: 0.9
This is now based on
:class:`aioxmpp.dispatcher.SimpleMessageDispatcher`.
"""
def decorator(f):
if asyncio.iscoroutinefunction(f):
raise TypeError("message_handler must not be a coroutine function")
aioxmpp.service.add_handler_spec(
f,
aioxmpp.service.HandlerSpec(
(_apply_message_handler, (type_, from_)),
require_deps=(
SimpleMessageDispatcher,
)
)
)
return f
return decorator | python | def message_handler(type_, from_):
"""
Register the decorated function as message handler.
:param type_: Message type to listen for
:type type_: :class:`~.MessageType`
:param from_: Sender JIDs to listen for
:type from_: :class:`aioxmpp.JID` or :data:`None`
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:meth:`~.StanzaStream.register_message_callback`
for more details on the `type_` and `from_` arguments
.. versionchanged:: 0.9
This is now based on
:class:`aioxmpp.dispatcher.SimpleMessageDispatcher`.
"""
def decorator(f):
if asyncio.iscoroutinefunction(f):
raise TypeError("message_handler must not be a coroutine function")
aioxmpp.service.add_handler_spec(
f,
aioxmpp.service.HandlerSpec(
(_apply_message_handler, (type_, from_)),
require_deps=(
SimpleMessageDispatcher,
)
)
)
return f
return decorator | Register the decorated function as message handler.
:param type_: Message type to listen for
:type type_: :class:`~.MessageType`
:param from_: Sender JIDs to listen for
:type from_: :class:`aioxmpp.JID` or :data:`None`
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:meth:`~.StanzaStream.register_message_callback`
for more details on the `type_` and `from_` arguments
.. versionchanged:: 0.9
This is now based on
:class:`aioxmpp.dispatcher.SimpleMessageDispatcher`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L338-L373 |
horazont/aioxmpp | aioxmpp/dispatcher.py | presence_handler | def presence_handler(type_, from_):
"""
Register the decorated function as presence stanza handler.
:param type_: Presence type to listen for
:type type_: :class:`~.PresenceType`
:param from_: Sender JIDs to listen for
:type from_: :class:`aioxmpp.JID` or :data:`None`
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:meth:`~.StanzaStream.register_presence_callback`
for more details on the `type_` and `from_` arguments
.. versionchanged:: 0.9
This is now based on
:class:`aioxmpp.dispatcher.SimplePresenceDispatcher`.
"""
def decorator(f):
if asyncio.iscoroutinefunction(f):
raise TypeError(
"presence_handler must not be a coroutine function"
)
aioxmpp.service.add_handler_spec(
f,
aioxmpp.service.HandlerSpec(
(_apply_presence_handler, (type_, from_)),
require_deps=(
SimplePresenceDispatcher,
)
)
)
return f
return decorator | python | def presence_handler(type_, from_):
"""
Register the decorated function as presence stanza handler.
:param type_: Presence type to listen for
:type type_: :class:`~.PresenceType`
:param from_: Sender JIDs to listen for
:type from_: :class:`aioxmpp.JID` or :data:`None`
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:meth:`~.StanzaStream.register_presence_callback`
for more details on the `type_` and `from_` arguments
.. versionchanged:: 0.9
This is now based on
:class:`aioxmpp.dispatcher.SimplePresenceDispatcher`.
"""
def decorator(f):
if asyncio.iscoroutinefunction(f):
raise TypeError(
"presence_handler must not be a coroutine function"
)
aioxmpp.service.add_handler_spec(
f,
aioxmpp.service.HandlerSpec(
(_apply_presence_handler, (type_, from_)),
require_deps=(
SimplePresenceDispatcher,
)
)
)
return f
return decorator | Register the decorated function as presence stanza handler.
:param type_: Presence type to listen for
:type type_: :class:`~.PresenceType`
:param from_: Sender JIDs to listen for
:type from_: :class:`aioxmpp.JID` or :data:`None`
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:meth:`~.StanzaStream.register_presence_callback`
for more details on the `type_` and `from_` arguments
.. versionchanged:: 0.9
This is now based on
:class:`aioxmpp.dispatcher.SimplePresenceDispatcher`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L376-L413 |
horazont/aioxmpp | aioxmpp/dispatcher.py | is_message_handler | def is_message_handler(type_, from_, cb):
"""
Return true if `cb` has been decorated with :func:`message_handler` for the
given `type_` and `from_`.
"""
try:
handlers = aioxmpp.service.get_magic_attr(cb)
except AttributeError:
return False
return aioxmpp.service.HandlerSpec(
(_apply_message_handler, (type_, from_)),
require_deps=(
SimpleMessageDispatcher,
)
) in handlers | python | def is_message_handler(type_, from_, cb):
"""
Return true if `cb` has been decorated with :func:`message_handler` for the
given `type_` and `from_`.
"""
try:
handlers = aioxmpp.service.get_magic_attr(cb)
except AttributeError:
return False
return aioxmpp.service.HandlerSpec(
(_apply_message_handler, (type_, from_)),
require_deps=(
SimpleMessageDispatcher,
)
) in handlers | Return true if `cb` has been decorated with :func:`message_handler` for the
given `type_` and `from_`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L416-L432 |
horazont/aioxmpp | aioxmpp/dispatcher.py | is_presence_handler | def is_presence_handler(type_, from_, cb):
"""
Return true if `cb` has been decorated with :func:`presence_handler` for
the given `type_` and `from_`.
"""
try:
handlers = aioxmpp.service.get_magic_attr(cb)
except AttributeError:
return False
return aioxmpp.service.HandlerSpec(
(_apply_presence_handler, (type_, from_)),
require_deps=(
SimplePresenceDispatcher,
)
) in handlers | python | def is_presence_handler(type_, from_, cb):
"""
Return true if `cb` has been decorated with :func:`presence_handler` for
the given `type_` and `from_`.
"""
try:
handlers = aioxmpp.service.get_magic_attr(cb)
except AttributeError:
return False
return aioxmpp.service.HandlerSpec(
(_apply_presence_handler, (type_, from_)),
require_deps=(
SimplePresenceDispatcher,
)
) in handlers | Return true if `cb` has been decorated with :func:`presence_handler` for
the given `type_` and `from_`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L435-L451 |
horazont/aioxmpp | aioxmpp/dispatcher.py | SimpleStanzaDispatcher._feed | def _feed(self, stanza):
"""
Dispatch the given `stanza`.
:param stanza: Stanza to dispatch
:type stanza: :class:`~.StanzaBase`
:rtype: :class:`bool`
:return: true if the stanza was dispatched, false otherwise.
Dispatch the stanza to up to one handler registered on the dispatcher.
If no handler is found for the stanza, :data:`False` is returned.
Otherwise, :data:`True` is returned.
"""
from_ = stanza.from_
if from_ is None:
from_ = self.local_jid
keys = [
(stanza.type_, from_, False),
(stanza.type_, from_.bare(), True),
(None, from_, False),
(None, from_.bare(), True),
(stanza.type_, None, False),
(None, from_, False),
(None, None, False),
]
for key in keys:
try:
cb = self._map[key]
except KeyError:
continue
cb(stanza)
return | python | def _feed(self, stanza):
"""
Dispatch the given `stanza`.
:param stanza: Stanza to dispatch
:type stanza: :class:`~.StanzaBase`
:rtype: :class:`bool`
:return: true if the stanza was dispatched, false otherwise.
Dispatch the stanza to up to one handler registered on the dispatcher.
If no handler is found for the stanza, :data:`False` is returned.
Otherwise, :data:`True` is returned.
"""
from_ = stanza.from_
if from_ is None:
from_ = self.local_jid
keys = [
(stanza.type_, from_, False),
(stanza.type_, from_.bare(), True),
(None, from_, False),
(None, from_.bare(), True),
(stanza.type_, None, False),
(None, from_, False),
(None, None, False),
]
for key in keys:
try:
cb = self._map[key]
except KeyError:
continue
cb(stanza)
return | Dispatch the given `stanza`.
:param stanza: Stanza to dispatch
:type stanza: :class:`~.StanzaBase`
:rtype: :class:`bool`
:return: true if the stanza was dispatched, false otherwise.
Dispatch the stanza to up to one handler registered on the dispatcher.
If no handler is found for the stanza, :data:`False` is returned.
Otherwise, :data:`True` is returned. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L103-L136 |
horazont/aioxmpp | aioxmpp/dispatcher.py | SimpleStanzaDispatcher.register_callback | def register_callback(self, type_, from_, cb, *,
wildcard_resource=True):
"""
Register a callback function.
:param type_: Stanza type to listen for, or :data:`None` for a
wildcard match.
:param from_: Sender to listen for, or :data:`None` for a full wildcard
match.
:type from_: :class:`aioxmpp.JID` or :data:`None`
:param cb: Callback function to register
:param wildcard_resource: Whether to wildcard the resourcepart of the
JID.
:type wildcard_resource: :class:`bool`
:raises ValueError: if another function is already registered for the
callback slot.
`cb` will be called whenever a stanza with the matching `type_` and
`from_` is processed. The following wildcarding rules apply:
1. If the :attr:`~aioxmpp.stanza.StanzaBase.from_` attribute of the
stanza has a resourcepart, the following lookup order for callbacks is used:
+---------------------------+----------------------------------+----------------------+
|``type_`` |``from_`` |``wildcard_resource`` |
+===========================+==================================+======================+
|:attr:`~.StanzaBase.type_` |:attr:`~.StanzaBase.from_` |*any* |
+---------------------------+----------------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |*bare* :attr:`~.StanzaBase.from_` |:data:`True` |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |:attr:`~.StanzaBase.from_` |*any* |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |*bare* :attr:`~.StanzaBase.from_` |:data:`True` |
+---------------------------+----------------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |:data:`None` |*any* |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |:data:`None` |*any* |
+---------------------------+----------------------------------+----------------------+
2. If the :attr:`~aioxmpp.stanza.StanzaBase.from_` attribute of the
stanza does *not* have a resourcepart, the following lookup order
for callbacks is used:
+---------------------------+---------------------------+----------------------+
|``type_`` |``from_`` |``wildcard_resource`` |
+===========================+===========================+======================+
|:attr:`~.StanzaBase.type_` |:attr:`~.StanzaBase.from_` |:data:`False` |
+---------------------------+---------------------------+----------------------+
|:data:`None` |:attr:`~.StanzaBase.from_` |:data:`False` |
+---------------------------+---------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |:data:`None` |*any* |
+---------------------------+---------------------------+----------------------+
|:data:`None` |:data:`None` |*any* |
+---------------------------+---------------------------+----------------------+
Only the first callback which matches is called. `wildcard_resource` is
ignored if `from_` is a full JID or :data:`None`.
.. note::
When the server sends a stanza without from attribute, it is
replaced with the bare :attr:`local_jid`, as per :rfc:`6120`.
""" # NOQA: E501
if from_ is None or not from_.is_bare:
wildcard_resource = False
key = (type_, from_, wildcard_resource)
if key in self._map:
raise ValueError(
"only one listener allowed per matcher"
)
self._map[type_, from_, wildcard_resource] = cb | python | def register_callback(self, type_, from_, cb, *,
wildcard_resource=True):
"""
Register a callback function.
:param type_: Stanza type to listen for, or :data:`None` for a
wildcard match.
:param from_: Sender to listen for, or :data:`None` for a full wildcard
match.
:type from_: :class:`aioxmpp.JID` or :data:`None`
:param cb: Callback function to register
:param wildcard_resource: Whether to wildcard the resourcepart of the
JID.
:type wildcard_resource: :class:`bool`
:raises ValueError: if another function is already registered for the
callback slot.
`cb` will be called whenever a stanza with the matching `type_` and
`from_` is processed. The following wildcarding rules apply:
1. If the :attr:`~aioxmpp.stanza.StanzaBase.from_` attribute of the
stanza has a resourcepart, the following lookup order for callbacks is used:
+---------------------------+----------------------------------+----------------------+
|``type_`` |``from_`` |``wildcard_resource`` |
+===========================+==================================+======================+
|:attr:`~.StanzaBase.type_` |:attr:`~.StanzaBase.from_` |*any* |
+---------------------------+----------------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |*bare* :attr:`~.StanzaBase.from_` |:data:`True` |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |:attr:`~.StanzaBase.from_` |*any* |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |*bare* :attr:`~.StanzaBase.from_` |:data:`True` |
+---------------------------+----------------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |:data:`None` |*any* |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |:data:`None` |*any* |
+---------------------------+----------------------------------+----------------------+
2. If the :attr:`~aioxmpp.stanza.StanzaBase.from_` attribute of the
stanza does *not* have a resourcepart, the following lookup order
for callbacks is used:
+---------------------------+---------------------------+----------------------+
|``type_`` |``from_`` |``wildcard_resource`` |
+===========================+===========================+======================+
|:attr:`~.StanzaBase.type_` |:attr:`~.StanzaBase.from_` |:data:`False` |
+---------------------------+---------------------------+----------------------+
|:data:`None` |:attr:`~.StanzaBase.from_` |:data:`False` |
+---------------------------+---------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |:data:`None` |*any* |
+---------------------------+---------------------------+----------------------+
|:data:`None` |:data:`None` |*any* |
+---------------------------+---------------------------+----------------------+
Only the first callback which matches is called. `wildcard_resource` is
ignored if `from_` is a full JID or :data:`None`.
.. note::
When the server sends a stanza without from attribute, it is
replaced with the bare :attr:`local_jid`, as per :rfc:`6120`.
""" # NOQA: E501
if from_ is None or not from_.is_bare:
wildcard_resource = False
key = (type_, from_, wildcard_resource)
if key in self._map:
raise ValueError(
"only one listener allowed per matcher"
)
self._map[type_, from_, wildcard_resource] = cb | Register a callback function.
:param type_: Stanza type to listen for, or :data:`None` for a
wildcard match.
:param from_: Sender to listen for, or :data:`None` for a full wildcard
match.
:type from_: :class:`aioxmpp.JID` or :data:`None`
:param cb: Callback function to register
:param wildcard_resource: Whether to wildcard the resourcepart of the
JID.
:type wildcard_resource: :class:`bool`
:raises ValueError: if another function is already registered for the
callback slot.
`cb` will be called whenever a stanza with the matching `type_` and
`from_` is processed. The following wildcarding rules apply:
1. If the :attr:`~aioxmpp.stanza.StanzaBase.from_` attribute of the
stanza has a resourcepart, the following lookup order for callbacks is used:
+---------------------------+----------------------------------+----------------------+
|``type_`` |``from_`` |``wildcard_resource`` |
+===========================+==================================+======================+
|:attr:`~.StanzaBase.type_` |:attr:`~.StanzaBase.from_` |*any* |
+---------------------------+----------------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |*bare* :attr:`~.StanzaBase.from_` |:data:`True` |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |:attr:`~.StanzaBase.from_` |*any* |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |*bare* :attr:`~.StanzaBase.from_` |:data:`True` |
+---------------------------+----------------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |:data:`None` |*any* |
+---------------------------+----------------------------------+----------------------+
|:data:`None` |:data:`None` |*any* |
+---------------------------+----------------------------------+----------------------+
2. If the :attr:`~aioxmpp.stanza.StanzaBase.from_` attribute of the
stanza does *not* have a resourcepart, the following lookup order
for callbacks is used:
+---------------------------+---------------------------+----------------------+
|``type_`` |``from_`` |``wildcard_resource`` |
+===========================+===========================+======================+
|:attr:`~.StanzaBase.type_` |:attr:`~.StanzaBase.from_` |:data:`False` |
+---------------------------+---------------------------+----------------------+
|:data:`None` |:attr:`~.StanzaBase.from_` |:data:`False` |
+---------------------------+---------------------------+----------------------+
|:attr:`~.StanzaBase.type_` |:data:`None` |*any* |
+---------------------------+---------------------------+----------------------+
|:data:`None` |:data:`None` |*any* |
+---------------------------+---------------------------+----------------------+
Only the first callback which matches is called. `wildcard_resource` is
ignored if `from_` is a full JID or :data:`None`.
.. note::
When the server sends a stanza without from attribute, it is
replaced with the bare :attr:`local_jid`, as per :rfc:`6120`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L138-L211 |
horazont/aioxmpp | aioxmpp/dispatcher.py | SimpleStanzaDispatcher.unregister_callback | def unregister_callback(self, type_, from_, *,
wildcard_resource=True):
"""
Unregister a callback function.
:param type_: Stanza type to listen for, or :data:`None` for a
wildcard match.
:param from_: Sender to listen for, or :data:`None` for a full wildcard
match.
:type from_: :class:`aioxmpp.JID` or :data:`None`
:param wildcard_resource: Whether to wildcard the resourcepart of the
JID.
:type wildcard_resource: :class:`bool`
The callback must be disconnected with the same arguments as were used
to connect it.
"""
if from_ is None or not from_.is_bare:
wildcard_resource = False
self._map.pop((type_, from_, wildcard_resource)) | python | def unregister_callback(self, type_, from_, *,
wildcard_resource=True):
"""
Unregister a callback function.
:param type_: Stanza type to listen for, or :data:`None` for a
wildcard match.
:param from_: Sender to listen for, or :data:`None` for a full wildcard
match.
:type from_: :class:`aioxmpp.JID` or :data:`None`
:param wildcard_resource: Whether to wildcard the resourcepart of the
JID.
:type wildcard_resource: :class:`bool`
The callback must be disconnected with the same arguments as were used
to connect it.
"""
if from_ is None or not from_.is_bare:
wildcard_resource = False
self._map.pop((type_, from_, wildcard_resource)) | Unregister a callback function.
:param type_: Stanza type to listen for, or :data:`None` for a
wildcard match.
:param from_: Sender to listen for, or :data:`None` for a full wildcard
match.
:type from_: :class:`aioxmpp.JID` or :data:`None`
:param wildcard_resource: Whether to wildcard the resourcepart of the
JID.
:type wildcard_resource: :class:`bool`
The callback must be disconnected with the same arguments as were used
to connect it. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L213-L233 |
horazont/aioxmpp | aioxmpp/dispatcher.py | SimpleStanzaDispatcher.handler_context | def handler_context(self, type_, from_, cb, *, wildcard_resource=True):
"""
Context manager which temporarily registers a callback.
The arguments are the same as for :meth:`register_callback`.
When the context is entered, the callback `cb` is registered. When the
context is exited, no matter if an exception is raised or not, the
callback is unregistered.
"""
self.register_callback(
type_, from_, cb,
wildcard_resource=wildcard_resource
)
try:
yield
finally:
self.unregister_callback(
type_, from_,
wildcard_resource=wildcard_resource
) | python | def handler_context(self, type_, from_, cb, *, wildcard_resource=True):
"""
Context manager which temporarily registers a callback.
The arguments are the same as for :meth:`register_callback`.
When the context is entered, the callback `cb` is registered. When the
context is exited, no matter if an exception is raised or not, the
callback is unregistered.
"""
self.register_callback(
type_, from_, cb,
wildcard_resource=wildcard_resource
)
try:
yield
finally:
self.unregister_callback(
type_, from_,
wildcard_resource=wildcard_resource
) | Context manager which temporarily registers a callback.
The arguments are the same as for :meth:`register_callback`.
When the context is entered, the callback `cb` is registered. When the
context is exited, no matter if an exception is raised or not, the
callback is unregistered. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/dispatcher.py#L236-L256 |
horazont/aioxmpp | aioxmpp/forms/fields.py | BoundField.clone_for | def clone_for(self, other_instance, memo=None):
"""
Clone this bound field for another instance, possibly during a
:func:`~copy.deepcopy` operation.
:param other_instance: Another form instance to which the newly created
bound field shall be bound.
:type other_instance: :class:`object`
:param memo: Optional deepcopy-memo (see :mod:`copy` for details)
If this is called during a deepcopy operation, passing the `memo` helps
preserving and preventing loops. This method is essentially a
deepcopy-operation, with a modification of the :attr:`instance`
afterwards.
"""
if memo is None:
result = copy.deepcopy(self)
else:
result = copy.deepcopy(self, memo)
result.instance = other_instance
return result | python | def clone_for(self, other_instance, memo=None):
"""
Clone this bound field for another instance, possibly during a
:func:`~copy.deepcopy` operation.
:param other_instance: Another form instance to which the newly created
bound field shall be bound.
:type other_instance: :class:`object`
:param memo: Optional deepcopy-memo (see :mod:`copy` for details)
If this is called during a deepcopy operation, passing the `memo` helps
preserving and preventing loops. This method is essentially a
deepcopy-operation, with a modification of the :attr:`instance`
afterwards.
"""
if memo is None:
result = copy.deepcopy(self)
else:
result = copy.deepcopy(self, memo)
result.instance = other_instance
return result | Clone this bound field for another instance, possibly during a
:func:`~copy.deepcopy` operation.
:param other_instance: Another form instance to which the newly created
bound field shall be bound.
:type other_instance: :class:`object`
:param memo: Optional deepcopy-memo (see :mod:`copy` for details)
If this is called during a deepcopy operation, passing the `memo` helps
preserving and preventing loops. This method is essentially a
deepcopy-operation, with a modification of the :attr:`instance`
afterwards. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/fields.py#L184-L205 |
horazont/aioxmpp | aioxmpp/forms/fields.py | BoundField.load | def load(self, field_xso):
"""
Load the field information from a data field.
:param field_xso: XSO describing the field.
:type field_xso: :class:`~.Field`
This loads the current value, description, label and possibly options
from the `field_xso`, shadowing the information from the declaration of
the field on the class.
This method is must be overriden and is thus marked abstract. However,
when called from a subclass, it loads the :attr:`desc`, :attr:`label`
and :attr:`required` from the given `field_xso`. Subclasses are
supposed to implement a mechansim to load options and/or values from
the `field_xso` and then call this implementation through
:func:`super`.
"""
if field_xso.desc:
self._desc = field_xso.desc
if field_xso.label:
self._label = field_xso.label
self._required = field_xso.required | python | def load(self, field_xso):
"""
Load the field information from a data field.
:param field_xso: XSO describing the field.
:type field_xso: :class:`~.Field`
This loads the current value, description, label and possibly options
from the `field_xso`, shadowing the information from the declaration of
the field on the class.
This method is must be overriden and is thus marked abstract. However,
when called from a subclass, it loads the :attr:`desc`, :attr:`label`
and :attr:`required` from the given `field_xso`. Subclasses are
supposed to implement a mechansim to load options and/or values from
the `field_xso` and then call this implementation through
:func:`super`.
"""
if field_xso.desc:
self._desc = field_xso.desc
if field_xso.label:
self._label = field_xso.label
self._required = field_xso.required | Load the field information from a data field.
:param field_xso: XSO describing the field.
:type field_xso: :class:`~.Field`
This loads the current value, description, label and possibly options
from the `field_xso`, shadowing the information from the declaration of
the field on the class.
This method is must be overriden and is thus marked abstract. However,
when called from a subclass, it loads the :attr:`desc`, :attr:`label`
and :attr:`required` from the given `field_xso`. Subclasses are
supposed to implement a mechansim to load options and/or values from
the `field_xso` and then call this implementation through
:func:`super`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/fields.py#L208-L232 |
horazont/aioxmpp | aioxmpp/forms/fields.py | BoundField.render | def render(self, *, use_local_metadata=True):
"""
Return a :class:`~.Field` containing the values and metadata set in the
field.
:param use_local_metadata: if true, the description, label and required
metadata can be sourced from the field
descriptor associated with this bound field.
:type use_local_metadata: :class:`bool`
:return: A new :class:`~.Field` instance.
The returned object uses the values accessible through this object;
that means, any values set for e.g. :attr:`desc` take precedence over
the values declared at the class level. If `use_local_metadata` is
false, values declared at the class level are not used if no local
values are declared. This is useful when generating a reply to a form
received by a peer, as it avoids sending a modified form.
This method is must be overriden and is thus marked abstract. However,
when called from a subclass, it creates the :class:`~.Field` instance
and initialises its :attr:`~.Field.var`, :attr:`~.Field.type_`,
:attr:`~.Field.desc`, :attr:`~.Field.required` and
:attr:`~.Field.label` attributes and returns the result. Subclasses are
supposed to override this method, call the base implementation through
:func:`super` to obtain the :class:`~.Field` instance and then fill in
the values and/or options.
"""
result = forms_xso.Field(
var=self.field.var,
type_=self.field.FIELD_TYPE,
)
if use_local_metadata:
result.desc = self.desc
result.label = self.label
result.required = self.required
else:
try:
result.desc = self._desc
except AttributeError:
pass
try:
result.label = self._label
except AttributeError:
pass
try:
result.required = self._required
except AttributeError:
pass
return result | python | def render(self, *, use_local_metadata=True):
"""
Return a :class:`~.Field` containing the values and metadata set in the
field.
:param use_local_metadata: if true, the description, label and required
metadata can be sourced from the field
descriptor associated with this bound field.
:type use_local_metadata: :class:`bool`
:return: A new :class:`~.Field` instance.
The returned object uses the values accessible through this object;
that means, any values set for e.g. :attr:`desc` take precedence over
the values declared at the class level. If `use_local_metadata` is
false, values declared at the class level are not used if no local
values are declared. This is useful when generating a reply to a form
received by a peer, as it avoids sending a modified form.
This method is must be overriden and is thus marked abstract. However,
when called from a subclass, it creates the :class:`~.Field` instance
and initialises its :attr:`~.Field.var`, :attr:`~.Field.type_`,
:attr:`~.Field.desc`, :attr:`~.Field.required` and
:attr:`~.Field.label` attributes and returns the result. Subclasses are
supposed to override this method, call the base implementation through
:func:`super` to obtain the :class:`~.Field` instance and then fill in
the values and/or options.
"""
result = forms_xso.Field(
var=self.field.var,
type_=self.field.FIELD_TYPE,
)
if use_local_metadata:
result.desc = self.desc
result.label = self.label
result.required = self.required
else:
try:
result.desc = self._desc
except AttributeError:
pass
try:
result.label = self._label
except AttributeError:
pass
try:
result.required = self._required
except AttributeError:
pass
return result | Return a :class:`~.Field` containing the values and metadata set in the
field.
:param use_local_metadata: if true, the description, label and required
metadata can be sourced from the field
descriptor associated with this bound field.
:type use_local_metadata: :class:`bool`
:return: A new :class:`~.Field` instance.
The returned object uses the values accessible through this object;
that means, any values set for e.g. :attr:`desc` take precedence over
the values declared at the class level. If `use_local_metadata` is
false, values declared at the class level are not used if no local
values are declared. This is useful when generating a reply to a form
received by a peer, as it avoids sending a modified form.
This method is must be overriden and is thus marked abstract. However,
when called from a subclass, it creates the :class:`~.Field` instance
and initialises its :attr:`~.Field.var`, :attr:`~.Field.type_`,
:attr:`~.Field.desc`, :attr:`~.Field.required` and
:attr:`~.Field.label` attributes and returns the result. Subclasses are
supposed to override this method, call the base implementation through
:func:`super` to obtain the :class:`~.Field` instance and then fill in
the values and/or options. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/fields.py#L235-L288 |
horazont/aioxmpp | aioxmpp/forms/fields.py | BoundMultiValueField.value | def value(self):
"""
A tuple of values. This attribute can be set with any iterable; the
iterable is then evaluated into a tuple and stored at the bound field.
Whenever values are written to this attribute, they are passed through
the :meth:`~.AbstractCDataType.coerce` method of the
:attr:`~.AbstractField.type_` of the field. To revert the
:attr:`value` to its default, use the ``del`` operator.
"""
try:
return self._value
except AttributeError:
self.value = self._field.default()
return self._value | python | def value(self):
"""
A tuple of values. This attribute can be set with any iterable; the
iterable is then evaluated into a tuple and stored at the bound field.
Whenever values are written to this attribute, they are passed through
the :meth:`~.AbstractCDataType.coerce` method of the
:attr:`~.AbstractField.type_` of the field. To revert the
:attr:`value` to its default, use the ``del`` operator.
"""
try:
return self._value
except AttributeError:
self.value = self._field.default()
return self._value | A tuple of values. This attribute can be set with any iterable; the
iterable is then evaluated into a tuple and stored at the bound field.
Whenever values are written to this attribute, they are passed through
the :meth:`~.AbstractCDataType.coerce` method of the
:attr:`~.AbstractField.type_` of the field. To revert the
:attr:`value` to its default, use the ``del`` operator. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/fields.py#L384-L398 |
horazont/aioxmpp | aioxmpp/forms/fields.py | BoundSelectField.value | def value(self):
"""
The current value of the field. If no value is set when this attribute
is accessed for reading, the :meth:`default` of the field is invoked
and the result is set and returned as value.
Only values contained in the :attr:`~.BoundOptionsField.options` can be
set, other values are rejected with a :class:`ValueError`. To revert
the value to the default value specified in the descriptor, use the
``del`` operator.
"""
try:
return self._value
except AttributeError:
self._value = self.field.default()
return self._value | python | def value(self):
"""
The current value of the field. If no value is set when this attribute
is accessed for reading, the :meth:`default` of the field is invoked
and the result is set and returned as value.
Only values contained in the :attr:`~.BoundOptionsField.options` can be
set, other values are rejected with a :class:`ValueError`. To revert
the value to the default value specified in the descriptor, use the
``del`` operator.
"""
try:
return self._value
except AttributeError:
self._value = self.field.default()
return self._value | The current value of the field. If no value is set when this attribute
is accessed for reading, the :meth:`default` of the field is invoked
and the result is set and returned as value.
Only values contained in the :attr:`~.BoundOptionsField.options` can be
set, other values are rejected with a :class:`ValueError`. To revert
the value to the default value specified in the descriptor, use the
``del`` operator. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/fields.py#L548-L563 |
horazont/aioxmpp | aioxmpp/forms/fields.py | AbstractField.make_bound | def make_bound(self, for_instance):
"""
Create a new :ref:`bound field class <api-aioxmpp.forms-bound-fields>`
or return an existing one for the given form object.
:param for_instance: The form instance to which the bound field should
be bound.
If no bound field can be found on the given `for_instance` for this
field, a new one is created using :meth:`create_bound`, stored at the
instance and returned. Otherwise, the existing instance is returned.
.. seealso::
:meth:`create_bound`
creates a new bound field for the given form instance (without
storing it anywhere).
"""
try:
return for_instance._descriptor_data[self]
except KeyError:
bound = self.create_bound(for_instance)
for_instance._descriptor_data[self] = bound
return bound | python | def make_bound(self, for_instance):
"""
Create a new :ref:`bound field class <api-aioxmpp.forms-bound-fields>`
or return an existing one for the given form object.
:param for_instance: The form instance to which the bound field should
be bound.
If no bound field can be found on the given `for_instance` for this
field, a new one is created using :meth:`create_bound`, stored at the
instance and returned. Otherwise, the existing instance is returned.
.. seealso::
:meth:`create_bound`
creates a new bound field for the given form instance (without
storing it anywhere).
"""
try:
return for_instance._descriptor_data[self]
except KeyError:
bound = self.create_bound(for_instance)
for_instance._descriptor_data[self] = bound
return bound | Create a new :ref:`bound field class <api-aioxmpp.forms-bound-fields>`
or return an existing one for the given form object.
:param for_instance: The form instance to which the bound field should
be bound.
If no bound field can be found on the given `for_instance` for this
field, a new one is created using :meth:`create_bound`, stored at the
instance and returned. Otherwise, the existing instance is returned.
.. seealso::
:meth:`create_bound`
creates a new bound field for the given form instance (without
storing it anywhere). | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/fields.py#L851-L875 |
horazont/aioxmpp | aioxmpp/xml.py | make_parser | def make_parser():
"""
Create a parser which is suitably configured for parsing an XMPP XML
stream. It comes equipped with :class:`XMPPLexicalHandler`.
"""
p = xml.sax.make_parser()
p.setFeature(xml.sax.handler.feature_namespaces, True)
p.setFeature(xml.sax.handler.feature_external_ges, False)
p.setProperty(xml.sax.handler.property_lexical_handler,
XMPPLexicalHandler)
return p | python | def make_parser():
"""
Create a parser which is suitably configured for parsing an XMPP XML
stream. It comes equipped with :class:`XMPPLexicalHandler`.
"""
p = xml.sax.make_parser()
p.setFeature(xml.sax.handler.feature_namespaces, True)
p.setFeature(xml.sax.handler.feature_external_ges, False)
p.setProperty(xml.sax.handler.property_lexical_handler,
XMPPLexicalHandler)
return p | Create a parser which is suitably configured for parsing an XMPP XML
stream. It comes equipped with :class:`XMPPLexicalHandler`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L1085-L1095 |
horazont/aioxmpp | aioxmpp/xml.py | serialize_single_xso | def serialize_single_xso(x):
"""
Serialize a single XSO `x` to a string. This is potentially very slow and
should only be used for debugging purposes. It is generally more efficient
to use a :class:`XMPPXMLGenerator` to stream elements.
"""
buf = io.BytesIO()
gen = XMPPXMLGenerator(buf,
short_empty_elements=True,
sorted_attributes=True)
x.unparse_to_sax(gen)
return buf.getvalue().decode("utf8") | python | def serialize_single_xso(x):
"""
Serialize a single XSO `x` to a string. This is potentially very slow and
should only be used for debugging purposes. It is generally more efficient
to use a :class:`XMPPXMLGenerator` to stream elements.
"""
buf = io.BytesIO()
gen = XMPPXMLGenerator(buf,
short_empty_elements=True,
sorted_attributes=True)
x.unparse_to_sax(gen)
return buf.getvalue().decode("utf8") | Serialize a single XSO `x` to a string. This is potentially very slow and
should only be used for debugging purposes. It is generally more efficient
to use a :class:`XMPPXMLGenerator` to stream elements. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L1098-L1109 |
horazont/aioxmpp | aioxmpp/xml.py | write_single_xso | def write_single_xso(x, dest):
"""
Write a single XSO `x` to a binary file-like object `dest`.
"""
gen = XMPPXMLGenerator(dest,
short_empty_elements=True,
sorted_attributes=True)
x.unparse_to_sax(gen) | python | def write_single_xso(x, dest):
"""
Write a single XSO `x` to a binary file-like object `dest`.
"""
gen = XMPPXMLGenerator(dest,
short_empty_elements=True,
sorted_attributes=True)
x.unparse_to_sax(gen) | Write a single XSO `x` to a binary file-like object `dest`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L1112-L1119 |
horazont/aioxmpp | aioxmpp/xml.py | read_xso | def read_xso(src, xsomap):
"""
Read a single XSO from a binary file-like input `src` containing an XML
document.
`xsomap` must be a mapping which maps :class:`~.XSO` subclasses
to callables. These will be registered at a newly created
:class:`.xso.XSOParser` instance which will be used to parse the document
in `src`.
The `xsomap` is thus used to determine the class parsing the root element
of the XML document. This can be used to support multiple versions.
"""
xso_parser = xso.XSOParser()
for class_, cb in xsomap.items():
xso_parser.add_class(class_, cb)
driver = xso.SAXDriver(xso_parser)
parser = xml.sax.make_parser()
parser.setFeature(
xml.sax.handler.feature_namespaces,
True)
parser.setFeature(
xml.sax.handler.feature_external_ges,
False)
parser.setContentHandler(driver)
parser.parse(src) | python | def read_xso(src, xsomap):
"""
Read a single XSO from a binary file-like input `src` containing an XML
document.
`xsomap` must be a mapping which maps :class:`~.XSO` subclasses
to callables. These will be registered at a newly created
:class:`.xso.XSOParser` instance which will be used to parse the document
in `src`.
The `xsomap` is thus used to determine the class parsing the root element
of the XML document. This can be used to support multiple versions.
"""
xso_parser = xso.XSOParser()
for class_, cb in xsomap.items():
xso_parser.add_class(class_, cb)
driver = xso.SAXDriver(xso_parser)
parser = xml.sax.make_parser()
parser.setFeature(
xml.sax.handler.feature_namespaces,
True)
parser.setFeature(
xml.sax.handler.feature_external_ges,
False)
parser.setContentHandler(driver)
parser.parse(src) | Read a single XSO from a binary file-like input `src` containing an XML
document.
`xsomap` must be a mapping which maps :class:`~.XSO` subclasses
to callables. These will be registered at a newly created
:class:`.xso.XSOParser` instance which will be used to parse the document
in `src`.
The `xsomap` is thus used to determine the class parsing the root element
of the XML document. This can be used to support multiple versions. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L1122-L1152 |
horazont/aioxmpp | aioxmpp/xml.py | read_single_xso | def read_single_xso(src, type_):
"""
Read a single :class:`~.XSO` of the given `type_` from the binary file-like
input `src` and return the instance.
"""
result = None
def cb(instance):
nonlocal result
result = instance
read_xso(src, {type_: cb})
return result | python | def read_single_xso(src, type_):
"""
Read a single :class:`~.XSO` of the given `type_` from the binary file-like
input `src` and return the instance.
"""
result = None
def cb(instance):
nonlocal result
result = instance
read_xso(src, {type_: cb})
return result | Read a single :class:`~.XSO` of the given `type_` from the binary file-like
input `src` and return the instance. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L1155-L1169 |
horazont/aioxmpp | aioxmpp/xml.py | XMPPXMLGenerator.startPrefixMapping | def startPrefixMapping(self, prefix, uri, *, auto=False):
"""
Start a prefix mapping which maps the given `prefix` to the given
`uri`.
Note that prefix mappings are handled transactional. All announcements
of prefix mappings are collected until the next call to
:meth:`startElementNS`. At that point, the mappings are collected and
start to override the previously declared mappings until the
corresponding :meth:`endElementNS` call.
Also note that calling :meth:`startPrefixMapping` is not mandatory; you
can use any namespace you like at any time. If you use a namespace
whose URI has not been associated with a prefix yet, a free prefix will
automatically be chosen. To avoid unneccessary performance penalties,
do not use prefixes of the form ``"ns{:d}".format(n)``, for any
non-negative number of `n`.
It is however required to call :meth:`endPrefixMapping` after a
:meth:`endElementNS` call for all namespaces which have been announced
directly before the :meth:`startElementNS` call (except for those which
have been chosen automatically). Not doing so will result in a
:class:`RuntimeError` at the next :meth:`startElementNS` or
:meth:`endElementNS` call.
During a transaction, it is not allowed to declare the same prefix
multiple times.
"""
if (prefix is not None and
(prefix == "xml" or
prefix == "xmlns" or
not xmlValidateNameValue_str(prefix) or
":" in prefix)):
raise ValueError("not a valid prefix: {!r}".format(prefix))
if prefix in self._ns_prefixes_floating_in:
raise ValueError("prefix already declared for next element")
if auto:
self._ns_auto_prefixes_floating_in.add(prefix)
self._ns_prefixes_floating_in[prefix] = uri
self._ns_decls_floating_in[uri] = prefix | python | def startPrefixMapping(self, prefix, uri, *, auto=False):
"""
Start a prefix mapping which maps the given `prefix` to the given
`uri`.
Note that prefix mappings are handled transactional. All announcements
of prefix mappings are collected until the next call to
:meth:`startElementNS`. At that point, the mappings are collected and
start to override the previously declared mappings until the
corresponding :meth:`endElementNS` call.
Also note that calling :meth:`startPrefixMapping` is not mandatory; you
can use any namespace you like at any time. If you use a namespace
whose URI has not been associated with a prefix yet, a free prefix will
automatically be chosen. To avoid unneccessary performance penalties,
do not use prefixes of the form ``"ns{:d}".format(n)``, for any
non-negative number of `n`.
It is however required to call :meth:`endPrefixMapping` after a
:meth:`endElementNS` call for all namespaces which have been announced
directly before the :meth:`startElementNS` call (except for those which
have been chosen automatically). Not doing so will result in a
:class:`RuntimeError` at the next :meth:`startElementNS` or
:meth:`endElementNS` call.
During a transaction, it is not allowed to declare the same prefix
multiple times.
"""
if (prefix is not None and
(prefix == "xml" or
prefix == "xmlns" or
not xmlValidateNameValue_str(prefix) or
":" in prefix)):
raise ValueError("not a valid prefix: {!r}".format(prefix))
if prefix in self._ns_prefixes_floating_in:
raise ValueError("prefix already declared for next element")
if auto:
self._ns_auto_prefixes_floating_in.add(prefix)
self._ns_prefixes_floating_in[prefix] = uri
self._ns_decls_floating_in[uri] = prefix | Start a prefix mapping which maps the given `prefix` to the given
`uri`.
Note that prefix mappings are handled transactional. All announcements
of prefix mappings are collected until the next call to
:meth:`startElementNS`. At that point, the mappings are collected and
start to override the previously declared mappings until the
corresponding :meth:`endElementNS` call.
Also note that calling :meth:`startPrefixMapping` is not mandatory; you
can use any namespace you like at any time. If you use a namespace
whose URI has not been associated with a prefix yet, a free prefix will
automatically be chosen. To avoid unneccessary performance penalties,
do not use prefixes of the form ``"ns{:d}".format(n)``, for any
non-negative number of `n`.
It is however required to call :meth:`endPrefixMapping` after a
:meth:`endElementNS` call for all namespaces which have been announced
directly before the :meth:`startElementNS` call (except for those which
have been chosen automatically). Not doing so will result in a
:class:`RuntimeError` at the next :meth:`startElementNS` or
:meth:`endElementNS` call.
During a transaction, it is not allowed to declare the same prefix
multiple times. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L348-L388 |
horazont/aioxmpp | aioxmpp/xml.py | XMPPXMLGenerator.startElementNS | def startElementNS(self, name, qname, attributes=None):
"""
Start a sub-element. `name` must be a tuple of ``(namespace_uri,
localname)`` and `qname` is ignored. `attributes` must be a dictionary
mapping attribute tag tuples (``(namespace_uri, attribute_name)``) to
string values. To use unnamespaced attributes, `namespace_uri` can be
false (e.g. :data:`None` or the empty string).
To use unnamespaced elements, `namespace_uri` in `name` must be false
**and** no namespace without prefix must be currently active. If a
namespace without prefix is active and `namespace_uri` in `name` is
false, :class:`ValueError` is raised.
Attribute values are of course automatically escaped.
"""
self._finish_pending_start_element()
old_counter = self._ns_counter
qname = self._qname(name)
if attributes:
attrib = [
(self._qname(attrname, attr=True), value)
for attrname, value in attributes.items()
]
for attrqname, _ in attrib:
if attrqname == "xmlns":
raise ValueError("xmlns not allowed as attribute name")
else:
attrib = []
pending_prefixes = self._pin_floating_ns_decls(old_counter)
self._write(b"<")
self._write(qname.encode("utf-8"))
if None in pending_prefixes:
uri = pending_prefixes.pop(None)
self._write(b" xmlns=")
self._write(xml.sax.saxutils.quoteattr(uri).encode("utf-8"))
for prefix, uri in sorted(pending_prefixes.items()):
self._write(b" xmlns")
if prefix:
self._write(b":")
self._write(prefix.encode("utf-8"))
self._write(b"=")
self._write(
xml.sax.saxutils.quoteattr(uri).encode("utf-8")
)
if self._sorted_attributes:
attrib.sort()
for attrname, value in attrib:
self._write(b" ")
self._write(attrname.encode("utf-8"))
self._write(b"=")
self._write(
xml.sax.saxutils.quoteattr(
value,
self._additional_escapes,
).encode("utf-8")
)
if self._short_empty_elements:
self._pending_start_element = name
else:
self._write(b">") | python | def startElementNS(self, name, qname, attributes=None):
"""
Start a sub-element. `name` must be a tuple of ``(namespace_uri,
localname)`` and `qname` is ignored. `attributes` must be a dictionary
mapping attribute tag tuples (``(namespace_uri, attribute_name)``) to
string values. To use unnamespaced attributes, `namespace_uri` can be
false (e.g. :data:`None` or the empty string).
To use unnamespaced elements, `namespace_uri` in `name` must be false
**and** no namespace without prefix must be currently active. If a
namespace without prefix is active and `namespace_uri` in `name` is
false, :class:`ValueError` is raised.
Attribute values are of course automatically escaped.
"""
self._finish_pending_start_element()
old_counter = self._ns_counter
qname = self._qname(name)
if attributes:
attrib = [
(self._qname(attrname, attr=True), value)
for attrname, value in attributes.items()
]
for attrqname, _ in attrib:
if attrqname == "xmlns":
raise ValueError("xmlns not allowed as attribute name")
else:
attrib = []
pending_prefixes = self._pin_floating_ns_decls(old_counter)
self._write(b"<")
self._write(qname.encode("utf-8"))
if None in pending_prefixes:
uri = pending_prefixes.pop(None)
self._write(b" xmlns=")
self._write(xml.sax.saxutils.quoteattr(uri).encode("utf-8"))
for prefix, uri in sorted(pending_prefixes.items()):
self._write(b" xmlns")
if prefix:
self._write(b":")
self._write(prefix.encode("utf-8"))
self._write(b"=")
self._write(
xml.sax.saxutils.quoteattr(uri).encode("utf-8")
)
if self._sorted_attributes:
attrib.sort()
for attrname, value in attrib:
self._write(b" ")
self._write(attrname.encode("utf-8"))
self._write(b"=")
self._write(
xml.sax.saxutils.quoteattr(
value,
self._additional_escapes,
).encode("utf-8")
)
if self._short_empty_elements:
self._pending_start_element = name
else:
self._write(b">") | Start a sub-element. `name` must be a tuple of ``(namespace_uri,
localname)`` and `qname` is ignored. `attributes` must be a dictionary
mapping attribute tag tuples (``(namespace_uri, attribute_name)``) to
string values. To use unnamespaced attributes, `namespace_uri` can be
false (e.g. :data:`None` or the empty string).
To use unnamespaced elements, `namespace_uri` in `name` must be false
**and** no namespace without prefix must be currently active. If a
namespace without prefix is active and `namespace_uri` in `name` is
false, :class:`ValueError` is raised.
Attribute values are of course automatically escaped. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L390-L457 |
horazont/aioxmpp | aioxmpp/xml.py | XMPPXMLGenerator.endElementNS | def endElementNS(self, name, qname):
"""
End a previously started element. `name` must be a ``(namespace_uri,
localname)`` tuple and `qname` is ignored.
"""
if self._ns_prefixes_floating_out:
raise RuntimeError("namespace prefix has not been closed")
if self._pending_start_element == name:
self._pending_start_element = False
self._write(b"/>")
else:
self._write(b"</")
self._write(self._qname(name).encode("utf-8"))
self._write(b">")
self._curr_ns_map, self._ns_prefixes_floating_out, self._ns_counter = \
self._ns_map_stack.pop() | python | def endElementNS(self, name, qname):
"""
End a previously started element. `name` must be a ``(namespace_uri,
localname)`` tuple and `qname` is ignored.
"""
if self._ns_prefixes_floating_out:
raise RuntimeError("namespace prefix has not been closed")
if self._pending_start_element == name:
self._pending_start_element = False
self._write(b"/>")
else:
self._write(b"</")
self._write(self._qname(name).encode("utf-8"))
self._write(b">")
self._curr_ns_map, self._ns_prefixes_floating_out, self._ns_counter = \
self._ns_map_stack.pop() | End a previously started element. `name` must be a ``(namespace_uri,
localname)`` tuple and `qname` is ignored. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L459-L476 |
horazont/aioxmpp | aioxmpp/xml.py | XMPPXMLGenerator.characters | def characters(self, chars):
"""
Put character data in the currently open element. Special characters
(such as ``<``, ``>`` and ``&``) are escaped.
If `chars` contains any ASCII control character, :class:`ValueError` is
raised.
"""
self._finish_pending_start_element()
if not is_valid_cdata_str(chars):
raise ValueError("control characters are not allowed in "
"well-formed XML")
self._write(xml.sax.saxutils.escape(
chars,
self._additional_escapes,
).encode("utf-8")) | python | def characters(self, chars):
"""
Put character data in the currently open element. Special characters
(such as ``<``, ``>`` and ``&``) are escaped.
If `chars` contains any ASCII control character, :class:`ValueError` is
raised.
"""
self._finish_pending_start_element()
if not is_valid_cdata_str(chars):
raise ValueError("control characters are not allowed in "
"well-formed XML")
self._write(xml.sax.saxutils.escape(
chars,
self._additional_escapes,
).encode("utf-8")) | Put character data in the currently open element. Special characters
(such as ``<``, ``>`` and ``&``) are escaped.
If `chars` contains any ASCII control character, :class:`ValueError` is
raised. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L493-L508 |
horazont/aioxmpp | aioxmpp/xml.py | XMPPXMLGenerator._save_state | def _save_state(self):
"""
Helper context manager for :meth:`buffer` which saves the whole state.
This is broken out in a separate method for readability and tested
indirectly by testing :meth:`buffer`.
"""
ns_prefixes_floating_in = copy.copy(self._ns_prefixes_floating_in)
ns_prefixes_floating_out = copy.copy(self._ns_prefixes_floating_out)
ns_decls_floating_in = copy.copy(self._ns_decls_floating_in)
curr_ns_map = copy.copy(self._curr_ns_map)
ns_map_stack = copy.copy(self._ns_map_stack)
pending_start_element = self._pending_start_element
ns_counter = self._ns_counter
# XXX: I have been unable to find a test justifying copying this :/
# for completeness, I’m still doing it
ns_auto_prefixes_floating_in = \
copy.copy(self._ns_auto_prefixes_floating_in)
try:
yield
except: # NOQA: E722
self._ns_prefixes_floating_in = ns_prefixes_floating_in
self._ns_prefixes_floating_out = ns_prefixes_floating_out
self._ns_decls_floating_in = ns_decls_floating_in
self._pending_start_element = pending_start_element
self._curr_ns_map = curr_ns_map
self._ns_map_stack = ns_map_stack
self._ns_counter = ns_counter
self._ns_auto_prefixes_floating_in = ns_auto_prefixes_floating_in
raise | python | def _save_state(self):
"""
Helper context manager for :meth:`buffer` which saves the whole state.
This is broken out in a separate method for readability and tested
indirectly by testing :meth:`buffer`.
"""
ns_prefixes_floating_in = copy.copy(self._ns_prefixes_floating_in)
ns_prefixes_floating_out = copy.copy(self._ns_prefixes_floating_out)
ns_decls_floating_in = copy.copy(self._ns_decls_floating_in)
curr_ns_map = copy.copy(self._curr_ns_map)
ns_map_stack = copy.copy(self._ns_map_stack)
pending_start_element = self._pending_start_element
ns_counter = self._ns_counter
# XXX: I have been unable to find a test justifying copying this :/
# for completeness, I’m still doing it
ns_auto_prefixes_floating_in = \
copy.copy(self._ns_auto_prefixes_floating_in)
try:
yield
except: # NOQA: E722
self._ns_prefixes_floating_in = ns_prefixes_floating_in
self._ns_prefixes_floating_out = ns_prefixes_floating_out
self._ns_decls_floating_in = ns_decls_floating_in
self._pending_start_element = pending_start_element
self._curr_ns_map = curr_ns_map
self._ns_map_stack = ns_map_stack
self._ns_counter = ns_counter
self._ns_auto_prefixes_floating_in = ns_auto_prefixes_floating_in
raise | Helper context manager for :meth:`buffer` which saves the whole state.
This is broken out in a separate method for readability and tested
indirectly by testing :meth:`buffer`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L562-L591 |
horazont/aioxmpp | aioxmpp/xml.py | XMPPXMLGenerator.buffer | def buffer(self):
"""
Context manager to temporarily buffer the output.
:raise RuntimeError: If two :meth:`buffer` context managers are used
nestedly.
If the context manager is left without exception, the buffered output
is sent to the actual sink. Otherwise, it is discarded.
In addition to the output being buffered, buffer also captures the
entire state of the XML generator and restores it to the previous state
if the context manager is left with an exception.
This can be used to fail-safely attempt to serialise a subtree and
return to a well-defined state if serialisation fails.
:meth:`flush` is not called automatically.
If :meth:`flush` is called while a :meth:`buffer` context manager is
active, no actual flushing happens (but unfinished opening tags are
closed as usual, see the `short_empty_arguments` parameter).
"""
if self._buf_in_use:
raise RuntimeError("nested use of buffer() is not supported")
self._buf_in_use = True
old_write = self._write
old_flush = self._flush
if self._buf is None:
self._buf = io.BytesIO()
else:
try:
self._buf.seek(0)
self._buf.truncate()
except BufferError:
# we need a fresh buffer for this, the other is still in use.
self._buf = io.BytesIO()
self._write = self._buf.write
self._flush = None
try:
with self._save_state():
yield
old_write(self._buf.getbuffer())
if old_flush:
old_flush()
finally:
self._buf_in_use = False
self._write = old_write
self._flush = old_flush | python | def buffer(self):
"""
Context manager to temporarily buffer the output.
:raise RuntimeError: If two :meth:`buffer` context managers are used
nestedly.
If the context manager is left without exception, the buffered output
is sent to the actual sink. Otherwise, it is discarded.
In addition to the output being buffered, buffer also captures the
entire state of the XML generator and restores it to the previous state
if the context manager is left with an exception.
This can be used to fail-safely attempt to serialise a subtree and
return to a well-defined state if serialisation fails.
:meth:`flush` is not called automatically.
If :meth:`flush` is called while a :meth:`buffer` context manager is
active, no actual flushing happens (but unfinished opening tags are
closed as usual, see the `short_empty_arguments` parameter).
"""
if self._buf_in_use:
raise RuntimeError("nested use of buffer() is not supported")
self._buf_in_use = True
old_write = self._write
old_flush = self._flush
if self._buf is None:
self._buf = io.BytesIO()
else:
try:
self._buf.seek(0)
self._buf.truncate()
except BufferError:
# we need a fresh buffer for this, the other is still in use.
self._buf = io.BytesIO()
self._write = self._buf.write
self._flush = None
try:
with self._save_state():
yield
old_write(self._buf.getbuffer())
if old_flush:
old_flush()
finally:
self._buf_in_use = False
self._write = old_write
self._flush = old_flush | Context manager to temporarily buffer the output.
:raise RuntimeError: If two :meth:`buffer` context managers are used
nestedly.
If the context manager is left without exception, the buffered output
is sent to the actual sink. Otherwise, it is discarded.
In addition to the output being buffered, buffer also captures the
entire state of the XML generator and restores it to the previous state
if the context manager is left with an exception.
This can be used to fail-safely attempt to serialise a subtree and
return to a well-defined state if serialisation fails.
:meth:`flush` is not called automatically.
If :meth:`flush` is called while a :meth:`buffer` context manager is
active, no actual flushing happens (but unfinished opening tags are
closed as usual, see the `short_empty_arguments` parameter). | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L594-L644 |
horazont/aioxmpp | aioxmpp/xml.py | XMLStreamWriter.start | def start(self):
"""
Send the stream header as described above.
"""
attrs = {
(None, "to"): str(self._to),
(None, "version"): ".".join(map(str, self._version))
}
if self._from:
attrs[None, "from"] = str(self._from)
self._writer.startDocument()
for prefix, uri in self._nsmap_to_use.items():
self._writer.startPrefixMapping(prefix, uri)
self._writer.startElementNS(
(namespaces.xmlstream, "stream"),
None,
attrs)
self._writer.flush() | python | def start(self):
"""
Send the stream header as described above.
"""
attrs = {
(None, "to"): str(self._to),
(None, "version"): ".".join(map(str, self._version))
}
if self._from:
attrs[None, "from"] = str(self._from)
self._writer.startDocument()
for prefix, uri in self._nsmap_to_use.items():
self._writer.startPrefixMapping(prefix, uri)
self._writer.startElementNS(
(namespaces.xmlstream, "stream"),
None,
attrs)
self._writer.flush() | Send the stream header as described above. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L718-L736 |
horazont/aioxmpp | aioxmpp/xml.py | XMLStreamWriter.send | def send(self, xso):
"""
Send a single XML stream object.
:param xso: Object to serialise and send.
:type xso: :class:`aioxmpp.xso.XSO`
:raises Exception: from any serialisation errors, usually
:class:`ValueError`.
Serialise the `xso` and send it over the stream. If any serialisation
error occurs, no data is sent over the stream and the exception is
re-raised; the :meth:`send` method thus provides strong exception
safety.
.. warning::
The behaviour of :meth:`send` after :meth:`abort` or :meth:`close`
and before :meth:`start` is undefined.
"""
with self._writer.buffer():
xso.unparse_to_sax(self._writer) | python | def send(self, xso):
"""
Send a single XML stream object.
:param xso: Object to serialise and send.
:type xso: :class:`aioxmpp.xso.XSO`
:raises Exception: from any serialisation errors, usually
:class:`ValueError`.
Serialise the `xso` and send it over the stream. If any serialisation
error occurs, no data is sent over the stream and the exception is
re-raised; the :meth:`send` method thus provides strong exception
safety.
.. warning::
The behaviour of :meth:`send` after :meth:`abort` or :meth:`close`
and before :meth:`start` is undefined.
"""
with self._writer.buffer():
xso.unparse_to_sax(self._writer) | Send a single XML stream object.
:param xso: Object to serialise and send.
:type xso: :class:`aioxmpp.xso.XSO`
:raises Exception: from any serialisation errors, usually
:class:`ValueError`.
Serialise the `xso` and send it over the stream. If any serialisation
error occurs, no data is sent over the stream and the exception is
re-raised; the :meth:`send` method thus provides strong exception
safety.
.. warning::
The behaviour of :meth:`send` after :meth:`abort` or :meth:`close`
and before :meth:`start` is undefined. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L738-L759 |
horazont/aioxmpp | aioxmpp/xml.py | XMLStreamWriter.abort | def abort(self):
"""
Abort the stream.
The stream is flushed and the internal data structures are cleaned up.
No stream footer is sent. The stream is :attr:`closed` afterwards.
If the stream is already :attr:`closed`, this method does nothing.
"""
if self._closed:
return
self._closed = True
self._writer.flush()
del self._writer | python | def abort(self):
"""
Abort the stream.
The stream is flushed and the internal data structures are cleaned up.
No stream footer is sent. The stream is :attr:`closed` afterwards.
If the stream is already :attr:`closed`, this method does nothing.
"""
if self._closed:
return
self._closed = True
self._writer.flush()
del self._writer | Abort the stream.
The stream is flushed and the internal data structures are cleaned up.
No stream footer is sent. The stream is :attr:`closed` afterwards.
If the stream is already :attr:`closed`, this method does nothing. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L761-L774 |
horazont/aioxmpp | aioxmpp/xml.py | XMLStreamWriter.close | def close(self):
"""
Close the stream.
The stream footer is sent and the internal structures are cleaned up.
If the stream is already :attr:`closed`, this method does nothing.
"""
if self._closed:
return
self._closed = True
self._writer.endElementNS((namespaces.xmlstream, "stream"), None)
for prefix in self._nsmap_to_use:
self._writer.endPrefixMapping(prefix)
self._writer.endDocument()
del self._writer | python | def close(self):
"""
Close the stream.
The stream footer is sent and the internal structures are cleaned up.
If the stream is already :attr:`closed`, this method does nothing.
"""
if self._closed:
return
self._closed = True
self._writer.endElementNS((namespaces.xmlstream, "stream"), None)
for prefix in self._nsmap_to_use:
self._writer.endPrefixMapping(prefix)
self._writer.endDocument()
del self._writer | Close the stream.
The stream footer is sent and the internal structures are cleaned up.
If the stream is already :attr:`closed`, this method does nothing. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L776-L791 |
horazont/aioxmpp | aioxmpp/rsm/xso.py | ResultSetMetadata.fetch_page | def fetch_page(cls, index, max_=None):
"""
Return a query set which requests a specific page.
:param index: Index of the first element of the page to fetch.
:type index: :class:`int`
:param max_: Maximum number of elements to fetch
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request a page starting with the
element indexed by `index`.
.. note::
This way of retrieving items may be approximate. See :xep:`59` and
the embedding protocol for which RSM is used for specifics.
"""
result = cls()
result.index = index
result.max_ = max_
return result | python | def fetch_page(cls, index, max_=None):
"""
Return a query set which requests a specific page.
:param index: Index of the first element of the page to fetch.
:type index: :class:`int`
:param max_: Maximum number of elements to fetch
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request a page starting with the
element indexed by `index`.
.. note::
This way of retrieving items may be approximate. See :xep:`59` and
the embedding protocol for which RSM is used for specifics.
"""
result = cls()
result.index = index
result.max_ = max_
return result | Return a query set which requests a specific page.
:param index: Index of the first element of the page to fetch.
:type index: :class:`int`
:param max_: Maximum number of elements to fetch
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request a page starting with the
element indexed by `index`.
.. note::
This way of retrieving items may be approximate. See :xep:`59` and
the embedding protocol for which RSM is used for specifics. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/rsm/xso.py#L193-L214 |
horazont/aioxmpp | aioxmpp/rsm/xso.py | ResultSetMetadata.limit | def limit(self, max_):
"""
Limit the result set to a given number of items.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request at most `max_` items.
This method can be called on the class and on objects. When called on
objects, it returns a copy of the object with :attr:`max_` set
accordingly. When called on the class, it creates a fresh object with
:attr:`max_` set accordingly.
"""
if isinstance(self, type):
result = self()
else:
result = copy.deepcopy(self)
result.max_ = max_
return result | python | def limit(self, max_):
"""
Limit the result set to a given number of items.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request at most `max_` items.
This method can be called on the class and on objects. When called on
objects, it returns a copy of the object with :attr:`max_` set
accordingly. When called on the class, it creates a fresh object with
:attr:`max_` set accordingly.
"""
if isinstance(self, type):
result = self()
else:
result = copy.deepcopy(self)
result.max_ = max_
return result | Limit the result set to a given number of items.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request at most `max_` items.
This method can be called on the class and on objects. When called on
objects, it returns a copy of the object with :attr:`max_` set
accordingly. When called on the class, it creates a fresh object with
:attr:`max_` set accordingly. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/rsm/xso.py#L217-L237 |
horazont/aioxmpp | aioxmpp/rsm/xso.py | ResultSetMetadata.next_page | def next_page(self, max_=None):
"""
Return a query set which requests the page after this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the next page.
Must be called on a result set which has :attr:`last` set.
"""
result = type(self)()
result.after = After(self.last.value)
result.max_ = max_
return result | python | def next_page(self, max_=None):
"""
Return a query set which requests the page after this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the next page.
Must be called on a result set which has :attr:`last` set.
"""
result = type(self)()
result.after = After(self.last.value)
result.max_ = max_
return result | Return a query set which requests the page after this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the next page.
Must be called on a result set which has :attr:`last` set. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/rsm/xso.py#L239-L254 |
horazont/aioxmpp | aioxmpp/rsm/xso.py | ResultSetMetadata.previous_page | def previous_page(self, max_=None):
"""
Return a query set which requests the page before this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the previous page.
Must be called on a result set which has :attr:`first` set.
"""
result = type(self)()
result.before = Before(self.first.value)
result.max_ = max_
return result | python | def previous_page(self, max_=None):
"""
Return a query set which requests the page before this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the previous page.
Must be called on a result set which has :attr:`first` set.
"""
result = type(self)()
result.before = Before(self.first.value)
result.max_ = max_
return result | Return a query set which requests the page before this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the previous page.
Must be called on a result set which has :attr:`first` set. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/rsm/xso.py#L256-L271 |
horazont/aioxmpp | aioxmpp/rsm/xso.py | ResultSetMetadata.last_page | def last_page(self_or_cls, max_=None):
"""
Return a query set which requests the last page.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the last page.
"""
result = self_or_cls()
result.before = Before()
result.max_ = max_
return result | python | def last_page(self_or_cls, max_=None):
"""
Return a query set which requests the last page.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the last page.
"""
result = self_or_cls()
result.before = Before()
result.max_ = max_
return result | Return a query set which requests the last page.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the last page. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/rsm/xso.py#L274-L286 |
horazont/aioxmpp | aioxmpp/forms/xso.py | FieldType.allow_upcast | def allow_upcast(self, to):
"""
Return true if the field type may be upcast to the other field type
`to`.
This relation specifies when it is safe to transfer data from this
field type to the given other field type `to`.
This is the case if any of the following holds true:
* `to` is equal to this type
* this type is :attr:`TEXT_SINGLE` and `to` is :attr:`TEXT_PRIVATE`
"""
if self == to:
return True
if self == FieldType.TEXT_SINGLE and to == FieldType.TEXT_PRIVATE:
return True
return False | python | def allow_upcast(self, to):
"""
Return true if the field type may be upcast to the other field type
`to`.
This relation specifies when it is safe to transfer data from this
field type to the given other field type `to`.
This is the case if any of the following holds true:
* `to` is equal to this type
* this type is :attr:`TEXT_SINGLE` and `to` is :attr:`TEXT_PRIVATE`
"""
if self == to:
return True
if self == FieldType.TEXT_SINGLE and to == FieldType.TEXT_PRIVATE:
return True
return False | Return true if the field type may be upcast to the other field type
`to`.
This relation specifies when it is safe to transfer data from this
field type to the given other field type `to`.
This is the case if any of the following holds true:
* `to` is equal to this type
* this type is :attr:`TEXT_SINGLE` and `to` is :attr:`TEXT_PRIVATE` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/xso.py#L252-L270 |
horazont/aioxmpp | aioxmpp/forms/xso.py | Data.get_form_type | def get_form_type(self):
"""
Extract the ``FORM_TYPE`` from the fields.
:return: ``FORM_TYPE`` value or :data:`None`
:rtype: :class:`str` or :data:`None`
Return :data:`None` if no well-formed ``FORM_TYPE`` field is found in
the list of fields.
.. versionadded:: 0.8
"""
for field in self.fields:
if field.var == "FORM_TYPE" and field.type_ == FieldType.HIDDEN:
if len(field.values) != 1:
return None
return field.values[0] | python | def get_form_type(self):
"""
Extract the ``FORM_TYPE`` from the fields.
:return: ``FORM_TYPE`` value or :data:`None`
:rtype: :class:`str` or :data:`None`
Return :data:`None` if no well-formed ``FORM_TYPE`` field is found in
the list of fields.
.. versionadded:: 0.8
"""
for field in self.fields:
if field.var == "FORM_TYPE" and field.type_ == FieldType.HIDDEN:
if len(field.values) != 1:
return None
return field.values[0] | Extract the ``FORM_TYPE`` from the fields.
:return: ``FORM_TYPE`` value or :data:`None`
:rtype: :class:`str` or :data:`None`
Return :data:`None` if no well-formed ``FORM_TYPE`` field is found in
the list of fields.
.. versionadded:: 0.8 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/forms/xso.py#L623-L640 |
horazont/aioxmpp | aioxmpp/ibr/service.py | get_registration_fields | def get_registration_fields(xmlstream,
timeout=60,
):
"""
A query is sent to the server to obtain the fields that need to be
filled to register with the server.
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aioxmpp.protocol.XMLStream`
:param timeout: Maximum time in seconds to wait for an IQ response, or
:data:`None` to disable the timeout.
:type timeout: :class:`~numbers.Real` or :data:`None`
:return: :attr:`list`
"""
iq = aioxmpp.IQ(
to=aioxmpp.JID.fromstr(xmlstream._to),
type_=aioxmpp.IQType.GET,
payload=xso.Query()
)
iq.autoset_id()
reply = yield from aioxmpp.protocol.send_and_wait_for(xmlstream,
[iq],
[aioxmpp.IQ],
timeout=timeout)
return reply.payload | python | def get_registration_fields(xmlstream,
timeout=60,
):
"""
A query is sent to the server to obtain the fields that need to be
filled to register with the server.
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aioxmpp.protocol.XMLStream`
:param timeout: Maximum time in seconds to wait for an IQ response, or
:data:`None` to disable the timeout.
:type timeout: :class:`~numbers.Real` or :data:`None`
:return: :attr:`list`
"""
iq = aioxmpp.IQ(
to=aioxmpp.JID.fromstr(xmlstream._to),
type_=aioxmpp.IQType.GET,
payload=xso.Query()
)
iq.autoset_id()
reply = yield from aioxmpp.protocol.send_and_wait_for(xmlstream,
[iq],
[aioxmpp.IQ],
timeout=timeout)
return reply.payload | A query is sent to the server to obtain the fields that need to be
filled to register with the server.
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aioxmpp.protocol.XMLStream`
:param timeout: Maximum time in seconds to wait for an IQ response, or
:data:`None` to disable the timeout.
:type timeout: :class:`~numbers.Real` or :data:`None`
:return: :attr:`list` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibr/service.py#L34-L63 |
horazont/aioxmpp | aioxmpp/ibr/service.py | register | def register(xmlstream,
query_xso,
timeout=60,
):
"""
Create a new account on the server.
:param query_xso: XSO with the information needed for the registration.
:type query_xso: :class:`~aioxmpp.ibr.Query`
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aioxmpp.protocol.XMLStream`
:param timeout: Maximum time in seconds to wait for an IQ response, or
:data:`None` to disable the timeout.
:type timeout: :class:`~numbers.Real` or :data:`None`
"""
iq = aioxmpp.IQ(
to=aioxmpp.JID.fromstr(xmlstream._to),
type_=aioxmpp.IQType.SET,
payload=query_xso
)
iq.autoset_id()
yield from aioxmpp.protocol.send_and_wait_for(xmlstream,
[iq],
[aioxmpp.IQ],
timeout=timeout) | python | def register(xmlstream,
query_xso,
timeout=60,
):
"""
Create a new account on the server.
:param query_xso: XSO with the information needed for the registration.
:type query_xso: :class:`~aioxmpp.ibr.Query`
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aioxmpp.protocol.XMLStream`
:param timeout: Maximum time in seconds to wait for an IQ response, or
:data:`None` to disable the timeout.
:type timeout: :class:`~numbers.Real` or :data:`None`
"""
iq = aioxmpp.IQ(
to=aioxmpp.JID.fromstr(xmlstream._to),
type_=aioxmpp.IQType.SET,
payload=query_xso
)
iq.autoset_id()
yield from aioxmpp.protocol.send_and_wait_for(xmlstream,
[iq],
[aioxmpp.IQ],
timeout=timeout) | Create a new account on the server.
:param query_xso: XSO with the information needed for the registration.
:type query_xso: :class:`~aioxmpp.ibr.Query`
:param xmlstream: Specifies the stream connected to the server where
the account will be created.
:type xmlstream: :class:`aioxmpp.protocol.XMLStream`
:param timeout: Maximum time in seconds to wait for an IQ response, or
:data:`None` to disable the timeout.
:type timeout: :class:`~numbers.Real` or :data:`None` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibr/service.py#L67-L95 |
horazont/aioxmpp | aioxmpp/ibr/service.py | get_used_fields | def get_used_fields(payload):
"""
Get a list containing the names of the fields that are used in the
xso.Query.
:param payload: Query object o be
:type payload: :class:`~aioxmpp.ibr.Query`
:return: :attr:`list`
"""
return [
tag
for tag, descriptor in payload.CHILD_MAP.items()
if descriptor.__get__(payload, type(payload)) is not None
] | python | def get_used_fields(payload):
"""
Get a list containing the names of the fields that are used in the
xso.Query.
:param payload: Query object o be
:type payload: :class:`~aioxmpp.ibr.Query`
:return: :attr:`list`
"""
return [
tag
for tag, descriptor in payload.CHILD_MAP.items()
if descriptor.__get__(payload, type(payload)) is not None
] | Get a list containing the names of the fields that are used in the
xso.Query.
:param payload: Query object o be
:type payload: :class:`~aioxmpp.ibr.Query`
:return: :attr:`list` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibr/service.py#L98-L111 |
horazont/aioxmpp | aioxmpp/ibr/service.py | RegistrationService.get_client_info | def get_client_info(self):
"""
A query is sent to the server to obtain the client's data stored at the
server.
:return: :class:`~aioxmpp.ibr.Query`
"""
iq = aioxmpp.IQ(
to=self.client.local_jid.bare().replace(localpart=None),
type_=aioxmpp.IQType.GET,
payload=xso.Query()
)
reply = (yield from self.client.send(iq))
return reply | python | def get_client_info(self):
"""
A query is sent to the server to obtain the client's data stored at the
server.
:return: :class:`~aioxmpp.ibr.Query`
"""
iq = aioxmpp.IQ(
to=self.client.local_jid.bare().replace(localpart=None),
type_=aioxmpp.IQType.GET,
payload=xso.Query()
)
reply = (yield from self.client.send(iq))
return reply | A query is sent to the server to obtain the client's data stored at the
server.
:return: :class:`~aioxmpp.ibr.Query` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibr/service.py#L132-L146 |
horazont/aioxmpp | aioxmpp/ibr/service.py | RegistrationService.change_pass | def change_pass(self,
new_pass):
"""
Change the client password for 'new_pass'.
:param new_pass: New password of the client.
:type new_pass: :class:`str`
:param old_pass: Old password of the client.
:type old_pass: :class:`str`
"""
iq = aioxmpp.IQ(
to=self.client.local_jid.bare().replace(localpart=None),
type_=aioxmpp.IQType.SET,
payload=xso.Query(self.client.local_jid.localpart, new_pass)
)
yield from self.client.send(iq) | python | def change_pass(self,
new_pass):
"""
Change the client password for 'new_pass'.
:param new_pass: New password of the client.
:type new_pass: :class:`str`
:param old_pass: Old password of the client.
:type old_pass: :class:`str`
"""
iq = aioxmpp.IQ(
to=self.client.local_jid.bare().replace(localpart=None),
type_=aioxmpp.IQType.SET,
payload=xso.Query(self.client.local_jid.localpart, new_pass)
)
yield from self.client.send(iq) | Change the client password for 'new_pass'.
:param new_pass: New password of the client.
:type new_pass: :class:`str`
:param old_pass: Old password of the client.
:type old_pass: :class:`str` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibr/service.py#L149-L167 |
horazont/aioxmpp | aioxmpp/ibr/service.py | RegistrationService.cancel_registration | def cancel_registration(self):
"""
Cancels the currents client's account with the server.
Even if the cancelation is succesful, this method will raise an
exception due to he account no longer exists for the server, so the
client will fail.
To continue with the execution, this method should be surrounded by a
try/except statement.
"""
iq = aioxmpp.IQ(
to=self.client.local_jid.bare().replace(localpart=None),
type_=aioxmpp.IQType.SET,
payload=xso.Query()
)
iq.payload.remove = True
yield from self.client.send(iq) | python | def cancel_registration(self):
"""
Cancels the currents client's account with the server.
Even if the cancelation is succesful, this method will raise an
exception due to he account no longer exists for the server, so the
client will fail.
To continue with the execution, this method should be surrounded by a
try/except statement.
"""
iq = aioxmpp.IQ(
to=self.client.local_jid.bare().replace(localpart=None),
type_=aioxmpp.IQType.SET,
payload=xso.Query()
)
iq.payload.remove = True
yield from self.client.send(iq) | Cancels the currents client's account with the server.
Even if the cancelation is succesful, this method will raise an
exception due to he account no longer exists for the server, so the
client will fail.
To continue with the execution, this method should be surrounded by a
try/except statement. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibr/service.py#L170-L187 |
horazont/aioxmpp | aioxmpp/node.py | discover_connectors | def discover_connectors(
domain: str,
loop=None,
logger=logger):
"""
Discover all connection options for a domain, in descending order of
preference.
This coroutine returns options discovered from SRV records, or if none are
found, the generic option using the domain name and the default XMPP client
port.
Each option is represented by a triple ``(host, port, connector)``.
`connector` is a :class:`aioxmpp.connector.BaseConnector` instance which is
suitable to connect to the given host and port.
`logger` is the logger used by the function.
The following sources are supported:
* :rfc:`6120` SRV records. One option is returned per SRV record.
If one of the SRV records points to the root name (``.``),
:class:`ValueError` is raised (the domain specifically said that XMPP is
not supported here).
* :xep:`368` SRV records. One option is returned per SRV record.
* :rfc:`6120` fallback process (only if no SRV records are found). One
option is returned for the host name with the default XMPP client port.
The options discovered from SRV records are mixed together, ordered by
priority and then within priorities are shuffled according to their weight.
Thus, if there are multiple records of equal priority, the result of the
function is not deterministic.
.. versionadded:: 0.6
"""
domain_encoded = domain.encode("idna") + b"."
starttls_srv_failed = False
tls_srv_failed = False
try:
starttls_srv_records = yield from network.lookup_srv(
domain_encoded,
"xmpp-client",
)
starttls_srv_disabled = False
except dns.resolver.NoNameservers as exc:
starttls_srv_records = []
starttls_srv_disabled = False
starttls_srv_failed = True
starttls_srv_exc = exc
logger.debug("xmpp-client SRV lookup for domain %s failed "
"(may not be fatal)",
domain_encoded,
exc_info=True)
except ValueError:
starttls_srv_records = []
starttls_srv_disabled = True
try:
tls_srv_records = yield from network.lookup_srv(
domain_encoded,
"xmpps-client",
)
tls_srv_disabled = False
except dns.resolver.NoNameservers:
tls_srv_records = []
tls_srv_disabled = False
tls_srv_failed = True
logger.debug("xmpps-client SRV lookup for domain %s failed "
"(may not be fatal)",
domain_encoded,
exc_info=True)
except ValueError:
tls_srv_records = []
tls_srv_disabled = True
if starttls_srv_failed and (tls_srv_failed or tls_srv_records is None):
# the failure is probably more useful as a diagnostic
# if we find a good reason to allow this scenario, we might change it
# later.
raise starttls_srv_exc
if starttls_srv_disabled and (tls_srv_disabled or tls_srv_records is None):
raise ValueError(
"XMPP not enabled on domain {!r}".format(domain),
)
if starttls_srv_records is None and tls_srv_records is None:
# no SRV records published, fall back
logger.debug(
"no SRV records found for %s, falling back",
domain,
)
return [
(domain, 5222, connector.STARTTLSConnector()),
]
starttls_srv_records = starttls_srv_records or []
tls_srv_records = tls_srv_records or []
srv_records = [
(prio, weight, (host.decode("ascii"), port,
connector.STARTTLSConnector()))
for prio, weight, (host, port) in starttls_srv_records
]
srv_records.extend(
(prio, weight, (host.decode("ascii"), port,
connector.XMPPOverTLSConnector()))
for prio, weight, (host, port) in tls_srv_records
)
options = list(
network.group_and_order_srv_records(srv_records)
)
logger.debug(
"options for %s: %r",
domain,
options,
)
return options | python | def discover_connectors(
domain: str,
loop=None,
logger=logger):
"""
Discover all connection options for a domain, in descending order of
preference.
This coroutine returns options discovered from SRV records, or if none are
found, the generic option using the domain name and the default XMPP client
port.
Each option is represented by a triple ``(host, port, connector)``.
`connector` is a :class:`aioxmpp.connector.BaseConnector` instance which is
suitable to connect to the given host and port.
`logger` is the logger used by the function.
The following sources are supported:
* :rfc:`6120` SRV records. One option is returned per SRV record.
If one of the SRV records points to the root name (``.``),
:class:`ValueError` is raised (the domain specifically said that XMPP is
not supported here).
* :xep:`368` SRV records. One option is returned per SRV record.
* :rfc:`6120` fallback process (only if no SRV records are found). One
option is returned for the host name with the default XMPP client port.
The options discovered from SRV records are mixed together, ordered by
priority and then within priorities are shuffled according to their weight.
Thus, if there are multiple records of equal priority, the result of the
function is not deterministic.
.. versionadded:: 0.6
"""
domain_encoded = domain.encode("idna") + b"."
starttls_srv_failed = False
tls_srv_failed = False
try:
starttls_srv_records = yield from network.lookup_srv(
domain_encoded,
"xmpp-client",
)
starttls_srv_disabled = False
except dns.resolver.NoNameservers as exc:
starttls_srv_records = []
starttls_srv_disabled = False
starttls_srv_failed = True
starttls_srv_exc = exc
logger.debug("xmpp-client SRV lookup for domain %s failed "
"(may not be fatal)",
domain_encoded,
exc_info=True)
except ValueError:
starttls_srv_records = []
starttls_srv_disabled = True
try:
tls_srv_records = yield from network.lookup_srv(
domain_encoded,
"xmpps-client",
)
tls_srv_disabled = False
except dns.resolver.NoNameservers:
tls_srv_records = []
tls_srv_disabled = False
tls_srv_failed = True
logger.debug("xmpps-client SRV lookup for domain %s failed "
"(may not be fatal)",
domain_encoded,
exc_info=True)
except ValueError:
tls_srv_records = []
tls_srv_disabled = True
if starttls_srv_failed and (tls_srv_failed or tls_srv_records is None):
# the failure is probably more useful as a diagnostic
# if we find a good reason to allow this scenario, we might change it
# later.
raise starttls_srv_exc
if starttls_srv_disabled and (tls_srv_disabled or tls_srv_records is None):
raise ValueError(
"XMPP not enabled on domain {!r}".format(domain),
)
if starttls_srv_records is None and tls_srv_records is None:
# no SRV records published, fall back
logger.debug(
"no SRV records found for %s, falling back",
domain,
)
return [
(domain, 5222, connector.STARTTLSConnector()),
]
starttls_srv_records = starttls_srv_records or []
tls_srv_records = tls_srv_records or []
srv_records = [
(prio, weight, (host.decode("ascii"), port,
connector.STARTTLSConnector()))
for prio, weight, (host, port) in starttls_srv_records
]
srv_records.extend(
(prio, weight, (host.decode("ascii"), port,
connector.XMPPOverTLSConnector()))
for prio, weight, (host, port) in tls_srv_records
)
options = list(
network.group_and_order_srv_records(srv_records)
)
logger.debug(
"options for %s: %r",
domain,
options,
)
return options | Discover all connection options for a domain, in descending order of
preference.
This coroutine returns options discovered from SRV records, or if none are
found, the generic option using the domain name and the default XMPP client
port.
Each option is represented by a triple ``(host, port, connector)``.
`connector` is a :class:`aioxmpp.connector.BaseConnector` instance which is
suitable to connect to the given host and port.
`logger` is the logger used by the function.
The following sources are supported:
* :rfc:`6120` SRV records. One option is returned per SRV record.
If one of the SRV records points to the root name (``.``),
:class:`ValueError` is raised (the domain specifically said that XMPP is
not supported here).
* :xep:`368` SRV records. One option is returned per SRV record.
* :rfc:`6120` fallback process (only if no SRV records are found). One
option is returned for the host name with the default XMPP client port.
The options discovered from SRV records are mixed together, ordered by
priority and then within priorities are shuffled according to their weight.
Thus, if there are multiple records of equal priority, the result of the
function is not deterministic.
.. versionadded:: 0.6 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/node.py#L105-L231 |