slidge
#
Subpackages#
slidge.core
slidge.core.command
slidge.core.contact
slidge.core.gateway
slidge.core.gateway.base
slidge.core.gateway.caps
slidge.core.gateway.delivery_receipt
slidge.core.gateway.disco
slidge.core.gateway.mam
slidge.core.gateway.muc_admin
slidge.core.gateway.ping
slidge.core.gateway.registration
slidge.core.gateway.search
slidge.core.gateway.session_dispatcher
slidge.core.gateway.vcard_temp
slidge.core.mixins
slidge.core.muc
slidge.core.cache
slidge.core.config
slidge.core.pubsub
slidge.core.session
slidge.plugins
slidge.util
Submodules#
Package Contents#
Classes#
Represents a field of the form that a user will see when registering to the gateway |
|
Results of the search command (search for contacts via Jabber Search) |
|
This class centralizes actions in relation to a specific legacy contact. |
|
Virtual roster of a gateway user, that allows to represent all |
|
Must be subclassed by a plugin to set up various aspects of the XMPP |
|
Abstract base class for generic types. |
|
Abstract base class for generic types. |
|
int([x]) -> integer |
|
Represents a gateway user logged in to the legacy network and performing actions. |
|
A dataclass representing a gateway user |
Attributes#
- class slidge.FormField#
Represents a field of the form that a user will see when registering to the gateway via their XMPP client.
- var: str = ''#
Internal name of the field, will be used to retrieve via
slidge.GatewayUser.registration_form
- private: bool = False#
For sensitive info that should not be displayed on screen while the user types. Forces field_type to “text-private”
- value: str = ''#
Pre-filled value. Will be automatically pre-filled if a registered user modifies their subscription
- dict()#
- __post_init__()#
- __acceptable_options()#
- validate(value)#
Raise appropriate XMPPError if a given value is valid for this field
- Parameters:
value (str) – The value to test
- Returns:
The same value OR a JID if
self.type=jid-single
- get_xml()#
Get the field in slixmpp format
- Returns:
some XML
- class slidge.SearchResult#
Bases:
TableResult
Results of the search command (search for contacts via Jabber Search)
- class slidge.LegacyContact(session, legacy_id, jid_username)#
Bases:
Generic
[slidge.util.types.LegacyUserIdType
],slidge.core.mixins.FullCarbonMixin
,slidge.core.mixins.recipient.ReactionRecipientMixin
,slidge.core.mixins.recipient.ThreadRecipientMixin
This class centralizes actions in relation to a specific legacy contact.
You shouldn’t create instances of contacts manually, but rather rely on
LegacyRoster.by_legacy_id()
to ensure that contact instances are singletons. TheLegacyRoster
instance of a session is accessible through theBaseSession.contacts
attribute.Typically, your plugin should have methods hook to the legacy events and call appropriate methods here to transmit the “legacy action” to the xmpp user. This should look like this:
Use
carbon=True
as a keyword arg for methods to represent an action FROM the user TO the contact, typically when the user uses an official client to do an action such as sending a message or marking as message as read. This will use XEP-0363 to impersonate the XMPP user in order.- Parameters:
session (slidge.core.session.BaseSession) – The session this contact is part of
legacy_id (slidge.util.types.LegacyUserIdType) – The contact’s legacy ID
jid_username (str) – User part of this contact’s ‘puppet’ JID. NB: case-insensitive, and some special characters are not allowed
- property name#
Friendly name of the contact, as it should appear in the user’s roster
- property avatar#
An image that represents this contact
- session: slidge.core.session.BaseSession#
- RESOURCE: str = 'slidge'#
A full JID, including a resource part is required for chat states (and maybe other stuff) to work properly. This is the name of the resource the contacts will use.
- mtype = 'chat'#
- _can_send_carbon = True#
- is_group = False#
- _ONLY_SEND_PRESENCE_CHANGES = True#
- STRIP_SHORT_DELAY = True#
- __repr__()#
Return repr(self).
- __get_subscription_string()#
- _send(stanza, carbon=False, **send_kwargs)#
- Parameters:
stanza (Union[slixmpp.Message, slixmpp.Presence]) –
- get_msg_xmpp_id_up_to(horizon_xmpp_id)#
Return XMPP msg ids sent by this contact up to a given XMPP msg id.
Plugins have no reason to use this, but it is used by slidge core for legacy networks that need to mark all messages as read (most XMPP clients only send a read marker for the latest message).
This has side effects, if the horizon XMPP id is found, messages up to this horizon are not cleared, to avoid sending the same read mark twice.
- Parameters:
horizon_xmpp_id (str) – The latest message
- Returns:
A list of XMPP ids or None if horizon_xmpp_id was not found
- async set_avatar(a, avatar_unique_id=None, blocking=False)#
Set the avatar for this contact
- Parameters:
a (Optional[slidge.util.types.AvatarType]) – Any avatar format supported by slidge
avatar_unique_id (Optional[Union[int, str]]) – If possible, provide a unique ID to cache the avatar. If it is not provided, the SHA-1 of the avatar will be used, unless it is an HTTP url. In this case, the url will be used, along with etag or last modified HTTP headers, to avoid fetching uselessly. Beware of legacy plugin where URLs are not stable.
blocking – if True, will await setting the avatar, if False, launch in a task
- Returns:
- get_avatar()#
- set_vcard(/, full_name = None, given = None, surname = None, birthday = None, phone = None, phones = (), note = None, url = None, email = None, country = None, locality=None)#
- async __broadcast_pubsub_items()#
- async _set_roster(**kw)#
- _send_subscription_request()#
- async on_added_to_roster_no_privilege()#
- unsubscribe()#
Send an “unsubscribe”, “unsubscribed”, “unavailable” presence sequence from this contact to the user, ie, “this contact has removed you from their ‘friends’”.
- async update_info()#
Fetch information about this contact from the legacy network
This is awaited on Contact instantiation, and should be overridden to update the nickname, avatar, vcard [..] of this contact, by making “legacy API calls”.
- async fetch_vcard()#
It the legacy network doesn’t like that you fetch too many profiles on startup, it’s also possible to fetch it here, which will be called when XMPP clients of the user request the vcard, if it hasn’t been fetched before :return:
- class slidge.LegacyRoster(session)#
Bases:
Generic
[slidge.util.types.LegacyUserIdType
,slidge.util.types.LegacyContactType
],slidge.core.mixins.lock.NamedLockMixin
Virtual roster of a gateway user, that allows to represent all of their contacts as singleton instances (if used properly and not too bugged).
Every
BaseSession
instance will have its ownLegacyRoster
instance accessible via theBaseSession.contacts
attribute.Typically, you will mostly use the
LegacyRoster.by_legacy_id()
function to retrieve a contact instance.You might need to override
LegacyRoster.legacy_id_to_jid_username()
and/orLegacyRoster.jid_username_to_legacy_id()
to incorporate some custom logic if you need some characters when translation JID user parts and legacy IDs.- Parameters:
session (slidge.core.session.BaseSession) –
- __repr__()#
Return repr(self).
- __iter__()#
- async __finish_init_contact(legacy_id, jid_username, *args, **kwargs)#
- Parameters:
legacy_id (slidge.util.types.LegacyUserIdType) –
jid_username (str) –
- known_contacts()#
- async by_jid(contact_jid)#
Retrieve a contact by their JID
If the contact was not instantiated before, it will be created using
slidge.LegacyRoster.jid_username_to_legacy_id()
to infer their legacy user ID.- Parameters:
contact_jid (slixmpp.JID) –
- Returns:
- Return type:
slidge.util.types.LegacyContactType
- async by_legacy_id(legacy_id, *args, **kwargs)#
Retrieve a contact by their legacy_id
If the contact was not instantiated before, it will be created using
slidge.LegacyRoster.legacy_id_to_jid_username()
to infer their legacy user ID.- Parameters:
legacy_id (slidge.util.types.LegacyUserIdType) –
args – arbitrary additional positional arguments passed to the contact constructor. Requires subclassing LegacyContact.__init__ to accept those. This is useful for networks where you fetch the contact list and information about these contacts in a single request
kwargs – arbitrary keyword arguments passed to the contact constructor
- Returns:
- Return type:
slidge.util.types.LegacyContactType
- async by_stanza(s)#
Retrieve a contact by the destination of a stanza
See
slidge.Roster.by_legacy_id()
for more info.- Parameters:
s –
- Returns:
- Return type:
- async legacy_id_to_jid_username(legacy_id)#
Convert a legacy ID to a valid ‘user’ part of a JID
Should be overridden for cases where the str conversion of the legacy_id is not enough, e.g., if it is case-sensitive or contains forbidden characters not covered by XEP-0106.
- Parameters:
legacy_id (slidge.util.types.LegacyUserIdType) –
- Return type:
- async jid_username_to_legacy_id(jid_username)#
Convert a JID user part to a legacy ID.
Should be overridden in case legacy IDs are not strings, or more generally for any case where the username part of a JID (unescaped with to the mapping defined by XEP-0106) is not enough to identify a contact on the legacy network.
Default implementation is an identity operation
- Parameters:
jid_username (str) – User part of a JID, ie “user” in “user@example.com”
- Returns:
An identifier for the user on the legacy network.
- Return type:
slidge.util.types.LegacyUserIdType
- async fill()#
Populate slidge’s “virtual roster”.
Override this and in it,
await self.by_legacy_id(contact_id)
for the every legacy contacts of the user for which you’d like to set an avatar, nickname, vcard…Await
Contact.add_to_roster()
in here to add the contact to the user’s XMPP roster.
- class slidge.BaseGateway#
Bases:
slixmpp.ComponentXMPP
,slidge.core.mixins.MessageMixin
Must be subclassed by a plugin to set up various aspects of the XMPP component behaviour, such as its display name or its registration process.
On slidge launch, a singleton is instantiated, and it will be made available to public classes such
LegacyContact
orBaseSession
as the.xmpp
attribute. Since it inherits fromslixmpp.componentxmpp.ComponentXMPP
, this gives you a hand on low-level XMPP interactions via slixmpp plugins, 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.
- REGISTRATION_FIELDS: Collection[slidge.core.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 that wants to register (or modify) their legacy account configuration.
- REGISTRATION_TYPE#
SINGLE_STEP_FORM: 1 step, 1 form, compatible with XEP-0077 (in-band registration)
QRCODE: The registration requires flashing a QR code in an official client. See
BaseGateway.()
TWO_FACTOR_CODE: The registration requires confirming login with a 2FA code
- COMPONENT_TYPE: str | None = ''#
Type of the gateway, should ideally follow https://xmpp.org/registrar/disco-categories.html
- COMPONENT_AVATAR: slidge.util.types.AvatarType | None#
Path, bytes or URL used by the component as an avatar.
- ROSTER_GROUP: str = 'slidge'#
Roster entries added by the plugin in the user’s roster will be part of the group specified here.
- SEARCH_FIELDS: Sequence[slidge.core.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()
, effectively restricting search to registered users by default.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.
- 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.
- 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).
- REGISTRATION_2FA_TITLE = 'Enter your 2FA code'#
- REGISTRATION_2FA_INSTRUCTIONS = 'You should have received something via email or SMS, or something'#
- REGISTRATION_QR_INSTRUCTIONS = 'Flash this code or follow this link'#
- 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#
- jid: slixmpp.JID#
- mtype: slixmpp.types.MessageTypes = 'chat'#
- is_group = False#
- _can_send_carbon = False#
- __register_commands()#
- __exception_handler(loop, context)#
Called when a task created by loop.create_task() raises an Exception
- Parameters:
loop (asyncio.AbstractEventLoop) –
context –
- Returns:
- __register_slixmpp_events()#
- async __on_group_chat_error(msg)#
- Parameters:
msg (slixmpp.Message) –
- async __on_session_start(event)#
- async __login_wrap(session)#
- Parameters:
session (slidge.core.session.BaseSession) –
- _send(stanza, **send_kwargs)#
- Parameters:
stanza (Union[slixmpp.Message, slixmpp.Presence]) –
- async _on_user_register(iq)#
- Parameters:
iq (slixmpp.Iq) –
- async _on_user_unregister(iq)#
- Parameters:
iq (slixmpp.Iq) –
- raise_if_not_allowed_jid(jid)#
- Parameters:
jid (slixmpp.JID) –
- send_raw(data)#
Send raw data across the stream.
- Parameters:
data (string) – Any bytes or utf-8 string value.
- get_session_from_jid(j)#
- Parameters:
j (slixmpp.JID) –
- async get_muc_from_stanza(iq)#
- Parameters:
iq (Union[slixmpp.Iq, slixmpp.Message]) –
- Return type:
- exception(exception)#
Called when a task created by slixmpp’s internal (eg, on slix events) raises an Exception.
Stop the event loop and exit on unhandled exception.
The default
slixmpp.basexmpp.BaseXMPP
behaviour is just to log the exception, but we want to avoid undefined behaviour.
- re_login(session)#
- Parameters:
session (slidge.core.session.BaseSession) –
- async make_registration_form(_jid, _node, _ifrom, iq)#
- Parameters:
iq (slixmpp.Iq) –
- async user_prevalidate(ifrom, form_dict)#
Pre validate a registration form using the content of self.REGISTRATION_FIELDS before passing it to the plugin custom validation logic.
- async validate(user_jid, registration_form)#
Validate a registration form from a user.
Since XEP-0077 is pretty limited in terms of validation, it is OK to validate anything that looks good here and continue the legacy auth process via direct messages to the user (using
BaseGateway.input()
for instance).- Parameters:
user_jid (slixmpp.JID) – JID of the user that has just registered
registration_form (dict[str, Optional[str]]) – A dict where keys are the
FormField.var
attributes of theBaseGateway.REGISTRATION_FIELDS
iterable
- async unregister_user(user)#
- Parameters:
user (slidge.util.db.GatewayUser) –
- async unregister(user)#
Optionally override this if you need to clean additional stuff after a user has been removed from the permanent user_store.
You may need to manually logout the legacy session in here,
Session.logout()
will not be called automatically.- Parameters:
user (slidge.util.db.GatewayUser) –
- async input(jid, text=None, mtype='chat', **msg_kwargs)#
Request arbitrary user input using a simple chat message, and await the result.
You shouldn’t need to call directly bust instead use
BaseSession.input()
to directly target a user.NB: When using this, the next message that the user sent to the component will not be transmitted to
BaseGateway.on_gateway_message()
, but rather intercepted. Await the coroutine to get its content.- Parameters:
jid (slixmpp.JID) – The JID we want input from
text – A prompt to display for the user
mtype (slixmpp.types.MessageTypes) – Message type
- Returns:
The user’s reply
- Return type:
- async send_qr(text, **msg_kwargs)#
Sends a QR Code to a JID
- Parameters:
text (str) – 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.
- abstract async validate_two_factor_code(user, code)#
Called when the user enters their 2FA code.
Should raise the appropriate
XMPPError
if the login fails- Parameters:
user (slidge.util.db.GatewayUser) – The gateway user whose registration is pending Use their
.bare_jid
and/or``.registration_form`` attributes to get what you needcode (str) – The code they entered, either via “chatbot” message or adhoc command
- abstract async get_qr_text(user)#
Plugins should call this to complete registration with QR codes
- Parameters:
user (slidge.util.db.GatewayUser) – The not-yet-fully-registered GatewayUser. Use its
.bare_jid
and/or``.registration_form`` attributes to get what you need- Return type:
- async confirm_qr(user_bare_jid, exception=None)#
Plugins should call this to complete registration with QR codes
- shutdown()#
Called by the slidge entrypoint on normal exit.
Sends offline presences from all contacts of all user sessions and from the gateway component itself. No need to call this manually,
slidge.__main__.main()
should take care of it.
- class slidge.LegacyBookmarks(session)#
Bases:
Generic
[slidge.util.types.LegacyGroupIdType
,slidge.util.types.LegacyMUCType
],slidge.core.mixins.lock.NamedLockMixin
Abstract base class for generic types.
A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:
class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc.
This class can then be used as follows:
def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default
- Parameters:
session (slidge.core.session.BaseSession) –
- property user_nick#
- __iter__()#
- __repr__()#
Return repr(self).
- async __finish_init_muc(legacy_id, jid)#
- Parameters:
legacy_id (slidge.util.types.LegacyGroupIdType) –
jid (slixmpp.JID) –
- async legacy_id_to_jid_local_part(legacy_id)#
- Parameters:
legacy_id (slidge.util.types.LegacyGroupIdType) –
- async by_jid(jid)#
- Parameters:
jid (slixmpp.JID) –
- Return type:
slidge.util.types.LegacyMUCType
- async by_legacy_id(legacy_id)#
- Parameters:
legacy_id (slidge.util.types.LegacyGroupIdType) –
- Return type:
slidge.util.types.LegacyMUCType
- async fill()#
Establish a user’s known groups.
This has to be overridden in plugins with group support and at the minimum, this should
await self.by_legacy_id(group_id)
for all the groups a user is part of.Ideally, set the group subject, friendly, number, etc. in this method
Slidge internals will call this on successful
BaseSession.login()
- class slidge.LegacyMUC(session, legacy_id, jid)#
Bases:
Generic
[slidge.util.types.LegacyGroupIdType
,slidge.util.types.LegacyMessageType
,slidge.util.types.LegacyParticipantType
,slidge.util.types.LegacyUserIdType
],slidge.core.mixins.lock.NamedLockMixin
,slidge.core.mixins.disco.ChatterDiscoMixin
,slidge.core.mixins.recipient.ReactionRecipientMixin
,slidge.core.mixins.recipient.ThreadRecipientMixin
Abstract base class for generic types.
A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:
class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc.
This class can then be used as follows:
def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default
- Parameters:
session (slidge.core.session.BaseSession) –
legacy_id (slidge.util.types.LegacyGroupIdType) –
jid (slixmpp.JID) –
- property user_nick#
- property user_nick_non_none#
- property avatar#
- property name#
- property subject#
- property user_muc_jid#
- subject_date: datetime.datetime | None#
- max_history_fetch = 100#
- description = ''#
- type#
- is_group = True#
- DISCO_TYPE = 'text'#
- DISCO_CATEGORY = 'conference'#
- DISCO_NAME = 'unnamed-room'#
- STABLE_ARCHIVE = False#
Because legacy events like reactions, editions, etc. don’t all map to a stanza with a proper legacy ID, slidge usually cannot guarantee the stability of the archive across restarts.
Set this to True if you know what you’re doing, but realistically, this can’t be set to True until archive is permanently stored on disk by slidge.
This is just a flag on archive responses that most clients ignore anyway.
- _ALL_INFO_FILLED_ON_STARTUP = False#
Set this to true if the fill_participants() / fill_participants() design does not fit the legacy API, ie, no lazy loading of the participant list and history.
- __repr__()#
Return repr(self).
- async __fill_participants()#
- async __fill_history()#
- async __set_avatar(a)#
- Parameters:
a (Optional[slidge.util.types.AvatarType]) –
- __get_vcard()#
- async send_avatar(iq)#
- Parameters:
iq (slixmpp.Iq) –
- Parameters:
p (slixmpp.Presence) –
- async backfill(oldest_message_id=None, oldest_message_date=None)#
Override this if the legacy network provide server-side archive. In it, send history messages using
self.get_participant().send*
, with thearchive_only=True
kwarg.You only need to fetch messages older than
oldest_message_id
.- Parameters:
oldest_message_id (Optional[slidge.util.types.LegacyMessageType]) – The oldest message ID already present in the archive
oldest_message_date (Optional[datetime.datetime]) – The oldest message date already present in the archive
- async update_info()#
Fetch information about this group from the legacy network
This is awaited on MUC instantiation, and should be overridden to update the attributes of the group chat, like title, subject, number of participants etc.
- features()#
- async extended_features()#
- _make_subject_message(user_full_jid)#
- Parameters:
user_full_jid (slixmpp.JID) –
- shutdown()#
- user_full_jids()#
- _legacy_to_xmpp(legacy_id)#
- Parameters:
legacy_id (slidge.util.types.LegacyMessageType) –
- async echo(msg, legacy_msg_id=None)#
- Parameters:
msg (slixmpp.Message) –
legacy_msg_id (Optional[slidge.util.types.LegacyMessageType]) –
- _send_room_presence(user_full_jid=None)#
- Parameters:
user_full_jid (Optional[slixmpp.JID]) –
- async join(join_presence)#
- Parameters:
join_presence (slixmpp.Presence) –
- async get_user_participant(**kwargs)#
Get the participant representing the gateway user
- Parameters:
kwargs – additional parameters for the
Participant
construction (optional)- Returns:
- Return type:
slidge.util.types.LegacyParticipantType
- __store_participant(p)#
- Parameters:
p (slidge.util.types.LegacyParticipantType) –
- async get_participant(nickname, raise_if_not_found=False, fill_first=False, **kwargs)#
Get a participant by their nickname.
In non-anonymous groups, you probably want to use
LegacyMUC.get_participant_by_contact()
instead.- Parameters:
nickname (str) – Nickname of the participant (used as resource part in the MUC)
raise_if_not_found – Raise XMPPError(“item-not-found”) if they are not in the participant list (internal use by slidge, plugins should not need that)
fill_first – Ensure
LegacyMUC.fill_participants()
has been called first (internal use by slidge, plugins should not need that)kwargs – additional parameters for the
Participant
construction (optional)
- Returns:
- Return type:
slidge.util.types.LegacyParticipantType
- get_system_participant()#
Get a pseudo-participant, representing the room itself
Can be useful for events that cannot be mapped to a participant, e.g. anonymous moderation events, or announces from the legacy service :return:
- async get_participant_by_contact(c, **kwargs)#
Get a non-anonymous participant.
This is what should be used in non-anonymous groups ideally, to ensure that the Contact jid is associated to this participant
- Parameters:
c (slidge.core.contact.LegacyContact) – The
LegacyContact
instance corresponding to this contactkwargs – additional parameters for the
Participant
construction (optional)
- Returns:
- Return type:
slidge.util.types.LegacyParticipantType
- async get_participant_by_legacy_id(legacy_id, **kwargs)#
- Parameters:
legacy_id (slidge.util.types.LegacyUserIdType) –
- Return type:
slidge.util.types.LegacyParticipantType
- async get_participants()#
Get all known participants of the group, ensure
LegacyMUC.fill_participants()
has been awaited once before. Plugins should not use that, internal slidge use only. :return:
- remove_participant(p)#
This ho :param p: :return:
- Parameters:
p (slidge.util.types.LegacyParticipantType) –
- async fill_participants()#
In here, call self.get_participant(), self.get_participant_by_contact(), of self.get_user_participant() to make an initial list of participants.
- async _fill_history(full_jid, maxchars=None, maxstanzas=None, seconds=None, since=None)#
Old-style history join (internal slidge use)
- Parameters:
full_jid (slixmpp.JID) –
maxchars (Optional[int]) –
maxstanzas (Optional[int]) –
seconds (Optional[int]) –
since (Optional[datetime.datetime]) –
- Returns:
- async send_mam(iq)#
- Parameters:
iq (slixmpp.Iq) –
- async send_mam_metadata(iq)#
- Parameters:
iq (slixmpp.Iq) –
- class slidge.LegacyParticipant(muc, nickname=None, is_user=False, is_system=False)#
Bases:
slidge.core.mixins.PresenceMixin
,slidge.core.mixins.MessageMixin
,slidge.core.mixins.ChatterDiscoMixin
- Parameters:
muc (slidge.core.muc.room.LegacyMUC) –
nickname (Optional[str]) –
- property DISCO_NAME#
- mtype: slixmpp.types.MessageTypes = 'groupchat'#
- _can_send_carbon = False#
- USE_STANZA_ID = True#
- STRIP_SHORT_DELAY = False#
- __repr__()#
Return repr(self).
- _make_presence(*, last_seen=None, status_codes=None, user_full_jid=None, **presence_kwargs)#
- Parameters:
last_seen (Optional[datetime.datetime]) –
user_full_jid (Optional[slixmpp.JID]) –
- __send_presence_if_needed(stanza, full_jid, archive_only)#
- Parameters:
stanza (Union[slixmpp.Message, slixmpp.Presence]) –
full_jid (slixmpp.JID) –
archive_only (bool) –
- _send(stanza, full_jid=None, archive_only=False, **send_kwargs)#
- Parameters:
stanza (Union[slixmpp.Message, slixmpp.Presence]) –
full_jid (Optional[slixmpp.JID]) –
- mucadmin_item()#
- send_initial_presence(full_jid, nick_change=False, presence_id=None)#
Called when the user joins a MUC, as a mechanism to indicate to the joining XMPP client the list of “participants”.
Can be called this to trigger a “participant has joined the group” event.
- Parameters:
full_jid (slixmpp.JID) – Set this to only send to a specific user XMPP resource.
nick_change – Used when the user joins and the MUC renames them (code 210)
presence_id (Optional[str]) – set the presence ID. used internally by slidge
- leave()#
To be called only by room. To remove a participant, call Room.remove_participant(self) instead.
- get_disco_info()#
- class slidge.MucType#
-
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
Initialize self. See help(type(self)) for accurate signature.
- GROUP = 0#
- CHANNEL = 1#
- class slidge.BaseSession(user)[source]#
Bases:
Generic
[slidge.util.types.LegacyMessageType
,slidge.util.types.RecipientType
]Represents a gateway user logged in to the legacy network and performing actions.
Will be instantiated automatically when a user sends an online presence to the gateway component, as per XEP-0100.
Must be subclassed for a functional slidge plugin.
- Parameters:
user (slidge.util.db.GatewayUser) –
- property logged#
- sent: slidge.util.BiDict[slidge.util.types.LegacyMessageType, str]#
Since we cannot set the XMPP ID of messages sent by XMPP clients, we need to keep a mapping between XMPP IDs and legacy message IDs if we want to further refer to a message that was sent by the user. This also applies to ‘carboned’ messages, ie, messages sent by the user from the official client of a legacy network.
- xmpp: slidge.core.gateway.BaseGateway#
The gateway instance singleton. Use it for low-level XMPP calls or custom methods that are not session-specific.
- http: aiohttp.ClientSession#
- 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).
- __reset_ready()#
- __repr__()#
Return repr(self).
- shutdown()#
- static legacy_msg_id_to_xmpp_msg_id(legacy_msg_id)#
Convert a legacy msg ID to a valid XMPP msg ID. Needed for read marks and message corrections.
The default implementation just converts the legacy ID to a
str
, but this should be overridden in case some characters needs to be escaped, or to add some additional, legacy network-specific logic.- Parameters:
legacy_msg_id (slidge.util.types.LegacyMessageType) –
- Returns:
Should return a string that is usable as an XMPP stanza ID
- Return type:
- static xmpp_msg_id_to_legacy_msg_id(i)#
Convert a legacy XMPP ID to a valid XMPP msg ID. Needed for read marks and message corrections.
The default implementation just converts the legacy ID to a
str
, but this should be overridden in case some characters needs to be escaped, or to add some additional, legacy network-specific logic.The default implementation is an identity function
- Parameters:
i (str) – The XMPP stanza ID
- Returns:
An ID that can be used to identify a message on the legacy network
- Return type:
slidge.util.types.LegacyMessageType
- raise_if_not_logged()#
- classmethod _from_user_or_none(user)#
- classmethod from_user(user)#
- classmethod from_stanza(s)#
Get a user’s
LegacySession
using the “from” field of a stanzaMeant to be called from
BaseGateway
only.- Parameters:
s –
- Returns:
- Return type:
- classmethod from_jid(jid)#
Get a user’s
LegacySession
using its jidMeant to be called from
BaseGateway
only.- Parameters:
jid (slixmpp.JID) –
- Returns:
- Return type:
- async classmethod kill_by_jid(jid)#
Terminate a user session.
Meant to be called from
BaseGateway
only.- Parameters:
jid (slixmpp.JID) –
- Returns:
- async send_from_msg(m)#
Meant to be called from
BaseGateway
only.- Parameters:
m (slixmpp.Message) –
- Returns:
- async __xmpp_to_legacy_thread(msg, recipient)#
- Parameters:
msg (slixmpp.Message) –
recipient (slidge.util.types.RecipientType) –
- __ack(msg)#
- Parameters:
msg (slixmpp.Message) –
- async __get_entity(m)#
- Parameters:
m (slixmpp.Message) –
- Return type:
slidge.util.types.RecipientType
- async active_from_msg(m)#
Meant to be called from
BaseGateway
only.- Parameters:
m (slixmpp.Message) –
- Returns:
- async inactive_from_msg(m)#
Meant to be called from
BaseGateway
only.- Parameters:
m (slixmpp.Message) –
- Returns:
- async composing_from_msg(m)#
Meant to be called from
BaseGateway
only.- Parameters:
m (slixmpp.Message) –
- Returns:
- async paused_from_msg(m)#
Meant to be called from
BaseGateway
only.- Parameters:
m (slixmpp.Message) –
- Returns:
- async displayed_from_msg(m)#
Meant to be called from
BaseGateway
only.- Parameters:
m (slixmpp.Message) –
- Returns:
- async correct_from_msg(m)#
- Parameters:
m (slixmpp.Message) –
- async react_from_msg(m)#
- Parameters:
m (slixmpp.Message) –
- async retract_from_msg(m)#
- Parameters:
m (slixmpp.Message) –
- async join_groupchat(p)#
- Parameters:
p (slixmpp.Presence) –
- async __get_contact_or_ignore_or_raise(p)#
- Parameters:
p (slixmpp.Presence) –
- async on_subscribe(p)#
Called when receiving a “subscribe” presence, which is more or less a “friend request”.
Right now, this is mostly a placeholder for a future friend request workflow, but is useful to ensure avatars and nicks ard broadcast when XEP-0356 is not available for slidge
- Parameters:
p (slixmpp.Presence) –
- async on_subscribed(p)#
Called when receiving a “subscribed” presence, confirming that a contact is in the roster.
Right now, this is mostly a placeholder for a future friend request workflow, but is useful to ensure avatars and nicks ard broadcast when XEP-0356 is not available for slidge
- Parameters:
p (slixmpp.Presence) –
- send_gateway_status(status=None, show=Optional[PresenceShow], **kwargs)#
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 (Optional[str]) – 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, **msg_kwargs)#
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
- async input(text, **msg_kwargs)#
Request user input via direct messages.
Wraps call to
BaseSession.input()
- Parameters:
text (str) – The prompt to send to the user
msg_kwargs – Extra attributes
- Returns:
- async send_qr(text)#
Sends a QR code generated from ‘text’ via HTTP Upload and send the URL to
self.user
- Parameters:
text (str) – Text to encode as a QR code
- abstract async login()#
Login 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’”
- Return type:
Optional[str]
- abstract async logout()#
Logout the gateway user from the legacy network.
Called on user unregistration and gateway shutdown.
- re_login()#
Logout then re-login
No reason to override this
- abstract async send_text(chat, text, *, reply_to_msg_id=None, reply_to_fallback_text=None, reply_to=None, thread=None)#
Triggered when the user sends a text message from XMPP to a bridged entity, e.g. to
translated_user_name@slidge.example.com
, ortranslated_group_name@slidge.example.com
Override this and implement sending a message to the legacy network in this method.
- Parameters:
text (str) – Content of the message
chat (slidge.util.types.RecipientType) – RecipientType of the message.
LegacyContact
instance for 1:1 chat,MUC
instance for groups.reply_to_msg_id (Optional[slidge.util.types.LegacyMessageType]) – A legacy message ID if the message references (quotes) another message (XEP-0461)
reply_to_fallback_text (Optional[str]) – Content of the quoted text. Not necessarily set by XMPP clients
reply_to (Optional[slidge.util.types.Sender]) – Author of the quoted message.
LegacyContact
instance for 1:1 chat,LegacyParticipant
instance for groups. If None, should be interpreted as a self-reply if reply_to_msg_id is not None.thread (Optional[slidge.util.types.LegacyThreadType]) –
- Returns:
An ID of some sort that can be used later to ack and mark the message as read by the user
- Return type:
Optional[slidge.util.types.LegacyMessageType]
- abstract async send_file(chat, url, *, http_response, reply_to_msg_id=None, reply_to_fallback_text=None, reply_to=None, thread=None)#
Triggered when the user has sends a file using HTTP Upload (XEP-0363)
- Parameters:
url (str) – URL of the file
chat (slidge.util.types.RecipientType) – See
BaseSession.send_text()
http_response (aiohttp.ClientResponse) – The HTTP GET response object on the URL
reply_to_msg_id (Optional[slidge.util.types.LegacyMessageType]) – See
BaseSession.send_text()
reply_to_fallback_text (Optional[str]) – See
BaseSession.send_text()
reply_to (Optional[Union[slidge.core.contact.LegacyContact, slidge.core.muc.participant.LegacyParticipant]]) – See
BaseSession.send_text()
thread (Optional[slidge.util.types.LegacyThreadType]) –
- Returns:
An ID of some sort that can be used later to ack and mark the message as read by the user
- Return type:
Optional[slidge.util.types.LegacyMessageType]
- abstract async active(c, thread=None)#
Triggered when the user sends an ‘active’ chat state to the legacy network (XEP-0085)
- Parameters:
c (slidge.util.types.RecipientType) – RecipientType of the active chat state
thread (Optional[slidge.util.types.LegacyThreadType]) –
- abstract async inactive(c, thread=None)#
Triggered when the user sends an ‘inactive’ chat state to the legacy network (XEP-0085)
- Parameters:
c (slidge.util.types.RecipientType) –
thread (Optional[slidge.util.types.LegacyThreadType]) –
- abstract async composing(c, thread=None)#
Triggered when the user starts typing in the window of a legacy contact (XEP-0085)
- Parameters:
c (slidge.util.types.RecipientType) –
thread (Optional[slidge.util.types.LegacyThreadType]) –
- abstract async paused(c, thread=None)#
Triggered when the user pauses typing in the window of a legacy contact (XEP-0085)
- Parameters:
c (slidge.util.types.RecipientType) –
thread (Optional[slidge.util.types.LegacyThreadType]) –
- abstract async displayed(c, legacy_msg_id, thread=None)#
Triggered when the user reads a message sent by a legacy contact. (XEP-0333)
This is only possible if a valid
legacy_msg_id
was passed when transmitting a message from a contact to the user inLegacyContact.sent_text()
orslidge.LegacyContact.send_file()
.- Parameters:
legacy_msg_id (slidge.util.types.LegacyMessageType) – Identifier of the message, passed to
slidge.LegacyContact.send_text()
orslidge.LegacyContact.send_file()
c (slidge.util.types.RecipientType) –
thread (Optional[slidge.util.types.LegacyThreadType]) –
- abstract async correct(c, text, legacy_msg_id, thread=None)#
Triggered when the user corrected a message using XEP-0308
This is only possible if a valid
legacy_msg_id
was passed when transmitting a message from a contact to the user inLegacyContact.send_text()
orslidge.LegacyContact.send_file()
.- Parameters:
text (str) –
legacy_msg_id (slidge.util.types.LegacyMessageType) –
c (slidge.util.types.RecipientType) –
thread (Optional[slidge.util.types.LegacyThreadType]) –
- Return type:
Optional[slidge.util.types.LegacyMessageType]
- abstract async search(form_values)#
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 (dict[str, str]) – search query, defined for a specific plugin by overriding in
BaseGateway.SEARCH_FIELDS
- Returns:
- Return type:
Optional[slidge.core.command.base.SearchResult]
- abstract async react(c, legacy_msg_id, emojis, thread=None)#
Triggered when the user sends message reactions (XEP-0444).
- Parameters:
legacy_msg_id (slidge.util.types.LegacyMessageType) – ID of the message the user reacts to
emojis (list[str]) – Unicode characters representing reactions to the message
legacy_msg_id
. An empty string means “no reaction”, ie, remove all reactions if any were present beforec (slidge.util.types.RecipientType) – Contact or MUC the reaction refers to
thread (Optional[slidge.util.types.LegacyThreadType]) –
- abstract async retract(c, legacy_msg_id, thread=None)#
Triggered when the user retracts (XEP-0424) a message.
- Parameters:
legacy_msg_id (slidge.util.types.LegacyMessageType) – Legacy ID of the retracted message
c (slidge.util.types.RecipientType) – The contact this retraction refers to
thread (Optional[slidge.util.types.LegacyThreadType]) –
- async get_contact_or_group_or_participant(jid)#
- Parameters:
jid (slixmpp.JID) –
- class slidge.GatewayUser[source]#
A dataclass representing a gateway user
- property jid: slixmpp.JID#
The user’s (bare) JID
- Returns:
- Return type:
slixmpp.JID
- registration_date: datetime.datetime | None#
- __hash__()#
Return hash(self).
- __repr__()#
Return repr(self).
- __post_init__()#
- get(field, default='')#
Get fields from the registration form (required to comply with slixmpp backend protocol)
- commit()#
- exception slidge.XMPPError(condition='undefined-condition', text='', by=None, etype=None)[source]#
Bases:
slixmpp.exceptions.XMPPError
Improvements over Base: include by, automatically determine appropriate etype if not given
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
condition (Conditions) –
by (Optional[slixmpp.types.JidStr]) –
etype (Optional[ErrorTypes]) –