Coverage for slidge/core/dispatcher/pubsub.py: 92%

247 statements  

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

1from slixmpp import CoroutineCallback, Iq, StanzaPath 

2from slixmpp.exceptions import XMPPError 

3from slixmpp.plugins.xep_0060.stanza import Affiliation, OwnerAffiliation, Subscription 

4from slixmpp.plugins.xep_0084.stanza import Data as AvatarData 

5from slixmpp.plugins.xep_0084.stanza import MetaData as SlixAvatarMetadata 

6from slixmpp.xmlstream import StanzaBase 

7 

8from slidge.db.models import Space 

9from slidge.space import LegacySpace 

10 

11from ...util.types import AnyGateway, AnySession, AvatarMetadata 

12from ..session import BaseSession 

13from .util import DispatcherMixin, exceptions_to_xmpp_errors 

14 

15 

16class PubSubMixin(DispatcherMixin): 

17 __slots__: list[str] = [] 

18 xmpp: AnyGateway 

19 

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

21 super().__init__(xmpp) 

22 

23 for path, func in [ 

24 ("get/pubsub/items", self.__get_items), 

25 ("set/pubsub/subscribe", self.__set_subscribe), 

26 ("set/pubsub/unsubscribe", self.__set_unsubscribe), 

27 ("set/pubsub/publish", self.__set_publish), 

28 ("set/pubsub/create", self.__set_create), 

29 ("get/pubsub/affiliations", self.__get_affiliations), 

30 ("get/pubsub_owner/affiliations", self.__owner_get_affiliations), 

31 ("get/pubsub/subscriptions", self.__get_subscriptions), 

32 ("get/pubsub_owner/subscriptions", self.__owner_get_subscriptions), 

33 ("get/pubsub_owner/configure", self.__owner_get_configure), 

34 ("set/pubsub_owner/configure", self.__owner_set_configure), 

35 ("set/pubsub_owner/delete", self.__owner_set_delete), 

36 ]: 

37 self.xmpp.register_handler( 

38 CoroutineCallback( 

39 func.__name__, 

40 StanzaPath(f"iq@to={self.xmpp.boundjid.bare}@type={path}"), 

41 func, # type:ignore[arg-type] # ty:ignore[invalid-argument-type] 

42 ) 

43 ) 

44 

45 self.xmpp.register_handler( 

46 CoroutineCallback( 

47 "get_items_any", 

48 StanzaPath("iq@type=get/pubsub/items"), 

49 self.__get_items_any, 

50 ) 

51 ) 

52 

53 async def __get_items_any(self, iq: StanzaBase) -> None: 

54 ito = iq.get_to() 

55 if not ito.local: 

56 return # handled elsewhere (all over the place actually, refactor needed!) 

57 node = iq["pubsub"]["items"]["node"] 

58 if node not in _NODES_HANDLED_ELSEWHERE: 

59 raise XMPPError("item-not-found") 

60 

61 async def __get_items(self, iq: Iq) -> None: 

62 node = iq["pubsub"]["items"]["node"] 

63 

64 if node in _NODES_HANDLED_ELSEWHERE: 

65 # handled in slidge/core/pubsub.py 

66 # TODO: have a single entrypoint for all get/pubsub/items 

67 return 

68 

69 session = await self._get_session(iq, logged=True) 

70 legacy_id = await self.__get_legacy_id(session, node) 

71 item_ids: list[str] = [item["id"] for item in iq["pubsub"]["items"]["items"]] 

72 

73 room_item_ids = list(filter(_is_not_space_image, item_ids)) 

74 invalid = list(filter(self.__is_not_local_jid, room_item_ids)) 

75 

76 if invalid: 

77 raise XMPPError( 

78 "item-not-found", 

79 f"These items are not part of this space: {invalid}.", 

80 ) 

81 

82 room_legacy_ids = ( 

83 [self.__item_to_room_legacy_id(item_id) for item_id in room_item_ids] 

84 if room_item_ids 

85 else None 

86 ) 

87 

88 space = await session.spaces.get_or_create(legacy_id) 

89 stored = space._stored 

90 stored.load_rooms(self.xmpp.store.session, filt=room_legacy_ids) 

91 

92 if room_item_ids and len(stored.rooms) != len(room_item_ids): 

93 raise XMPPError( 

94 "item-not-found", 

95 f"Could not find rooms: {set(room_item_ids) - {str(r.jid) for r in stored.rooms}}", 

96 ) 

97 stored.ensure_relation("avatar", self.xmpp.store.session) 

98 stored.ensure_relation("banner", self.xmpp.store.session) 

99 

100 reply = iq.reply() 

101 reply["pubsub"]["items"]["node"] = node 

102 self.xmpp.pubsub.set_space_items(stored, reply["pubsub"]["items"], item_ids) 

103 

104 if len(reply["pubsub"]["items"]) == 0: 

105 if len(item_ids) == 1: 

106 raise XMPPError( 

107 "item-not-found", f"{item_ids[0]!r} could not be found." 

108 ) 

109 else: 

110 raise XMPPError( 

111 "item-not-found", 

112 f"Some of these items could not be found: {item_ids}.", 

113 ) 

114 

115 reply.send() 

116 

117 def __item_to_room_legacy_id(self, item_id: str) -> str: 

118 _type, legacy_id = self.xmpp.localpart_to_legacy_id( 

119 item_id.removesuffix(f"@{self.xmpp.boundjid.bare}") 

120 ) 

121 return legacy_id 

122 

123 def __is_not_local_jid(self, item_id: str) -> bool: 

124 return not item_id.endswith(f"@{self.xmpp.boundjid.bare}") 

125 

126 async def __get_legacy_id(self, session: BaseSession, node: str) -> str: 

127 try: 

128 legacy_id = session.spaces.node_to_legacy_id(node) 

129 except Exception as e: # noqa: BLE001 

130 raise XMPPError("item-not-found", str(e)) 

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

132 if not self.xmpp.store.spaces.exists(orm, session.user_pk, legacy_id): 

133 raise XMPPError( 

134 "item-not-found", f"This is not a known space: '{legacy_id}'" 

135 ) 

136 return legacy_id 

137 

138 async def __set_subscribe(self, iq: Iq) -> None: 

139 node = iq["pubsub"]["subscribe"]["node"] 

140 

141 session = await self._get_session(iq, logged=True) 

142 await self.__get_legacy_id(session, node) 

143 

144 reply = iq.reply(clear=True) 

145 sub = reply["pubsub"]["subscription"] 

146 sub["node"] = node 

147 sub["jid"] = session.user_jid 

148 sub["subscription"] = "subscribed" 

149 reply.send() 

150 

151 @exceptions_to_xmpp_errors 

152 async def __set_unsubscribe(self, iq: Iq) -> None: 

153 session = await self._get_session(iq, logged=True) 

154 

155 jid = iq["pubsub"]["unsubscribe"]["jid"] 

156 if jid != session.user_jid.bare: 

157 raise XMPPError("bad-request", f"Cannot unsubscribe JID {jid}") 

158 

159 node = iq["pubsub"]["unsubscribe"]["node"] 

160 legacy_id = session.spaces.node_to_legacy_id(node) 

161 

162 await session.on_leave_space(legacy_id) 

163 reply = iq.reply(clear=True) 

164 

165 sub = reply["pubsub"]["subscription"] 

166 sub["node"] = node 

167 sub["jid"] = session.user_jid 

168 sub["subscription"] = "none" 

169 reply.send() 

170 

171 async def __get_affiliations(self, iq: Iq) -> None: 

172 session = await self._get_session(iq, logged=True) 

173 

174 reply = iq.reply() 

175 node = iq["pubsub"]["affiliations"]["node"] 

176 if node: 

177 legacy_id = await self.__get_legacy_id(session, node) 

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

179 assert session.contacts.user_legacy_id is not None 

180 space = self.xmpp.store.spaces.by_legacy_id( 

181 orm, session.user_pk, legacy_id 

182 ) 

183 if space is None: 

184 raise XMPPError("item-not-found", f"Space '{legacy_id}' not found") 

185 reply["pubsub"]["affiliations"].append( 

186 self.__make_affiliation(session, space) 

187 ) 

188 else: 

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

190 for space in self.xmpp.store.spaces.get_all(orm, session.user_pk): 

191 reply["pubsub"]["affiliations"].append( 

192 self.__make_affiliation(session, space) 

193 ) 

194 

195 reply.send() 

196 

197 @staticmethod 

198 def __make_affiliation(session: AnySession, space: Space) -> Affiliation: 

199 affiliation = Affiliation() 

200 node = session.spaces.legacy_id_to_node(space.legacy_id) 

201 affiliation["node"] = node 

202 affiliation["affiliation"] = space.user_affiliation( 

203 session.contacts.user_legacy_id 

204 ) 

205 return affiliation 

206 

207 async def __owner_get_affiliations(self, iq: Iq) -> None: 

208 node = iq["pubsub_owner"]["affiliations"]["node"] 

209 if not node: 

210 raise XMPPError("bad-request", "No node was specified") 

211 

212 session = await self._get_session(iq, logged=True) 

213 legacy_id = await self.__get_legacy_id(session, node) 

214 

215 reply = iq.reply(clear=True) 

216 

217 user_found = False 

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

219 for owner_jid in self.xmpp.store.spaces.get_owner_jid_localparts( 

220 orm, session.user_pk, legacy_id 

221 ): 

222 affiliation = OwnerAffiliation() 

223 if owner_jid == session.contacts.user_legacy_id: 

224 user_found = True 

225 affiliation["jid"] = session.user_jid.bare 

226 else: 

227 affiliation["jid"] = f"{owner_jid}@{self.xmpp.boundjid.bare}" 

228 affiliation["affiliation"] = "owner" 

229 reply["pubsub_owner"]["affiliations"].append(affiliation) 

230 

231 if not user_found: 

232 affiliation = OwnerAffiliation() 

233 affiliation["jid"] = session.user_jid.bare 

234 affiliation["affiliation"] = "member" 

235 reply["pubsub_owner"]["affiliations"].append(affiliation) 

236 

237 reply.send() 

238 

239 async def __owner_get_subscriptions(self, iq: Iq) -> None: 

240 node = iq["pubsub_owner"]["subscriptions"]["node"] 

241 if not node: 

242 raise XMPPError("bad-request", "No node was specified") 

243 

244 session = await self._get_session(iq, logged=True) 

245 await self.__get_legacy_id(session, node) 

246 

247 reply = iq.reply(clear=False) 

248 sub = reply["pubsub_owner"]["subscriptions"]["subscription"] 

249 sub["jid"] = session.user_jid 

250 sub["subscription"] = "subscribed" 

251 reply.send() 

252 

253 async def __get_subscriptions(self, iq: Iq) -> None: 

254 session = await self._get_session(iq, logged=True) 

255 

256 reply = iq.reply(clear=False) 

257 subscriptions = reply["pubsub"]["subscriptions"] 

258 if node := iq["pubsub"]["subscriptions"]["node"]: 

259 await self.__get_legacy_id(session, node) 

260 subscription = subscriptions["subscription"] 

261 subscription["node"] = node 

262 subscription["jid"] = session.user_jid 

263 subscription["subscription"] = "subscribed" 

264 else: 

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

266 spaces = list(self.xmpp.store.spaces.get_all(orm, session.user_pk)) 

267 for space in spaces: 

268 subscriptions.append(await self.__make_subscription(session, space)) 

269 

270 reply.send() 

271 

272 @staticmethod 

273 async def __make_subscription(session: AnySession, space: Space) -> Subscription: 

274 subscription = Subscription() 

275 node = session.spaces.legacy_id_to_node(space.legacy_id) 

276 subscription["node"] = node 

277 subscription["jid"] = session.user_jid 

278 subscription["subscription"] = "subscribed" 

279 return subscription 

280 

281 @exceptions_to_xmpp_errors 

282 async def __owner_get_configure(self, iq: Iq) -> None: 

283 node = iq["pubsub_owner"]["configure"]["node"] 

284 if not node: 

285 raise XMPPError("bad-request", "No node was specified") 

286 

287 session = await self._get_session(iq, logged=True) 

288 legacy_id = session.spaces.node_to_legacy_id(node) 

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

290 space = self.xmpp.store.spaces.get_by_legacy_id( 

291 orm, session.user_pk, legacy_id 

292 ) 

293 if space is None: 

294 raise XMPPError("item-not-found") 

295 assert session.contacts.user_legacy_id 

296 if space.user_affiliation(session.contacts.user_legacy_id) != "owner": 

297 raise XMPPError("not-authorized", "You are not owner of this space") 

298 reply = iq.reply() 

299 # why isn't that preserved? 

300 reply["pubsub_owner"]["configure"]["node"] = node 

301 form = reply["pubsub_owner"]["configure"]["form"] 

302 form.add_field( 

303 "FORM_TYPE", 

304 value="http://jabber.org/protocol/pubsub#node_config", 

305 ftype="hidden", 

306 ) 

307 form.add_field( 

308 "pubsub#title", 

309 value=space.name, 

310 label="Human-readable name of this space", 

311 ) 

312 form.add_field( 

313 "pubsub#description", 

314 value=space.description, 

315 label="Description of this space", 

316 ) 

317 reply.send() 

318 

319 @exceptions_to_xmpp_errors 

320 async def __owner_set_configure(self, iq: Iq) -> None: 

321 space = await self.__get_space(iq, iq["pubsub_owner"]["configure"]["node"]) 

322 form = iq["pubsub_owner"]["configure"]["form"] 

323 values = form.get_values() 

324 await space.on_config( 

325 name=values.get("pubsub#title"), 

326 description=values.get("pubsub#description"), 

327 ) 

328 

329 iq.reply(clear=True).send() 

330 

331 @exceptions_to_xmpp_errors 

332 async def __set_publish(self, iq: Iq) -> None: 

333 space = await self.__get_space(iq, iq["pubsub"]["publish"]["node"]) 

334 item = iq["pubsub"]["publish"]["item"] 

335 if "avatar_metadata" not in item: 

336 raise XMPPError("bad-request", "No avatar metadata payload") 

337 metadata = AvatarMetadata._from_slix(item["avatar_metadata"]) 

338 

339 if item["id"] in ( 

340 "urn:xmpp:spaces:avatar:metadata:0", 

341 "urn:xmpp:avatar:metadata", # COMPAT: movim 

342 ): 

343 await space.on_avatar(metadata) 

344 elif item["id"] == "urn:xmpp:spaces:banner:metadata:0": 

345 await space.on_banner(metadata) 

346 else: 

347 raise XMPPError( 

348 "feature-not-implemented", 

349 "Slidge only supports setting space avatar or banner", 

350 ) 

351 iq.reply(clear=True).send() 

352 

353 @exceptions_to_xmpp_errors 

354 async def __owner_set_delete(self, iq: Iq) -> None: 

355 space = await self.__get_space(iq, iq["pubsub_owner"]["delete"]["node"]) 

356 await space.on_deletion_request() 

357 iq.reply(clear=True).send() 

358 

359 async def __get_space(self, iq: Iq, node: str) -> LegacySpace: 

360 if not node: 

361 raise XMPPError("bad-request", "No node was specified") 

362 session = await self._get_session(iq, logged=True) 

363 return await session.spaces.get_or_create( 

364 session.spaces.node_to_legacy_id(node) 

365 ) 

366 

367 @exceptions_to_xmpp_errors 

368 async def __set_create(self, iq: Iq) -> None: 

369 node = iq["pubsub"]["create"]["node"] or None 

370 if "configure" in iq["pubsub"] and "form" in iq["pubsub"]["configure"]: 

371 values = iq["pubsub"]["configure"]["form"].get_values() 

372 name = values.get("pubsub#title") or None 

373 description = values.get("pubsub#description") or None 

374 if not isinstance(name, str | None): 

375 raise XMPPError("bad-request", f"Bad value type for name: {name!r}") 

376 if not isinstance(description, str | None): 

377 raise XMPPError( 

378 "bad-request", f"Bad value type for description: {description!r}" 

379 ) 

380 pubsub_type = values.get("pubsub#type") 

381 if pubsub_type and pubsub_type != "urn:xmpp:spaces:0": 

382 raise XMPPError( 

383 "feature-not-implemented", 

384 "Slidge only supports creating space nodes", 

385 ) 

386 else: 

387 # Here, in the absence of config form, we suppose the intent is to 

388 # create a space. Maybe we should not? 

389 name = description = None 

390 session = await self._get_session(iq, logged=True) 

391 legacy_id = await session.spaces.on_creation_request( 

392 name=name, description=description, pubsub_node=node 

393 ) 

394 node = session.spaces.legacy_id_to_node(legacy_id) 

395 reply = iq.reply(clear=True) 

396 reply["pubsub"]["create"]["node"] = node 

397 reply.send() 

398 

399 

400def _is_not_space_image(item_id: str) -> bool: 

401 return item_id not in _SPACE_IMAGES_NAMESPACES 

402 

403 

404_SPACE_IMAGES_NAMESPACES = ( 

405 "urn:xmpp:spaces:avatar:metadata:0", 

406 "urn:xmpp:spaces:banner:metadata:0", 

407) 

408 

409_NODES_HANDLED_ELSEWHERE = ( 

410 AvatarData.namespace, 

411 SlixAvatarMetadata.namespace, 

412 "urn:xmpp:vcard4", 

413 *_SPACE_IMAGES_NAMESPACES, 

414)