Coverage for slidge/core/mixins/message_maker.py: 84%

151 statements  

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

1import base64 

2import io 

3import logging 

4import uuid 

5import warnings 

6from collections.abc import Iterable 

7from datetime import UTC, datetime 

8from pathlib import Path 

9 

10from PIL import Image 

11from slixmpp import Message 

12from slixmpp.plugins.xep_0394.stanza import Span 

13from slixmpp.plugins.xep_0511.stanza import LinkMetadata 

14from slixmpp.types import MessageTypes 

15 

16from slidge.util import strip_illegal_chars 

17 

18from ...db.models import GatewayUser 

19from ...util.types import ( 

20 AnyRoom, 

21 ChatState, 

22 LinkPreview, 

23 Mention, 

24 MessageReference, 

25 ProcessingHint, 

26) 

27from .. import config 

28from .base import BaseSender 

29 

30 

31class MessageMaker(BaseSender): 

32 _mtype: MessageTypes = NotImplemented 

33 _can_send_carbon: bool = NotImplemented 

34 _STRIP_SHORT_DELAY = False 

35 _USE_STANZA_ID = False 

36 

37 _room: AnyRoom 

38 

39 def _recipient_pk(self) -> int | None: 

40 """Primary key of receiver of messages made.""" 

41 return None 

42 

43 def _make_message( 

44 self, 

45 state: ChatState | None = None, 

46 hints: Iterable[ProcessingHint] = (), 

47 legacy_msg_id: str | None = None, 

48 when: datetime | None = None, 

49 reply_to: MessageReference | None = None, 

50 carbon: bool = False, 

51 link_previews: Iterable[LinkPreview] | None = None, 

52 mentions: Iterable[Mention] = (), 

53 **kwargs: object, 

54 ) -> Message: 

55 body = kwargs.pop("mbody", None) 

56 mfrom = kwargs.pop("mfrom", self.jid) 

57 mto = kwargs.pop("mto", None) 

58 thread = kwargs.pop("thread", None) 

59 # the msg needs to have jabber:client as xmlns, so 

60 # we don't want to associate with the XML stream 

61 msg_cls = Message if carbon and self._can_send_carbon else self.xmpp.Message 

62 msg = msg_cls( 

63 sfrom=mfrom, 

64 stype=kwargs.pop("mtype", None) or self._mtype, 

65 sto=mto, 

66 **kwargs, 

67 ) 

68 if body: 

69 assert isinstance(body, str) 

70 msg["body"] = strip_illegal_chars(body, "�") 

71 state = "active" 

72 if thread: 

73 if not self.xmpp.THREADS: 

74 raise RuntimeError( 

75 "Gateway.THREADS = False, no thread should be used here!" 

76 ) 

77 assert isinstance(thread, str) 

78 if (recipient_pk := self._recipient_pk()) is None: 

79 # messages from the gateway component bare JID 

80 msg["thread"] = thread 

81 else: 

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

83 msg["thread"] = ( 

84 self.xmpp.store.id_map.get_thread( 

85 orm, recipient_pk, thread, self.is_participant 

86 ) 

87 or thread 

88 ) 

89 if state: 

90 msg["chat_state"] = state 

91 for hint in hints: 

92 msg.enable(hint) 

93 self._set_msg_id(msg, legacy_msg_id) 

94 self._add_delay(msg, when) 

95 if link_previews: 

96 self._add_link_previews(msg, link_previews) 

97 if reply_to: 

98 self._add_reply_to(msg, reply_to) 

99 for mention in mentions: 

100 self._add_mention(msg, mention) 

101 return msg 

102 

103 def _add_mention(self, msg: Message, mention: Mention) -> None: 

104 markup = msg["markup"] 

105 span = Span() 

106 span["start"] = mention.start 

107 span["end"] = mention.end 

108 span["mention"]["type"] = "occupant" 

109 span["mention"]["target"] = mention.participant.occupant_id 

110 markup.append(span) 

111 

112 def _set_msg_id(self, msg: Message, legacy_msg_id: str | None = None) -> None: 

113 if legacy_msg_id is not None: 

114 msg.set_id(legacy_msg_id) 

115 if self._USE_STANZA_ID: 

116 msg["stanza_id"]["id"] = legacy_msg_id 

117 msg["stanza_id"]["by"] = self._room.jid 

118 elif self._USE_STANZA_ID: 

119 msg["stanza_id"]["id"] = str(uuid.uuid4()) 

120 msg["stanza_id"]["by"] = self._room.jid 

121 

122 def _legacy_to_xmpp(self, legacy_id: str) -> list[str]: 

123 """ 

124 Get XMPP message IDs that correspond to a given legacy msg ID. 

125 

126 This takes into account single legacy message -> multiple XMPP messages 

127 (eg, multi-attachments). For user-sent 1:1 messages, this returns the 

128 XMPP client-generated msg ID. 

129 """ 

130 # In the case of messages sent by the component's bare JID itself, 

131 # recipient_pk is None and this just wraps the ID in a list. 

132 if (recipient_pk := self._recipient_pk()) is not None: 

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

134 ids = self.xmpp.store.id_map.get_xmpp( 

135 orm, 

136 recipient_pk, 

137 str(legacy_id), 

138 self.is_participant, 

139 ) 

140 if ids: 

141 return ids 

142 return [legacy_id] 

143 

144 def _add_delay(self, msg: Message, when: datetime | None) -> None: 

145 if when: 

146 if when.tzinfo is None: 

147 when = when.astimezone(UTC) 

148 # .contacts (Roster) not being ready means we are in Contact.backfill() 

149 # and in this situation we never want to strip the delay. 

150 if ( 

151 self._session and self._session.contacts.ready.done() 

152 ) and self._STRIP_SHORT_DELAY: 

153 delay = (datetime.now().astimezone(UTC) - when).seconds 

154 if delay < config.IGNORE_DELAY_THRESHOLD: 

155 return 

156 msg["delay"].set_stamp(when) 

157 msg["delay"].set_from(self.xmpp.boundjid.bare) 

158 

159 def _add_reply_to(self, msg: Message, reply_to: MessageReference) -> None: 

160 xmpp_id = self._legacy_to_xmpp(reply_to.legacy_id)[0] 

161 msg["reply"]["id"] = xmpp_id 

162 

163 if entity := reply_to.author: 

164 if entity == "user" or isinstance(entity, GatewayUser): 

165 if isinstance(entity, GatewayUser): 

166 warnings.warn( 

167 "Using a GatewayUser as the author of a " 

168 "MessageReference is deprecated. Use the string 'user' " 

169 "instead.", 

170 DeprecationWarning, 

171 ) 

172 if self.is_participant: 

173 msg["reply"]["to"] = self._room.user_muc_jid 

174 fallback_nick: str | None = self._room.user_nick 

175 elif (session := self._session) is not None: 

176 msg["reply"]["to"] = session.user_jid 

177 # TODO: here we should use preferably use the PEP nick of the user 

178 # (but it doesn't matter much) 

179 fallback_nick = session.user_jid.user 

180 else: 

181 if self.is_participant: 

182 participant = ( 

183 entity 

184 if entity.is_participant 

185 else self._room.participants.get_or_create(contact=entity) 

186 ) 

187 fallback_nick = participant.nickname 

188 msg["reply"]["to"] = participant.jid 

189 else: 

190 if entity.is_participant: 

191 log.warning("A 1:1 reply cannot be to a participant") 

192 fallback_nick = None 

193 else: 

194 fallback_nick = entity.name 

195 msg["reply"]["to"] = entity.jid 

196 else: 

197 fallback_nick = None 

198 

199 if fallback := reply_to.body: 

200 msg["reply"].add_quoted_fallback(fallback, fallback_nick) 

201 

202 def _add_link_previews( 

203 self, msg: Message, link_previews: Iterable[LinkPreview] 

204 ) -> None: 

205 for preview in link_previews: 

206 if preview.is_empty: 

207 continue 

208 element = LinkMetadata() 

209 for i, name in enumerate(preview._fields): 

210 val = preview[i] 

211 if isinstance(val, Path): 

212 val = val.read_bytes() 

213 if isinstance(val, bytes): 

214 val = self._process_link_preview_image(val) 

215 if not val: 

216 continue 

217 element[name] = val 

218 msg.append(element) 

219 

220 @staticmethod 

221 def _process_link_preview_image(data: bytes) -> str | None: 

222 # this will block the main thread. if this proves to be an issue in practice, 

223 # this could be rewritten to use the thread pool we use to resize avatars. 

224 try: 

225 image = Image.open(io.BytesIO(data)) 

226 except Exception: 

227 log.exception("Skipping link preview image") 

228 return None 

229 

230 rewrite = False 

231 if image.format != "JPEG": 

232 rewrite = True 

233 

234 if any(x > MAX_LINK_PREVIEW_IMAGE_SIZE for x in image.size): 

235 image.thumbnail((MAX_LINK_PREVIEW_IMAGE_SIZE, MAX_LINK_PREVIEW_IMAGE_SIZE)) 

236 rewrite = True 

237 

238 if rewrite: 

239 with io.BytesIO() as f: 

240 image.save(f, format="JPEG") 

241 data = f.getvalue() 

242 

243 return "data:image/jpeg;base64," + base64.b64encode(data).decode("utf-8") 

244 

245 

246# Instead of having a hardcoded value for this, we would ideally use 

247# XEP-0478: Stream Limits Advertisement to know which size is authorized. 

248# However, this isn't possible until XEP-0225: Component Connections is a thing. 

249# Prosody defaults to 512kb for s2s connection and 10Mb for c2s connections. 

250# Some quick tests about JPEG image: 

251# median size of 50 base64-encoded JPEG random RGB image 

252# 128x128 pixels: 14kb ± 0.04 

253# 256x256 pixels: 53kb ± 0.06 # sounds like a good tradeoff 

254# 384x384 pixels: 119kb ± 0.11 

255# 512x512 pixels: 211kb ± 0.13 

256# 640x640 pixels: 329kb ± 0.15 

257# 768x768 pixels: 473kb ± 0.21 

258# 896x896 pixels: 644kb ± 0.27 

259# 1024x1024 pixels: 841kb ± 0.22 

260MAX_LINK_PREVIEW_IMAGE_SIZE = 256 

261 

262log = logging.getLogger(__name__)