slidge
======

.. py:module:: slidge

.. autoapi-nested-parse::

   The main slidge package.

   Contains importable classes for a minimal function :term:`Legacy Module`.



Submodules
----------

.. toctree::
   :maxdepth: 1

   /api/auto/slidge/command/index
   /api/auto/slidge/contact/index
   /api/auto/slidge/group/index
   /api/auto/slidge/main/index
   /api/auto/slidge/util/index






Package Contents
----------------

.. py:class:: BaseGateway

   Bases: :py:obj:`slixmpp.ComponentXMPP`, :py:obj:`slidge.core.mixins.message.MessageMixin`, :py:obj:`slidge.util.SubclassableOnce`, :py:obj:`abc.ABC`, :py:obj:`Generic`\ [\ :py:obj:`slidge.util.types.SessionType`\ ]


   The gateway component, handling registrations and un-registrations.

   On slidge launch, a singleton is instantiated, and it will be made available
   to public classes such :class:`.LegacyContact` or :class:`.BaseSession` as the
   ``.xmpp`` attribute.

   Must be subclassed by a legacy module to set up various aspects of the XMPP
   component behaviour, such as its display name or welcome message, via
   class attributes :attr:`.COMPONENT_NAME` :attr:`.WELCOME_MESSAGE`.

   Abstract methods related to the registration process must be overriden
   for a functional :term:`Legacy Module`:

   - :meth:`.validate`
   - :meth:`.validate_two_factor_code`
   - :meth:`.get_qr_text`
   - :meth:`.confirm_qr`

   NB: Not all of these must be overridden, it depends on the
   :attr:`REGISTRATION_TYPE`.

   The other methods, such as :meth:`.send_text` or :meth:`.react` are the same
   as those of :class:`.LegacyContact` and :class:`.LegacyParticipant`, because
   the component itself is also a "messaging actor", ie, an :term:`XMPP Entity`.
   For these methods, you need to specify the JID of the recipient with the
   `mto` parameter.

   Since it inherits from :class:`slixmpp.componentxmpp.ComponentXMPP`,you also
   have a hand on low-level XMPP interactions via slixmpp methods, e.g.:

   .. code-block:: python

       self.send_presence(
           pfrom="somebody@component.example.com",
           pto="someonwelse@anotherexample.com",
       )

   However, you should not need to do so often since the classes of the plugin
   API provides higher level abstractions around most commonly needed use-cases, such
   as sending messages, or displaying a custom status.



   .. py:attribute:: COMPONENT_NAME
      :type:  str
      :value: NotImplemented


      Name of the component, as seen in service discovery by XMPP clients



   .. py:attribute:: COMPONENT_TYPE
      :type:  str
      :value: ''


      Type of the gateway, should follow https://xmpp.org/registrar/disco-categories.html



   .. py:attribute:: COMPONENT_AVATAR
      :type:  slidge.util.types.Avatar | pathlib.Path | str | None
      :value: None


      Path, bytes or URL used by the component as an avatar.



   .. py:attribute:: REGISTRATION_FIELDS
      :type:  ClassVar[collections.abc.Sequence[slidge.command.base.FormField]]

      Iterable of fields presented to the gateway user when registering using :xep:`0077`
      `extended <https://xmpp.org/extensions/xep-0077.html#extensibility>`_ by :xep:`0004`.



   .. py:attribute:: REGISTRATION_INSTRUCTIONS
      :type:  str
      :value: 'Enter your credentials'


      The text presented to a user who wants to register (or modify) their
      :term:`legacy <Legacy>` account configuration.



   .. py:attribute:: REGISTRATION_TYPE
      :type:  slidge.command.register.RegistrationType

      This attribute determines how users register to the gateway, ie, how they
      login to the :term:`legacy network <Legacy Network>`.
      The credentials are then stored persistently, so this process should happen
      once per user (unless they unregister).

      The registration process always start with a basic data form (:xep:`0004`)
      presented to the user.
      But the legacy login flow might require something more sophisticated, see
      :class:`.RegistrationType` for more details.



   .. py:attribute:: ROSTER_GROUP
      :type:  str
      :value: 'slidge'


      Name of the group assigned to a :class:`.LegacyContact` automagically
      added to the :term:`User`'s roster with :meth:`.LegacyContact.add_to_roster`.



   .. py:attribute:: WELCOME_MESSAGE
      :value: "Thank you for registering. Type 'help' to list the available commands, or just start messaging away!"


      A welcome message displayed to users on registration.
      This is useful notably for clients that don't consider component JIDs as a
      valid recipient in their UI, yet still open a functional chat window on
      incoming messages from components.



   .. py:attribute:: SEARCH_FIELDS
      :type:  ClassVar[collections.abc.Sequence[slidge.command.base.FormField]]

      Fields used for searching items via the component, through :xep:`0055` (jabber search).
      A common use case is to allow users to search for legacy contacts by something else than
      their usernames, eg their phone number.

      Plugins should implement search by overriding :meth:`.BaseSession.search`
      (restricted to registered users).

      If there is only one field, it can also be used via the ``jabber:iq:gateway`` protocol
      described in :xep:`0100`. Limitation: this only works if the search request returns
      one result item, and if this item has a 'jid' var.



   .. py:attribute:: SEARCH_TITLE
      :type:  str
      :value: 'Search for legacy contacts'


      Title of the search form.



   .. py:attribute:: SEARCH_INSTRUCTIONS
      :type:  str
      :value: ''


      Instructions of the search form.



   .. py:attribute:: MARK_ALL_MESSAGES
      :value: False


      Set this to True for :term:`legacy networks <Legacy Network>` that expects
      read marks for *all* messages and not just the latest one that was read
      (as most XMPP clients will only send a read mark for the latest msg).



   .. py:attribute:: PROPER_RECEIPTS
      :value: False


      Set this to True if the legacy service provides a real equivalent of message delivery receipts
      (:xep:`0184`), meaning that there is an event thrown when the actual device of a contact receives
      a message. Make sure to call Contact.received() adequately if this is set to True.



   .. py:attribute:: GROUPS
      :value: False


      This must be set to True if this gateway supports groups.



   .. py:attribute:: SPACES
      :value: False


      This must be set to True if this gateway supports spaces, cf :xep:`0503`.



   .. py:method:: validate(user_jid: slixmpp.JID, registration_form: dict[str, str | None]) -> slidge.db.meta.JSONSerializable | None
      :abstractmethod:

      :async:


      Validate a user's initial registration form.

      Should raise the appropriate :class:`slixmpp.exceptions.XMPPError`
      if the registration does not allow to continue the registration process.

      If :py:attr:`REGISTRATION_TYPE` is a
      :attr:`.RegistrationType.SINGLE_STEP_FORM`,
      this method should raise something if it wasn't possible to successfully
      log in to the legacy service with the registration form content.

      It is also used for other types of :py:attr:`REGISTRATION_TYPE` too, since
      the first step is always a form. If :attr:`.REGISTRATION_FIELDS` is an
      empty list (ie, it declares no :class:`.FormField`), the "form" is
      effectively a confirmation dialog displaying
      :attr:`.REGISTRATION_INSTRUCTIONS`.

      :param user_jid: JID of the user that has just registered
      :param registration_form: A dict where keys are the :attr:`.FormField.var` attributes
          of the :attr:`.BaseGateway.REGISTRATION_FIELDS` iterable.
          This dict can be modified and will be accessible as the ``legacy_module_data``
          of the

      :return : A dict that will be stored as the persistent "legacy_module_data"
          for this user. If you don't return anything here, the whole registration_form
          content will be stored.



   .. py:method:: validate_two_factor_code(user: slidge.db.GatewayUser, code: str) -> slidge.db.meta.JSONSerializable | None
      :abstractmethod:

      :async:


      Called when the user enters their 2FA code.

      Should raise the appropriate :class:`slixmpp.exceptions.XMPPError`
      if the login fails, and return successfully otherwise.

      Only used when :attr:`REGISTRATION_TYPE` is
      :attr:`.RegistrationType.TWO_FACTOR_CODE`.

      :param user: The :class:`.GatewayUser` whose registration is pending
          Use their :attr:`.GatewayUser.bare_jid` and/or
          :attr:`.registration_form` attributes to get what you need.
      :param code: The code they entered, either via "chatbot" message or
          adhoc command

      :return : A dict which keys and values will be added to the persistent "legacy_module_data"
          for this user.



   .. py:method:: get_qr_text(user: slidge.db.GatewayUser) -> str
      :abstractmethod:

      :async:


      This is where slidge gets the QR code content for the QR-based
      registration process. It will turn it into a QR code image and send it
      to the not-yet-fully-registered :class:`.GatewayUser`.

      Only used in when :attr:`BaseGateway.REGISTRATION_TYPE` is
      :attr:`.RegistrationType.QRCODE`.

      :param user: The :class:`.GatewayUser` whose registration is pending
          Use their :attr:`.GatewayUser.bare_jid` and/or
          :attr:`.registration_form` attributes to get what you need.



   .. py:method:: confirm_qr(user_bare_jid: str, exception: Exception | None = None, legacy_data: slidge.db.meta.JSONSerializable | None = None) -> None
      :async:


      This method is meant to be called to finalize QR code-based registration
      flows, once the legacy service confirms the QR flashing.

      Only used in when :attr:`BaseGateway.REGISTRATION_TYPE` is
      :attr:`.RegistrationType.QRCODE`.

      :param user_bare_jid: The bare JID of the almost-registered
          :class:`GatewayUser` instance
      :param exception: Optionally, an XMPPError to be raised to **not** confirm
          QR code flashing.
      :param legacy_data: dict which keys and values will be added to the persistent
          "legacy_module_data" for this user.



   .. py:method:: unregister(session: slidge.util.types.SessionType) -> None
      :async:


      Optionally override this if you need to clean additional
      stuff after a user has been removed from the persistent user store.

      By default, this just calls :meth:`BaseSession.logout`.

      :param session: The session of the user who just unregistered



   .. py:method:: input(jid: slixmpp.JID, text: str | None = None, mtype: slixmpp.types.MessageTypes = 'chat', **input_kwargs: Any) -> str
      :async:


      Request arbitrary user input using a simple chat message, and await the result.

      You shouldn't need to call this directly bust instead use
      :meth:`.BaseSession.input` to directly target a user.

      :param jid: The JID we want input from
      :param text: A prompt to display for the user
      :param mtype: Message type
      :return: The user's reply



   .. py:method:: send_qr(text: str, **msg_kwargs: Any) -> None
      :async:


      Sends a QR Code to a JID

      You shouldn't need to call directly bust instead use
      :meth:`.BaseSession.send_qr` to directly target a user.

      :param text: The text that will be converted to a QR Code
      :param msg_kwargs: Optional additional arguments to pass to
          :meth:`.BaseGateway.send_file`, such as the recipient of the QR,
          code



   .. py:method:: invite_to(muc: slidge.util.types.AnyMUC, reason: str | None = None, password: str | None = None, **send_kwargs: object) -> None

      Send an invitation to join a group (:xep:`0249`) from this :term:`XMPP Entity`.

      :param muc: the muc the user is invited to
      :param reason: a text explaining why the user should join this muc
      :param password: maybe this will make sense later? not sure
      :param send_kwargs: additional kwargs to be passed to _send()
          (internal use by slidge)



   .. py:method:: active(**kwargs: object) -> None

      Send an "active" chat state (:xep:`0085`) from this
      :term:`XMPP Entity`.



   .. py:method:: composing(**kwargs: object) -> None

      Send a "composing" (ie "typing notification") chat state (:xep:`0085`)
      from this :term:`XMPP Entity`.



   .. py:method:: paused(**kwargs: object) -> None

      Send a "paused" (ie "typing paused notification") chat state
      (:xep:`0085`) from this :term:`XMPP Entity`.



   .. py:method:: inactive(**kwargs: object) -> None

      Send an "inactive" (ie "contact has not interacted with the chat session
      interface for an intermediate period of time") chat state (:xep:`0085`)
      from this :term:`XMPP Entity`.



   .. py:method:: gone(**kwargs: object) -> None

      Send a "gone" (ie "contact has not interacted with the chat session interface,
      system, or device for a relatively long period of time") chat state
      (:xep:`0085`) from this :term:`XMPP Entity`.



   .. py:method:: ack(legacy_msg_id: str, **kwargs: object) -> None

      Send an "acknowledged" message marker (:xep:`0333`) from this :term:`XMPP Entity`.

      :param legacy_msg_id: The message this marker refers to



   .. py:method:: received(legacy_msg_id: str, **kwargs: object) -> None

      Send a "received" message marker (:xep:`0333`) from this :term:`XMPP Entity`.
      If called on a :class:`LegacyContact`, also send a delivery receipt
      marker (:xep:`0184`).

      :param legacy_msg_id: The message this marker refers to



   .. py:method:: displayed(legacy_msg_id: str, **kwargs: object) -> None

      Send a "displayed" message marker (:xep:`0333`) from this :term:`XMPP Entity`.

      :param legacy_msg_id: The message this marker refers to



   .. py:method:: send_file(attachment: slidge.util.types.LegacyAttachment | pathlib.Path | str, legacy_msg_id: str | None = None, *, reply_to: slidge.util.types.MessageReference | None = None, when: datetime.datetime | None = None, thread: str | None = None, **kwargs: Any) -> tuple[str | None, list[slixmpp.Message]]
      :async:


      Send a single file from this :term:`XMPP Entity`.

      :param attachment: The file to send.
          Ideally, a :class:`.LegacyAttachment` with a unique ``legacy_file_id``
          attribute set, to optimise potential future reuses.
          It can also be:
          - a :class:`pathlib.Path` instance to point to a local file, or
          - a ``str``, representing a fetchable HTTP URL.
      :param legacy_msg_id: If you want to be able to transport read markers from the gateway
          user to the legacy network, specify this
      :param reply_to: Quote another message (:xep:`0461`)
      :param when: when the file was sent, for a "delay" tag (:xep:`0203`)
      :param thread:



   .. py:method:: send_text(body: str, legacy_msg_id: str | None = None, *, when: datetime.datetime | None = None, reply_to: slidge.util.types.MessageReference | None = None, thread: str | None = None, hints: collections.abc.Iterable[slidge.util.types.ProcessingHint] | None = None, carbon: bool = False, archive_only: bool = False, correction: bool = False, correction_event_id: str | None = None, link_previews: list[slidge.util.types.LinkPreview] | None = None, **send_kwargs: object) -> slixmpp.Message | None

      Send a text message from this :term:`XMPP Entity`.

      :param body: Content of the message
      :param legacy_msg_id: If you want to be able to transport read markers from the gateway
          user to the legacy network, specify this
      :param when: when the message was sent, for a "delay" tag (:xep:`0203`)
      :param reply_to: Quote another message (:xep:`0461`)
      :param hints:
      :param thread:
      :param carbon: (only used if called on a :class:`LegacyContact`)
          Set this to ``True`` if this is actually a message sent **to** the
          :class:`LegacyContact` by the :term:`User`.
          Use this to synchronize outgoing history for legacy official apps.
      :param correction: whether this message is a correction or not
      :param correction_event_id: in the case where an ID is associated with the legacy
          'correction event', specify it here to use it on the XMPP side. If not specified,
          a random ID will be used.
      :param link_previews: A little of sender (or server, or gateway)-generated
          previews of URLs linked in the body.
      :param archive_only: (only in groups) Do not send this message to user,
          but store it in the archive. Meant to be used during ``MUC.backfill()``



   .. py:method:: correct(legacy_msg_id: str, new_text: str, *, when: datetime.datetime | None = None, reply_to: slidge.util.types.MessageReference | None = None, thread: str | None = None, hints: collections.abc.Iterable[slidge.util.types.ProcessingHint] | None = None, carbon: bool = False, archive_only: bool = False, correction_event_id: str | None = None, link_previews: list[slidge.util.types.LinkPreview] | None = None, **send_kwargs: object) -> None

      Modify a message that was previously sent by this :term:`XMPP Entity`.

      Uses last message correction (:xep:`0308`)

      :param new_text: New content of the message
      :param legacy_msg_id: The legacy message ID of the message to correct
      :param when: when the message was sent, for a "delay" tag (:xep:`0203`)
      :param reply_to: Quote another message (:xep:`0461`)
      :param hints:
      :param thread:
      :param carbon: (only in 1:1) Reflect a message sent to this ``Contact`` by the user.
          Use this to synchronize outgoing history for legacy official apps.
      :param archive_only: (only in groups) Do not send this message to user,
          but store it in the archive. Meant to be used during ``MUC.backfill()``
      :param correction_event_id: in the case where an ID is associated with the legacy
          'correction event', specify it here to use it on the XMPP side. If not specified,
          a random ID will be used.
      :param link_previews: A little of sender (or server, or gateway)-generated
          previews of URLs linked in the body.



   .. py:method:: react(legacy_msg_id: str, emojis: collections.abc.Iterable[str] = (), thread: str | None = None, **kwargs: object) -> None

      Send a reaction (:xep:`0444`) from this :term:`XMPP Entity`.

      :param legacy_msg_id: The message which the reaction refers to.
      :param emojis: An iterable of emojis used as reactions
      :param thread:



   .. py:method:: retract(legacy_msg_id: str, thread: str | None = None, **kwargs: object) -> None

      Send a message retraction (:XEP:`0424`) from this :term:`XMPP Entity`.

      :param legacy_msg_id: Legacy ID of the message to delete
      :param thread:



.. py:class:: BaseSession(user: slidge.db.models.GatewayUser)

   Bases: :py:obj:`slidge.util.lock.NamedLockMixin`, :py:obj:`slidge.util.SubclassableOnce`, :py:obj:`abc.ABC`, :py:obj:`Generic`\ [\ :py:obj:`slidge.util.types.LegacyContactType`\ ]


   The session of a registered :term:`User`.

   Represents a gateway user logged in to the legacy network and performing actions.

   Will be instantiated automatically on slidge startup for each registered user,
   or upon registration for new (validated) users.

   Must be subclassed for a functional :term:`Legacy Module`.


   .. py:attribute:: xmpp
      :type:  BaseGateway[Self]

      The gateway instance singleton. Use it for low-level XMPP calls or custom methods that are not
      session-specific.



   .. py:attribute:: MESSAGE_IDS_ARE_THREAD_IDS
      :value: False


      Set this to True if the legacy service uses message IDs as thread IDs,
      eg Mattermost, where you can only 'create a thread' by replying to the message,
      in which case the message ID is also a thread ID (and all messages are potential
      threads).



   .. py:attribute:: SPECIAL_MSG_ID_PREFIX
      :type:  str | None
      :value: None


      If you set this, XMPP message IDs starting with this won't be converted to legacy ID,
      but passed as is to :meth:`LegacyContact.on_react`, and usual checks for emoji restriction won't be
      applied.
      This can be used to implement voting in polls in a hacky way.



   .. py:attribute:: user

      The :term:`slidge user <User>`.



   .. py:method:: login() -> str | None
      :abstractmethod:

      :async:


      Logs in the gateway user to the legacy network.

      Triggered when the gateway start and on user registration.
      It is recommended that this function returns once the user is logged in,
      so if you need to await forever (for instance to listen to incoming events),
      it's a good idea to wrap your listener in an asyncio.Task.

      :return: Optionally, a text to use as the gateway status, e.g., "Connected as 'dude@legacy.network'"



   .. py:method:: logout() -> None
      :abstractmethod:

      :async:


      Logs out the gateway user from the legacy network.

      Called on gateway shutdown.



   .. py:method:: on_presence(resource: str, show: slidge.util.types.PseudoPresenceShow, status: str, resources: dict[str, slixmpp.types.ResourceDict], merged_resource: slixmpp.types.ResourceDict | None) -> None
      :abstractmethod:

      :async:


      Called when the gateway component receives a presence, ie, when
      one of the user's clients goes online of offline, or changes its
      status.

      :param resource: The XMPP client identifier, arbitrary string.
      :param show: The presence ``<show>``, if available. If the resource is
          just 'available' without any ``<show>`` element, this is an empty
          str.
      :param status: A status message, like a deeply profound quote, eg,
          "Roses are red, violets are blue, [INSERT JOKE]".
      :param resources: A summary of all the resources for this user.
      :param merged_resource: A global presence for the user account,
          following rules described in :meth:`merge_resources`



   .. py:method:: on_search(form_values: dict[str, str]) -> slidge.command.SearchResult | None
      :abstractmethod:

      :async:


      Triggered when the user uses Jabber Search (:xep:`0055`) on the component

      Form values is a dict in which keys are defined in :attr:`.BaseGateway.SEARCH_FIELDS`

      :param form_values: search query, defined for a specific plugin by overriding
          in :attr:`.BaseGateway.SEARCH_FIELDS`
      :return:



   .. py:method:: on_avatar(bytes_: bytes | None, hash_: str | None, type_: str | None, width: int | None, height: int | None) -> None
      :abstractmethod:

      :async:


      Triggered when the user uses modifies their avatar via :xep:`0084`.

      :param bytes_: The data of the avatar. According to the spec, this
          should always be a PNG, but some implementations do not respect
          that. If `None` it means the user has unpublished their avatar.
      :param hash_: The SHA1 hash of the avatar data. This is an identifier of
          the avatar.
      :param type_: The MIME type of the avatar.
      :param width: The width of the avatar image.
      :param height: The height of the avatar image.



   .. py:method:: on_create_group(name: str, contacts: list[slidge.util.types.LegacyContactType]) -> str
      :abstractmethod:

      :async:


      Triggered when the user request the creation of a group via the
      dedicated :term:`Command`.

      :param name: Name of the group
      :param contacts: list of contacts that should be members of the group



   .. py:method:: on_leave_space(space_legacy_id: str) -> None
      :abstractmethod:

      :async:


      Triggered when the user sends a request to leave a :xep:`0503` space.

      :param space_legacy_id: The legacy ID of the space to leave



   .. py:method:: on_preferences(previous: dict[str, Any], new: dict[str, Any]) -> None
      :abstractmethod:

      :async:


      This is called when the user updates their preferences.

      Override this if you need set custom preferences field and need to trigger
      something when a preference has changed.



   .. py:method:: send_gateway_status(status: str | None = None, show: slixmpp.types.PresenceShows | None = None, **kwargs: Any) -> None

      Send a presence from the gateway to the user.

      Can be used to indicate the user session status, ie "SMS code required", "connected", …

      :param status: A status message
      :param show: Presence stanza 'show' element. I suggest using "dnd" to show
          that the gateway is not fully functional



   .. py:method:: send_gateway_message(text: str, **msg_kwargs: Any) -> None

      Send a message from the gateway component to the user.

      Can be used to indicate the user session status, ie "SMS code required", "connected", …

      :param text: A text



   .. py:method:: send_gateway_invite(muc: slidge.util.types.AnyMUC, reason: str | None = None, password: str | None = None) -> None

      Send an invitation to join a MUC, emanating from the gateway component.

      :param muc:
      :param reason:
      :param password:



   .. py:method:: input(text: str, **msg_kwargs: Any) -> str
      :async:


      Request user input via direct messages from the gateway component.

      Wraps call to :meth:`.BaseSession.input`

      :param text: The prompt to send to the user
      :param msg_kwargs: Extra attributes
      :return:



   .. py:method:: send_qr(text: str) -> None
      :async:


      Sends a QR code generated from 'text' via HTTP Upload and send the URL to
      ``self.user``

      :param text: Text to encode as a QR code



.. py:class:: GatewayUser

   Bases: :py:obj:`slidge.db.meta.Base`


   A user, registered to the gateway component.


   .. py:attribute:: legacy_module_data
      :type:  sqlalchemy.orm.Mapped[slidge.db.meta.JSONSerializable]

      Arbitrary non-relational data that legacy modules can use



   .. py:attribute:: avatar_hash
      :type:  sqlalchemy.orm.Mapped[str | None]

      Hash of the user's avatar, to avoid re-publishing the same avatar on the
      legacy network



.. py:function:: entrypoint(module_name: str) -> None

   Entrypoint to be used in ``__main__.py`` of
   :term:`legacy modules <Legacy Module>`.

   :param module_name: An importable :term:`Legacy Module`.


