Coverage for slidge/core/gateway.py: 59%

590 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-12-01 19:36 +0000

1""" 

2This module extends slixmpp.ComponentXMPP to make writing new LegacyClients easier 

3""" 

4 

5from __future__ import annotations 

6 

7import abc 

8import asyncio 

9import logging 

10import re 

11import sys 

12import tempfile 

13from collections.abc import ( 

14 Awaitable, 

15 Callable, 

16 Coroutine, 

17 Iterable, 

18 Mapping, 

19 Sequence, 

20) 

21from copy import copy 

22from datetime import UTC, datetime, timedelta 

23from pathlib import Path 

24from typing import ( 

25 Any, 

26 ClassVar, 

27 Concatenate, 

28 ParamSpec, 

29 TypedDict, 

30 TypeVar, 

31) 

32 

33import aiohttp 

34from slixmpp import JID, ComponentXMPP, Iq 

35from slixmpp.exceptions import IqError, IqTimeout, XMPPError 

36from slixmpp.jid import escape_node, unescape_node 

37from slixmpp.plugins.xep_0004.stanza.form import Form 

38from slixmpp.plugins.xep_0030.stanza import DiscoInfo # type:ignore[attr-defined] 

39from slixmpp.plugins.xep_0060.stanza import OwnerAffiliation 

40from slixmpp.plugins.xep_0356.privilege import PrivilegedIqError 

41from slixmpp.types import MessageTypes 

42from slixmpp.xmlstream.xmlstream import NotConnectedError 

43from sqlalchemy.orm import Session as OrmSession 

44 

45import slidge.command.categories 

46from slidge.command import BUILTIN_COMMANDS 

47from slidge.command.adhoc import AdhocProvider 

48from slidge.command.admin import Exec 

49from slidge.command.base import ( 

50 Command, 

51 CommandBase, 

52 ContactCommand, 

53 FormField, 

54 RoomCommand, 

55) 

56from slidge.command.chat_command import ChatCommandProvider 

57from slidge.command.register import AltRegistrationFlow, Register, RegistrationType 

58from slidge.contact import LegacyContact 

59from slidge.core import config 

60from slidge.core.attachment_upload import AttachmentUploader 

61from slidge.core.dispatcher.session_dispatcher import SessionDispatcher 

62from slidge.core.mixins.avatar import convert_avatar 

63from slidge.core.mixins.message import ContentMessageMixin, InviteMixin 

64from slidge.core.pubsub import PubSubComponent 

65from slidge.core.session import BaseSession 

66from slidge.db import GatewayUser, SlidgeStore 

67from slidge.db.avatar import CachedAvatar, avatar_cache 

68from slidge.db.models import Attachment 

69from slidge.room import LegacyRoom 

70from slidge.slixfix.delivery_receipt import DeliveryReceipt 

71from slidge.slixfix.roster import RosterBackend 

72from slidge.util.lock import NamedLockMixin 

73from slidge.util.types import ( 

74 AnySession, 

75 Avatar, 

76 LocalpartType, 

77 MessageOrPresenceTypeVar, 

78 RegistrationValidationCoroutine, 

79) 

80from slidge.util.util import derive_wired_class 

81 

82T = TypeVar("T") 

83P = ParamSpec("P") 

84 

85 

86class _DefaultRegistrationForm(TypedDict): 

87 username: str 

88 password: str 

89 

90 

91class BaseGateway[ 

92 SessionT: AnySession = BaseSession, 

93 RegistrationFormT: Any = _DefaultRegistrationForm, 

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

95](ComponentXMPP, InviteMixin, ContentMessageMixin, NamedLockMixin, abc.ABC): 

96 """ 

97 The gateway component, handling registrations and un-registrations. 

98 

99 On slidge launch, a singleton is instantiated, and it will be made available 

100 to public classes such :class:`.LegacyContact` or :class:`.BaseSession` as the 

101 ``.xmpp`` attribute. 

102 

103 Must be subclassed by a legacy module to set up various aspects of the XMPP 

104 component behaviour, such as its display name or welcome message, via 

105 class attributes :attr:`.COMPONENT_NAME` :attr:`.WELCOME_MESSAGE`. 

106 

107 Abstract methods related to the registration process must be overriden 

108 for a functional :term:`Legacy Module`: 

109 

110 - :meth:`.validate` 

111 - :meth:`.validate_two_factor_code` 

112 - :meth:`.get_qr_text` 

113 - :meth:`.confirm_qr` 

114 

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

116 :attr:`REGISTRATION_TYPE`. 

117 

118 The other methods, such as :meth:`.send_text` or :meth:`.react` are the same 

119 as those of :class:`.LegacyContact` and :class:`.LegacyParticipant`, because 

120 the component itself is also a "messaging actor", ie, an :term:`XMPP Entity`. 

121 For these methods, you need to specify the JID of the recipient with the 

122 `mto` parameter. 

123 

124 Since it inherits from :class:`slixmpp.componentxmpp.ComponentXMPP`,you also 

125 have a hand on low-level XMPP interactions via slixmpp methods, e.g.: 

126 

127 .. code-block:: python 

128 

129 self.send_presence( 

130 pfrom="somebody@component.example.com", 

131 pto="someonwelse@anotherexample.com", 

132 ) 

133 

134 However, you should not need to do so often since the classes of the plugin 

135 API provides higher level abstractions around most commonly needed use-cases, such 

136 as sending messages, or displaying a custom status. 

137 

138 """ 

139 

140 COMPONENT_NAME: str = NotImplemented 

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

142 COMPONENT_TYPE: str = "" 

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

144 COMPONENT_AVATAR: Avatar | Path | str | None = None 

145 """ 

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

147 """ 

148 

149 REGISTRATION_FIELDS: ClassVar[Sequence[FormField]] = [ 

150 FormField(var="username", label="User name", required=True), 

151 FormField(var="password", label="Password", required=True, private=True), 

152 ] 

153 """ 

154 Iterable of fields presented to the gateway user when registering using :xep:`0077` 

155 `extended <https://xmpp.org/extensions/xep-0077.html#extensibility>`_ by :xep:`0004`. 

156 """ 

157 REGISTRATION_INSTRUCTIONS: str = "Enter your credentials" 

158 """ 

159 The text presented to a user who wants to register (or modify) their 

160 :term:`legacy <Legacy>` account configuration. 

161 """ 

162 REGISTRATION_TYPE: RegistrationType = RegistrationType.SINGLE_STEP_FORM 

163 """ 

164 This attribute determines how users register to the gateway, ie, how they 

165 login to the :term:`legacy network <Legacy Network>`. 

166 The credentials are then stored persistently, so this process should happen 

167 once per user (unless they unregister). 

168 

169 The registration process always start with a basic data form (:xep:`0004`) 

170 presented to the user. 

171 But the legacy login flow might require something more sophisticated, see 

172 :class:`.RegistrationType` for more details. 

173 """ 

174 

175 REGISTRATION_2FA_TITLE = "Enter your 2FA code" 

176 REGISTRATION_2FA_INSTRUCTIONS = ( 

177 "You should have received something via email or SMS, or something" 

178 ) 

179 REGISTRATION_QR_INSTRUCTIONS = "Flash this code or follow this link" 

180 

181 ALTERNATIVE_REGISTRATION_FLOWS: ClassVar[ 

182 list[AltRegistrationFlow[Any, ModuleDataT]] 

183 ] = [] 

184 

185 PREFERENCES: ClassVar[list[FormField]] = [ 

186 FormField( 

187 var="sync_presence", 

188 label="Propagate your XMPP presence to the legacy network.", 

189 value="true", 

190 required=True, 

191 type="boolean", 

192 ), 

193 FormField( 

194 var="sync_avatar", 

195 label="Propagate your XMPP avatar to the legacy network.", 

196 value="true", 

197 required=True, 

198 type="boolean", 

199 ), 

200 FormField( 

201 var="bookmarks_push", 

202 label="Add private rooms to your bookmarks.", 

203 value="true", 

204 required=True, 

205 type="boolean", 

206 ), 

207 FormField( 

208 var="bookmarks_push_public", 

209 label="Add public rooms to your bookmarks.", 

210 value="false", 

211 required=True, 

212 type="boolean", 

213 ), 

214 FormField( 

215 var="autojoin_public", 

216 label="Auto-join public rooms.", 

217 value="false", 

218 required=True, 

219 type="boolean", 

220 ), 

221 FormField( 

222 var="parse_mentions", 

223 label="Parse the body of messages I send for mentions.", 

224 value="true", 

225 required=True, 

226 type="boolean", 

227 ), 

228 FormField( 

229 var="last_seen_fallback", 

230 label="Use contact presence status message to show when they were last seen.", 

231 value="true", 

232 required=True, 

233 type="boolean", 

234 ), 

235 FormField( 

236 var="roster_push", 

237 label="Add contacts to your roster.", 

238 value="true", 

239 required=True, 

240 type="boolean", 

241 ), 

242 FormField( 

243 var="reaction_fallback", 

244 label="Receive fallback messages for reactions (for legacy XMPP clients)", 

245 value="false", 

246 required=True, 

247 type="boolean", 

248 ), 

249 ] 

250 

251 ROSTER_GROUP: str = "slidge" 

252 """ 

253 Name of the group assigned to a :class:`.LegacyContact` automagically 

254 added to the :term:`User`'s roster with :meth:`.LegacyContact.add_to_roster`. 

255 """ 

256 WELCOME_MESSAGE = ( 

257 "Thank you for registering. Type 'help' to list the available commands, " 

258 "or just start messaging away!" 

259 ) 

260 """ 

261 A welcome message displayed to users on registration. 

262 This is useful notably for clients that don't consider component JIDs as a 

263 valid recipient in their UI, yet still open a functional chat window on 

264 incoming messages from components. 

265 """ 

266 

267 SEARCH_FIELDS: ClassVar[Sequence[FormField]] = [ 

268 FormField(var="first", label="First name", required=True), 

269 FormField(var="last", label="Last name", required=True), 

270 FormField(var="phone", label="Phone number", required=False), 

271 ] 

272 """ 

273 Fields used for searching items via the component, through :xep:`0055` (jabber search). 

274 A common use case is to allow users to search for legacy contacts by something else than 

275 their usernames, eg their phone number. 

276 

277 Plugins should implement search by overriding :meth:`.BaseSession.search` 

278 (restricted to registered users). 

279 

280 If there is only one field, it can also be used via the ``jabber:iq:gateway`` protocol 

281 described in :xep:`0100`. Limitation: this only works if the search request returns 

282 one result item, and if this item has a 'jid' var. 

283 """ 

284 SEARCH_TITLE: str = "Search for legacy contacts" 

285 """ 

286 Title of the search form. 

287 """ 

288 SEARCH_INSTRUCTIONS: str = "" 

289 """ 

290 Instructions of the search form. 

291 """ 

292 

293 MARK_ALL_MESSAGES = False 

294 """ 

295 Set this to True for :term:`legacy networks <Legacy Network>` that expects 

296 read marks for *all* messages and not just the latest one that was read 

297 (as most XMPP clients will only send a read mark for the latest msg). 

298 """ 

299 

300 PROPER_RECEIPTS = False 

301 """ 

302 Set this to True if the legacy service provides a real equivalent of message delivery receipts 

303 (:xep:`0184`), meaning that there is an event thrown when the actual device of a contact receives 

304 a message. Make sure to call Contact.received() adequately if this is set to True. 

305 """ 

306 

307 ROOMS = False 

308 """ 

309 This must be set to True if this gateway supports multi-user chats. 

310 """ 

311 SPACES = False 

312 """ 

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

314 """ 

315 THREADS: bool = True 

316 """ 

317 This must be set to True if this gateway supports threads, to enable 

318 storing an XMPP/legacy thread ID mapping when necessary. 

319 """ 

320 

321 _mtype: MessageTypes = "chat" 

322 is_group = False 

323 _can_send_carbon = False 

324 store: SlidgeStore 

325 

326 _session_cls: type[SessionT] 

327 """Concrete :class:`.BaseSession` subclass of this legacy module. 

328 

329 Derived automatically from the generic parameter, e.g., 

330 ``class Gateway(BaseGateway[Session])``. 

331 """ 

332 

333 def __init_subclass__(cls, **kwargs: object) -> None: 

334 super().__init_subclass__(**kwargs) 

335 derive_wired_class(cls, BaseGateway, "_session_cls") 

336 

337 COMMANDS: ClassVar[tuple[type[CommandBase], ...]] = BUILTIN_COMMANDS 

338 """Commands (adhoc and chatbot) this gateway provides. 

339 

340 Subclasses may override this with additional custom commands. 

341 E.g.: ``COMMANDS = BaseGateway.COMMANDS + commands_from_module(command)``. 

342 """ 

343 

344 http: aiohttp.ClientSession 

345 avatar: CachedAvatar | None = None 

346 

347 def __init__(self) -> None: 

348 if getattr(self, "_session_cls", None) is None: 

349 raise RuntimeError( 

350 f"{type(self).__name__}._session_cls is not set. Your gateway" 

351 " class must be parameterized with its BaseSession subclass," 

352 " e.g. 'class Gateway(BaseGateway[Session])'." 

353 ) 

354 if config.COMPONENT_NAME: 

355 self.COMPONENT_NAME = config.COMPONENT_NAME 

356 if config.WELCOME_MESSAGE: 

357 self.WELCOME_MESSAGE = config.WELCOME_MESSAGE 

358 self.log = log 

359 self.datetime_started = datetime.now(tz=UTC) 

360 # FIXME: ugly hack to work with the BaseSender mixin :/ 

361 self.xmpp = self 

362 self.default_ns = "jabber:component:accept" 

363 super().__init__( 

364 config.JID, 

365 config.SECRET, 

366 config.SERVER, 

367 config.PORT, 

368 plugin_whitelist=SLIXMPP_PLUGINS, 

369 plugin_config={ 

370 "xep_0077": { 

371 "form_fields": None, 

372 "form_instructions": self.REGISTRATION_INSTRUCTIONS, 

373 "enable_subscription": self.REGISTRATION_TYPE 

374 == RegistrationType.SINGLE_STEP_FORM, 

375 }, 

376 "xep_0100": { 

377 "component_name": self.COMPONENT_NAME, 

378 "type": self.COMPONENT_TYPE, 

379 }, 

380 "xep_0184": { 

381 "auto_ack": False, 

382 "auto_request": False, 

383 }, 

384 "xep_0363": { 

385 "upload_service": config.UPLOAD_SERVICE, 

386 }, 

387 }, 

388 fix_error_ns=True, 

389 ) 

390 NamedLockMixin.__init__(self) 

391 self.loop.set_exception_handler(self.__exception_handler) 

392 self.create_task(self.__set_http(), name="set http client") 

393 self.has_crashed: bool = False 

394 self.use_origin_id = False 

395 

396 if config.USER_JID_VALIDATOR is None: 

397 config.USER_JID_VALIDATOR = f".*@{self.infer_real_domain()}" 

398 log.info( 

399 "No USER_JID_VALIDATOR was set, using '%s'.", 

400 config.USER_JID_VALIDATOR, 

401 ) 

402 self.jid_validator: re.Pattern[str] = re.compile(config.USER_JID_VALIDATOR) 

403 self.qr_pending_registrations = dict[str, asyncio.Future[ModuleDataT | None]]() 

404 

405 self.register_plugins() 

406 self.__setup_session_cls() 

407 

408 self.get_session_from_stanza = self._session_cls.from_stanza 

409 self.get_session_from_user = self._session_cls.from_user 

410 

411 self.__register_slixmpp_events() 

412 self.__register_slixmpp_api() 

413 self.roster.set_backend(RosterBackend(self)) 

414 

415 self.register_plugin("pubsub", {"component_name": self.COMPONENT_NAME}) 

416 self.pubsub: PubSubComponent = self.plugin["pubsub"] # type:ignore[typeddict-item] 

417 self.delivery_receipt = DeliveryReceipt(self) 

418 

419 # with this we receive user avatar updates 

420 self.plugin["xep_0030"].add_feature("urn:xmpp:avatar:metadata+notify") 

421 

422 self.plugin["xep_0030"].add_feature("urn:xmpp:chat-markers:0") 

423 

424 if self.ROOMS: 

425 self.plugin["xep_0030"].add_feature("http://jabber.org/protocol/muc") 

426 self.plugin["xep_0030"].add_feature(self.plugin["xep_0463"].stanza.NS) 

427 self.plugin["xep_0030"].add_feature("urn:xmpp:mam:2") 

428 self.plugin["xep_0030"].add_feature("urn:xmpp:mam:2#extended") 

429 self.plugin["xep_0030"].add_feature(self.plugin["xep_0421"].namespace) 

430 self.plugin["xep_0030"].add_feature(self.plugin["xep_0317"].stanza.NS) 

431 self.plugin["xep_0030"].add_identity( 

432 category="conference", 

433 name=self.COMPONENT_NAME, 

434 itype="text", 

435 jid=self.boundjid, 

436 ) 

437 if self.SPACES: 

438 self.plugin["xep_0030"].add_feature("urn:xmpp:spaces:0") 

439 

440 self.__adhoc_handler = AdhocProvider(self) 

441 self.__chat_commands_handler = ChatCommandProvider(self) 

442 

443 self.__dispatcher = SessionDispatcher[RegistrationFormT](self) 

444 self.get_caps_ver = self.__dispatcher.get_caps_ver 

445 self._populate_caps_cache = self.__dispatcher.populate_cache 

446 

447 self.__register_commands() 

448 

449 def __setup_session_cls(self) -> None: 

450 contact_cls = self._session_cls._roster_cls._contact_cls 

451 

452 if contact_cls.REACTIONS_SINGLE_EMOJI: 

453 form = Form() 

454 form["type"] = "result" 

455 form.add_field( 

456 "FORM_TYPE", "hidden", value="urn:xmpp:reactions:0:restrictions" 

457 ) 

458 form.add_field("max_reactions_per_user", value="1", type="text-single") 

459 form.add_field("scope", value="domain") 

460 self.plugin["xep_0128"].add_extended_info(data=form) 

461 

462 self._session_cls.xmpp = self 

463 

464 @property 

465 def _uploader(self) -> AttachmentUploader: 

466 # the component itself is not bound to any user session 

467 return AttachmentUploader(self, None) 

468 

469 async def kill_session(self, jid: JID) -> None: 

470 await self._session_cls.kill_by_jid(jid) 

471 

472 async def __set_http(self) -> None: 

473 self.http = aiohttp.ClientSession() 

474 if getattr(self, "_test_mode", False): 

475 return 

476 avatar_cache.http = self.http 

477 

478 def __register_commands(self) -> None: 

479 for cls in self.COMMANDS: 

480 if any(x is NotImplemented for x in [cls.CHAT_COMMAND, cls.NODE, cls.NAME]): 

481 raise TypeError( 

482 f"{cls} is listed in {type(self).__name__}.COMMANDS but" 

483 " does not set NAME, NODE and CHAT_COMMAND." 

484 ) 

485 if issubclass(cls, ContactCommand): 

486 LegacyContact._commands[cls.NODE] = cls 

487 LegacyContact._commands_chat[cls.CHAT_COMMAND] = cls 

488 continue 

489 if issubclass(cls, RoomCommand): 

490 LegacyRoom._commands[cls.NODE] = cls 

491 LegacyRoom._commands_chat[cls.CHAT_COMMAND] = cls 

492 continue 

493 if not issubclass(cls, Command): 

494 raise TypeError( 

495 f"{cls} is listed in {type(self).__name__}.COMMANDS but is" 

496 " not a Command, ContactCommand or RoomCommand subclass." 

497 ) 

498 if cls is Exec: 

499 if config.DEV_MODE: 

500 log.warning(r"/!\ DEV MODE ENABLED /!\\") 

501 else: 

502 continue 

503 if cls.CATEGORY == slidge.command.categories.ROOMS and not self.ROOMS: 

504 continue 

505 if cls.CATEGORY == slidge.command.categories.SPACES and not self.SPACES: 

506 continue 

507 c = cls(self) 

508 log.debug("Registering %s", cls) 

509 self.__adhoc_handler.register(c) 

510 self.__chat_commands_handler.register(c) 

511 

512 for i, alt in enumerate(self.ALTERNATIVE_REGISTRATION_FLOWS): 

513 

514 class AltRegister(Register[RegistrationFormT, ModuleDataT]): 

515 NAME = alt.title 

516 NODE = f"https://slidge.im/register/alt{i}" 

517 CHAT_COMMAND = f"register-{i}" 

518 _instructions = alt.instructions 

519 _type = alt.type 

520 _fields = alt.fields 

521 _validate = staticmethod(alt.validate) if alt.validate else None 

522 

523 inst = AltRegister(self) 

524 log.debug("Registering alternative registration flow: %s", alt.title) 

525 self.__adhoc_handler.register(inst) 

526 self.__chat_commands_handler.register(inst) 

527 

528 def __exception_handler( 

529 self, loop: asyncio.AbstractEventLoop, context: dict[Any, Any] 

530 ) -> None: 

531 """ 

532 Called when the event loop encounters an exception that was not 

533 handled anywhere else. 

534 

535 Tasks created via :meth:`create_task`, are handled separately and do not reach 

536 this handler. 

537 """ 

538 log.debug("Context in the exception handler: %s", context) 

539 exc = context.get("exception") 

540 if exc is None: 

541 log.debug("No exception in this context: %s", context) 

542 elif isinstance(exc, SystemExit): 

543 log.debug("SystemExit called in an asyncio task") 

544 elif context.get("future") is not None: 

545 log.warning( 

546 "Exception in a third-party task was never retrieved: %s", 

547 context, 

548 exc_info=exc, 

549 ) 

550 else: 

551 log.error("Crash in an asyncio task: %s", context) 

552 log.exception("Crash in task", exc_info=exc) 

553 self.has_crashed = True 

554 loop.stop() 

555 

556 def create_task( 

557 self, 

558 coro: Coroutine[Any, Any, Any], 

559 *, 

560 name: str | None = None, 

561 ) -> asyncio.Task[Any]: 

562 """Create a task that crashes the gateway if it fails.""" 

563 task = self.loop.create_task(coro, name=name) 

564 task.add_done_callback(self.__handle_task_result) 

565 return task 

566 

567 def __handle_task_result(self, task: asyncio.Task[Any]) -> None: 

568 if task.cancelled(): 

569 return 

570 exc = task.exception() 

571 if exc is not None: 

572 log.error( 

573 "Crash in task %s", 

574 task.get_name(), 

575 exc_info=(type(exc), exc, exc.__traceback__), 

576 ) 

577 self.has_crashed = True 

578 self.loop.stop() 

579 

580 def __register_slixmpp_events(self) -> None: 

581 self.del_event_handler("presence_subscribe", self._handle_subscribe) 

582 self.del_event_handler("presence_unsubscribe", self._handle_unsubscribe) 

583 self.del_event_handler("presence_subscribed", self._handle_subscribed) 

584 self.del_event_handler("presence_unsubscribed", self._handle_unsubscribed) 

585 self.del_event_handler( 

586 "roster_subscription_request", self._handle_new_subscription 

587 ) 

588 self.del_event_handler("presence_probe", self._handle_probe) 

589 self.add_event_handler("session_start", self.__on_session_start) 

590 

591 def __register_slixmpp_api(self) -> None: 

592 def with_session( 

593 func: Callable[Concatenate[OrmSession, P], T], commit: bool = True 

594 ) -> Callable[P, T]: 

595 def wrapped(*a: P.args, **kw: P.kwargs) -> T: 

596 with self.store.session() as orm: 

597 res = func(orm, *a, **kw) 

598 if commit: 

599 orm.commit() 

600 return res 

601 

602 return wrapped 

603 

604 self.plugin["xep_0231"].api.register( 

605 with_session(self.store.bob.get_bob, False), "get_bob" 

606 ) 

607 self.plugin["xep_0231"].api.register( 

608 with_session(self.store.bob.set_bob), "set_bob" 

609 ) 

610 self.plugin["xep_0231"].api.register( 

611 with_session(self.store.bob.del_bob), "del_bob" 

612 ) 

613 

614 @property # type:ignore[override] 

615 def jid(self) -> JID: 

616 # Override to avoid slixmpp deprecation warnings. 

617 return self.boundjid 

618 

619 @jid.setter 

620 def jid(self, jid: JID) -> None: 

621 raise RuntimeError 

622 

623 async def __on_session_start(self, event: object) -> None: 

624 log.debug("Gateway session start: %s", event) 

625 

626 await self.__setup_attachments() 

627 

628 # prevents XMPP clients from considering the gateway as an HTTP upload 

629 disco = self.plugin["xep_0030"] 

630 await disco.del_feature(feature="urn:xmpp:http:upload:0", jid=self.boundjid) 

631 await self.plugin["xep_0115"].update_caps(jid=self.boundjid) 

632 

633 if self.COMPONENT_AVATAR is not None: 

634 log.debug("Setting gateway avatar…") 

635 avatar = convert_avatar(self.COMPONENT_AVATAR, "!!---slidge---special---") 

636 assert avatar is not None 

637 try: 

638 cached_avatar = await avatar_cache.get(avatar) 

639 except Exception as e: 

640 log.exception("Could not set the component avatar.", exc_info=e) 

641 cached_avatar = None 

642 else: 

643 assert cached_avatar is not None 

644 self.avatar = cached_avatar 

645 else: 

646 cached_avatar = None 

647 

648 with self.store.session() as orm: 

649 users = orm.query(GatewayUser).all() 

650 for user in users: 

651 # TODO: before this, we should check if the user has removed us from their roster 

652 # while we were offline and trigger unregister from there. Presence probe does not seem 

653 # to work in this case, there must be another way. privileged entity could be used 

654 # as last resort. 

655 try: 

656 await self["xep_0100"].add_component_to_roster(user.jid) 

657 await self.__add_component_to_mds_whitelist(user.jid) 

658 except (IqError, IqTimeout) as e: 

659 # TODO: remove the user when this happens? or at least 

660 # this can happen when the user has unsubscribed from the XMPP server 

661 log.warning( 

662 "Error with user %s, not logging them automatically", 

663 user, 

664 exc_info=e, 

665 ) 

666 continue 

667 session = self._session_cls.from_user(user) 

668 session.create_task(self.login_wrap(session), name=f"login wrap of {user}") 

669 if cached_avatar is not None: 

670 await self.pubsub.broadcast_avatar( 

671 self.boundjid.bare, session.user_jid, cached_avatar 

672 ) 

673 

674 log.info("Slidge has successfully started") 

675 

676 async def __setup_attachments(self) -> None: 

677 expire_coro = self.__expire_attachments_upload 

678 if config.NO_UPLOAD_PATH: 

679 if config.NO_UPLOAD_URL_PREFIX is None: 

680 raise RuntimeError( 

681 "If you set NO_UPLOAD_PATH you must set NO_UPLOAD_URL_PREFIX too." 

682 ) 

683 expire_coro = self.__expire_attachments_no_upload 

684 elif not config.UPLOAD_SERVICE: 

685 try: 

686 info_iq = await self.xmpp.plugin["xep_0363"].find_upload_service( 

687 self.infer_real_domain() 

688 ) 

689 except XMPPError: 

690 info_iq = None 

691 log.exception( 

692 "The upload service could not be automatically determine. " 

693 "Attachments to XMPP will not work. " 

694 "Either specify 'upload-service' or 'no-upload-path' to fix that." 

695 ) 

696 if info_iq is None: 

697 if self.REGISTRATION_TYPE == RegistrationType.QRCODE: 

698 log.warning( 

699 "No method was configured for attachment and slidge " 

700 "could not automatically determine the JID of a usable upload service. " 

701 "Users likely won't be able to register since this network uses a " 

702 "QR-code based registration flow." 

703 ) 

704 if not config.USE_ATTACHMENT_ORIGINAL_URLS: 

705 log.warning( 

706 "Setting USE_ATTACHMENT_ORIGINAL_URLS to True since no method was configured " 

707 "for attachments and no upload service was found. NB: this does not work for all " 

708 "networks, especially for the E2EE attachments." 

709 ) 

710 config.USE_ATTACHMENT_ORIGINAL_URLS = True 

711 else: 

712 log.info("Auto-discovered upload service: %s", info_iq["from"]) 

713 config.UPLOAD_SERVICE = info_iq["from"] 

714 

715 self.__expire_attachments_task = self.create_task(_loop(expire_coro, 3600 * 24)) 

716 

717 async def __expire_attachments_no_upload(self) -> None: 

718 with self.store.session() as orm: 

719 attachments = self.store.attachments.get_all(orm) 

720 self.__expire_attachments_in_store( 

721 await asyncio.to_thread(self.__rm_local_attachments, attachments) 

722 ) 

723 

724 def __rm_local_attachments(self, attachments: list[Attachment]) -> list[int]: 

725 to_remove = [] 

726 cutoff = datetime.now(tz=UTC) - timedelta( 

727 days=config.NO_UPLOAD_MAX_DAYS or config.MAM_MAX_DAYS 

728 ) 

729 

730 for attachment in attachments: 

731 path = attachment.local_path 

732 try: 

733 created = datetime.fromtimestamp(path.stat().st_ctime, tz=UTC) 

734 except OSError: 

735 self.log.debug( 

736 "mtime of %s could not be determined, clearing up the row", 

737 attachment, 

738 ) 

739 to_remove.append(attachment.id) 

740 else: 

741 if created > cutoff: 

742 continue 

743 to_remove.append(attachment.id) 

744 self.log.debug("%s is too old", attachment) 

745 _safe_rm_parent(path) 

746 to_remove.append(attachment.id) 

747 

748 return to_remove 

749 

750 async def __expire_attachments_upload(self) -> None: 

751 with self.store.session() as orm: 

752 attachments = self.store.attachments.get_all(orm) 

753 to_remove = [] 

754 for attachment in attachments: 

755 try: 

756 async with self.http.head(attachment.url) as resp: 

757 if not resp.ok: 

758 self.log.debug("%s is not reachable anymore", attachment) 

759 to_remove.append(attachment.id) 

760 except Exception as e: 

761 self.log.debug("Error when trying to reach %s", attachment, exc_info=e) 

762 to_remove.append(attachment.id) 

763 self.__expire_attachments_in_store(to_remove) 

764 

765 def __expire_attachments_in_store(self, to_remove: list[int]) -> None: 

766 with self.store.session() as orm: 

767 self.store.attachments.remove(orm, to_remove) 

768 orm.commit() 

769 

770 def infer_real_domain(self) -> JID: 

771 return JID(re.sub(r"^.*?\.", "", self.xmpp.boundjid.bare)) 

772 

773 async def __add_component_to_mds_whitelist(self, user_jid: JID) -> None: 

774 # Uses privileged entity to add ourselves to the whitelist of the PEP 

775 # MDS node so we receive MDS events 

776 iq_creation = Iq(sto=user_jid.bare, sfrom=user_jid, stype="set") 

777 iq_creation["pubsub"]["create"]["node"] = self.plugin["xep_0490"].stanza.NS 

778 

779 try: 

780 await self.plugin["xep_0356"].send_privileged_iq(iq_creation) 

781 except PermissionError: 

782 log.warning( 

783 "IQ privileges not granted for pubsub namespace, we cannot " 

784 "create the MDS node of %s", 

785 user_jid, 

786 ) 

787 except PrivilegedIqError as exc: 

788 nested = exc.nested_error() 

789 # conflict this means the node already exists, we can ignore that 

790 if nested is not None and nested.condition != "conflict": 

791 log.exception( 

792 "Could not create the MDS node of %s", user_jid, exc_info=exc 

793 ) 

794 except Exception as e: 

795 log.exception( 

796 "Error while trying to create to the MDS node of %s", 

797 user_jid, 

798 exc_info=e, 

799 ) 

800 

801 iq_affiliation = Iq(sto=user_jid.bare, sfrom=user_jid, stype="set") 

802 iq_affiliation["pubsub_owner"]["affiliations"]["node"] = self.plugin[ 

803 "xep_0490" 

804 ].stanza.NS 

805 

806 aff = OwnerAffiliation() 

807 aff["jid"] = self.boundjid.bare 

808 aff["affiliation"] = "member" 

809 iq_affiliation["pubsub_owner"]["affiliations"].append(aff) 

810 

811 try: 

812 await self.plugin["xep_0356"].send_privileged_iq(iq_affiliation) 

813 except PermissionError: 

814 log.warning( 

815 "IQ privileges not granted for pubsub#owner namespace, we cannot " 

816 "listen to the MDS events of %s", 

817 user_jid, 

818 ) 

819 except Exception as e: 

820 log.exception( 

821 "Error while trying to subscribe to the MDS node of %s", 

822 user_jid, 

823 exc_info=e, 

824 ) 

825 

826 async def login_wrap(self, session: AnySession) -> str: 

827 session.log.debug("In login_wrap…") 

828 session.send_gateway_status("Logging in…", show="dnd") 

829 session.is_logging_in = True 

830 try: 

831 status = await session.login() 

832 except Exception as e: 

833 log.warning("Login problem for %s", session.user_jid, exc_info=e) 

834 session.send_gateway_status(f"Could not login: {e}", show="dnd") 

835 msg = ( 

836 "You are not connected to this gateway! " 

837 f"Maybe this message will tell you why: {e}" 

838 ) 

839 session.send_gateway_message(msg) 

840 session.logged = False 

841 session.send_gateway_status("Login failed", show="dnd") 

842 return msg 

843 

844 session.log.info("Login success") 

845 session.logged = True 

846 session.log.debug("Sync contacts…") 

847 session.send_gateway_status("Syncing contacts…", show="dnd") 

848 await session.contacts._fill() 

849 if not (r := session.contacts.ready).done(): 

850 r.set_result(True) 

851 if self.ROOMS: 

852 session.log.debug("Sync rooms…") 

853 session.send_gateway_status("Syncing rooms…", show="dnd") 

854 await session.rooms._fill() 

855 if not (r := session.rooms.ready).done(): 

856 r.set_result(True) 

857 session.log.debug("Probe") 

858 self.send_presence(pto=session.user.jid.bare, ptype="probe") 

859 if status is None: 

860 status = "Logged in" 

861 session.send_gateway_status(status, show="chat") 

862 

863 if session.preferences.get("sync_avatar", False): 

864 session.create_task( 

865 self.fetch_user_avatar(session), name=f"fetch avatar of {session.user}" 

866 ) 

867 else: 

868 with self.store.session(expire_on_commit=False) as orm: 

869 session.user.avatar_hash = None 

870 orm.add(session.user) 

871 orm.commit() 

872 return status 

873 

874 async def fetch_user_avatar(self, session: AnySession) -> None: 

875 try: 

876 iq = await self.xmpp.plugin["xep_0060"].get_items( 

877 session.user_jid.bare, 

878 self.xmpp.plugin["xep_0084"].stanza.MetaData.namespace, 

879 ifrom=self.boundjid.bare, 

880 ) 

881 except IqTimeout: 

882 self.log.warning("Iq timeout trying to fetch user avatar") 

883 return 

884 except IqError as e: 

885 self.log.debug("Iq error when trying to fetch user avatar: %s", e) 

886 if e.condition == "item-not-found": 

887 try: 

888 await session.on_avatar(None, None, None, None, None) 

889 except NotImplementedError: 

890 pass 

891 else: 

892 with self.store.session(expire_on_commit=False) as orm: 

893 session.user.avatar_hash = None 

894 orm.add(session.user) 

895 orm.commit() 

896 return 

897 await self.__dispatcher.on_avatar_metadata_info( 

898 session, iq["pubsub"]["items"]["item"]["avatar_metadata"]["info"] 

899 ) 

900 

901 def _send( 

902 self, 

903 stanza: MessageOrPresenceTypeVar, 

904 **send_kwargs: Any, # noqa:ANN401 

905 ) -> MessageOrPresenceTypeVar: 

906 stanza.set_from(self.boundjid.bare) 

907 if mto := send_kwargs.get("mto"): 

908 stanza.set_to(mto) 

909 stanza.send() 

910 return stanza 

911 

912 def raise_if_not_allowed_jid(self, jid: JID) -> None: 

913 if not self.jid_validator.match(jid.bare): 

914 raise XMPPError( 

915 condition="not-allowed", 

916 text="Your account is not allowed to use this gateway. " 

917 "The admin controls that with the USER_JID_VALIDATOR option.", 

918 ) 

919 

920 def send_raw(self, data: str | bytes) -> None: 

921 # overridden from XMLStream to strip base64-encoded data from the logs 

922 # to make them more readable. 

923 if log.isEnabledFor(level=logging.DEBUG): 

924 stripped = copy(data) if isinstance(data, str) else data.decode("utf-8") 

925 # there is probably a way to do that in a single RE, 

926 # but since it's only for debugging, the perf penalty 

927 # does not matter much 

928 for el in LOG_STRIP_ELEMENTS: 

929 stripped = re.sub( 

930 f"(<{el}.*?>)(.*)(</{el}>)", 

931 "\1[STRIPPED]\3", 

932 stripped, 

933 flags=re.DOTALL | re.IGNORECASE, 

934 ) 

935 log.debug("SEND: %s", stripped) 

936 if not self.transport: 

937 raise NotConnectedError() 

938 if isinstance(data, str): 

939 data = data.encode("utf-8") 

940 self.transport.write(data) 

941 

942 def get_session_from_jid(self, j: JID) -> BaseSession | None: 

943 try: 

944 return self._session_cls.from_jid(j) 

945 except XMPPError: 

946 return None 

947 

948 def exception(self, exception: Exception) -> None: 

949 # """ 

950 # Called when a task created by slixmpp's internal (eg, on slix events) raises an Exception. 

951 # 

952 # Stop the event loop and exit on unhandled exception. 

953 # 

954 # The default :class:`slixmpp.basexmpp.BaseXMPP` behaviour is just to 

955 # log the exception, but we want to avoid undefined behaviour. 

956 # 

957 # :param exception: An unhandled :class:`Exception` object. 

958 # """ 

959 if isinstance(exception, IqError): 

960 iq = exception.iq 

961 log.error("%s: %s", iq["error"]["condition"], iq["error"]["text"]) 

962 log.warning("You should catch IqError exceptions") 

963 elif isinstance(exception, IqTimeout): 

964 iq = exception.iq 

965 log.error("Request timed out: %s", iq) 

966 log.warning("You should catch IqTimeout exceptions") 

967 elif isinstance(exception, SyntaxError): 

968 # Hide stream parsing errors that occur when the 

969 # stream is disconnected (they've been handled, we 

970 # don't need to make a mess in the logs). 

971 pass 

972 else: 

973 if exception: 

974 log.exception(exception) 

975 self.loop.stop() 

976 sys.exit(1) 

977 

978 async def make_registration_form( 

979 self, _jid: JID, _node: str, _ifrom: JID, iq: Iq 

980 ) -> Iq: 

981 self.raise_if_not_allowed_jid(iq.get_from()) 

982 reg = iq["register"] 

983 with self.store.session() as orm: 

984 user = ( 

985 orm.query(GatewayUser).filter_by(jid=iq.get_from().bare).one_or_none() 

986 ) 

987 log.debug("User found: %s", user) 

988 

989 form = reg["form"] 

990 form.add_field( 

991 "FORM_TYPE", 

992 ftype="hidden", 

993 value="jabber:iq:register", 

994 ) 

995 form["title"] = f"Registration to '{self.COMPONENT_NAME}'" 

996 form["instructions"] = self.REGISTRATION_INSTRUCTIONS 

997 

998 if user is not None: 

999 reg["registered"] = False 

1000 form.add_field( 

1001 "remove", 

1002 label="Remove my registration", 

1003 required=True, 

1004 ftype="boolean", 

1005 value=False, 

1006 ) 

1007 

1008 for field in self.REGISTRATION_FIELDS: 

1009 if field.var in reg.interfaces: 

1010 val = None if user is None else user.get(field.var) 

1011 if val is None: 

1012 reg.add_field(field.var) 

1013 else: 

1014 reg[field.var] = val 

1015 

1016 reg["instructions"] = self.REGISTRATION_INSTRUCTIONS 

1017 

1018 for field in self.REGISTRATION_FIELDS: 

1019 form.add_field( 

1020 field.var, 

1021 label=field.label, 

1022 required=field.required, 

1023 ftype=field.type, 

1024 options=field.options, 

1025 value=field.value if user is None else user.get(field.var, field.value), 

1026 ) 

1027 

1028 reply = iq.reply() 

1029 reply.set_payload(reg) 

1030 return reply # type:ignore[no-any-return] 

1031 

1032 async def user_prevalidate( 

1033 self, 

1034 ifrom: JID, 

1035 form_dict: RegistrationFormT, 

1036 fields: Iterable[FormField] | None = None, 

1037 validate: RegistrationValidationCoroutine[RegistrationFormT, ModuleDataT] 

1038 | None = None, 

1039 ) -> ModuleDataT | None: 

1040 # Pre validate a registration form using the content of self.REGISTRATION_FIELDS 

1041 # before passing it to the plugin custom validation logic 

1042 if fields is None: 

1043 fields = self.REGISTRATION_FIELDS 

1044 for field in fields: 

1045 if field.required and not form_dict.get(field.var): 

1046 raise ValueError(f"Missing field: '{field.label}'") 

1047 if validate: 

1048 return await validate(ifrom, form_dict) 

1049 else: 

1050 return await self.validate(ifrom, form_dict) 

1051 

1052 @abc.abstractmethod 

1053 async def validate( 

1054 self, user_jid: JID, registration_form: RegistrationFormT 

1055 ) -> ModuleDataT | None: 

1056 """ 

1057 Validate a user's initial registration form. 

1058 

1059 Should raise the appropriate :class:`slixmpp.exceptions.XMPPError` 

1060 if the registration does not allow to continue the registration process. 

1061 

1062 If :py:attr:`REGISTRATION_TYPE` is a 

1063 :attr:`.RegistrationType.SINGLE_STEP_FORM`, 

1064 this method should raise something if it wasn't possible to successfully 

1065 log in to the legacy service with the registration form content. 

1066 

1067 It is also used for other types of :py:attr:`REGISTRATION_TYPE` too, since 

1068 the first step is always a form. If :attr:`.REGISTRATION_FIELDS` is an 

1069 empty list (ie, it declares no :class:`.FormField`), the "form" is 

1070 effectively a confirmation dialog displaying 

1071 :attr:`.REGISTRATION_INSTRUCTIONS`. 

1072 

1073 :param user_jid: JID of the user that has just registered 

1074 :param registration_form: A dict where keys are the :attr:`.FormField.var` attributes 

1075 of the :attr:`.BaseGateway.REGISTRATION_FIELDS` iterable. 

1076 This dict can be modified and will be accessible as the ``legacy_module_data`` 

1077 of the 

1078 

1079 :return : A dict that will be stored as the persistent "legacy_module_data" 

1080 for this user. If you don't return anything here, the whole registration_form 

1081 content will be stored. 

1082 """ 

1083 raise NotImplementedError 

1084 

1085 async def validate_two_factor_code( 

1086 self, user: GatewayUser, code: str 

1087 ) -> ModuleDataT | None: 

1088 """ 

1089 Called when the user enters their 2FA code. 

1090 

1091 Should raise the appropriate :class:`slixmpp.exceptions.XMPPError` 

1092 if the login fails, and return successfully otherwise. 

1093 

1094 Only used when :attr:`REGISTRATION_TYPE` is 

1095 :attr:`.RegistrationType.TWO_FACTOR_CODE`. 

1096 

1097 :param user: The :class:`.GatewayUser` whose registration is pending 

1098 Use their :attr:`.GatewayUser.bare_jid` and/or 

1099 :attr:`.registration_form` attributes to get what you need. 

1100 :param code: The code they entered, either via "chatbot" message or 

1101 adhoc command 

1102 

1103 :return : A dict which keys and values will be added to the persistent "legacy_module_data" 

1104 for this user. 

1105 """ 

1106 raise NotImplementedError 

1107 

1108 async def get_qr_text(self, user: GatewayUser) -> str: 

1109 """ 

1110 This is where slidge gets the QR code content for the QR-based 

1111 registration process. It will turn it into a QR code image and send it 

1112 to the not-yet-fully-registered :class:`.GatewayUser`. 

1113 

1114 Only used in when :attr:`BaseGateway.REGISTRATION_TYPE` is 

1115 :attr:`.RegistrationType.QRCODE`. 

1116 

1117 :param user: The :class:`.GatewayUser` whose registration is pending 

1118 Use their :attr:`.GatewayUser.bare_jid` and/or 

1119 :attr:`.registration_form` attributes to get what you need. 

1120 """ 

1121 raise NotImplementedError 

1122 

1123 async def confirm_qr( 

1124 self, 

1125 user_bare_jid: str, 

1126 exception: Exception | None = None, 

1127 legacy_data: ModuleDataT | None = None, 

1128 ) -> None: 

1129 """ 

1130 This method is meant to be called to finalize QR code-based registration 

1131 flows, once the legacy service confirms the QR flashing. 

1132 

1133 Only used in when :attr:`BaseGateway.REGISTRATION_TYPE` is 

1134 :attr:`.RegistrationType.QRCODE`. 

1135 

1136 :param user_bare_jid: The bare JID of the almost-registered 

1137 :class:`GatewayUser` instance 

1138 :param exception: Optionally, an XMPPError to be raised to **not** confirm 

1139 QR code flashing. 

1140 :param legacy_data: dict which keys and values will be added to the persistent 

1141 "legacy_module_data" for this user. 

1142 """ 

1143 fut = self.qr_pending_registrations[user_bare_jid] 

1144 if exception is None: 

1145 fut.set_result(legacy_data) 

1146 else: 

1147 fut.set_exception(exception) 

1148 

1149 async def unregister_user( 

1150 self, user: GatewayUser, msg: str = "You unregistered from this gateway." 

1151 ) -> None: 

1152 self.send_presence(pshow="dnd", pstatus=msg, pto=user.jid) 

1153 await self.xmpp.plugin["xep_0077"].api["user_remove"](None, None, user.jid) # type:ignore[call-arg] 

1154 await self.xmpp._session_cls.kill_by_jid(user.jid) 

1155 

1156 async def input( 

1157 self, 

1158 jid: JID, 

1159 text: str | None = None, 

1160 mtype: MessageTypes = "chat", 

1161 **input_kwargs: Any, # noqa:ANN401 

1162 ) -> str: 

1163 """ 

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

1165 

1166 You shouldn't need to call this directly bust instead use 

1167 :meth:`.BaseSession.input` to directly target a user. 

1168 

1169 :param jid: The JID we want input from 

1170 :param text: A prompt to display for the user 

1171 :param mtype: Message type 

1172 :return: The user's reply 

1173 """ 

1174 return await self.__chat_commands_handler.input( 

1175 jid, text, mtype=mtype, **input_kwargs 

1176 ) 

1177 

1178 async def send_qr( 

1179 self, 

1180 text: str, 

1181 **msg_kwargs: Any, # noqa:ANN401 

1182 ) -> str | None: 

1183 """ 

1184 Sends a QR Code to a JID 

1185 

1186 You shouldn't need to call directly bust instead use 

1187 :meth:`.BaseSession.send_qr` to directly target a user. 

1188 

1189 :param text: The text that will be converted to a QR Code 

1190 :param msg_kwargs: Optional additional arguments to pass to 

1191 :meth:`.BaseGateway.send_file`, such as the recipient of the QR, 

1192 code 

1193 """ 

1194 try: 

1195 import qrcode 

1196 except ImportError: 

1197 log.error("Slidge needs the [qr] extra to be able to generate QR codes") 

1198 raise 

1199 qr = qrcode.make(text) 

1200 with tempfile.NamedTemporaryFile(suffix=".png") as f: 

1201 qr.save(f.name) 

1202 url, _msgs = await self.send_file(Path(f.name), **msg_kwargs) 

1203 return url 

1204 

1205 def shutdown(self) -> list[asyncio.Task[None]]: 

1206 # """ 

1207 # Called by the slidge entrypoint on normal exit. 

1208 # 

1209 # Sends offline presences from all contacts of all user sessions and from 

1210 # the gateway component itself. 

1211 # No need to call this manually, :func:`slidge.__main__.main` should take care of it. 

1212 # """ 

1213 log.debug("Shutting down") 

1214 tasks = [] 

1215 with self.store.session() as orm: 

1216 for user in orm.query(GatewayUser).all(): 

1217 tasks.append(self._session_cls.from_jid(user.jid).shutdown()) 

1218 self.send_presence(ptype="unavailable", pto=user.jid) 

1219 return tasks 

1220 

1221 def localpart_to_legacy_id(self, localpart: str) -> tuple[LocalpartType, str]: 

1222 """ 

1223 Converts a JID local part to a legacy ID, specifying whether this is a 

1224 group or a contact. 

1225 

1226 The default implementation mandates the "room-" and "contact-" 

1227 prefixes and applies JID (un)escaping (:xep:`0106`). 

1228 

1229 Should be overridden if you want to customize how legacy IDs map 

1230 to JIDs. This must be overridden if the default conversion is not 

1231 enough, e.g., if legacy IDs are case-sensitive. 

1232 

1233 No network calls are expected, but if a legacy ID is not of the right 

1234 type (e.g., it contains letters when it should only be numbers), this 

1235 should raise an ``XMPPError``. 

1236 

1237 Implementations must ensure consistency with 

1238 :meth:`.legacy_id_to_localpart`. 

1239 

1240 :param localpart: The local part of a JID (aka "user part" or 

1241 sometimes "node part"). 

1242 :return: (legacy entity type, legacy ID). 

1243 """ 

1244 if localpart.startswith("room-"): 

1245 return "room", unescape_node(localpart.removeprefix("room-")) 

1246 elif localpart.startswith("contact-"): 

1247 return "contact", unescape_node(localpart.removeprefix("contact-")) 

1248 else: 

1249 raise XMPPError("bad-request") 

1250 

1251 def legacy_id_to_localpart(self, type_: LocalpartType, legacy_id: str) -> str: 

1252 """ 

1253 Converts a legacy ID into a JID local part. 

1254 

1255 The default implementation adds the "room-" and "contact-" 

1256 prefixes and applies JID escaping (:xep:`0106`). 

1257 

1258 Should be overridden if you want to customize how legacy IDs map to 

1259 JIDs. This must be overridden if the default conversion is not enough, 

1260 e.g., if legacy IDs are case-sensitive. 

1261 

1262 Implementations must ensure consistency with 

1263 :meth:`.localpart_to_legacy_id`. 

1264 

1265 :param type_: Whether this is a "contact" or "room" legacy ID. 

1266 :param legacy_id: The legacy ID. 

1267 

1268 :return: A valid JID local part. 

1269 """ 

1270 match type_: 

1271 case "room": 

1272 return f"room-{escape_node(legacy_id)}" 

1273 case "contact": 

1274 return f"contact-{escape_node(legacy_id)}" 

1275 case _: 

1276 raise XMPPError("bad-request") 

1277 

1278 async def _has_feature(self, jid: JID, feature: str) -> bool: 

1279 features = await self._get_features(jid) 

1280 return feature in features 

1281 

1282 async def _get_features( 

1283 self, jid: JID, ver_string: str | None = None 

1284 ) -> Iterable[str]: 

1285 if ver_string: 

1286 info = await self.xmpp.plugin["xep_0115"].get_caps(jid, ver_string) 

1287 else: 

1288 async with self.lock(jid): 

1289 try: 

1290 iq_or_info = await self.xmpp.plugin["xep_0030"].get_info( 

1291 jid, cached=True 

1292 ) 

1293 except (IqError, IqTimeout) as e: 

1294 log.debug( 

1295 "Could not get disco#info of %s, ignoring", jid, exc_info=e 

1296 ) 

1297 return [] 

1298 info = ( 

1299 iq_or_info["disco_info"] 

1300 if isinstance(iq_or_info, Iq) 

1301 else iq_or_info 

1302 ) 

1303 assert isinstance(info, DiscoInfo) 

1304 return info.get_features() 

1305 

1306 

1307SLIXMPP_PLUGINS = [ 

1308 "xep_0030", # Service discovery 

1309 "xep_0045", # Multi-User Chat 

1310 "xep_0050", # Adhoc commands 

1311 "xep_0054", # VCard-temp (for MUC avatars) 

1312 "xep_0055", # Jabber search 

1313 "xep_0059", # Result Set Management 

1314 "xep_0066", # Out of Band Data 

1315 "xep_0071", # XHTML-IM (for stickers and custom emojis maybe later) 

1316 "xep_0077", # In-band registration 

1317 "xep_0084", # User Avatar 

1318 "xep_0085", # Chat state notifications 

1319 "xep_0100", # Gateway interaction 

1320 "xep_0106", # JID Escaping 

1321 "xep_0115", # Entity capabilities 

1322 "xep_0122", # Data Forms Validation 

1323 "xep_0128", # Service Discovery Extensions 

1324 "xep_0153", # vCard-Based Avatars (for MUC avatars) 

1325 "xep_0172", # User nickname 

1326 "xep_0184", # Message Delivery Receipts 

1327 "xep_0199", # XMPP Ping 

1328 "xep_0221", # Data Forms Media Element 

1329 "xep_0231", # Bits of Binary (for stickers and custom emojis maybe later) 

1330 "xep_0249", # Direct MUC Invitations 

1331 "xep_0264", # Jingle Content Thumbnails 

1332 "xep_0280", # Carbons 

1333 "xep_0292_provider", # VCard4 

1334 "xep_0308", # Last message correction 

1335 "xep_0313", # Message Archive Management 

1336 "xep_0317", # Hats 

1337 "xep_0319", # Last User Interaction in Presence 

1338 "xep_0333", # Chat markers 

1339 "xep_0334", # Message Processing Hints 

1340 "xep_0356", # Privileged Entity 

1341 "xep_0363", # HTTP file upload 

1342 "xep_0385", # Stateless in-line media sharing 

1343 "xep_0394", # Message Markup 

1344 "xep_0402", # PEP Native Bookmarks 

1345 "xep_0421", # Anonymous unique occupant identifiers for MUCs 

1346 "xep_0424", # Message retraction 

1347 "xep_0425", # Message moderation 

1348 "xep_0444", # Message reactions 

1349 "xep_0447", # Stateless File Sharing 

1350 "xep_0449", # Stickers 

1351 "xep_0461", # Message replies 

1352 "xep_0462", # Pubsub Type Filtering 

1353 "xep_0463", # MUC Affiliation Versioning 

1354 "xep_0469", # Bookmark Pinning 

1355 "xep_0490", # Message Displayed Synchronization 

1356 "xep_0492", # Chat Notification Settings 

1357 # "xep_0503", # Server-side spaces 

1358 "xep_0511", # Link Metadata 

1359 "xep_0513", # Intentional Mention Markup 

1360] 

1361 

1362 

1363async def _loop(coro: Callable[[], Awaitable[None]], sleep: int) -> None: 

1364 while True: 

1365 await coro() 

1366 await asyncio.sleep(sleep) 

1367 

1368 

1369def _safe_rm_parent(path: Path) -> None: 

1370 try: 

1371 path.unlink() 

1372 path.parent.rmdir() 

1373 except OSError as exc: 

1374 log.warning("%s couldn't be cleanly removed: !r", exc) 

1375 

1376 

1377LOG_STRIP_ELEMENTS = ["data", "binval"] 

1378 

1379log = logging.getLogger(__name__)