Coverage for slidge/room/room.py: 92%
672 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
1from __future__ import annotations
3import hashlib
4import json
5import logging
6import re
7import string
8import uuid
9from asyncio import Lock
10from collections.abc import AsyncIterator, Iterable, Iterator
11from contextlib import asynccontextmanager
12from copy import copy
13from datetime import UTC, datetime, timedelta
14from typing import (
15 TYPE_CHECKING,
16 Any,
17 ClassVar,
18 Literal,
19 Self,
20)
22import sqlalchemy as sa
23from slixmpp import JID, Iq, Message, Presence
24from slixmpp.exceptions import XMPPError
25from slixmpp.plugins.xep_0004.stanza.form import Form
26from slixmpp.plugins.xep_0045.stanza import MUCUserItem
27from slixmpp.plugins.xep_0082 import parse as str_to_datetime
28from slixmpp.plugins.xep_0492.stanza import WhenLiteral
29from slixmpp.xmlstream import ET
30from sqlalchemy.orm import Session as OrmSession
31from typing_extensions import TypedDict
33from ..contact.contact import LegacyContact
34from ..core.mixins.avatar import ImageMixin
35from ..core.mixins.disco import ChatterDiscoMixin
36from ..core.mixins.recipient import RecipientMixin
37from ..db.models import ArchivedMessage, Avatar, Participant, Room, Space
38from ..space import LegacySpace
39from ..util.types import (
40 AnyParticipant,
41 ExtraAttrMapping,
42 HoleBound,
43 Mention,
44 MucAffiliation,
45 RoomMessage,
46 RoomSticker,
47 RoomType,
48)
49from ..util.util import derive_wired_class, timeit, uniquify_replace
50from .archive import MessageArchive
51from .participant import LegacyParticipant
52from .participants import RoomRoster, get_resource
54if TYPE_CHECKING:
55 from ..command.base import RoomCommand
56 from ..core.session import BaseSession
57 from ..db.avatar import CachedAvatar
58 from .bookmarks import LegacyBookmarks
60ADMIN_NS = "http://jabber.org/protocol/muc#admin"
63type SubjectSetterType = "str | LegacyContact | AnyParticipant | None"
66class _RoomProps(TypedDict, total=False, closed=True):
67 name: str | None
68 n_participants: int | None
69 subject_date: datetime | None
70 type: RoomType
71 pinned: bool | None
72 notify_settings: WhenLiteral | None
73 subject_setter: SubjectSetterType | None
74 user_nick: str | None
77class LegacyRoom[
78 LegacyParticipantT: AnyParticipant = Any,
79 T: ExtraAttrMapping = Any,
80](
81 ImageMixin[T, _RoomProps],
82 ChatterDiscoMixin,
83 RecipientMixin,
84):
85 """
86 A room, a.k.a. a Multi-User Chat.
88 Room instances are obtained by calling :py:meth:`slidge.group.rooms.LegacyBookmarks`
89 on the user's :py:class:`slidge.core.session.BaseSession`.
90 """
92 max_history_fetch = 100
94 is_group: Literal[True] = True
96 DISCO_TYPE = "text"
97 DISCO_CATEGORY = "conference"
99 STABLE_ARCHIVE = False
100 """
101 Because legacy events like reactions, editions, etc. don't all map to a stanza
102 with a proper legacy ID, slidge usually cannot guarantee the stability of the archive
103 across restarts.
105 Set this to True if you know what you're doing, but realistically, this can't
106 be set to True until archive is permanently stored on disk by slidge.
108 This is just a flag on archive responses that most clients ignore anyway.
109 """
111 """
112 Set this to true if the fill_participants() / fill_participants() design does not
113 fit the legacy API, ie, no lazy loading of the participant list and history.
114 """
116 HAS_DESCRIPTION = True
117 """
118 Set this to false if the legacy network does not allow setting a description
119 for the group. In this case the description field will not be present in the
120 room configuration form.
121 """
123 HAS_SUBJECT = True
124 """
125 Set this to false if the legacy network does not allow setting a subject
126 (sometimes also called topic) for the group. In this case, as a subject is
127 recommended by :xep:`0045` ("SHALL"), the description (or the group name as
128 ultimate fallback) will be used as the room subject.
129 By setting this to false, an error will be returned when the :term:`User`
130 tries to set the room subject.
131 """
133 archive: MessageArchive
135 _stored: Room
137 _commands: ClassVar[dict[str, type[RoomCommand[Any]]]] = {}
138 _commands_chat: ClassVar[dict[str, type[RoomCommand[Any]]]] = {}
140 _participant_cls: type[LegacyParticipantT]
141 """
142 The concrete :class:`.LegacyParticipant` subclass this Room produces.
144 Derived automatically from the generic parameter, e.g.,
145 ``class Room(LegacyRoom[Participant])`` produces ``Participant`` instances.
146 """
148 is_participant: Literal[False] = False
150 extra_attributes: T
152 _session: BaseSession[Any, LegacyBookmarks[Self]]
154 def __init_subclass__(cls, **kwargs: object) -> None:
155 super().__init_subclass__(**kwargs)
156 derive_wired_class(cls, LegacyRoom, "_participant_cls")
158 def __init__(
159 self, session: BaseSession[Any, LegacyBookmarks[Self]], stored: Room
160 ) -> None:
161 self._session = session
162 self.xmpp = session.xmpp
163 self._stored = stored
164 self._set_logger()
165 self.participants = RoomRoster[LegacyParticipantT](self)
166 super().__init__()
168 self.archive = MessageArchive(stored, self.xmpp.store)
170 async def on_message(self, message: RoomMessage[LegacyParticipantT]) -> str | None:
171 """
172 Triggered when the user sends a message to this :term:`Room`.
174 :return: A message ID of that can be used later to further reference
175 this message (reactions, read marks, etc.).
176 """
177 raise NotImplementedError
179 async def on_sticker(self, sticker: RoomSticker) -> str | None:
180 """
181 Triggered when the user sends a sticker to this :term:`Room`.
183 :param sticker: The sticker sent by the user.
185 :return: A message ID of that can be used later to further reference
186 this message (reactions, read marks, etc.).
187 """
188 raise NotImplementedError
190 def pop_unread_xmpp_ids_up_to(self, horizon_xmpp_id: str) -> list[str]:
191 """
192 Return XMPP msg ids sent in this group up to a given XMPP msg id.
194 Plugins have no reason to use this, but it is used by slidge core
195 for legacy networks that need to mark *all* messages as read (most XMPP
196 clients only send a read marker for the latest message).
198 This has side effects: all messages up to the horizon XMPP id will be marked
199 as read in the DB. If the horizon XMPP id is not found, all messages of this
200 Room will be marked as read.
202 :param horizon_xmpp_id: The latest message
203 :return: A list of XMPP ids if horizon_xmpp_id was not found
204 """
205 with self.xmpp.store.session() as orm:
206 assert self._stored.id is not None
207 ids = self.xmpp.store.mam.pop_unread_up_to(
208 orm, self._stored.id, horizon_xmpp_id
209 )
210 orm.commit()
211 return ids
213 @property
214 def jid(self) -> JID:
215 return self._stored.jid
217 @property
218 def legacy_id(self) -> str:
219 return self._stored.legacy_id
221 def __stored_space(self) -> Space | None:
222 self._stored.ensure_relation("space", self.xmpp.store.session)
223 return self._stored.space
225 @property
226 def space(self) -> LegacySpace | None:
227 stored = self.__stored_space()
228 if stored is None:
229 return None
230 return self._session.spaces.get(
231 stored.legacy_id
232 ) or self._session.spaces._from_store(stored)
234 @space.setter
235 def space(self, space: LegacySpace | None) -> None:
236 self._stored.ensure_relation("space", self.xmpp.store.session)
237 old = self._stored.space
239 new = space._stored if space else None
240 new_id = space._stored.id if space else None
242 self._update_stored_attribute(space_id=new_id)
243 self._stored._set_committed_value("space", new)
244 self._stored._set_committed_value("space_id", new_id)
246 if not self._session.rooms.ready.done():
247 return
249 if old is not None:
250 old.ensure_relation("avatar", self._session.xmpp.store.session)
251 old.ensure_relation("banner", self._session.xmpp.store.session)
252 old.load_rooms(self._session.xmpp.store.session)
253 self.xmpp.pubsub.broadcast_space(
254 self._session,
255 old,
256 self._session.spaces.legacy_id_to_node(old.legacy_id),
257 [str(self.jid)],
258 )
259 if new is not None:
260 new._set_committed_value("rooms", [self._stored])
261 self.xmpp.pubsub.broadcast_space(
262 self._session,
263 new,
264 self._session.spaces.legacy_id_to_node(new.legacy_id),
265 [str(self.jid)],
266 )
268 def __orm(
269 self,
270 **kwargs: Any, # noqa:ANN401
271 ) -> OrmSession:
272 return self.xmpp.store.session(**kwargs)
274 @property
275 def type(self) -> RoomType:
276 return self._stored.type
278 @type.setter
279 def type(self, type_: RoomType) -> None:
280 self._update_stored_attribute(type=type_)
281 self._session.rooms.schedule_pep_add(self, "type change")
283 @property
284 def n_participants(self) -> int | None:
285 self._stored.ensure_loaded("disco", self.xmpp.store.session)
286 return self._stored.n_participants
288 @n_participants.setter
289 def n_participants(self, n_participants: int | None) -> None:
290 self._update_stored_attribute(n_participants=n_participants)
292 def _set_logger(self) -> None:
293 self.log = logging.getLogger(f"{self.user_jid}:muc:{self}")
295 def __repr__(self) -> str:
296 return f"<Room #{self._stored.id} '{self.name}' ({self._stored.legacy_id} - {self.jid.user})'>"
298 @property
299 def subject_date(self) -> datetime | None:
300 self._stored.ensure_loaded("subject", self.xmpp.store.session)
301 if self._stored.subject_date is None:
302 return None
303 return self._stored.subject_date.replace(tzinfo=UTC)
305 @subject_date.setter
306 def subject_date(self, when: datetime | None) -> None:
307 self._update_stored_attribute(subject_date=when)
309 def __send_configuration_change(self, codes: tuple[int, ...]) -> None:
310 part = self.get_system_participant()
311 part.send_configuration_change(codes)
313 @property
314 def user_nick(self) -> str:
315 return (
316 self._stored.user_nick
317 or self._session.rooms.user_nick
318 or self.user_jid.node
319 )
321 @user_nick.setter
322 def user_nick(self, nick: str) -> None:
323 self._update_stored_attribute(user_nick=nick)
325 def add_user_resource(self, resource: str) -> None:
326 stored_set = self.get_user_resources()
327 if resource in stored_set:
328 return
329 stored_set.add(resource)
330 self._update_stored_attribute(
331 user_resources=(json.dumps(list(stored_set)) if stored_set else None)
332 )
334 def get_user_resources(self) -> set[str]:
335 stored_str = self._stored.user_resources
336 if stored_str is None:
337 return set()
338 return set(json.loads(stored_str))
340 def remove_user_resource(self, resource: str) -> None:
341 stored_set = self.get_user_resources()
342 if resource not in stored_set:
343 return
344 stored_set.remove(resource)
345 self._update_stored_attribute(
346 user_resources=(json.dumps(list(stored_set)) if stored_set else None)
347 )
349 @asynccontextmanager
350 async def lock(self, id_: str) -> AsyncIterator[None]:
351 async with self._session.lock((self.legacy_id, id_)):
352 yield
354 def get_lock(self, id_: str) -> Lock | None:
355 return self._session.get_lock((self.legacy_id, id_))
357 async def get_participants(
358 self, affiliation: MucAffiliation | None = None
359 ) -> AsyncIterator[LegacyParticipantT]:
360 await self.participants.ensure_filled()
361 for p in self.participants.__iter__(affiliation):
362 yield p
364 async def __fill_history(self) -> None:
365 async with self.lock("fill history"):
366 with self.xmpp.store.session(expire_on_commit=False) as orm:
367 self._stored._set_committed_value(
368 "history_filled",
369 orm.scalar(
370 sa.select(
371 Room.history_filled,
372 ).where(Room.id == self._stored.id)
373 ),
374 )
375 if self._stored.history_filled:
376 self.log.debug("History has already been fetched.")
377 return
378 log.debug("Fetching history for %s", self)
379 try:
380 await self.backfill(*self.archive.get_hole_bounds())
381 except NotImplementedError:
382 return
383 except Exception as e:
384 self.log.exception("Could not backfill", exc_info=e)
385 finally:
386 self._update_stored_attribute(history_filled=True)
388 def _get_disco_name(self) -> str | None:
389 return self.name
391 @property
392 def name(self) -> str | None:
393 return self._stored.name
395 @name.setter
396 def name(self, n: str | None) -> None:
397 if not self._update_stored_attribute(name=n):
398 return
399 self._set_logger()
400 self.__send_configuration_change((104,))
402 @property
403 def description(self) -> str:
404 self._stored.ensure_loaded("disco", self.xmpp.store.session)
405 return self._stored.description or ""
407 @description.setter
408 def description(self, d: str | None) -> None:
409 d = d or ""
411 if not self._update_stored_attribute(description=d):
412 return
413 self.__send_configuration_change((104,))
415 def on_presence_unavailable(self, p: Presence) -> None:
416 pto = p.get_to()
417 if pto.bare != self.jid.bare:
418 return
420 pfrom = p.get_from()
421 if pfrom.bare != self.user_jid.bare:
422 return
423 if (resource := pfrom.resource) in self.get_user_resources():
424 if pto.resource != self.user_nick:
425 self.log.debug(
426 "Received 'leave group' request but with wrong nickname. %s", p
427 )
428 self.remove_user_resource(resource)
429 else:
430 self.log.debug(
431 "Received 'leave group' request but resource was not listed. %s", p
432 )
434 async def backfill(
435 self,
436 after: HoleBound | None = None,
437 before: HoleBound | None = None,
438 ) -> None:
439 """
440 Override this if the legacy network provide server-side group archives.
442 In it, send history messages using ``self.participants.get_or_create(...).send_xxxx``.
443 This is only called once per slidge run for a given group.
445 :param after: Fetch messages after this one.
446 If ``None``, slidge's local archive was empty before start-up,
447 ie, no history was ever fetched for this room since the user registered.
448 It's up to gateway implementations to decide how far to fetch messages before
449 the user registered.
450 If not ``None``, slidge has some messages in this archive, and
451 the gateway shall try to fetch history up to (and excluding) this message
452 to avoid "holes" in the history of this group.
453 :param before: Fetch messages before this one.
454 If ``None``, the gateway shall fetch all messages up to the most recent one.
455 If not ``None``, slidge has already archived some live messages
456 it received during its lifetime, and there is no need to query the legacy
457 network for any message after (and including) this one.
458 """
459 raise NotImplementedError
461 async def fill_participants(self) -> AsyncIterator[LegacyParticipantT]:
462 """
463 This method should yield the list of all members of this room.
465 It will only be called once per-room, only when actually needed by
466 an XMPP action (typically joining the room).
467 """
468 return
469 yield
471 @property
472 def subject(self) -> str:
473 self._stored.ensure_loaded("subject", self.xmpp.store.session)
474 return self._stored.subject or ""
476 @subject.setter
477 def subject(self, s: str) -> None:
478 if not self._update_stored_attribute(subject=s):
479 return
480 self.__get_subject_setter_participant().set_room_subject(
481 s, None, self.subject_date, False
482 )
484 @property
485 def is_anonymous(self) -> bool:
486 return self.type == RoomType.CHANNEL
488 @property
489 def subject_setter(self) -> str | None:
490 self._stored.ensure_loaded("subject", self.xmpp.store.session)
491 return self._stored.subject_setter
493 @subject_setter.setter
494 def subject_setter(self, subject_setter: SubjectSetterType) -> None:
495 if isinstance(subject_setter, LegacyContact):
496 subject_setter = subject_setter.name
497 elif isinstance(subject_setter, LegacyParticipant):
498 subject_setter = subject_setter.nickname
500 assert isinstance(subject_setter, str | None)
501 self._update_stored_attribute(subject_setter=subject_setter)
503 def __get_subject_setter_participant(self) -> AnyParticipant:
504 if self.subject_setter:
505 nick = self.subject_setter or "subject-setter"
506 return self._participant_cls(
507 self,
508 Participant(
509 nickname=nick,
510 resource=get_resource(nick),
511 ),
512 )
513 else:
514 return self.get_system_participant()
516 @property
517 def notify_settings(self) -> WhenLiteral | None:
518 self._stored.ensure_loaded("bookmarks", self.__orm)
519 return self._stored.notify_settings
521 @notify_settings.setter
522 def notify_settings(self, when: WhenLiteral | None) -> None:
523 if self._update_stored_attribute(notify_settings=when):
524 self._session.rooms.schedule_pep_add(self, "notify setting change")
526 @property
527 def pinned(self) -> bool | None:
528 self._stored.ensure_loaded("bookmarks", self.__orm)
529 return self._stored.pinned
531 @pinned.setter
532 def pinned(self, pinned: bool | None) -> None:
533 if self._update_stored_attribute(pinned=pinned):
534 self._session.rooms.schedule_pep_add(self, "pinned change")
536 def features(self) -> list[str]:
537 features = [
538 "http://jabber.org/protocol/muc",
539 "http://jabber.org/protocol/muc#stable_id",
540 "http://jabber.org/protocol/muc#self-ping-optimization",
541 "urn:xmpp:mam:2",
542 "urn:xmpp:mam:2#extended",
543 "urn:xmpp:sid:0",
544 "muc_persistent",
545 "vcard-temp",
546 "urn:xmpp:ping",
547 "urn:xmpp:occupant-id:0",
548 "jabber:iq:register",
549 "http://jabber.org/protocol/commands",
550 "urn:xmpp:muc:affiliations:1",
551 self.xmpp.plugin["xep_0425"].stanza.NS,
552 ]
553 if self.type == RoomType.GROUP:
554 features.extend(["muc_membersonly", "muc_nonanonymous", "muc_hidden"])
555 elif self.type == RoomType.CHANNEL:
556 features.extend(["muc_open", "muc_semianonymous", "muc_public"])
557 elif self.type == RoomType.CHANNEL_NON_ANONYMOUS:
558 features.extend(["muc_open", "muc_nonanonymous", "muc_public"])
560 if self._stored.space_id is not None:
561 features.append("urn:xmpp:spaces:0")
562 return features
564 async def extended_features(self) -> list[Form]:
565 is_group = self.type == RoomType.GROUP
567 form = self.xmpp.plugin["xep_0004"].make_form(ftype="result")
569 form.add_field(
570 "FORM_TYPE", "hidden", value="http://jabber.org/protocol/muc#roominfo"
571 )
572 form.add_field("muc#roomconfig_persistentroom", "boolean", value=True)
573 form.add_field("muc#roomconfig_changesubject", "boolean", value=False)
574 form.add_field("muc#maxhistoryfetch", value=str(self.max_history_fetch))
575 form.add_field("muc#roominfo_subjectmod", "boolean", value=False)
577 self._stored.ensure_loaded("disco", self.xmpp.store.session)
578 if self.participants_filled:
579 with self.xmpp.store.session() as orm:
580 n = orm.scalar(
581 sa.select(sa.func.count(Participant.id)).filter_by(
582 room_id=self._stored.id
583 )
584 )
585 else:
586 n = self._stored.n_participants
588 if n is not None:
589 form.add_field("muc#roominfo_occupants", value=str(n))
591 if d := self._stored.description:
592 form.add_field("muc#roominfo_description", value=d)
594 if s := self.subject:
595 form.add_field("muc#roominfo_subject", value=s)
597 if name := self.name:
598 form.add_field("muc#roomconfig_roomname", value=name)
600 if self._set_avatar_task is not None:
601 await self._set_avatar_task
602 avatar = self.get_avatar()
603 if avatar and (h := avatar.id):
604 form.add_field(
605 "{http://modules.prosody.im/mod_vcard_muc}avatar#sha1", value=h
606 )
607 form.add_field("muc#roominfo_avatarhash", "text-multi", value=[h])
608 if avatar.url:
609 form.add_field("{http://slidge.im}/avatar#url", value=avatar.url)
611 form.add_field("muc#roomconfig_membersonly", "boolean", value=is_group)
612 form.add_field(
613 "muc#roomconfig_whois",
614 "list-single",
615 value="moderators" if self.is_anonymous else "anyone",
616 )
617 form.add_field("muc#roomconfig_publicroom", "boolean", value=not is_group)
618 form.add_field("muc#roomconfig_allowpm", "boolean", value=False)
620 r = [form]
622 if reaction_form := await self.restricted_emoji_extended_feature():
623 r.append(reaction_form)
625 if self._stored.space_id is not None:
626 stored = self.__stored_space()
627 assert stored is not None
628 node = self._session.spaces.legacy_id_to_node(stored.legacy_id)
629 iri = f"xmpp:{self.xmpp.boundjid.bare}?node={node}"
630 form.add_field("muc#roominfo_pubsub", value=iri)
631 space_form = self.xmpp.plugin["xep_0004"].make_form(ftype="result")
632 space_form.add_field("FORM_TYPE", "hidden", value="urn:xmpp:spaces:0")
633 space_form.add_field("parent", label="Space parent", value=iri)
635 return r
637 def user_full_jids(self) -> Iterable[JID]:
638 for r in self.get_user_resources():
639 j = JID(self.user_jid)
640 j.resource = r
641 yield j
643 @property
644 def user_muc_jid(self) -> JID:
645 return self.participants.get_user().jid
647 async def echo(
648 self, msg: Message, legacy_msg_id: str | None = None, replace: str | None = None
649 ) -> str:
650 msg.set_from(self.user_muc_jid)
651 if replace and not (legacy_msg_id or legacy_msg_id == replace):
652 msg["stanza_id"]["id"] = uniquify_replace(replace)
653 elif legacy_msg_id:
654 msg["stanza_id"]["id"] = legacy_msg_id
655 else:
656 msg["stanza_id"]["id"] = str(uuid.uuid4())
657 msg["stanza_id"]["by"] = self.jid
659 user_part = self.participants.get_user()
660 msg["occupant-id"]["id"] = user_part.occupant_id
662 self.archive.add(msg, user_part, legacy_msg_id=legacy_msg_id)
664 for user_full_jid in self.user_full_jids():
665 self.log.debug("Echoing to %s", user_full_jid)
666 msg = copy(msg)
667 msg.set_to(user_full_jid)
669 msg.send()
671 return msg["stanza_id"]["id"] # type:ignore[no-any-return]
673 def _post_image_update(
674 self, cached_avatar: CachedAvatar | None, *, attr: str = "avatar"
675 ) -> None:
676 self.__send_configuration_change((104,))
677 self._send_room_presence()
679 def _send_room_presence(self, user_full_jid: JID | None = None) -> None:
680 tos = self.user_full_jids() if user_full_jid is None else [user_full_jid]
681 for to in tos:
682 p = self.xmpp.make_presence(pfrom=self.jid, pto=to)
683 if (avatar := self.get_avatar()) and (h := avatar.id):
684 p["vcard_temp_update"]["photo"] = h
685 if avatar.http_metadata is not None:
686 metadata = self.xmpp.plugin["xep_0084"].stanza.MetaData()
687 metadata.append(avatar.http_metadata)
688 p.append(metadata)
689 else:
690 p["vcard_temp_update"]["photo"] = ""
691 p.send()
693 @timeit
694 async def join(self, join_presence: Presence) -> None:
695 user_full_jid = join_presence.get_from()
696 requested_nickname = join_presence.get_to().resource
697 client_resource = user_full_jid.resource
699 if client_resource in self.get_user_resources():
700 self.log.debug("Received join from a resource that is already joined.")
702 if not requested_nickname or not client_resource:
703 raise XMPPError("jid-malformed", by=self.jid)
705 self.add_user_resource(client_resource)
707 self.log.debug(
708 "Resource %s of %s wants to join room %s with nickname %s",
709 client_resource,
710 self.user_jid,
711 self.legacy_id,
712 requested_nickname,
713 )
715 await self.participants.ensure_filled(with_presence=True)
716 self._stored.load_participants(self.__orm, with_presence=True)
717 if "mav" in join_presence["muc_join"]:
718 mav_until = await self.__get_mav()
719 self.log.debug("client uses Room affiliation versioning")
720 if join_presence["muc_join"]["mav"]["since"] != mav_until:
721 self.log.debug(
722 "client mav: %s vs our mav: %s",
723 join_presence["muc_join"]["mav"]["since"],
724 mav_until,
725 )
726 await self.__send_mav(user_full_jid, mav_until)
727 else:
728 mav_until = None
730 self.log.debug("Sending presences for join of %s", client_resource)
732 self._stored.load_participants(self.xmpp.store.session, with_presence=True)
733 user_participant = None
735 for db_participant in self._stored.participants:
736 participant = self.participants._from_store(db_participant)
737 if participant.is_user:
738 user_participant = participant
739 continue
740 participant.send_initial_presence(full_jid=user_full_jid)
742 if user_participant is None:
743 user_participant = self.participants.get_user()
744 with self.xmpp.store.session() as orm:
745 orm.add(self._stored)
746 with orm.no_autoflush:
747 orm.refresh(self._stored, ["participants"])
748 if not user_participant.is_user:
749 self.log.warning("is_user flag not set on user_participant")
750 user_participant.is_user = True
751 user_participant.send_initial_presence(
752 user_full_jid,
753 presence_id=join_presence["id"],
754 nick_change=user_participant.jid.resource != requested_nickname,
755 mav_until=mav_until,
756 )
758 self.log.debug("Sending presences for join of %s: DONE", client_resource)
760 history_params = join_presence["muc_join"]["history"]
761 maxchars = int_or_none(history_params["maxchars"])
762 maxstanzas = int_or_none(history_params["maxstanzas"])
763 seconds = int_or_none(history_params["seconds"])
764 try:
765 since = self.xmpp.plugin["xep_0082"].parse(history_params["since"])
766 except ValueError:
767 since = None
768 if seconds is not None:
769 since = datetime.now(tz=UTC) - timedelta(seconds=seconds)
770 if equals_zero(maxchars) or equals_zero(maxstanzas):
771 log.debug(
772 "Joining client does not want any old-school Room history-on-join"
773 )
774 else:
775 self.log.debug("Old school history fill")
776 await self.__fill_history()
777 await self.__old_school_history(
778 user_full_jid,
779 maxchars=maxchars,
780 maxstanzas=maxstanzas,
781 since=since,
782 )
783 if self.HAS_SUBJECT:
784 subject = self.subject or ""
785 else:
786 subject = self.description or self.name or ""
787 self.__get_subject_setter_participant().set_room_subject(
788 subject,
789 user_full_jid,
790 self.subject_date,
791 update_muc=False,
792 )
793 if t := self._set_avatar_task:
794 await t
795 self._send_room_presence(user_full_jid)
797 async def __get_mav(self) -> str:
798 data = self.__get_mav_data()
799 return self.__compute_mav_ver(data)
801 def __get_mav_data(self) -> list[tuple[str, MucAffiliation]]:
802 data: list[tuple[str, MucAffiliation]] = []
804 self._stored.load_participants(self.__orm, with_presence=False)
805 for part in self._stored.participants:
806 if not (part.is_user or part.contact):
807 continue
808 if part.affiliation == "none":
809 continue
810 data.append((self.__get_part_mav_id(part), part.affiliation))
811 return data
813 def __get_part_mav_id(self, part: LegacyParticipantT | Participant) -> str:
814 return str(self.user_jid if part.is_user else part.contact.legacy_id) # type:ignore[union-attr] # ty:ignore[unresolved-attribute]
816 def __compute_mav_ver(self, data: list[tuple[Any, MucAffiliation]]) -> str:
817 self.log.debug("MAV data: %s", data)
818 affs = []
819 for id_, aff in data:
820 if aff == "none":
821 continue
822 affs.append(f"{id_}\0{aff}".encode())
823 affs.sort()
824 return hashlib.sha256(b"\0".join(affs)).hexdigest()
826 async def __send_mav(self, full_jid: JID, until: str) -> None:
827 self.log.debug("Sending MAV")
828 msg = self.xmpp.make_message(mto=full_jid, mfrom=self.jid)
829 msg["muc"]["mav"]["until"] = until
830 for part in self._stored.participants:
831 if not (part.is_user or part.contact):
832 continue
833 item = MUCUserItem()
834 item["jid"] = self.user_jid if part.is_user else part.contact.jid.bare # type:ignore[union-attr]
835 item["affiliation"] = part.affiliation
836 msg["muc"].append(item)
837 msg.send()
839 def send_affiliation_change(
840 self, part: LegacyParticipantT, was: MucAffiliation = "none"
841 ) -> None:
842 # internal use by slidge
843 if not self.participants_filled:
844 return
845 if self.get_lock("fill participants"):
846 return
847 if self.get_lock("fill history"):
848 return
849 if part.contact is None:
850 return
851 if part.is_system:
852 return
853 if was == part.affiliation:
854 return
855 system_part = self.get_system_participant()
856 msg = system_part._make_message(mtype="normal")
857 until = self.__get_mav_data()
858 since = [
859 (id_, was if id_ == self.__get_part_mav_id(part) else aff)
860 for id_, aff in until
861 ]
862 if part.affiliation == "none":
863 since.append((self.__get_part_mav_id(part), was))
864 msg["muc"]["mav"]["since"] = self.__compute_mav_ver(since)
865 msg["muc"]["mav"]["until"] = self.__compute_mav_ver(until)
866 item = MUCUserItem()
867 item["affiliation"] = part.affiliation
868 item["jid"] = self.user_jid if part.is_user else part.contact.jid.bare
869 msg["muc"].append(item)
870 system_part._send(msg)
872 def get_system_participant(self) -> LegacyParticipantT:
873 """
874 Get a pseudo-participant, representing the room itself
876 Can be useful for events that cannot be mapped to a participant,
877 e.g. anonymous moderation events, or announces from the legacy
878 service
879 :return:
880 """
881 return self._participant_cls(
882 self, Participant(occupant_id="room"), is_system=True
883 )
885 def remove_participant(
886 self,
887 p: LegacyParticipantT,
888 kick: bool = False,
889 ban: bool = False,
890 reason: str | None = None,
891 ) -> None:
892 """
893 Call this when a participant leaves the room
895 :param p: The participant
896 :param kick: Whether the participant left because they were kicked
897 :param ban: Whether the participant left because they were banned
898 :param reason: Optionally, a reason why the participant was removed.
899 """
900 self.log.debug("Removing participant: %s", p)
901 if kick and ban:
902 raise TypeError("Either kick or ban")
903 if kick:
904 codes = {307}
905 elif ban:
906 codes = {301}
907 else:
908 codes = None
909 was = p._stored.affiliation
910 p._stored.affiliation = "outcast" if ban else "none"
911 p._stored.role = "none"
912 presence = p._make_presence(ptype="unavailable", status_codes=codes)
913 with self.__orm() as orm:
914 self.xmpp.store.participants.delete(orm, p._stored.id)
915 orm.commit()
916 self._stored.delete_participant(p._stored)
917 self.send_affiliation_change(p, was)
918 if reason:
919 presence["muc"].set_item_attr("reason", reason)
920 p._send(presence, force=True)
922 def rename_participant(self, old_nickname: str, new_nickname: str) -> None:
923 part = self.participants.get_by_nick(old_nickname)
924 if part is None:
925 self.log.debug("Tried to rename a participant that we didn't know")
926 return
927 part.nickname = new_nickname
929 async def __old_school_history(
930 self,
931 full_jid: JID,
932 maxchars: int | None = None,
933 maxstanzas: int | None = None,
934 seconds: int | None = None,
935 since: datetime | None = None,
936 ) -> None:
937 """
938 Old-style history join (internal slidge use)
940 :param full_jid:
941 :param maxchars:
942 :param maxstanzas:
943 :param seconds:
944 :param since:
945 :return:
946 """
947 if since is None:
948 if seconds is None:
949 start_date = datetime.now(tz=UTC) - timedelta(days=1)
950 else:
951 start_date = datetime.now(tz=UTC) - timedelta(seconds=seconds)
952 else:
953 start_date = since or datetime.now(tz=UTC) - timedelta(days=1)
955 for h_msg in self.archive.get_all(
956 start_date=start_date, end_date=None, last_page_n=maxstanzas
957 ):
958 msg = h_msg.stanza("jabber:component:accept", user_jid=self.user_jid.bare)
959 msg["delay"]["stamp"] = h_msg.timestamp.replace(tzinfo=UTC)
960 msg["delay"]["from"] = self.jid
961 msg.set_to(full_jid)
962 self.xmpp.send(msg, False)
964 async def send_mam(self, iq: Iq) -> None:
965 await self.__fill_history()
967 form_values = iq["mam"]["form"].get_values()
969 start_date = str_to_datetime_or_none(form_values.get("start"))
970 end_date = str_to_datetime_or_none(form_values.get("end"))
972 after_id = form_values.get("after-id")
973 before_id = form_values.get("before-id")
975 ids = form_values.get("ids") or ()
977 if max_str := iq["mam"]["rsm"]["max"]:
978 try:
979 max_results = int(max_str)
980 except ValueError:
981 max_results = None
982 else:
983 max_results = None
985 after_id_rsm = iq["mam"]["rsm"]["after"]
986 after_id = after_id_rsm or after_id
988 before_rsm = iq["mam"]["rsm"]["before"]
989 if before_rsm is not None and max_results is not None:
990 last_page_n = max_results
991 # - before_rsm is True means the empty element <before />, which means
992 # "last page in chronological order", cf https://xmpp.org/extensions/xep-0059.html#backwards
993 # - before_rsm == "an ID" means <before>an ID</before>
994 if before_rsm is not True:
995 before_id = before_rsm
996 else:
997 last_page_n = None
999 first = None
1000 last = None
1001 count = 0
1003 sender = form_values.get("with")
1004 sender_resource = JID(sender).resource if sender else None
1006 it = self.archive.get_all(
1007 start_date,
1008 end_date,
1009 before_id,
1010 after_id,
1011 ids,
1012 last_page_n,
1013 sender_resource,
1014 bool(iq["mam"]["flip_page"]),
1015 )
1017 for history_msg in it:
1018 last = xmpp_id = history_msg.stanza_id
1019 if first is None:
1020 first = xmpp_id
1022 wrapper_msg = self.xmpp.make_message(mfrom=self.jid, mto=iq.get_from())
1023 wrapper_msg["mam_result"]["queryid"] = iq["mam"]["queryid"]
1024 wrapper_msg["mam_result"]["id"] = xmpp_id
1025 wrapper_msg["mam_result"].append(
1026 history_msg.forwarded(user_jid=self.user_jid.bare)
1027 )
1029 wrapper_msg.send()
1030 count += 1
1032 if max_results and count == max_results:
1033 break
1035 if max_results:
1036 try:
1037 next(it)
1038 except StopIteration:
1039 complete = True
1040 else:
1041 complete = False
1042 else:
1043 complete = True
1045 reply = iq.reply()
1046 if not self.STABLE_ARCHIVE:
1047 reply["mam_fin"]["stable"] = "false"
1048 if complete:
1049 reply["mam_fin"]["complete"] = "true"
1050 reply["mam_fin"]["rsm"]["first"] = first
1051 reply["mam_fin"]["rsm"]["last"] = last
1052 reply["mam_fin"]["rsm"]["count"] = str(count)
1053 reply.send()
1055 async def send_mam_metadata(self, iq: Iq) -> None:
1056 await self.__fill_history()
1057 await self.archive.send_metadata(iq)
1059 async def kick_resource(self, r: str) -> None:
1060 """
1061 Kick a XMPP client of the user. (slidge internal use)
1063 :param r: The resource to kick
1064 """
1065 pto = JID(self.user_jid)
1066 pto.resource = r
1067 p = self.xmpp.make_presence(pfrom=(self.participants.get_user()).jid, pto=pto)
1068 p["type"] = "unavailable"
1069 p["muc"]["affiliation"] = "none"
1070 p["muc"]["role"] = "none"
1071 p["muc"]["status_codes"] = {110, 333}
1072 p.send()
1074 def _on_delete(self) -> None:
1075 self._session.create_task(
1076 self._session.rooms._pep_del(self), f"Remove {self} from PEP bookmarks"
1077 )
1079 async def on_avatar(self, data: bytes | None, mime: str | None) -> str | None:
1080 """
1081 Called when the user tries to set the avatar of the room from an XMPP
1082 client.
1084 If the set avatar operation is completed, should return a legacy image
1085 unique identifier. In this case the Room avatar will be immediately
1086 updated on the XMPP side.
1088 If data is not None and this method returns None, then we assume that
1089 self.set_avatar() will be called elsewhere, eg triggered by a legacy
1090 room update event.
1092 :param data: image data or None if the user meant to remove the avatar
1093 :param mime: the mime type of the image. Since this is provided by
1094 the XMPP client, there is no guarantee that this is valid or
1095 correct.
1096 :return: A unique avatar identifier, which will trigger
1097 :py:meth:`slidge.group.room.LegacyRoom.set_avatar`. Alternatively, None, if
1098 :py:meth:`.LegacyRoom.set_avatar` is meant to be awaited somewhere else.
1099 """
1100 raise NotImplementedError
1102 async def on_set_config(
1103 self,
1104 name: str | None,
1105 description: str | None,
1106 ) -> None:
1107 """
1108 Triggered when the user requests changing the room configuration.
1109 Only title and description can be changed at the moment.
1111 The legacy module is responsible for updating :attr:`.title` and/or
1112 :attr:`LegacyRoom.description` of this instance.
1114 If :attr:`.HAS_DESCRIPTION` is set to False, description will always
1115 be ``None``.
1117 :param name: The new name of the room.
1118 :param description: The new description of the room.
1119 """
1120 raise NotImplementedError
1122 async def on_destroy_request(self, reason: str | None) -> None:
1123 """
1124 Triggered when the user requests room destruction.
1126 :param reason: Optionally, a reason for the destruction
1127 """
1128 raise NotImplementedError
1130 async def parse_mentions(
1131 self, text: str | None
1132 ) -> tuple[Mention[LegacyParticipantT], ...]:
1133 if not text or not self._session.preferences.get("parse_mentions", True):
1134 return ()
1135 await self.participants.ensure_filled()
1136 with self.xmpp.store.session() as orm:
1137 orm.add(self._stored)
1138 participants = {
1139 p.nickname: p for p in self._stored.participants if len(p.nickname) > 1
1140 }
1142 if len(participants) == 0:
1143 return ()
1145 result = []
1146 for match in re.finditer(
1147 "|".join(
1148 sorted(
1149 [re.escape(nick) for nick in participants],
1150 key=lambda nick: len(nick),
1151 reverse=True,
1152 )
1153 ),
1154 text,
1155 ):
1156 span = match.span()
1157 nick = match.group()
1158 if span[0] != 0 and text[span[0] - 1] not in _WHITESPACE_OR_PUNCTUATION:
1159 continue
1160 if span[1] == len(text) or text[span[1]] in _WHITESPACE_OR_PUNCTUATION:
1161 participant = self.participants._from_store(
1162 stored=participants[nick]
1163 )
1164 result.append(
1165 Mention(participant=participant, start=span[0], end=span[1])
1166 )
1167 return tuple(result)
1169 async def on_set_subject(self, subject: str) -> None:
1170 """
1171 Triggered when the user requests changing the room subject.
1173 The legacy module is responsible for updating :attr:`.subject` of this
1174 instance.
1176 :param subject: The new subject for this room.
1177 """
1178 raise NotImplementedError
1180 async def on_set_thread_subject(self, thread: str, subject: str) -> None:
1181 """
1182 Triggered when the user requests changing the subject of a specific thread.
1184 :param thread: Legacy identifier of the thread
1185 :param subject: The new subject for this thread.
1186 """
1187 raise NotImplementedError
1189 async def on_moderate(self, legacy_msg_id: str, reason: str | None) -> None:
1190 """
1191 Triggered when the user attempts to retract a message that was sent in
1192 a Room using :xep:`0425`.
1194 If retraction is not possible, this should raise the appropriate
1195 XMPPError with a human-readable message.
1197 NB: the legacy module is responsible for calling
1198 :func:`LegacyParticipant.moderate` when this is successful, because
1199 slidge will acknowledge the moderation IQ, but will not send the
1200 moderation message from the Room automatically.
1202 :param legacy_msg_id: The legacy ID of the message to be retracted
1203 :param reason: Optionally, a reason for the moderation, given by the
1204 user-moderator.
1205 """
1206 raise NotImplementedError
1208 async def on_leave(self) -> None:
1209 """
1210 Triggered when the user leaves a group via the dedicated slidge command
1211 or the :xep:`0077` ``<remove />`` mechanism.
1213 This should be interpreted as definitely leaving the group.
1214 """
1215 raise NotImplementedError
1217 @property
1218 def participants_filled(self) -> bool:
1219 return self._stored.participants_filled
1221 def get_archived_messages(
1222 self, msg_id: str | list[str]
1223 ) -> Iterator[ArchivedMessage]:
1224 """
1225 Query the slidge archive for messages sent in this group
1227 :param msg_id: Message ID of the message in question. Can be either a legacy ID
1228 or an XMPP ID.
1229 :return: Iterator over messages. A single legacy ID can map to several messages,
1230 because of multi-attachment messages.
1231 """
1232 with self.xmpp.store.session() as orm:
1233 yield from self.xmpp.store.mam.get_messages(
1234 orm,
1235 self._stored.id,
1236 ids=[str(msg_id)] if isinstance(msg_id, str) else msg_id,
1237 )
1239 def _get_stored_image(self, attr: str) -> Avatar | None:
1240 image = super()._get_stored_image(attr)
1241 if image is None and self.space is not None:
1242 image = self.space._get_stored_image(attr)
1243 return image
1246def set_origin_id(msg: Message, origin_id: str) -> None:
1247 sub = ET.Element("{urn:xmpp:sid:0}origin-id")
1248 sub.attrib["id"] = origin_id
1249 msg.xml.append(sub)
1252def int_or_none(x: str) -> int | None:
1253 try:
1254 return int(x)
1255 except ValueError:
1256 return None
1259def equals_zero(x: int | None) -> bool:
1260 if x is None:
1261 return False
1262 else:
1263 return x == 0
1266def str_to_datetime_or_none(date: str | None) -> datetime | None:
1267 if date is None:
1268 return None
1269 try:
1270 return str_to_datetime(date)
1271 except ValueError:
1272 return None
1275LegacyRoom._participant_cls = LegacyParticipant # type:ignore[misc]
1277_WHITESPACE_OR_PUNCTUATION = string.whitespace + "!\"'(),.:;?@_"
1279log = logging.getLogger(__name__)