func_code_string
stringlengths
52
1.94M
func_documentation_string
stringlengths
1
47.2k
def algo_of_hash(h): 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 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`...
def select_common_hashes(self, other_entity): 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): rai...
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 o...
def first_signal(*signals): 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 excep...
def connect(self, f, mode=None): 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 :...
def fire(self, *args, **kwargs): 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...
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 th...
def future(self): 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.
def connect(self, coro): 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`. ...
def fire(self, *args, **kwargs): 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.
def register(self, func, order): 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`...
def filter(self, obj, *args, **kwargs): 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...
def unregister(self, token_to_remove): 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`.
def context_register(self, func, *args): 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 ...
def set_timeout(self, timeout): 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, ...
def _set_state(self, new_state, response=None): 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._...
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 transit...
def send_tracked(self, stanza, tracker): 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. ...
def attach_tracker(self, stanza, tracker=None, token=None): 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._trac...
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-gr...
def start(self): 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.
def _interpret_result(self, task): 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, ...
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.XMPPErro...
def reset(self): 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.
def compose_receipt(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("r...
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...
def attach_tracker(self, stanza, tracker=None): if stanza.xep0184_received is not None: raise ValueError( "requesting delivery receipts for delivery receipts is not " "allowed" ) if stanza.type_ == aioxmpp.MessageType.ERROR: ra...
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 ...
def get_private_xml(self, query_xso): 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 ...
def set_private_xml(self, xso): 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.
def gather_reraise_multi(*fut_or_coros, message="gather_reraise_multi"): 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 N...
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:`...
def to_nmtoken(rand_token): 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,...
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 inpu...
def localize(self, formatter, translator): 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`.
def _get_bookmarks(self): 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
def _set_bookmarks(self, bookmarks): storage = bookmark_xso.Storage() storage.bookmarks[:] = bookmarks yield from self._private_xml.set_private_xml(storage)
Set the bookmarks stored on the server.
def _diff_emit_update(self, new_bookmarks): self.logger.debug("diffing %s, %s", self._bookmark_cache, new_bookmarks) def subdivide(level, old, new): if len(old) == len(new) == 1: old_entry = old.pop() new_entry =...
Diff the bookmark cache and the new bookmark state, emit signals as needed and set the bookmark cache to the new data.
def get_bookmarks(self): 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
def set_bookmarks(self, bookmarks): 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 ...
def add_bookmark(self, new_bookmark, *, max_retries=3): with (yield from self._lock): bookmarks = yield from self._get_bookmarks() try: modified_bookmarks = list(bookmarks) if new_bookmark not in bookmarks: modified_bookmarks.a...
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 setti...
def discard_bookmark(self, bookmark_to_remove, *, max_retries=3): with (yield from self._lock): bookmarks = yield from self._get_bookmarks() occurences = bookmarks.count(bookmark_to_remove) try: if not occurences: return ...
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_retrie...
def update_bookmark(self, old, new, *, max_retries=3): def replace_bookmark(bookmarks, old, new): modified_bookmarks = list(bookmarks) try: i = bookmarks.index(old) modified_bookmarks[i] = new except ValueError: modifie...
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_remov...
def iter_identities(self, stanza=None): 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 :re...
def iter_features(self, stanza=None): 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 ...
def register_feature(self, var): 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.
def register_identity(self, category, type_, *, names={}): 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 t...
def unregister_identity(self, category, type_): 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` i...
def as_info_xso(self, stanza=None): result = disco_xso.InfoQuery() result.features.update(self.iter_features(stanza)) result.identities[:] = ( disco_xso.Identity( category=category, type_=type_, lang=lang, name=...
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:`~.d...
def clone(cls, other_node): 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._identiti...
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`. ...
def query_info(self, jid, *, node=None, require_fresh=False, timeout=None, no_cache=False): key = jid, node if not require_fresh: try: request = self._info_pending[key] except KeyError: pass ...
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 requi...
def query_items(self, jid, *, node=None, require_fresh=False, timeout=None): key = jid, node if not require_fresh: try: request = self._items_pending[key] except KeyError: pass else: try: ...
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:`...
def set_info_cache(self, jid, node, info): 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
def set_info_future(self, jid, node, fut): 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 bypasse...
def localize(self, formatter, translator, *args, **kwargs): if self.plural is not None: n, _ = formatter.get_field(self.number_index, args, kwargs) translated = translator.ngettext(self.singular, self.plural, ...
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 :at...
def update_from_xso_item(self, xso_item): 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.
def from_xso_item(cls, xso_item): 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.
def export_as_json(self): 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 ...
Return a :mod:`json`-compatible dictionary which contains the attributes of this :class:`Item` except its JID.
def update_from_json(self, data): 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`.
def export_as_json(self): 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.
def import_from_json(self, data): 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) ...
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 met...
def set_entry(self, jid, *, name=_Sentinel, add_to_groups=frozenset(), remove_from_groups=frozenset(), timeout=None): existing = self.items.get(jid, Item(jid)) post_groups = (existing.groups | add_to_groups) - remove_from_g...
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. ...
def remove_entry(self, jid, *, timeout=None): yield from self.client.send( stanza.IQ( structs.IQType.SET, payload=roster_xso.Query(items=[ roster_xso.Item( jid=jid, subscription="remove" ...
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 m...
def approve(self, peer_jid): 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 r...
def subscribe(self, peer_jid): 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 subsc...
def unsubscribe(self, peer_jid): self.client.enqueue( stanza.Presence(type_=structs.PresenceType.UNSUBSCRIBE, to=peer_jid) )
Unsubscribe from the presence of the given `peer_jid`.
def message_handler(type_, from_): 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_handl...
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 .. seeals...
def presence_handler(type_, from_): 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( ...
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 ...
def is_message_handler(type_, from_, cb): try: handlers = aioxmpp.service.get_magic_attr(cb) except AttributeError: return False return aioxmpp.service.HandlerSpec( (_apply_message_handler, (type_, from_)), require_deps=( SimpleMessageDispatcher, ) ...
Return true if `cb` has been decorated with :func:`message_handler` for the given `type_` and `from_`.
def is_presence_handler(type_, from_, cb): try: handlers = aioxmpp.service.get_magic_attr(cb) except AttributeError: return False return aioxmpp.service.HandlerSpec( (_apply_presence_handler, (type_, from_)), require_deps=( SimplePresenceDispatcher, )...
Return true if `cb` has been decorated with :func:`presence_handler` for the given `type_` and `from_`.
def _feed(self, stanza): 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), (st...
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 ...
def register_callback(self, type_, from_, cb, *, wildcard_resource=True): # 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( ...
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` :para...
def unregister_callback(self, type_, from_, *, wildcard_resource=True): 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` :pa...
def handler_context(self, type_, from_, cb, *, wildcard_resource=True): self.register_callback( type_, from_, cb, wildcard_resource=wildcard_resource ) try: yield finally: self.unregister_callback( type_, from_, ...
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.
def clone_for(self, other_instance, memo=None): 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...
def load(self, field_xso): 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...
def render(self, *, use_local_metadata=True): 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...
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...
def value(self): 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.t...
def value(self): 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...
def make_bound(self, for_instance): 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` f...
def make_parser(): 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`.
def serialize_single_xso(x): 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.
def write_single_xso(x, 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`.
def read_xso(src, xsomap): 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...
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 `...
def read_single_xso(src, type_): 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.
def startPrefixMapping(self, prefix, uri, *, auto=False): 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:...
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 ...
def startElementNS(self, name, qname, attributes=None): 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, val...
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. ...
def endElementNS(self, name, qname): 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._w...
End a previously started element. `name` must be a ``(namespace_uri, localname)`` tuple and `qname` is ignored.
def characters(self, chars): 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, s...
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.
def _save_state(self): 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_s...
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`.
def buffer(self): 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: t...
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. I...
def start(self): 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.item...
Send the stream header as described above.
def send(self, xso): 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...
def abort(self): 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.
def close(self): 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._wri...
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.
def fetch_page(cls, index, max_=None): 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` :retur...
def limit(self, max_): 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...
def next_page(self, max_=None): 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 whi...
def previous_page(self, max_=None): 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 se...
def last_page(self_or_cls, max_=None): 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.
def allow_upcast(self, to): 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 ...
def get_form_type(self): 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
def get_registration_fields(xmlstream, timeout=60, ): 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_...
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 ti...
def register(xmlstream, query_xso, timeout=60, ): 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, ...
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:`aiox...
def get_used_fields(payload): 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`
def get_client_info(self): 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`
def change_pass(self, new_pass): 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`
def cancel_registration(self): 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/...
def discover_connectors( domain: str, loop=None, logger=logger): 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-...
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, connec...