Coverage for slidge/util/types.py: 97%
266 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-12-01 19:36 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-12-01 19:36 +0000
1"""
2Typing stuff
3"""
5from __future__ import annotations
7import contextlib
8import re
9import warnings
10from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
11from dataclasses import dataclass, fields
12from datetime import datetime
13from enum import IntEnum
14from functools import cached_property
15from pathlib import Path
16from typing import (
17 IO,
18 TYPE_CHECKING,
19 Any,
20 Literal,
21 NamedTuple,
22 Protocol,
23 TypeIs,
24 TypeVar,
25 Union,
26 runtime_checkable,
27)
29import aiohttp
30from slixmpp import JID, Message, Presence
31from slixmpp.plugins.xep_0084.stanza import MetaData
32from slixmpp.types import PresenceShows, PresenceTypes, ResourceDict # noqa: F401
33from typing_extensions import TypedDict
35if TYPE_CHECKING:
36 from ..contact import LegacyContact, LegacyRoster
37 from ..core.gateway import BaseGateway
38 from ..core.session import BaseSession
39 from ..room import LegacyBookmarks, LegacyRoom
40 from ..room.participant import LegacyParticipant
41 from ..space import LegacySpace, LegacySpaceNodes
43type AnySession = "BaseSession[Any, Any]"
44type AnyGateway = "BaseGateway[Any, Any, Any]"
45type AnyRoom = "LegacyRoom[Any]"
46type AnySpace = "LegacySpace[Any]"
47type AnyBookmarks = "LegacyBookmarks[Any]"
49type AnySpaceBookmarks = "LegacySpaceNodes[Any]"
50type AnyRoster = "LegacyRoster[Any]"
51type AnyParticipant = "LegacyParticipant[Any]"
54LegacyContactType = TypeVar("LegacyContactType", bound="LegacyContact")
55LegacyRoomType = TypeVar("LegacyRoomType", bound=AnyRoom)
56LegacyParticipantType = TypeVar("LegacyParticipantType", bound=AnyParticipant)
59SessionType = TypeVar("SessionType", bound=AnySession)
60AnyRecipient = Union["LegacyContact", AnyRoom]
61Sender = Union["LegacyContact[Any]", "AnyParticipant"]
63ChatState = Literal["active", "composing", "gone", "inactive", "paused"]
64ProcessingHint = Literal["no-store", "markable", "store"]
65Marker = Literal["acknowledged", "received", "displayed"]
66FieldType = Literal[
67 "boolean",
68 "fixed",
69 "text-single",
70 "text-multi",
71 "jid-single",
72 "jid-multi",
73 "list-single",
74 "list-multi",
75 "text-private",
76]
77MucAffiliation = Literal["owner", "admin", "member", "outcast", "none"]
78MucRole = Literal["visitor", "participant", "moderator", "none"]
79# https://xmpp.org/registrar/disco-categories.html#client
80ClientType = Literal[
81 "bot", "console", "game", "handheld", "pc", "phone", "sms", "tablet", "web"
82]
83AttachmentDisposition = Literal["attachment", "inline"]
86@dataclass
87class MessageReference:
88 """
89 A "message reply", ie a "quoted message" (:xep:`0461`)
91 At the very minimum, the legacy message ID attribute must be set, but to
92 ensure that the quote is displayed in all XMPP clients, the author must also
93 be set (use the string "user" if the slidge user is the author of the referenced
94 message).
95 The body is used as a fallback for XMPP clients that do not support :xep:`0461`
96 of that failed to find the referenced message.
97 """
99 legacy_id: str
100 author: Literal["user"] | AnyParticipant | LegacyContact | None = None
101 body: str | None = None
104@dataclass
105class LegacyAttachment:
106 """
107 A file attachment to a message
109 At the minimum, one of the ``path``, ``steam``, ``data`` or ``url`` attribute
110 has to be set
112 To be used with :meth:`.LegacyContact.send_files` or
113 :meth:`.LegacyParticipant.send_files`
114 """
116 path: Path | str | None = None
117 name: str | None = None
118 stream: IO[bytes] | None = None
119 aio_stream: AsyncIterator[bytes] | None = None
120 data: bytes | None = None
121 content_type: str | None = None
122 legacy_file_id: str | None = None
123 url: str | None = None
124 caption: str | None = None
125 """
126 A caption for this specific image. For a global caption for a list of attachments,
127 use the ``body`` parameter of :meth:`.AttachmentMixin.send_files`
128 """
129 disposition: AttachmentDisposition | None = None
130 is_sticker: bool = False
131 size: int | None = None
132 date: datetime | None = None
133 sha256: str | None = None
134 """
135 Base64-encoded sha256 hash of the file. NB: not the hexdigest.
136 """
138 def __post_init__(self) -> None:
139 if all(
140 x is None
141 for x in (self.path, self.stream, self.data, self.url, self.aio_stream)
142 ):
143 raise TypeError("There is not data in this attachment", self)
145 if isinstance(self.path, str):
146 self.path = Path(self.path)
148 if self.is_sticker:
149 if self.disposition == "attachment":
150 warnings.warn(
151 "Sticker declared as 'attachment' disposition, changing it to 'inline'"
152 )
153 self.disposition = "inline"
155 def format_for_user(self) -> str:
156 if self.name:
157 name = self.name
158 elif self.path:
159 name = self.path.name # type:ignore[union-attr]
160 elif self.url:
161 name = self.url
162 else:
163 name = ""
165 if self.caption:
166 name = f"{name}: {self.caption}" if name else self.caption
168 return name
170 def __str__(self) -> str:
171 attrs = ", ".join(
172 f"{f.name}={getattr(self, f.name)!r}"
173 for f in fields(self)
174 if getattr(self, f.name) is not None and f.name != "data"
175 )
176 if self.data is not None:
177 data_str = f"data=<{len(self.data)} bytes>"
178 to_join = (attrs, data_str) if attrs else (data_str,)
179 attrs = ", ".join(to_join)
180 return f"Attachment({attrs})"
183class RoomType(IntEnum):
184 """
185 The type of group, private, public, anonymous or not.
186 """
188 GROUP = 0
189 """
190 A private group, members-only and non-anonymous, eg a family group.
191 """
192 CHANNEL = 1
193 """
194 A public group, aka an anonymous channel.
195 """
196 CHANNEL_NON_ANONYMOUS = 2
197 """
198 A public group where participants' legacy IDs are visible to everybody.
199 """
202PseudoPresenceShow = PresenceShows | Literal[""]
205MessageOrPresenceTypeVar = TypeVar("MessageOrPresenceTypeVar", bound=Message | Presence)
208class LinkPreview(NamedTuple):
209 """
210 Embedded metadata from :xep:`0511`.
212 See <https://ogp.me/>_.
213 """
215 about: str
216 """
217 URL of the link.
218 """
219 title: str | None
220 """
221 Title of the linked page.
222 """
223 description: str | None
224 """
225 A description of the page.
226 """
227 url: str | None
228 """
229 The canonical URL of the link.
230 """
231 image: str | Path | bytes | None
232 """
233 An image representing the link. If it is a string, it should represent a URL to an image.
234 """
235 type: str | None
236 """
237 Type of the link destination.
238 """
239 site_name: str | None
240 """
241 Name of the web site.
242 """
244 @property
245 def is_empty(self) -> bool:
246 return not any(x for x in self)
249class Mention[LegacyParticipantType: AnyParticipant = AnyParticipant](NamedTuple):
250 participant: LegacyParticipantType
251 start: int
252 end: int
255class Hat(NamedTuple):
256 uri: str
257 title: str
258 hue: float | None = None
261class UserPreferences(TypedDict, total=False):
262 sync_avatar: bool
263 sync_presence: bool
264 bookmarks_push: bool
265 bookmarks_push_public: bool
266 autojoin_public: bool
267 parse_mentions: bool
268 last_seen_fallback: bool
269 roster_push: bool
270 reaction_fallback: bool
273class MamMetadata(NamedTuple):
274 id: str
275 sent_on: datetime
278class HoleBound(NamedTuple):
279 id: str
280 timestamp: datetime
283class Avatar(NamedTuple):
284 path: Path | None = None
285 unique_id: str | None = None
286 url: str | None = None
287 data: bytes | None = None
290class AvatarMetadata(NamedTuple):
291 id: str
292 type: str
293 bytes: int
294 url: str
295 height: int
296 width: int
298 @staticmethod
299 def _from_slix(metadata: MetaData) -> AvatarMetadata:
300 info = metadata["info"]
301 return AvatarMetadata(
302 id=info["id"],
303 type=info["type"],
304 bytes=info["bytes"],
305 url=info["url"],
306 height=info["height"],
307 width=info["width"],
308 )
311@dataclass
312class Reply:
313 """
314 Represents a message referenced (replied to) via :xep:`0461`
315 """
317 msg_id: str
318 """
319 The ID of the message being replied to.
320 """
321 fallback: str | None
322 """
323 A fallback (:xep:`0428`) text for clients not supporting :xep:`0461`,
324 usually consisting of the text of the referenced message.
325 NB: some XMPP clients might not fill this, so it can be empty.
326 """
327 to: Literal["self", "contact"] | LegacyParticipant[Any] = "contact"
328 """
329 Author of the referenced message.
330 """
332 @cached_property
333 def fallback_no_quote_mark(self) -> str | None:
334 """
335 Return multi-line text without leading quote marks (i.e. the ">" character).
336 """
337 if not self.fallback:
338 return None
339 return re.sub(_STRIP_QUOTE_RE, "", self.fallback).strip()
342_STRIP_QUOTE_RE = re.compile(r"^>\s*", flags=re.MULTILINE)
345class _ReplyProtocol(Protocol):
346 msg_id: str
347 fallback: str | None
348 to: Literal["self", "contact"] | LegacyParticipant[Any]
351@runtime_checkable
352class RoomReplyProtocol(_ReplyProtocol, Protocol):
353 to: LegacyParticipant[Any]
356@runtime_checkable
357class ContactReplyProtocol(_ReplyProtocol, Protocol):
358 to: Literal["self", "contact"]
361@dataclass
362class XMPPAttachment:
363 url: str
364 http: aiohttp.ClientSession | None = None
365 is_sticker: bool = False
366 cid: str | None = None
367 content_type: str | None = None
369 @contextlib.asynccontextmanager
370 async def get(self) -> AsyncIterator[aiohttp.ClientResponse]:
371 http_context = (
372 aiohttp.ClientSession()
373 if self.http is None
374 else contextlib.nullcontext(self.http)
375 )
376 async with http_context as http, http.get(self.url) as response:
377 yield response
380@dataclass
381class XMPPMessage[LegacyParticipantType: AnyParticipant]:
382 body: str | None = None
383 """
384 Text content of the message. Can be empty if there are attachments.
385 """
386 attachments: tuple[XMPPAttachment, ...] = ()
387 """
388 Attachments to this message (:xep:`0066`, :xep:`0385` or :xep:`0447`).
389 Is never empty if there is no body.
390 """
391 reply: Reply | None = None
392 """
393 A reference to message being replied-to (:xep:`0461`), if applicable.
394 """
395 link_previews: tuple[LinkPreview, ...] = ()
396 """
397 A list of link metadata (:xep:`0511`), attached to this message.
398 """
399 replace: str | None = None
400 """
401 The message this message is a correction for (:xep:`0308`).
402 """
403 thread: str | None = None
404 """
405 The thread this message is part of.
406 """
407 mentions: tuple[Mention[LegacyParticipantType], ...] = ()
408 """
409 A list of mentions parsed in the body of this message (by searching for
410 nicknames of Room participants).
411 Is always empty for 1:1 messages.
412 """
415class XMPPMessageProtocol[LegacyParticipantType: AnyParticipant](Protocol):
416 body: str | None
417 attachments: tuple[XMPPAttachment, ...]
418 reply: _ReplyProtocol | None
419 link_previews: tuple[LinkPreview, ...]
420 replace: str | None
421 thread: str | None
422 mentions: tuple[Mention[LegacyParticipantType], ...]
425@runtime_checkable
426class ContactMessageProtocol(XMPPMessageProtocol[Any], Protocol):
427 reply: ContactReplyProtocol | None
428 mentions: tuple[()]
431@runtime_checkable
432class RoomMessageProtocol[T: AnyParticipant](XMPPMessageProtocol[T], Protocol):
433 reply: RoomReplyProtocol | None
434 mentions: tuple[Mention[T], ...]
437class AttachmentMessageProtocol[T: AnyParticipant](XMPPMessageProtocol[T]):
438 attachments: tuple[XMPPAttachment, *tuple[XMPPAttachment, ...]]
441class XMPPTextMessageProtocol[T: AnyParticipant](XMPPMessageProtocol[T]):
442 body: str
443 attachments: tuple[()]
446class ContactAttachmentMessage[T: AnyParticipant](
447 ContactMessageProtocol, AttachmentMessageProtocol[T]
448):
449 pass
452class RoomAttachmentMessage[T: AnyParticipant](
453 RoomMessageProtocol[T],
454 AttachmentMessageProtocol[T],
455):
456 pass
459class ContactTextMessage[T: AnyParticipant](
460 ContactMessageProtocol, XMPPTextMessageProtocol[T]
461):
462 pass
465class RoomTextMessage[T: AnyParticipant](
466 RoomMessageProtocol[T], XMPPTextMessageProtocol[T]
467):
468 pass
471type RoomMessage[T] = "RoomAttachmentMessage[T]|RoomTextMessage[T]"
472ContactMessage = ContactAttachmentMessage[Any] | ContactTextMessage[Any]
475def has_attachments[T: AnyParticipant](
476 message: XMPPMessageProtocol[T],
477) -> TypeIs[AttachmentMessageProtocol[T]]:
478 return bool(message.attachments)
481@dataclass
482class Sticker:
483 path: Path
484 content_type: str | None
485 hashes: dict[str, str]
486 fallback: str | None = None
487 reply: Reply | None = None
488 thread: str | None = None
491class StickerProtocol(Protocol):
492 path: Path
493 content_type: str | None
494 hashes: dict[str, str]
495 fallback: str | None
496 reply: _ReplyProtocol | None
497 thread: str | None
500@runtime_checkable
501class ContactSticker(StickerProtocol, Protocol):
502 reply: ContactReplyProtocol | None
505@runtime_checkable
506class RoomSticker(StickerProtocol, Protocol):
507 reply: RoomReplyProtocol | None
510type RegistrationValidationCoroutine[
511 RegistrationFormT: Any = Any,
512 ModuleDataT: Mapping[str, object] = Any,
513] = Callable[[JID, RegistrationFormT], Awaitable[ModuleDataT | None]]
516LocalpartType = Literal["contact", "room"]
519_BaseAttrT = str | float | bool | None
520_AttrT = _BaseAttrT | list[str | float]
521ExtraAttrMapping = Mapping[str, _AttrT]