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

1""" 

2Typing stuff 

3""" 

4 

5from __future__ import annotations 

6 

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) 

28 

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 

34 

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 

42 

43type AnySession = "BaseSession[Any, Any]" 

44type AnyGateway = "BaseGateway[Any, Any, Any]" 

45type AnyRoom = "LegacyRoom[Any]" 

46type AnySpace = "LegacySpace[Any]" 

47type AnyBookmarks = "LegacyBookmarks[Any]" 

48 

49type AnySpaceBookmarks = "LegacySpaceNodes[Any]" 

50type AnyRoster = "LegacyRoster[Any]" 

51type AnyParticipant = "LegacyParticipant[Any]" 

52 

53 

54LegacyContactType = TypeVar("LegacyContactType", bound="LegacyContact") 

55LegacyRoomType = TypeVar("LegacyRoomType", bound=AnyRoom) 

56LegacyParticipantType = TypeVar("LegacyParticipantType", bound=AnyParticipant) 

57 

58 

59SessionType = TypeVar("SessionType", bound=AnySession) 

60AnyRecipient = Union["LegacyContact", AnyRoom] 

61Sender = Union["LegacyContact[Any]", "AnyParticipant"] 

62 

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

84 

85 

86@dataclass 

87class MessageReference: 

88 """ 

89 A "message reply", ie a "quoted message" (:xep:`0461`) 

90 

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 """ 

98 

99 legacy_id: str 

100 author: Literal["user"] | AnyParticipant | LegacyContact | None = None 

101 body: str | None = None 

102 

103 

104@dataclass 

105class LegacyAttachment: 

106 """ 

107 A file attachment to a message 

108 

109 At the minimum, one of the ``path``, ``steam``, ``data`` or ``url`` attribute 

110 has to be set 

111 

112 To be used with :meth:`.LegacyContact.send_files` or 

113 :meth:`.LegacyParticipant.send_files` 

114 """ 

115 

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 """ 

137 

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) 

144 

145 if isinstance(self.path, str): 

146 self.path = Path(self.path) 

147 

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" 

154 

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

164 

165 if self.caption: 

166 name = f"{name}: {self.caption}" if name else self.caption 

167 

168 return name 

169 

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})" 

181 

182 

183class RoomType(IntEnum): 

184 """ 

185 The type of group, private, public, anonymous or not. 

186 """ 

187 

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 """ 

200 

201 

202PseudoPresenceShow = PresenceShows | Literal[""] 

203 

204 

205MessageOrPresenceTypeVar = TypeVar("MessageOrPresenceTypeVar", bound=Message | Presence) 

206 

207 

208class LinkPreview(NamedTuple): 

209 """ 

210 Embedded metadata from :xep:`0511`. 

211 

212 See <https://ogp.me/>_. 

213 """ 

214 

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 """ 

243 

244 @property 

245 def is_empty(self) -> bool: 

246 return not any(x for x in self) 

247 

248 

249class Mention[LegacyParticipantType: AnyParticipant = AnyParticipant](NamedTuple): 

250 participant: LegacyParticipantType 

251 start: int 

252 end: int 

253 

254 

255class Hat(NamedTuple): 

256 uri: str 

257 title: str 

258 hue: float | None = None 

259 

260 

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 

271 

272 

273class MamMetadata(NamedTuple): 

274 id: str 

275 sent_on: datetime 

276 

277 

278class HoleBound(NamedTuple): 

279 id: str 

280 timestamp: datetime 

281 

282 

283class Avatar(NamedTuple): 

284 path: Path | None = None 

285 unique_id: str | None = None 

286 url: str | None = None 

287 data: bytes | None = None 

288 

289 

290class AvatarMetadata(NamedTuple): 

291 id: str 

292 type: str 

293 bytes: int 

294 url: str 

295 height: int 

296 width: int 

297 

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 ) 

309 

310 

311@dataclass 

312class Reply: 

313 """ 

314 Represents a message referenced (replied to) via :xep:`0461` 

315 """ 

316 

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 """ 

331 

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

340 

341 

342_STRIP_QUOTE_RE = re.compile(r"^>\s*", flags=re.MULTILINE) 

343 

344 

345class _ReplyProtocol(Protocol): 

346 msg_id: str 

347 fallback: str | None 

348 to: Literal["self", "contact"] | LegacyParticipant[Any] 

349 

350 

351@runtime_checkable 

352class RoomReplyProtocol(_ReplyProtocol, Protocol): 

353 to: LegacyParticipant[Any] 

354 

355 

356@runtime_checkable 

357class ContactReplyProtocol(_ReplyProtocol, Protocol): 

358 to: Literal["self", "contact"] 

359 

360 

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 

368 

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 

378 

379 

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 """ 

413 

414 

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], ...] 

423 

424 

425@runtime_checkable 

426class ContactMessageProtocol(XMPPMessageProtocol[Any], Protocol): 

427 reply: ContactReplyProtocol | None 

428 mentions: tuple[()] 

429 

430 

431@runtime_checkable 

432class RoomMessageProtocol[T: AnyParticipant](XMPPMessageProtocol[T], Protocol): 

433 reply: RoomReplyProtocol | None 

434 mentions: tuple[Mention[T], ...] 

435 

436 

437class AttachmentMessageProtocol[T: AnyParticipant](XMPPMessageProtocol[T]): 

438 attachments: tuple[XMPPAttachment, *tuple[XMPPAttachment, ...]] 

439 

440 

441class XMPPTextMessageProtocol[T: AnyParticipant](XMPPMessageProtocol[T]): 

442 body: str 

443 attachments: tuple[()] 

444 

445 

446class ContactAttachmentMessage[T: AnyParticipant]( 

447 ContactMessageProtocol, AttachmentMessageProtocol[T] 

448): 

449 pass 

450 

451 

452class RoomAttachmentMessage[T: AnyParticipant]( 

453 RoomMessageProtocol[T], 

454 AttachmentMessageProtocol[T], 

455): 

456 pass 

457 

458 

459class ContactTextMessage[T: AnyParticipant]( 

460 ContactMessageProtocol, XMPPTextMessageProtocol[T] 

461): 

462 pass 

463 

464 

465class RoomTextMessage[T: AnyParticipant]( 

466 RoomMessageProtocol[T], XMPPTextMessageProtocol[T] 

467): 

468 pass 

469 

470 

471type RoomMessage[T] = "RoomAttachmentMessage[T]|RoomTextMessage[T]" 

472ContactMessage = ContactAttachmentMessage[Any] | ContactTextMessage[Any] 

473 

474 

475def has_attachments[T: AnyParticipant]( 

476 message: XMPPMessageProtocol[T], 

477) -> TypeIs[AttachmentMessageProtocol[T]]: 

478 return bool(message.attachments) 

479 

480 

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 

489 

490 

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 

498 

499 

500@runtime_checkable 

501class ContactSticker(StickerProtocol, Protocol): 

502 reply: ContactReplyProtocol | None 

503 

504 

505@runtime_checkable 

506class RoomSticker(StickerProtocol, Protocol): 

507 reply: RoomReplyProtocol | None 

508 

509 

510type RegistrationValidationCoroutine[ 

511 RegistrationFormT: Any = Any, 

512 ModuleDataT: Mapping[str, object] = Any, 

513] = Callable[[JID, RegistrationFormT], Awaitable[ModuleDataT | None]] 

514 

515 

516LocalpartType = Literal["contact", "room"] 

517 

518 

519_BaseAttrT = str | float | bool | None 

520_AttrT = _BaseAttrT | list[str | float] 

521ExtraAttrMapping = Mapping[str, _AttrT]