Coverage for slidge/core/dispatcher/message/message.py: 86%

287 statements  

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

1import base64 

2import hashlib 

3import logging 

4from copy import copy 

5from typing import TYPE_CHECKING, Any, NamedTuple 

6from xml.etree import ElementTree 

7 

8from slixmpp import JID, Message 

9from slixmpp.exceptions import XMPPError 

10from slixmpp.plugins.xep_0511.stanza import LinkMetadata 

11 

12from ....contact.contact import LegacyContact 

13from ....room.room import LegacyRoom 

14from ....util.types import ( 

15 AnyRecipient, 

16 AnyRoom, 

17 ContactMessageProtocol, 

18 ContactSticker, 

19 LinkPreview, 

20 Mention, 

21 Reply, 

22 RoomMessageProtocol, 

23 RoomSticker, 

24 XMPPAttachment, 

25 XMPPMessage, 

26) 

27from ....util.util import dict_to_named_tuple, remove_emoji_variation_selector_16 

28from ... import config 

29from ..util import DispatcherMixin, exceptions_to_xmpp_errors 

30 

31if TYPE_CHECKING: 

32 from slidge.util.types import AnyGateway 

33 

34 

35class _IncomingAttachment(NamedTuple): 

36 attachment: XMPPAttachment 

37 cid: str | None = None 

38 

39 

40class MessageContentMixin(DispatcherMixin): 

41 __slots__: list[str] = [] 

42 xmpp: "AnyGateway" # not strictly necessary, but helps ty and ty is nice 

43 

44 def __init__(self, xmpp: "AnyGateway") -> None: 

45 super().__init__(xmpp) 

46 xmpp.add_event_handler("legacy_message", self.on_legacy_message) 

47 xmpp.add_event_handler("message_retract", self.on_message_retract) 

48 xmpp.add_event_handler("groupchat_message", self.on_groupchat_message) 

49 xmpp.add_event_handler("reactions", self.on_reactions) 

50 

51 async def on_groupchat_message(self, msg: Message) -> None: 

52 await self.on_legacy_message(msg) 

53 

54 @exceptions_to_xmpp_errors 

55 async def on_legacy_message(self, msg: Message) -> None: 

56 """ 

57 Meant to be called from :class:`BaseGateway` only. 

58 

59 :param msg: 

60 :return: 

61 """ 

62 # we MUST not use `if m["replace"]["id"]` because it adds the tag if not 

63 # present. this is a problem for Room echoed messages 

64 if "apply_to" in msg: 

65 # ignore message retraction (handled by a specific method) 

66 # this is an old version of the protocol that depends on the 

67 # message fastening deprecated xep. 

68 return 

69 if "reactions" in msg: 

70 # ignore message reaction fallback. 

71 # the reaction itself is handled by self.react_from_msg(). 

72 return 

73 if "retract" in msg: 

74 # ignore message retraction fallback. 

75 # the retraction itself is handled by self.on_retract 

76 return 

77 recipient, thread = await self._get_recipient_and_thread(msg) 

78 replace = await self.__get_replace(msg, recipient) 

79 if msg.xml.find(".//{*}encrypted") is not None: 

80 raise XMPPError( 

81 "bad-request", "You cannot send encrypted messages through this gateway" 

82 ) 

83 body, reply = await self.__get_reply(msg, recipient) 

84 cid = self.__get_xhtml_sticker_cid(msg) 

85 

86 if cid: 

87 legacy_msg_id = await self.__dispatch_bob( 

88 msg.get_from(), 

89 cid, 

90 recipient, 

91 reply=reply, 

92 thread=thread, 

93 ) 

94 else: 

95 attachments = self.__get_attachments(msg) 

96 if len(attachments) == 1 and attachments[0].attachment.is_sticker: 

97 legacy_msg_id = await self.__dispatch_nonbob_sticker( 

98 attachments[0], 

99 recipient, 

100 msg["body"], 

101 reply=reply, 

102 thread=thread, 

103 ) 

104 else: 

105 legacy_msg_id = await self.__dispatch_msg( 

106 replace=replace, 

107 body=body, 

108 attachments=tuple(a.attachment for a in attachments), 

109 recipient=recipient, 

110 thread=thread, 

111 reply=reply, 

112 slix_msg=msg, 

113 mentions=await self.__parse_mentions(msg, body, recipient), 

114 ) 

115 

116 if isinstance(recipient, LegacyRoom): 

117 await recipient.echo(msg, legacy_msg_id, replace=replace) 

118 else: 

119 self.__ack(msg) 

120 

121 if not legacy_msg_id: 

122 return 

123 

124 with self.xmpp.store.session() as orm: 

125 if recipient.is_group: 

126 self.xmpp.store.id_map.set_origin( 

127 orm, recipient._stored.id, legacy_msg_id, msg.get_id() 

128 ) 

129 else: 

130 self.xmpp.store.id_map.set_msg( 

131 orm, 

132 recipient._stored.id, 

133 legacy_msg_id, 

134 [msg.get_id()], 

135 False, 

136 ) 

137 orm.commit() 

138 

139 async def __parse_mentions( 

140 self, msg: Message, body: str, room: AnyRecipient 

141 ) -> tuple[Mention, ...]: 

142 if not room.is_group: 

143 return () 

144 if await self.xmpp._has_feature( 

145 msg.get_from(), self.xmpp.plugin["xep_0513"].stanza.NAMESPACE 

146 ): 

147 if not "markup" in msg: 

148 return () 

149 mentions = [] 

150 for span in msg["markup"]["spans"]: 

151 if ( 

152 "mention" in span 

153 and span["mention"]["type"] 

154 == f"{self.xmpp.plugin['xep_0513'].stanza.NAMESPACE}#occupant" 

155 ): 

156 participant = await room.participants._get_or_create_by_occupant_id( 

157 span["mention"]["target"] 

158 ) 

159 if participant is None: 

160 room.log.warning( 

161 "Could not find participant with occupant_id %r", 

162 span["mention"]["target"], 

163 ) 

164 continue 

165 mentions.append( 

166 Mention( 

167 participant=participant, 

168 start=span["start"], 

169 end=span["end"], 

170 ) 

171 ) 

172 return tuple(mentions) 

173 else: 

174 return tuple(await room.parse_mentions(body)) 

175 

176 def __get_xhtml_sticker_cid(self, msg: Message) -> str | None: 

177 if "html" not in msg: 

178 return None 

179 body = ElementTree.fromstring("<body>" + msg["html"].get_body() + "</body>") 

180 p = body.findall("p") 

181 if p is None: 

182 return None 

183 if len(p) != 1: 

184 return None 

185 if p[0].text is not None and p[0].text.strip(): 

186 return None 

187 

188 images = p[0].findall("img") 

189 if len(images) != 1: 

190 return None 

191 # no text, single img ⇒ this is a sticker 

192 # other cases should be interpreted as "custom emojis" in text 

193 src = images[0].get("src") 

194 if src is None: 

195 return None 

196 if src.startswith("cid:"): 

197 return src.removeprefix("cid:") 

198 return None 

199 

200 async def __get_replace[T: LegacyContact | AnyRoom]( 

201 self, msg: Message, recipient: T 

202 ) -> str | None: 

203 if "replace" not in msg or "id" not in msg["replace"]: 

204 return None 

205 return ( 

206 self._xmpp_msg_id_to_legacy(msg["replace"]["id"], recipient, True) or None 

207 ) 

208 

209 def __get_attachments(self, msg: Message) -> list[_IncomingAttachment]: 

210 is_sticker = "sticker" in msg 

211 

212 if ( 

213 "sfs" in msg 

214 and "sources" in msg["sfs"] 

215 and "url-data" in msg["sfs"]["sources"] 

216 and "target" in msg["sfs"]["sources"]["url-data"] 

217 ): 

218 # TODO: support "attach source in later message", cf https://xmpp.org/extensions/xep-0447.html#example-5 

219 # TODO: support for other sources than URL 

220 # TODO: support for multiattachments in single message. 

221 # What do we do if is_sticker and multiple files? 

222 content_type = cid = None 

223 if "file" in msg["sfs"]: 

224 content_type = msg["sfs"]["file"]["media-type"] or None 

225 if "hash" in msg["sfs"]["file"]: 

226 algo = msg["sfs"]["file"]["hash"]["algo"] 

227 h = msg["sfs"]["file"]["hash"]["value"] 

228 cid = f"{algo}+{h}" if algo and h else None 

229 attachment = _IncomingAttachment( 

230 XMPPAttachment( 

231 url=msg["sfs"]["sources"]["url-data"]["target"], 

232 http=self.xmpp.http, 

233 is_sticker=is_sticker, 

234 content_type=content_type, 

235 ), 

236 cid=cid, 

237 ) 

238 return [attachment] 

239 

240 if "oob" in msg: 

241 return [ 

242 _IncomingAttachment( 

243 XMPPAttachment( 

244 url=msg["oob"]["url"], 

245 http=self.xmpp.http, 

246 is_sticker=is_sticker, 

247 ), 

248 ) 

249 ] 

250 

251 if ( 

252 "reference" in msg 

253 and "sims" in msg["reference"] 

254 and "sources" in msg["reference"]["sims"] 

255 ): 

256 for source in msg["reference"]["sims"]["sources"]["substanzas"]: 

257 if source["uri"].startswith("http"): 

258 attachment = _IncomingAttachment( 

259 XMPPAttachment( 

260 url=source["uri"], 

261 http=self.xmpp.http, 

262 is_sticker=is_sticker, 

263 ), 

264 ) 

265 break 

266 else: 

267 return [] 

268 if "file" in msg["reference"]["sims"]: 

269 attachment.attachment.content_type = msg["media-type"] or None 

270 return [attachment] 

271 

272 return [] 

273 

274 async def __dispatch_msg( 

275 self, 

276 *, 

277 replace: str | None, 

278 reply: Reply | None, 

279 body: str | None, 

280 attachments: tuple[XMPPAttachment, ...], 

281 recipient: AnyRecipient, 

282 thread: str | None, 

283 slix_msg: Message, 

284 mentions: tuple[Mention, ...] = (), 

285 ) -> str | None: 

286 if replace: 

287 if body is not None: 

288 body = body.strip() 

289 if not body and not attachments and recipient.RETRACTION: 

290 await recipient.on_retract(replace, thread=thread) 

291 return None 

292 if not recipient.CORRECTION: 

293 if recipient.RETRACTION: 

294 await recipient.on_retract(replace, thread=thread) 

295 replace = None 

296 elif body: 

297 body = "Correction:\n" + body 

298 

299 if not any([attachments, body]): 

300 log.debug( 

301 "Ignoring msg with id '%s' because no body or attachments found", 

302 slix_msg.get_id(), 

303 ) 

304 return None 

305 link_previews = ( 

306 parse_link_previews(slix_msg["link_metadatas"]) 

307 if "link_metadata" in slix_msg 

308 else () 

309 ) 

310 

311 for attachment in attachments: 

312 if not body: 

313 body = None 

314 break 

315 body = body.replace(attachment.url, "").strip() 

316 

317 msg = XMPPMessage[Any]( 

318 body=body, 

319 attachments=attachments, 

320 reply=reply, 

321 thread=thread, 

322 link_previews=link_previews, 

323 replace=replace, 

324 mentions=mentions, 

325 ) 

326 assert isinstance( 

327 msg, RoomMessageProtocol if recipient.is_group else ContactMessageProtocol 

328 ) 

329 return await recipient.on_message(msg) 

330 

331 @exceptions_to_xmpp_errors 

332 async def on_message_retract(self, msg: Message) -> None: 

333 recipient, thread = await self._get_recipient_and_thread(msg) 

334 if not recipient.RETRACTION: 

335 raise XMPPError( 

336 "bad-request", 

337 "This legacy service does not support message retraction.", 

338 ) 

339 xmpp_id: str = msg["retract"]["id"] 

340 legacy_id = self._xmpp_msg_id_to_legacy(xmpp_id, recipient, origin=True) 

341 await recipient.on_retract(legacy_id, thread=thread) 

342 if isinstance(recipient, LegacyRoom): 

343 await recipient.echo(msg, None) 

344 self.__ack(msg) 

345 

346 @exceptions_to_xmpp_errors 

347 async def on_reactions(self, msg: Message) -> None: 

348 recipient, thread = await self._get_recipient_and_thread(msg) 

349 react_to: str = msg["reactions"]["id"] 

350 

351 legacy_id = self._xmpp_msg_id_to_legacy(react_to, recipient) 

352 

353 if not legacy_id: 

354 log.debug("Ignored reaction from user") 

355 raise XMPPError( 

356 "internal-server-error", 

357 "Could not convert the XMPP msg ID to a legacy ID", 

358 ) 

359 

360 emojis = [ 

361 remove_emoji_variation_selector_16(r["value"]) for r in msg["reactions"] 

362 ] 

363 error_msg = None 

364 

365 if recipient.REACTIONS_SINGLE_EMOJI and len(emojis) > 1: 

366 error_msg = "Maximum 1 emoji/message" 

367 

368 if ( 

369 not error_msg 

370 and (subset := await recipient.available_emojis(legacy_id)) 

371 and not set(emojis).issubset(subset) 

372 ): 

373 error_msg = ( 

374 f"You can only react with the following emojis: {''.join(subset)}" 

375 ) 

376 

377 if error_msg: 

378 recipient._session.send_gateway_message(error_msg) 

379 if not isinstance(recipient, LegacyRoom): 

380 # no need to carbon for groups, we just don't echo the stanza 

381 recipient.react(legacy_id, carbon=True) 

382 await recipient.on_react(legacy_id, [], thread=thread) 

383 raise XMPPError( 

384 "policy-violation", 

385 text=error_msg, 

386 clear=False, 

387 ) 

388 

389 await recipient.on_react(legacy_id, emojis, thread=thread) 

390 if isinstance(recipient, LegacyRoom): 

391 await recipient.echo(msg, None) 

392 else: 

393 self.__ack(msg) 

394 

395 with self.xmpp.store.session() as orm: 

396 multi = self.xmpp.store.id_map.get_xmpp( 

397 orm, recipient._stored.id, legacy_id, recipient.is_group 

398 ) 

399 multi = [m for m in multi if react_to != m] 

400 if not multi: 

401 return 

402 

403 if isinstance(recipient, LegacyRoom): 

404 for xmpp_id in multi: 

405 mc = copy(msg) 

406 mc["reactions"]["id"] = xmpp_id 

407 await recipient.echo(mc) 

408 elif isinstance(recipient, LegacyContact): 

409 for xmpp_id in multi: 

410 recipient.react(legacy_id, emojis, xmpp_id=xmpp_id, carbon=True) 

411 

412 def __ack(self, msg: Message) -> None: 

413 if not self.xmpp.PROPER_RECEIPTS: 

414 self.xmpp.delivery_receipt.ack(msg) 

415 

416 async def __get_reply( 

417 self, msg: Message, recipient: AnyRecipient 

418 ) -> tuple[str, Reply | None]: 

419 if "reply" not in msg: 

420 return msg["body"], None 

421 

422 session = recipient._session 

423 

424 try: 

425 msg_id = self._xmpp_msg_id_to_legacy(msg["reply"]["id"], recipient) 

426 except XMPPError: 

427 session.log.debug( 

428 "Could not determine reply-to legacy msg ID, sending quote instead." 

429 ) 

430 return redact_url(msg["body"]), None 

431 

432 if "fallback" in msg and ( 

433 isinstance(recipient, LegacyRoom) or recipient.REPLIES 

434 ): 

435 text = msg["fallback"].get_stripped_body( 

436 self.xmpp.plugin["xep_0461"].namespace 

437 ) 

438 try: 

439 fallback = redact_url(msg["reply"].get_fallback_body()) 

440 except AttributeError: 

441 fallback = None 

442 else: 

443 text = msg["body"] 

444 fallback = None 

445 

446 jid = JID(msg["reply"]["to"]) 

447 reply = Reply(msg_id, fallback) 

448 if recipient.is_group: 

449 if not jid: 

450 recipient.log.warning( 

451 "Invalid replied-to JID: %s, assuming reply to the system participant.", 

452 jid, 

453 ) 

454 resource = jid.resource 

455 if resource: 

456 await recipient.participants.ensure_filled() 

457 participant = recipient.participants.get_by_resource(resource) 

458 if participant is None: 

459 participant = recipient.participants.create( 

460 nick=resource, temp=True 

461 ) 

462 reply.to = participant 

463 else: 

464 reply.to = recipient.get_system_participant() 

465 else: 

466 if jid.bare == session.user_jid.bare: 

467 reply.to = "self" 

468 elif jid.bare == recipient.jid.bare: 

469 reply.to = "contact" 

470 else: 

471 recipient.log.warning( 

472 "Invalid replied-to JID: %r, assuming reply to the contact (%r)", 

473 jid, 

474 recipient.jid, 

475 ) 

476 

477 return text, reply 

478 

479 async def __dispatch_nonbob_sticker( 

480 self, 

481 attachment: _IncomingAttachment, 

482 recipient: AnyRecipient, 

483 fallback: str, 

484 reply: Reply | None = None, 

485 thread: str | None = None, 

486 ) -> str | None: 

487 if attachment.cid: 

488 with self.xmpp.store.session() as orm: 

489 sticker = self.xmpp.store.bob.get_sticker(orm, attachment.cid) 

490 else: 

491 sticker = None 

492 if sticker is None: 

493 async with attachment.attachment.get() as response: 

494 response.raise_for_status() 

495 data = await response.read() 

496 cid = "sha256+" + hashlib.sha256(data).hexdigest() 

497 with self.xmpp.store.session() as orm: 

498 sticker = self.xmpp.store.bob.set_sticker( 

499 orm, cid, data, attachment.attachment.content_type 

500 ) 

501 orm.commit() 

502 if sticker is None: 

503 msg = XMPPMessage[Any]( 

504 body=f"{attachment.attachment.url}\n{fallback}", 

505 thread=thread, 

506 reply=reply, 

507 ) 

508 if recipient.is_group: 

509 assert isinstance(msg, RoomMessageProtocol) 

510 else: 

511 assert isinstance(msg, ContactMessageProtocol) 

512 return await recipient.on_message(msg) 

513 

514 sticker.thread = thread 

515 sticker.reply = reply 

516 return await recipient.on_sticker(sticker) # type:ignore[arg-type] 

517 

518 async def __dispatch_bob( 

519 self, 

520 from_: JID, 

521 cid: str, 

522 recipient: AnyRecipient, 

523 reply: Reply | None = None, 

524 thread: str | None = None, 

525 ) -> str | None: 

526 with self.xmpp.store.session() as orm: 

527 sticker = self.xmpp.store.bob.get_sticker(orm, cid) 

528 if sticker is None: 

529 await self.xmpp.plugin["xep_0231"].get_bob( 

530 from_, cid, ifrom=self.xmpp.boundjid 

531 ) 

532 with self.xmpp.store.session() as orm: 

533 sticker = self.xmpp.store.bob.get_sticker(orm, cid) 

534 assert sticker is not None 

535 sticker.reply = reply 

536 sticker.thread = thread 

537 if recipient.is_group: 

538 assert isinstance(sticker, RoomSticker) 

539 else: 

540 assert isinstance(sticker, ContactSticker) 

541 return await recipient.on_sticker(sticker) 

542 

543 

544def redact_url(text: str) -> str: 

545 needle = config.NO_UPLOAD_URL_PREFIX or config.UPLOAD_URL_PREFIX 

546 if not needle: 

547 return text 

548 return text.replace(needle, "") 

549 

550 

551def parse_link_previews(link_metadatas: list[LinkMetadata]) -> tuple[LinkPreview, ...]: 

552 result = [] 

553 for link_metadata in link_metadatas: 

554 preview: LinkPreview = dict_to_named_tuple(link_metadata, LinkPreview) # type:ignore[arg-type] 

555 if ( 

556 preview.image 

557 and isinstance(preview.image, str) 

558 and preview.image.startswith("data:image/jpeg;base64,") 

559 ): 

560 try: 

561 image = base64.b64decode( 

562 preview.image.removeprefix("data:image/jpeg;base64,") 

563 ) 

564 except Exception as e: # noqa: BLE001 

565 log.warning( 

566 "Could not decode base64-encoded image: %s '%s'", e, preview.image 

567 ) 

568 else: 

569 preview = preview._replace(image=image) 

570 result.append(preview) 

571 return tuple(result) 

572 

573 

574log = logging.getLogger(__name__)