# `structs` — Simple data holders for common data types

These classes provide a way to hold structured data which is commonly encountered in the XMPP realm.

## Stanza types

class aioxmpp.IQType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

  Enumeration for the RFC 6120 specified IQ stanza types.

  See also

  `type_`

    Type attribute of IQ stanzas.

  Each member has the following meta-information:

  is_error

    True for the `ERROR` type, false otherwise.

  is_request

    True for request types (`GET` and `SET`), false otherwise.

  is_response

    True for the response types (`RESULT` and `ERROR`), false otherwise.

  Note

  The `is_error`, `is_request` and `is_response` meta-information attributes share semantics across `MessageType`, `PresenceType` and `IQType`. You are encouraged to exploit this in full duck-typing manner in generic stanza handling code.

  The following types are specified. The quotations in the member descriptions are from RFC 6120, Section 8.2.3.

  GET

    The `"get"` IQ type:

    > The stanza requests information, inquires about what data is needed in order to complete further operations, etc.

    A `GET` IQ must contain a payload, via the `payload` attribute.

  SET

    The `"set"` IQ type:

    > The stanza provides data that is needed for an operation to be completed, sets new values, replaces existing values, etc.

    A `SET` IQ must contain a payload, via the `payload` attribute.

  ERROR

    The `"error"` IQ type:

    > The stanza reports an error that has occurred regarding processing or delivery of a get or set request[…].

    `IQ` objects carrying the `ERROR` type usually have the `error` set to a `Error` instance describing the details of the error.

    The `payload` attribute may also be set if the sender of the `ERROR` was kind enough to include the data which caused the problem.

  RESULT

    The `"result"` IQ type:

    > The stanza is a response to a successful get or set request.

    A `RESULT` IQ may contain a payload with more data.

  `IQType` members compare and hash equal to their values. For example:

      assert IQType.GET == "get"
      assert "get" == IQType.GET
      assert hash(IQType.GET) == hash("get")

  Deprecated since version 0.7: This behaviour will cease with aioxmpp 1.0, and the first assertion will fail, the second may fail.

  Please see the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

class aioxmpp.MessageType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

  Enumeration for the RFC 6121 specified Message stanza types.

  See also

  `type_`

    Type attribute of Message stanzas.

  Each member has the following meta-information:

  is_error

    True for the `ERROR` type, false for all others.

  is_request

    False. See `is_response`.

  is_response

    True for the `ERROR` type, false for all others.

    This is intended. Request/Response semantics do not really apply for messages, except that errors are generally in response to other messages.

  Note

  The `is_error`, `is_request` and `is_response` meta-information attributes share semantics across `MessageType`, `PresenceType` and `IQType`. You are encouraged to exploit this in full duck-typing manner in generic stanza handling code.

  The following types are specified. The quotations in the member descriptions are from RFC 6121, Section 5.2.2.

  NORMAL

    The `"normal"` Message type:

    > The message is a standalone message that is sent outside the context of a one-to-one conversation or groupchat, and to which it is expected that the recipient will reply. Typically a receiving client will present a message of type “normal” in an interface that enables the recipient to reply, but without a conversation history. The default value of the ‘type’ attribute is “normal”.

    Think of it as somewhat similar to “E-Mail via XMPP”.

  CHAT

    The `"chat"` Message type:

    > The message is sent in the context of a one-to-one chat session. Typically an interactive client will present a message of type “chat” in an interface that enables one-to-one chat between the two parties, including an appropriate conversation history.

  GROUPCHAT

    The `"groupchat"` Message type:

    > The message is sent in the context of a multi-user chat environment […]. Typically a receiving client will present a message of type “groupchat” in an interface that enables many-to-many chat between the parties, including a roster of parties in the chatroom and an appropriate conversation history.

  HEADLINE

    The `"headline"` Message type:

    > The message provides an alert, a notification, or other transient information to which no reply is expected (e.g., news headlines, sports updates, near-real-time market data, or syndicated content). Because no reply to the message is expected, typically a receiving client will present a message of type “headline” in an interface that appropriately differentiates the message from standalone messages, chat messages, and groupchat messages (e.g., by not providing the recipient with the ability to reply).

    Do not confuse this message type with the `subject` member of Messages!

  ERROR

    The `"error"` Message type:

    > The message is generated by an entity that experiences an error when processing a message received from another entity […]. A client that receives a message of type “error” SHOULD present an appropriate interface informing the original sender regarding the nature of the error.

    This is the only message type which is used in direct response to another message, in the sense that the Stanza ID is preserved in the response.

  `MessageType` members compare and hash equal to their values. For example:

      assert MessageType.CHAT == "chat"
      assert "chat" == MessageType.CHAT
      assert hash(MessageType.CHAT) == hash("chat")

  Deprecated since version 0.7: This behaviour will cease with aioxmpp 1.0, and the first assertion will fail, the second may fail.

  Please see the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

class aioxmpp.PresenceType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

  Enumeration for the RFC 6121 specified Presence stanza types.

  See also

  `type_`

    Type attribute of Presence stanzas.

  Each member has the following meta-information:

  is_error

    True for the `ERROR` type, false otherwise.

  is_request

    False. See `is_response`.

  is_response

    True for the `ERROR` type, false otherwise.

    This is intended. Request/Response semantics do not really apply for presence stanzas, except that errors are generally in response to other presence stanzas.

  is_presence_state

    True for the `AVAILABLE` and `UNAVAILABLE` types, false otherwise.

    Useful to discern presence state notifications from meta-stanzas regarding presence broadcast control.

  Note

  The `is_error`, `is_request` and `is_response` meta-information attributes share semantics across `MessageType`, `PresenceType` and `IQType`. You are encouraged to exploit this in full duck-typing manner in generic stanza handling code.

  The following types are specified. The quotes in the member descriptions are from RFC 6121, Section 4.7.1.

  ERROR

    The `"error"` Presence type:

    > An error has occurred regarding processing of a previously sent presence stanza; if the presence stanza is of type “error”, it MUST include an <error/> child element […].

    This is the only presence stanza type which is used in direct response to another presence stanza, in the sense that the Stanza ID is preserved in the response.

    In addition, `ERROR` presence stanzas may be seen during presence broadcast if inter-server communication fails.

  PROBE

    The `"probe"` Presence type:

    > A request for an entity’s current presence; SHOULD be generated only by a server on behalf of a user.

    This should not be seen in client code.

  SUBSCRIBE

    The `"subscribe"` Presence type:

    > The sender wishes to subscribe to the recipient’s presence.

  SUBSCRIBED

    The `"subscribed"` Presence type:

    > The sender has allowed the recipient to receive their presence.

  UNSUBSCRIBE

    The `"unsubscribe"` Presence type:

    > The sender is unsubscribing from the receiver’s presence.

  UNSUBSCRIBED

    The `"unsubscribed"` Presence type:

    > The subscription request has been denied or a previously granted subscription has been canceled.

  AVAILABLE

    The Presence type signalled with an absent type attribute:

    > The absence of a ‘type’ attribute signals that the relevant entity is available for communication […].

  UNAVAILABLE

    The `"unavailable"` Presence type:

    > The sender is no longer available for communication.

  `PresenceType` members compare and hash equal to their values. For example:

      assert PresenceType.PROBE == "probe"
      assert "probe" == PresenceType.PROBE
      assert hash(PresenceType.PROBE) == hash("probe")

  Deprecated since version 0.7: This behaviour will cease with aioxmpp 1.0, and the first assertion will fail, the second may fail.

  Please see the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

class aioxmpp.ErrorType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

  Enumeration for the RFC 6120 specified stanza error types.

  These error types reflect are actually more reflecting the error classes, but the attribute is called “type” nonetheless. For consistency, we are calling it “type” here, too.

  The following types are specified. The quotations in the member descriptions are from RFC 6120, Section 8.3.2.

  AUTH

    The `"auth"` error type:

    > retry after providing credentials

    When converted to an exception, it uses `XMPPAuthError`.

  CANCEL

    The `"cancel"` error type:

    > do not retry (the error cannot be remedied)

    When converted to an exception, it uses `XMPPCancelError`.

  CONTINUE

    The `"continue"` error type:

    > proceed (the condition was only a warning)

    When converted to an exception, it uses `XMPPContinueError`.

  MODIFY

    The `"modify"` error type:

    > retry after changing the data sent

    When converted to an exception, it uses `XMPPModifyError`.

  WAIT

    The `"wait"` error type:

    > retry after waiting (the error is temporary)

    When converted to an exception, it uses (guess what) `XMPPWaitError`.

  `ErrorType` members compare and hash equal to their values. For example:

      assert ErrorType.CANCEL == "cancel"
      assert "cancel" == ErrorType.CANCEL
      assert hash(ErrorType.CANCEL) == hash("cancel")

  Deprecated since version 0.7: This behaviour will cease with aioxmpp 1.0, and the first assertion will fail, the second may fail.

  Please see the Changelog for Version 0.7 for further details on how to upgrade your code efficiently.

## Jabber IDs

class aioxmpp.JID(localpart, domain, resource)

  Represent a Jabber ID (JID).

  To construct a `JID`, either use the actual constructor, or use the `fromstr()` class method.

  Parameters:

    - localpart (`str` or `None`) – The part in front of the `@` of the JID, or `None` if the localpart shall be omitted (which is different from it being empty, which would be invalid).

    - domain (`str`) – The domain of the JID. This is the only mandatory part of a JID.

    - resource (`str` or `None`) – The resource part of the JID or `None` to omit the resource part.

    - strict (`bool`) – Enable strict validation

  Raises:

    ValueError – if the JID composed of the given parts is invalid

  Construct a JID out of its parts. It validates the parts individually, as well as the JID as a whole.

  If strict is false, unassigned codepoints are allowed in any of the parts of the JID. In the future, other deviations from the respective stringprep profiles may be allowed, too.

  The idea is to use non-strict when output is received from outside and when it is reflected, following the old principle “be conservative in what you send and liberal in what you receive”. Otherwise, strict checking should be enabled. This brings maximum interoperability.

  classmethod fromstr(s, *, strict=True)

    Construct a JID out of a string containing it.

    Parameters:

      - s (`str`) – The string to parse.

      - strict (`bool`) – Whether to enable strict parsing.

    Raises:

      See `JID`

    Returns:

      The parsed JID

    Return type:

      `JID`

    See the `JID` class level documentation for the semantics of strict.

  Information about a JID:

  localpart

    The localpart, stringprep’d from the argument to the constructor.

  domain

    The domain, stringprep’d from the argument to the constructor.

  resource

    The resource, stringprep’d from the argument to the constructor.

  is_bare

    `True` if the JID is bare, i.e. has an empty `resource` part.

  is_domain

    `True` if the JID is a domain, i.e. if both the `localpart` and the `resource` are empty.

  `JID` objects are immutable. To obtain a JID object with a changed property, use one of the following methods:

  bare()

    Create a copy of the `JID` which is bare.

    Returns:

      This JID with the `resource` set to `None`.

    Return type:

      `JID`

    Return the bare version of this JID as new `JID` object.

  replace(*[, localpart][, domain][, resource])

    Construct a new `JID` object, using the values of the current JID. Use the arguments to override specific attributes on the new object.

    All arguments are keyword arguments.

    Parameters:

      - localpart – Set the local part of the resulting JID.

      - domain – Set the domain of the resulting JID.

      - resource – Set the resource part of the resulting JID.

    Raises:

      See `JID`

    Returns:

      A new `JID` object with the corresponding substitutions performed.

    Return type:

      `JID`

    The attributes of parameters which are omitted are not modified and copied down to the result.

aioxmpp.jid_escape(s)

  Return an escaped version of a string for use in a JID localpart.

  See also

  `jid_unescape()`

    for the reverse transformation

  Parameters:

    s (`str`) – The string to escape for use as localpart.

  Raises:

    ValueError – If the string starts or ends with a space.

  Returns:

    The escaped string.

  Return type:

    `str`

  Note

  JID Escaping does not allow embedding arbitrary characters in the localpart. Only a defined subset of characters can be escaped. Refer to XEP-0106 for details.

  Note

  No validity check is made on the result. It is assumed that the result is passed to the `JID` constructor, which will perform validity checks on its own.

aioxmpp.jid_unescape(localpart)

  Un-escape a JID Escaped localpart.

  See also

  `jid_escape()`

    for the reverse transformation

  Parameters:

    localpart (`str`) – The escaped localpart

  Returns:

    The unescaped localpart.

  Return type:

    `str`

  Note

  JID Escaping does not allow embedding arbitrary characters in the localpart. Only a defined subset of characters can be escaped. Refer to XEP-0106 for details.

## Presence

class aioxmpp.PresenceShow(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

  Enumeration to support the `show` element of presence stanzas.

  The enumeration members support total ordering. The order is defined by relevance and is the following (from lesser to greater): `XA`, `AWAY`, `NONE`, `CHAT`, `DND`. The order is intended to be used to extract the most relevant resource e.g. in a roster.

  New in version 0.8.

  XA = "xa"

    > The entity or resource is away for an extended period (xa = “eXtended Away”).

    > —RFC 6121, Section 4.7.2.1

  EXTENDED_AWAY = "xa"

    Alias to `XA`.

  AWAY = "away"

    > The entity or resource is temporarily away.

    > —RFC 6121, Section 4.7.2.1

  NONE = None

    Signifies absence of the `show` element.

  PLAIN = None

    Alias to `NONE`.

  CHAT = "chat"

    > The entity or resource is actively interested in chatting.

    > —RFC 6121, Section 4.7.2.1

  FREE_FOR_CHAT = "chat"

    Alias to `CHAT`.

  DND = "dnd"

    > The entity or resource is busy (dnd = “Do Not Disturb”).

    > —RFC 6121, Section 4.7.2.1

  DO_NOT_DISTURB = "dnd"

    Alias to `DND`.

class aioxmpp.PresenceState(available=False, show=PresenceShow.NONE)

  Hold a presence state of an XMPP resource, as defined by the presence stanza semantics.

  available must be a boolean value, which defines whether the resource is available or not. If the resource is available, show may be set to one of `"dnd"`, `"xa"`, `"away"`, `None`, `"chat"` (it is a `ValueError` to attempt to set show to a non-`None` value if available is false).

  `PresenceState` objects are ordered by their availability and by their show values. Non-availability sorts lower than availability, and for available presence states the order is in the order of valid values given for the show above.

  available

    As per the argument to the constructor, converted to a `bool`.

  show

    As per the argument to the constructor.

  apply_to_stanza(stanza_obj)

    Apply the properties of this `PresenceState` to a `Presence` stanza_obj. The `type_` and `show` attributes of the object will be modified to fit the values in this object.

  classmethod from_stanza(stanza_obj, strict=False)

    Create and return a new `PresenceState` object which inherits the presence state as advertised in the given `Presence` stanza.

    If strict is `True`, the value of show is strictly checked, that is, it is required to be `None` if the stanza indicates an unavailable state.

    The default is not to check this.

  `PresenceState` objects are immutable.

## Languages

class aioxmpp.structs.LanguageTag(*, tag=None)

  Implementation of a language tag. This may be a fully RFC5646 compliant implementation some day, but for now it is only very simplistic stub.

  There is no input validation of any kind.

  `LanguageTag` instances compare and hash case-insensitively.

  classmethod fromstr(s)

    Create a language tag from the given string s.

    Note

    This is a stub implementation which merely refers to the given string as the `print_str` and derives the `match_str` from that.

  match_str

    The string which is used for matching two language tags. This is the lower-cased version of the `print_str`.

  print_str

    The stringified language tag.

class aioxmpp.structs.LanguageRange(*, tag=None)

  Implementation of a language range. This may be a fully RFC4647 compliant implementation some day, but for now it is only very simplistic stub.

  There is no input validation of any kind.

  `LanguageRange` instances compare and hash case-insensitively.

  classmethod fromstr(s)

    Create a language tag from the given string s.

    Note

    This is a stub implementation which merely refers to the given string as the `print_str` and derives the `match_str` from that.

  strip_rightmost()

    Strip the rightmost part of the language range. If the new rightmost part is a singleton or `x` (i.e. starts an extension or private use part), it is also stripped.

    Return the newly created `LanguageRange`.

  match_str

    The string which is used for matching two language tags. This is the lower-cased version of the `print_str`.

  print_str

    The stringified language tag.

class aioxmpp.structs.LanguageMap

  A `dict` subclass specialized for holding `LanugageTag` instances as keys.

  In addition to the interface provided by `dict`, instances of this class also have the following methods:

  lookup(language_ranges)

    Perform an RFC4647 language range lookup on the keys in the dictionary. language_ranges must be a sequence of `LanguageRange` instances.

    Return the entry in the dictionary with a key as produced by lookup_language. If lookup_language does not find a match and the mapping contains an entry with key `None`, that entry is returned, otherwise `KeyError` is raised.

  any()

    Returns any element from the language map, preferring the `None` key if it is available.

    Guarantees to always return the same element for a map with the same keys, even if the keys are iterated over in a different order.

### Functions for working with language tags

aioxmpp.structs.basic_filter_languages(languages, ranges)

  Filter languages using the string-based basic filter algorithm described in RFC4647.

  languages must be a sequence of `LanguageTag` instances which are to be filtered.

  ranges must be an iterable which represent the basic language ranges to filter with, in priority order. The language ranges must be given as `LanguageRange` objects.

  Return an iterator of languages which matched any of the ranges. The sequence produced by the iterator is in match order and duplicate-free. The first range to match a language yields the language into the iterator, no other range can yield that language afterwards.

aioxmpp.structs.lookup_language(languages, ranges)

  Look up a single language in the sequence languages using the lookup mechanism described in RFC4647. If no match is found, `None` is returned. Otherwise, the first matching language is returned.

  languages must be a sequence of `LanguageTag` objects, while ranges must be an iterable of `LanguageRange` objects.