Coverage for slidge/room/participants.py: 91%

181 statements  

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

1from __future__ import annotations 

2 

3import hashlib 

4import string 

5import uuid 

6import warnings 

7from collections.abc import Iterator 

8from typing import TYPE_CHECKING, Unpack, overload 

9 

10import sqlalchemy as sa 

11import sqlalchemy.orm 

12from slixmpp.jid import JID, InvalidJID, unescape_node 

13 

14from slidge.util.types import MucAffiliation 

15 

16from ..db.models import Contact, GatewayUser, Participant 

17from ..util.util import strip_illegal_chars 

18 

19if TYPE_CHECKING: 

20 from ..contact import LegacyContact 

21 from ..util.types import AnyParticipant 

22 from .participant import _ParticipantProps 

23 from .room import LegacyRoom 

24 

25 

26class RoomRoster[LegacyParticipantT: AnyParticipant]: 

27 _participant_cls: type[LegacyParticipantT] 

28 

29 @overload 

30 def _from_store( 

31 self, stored: Participant, contact: LegacyContact | None = ... 

32 ) -> LegacyParticipantT: ... 

33 

34 @overload 

35 def _from_store( 

36 self, stored: None, contact: LegacyContact | None = ... 

37 ) -> None: ... 

38 

39 def _from_store( 

40 self, 

41 stored: Participant | None, 

42 contact: LegacyContact | None = None, 

43 for_join: bool = False, 

44 ) -> LegacyParticipantT | None: 

45 return ( 

46 None 

47 if stored is None 

48 else self._participant_cls(muc=self._muc, stored=stored, contact=contact) 

49 ) 

50 

51 def get_by_nick(self, nick: str) -> LegacyParticipantT | None: 

52 """ 

53 Get a participant by their nickname, if they were created before. 

54 """ 

55 return self.__get(Participant.nickname == nick) 

56 

57 def get_by_resource(self, resource: str) -> LegacyParticipantT | None: 

58 """ 

59 Get a participant by their resource part, if they were created before. 

60 """ 

61 return self.__get( 

62 (Participant.nickname == resource) | (Participant._resource == resource) 

63 ) 

64 

65 def get_by_legacy_id(self, legacy_id: str) -> LegacyParticipantT | None: 

66 """ 

67 Get a non-anymous participant by their contact legacy ID, if they were 

68 created before. 

69 """ 

70 return self.__get(Participant.contact.has(Contact.legacy_id == legacy_id)) 

71 

72 def get_by_contact(self, contact: LegacyContact) -> LegacyParticipantT | None: 

73 """ 

74 Get a non-anymous participant by their :class:`~slidge.LegacyContact` 

75 instance, if they were created before 

76 """ 

77 return self.__get(Participant.contact == contact._stored) 

78 

79 async def _get_or_create_by_occupant_id( 

80 self, occupant_id: str 

81 ) -> LegacyParticipantT | None: 

82 if occupant_id == "slidge-user": 

83 return self.get_user() 

84 try: 

85 jid = JID(occupant_id) 

86 except InvalidJID: 

87 pass 

88 else: 

89 if jid.domain == self._muc.xmpp.boundjid.bare: 

90 return await self.get_or_create_by_legacy_id(jid.local) 

91 return self.__get(Participant.occupant_id == occupant_id) 

92 

93 def __get(self, filt: sa.ColumnElement[bool]) -> LegacyParticipantT | None: 

94 return self._from_store(self.__get_stored(filt)) 

95 

96 def __get_stored(self, filt: sa.ColumnElement[bool]) -> Participant | None: 

97 with self.__orm() as orm: 

98 return orm.scalar(self.__query(filt)) 

99 

100 def __query(self, filt: sa.ColumnElement[bool]) -> sa.Select[Participant]: 

101 return sa.select(Participant).where(Participant.room == self._muc._stored, filt) 

102 

103 @overload 

104 def get_or_create( 

105 self, *, nick: str, **kwargs: Unpack[_ParticipantProps] 

106 ) -> LegacyParticipantT: ... 

107 

108 @overload 

109 def get_or_create( 

110 self, *, contact: LegacyContact, **kwargs: Unpack[_ParticipantProps] 

111 ) -> LegacyParticipantT: ... 

112 

113 @overload 

114 def get_or_create( 

115 self, *, nick: str, contact: LegacyContact, **kwargs: Unpack[_ParticipantProps] 

116 ) -> LegacyParticipantT: ... 

117 

118 def get_or_create( 

119 self, 

120 *, 

121 nick: str | None = None, 

122 contact: LegacyContact | None = None, 

123 **kwargs: Unpack[_ParticipantProps], 

124 ) -> LegacyParticipantT: 

125 """ 

126 Get or create a participant, either by nick or 

127 :class:`~slidge.LegacyContact`. One of the two arguments MUST 

128 be provided. 

129 

130 This is guaranteed to return a participant. 

131 """ 

132 if not (nick or contact): 

133 raise TypeError("Either pass a nick or a contact here") 

134 if contact is not None: 

135 if contact.is_user: 

136 return self.get_user() 

137 stored = self.__get_stored(Participant.contact == contact._stored) 

138 elif nick is not None: 

139 stored = self.__get_stored(Participant.nickname == nick) 

140 part = self._from_store(stored, contact) 

141 if part is None: 

142 part = self.create(nick=nick, contact=contact, **kwargs) 

143 else: 

144 if kwargs: 

145 part.batch_set_attributes(**kwargs) 

146 return part 

147 

148 def create( 

149 self, 

150 nick: str | None, 

151 contact: LegacyContact | None = None, 

152 temp: bool = False, 

153 **kwargs: Unpack[_ParticipantProps], 

154 ) -> LegacyParticipantT: 

155 """ 

156 Create a participant, either by nick or :class:`~slidge.LegacyContact`. 

157 

158 :param nick: A nickname for this participant. If only a nick is passed, 

159 the participant will be anonymous. 

160 :param contact: A :class:`~slidge.LegacyContact` instance, for a 

161 non-anonymous partipant. 

162 :param temp: If set to True, do not store the participant persistently. 

163 This can be used when filling the history, if the participant has 

164 now left the room. 

165 """ 

166 if not nick: 

167 if not contact: 

168 raise RuntimeError( 

169 "Either pass a nick or a contact to create a participant" 

170 ) 

171 nick = contact.name or contact.jid.local 

172 occupant_id = str(contact.jid) if contact else str(uuid.uuid4()) 

173 with self.__orm() as orm: 

174 resource = self.__disambiguate( 

175 orm, 

176 get_resource(nick), 

177 unescape_node(contact.jid.local) if contact else occupant_id, 

178 ) 

179 

180 if affiliation := kwargs.pop("affiliation", None): 

181 kwargs["_affiliation"] = ( # type:ignore[typeddict-unknown-key] 

182 None if affiliation == "member" else affiliation 

183 ) 

184 

185 if role := kwargs.pop("role", None): 

186 kwargs["_role"] = None if role == "participant" else role # type:ignore[typeddict-unknown-key] 

187 

188 stored = Participant( 

189 contact_id=contact._stored.id if contact else None, 

190 nickname=nick, 

191 room_id=self._muc._stored.id, 

192 occupant_id=occupant_id, 

193 resource=resource, 

194 **kwargs, 

195 ) 

196 if not temp: 

197 stored = orm.merge(stored) 

198 orm.commit() 

199 p = self._from_store(stored, contact) 

200 if ( 

201 not temp 

202 and self._muc.participants_filled 

203 and not self._muc.get_lock("fill participants") 

204 and not self._muc.get_lock("fill history") 

205 ): 

206 if p.contact: 

207 self._muc.send_affiliation_change(p) 

208 p.send_last_presence(force=True) 

209 return p 

210 

211 def _rename(self, stored: Participant, nick: str, disamb: str) -> None: 

212 resource = get_resource(nick) 

213 with self.__orm() as orm: 

214 orm.add(stored) 

215 stored.nickname = nick 

216 stored.resource = self.__disambiguate( 

217 orm, resource, disamb, exclude_pk=stored.id 

218 ) 

219 orm.commit() 

220 

221 def _delete(self, pk: int) -> None: 

222 with self.__orm() as orm: 

223 orm.execute(sa.delete(Participant).where(Participant.id == pk)) 

224 orm.commit() 

225 

226 async def get_or_create_by_legacy_id( 

227 self, contact_legacy_id: str, **kwargs: Unpack[_ParticipantProps] 

228 ) -> LegacyParticipantT: 

229 """ 

230 Get or create a participant by a contact legacy_id 

231 """ 

232 if contact_legacy_id == self._muc._session.contacts.user_legacy_id: 

233 return self.get_user() 

234 contact = await self._muc._session.contacts.get_or_create(contact_legacy_id) 

235 return self.get_or_create(contact=contact, **kwargs) 

236 

237 def get_user(self) -> LegacyParticipantT: 

238 """ 

239 Get the :term:`user <User>` participant. 

240 """ 

241 with self.__orm() as orm: 

242 stored = orm.scalar(self.__query(Participant.is_user.is_(True))) 

243 if stored is None: 

244 stored = Participant( 

245 nickname=self._muc.user_nick, 

246 room_id=self._muc._stored.id, 

247 is_user=True, 

248 occupant_id="slidge-user", 

249 resource=self.__disambiguate( 

250 orm, get_resource(self._muc.user_nick), "slidge-user" 

251 ), 

252 ) 

253 orm.add(stored) 

254 orm.commit() 

255 return self._from_store(stored) 

256 

257 def __disambiguate( 

258 self, 

259 orm: sa.orm.Session, 

260 resource: str, 

261 discriminator: str, 

262 exclude_pk: int | None = None, 

263 ) -> str: 

264 if not self._muc.xmpp.store.rooms.resource_available( 

265 orm, self._muc._stored.id, resource, exclude_pk 

266 ): 

267 resource = f"{resource} ({discriminator})" 

268 return resource 

269 

270 async def ensure_filled(self, with_presence: bool = False) -> None: 

271 if self._muc.participants_filled: 

272 self._muc._stored.load_participants(self.__orm, with_presence=with_presence) 

273 return 

274 

275 async with self._muc.lock("fill participants"): 

276 with self._muc.xmpp.store.session(expire_on_commit=False) as orm: 

277 orm.add(self._muc._stored) 

278 with orm.no_autoflush: 

279 orm.refresh(self._muc._stored, ["participants_filled"]) 

280 if self._muc.participants_filled: 

281 return 

282 self._muc.log.debug("Filling participants") 

283 updates = [] 

284 participants = [] 

285 with self._participant_cls._batch_set_attributes(): 

286 async for participant in self._muc.fill_participants(): 

287 update = participant._pending_updates 

288 participants.append(participant._stored) 

289 if update: 

290 updates.append({"id": participant._stored.id, **update}) 

291 if not any(p.is_user for p in participants): 

292 participants.append(self.get_user()._stored) 

293 with self.__orm() as orm: 

294 orm.execute(sa.update(Participant), updates) 

295 orm.commit() 

296 self._muc._update_stored_attribute(participants_filled=True) 

297 

298 self._muc.log.debug("Filling participants: done") 

299 

300 def __init__(self, muc: LegacyRoom[LegacyParticipantT]) -> None: 

301 self._muc = muc 

302 self._participant_cls = muc._participant_cls 

303 

304 def __repr__(self) -> str: 

305 return f"<Participants of {self._muc}>" 

306 

307 @property 

308 def __user(self) -> GatewayUser: 

309 return self._muc._session.user 

310 

311 def __orm(self, expire_on_commit: bool = False) -> sa.orm.Session: 

312 return self._muc.xmpp.store.session(expire_on_commit=expire_on_commit) 

313 

314 def __iter__( 

315 self, affiliation: MucAffiliation | None = None 

316 ) -> Iterator[LegacyParticipantT]: 

317 q = sa.select(Participant).where(Participant.room == self._muc._stored) 

318 if affiliation == "member": 

319 q = q.where(Participant._affiliation.is_(None)) 

320 elif affiliation is not None: 

321 q = q.where(Participant._affiliation == affiliation) 

322 with self.__orm() as orm: 

323 rows = list(orm.scalars(q)) 

324 for stored in rows: 

325 yield self._from_store(stored) 

326 

327 

328def get_resource(nickname: str) -> str: 

329 no_illegal = strip_illegal_chars(nickname).replace("\n", " | ") 

330 jid = JID("x@x.com") 

331 

332 try: 

333 jid.resource = no_illegal 

334 except InvalidJID: 

335 punycoded = nickname.encode("punycode").decode() 

336 try: 

337 jid.resource = punycoded 

338 except InvalidJID: 

339 return _strip_non_printable(nickname) 

340 else: 

341 return punycoded 

342 else: 

343 return no_illegal 

344 

345 

346def _strip_non_printable(nickname: str) -> str: 

347 new = ( 

348 "".join(x for x in nickname if x in string.printable) 

349 + f"-slidge-{hashlib.md5(nickname.encode()).hexdigest()[:8]}" 

350 ) 

351 warnings.warn(f"Could not use {nickname} as a nickname, using {new}") 

352 return new