slidge

The main slidge package.

Contains importable classes for a minimal function Legacy Module.

Submodules

Package Contents

class slidge.BaseGateway

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

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 LegacyContact or 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 COMPONENT_NAME WELCOME_MESSAGE.

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

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

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

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

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.

COMPONENT_NAME: str = NotImplemented

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

COMPONENT_TYPE: str = ''

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

COMPONENT_AVATAR: slidge.util.types.Avatar | pathlib.Path | str | None = None

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

REGISTRATION_FIELDS: collections.abc.Sequence[slidge.command.base.FormField]

Iterable of fields presented to the gateway user when registering using XEP-0077 extended by XEP-0004.

REGISTRATION_INSTRUCTIONS: str = 'Enter your credentials'

The text presented to a user who wants to register (or modify) their legacy account configuration.

REGISTRATION_TYPE: slidge.command.register.RegistrationType

This attribute determines how users register to the gateway, ie, how they login to the 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 RegistrationType for more details.

ROSTER_GROUP: str = 'slidge'

Name of the group assigned to a LegacyContact automagically added to the User’s roster with LegacyContact.add_to_roster().

WELCOME_MESSAGE = "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.

SEARCH_FIELDS: 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 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.

SEARCH_TITLE: str = 'Search for legacy contacts'

Title of the search form.

SEARCH_INSTRUCTIONS: str = ''

Instructions of the search form.

MARK_ALL_MESSAGES = False

Set this to True for legacy networks 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).

PROPER_RECEIPTS = 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.

GROUPS = False

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

SPACES = False

This must be set to True if this gateway supports spaces, cf XEP-0503.

DB_POOL_SIZE: int = 5

Size of the queue pool for sqlalchemy engine. Typically, when using python async libraries, this does not need to be changed. Change that if your gateway use separate threads to call into slidge. The value of this parameter should be equal or greater than the potential number of threads.

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

Validate a user’s initial registration form.

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

If REGISTRATION_TYPE is a 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 REGISTRATION_TYPE too, since the first step is always a form. If REGISTRATION_FIELDS is an empty list (ie, it declares no FormField), the “form” is effectively a confirmation dialog displaying REGISTRATION_INSTRUCTIONS.

Parameters:
  • user_jid – JID of the user that has just registered

  • registration_form – A dict where keys are the FormField.var attributes of the BaseGateway.REGISTRATION_FIELDS iterable. This dict can be modified and will be accessible as the legacy_module_data of the

:returnA 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.

abstractmethod validate_two_factor_code(user: slidge.db.GatewayUser, code: str) slidge.db.meta.JSONSerializable | None
Async:

Called when the user enters their 2FA code.

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

Only used when REGISTRATION_TYPE is RegistrationType.TWO_FACTOR_CODE.

Parameters:
  • user – The GatewayUser whose registration is pending Use their GatewayUser.bare_jid and/or registration_form attributes to get what you need.

  • code – The code they entered, either via “chatbot” message or adhoc command

:returnA dict which keys and values will be added to the persistent “legacy_module_data”

for this user.

abstractmethod get_qr_text(user: slidge.db.GatewayUser) str
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 GatewayUser.

Only used in when BaseGateway.REGISTRATION_TYPE is RegistrationType.QRCODE.

Parameters:

user – The GatewayUser whose registration is pending Use their GatewayUser.bare_jid and/or registration_form attributes to get what you need.

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

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 BaseGateway.REGISTRATION_TYPE is RegistrationType.QRCODE.

Parameters:
  • user_bare_jid – The bare JID of the almost-registered GatewayUser instance

  • exception – Optionally, an XMPPError to be raised to not confirm QR code flashing.

  • legacy_data – dict which keys and values will be added to the persistent “legacy_module_data” for this user.

async unregister(session: slidge.util.types.SessionType) None

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 BaseSession.logout().

Parameters:

session – The session of the user who just unregistered

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

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

You shouldn’t need to call this directly bust instead use BaseSession.input() to directly target a user.

Parameters:
  • jid – The JID we want input from

  • text – A prompt to display for the user

  • mtype – Message type

Returns:

The user’s reply

async send_qr(text: str, **msg_kwargs: Any) None

Sends a QR Code to a JID

You shouldn’t need to call directly bust instead use BaseSession.send_qr() to directly target a user.

Parameters:
  • text – The text that will be converted to a QR Code

  • msg_kwargs – Optional additional arguments to pass to BaseGateway.send_file(), such as the recipient of the QR, code

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 XMPP Entity.

Parameters:
  • muc – the muc the user is invited to

  • reason – a text explaining why the user should join this muc

  • password – maybe this will make sense later? not sure

  • send_kwargs – additional kwargs to be passed to _send() (internal use by slidge)

active(**kwargs: object) None

Send an “active” chat state (XEP-0085) from this XMPP Entity.

composing(**kwargs: object) None

Send a “composing” (ie “typing notification”) chat state (XEP-0085) from this XMPP Entity.

paused(**kwargs: object) None

Send a “paused” (ie “typing paused notification”) chat state (XEP-0085) from this XMPP Entity.

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 XMPP Entity.

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 XMPP Entity.

ack(legacy_msg_id: str, **kwargs: object) None

Send an “acknowledged” message marker (XEP-0333) from this XMPP Entity.

Parameters:

legacy_msg_id – The message this marker refers to

received(legacy_msg_id: str, **kwargs: object) None

Send a “received” message marker (XEP-0333) from this XMPP Entity. If called on a LegacyContact, also send a delivery receipt marker (XEP-0184).

Parameters:

legacy_msg_id – The message this marker refers to

displayed(legacy_msg_id: str, **kwargs: object) None

Send a “displayed” message marker (XEP-0333) from this XMPP Entity.

Parameters:

legacy_msg_id – The message this marker refers to

async 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]]

Send a single file from this XMPP Entity.

Parameters:
  • attachment – The file to send. Ideally, a LegacyAttachment with a unique legacy_file_id attribute set, to optimise potential future reuses. It can also be: - a pathlib.Path instance to point to a local file, or - a str, representing a fetchable HTTP URL.

  • legacy_msg_id – If you want to be able to transport read markers from the gateway user to the legacy network, specify this

  • reply_to – Quote another message (XEP-0461)

  • when – when the file was sent, for a “delay” tag (XEP-0203)

  • thread

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 XMPP Entity.

Parameters:
  • body – Content of the message

  • legacy_msg_id – If you want to be able to transport read markers from the gateway user to the legacy network, specify this

  • when – when the message was sent, for a “delay” tag (XEP-0203)

  • reply_to – Quote another message (XEP-0461)

  • hints

  • thread

  • carbon – (only used if called on a LegacyContact) Set this to True if this is actually a message sent to the LegacyContact by the User. Use this to synchronize outgoing history for legacy official apps.

  • correction – whether this message is a correction or not

  • 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.

  • link_previews – A little of sender (or server, or gateway)-generated previews of URLs linked in the body.

  • 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()

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 XMPP Entity.

Uses last message correction (XEP-0308)

Parameters:
  • new_text – New content of the message

  • legacy_msg_id – The legacy message ID of the message to correct

  • when – when the message was sent, for a “delay” tag (XEP-0203)

  • reply_to – Quote another message (XEP-0461)

  • hints

  • thread

  • 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.

  • 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()

  • 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.

  • link_previews – A little of sender (or server, or gateway)-generated previews of URLs linked in the body.

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

Send a reaction (XEP-0444) from this XMPP Entity.

Parameters:
  • legacy_msg_id – The message which the reaction refers to.

  • emojis – An iterable of emojis used as reactions

  • thread

retract(legacy_msg_id: str, thread: str | None = None, **kwargs: object) None

Send a message retraction (XEP-0424) from this XMPP Entity.

Parameters:
  • legacy_msg_id – Legacy ID of the message to delete

  • thread

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

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

The session of a registered 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 Legacy Module.

xmpp: BaseGateway[Self]

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

MESSAGE_IDS_ARE_THREAD_IDS = 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).

SPECIAL_MSG_ID_PREFIX: str | None = None

If you set this, XMPP message IDs starting with this won’t be converted to legacy ID, but passed as is to 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.

user

The slidge user.

abstractmethod login() str | None
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.

Returns:

Optionally, a text to use as the gateway status, e.g., “Connected as ‘dude@legacy.network’”

abstractmethod logout() None
Async:

Logs out the gateway user from the legacy network.

Called on gateway shutdown.

abstractmethod on_presence(resource: str, show: slidge.util.types.PseudoPresenceShow, status: str, resources: dict[str, slixmpp.types.ResourceDict], merged_resource: slixmpp.types.ResourceDict | None) None
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.

Parameters:
  • resource – The XMPP client identifier, arbitrary string.

  • show – The presence <show>, if available. If the resource is just ‘available’ without any <show> element, this is an empty str.

  • status – A status message, like a deeply profound quote, eg, “Roses are red, violets are blue, [INSERT JOKE]”.

  • resources – A summary of all the resources for this user.

  • merged_resource – A global presence for the user account, following rules described in merge_resources()

Async:

Triggered when the user uses Jabber Search (XEP-0055) on the component

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

Parameters:

form_values – search query, defined for a specific plugin by overriding in BaseGateway.SEARCH_FIELDS

Returns:

abstractmethod on_avatar(bytes_: bytes | None, hash_: str | None, type_: str | None, width: int | None, height: int | None) None
Async:

Triggered when the user uses modifies their avatar via XEP-0084.

Parameters:
  • 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.

  • hash – The SHA1 hash of the avatar data. This is an identifier of the avatar.

  • type – The MIME type of the avatar.

  • width – The width of the avatar image.

  • height – The height of the avatar image.

abstractmethod on_create_group(name: str, contacts: list[slidge.util.types.LegacyContactType]) str
Async:

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

Parameters:
  • name – Name of the group

  • contacts – list of contacts that should be members of the group

abstractmethod on_leave_space(space_legacy_id: str) None
Async:

Triggered when the user sends a request to leave a XEP-0503 space.

Parameters:

space_legacy_id – The legacy ID of the space to leave

abstractmethod on_preferences(previous: dict[str, Any], new: dict[str, Any]) None
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.

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”, …

Parameters:
  • status – A status message

  • show – Presence stanza ‘show’ element. I suggest using “dnd” to show that the gateway is not fully functional

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”, …

Parameters:

text – A text

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.

Parameters:
  • muc

  • reason

  • password

async input(text: str, **msg_kwargs: Any) str

Request user input via direct messages from the gateway component.

Wraps call to BaseSession.input()

Parameters:
  • text – The prompt to send to the user

  • msg_kwargs – Extra attributes

Returns:

async send_qr(text: str) None

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

Parameters:

text – Text to encode as a QR code

class slidge.GatewayUser

Bases: slidge.db.meta.Base

A user, registered to the gateway component.

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

Arbitrary non-relational data that legacy modules can use

avatar_hash: sqlalchemy.orm.Mapped[str | None]

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

slidge.entrypoint(module_name: str) None

Entrypoint to be used in __main__.py of legacy modules.

Parameters:

module_name – An importable Legacy Module.