code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
key = category, type_ if key in self._identities: raise ValueError("identity already claimed: {!r}".format(key)) self._identities[key] = names self.on_info_changed()
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.
4.062025
6.06879
0.66933
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()
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.
3.240603
3.352312
0.966677
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
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
4.752714
3.203085
1.483793
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
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
5.870185
5.315712
1.104308
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
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.
2.436079
2.617579
0.930661
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
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.
3.016502
3.034957
0.993919
fut = asyncio.Future() fut.set_result(info) self.set_info_future(jid, node, fut)
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
4.020782
3.16535
1.270249
self._info_pending[jid, node] = fut
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
10.372621
21.760983
0.476661
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)
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`.
3.874549
2.827823
1.370152
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}
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.
3.446733
3.081201
1.118633
item = cls(xso_item.jid) item.update_from_xso_item(xso_item) return 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.
3.652806
2.488221
1.468039
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
def export_as_json(self)
Return a :mod:`json`-compatible dictionary which contains the attributes of this :class:`Item` except its JID.
3.404468
2.923482
1.164525
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", []))
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`.
3.351725
3.507341
0.955631
return { "items": { str(jid): item.export_as_json() for jid, item in self.items.items() }, "ver": self.version }
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.
4.308541
3.78075
1.1396
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)
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`).
3.015324
2.976963
1.012886
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 )
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.
4.198874
4.050883
1.036533
yield from self.client.send( stanza.IQ( structs.IQType.SET, payload=roster_xso.Query(items=[ roster_xso.Item( jid=jid, subscription="remove" ) ]) ), timeout=timeout )
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.
6.585177
6.007644
1.096133
self.client.enqueue( stanza.Presence(type_=structs.PresenceType.SUBSCRIBED, to=peer_jid) )
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.
9.146088
9.519903
0.960733
self.client.enqueue( stanza.Presence(type_=structs.PresenceType.SUBSCRIBE, to=peer_jid) )
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.
9.298411
9.223102
1.008165
self.client.enqueue( stanza.Presence(type_=structs.PresenceType.UNSUBSCRIBE, to=peer_jid) )
def unsubscribe(self, peer_jid)
Unsubscribe from the presence of the given `peer_jid`.
8.193046
7.167967
1.143008
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
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`.
7.53033
5.954721
1.264598
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
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`.
7.12269
5.497142
1.295708
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
def is_message_handler(type_, from_, cb)
Return true if `cb` has been decorated with :func:`message_handler` for the given `type_` and `from_`.
14.663423
13.10842
1.118626
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
def is_presence_handler(type_, from_, cb)
Return true if `cb` has been decorated with :func:`presence_handler` for the given `type_` and `from_`.
14.304971
13.349244
1.071594
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
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.
2.997534
2.996921
1.000205
# 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
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`.
4.850121
6.480252
0.748446
if from_ is None or not from_.is_bare: wildcard_resource = False self._map.pop((type_, from_, wildcard_resource))
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.
7.947275
7.916152
1.003932
self.register_callback( type_, from_, cb, wildcard_resource=wildcard_resource ) try: yield finally: self.unregister_callback( type_, from_, wildcard_resource=wildcard_resource )
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.
2.597376
2.82954
0.91795
if memo is None: result = copy.deepcopy(self) else: result = copy.deepcopy(self, memo) result.instance = other_instance return result
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.
2.876512
2.438766
1.179495
if field_xso.desc: self._desc = field_xso.desc if field_xso.label: self._label = field_xso.label self._required = field_xso.required
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`.
2.735868
2.354407
1.16202
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
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.
3.56122
2.941487
1.210687
try: return self._value except AttributeError: self.value = self._field.default() return self._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.
5.214844
5.306578
0.982713
try: return self._value except AttributeError: self._value = self.field.default() return self._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.
4.13061
4.296036
0.961493
try: return for_instance._descriptor_data[self] except KeyError: bound = self.create_bound(for_instance) for_instance._descriptor_data[self] = bound return 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).
3.340303
3.410995
0.979275
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
def make_parser()
Create a parser which is suitably configured for parsing an XMPP XML stream. It comes equipped with :class:`XMPPLexicalHandler`.
2.494433
1.860837
1.34049
buf = io.BytesIO() gen = XMPPXMLGenerator(buf, short_empty_elements=True, sorted_attributes=True) x.unparse_to_sax(gen) return buf.getvalue().decode("utf8")
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.
7.750794
5.127543
1.5116
gen = XMPPXMLGenerator(dest, short_empty_elements=True, sorted_attributes=True) x.unparse_to_sax(gen)
def write_single_xso(x, dest)
Write a single XSO `x` to a binary file-like object `dest`.
14.289309
13.990916
1.021328
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)
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.
2.570228
2.275804
1.129372
result = None def cb(instance): nonlocal result result = instance read_xso(src, {type_: cb}) return result
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.
6.604049
6.18834
1.067176
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
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.
5.389211
5.528241
0.974851
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">")
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.
2.546694
2.567398
0.991936
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()
def endElementNS(self, name, qname)
End a previously started element. `name` must be a ``(namespace_uri, localname)`` tuple and `qname` is ignored.
4.538274
4.492095
1.01028
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"))
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.
7.304284
6.908923
1.057225
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
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`.
2.642526
2.613112
1.011256
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
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).
2.80501
2.923142
0.959587
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()
def start(self)
Send the stream header as described above.
3.796231
3.631698
1.045305
with self._writer.buffer(): xso.unparse_to_sax(self._writer)
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.
18.440166
33.340378
0.553088
if self._closed: return self._closed = True self._writer.flush() del self._writer
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.
6.130665
5.060128
1.211563
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
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.
5.192466
4.793975
1.083123
result = cls() result.index = index result.max_ = max_ return result
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.
5.522719
6.392568
0.863928
if isinstance(self, type): result = self() else: result = copy.deepcopy(self) result.max_ = max_ return result
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.
5.044263
3.501683
1.440525
result = type(self)() result.after = After(self.last.value) result.max_ = max_ return result
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.
12.31687
9.34078
1.318613
result = type(self)() result.before = Before(self.first.value) result.max_ = max_ return result
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.
12.157486
9.969456
1.219473
result = self_or_cls() result.before = Before() result.max_ = max_ return result
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.
7.783093
9.291999
0.837612
if self == to: return True if self == FieldType.TEXT_SINGLE and to == FieldType.TEXT_PRIVATE: return True return False
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`
7.946979
4.439471
1.790074
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]
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
5.731696
4.49565
1.274943
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
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`
6.072553
6.561486
0.925484
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)
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`
5.05953
5.324112
0.950305
return [ tag for tag, descriptor in payload.CHILD_MAP.items() if descriptor.__get__(payload, type(payload)) is not None ]
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`
9.307459
12.561214
0.740968
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
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`
8.897915
8.828686
1.007841
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)
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`
7.304115
8.04259
0.908179
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)
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.
8.858444
9.220956
0.960686
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
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
2.807145
2.606574
1.076948
for host, port, conn in options: logger.debug( "domain %s: trying to connect to %r:%s using %r", jid.domain, host, port, conn ) try: transport, xmlstream, features = yield from conn.connect( loop, metadata, jid.domain, host, port, negotiation_timeout, base_logger=logger, ) except OSError as exc: logger.warning( "connection failed: %s", exc ) exceptions.append(exc) continue logger.debug( "domain %s: connection succeeded using %r", jid.domain, conn, ) if not metadata.sasl_providers: return transport, xmlstream, features try: features = yield from security_layer.negotiate_sasl( transport, xmlstream, metadata.sasl_providers, negotiation_timeout=None, jid=jid, features=features, ) except errors.SASLUnavailable as exc: protocol.send_stream_error_and_close( xmlstream, condition=errors.StreamErrorCondition.POLICY_VIOLATION, text=str(exc), ) exceptions.append(exc) continue except Exception as exc: protocol.send_stream_error_and_close( xmlstream, condition=errors.StreamErrorCondition.UNDEFINED_CONDITION, text=str(exc), ) raise return transport, xmlstream, features return None
def _try_options(options, exceptions, jid, metadata, negotiation_timeout, loop, logger)
Helper function for :func:`connect_xmlstream`.
3.047517
3.011376
1.012002
if self.running: raise RuntimeError("client already running") self._main_task = asyncio.ensure_future( self._main(), loop=self._loop ) self._main_task.add_done_callback(self._on_main_done)
def start(self)
Start the client. If it is already :attr:`running`, :class:`RuntimeError` is raised. While the client is running, it will try to keep an XMPP connection open to the server associated with :attr:`local_jid`.
3.441428
3.461939
0.994076
if not self.running: return self.logger.debug("stopping main task of %r", self, stack_info=True) self._main_task.cancel()
def stop(self)
Stop the client. This sends a signal to the clients main task which makes it terminate. It may take some cycles through the event loop to stop the client task. To check whether the task has actually stopped, query :attr:`running`.
6.360494
4.685756
1.35741
return UseConnected(self, presence=presence, **kwargs)
def connected(self, *, presence=structs.PresenceState(False), **kwargs)
Return a :class:`.node.UseConnected` context manager which does not modify the presence settings. The keyword arguments are passed to the :class:`.node.UseConnected` context manager constructor. .. versionadded:: 0.8
25.212551
8.95867
2.814319
if not self.established_event.is_set(): raise ConnectionError("stream is not ready") return self.stream._enqueue(stanza, **kwargs)
def enqueue(self, stanza, **kwargs)
Put a `stanza` in the internal transmission queue and return a token to track it. :param stanza: Stanza to send :type stanza: :class:`IQ`, :class:`Message` or :class:`Presence` :param kwargs: see :class:`StanzaToken` :raises ConnectionError: if the stream is not :attr:`established` yet. :return: token which tracks the stanza :rtype: :class:`StanzaToken` The `stanza` is enqueued in the active queue for transmission and will be sent on the next opportunity. The relative ordering of stanzas enqueued is always preserved. Return a fresh :class:`StanzaToken` instance which traks the progress of the transmission of the `stanza`. The `kwargs` are forwarded to the :class:`StanzaToken` constructor. This method calls :meth:`~.stanza.StanzaBase.autoset_id` on the stanza automatically. .. seealso:: :meth:`send` for a more high-level way to send stanzas. .. versionchanged:: 0.10 This method has been moved from :meth:`aioxmpp.stream.StanzaStream.enqueue`.
6.632646
5.681486
1.167414
self._presence_server.set_presence(state, status=status)
def set_presence(self, state, status)
Set the presence `state` and `status` on the client. This has the same effects as writing `state` to :attr:`presence`, but the status of the presence is also set at the same time. `status` must be either a string or something which can be passed to :class:`dict`. If it is a string, the string is wrapped in a ``{None: status}`` dictionary. Otherwise, the dictionary is set as the :attr:`~.Presence.status` attribute of the presence stanza. It must map :class:`aioxmpp.structs.LanguageTag` instances to strings. The `status` is the text shown alongside the `state` (indicating availability such as *away*, *do not disturb* and *free to chat*).
7.833364
13.655028
0.573662
handler = functools.partial( self._handle_conversation_exit, conversation ) tokens = [] def linked_token(signal, handler): return signal, signal.connect(handler) tokens.append(linked_token(conversation.on_exit, handler)) tokens.append(linked_token(conversation.on_failure, handler)) tokens.append(linked_token(conversation.on_message, functools.partial( self.on_message, conversation, ))) self._conversation_meta[conversation] = ( tokens, ) self._conversation_map[conversation.jid] = conversation self.on_conversation_added(conversation)
def _add_conversation(self, conversation)
Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conversations which can be queried at :attr:`conversations`. The :meth:`on_conversation_added` event is fired. In addition, the :class:`ConversationService` subscribes to the :meth:`~.AbstractConversation.on_exit` event to remove the conversation from the list automatically. There is no need to remove a conversation from the list explicitly.
4.231887
3.864976
1.094932
iq = aioxmpp.IQ( to=peer, type_=aioxmpp.IQType.GET, payload=ping_xso.Ping() ) yield from client.send(iq)
def ping(client, peer)
Ping a peer. :param peer: The peer to ping. :type peer: :class:`aioxmpp.JID` :raises aioxmpp.errors.XMPPError: as received Send a :xep:`199` ping IQ to `peer` and wait for the reply. This is a low-level version of :meth:`aioxmpp.PingService.ping`. **When to use this function vs. the service method:** See :meth:`aioxmpp.PingService.ping`. .. note:: If the peer does not support :xep:`199`, they will respond with a ``cancel`` ``service-unavailable`` error. However, some implementations return a ``cancel`` ``feature-not-implemented`` error instead. Callers should be prepared for the :class:`aioxmpp.XMPPCancelError` exceptions in those cases. .. versionchanged:: 0.11 Extracted this helper from :class:`aioxmpp.PingService`.
7.826866
6.64044
1.178667
self._node.register_feature( "#".join([namespaces.xep0131_shim, name]) )
def register_header(self, name)
Register support for the SHIM header with the given `name`. If the header has already been registered as supported, :class:`ValueError` is raised.
39.939327
35.222023
1.133931
self._node.unregister_feature( "#".join([namespaces.xep0131_shim, name]) )
def unregister_header(self, name)
Unregister support for the SHIM header with the given `name`. If the header is currently not registered as supported, :class:`KeyError` is raised.
32.182827
29.983812
1.07334
iq = aioxmpp.IQ( type_=aioxmpp.IQType.GET, to=jid, payload=vcard_xso.VCard(), ) try: return (yield from self.client.send(iq)) except aioxmpp.XMPPCancelError as e: if e.condition in ( aioxmpp.ErrorCondition.FEATURE_NOT_IMPLEMENTED, aioxmpp.ErrorCondition.ITEM_NOT_FOUND): return vcard_xso.VCard() else: raise
def get_vcard(self, jid=None)
Get the vCard stored for the jid `jid`. If `jid` is :data:`None` get the vCard of the connected entity. :param jid: the object to retrieve. :returns: the stored vCard. We mask a :class:`XMPPCancelError` in case it is ``feature-not-implemented`` or ``item-not-found`` and return an empty vCard, since this can be understood to be semantically equivalent.
3.662047
3.116466
1.175064
iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=vcard, ) yield from self.client.send(iq)
def set_vcard(self, vcard)
Store the vCard `vcard` for the connected entity. :param vcard: the vCard to store. .. note:: `vcard` should always be derived from the result of `get_vcard` to preserve the elements of the vcard the client does not modify. .. warning:: It is in the responsibility of the user to supply valid vcard data as per :xep:`0054`.
5.954786
7.264849
0.819671
if message: if state != chatstates_xso.ChatState.ACTIVE: raise ValueError( "Only the state ACTIVE can be sent with messages." ) elif self._state == state: return False self._state = state return self._strategy.sending
def handle(self, state, message=False)
Handle a state update. :param state: the new chat state :type state: :class:`~aioxmpp.chatstates.ChatState` :param message: pass true to indicate that we handle the :data:`ACTIVE` state that is implied by sending a content message. :type message: :class:`bool` :returns: whether a standalone notification must be sent for this state update, respective if a chat state notification must be included with the message. :raises ValueError: if `message` is true and a state other than :data:`ACTIVE` is passed.
13.197134
9.488453
1.390863
cls = type(xso.XSO)(name, (xso.XSO,), { "TAG": tag, }) Error.as_application_condition(cls) return cls
def make_application_error(name, tag)
Create and return a **class** inheriting from :class:`.xso.XSO`. The :attr:`.xso.XSO.TAG` is set to `tag` and the class’ name will be `name`. In addition, the class is automatically registered with :attr:`.Error.application_condition` using :meth:`~.Error.as_application_condition`. Keep in mind that if you subclass the class returned by this function, the subclass is not registered with :class:`.Error`. In addition, if you do not override the :attr:`~.xso.XSO.TAG`, you will not be able to register the subclass as application defined condition as it has the same tag as the class returned by this function, which has already been registered as application condition.
11.248067
5.315951
2.115909
result = cls( condition=exc.condition, type_=exc.TYPE, text=exc.text ) result.application_condition = exc.application_defined_condition return result
def from_exception(cls, exc)
Construct a new :class:`Error` payload from the attributes of the exception. :param exc: The exception to convert :type exc: :class:`aioxmpp.errors.XMPPError` :result: Newly constructed error payload :rtype: :class:`Error` .. versionchanged:: 0.10 The :attr:`aioxmpp.XMPPError.application_defined_condition` is now taken over into the result.
8.641187
4.35242
1.985375
if hasattr(self.application_condition, "to_exception"): result = self.application_condition.to_exception(self.type_) if isinstance(result, Exception): return result return self.EXCEPTION_CLS_MAP[self.type_]( condition=self.condition_obj, text=self.text, application_defined_condition=self.application_condition, )
def to_exception(self)
Convert the error payload to a :class:`~aioxmpp.errors.XMPPError` subclass. :result: Newly constructed exception :rtype: :class:`aioxmpp.errors.XMPPError` The exact type of the result depends on the :attr:`type_` (see :class:`~aioxmpp.errors.XMPPError` about the existing subclasses). The :attr:`condition_obj`, :attr:`text` and :attr:`application_condition` are transferred to the respective attributes of the :class:`~aioxmpp.errors.XMPPError`.
4.923644
3.282349
1.500037
try: self.id_ except AttributeError: pass else: if self.id_: return self.id_ = to_nmtoken(random.getrandbits(8*RANDOM_ID_BYTES))
def autoset_id(self)
If the :attr:`id_` already has a non-false (false is also the empty string!) value, this method is a no-op. Otherwise, the :attr:`id_` attribute is filled with :data:`RANDOM_ID_BYTES` of random data, encoded by :func:`aioxmpp.utils.to_nmtoken`. .. note:: This method only works on subclasses of :class:`StanzaBase` which define the :attr:`id_` attribute.
6.874649
2.878307
2.388435
obj = type(self)( from_=self.to, to=self.from_, # because flat is better than nested (sarcasm) type_=type(self).type_.type_.enum_class.ERROR, ) obj.id_ = self.id_ obj.error = error return obj
def make_error(self, error)
Create a new instance of this stanza (this directly uses ``type(self)``, so also works for subclasses without extra care) which has the given `error` value set as :attr:`error`. In addition, the :attr:`id_`, :attr:`from_` and :attr:`to` values are transferred from the original (with from and to being swapped). Also, the :attr:`type_` is set to ``"error"``.
9.654396
7.504154
1.28654
obj = super()._make_reply(self.type_) obj.id_ = None return obj
def make_reply(self)
Create a reply for the message. The :attr:`id_` attribute is cleared in the reply. The :attr:`from_` and :attr:`to` are swapped and the :attr:`type_` attribute is the same as the one of the original message. The new :class:`Message` object is returned.
10.664531
8.836968
1.206809
if (self._smachine.state == State.CLOSING or self._smachine.state == State.CLOSED): return self._writer.close() if self._transport.can_write_eof(): self._transport.write_eof() if self._smachine.state == State.STREAM_HEADER_SENT: # at this point, we cannot wait for the peer to send # </stream:stream> self._close_transport() self._smachine.state = State.CLOSING
def close(self)
Close the XML stream and the underlying transport. This gracefully shuts down the XML stream and the transport, if possible by writing the eof using :meth:`asyncio.Transport.write_eof` after sending the stream footer. After a call to :meth:`close`, no other stream manipulating or sending method can be called; doing so will result in a :class:`ConnectionError` exception or any exception caused by the transport during shutdown. Calling :meth:`close` while the stream is closing or closed is a no-op.
4.462965
4.186753
1.065973
self._require_connection(accept_partial=True) self._reset_state() self._writer.start() self._smachine.rewind(State.STREAM_HEADER_SENT)
def reset(self)
Reset the stream by discarding all state and re-sending the stream header. Calling :meth:`reset` when the stream is disconnected or currently disconnecting results in either :class:`ConnectionError` being raised or the exception which caused the stream to die (possibly a received stream error or a transport error) to be reraised. :meth:`reset` puts the stream into :attr:`~State.STREAM_HEADER_SENT` state and it cannot be used for sending XSOs until the peer stream header has been received. Usually, this is not a problem as stream resets only occur during stream negotiation and stream negotiation typically waits for the peers feature node to arrive first.
20.313202
15.015262
1.352837
if self._smachine.state == State.CLOSED: return if self._smachine.state == State.READY: self._smachine.state = State.CLOSED return if (self._smachine.state != State.CLOSING and self._transport.can_write_eof()): self._transport.write_eof() self._close_transport()
def abort(self)
Abort the stream by writing an EOF if possible and closing the transport. The transport is closed using :meth:`asyncio.BaseTransport.close`, so buffered data is sent, but no more data will be received. The stream is in :attr:`State.CLOSED` state afterwards. This also works if the stream is currently closing, that is, waiting for the peer to send a stream footer. In that case, the stream will be closed locally as if the stream footer had been received. .. versionadded:: 0.5
3.772729
3.750259
1.005992
self._require_connection() if not self.can_starttls(): raise RuntimeError("starttls not available on transport") yield from self._transport.starttls(ssl_context, post_handshake_callback) self._reset_state()
def starttls(self, ssl_context, post_handshake_callback=None)
Start TLS on the transport and wait for it to complete. The `ssl_context` and `post_handshake_callback` arguments are forwarded to the transports :meth:`aioopenssl.STARTTLSTransport.starttls` coroutine method. If the transport does not support starttls, :class:`RuntimeError` is raised; support for starttls can be discovered by querying :meth:`can_starttls`. After :meth:`starttls` returns, you must call :meth:`reset`. Any other method may fail in interesting ways as the internal state is discarded when starttls succeeds, for security reasons. :meth:`reset` re-creates the internal structures.
5.34372
4.321196
1.23663
fut = asyncio.Future(loop=self._loop) self._error_futures.append(fut) return fut
def error_future(self)
Return a future which will receive the next XML stream error as exception. It is safe to cancel the future at any time.
3.671009
3.994647
0.918982
response = yield from self._disco.query_info(jid) result = set() for feature in response.features: try: result.add(pubsub_xso.Feature(feature)) except ValueError: continue return result
def get_features(self, jid)
Return the features supported by a service. :param jid: Address of the PubSub service to query. :type jid: :class:`aioxmpp.JID` :return: Set of supported features :rtype: set containing :class:`~.pubsub.xso.Feature` enumeration members. This simply uses service discovery to obtain the set of features and converts the features to :class:`~.pubsub.xso.Feature` enumeration members. To get the full feature information, resort to using :meth:`.DiscoClient.query_info` directly on `jid`. Features returned by the peer which are not valid pubsub features are not returned.
8.306156
3.111737
2.669299
subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( pubsub_xso.Subscribe(subscription_jid, node=node) ) if config is not None: iq.payload.options = pubsub_xso.Options( subscription_jid, node=node ) iq.payload.options.data = config response = yield from self.client.send(iq) return response
def subscribe(self, jid, node=None, *, subscription_jid=None, config=None)
Subscribe to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to subscribe to. :type node: :class:`str` :param subscription_jid: The address to subscribe to the service. :type subscription_jid: :class:`aioxmpp.JID` :param config: Optional configuration of the subscription :type config: :class:`~.forms.Data` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the server. :rtype: :class:`.xso.Request` By default, the subscription request will be for the bare JID of the client. It can be specified explicitly using the `subscription_jid` argument. If the service requires it or if it makes sense for other reasons, the subscription configuration :class:`~.forms.Data` form can be passed using the `config` argument. On success, the whole :class:`.xso.Request` object returned by the server is returned. It contains a :class:`.xso.Subscription` :attr:`~.xso.Request.payload` which has information on the nature of the subscription (it may be ``"pending"`` or ``"unconfigured"``) and the :attr:`~.xso.Subscription.subid` which may be required for other operations. On failure, the corresponding :class:`~.errors.XMPPError` is raised.
3.845228
3.56656
1.078133
subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( pubsub_xso.Unsubscribe(subscription_jid, node=node, subid=subid) ) yield from self.client.send(iq)
def unsubscribe(self, jid, node=None, *, subscription_jid=None, subid=None)
Unsubscribe from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to unsubscribe from. :type node: :class:`str` :param subscription_jid: The address to subscribe from the service. :type subscription_jid: :class:`aioxmpp.JID` :param subid: Unique ID of the subscription to remove. :type subid: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service By default, the unsubscribe request will be for the bare JID of the client. It can be specified explicitly using the `subscription_jid` argument. If available, the `subid` should also be specified. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised.
4.71121
4.54722
1.036064
subscription_jid = subscription_jid or self.client.local_jid.bare() iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request() iq.payload.options = pubsub_xso.Options( subscription_jid, node=node, subid=subid, ) response = yield from self.client.send(iq) return response.options.data
def get_subscription_config(self, jid, node=None, *, subscription_jid=None, subid=None)
Request the current configuration of a subscription. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param subscription_jid: The address to query the configuration for. :type subscription_jid: :class:`aioxmpp.JID` :param subid: Unique ID of the subscription to query. :type subid: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The current configuration of the subscription. :rtype: :class:`~.forms.Data` By default, the request will be on behalf of the bare JID of the client. It can be overriden using the `subscription_jid` argument. If available, the `subid` should also be specified. On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised.
4.658529
4.508524
1.033271
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Default(node=node) ) response = yield from self.client.send(iq) return response.payload.data
def get_default_config(self, jid, node=None)
Request the default configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The default configuration of subscriptions at the node. :rtype: :class:`~.forms.Data` On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised.
5.98182
5.625651
1.063312
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.OwnerRequest( pubsub_xso.OwnerConfigure(node=node) ) response = yield from self.client.send(iq) return response.payload.data
def get_node_config(self, jid, node=None)
Request the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration of the node. :rtype: :class:`~.forms.Data` On success, the :class:`~.forms.Data` form is returned. If an error occurs, the corresponding :class:`~.errors.XMPPError` is raised.
7.505445
6.631417
1.131801
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.OwnerRequest( pubsub_xso.OwnerConfigure(node=node) ) iq.payload.payload.data = config yield from self.client.send(iq)
def set_node_config(self, jid, config, node=None)
Update the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param config: Configuration form :type config: :class:`aioxmpp.forms.Data` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration of the node. :rtype: :class:`~.forms.Data` .. seealso:: :class:`aioxmpp.pubsub.NodeConfigForm`
7.977228
8.05045
0.990905
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Items(node, max_items=max_items) ) return (yield from self.client.send(iq))
def get_items(self, jid, node, *, max_items=None)
Request the most recent items from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param max_items: Number of items to return at most. :type max_items: :class:`int` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the server. :rtype: :class:`.xso.Request`. By default, as many as possible items are requested. If `max_items` is given, it must be a positive integer specifying the maximum number of items which is to be returned by the server. Return the :class:`.xso.Request` object, which has a :class:`~.xso.Items` :attr:`~.xso.Request.payload`.
5.535959
4.737491
1.168542
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Items(node) ) iq.payload.payload.items = [ pubsub_xso.Item(id_) for id_ in ids ] if not iq.payload.payload.items: raise ValueError("ids must not be empty") return (yield from self.client.send(iq))
def get_items_by_id(self, jid, node, ids)
Request specific items by their IDs from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param ids: The item IDs to return. :type ids: :class:`~collections.abc.Iterable` of :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The response from the service :rtype: :class:`.xso.Request` `ids` must be an iterable of :class:`str` of the IDs of the items to request from the pubsub node. If the iterable is empty, :class:`ValueError` is raised (as otherwise, the request would be identical to calling :meth:`get_items` without `max_items`). Return the :class:`.xso.Request` object, which has a :class:`~.xso.Items` :attr:`~.xso.Request.payload`.
4.513468
3.537469
1.275903
iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.GET) iq.payload = pubsub_xso.Request( pubsub_xso.Subscriptions(node=node) ) response = yield from self.client.send(iq) return response.payload
def get_subscriptions(self, jid, node=None)
Return all subscriptions of the local entity to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The subscriptions response from the service. :rtype: :class:`.xso.Subscriptions. If `node` is :data:`None`, subscriptions on all nodes of the entity `jid` are listed.
5.585711
4.886767
1.143028
publish = pubsub_xso.Publish() publish.node = node if payload is not None: item = pubsub_xso.Item() item.id_ = id_ item.registered_payload = payload publish.item = item iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( publish ) if publish_options is not None: features = yield from self.get_features(jid) if pubsub_xso.Feature.PUBLISH_OPTIONS not in features: raise RuntimeError( "publish-options given, but not supported by server" ) iq.payload.publish_options = pubsub_xso.PublishOptions() iq.payload.publish_options.data = publish_options response = yield from self.client.send(iq) if response is not None and response.payload.item is not None: return response.payload.item.id_ or id_ return id_
def publish(self, jid, node, payload, *, id_=None, publish_options=None)
Publish an item to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to publish to. :type node: :class:`str` :param payload: Registered payload to publish. :type payload: :class:`aioxmpp.xso.XSO` :param id_: Item ID to use for the item. :type id_: :class:`str` or :data:`None`. :param publish_options: A data form with the options for the publish request :type publish_options: :class:`aioxmpp.forms.Data` :raises aioxmpp.errors.XMPPError: as returned by the service :raises RuntimeError: if `publish_options` is not :data:`None` but the service does not support `publish_options` :return: The Item ID which was used to publish the item. :rtype: :class:`str` or :data:`None` Publish the given `payload` (which must be a :class:`aioxmpp.xso.XSO` registered with :attr:`.xso.Item.registered_payload`). The item is published to `node` at `jid`. If `id_` is given, it is used as the ID for the item. If an item with the same ID already exists at the node, it is replaced. If no ID is given, a ID is generated by the server. If `publish_options` is given, it is passed as ``<publish-options/>`` element to the server. This needs to be a data form which allows to define e.g. node configuration as a pre-condition to publishing. If the publish-options cannot be satisfied, the server will raise a :attr:`aioxmpp.ErrorCondition.CONFLICT` error. If `publish_options` is given and the server does not announce the :attr:`aioxmpp.pubsub.xso.Feature.PUBLISH_OPTIONS` feature, :class:`RuntimeError` is raised to prevent security issues (e.g. if the publish options attempt to assert a restrictive access model). Return the ID of the item as published (or :data:`None` if the server does not inform us; this is unfortunately common).
3.477713
3.040173
1.143919
retract = pubsub_xso.Retract() retract.node = node item = pubsub_xso.Item() item.id_ = id_ retract.item = item retract.notify = notify iq = aioxmpp.stanza.IQ(to=jid, type_=aioxmpp.structs.IQType.SET) iq.payload = pubsub_xso.Request( retract ) yield from self.client.send(iq)
def retract(self, jid, node, id_, *, notify=False)
Retract a previously published item from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to send a notify from. :type node: :class:`str` :param id_: The ID of the item to retract. :type id_: :class:`str` :param notify: Flag indicating whether subscribers shall be notified about the retraction. :type notify: :class:`bool` :raises aioxmpp.errors.XMPPError: as returned by the service Retract an item previously published to `node` at `jid`. `id_` must be the ItemID of the item to retract. If `notify` is set to true, notifications will be generated (by setting the `notify` attribute on the retraction request).
4.249374
4.035766
1.052929
create = pubsub_xso.Create() create.node = node iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.Request(create) ) response = yield from self.client.send(iq) if response is not None and response.payload.node is not None: return response.payload.node return node
def create(self, jid, node=None)
Create a new node at a service. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to create. :type node: :class:`str` or :data:`None` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The name of the created node. :rtype: :class:`str` If `node` is :data:`None`, an instant node is created (see :xep:`60`). The server may not support or allow the creation of instant nodes. Return the actual `node` identifier.
5.592353
5.177937
1.080035