Coverage for slidge/command/user.py: 50%

295 statements  

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

1# Commands available to users 

2import contextlib 

3import inspect 

4import warnings 

5from copy import deepcopy 

6from typing import Any, cast 

7 

8from slixmpp import JID 

9from slixmpp.exceptions import XMPPError 

10 

11from ..db.meta import JSONSerializable 

12from ..db.models import Space 

13from ..space import LegacySpace 

14from ..util.types import AnyRoom, AnySession, RoomType, UserPreferences 

15from .base import ( 

16 Command, 

17 CommandAccess, 

18 Confirmation, 

19 ConfirmationSession, 

20 Form, 

21 FormField, 

22 FormSession, 

23 FormValues, 

24 Option, 

25 SearchResult, 

26 TableResult, 

27) 

28from .categories import CONTACTS, ROOMS, SPACES 

29 

30 

31class Search(Command): 

32 NAME = "🔎 Search for contacts" 

33 HELP = "Search for contacts via this gateway" 

34 CHAT_COMMAND = "find" 

35 NODE = CONTACTS.node + "/" + CHAT_COMMAND 

36 ACCESS = CommandAccess.USER_LOGGED 

37 CATEGORY = CONTACTS 

38 

39 async def run( 

40 self, session: "AnySession | None", _ifrom: JID, *args: str 

41 ) -> FormSession | SearchResult | None: 

42 assert session is not None 

43 await session.ready 

44 if args: 

45 return await session.on_search( 

46 {self.xmpp.SEARCH_FIELDS[0].var: " ".join(args)} 

47 ) 

48 return FormSession( 

49 title=self.xmpp.SEARCH_TITLE, 

50 instructions=self.xmpp.SEARCH_INSTRUCTIONS, 

51 fields=self.xmpp.SEARCH_FIELDS, 

52 handler=self.search, 

53 ) 

54 

55 @staticmethod 

56 async def search( 

57 form_values: FormValues, session: "AnySession | None", _ifrom: JID 

58 ) -> SearchResult: 

59 assert session is not None 

60 results = await session.on_search(form_values) # type: ignore 

61 if results is None: 

62 raise XMPPError("item-not-found", "No contact was found") 

63 

64 return results 

65 

66 

67class SyncContacts(Command): 

68 NAME = "🔄 Sync XMPP roster" 

69 HELP = ( 

70 "Synchronize your XMPP roster with your legacy contacts. " 

71 "Slidge will only add/remove/modify contacts in its dedicated roster group" 

72 ) 

73 CHAT_COMMAND = "sync-contacts" 

74 NODE = CONTACTS.node + "/" + CHAT_COMMAND 

75 ACCESS = CommandAccess.USER_LOGGED 

76 CATEGORY = CONTACTS 

77 

78 async def run( 

79 self, 

80 session: "AnySession | None", 

81 _ifrom: JID, 

82 *args: str, 

83 ) -> ConfirmationSession[AnySession]: 

84 assert session is not None 

85 await session.ready 

86 return ConfirmationSession[AnySession]( 

87 prompt="Are you sure you want to sync your roster?", 

88 success=None, 

89 handler=self.sync, 

90 ) 

91 

92 async def sync(self, session: "AnySession | None", _ifrom: JID) -> str: 

93 if session is None: 

94 raise RuntimeError 

95 added, removed, updated = await session.contacts._sync() 

96 return f"{added} added, {removed} removed, {updated} updated" 

97 

98 

99class ListContacts(Command): 

100 NAME = HELP = "👤 List your legacy contacts" 

101 CHAT_COMMAND = "contacts" 

102 NODE = CONTACTS.node + "/" + CHAT_COMMAND 

103 ACCESS = CommandAccess.USER_LOGGED 

104 CATEGORY = CONTACTS 

105 

106 async def run( 

107 self, 

108 session: "AnySession | None", 

109 _ifrom: JID, 

110 *_: str, 

111 ) -> TableResult: 

112 assert session is not None 

113 await session.ready 

114 contacts = sorted( 

115 session.contacts, key=lambda c: c.name.casefold() if c.name else "" 

116 ) 

117 return TableResult( 

118 description="Your buddies", 

119 fields=[FormField("name"), FormField("jid", type="jid-single")], 

120 items=[{"name": c.name, "jid": c.jid.bare} for c in contacts], 

121 ) 

122 

123 

124class ListRooms(Command): 

125 NAME = HELP = "👥 List your legacy rooms" 

126 CHAT_COMMAND = "rooms" 

127 NODE = ROOMS.node + "/" + CHAT_COMMAND 

128 ACCESS = CommandAccess.USER_LOGGED 

129 CATEGORY = ROOMS 

130 

131 async def run( 

132 self, session: "AnySession | None", _ifrom: JID, *_: str 

133 ) -> TableResult: 

134 assert session is not None 

135 await session.ready 

136 rooms: list[AnyRoom] = sorted( 

137 session.rooms, key=lambda g: (g.name or g.jid.node).casefold() 

138 ) 

139 return TableResult( 

140 description="Your rooms", 

141 fields=[FormField("name"), FormField("jid", type="jid-single")], 

142 items=[ 

143 {"name": g.name or str(g.legacy_id), "jid": g.jid.bare} for g in rooms 

144 ], 

145 jids_are_mucs=True, 

146 ) 

147 

148 

149class ListSpaces(Command): 

150 NAME = "🌐 List my spaces" 

151 HELP = "List the spaces you are part of. Spaces are collections of rooms." 

152 CHAT_COMMAND = "spaces" 

153 NODE = ROOMS.node + "/" + CHAT_COMMAND 

154 ACCESS = CommandAccess.USER_LOGGED 

155 CATEGORY = SPACES 

156 

157 related_to_spaces = True 

158 

159 async def run( 

160 self, session: "AnySession | None", _ifrom: JID, *_: str 

161 ) -> TableResult: 

162 assert session is not None 

163 spaces = await _get_updated_spaces(session) 

164 return TableResult( 

165 description="Your spaces. If your client does not support spaces, use the 'space-rooms' command.", 

166 fields=[FormField("name"), FormField("iri")], 

167 items=[ 

168 { 

169 "name": s.name or str(s.legacy_id), 

170 "iri": f"xmpp:{self.xmpp.boundjid.bare}?;node={session.spaces.legacy_id_to_node(s.legacy_id)}", 

171 } 

172 for s in spaces 

173 ], 

174 jids_are_mucs=True, 

175 ) 

176 

177 

178class ListRoomsInSpace(Command): 

179 NAME = "🌐 List the rooms in a space" 

180 HELP = "List the rooms of a space you are part of. Spaces are collections of rooms." 

181 CHAT_COMMAND = "space-rooms" 

182 NODE = ROOMS.node + "/" + CHAT_COMMAND 

183 ACCESS = CommandAccess.USER_LOGGED 

184 CATEGORY = SPACES 

185 

186 async def run( 

187 self, session: "AnySession | None", _ifrom: JID, *_: str 

188 ) -> "FormSession": 

189 assert session is not None 

190 spaces = await _get_updated_spaces(session) 

191 return FormSession( 

192 title="Your spaces", 

193 instructions="Select a space to view its rooms", 

194 fields=[ 

195 FormField( 

196 var="space_legacy_id", 

197 label="Space", 

198 required=True, 

199 type="list-single", 

200 options=[ 

201 { 

202 "label": s.name or str(s.legacy_id), 

203 "value": str(s.legacy_id), 

204 } 

205 for s in spaces 

206 ], 

207 ) 

208 ], 

209 handler=self.list_rooms, 

210 handler_args=({str(s.legacy_id): s.name for s in spaces},), 

211 ) 

212 

213 async def list_rooms( 

214 self, 

215 form_values: FormValues, 

216 session: "AnySession | None", 

217 _ifrom: JID, 

218 space_names: dict[str, str], 

219 ) -> TableResult: 

220 assert session is not None 

221 space_legacy_id = form_values.get("space_legacy_id") 

222 if space_legacy_id is None: 

223 raise XMPPError("bad-request", "You need to specify a space") 

224 assert isinstance(space_legacy_id, str) 

225 await session.ready 

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

227 rooms = sorted( 

228 self.xmpp.store.spaces.get_rooms( 

229 orm, 

230 session.user_pk, 

231 session.spaces.legacy_id_to_node(space_legacy_id), 

232 ), 

233 key=lambda r: (r.name or str(r.jid.node)).casefold(), 

234 ) 

235 name = space_names.get(space_legacy_id) 

236 return TableResult( 

237 fields=[ 

238 FormField("name", "Name"), 

239 FormField("jid", "JID", type="jid-single"), 

240 ], 

241 description=f"Rooms of '{name or space_legacy_id}'", 

242 items=[{"name": r.name or str(r.legacy_id), "jid": r.jid} for r in rooms], 

243 jids_are_mucs=True, 

244 ) 

245 

246 

247class SpaceAdmin(Command): 

248 NAME = "🌐 Change the configuration of a space" 

249 HELP = "Change the name or description of a space" 

250 CHAT_COMMAND = "space-admin" 

251 NODE = ROOMS.node + "/" + CHAT_COMMAND 

252 ACCESS = CommandAccess.USER_LOGGED 

253 CATEGORY = SPACES 

254 

255 async def run( 

256 self, session: "AnySession | None", _ifrom: JID, *_: str 

257 ) -> FormSession: 

258 assert session is not None 

259 spaces = await _get_updated_spaces(session) 

260 return FormSession( 

261 title="Your spaces", 

262 instructions="Select the space you want to change the configuration of", 

263 fields=[ 

264 FormField( 

265 var="space_legacy_id", 

266 label="Space", 

267 required=True, 

268 type="list-single", 

269 options=[ 

270 { 

271 "label": s.name or str(s.legacy_id), 

272 "value": str(s.legacy_id), 

273 } 

274 for s in spaces 

275 ], 

276 ), 

277 ], 

278 handler=self._form, 

279 ) 

280 

281 async def _form( 

282 self, 

283 form_values: FormValues, 

284 session: "AnySession | None", 

285 _ifrom: JID, 

286 ) -> FormSession: 

287 assert session is not None 

288 space_legacy_id = form_values.get("space_legacy_id") 

289 if space_legacy_id is None: 

290 raise XMPPError("bad-request", "You need to specify a space") 

291 assert isinstance(space_legacy_id, str) 

292 space = session.spaces.get(space_legacy_id) 

293 if space is None: 

294 raise XMPPError( 

295 "internal-server-error", f"Could not find the space {space_legacy_id!r}" 

296 ) 

297 return FormSession( 

298 title=f"Configuration of space {space.legacy_id!r}", 

299 instructions="Choose values for this space", 

300 fields=[ 

301 FormField(var="name", label="Name", value=space.name or ""), 

302 FormField( 

303 var="description", 

304 label="Description", 

305 value=space.description or "", 

306 ), 

307 ], 

308 handler=self._finish, 

309 handler_args=(space,), 

310 ) 

311 

312 async def _finish( 

313 self, 

314 form_values: FormValues, 

315 session: "AnySession | None", 

316 _ifrom: JID, 

317 space: LegacySpace, 

318 ) -> str: 

319 await space.on_config( 

320 name=cast(str, form_values.get("name")), 

321 description=cast(str, form_values.get("description")), 

322 ) 

323 return f"The configuration of the space {space.legacy_id!r} has been submitted to the legacy network." 

324 

325 

326class SpaceDelete(Command): 

327 NAME = "🌐 Delete a space" 

328 HELP = "Request the server-side destruction a space" 

329 CHAT_COMMAND = "space-delete" 

330 NODE = ROOMS.node + "/" + CHAT_COMMAND 

331 ACCESS = CommandAccess.USER_LOGGED 

332 CATEGORY = SPACES 

333 

334 async def run( 

335 self, session: "AnySession | None", _ifrom: JID, *_: str 

336 ) -> FormSession: 

337 assert session is not None 

338 spaces = await _get_updated_spaces(session) 

339 return FormSession( 

340 title="Your spaces", 

341 instructions="Select the space you want to change the configuration of", 

342 fields=[ 

343 FormField( 

344 var="space_legacy_id", 

345 label="Space", 

346 required=True, 

347 type="list-single", 

348 options=[ 

349 { 

350 "label": s.name or str(s.legacy_id), 

351 "value": str(s.legacy_id), 

352 } 

353 for s in spaces 

354 ], 

355 ), 

356 ], 

357 handler=self._finish, 

358 ) 

359 

360 async def _finish( 

361 self, 

362 form_values: FormValues, 

363 session: "AnySession | None", 

364 _ifrom: JID, 

365 ) -> str: 

366 assert session is not None 

367 space_legacy_id = form_values.get("space_legacy_id") 

368 if space_legacy_id is None: 

369 raise XMPPError("bad-request", "You need to specify a space") 

370 assert isinstance(space_legacy_id, str) 

371 space = session.spaces.get(space_legacy_id) 

372 if space is None: 

373 raise XMPPError( 

374 "internal-server-error", f"Could not find the space {space_legacy_id!r}" 

375 ) 

376 await space.on_deletion_request() 

377 return f"the space {space.name!r} has been deleted." 

378 

379 

380class SpaceCreate(Command): 

381 NAME = "🌐 Create a space" 

382 HELP = "Request the creation of a space on the legacy network" 

383 CHAT_COMMAND = "space-create" 

384 NODE = ROOMS.node + "/" + CHAT_COMMAND 

385 ACCESS = CommandAccess.USER_LOGGED 

386 CATEGORY = SPACES 

387 

388 async def run( 

389 self, session: "AnySession | None", _ifrom: JID, *_: str 

390 ) -> FormSession: 

391 assert session is not None 

392 return FormSession( 

393 title="Space creation", 

394 instructions="Fill in details of the space you want to create", 

395 fields=[ 

396 FormField(var="name", label="Human-facing name of this space"), 

397 FormField(var="description", label="A description of this space"), 

398 ], 

399 handler=self._finish, 

400 ) 

401 

402 async def _finish( 

403 self, 

404 form_values: FormValues, 

405 session: "AnySession | None", 

406 _ifrom: JID, 

407 ) -> str: 

408 assert session is not None 

409 name = form_values.get("name") or None 

410 description = form_values.get("description") or None 

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

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

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

414 raise XMPPError( 

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

416 ) 

417 legacy_id = await session.spaces.on_creation_request(name, description, None) 

418 return f"The space {legacy_id!r} has been created." 

419 

420 

421class Login(Command): 

422 NAME = "🔐 Re-login to the legacy network" 

423 HELP = "Login to the legacy service" 

424 CHAT_COMMAND = "re-login" 

425 NODE = "https://slidge.im/command/core/" + CHAT_COMMAND 

426 

427 ACCESS = CommandAccess.USER_NON_LOGGED 

428 

429 async def run( 

430 self, 

431 session: "AnySession | None", 

432 _ifrom: JID, 

433 *_: str, 

434 ) -> str: 

435 assert session is not None 

436 if session.is_logging_in: 

437 raise XMPPError("bad-request", "You are already logging in.") 

438 session.is_logging_in = True 

439 try: 

440 msg = await self.xmpp.login_wrap(session) 

441 except Exception as e: # noqa: BLE001 

442 session.send_gateway_status(f"Re-login failed: {e}", show="dnd") 

443 raise XMPPError( 

444 "internal-server-error", etype="wait", text=f"Could not login: {e}" 

445 ) 

446 finally: 

447 session.is_logging_in = False 

448 session.logged = True 

449 session.send_gateway_status(msg or "Re-connected", show="chat") 

450 session.send_gateway_message(msg or "Re-connected") 

451 return msg 

452 

453 

454class CreateGroup(Command): 

455 NAME = "🆕 New legacy group" 

456 HELP = "Create a group on the legacy service" 

457 CHAT_COMMAND = "create-group" 

458 NODE = ROOMS.node + "/" + CHAT_COMMAND 

459 CATEGORY = ROOMS 

460 

461 ACCESS = CommandAccess.USER_LOGGED 

462 

463 async def run( 

464 self, 

465 session: "AnySession | None", 

466 _ifrom: JID, 

467 *_: str, 

468 ) -> FormSession: 

469 assert session is not None 

470 await session.ready 

471 contacts = session.contacts.known_contacts(only_friends=True) 

472 fields = [ 

473 FormField(var="group_name", label="Name of the group", required=True), 

474 FormField( 

475 var="contacts", 

476 label="Contacts to add to the new group", 

477 type="list-multi", 

478 options=[ 

479 {"value": contact.legacy_id, "label": contact.name} 

480 for contact in sorted(contacts.values(), key=lambda c: c.name) 

481 ], 

482 required=False, 

483 ), 

484 FormField( 

485 var="private", 

486 label="Private group?", 

487 type="boolean", 

488 value="true", 

489 required=False, 

490 ), 

491 ] 

492 if session.xmpp.SPACES: 

493 options: list[Option] = [ 

494 {"value": ".slidge-no-space", "label": "(no space)"} 

495 ] 

496 options.extend( 

497 { 

498 "value": space.legacy_id, 

499 "label": space.name or space.legacy_id, 

500 } 

501 for space in sorted( 

502 session.spaces, 

503 key=lambda s: s.name or s.legacy_id, 

504 ) 

505 ) 

506 fields.append( 

507 FormField( 

508 var="space", 

509 label="Space in which to add this group", 

510 type="list-single", 

511 options=options, 

512 required=False, 

513 ), 

514 ) 

515 return FormSession( 

516 title="Create a new group", 

517 instructions="Pick contacts that should be part of this new group", 

518 fields=fields, 

519 handler=self.finish, 

520 ) 

521 

522 @staticmethod 

523 async def finish( 

524 form_values: FormValues, 

525 session: "AnySession | None", 

526 *_: Any, # noqa:ANN401 

527 ) -> TableResult: 

528 assert session is not None 

529 

530 params = inspect.signature(session.rooms.on_creation_request).parameters 

531 

532 if "space_id" in params: 

533 space_val = form_values.get("space", "") 

534 space = None if space_val == ".slidge-no-space" else space_val or "" 

535 legacy_id = await session.rooms.on_creation_request( 

536 cast(str, form_values["group_name"]), 

537 cast(list[str], form_values.get("contacts", [])), 

538 space, 

539 cast(bool | None, form_values.get("private", False)), 

540 ) 

541 else: 

542 warnings.warn( 

543 "The signature of on_creation_request() has changed. Update the legacy module!", 

544 FutureWarning, 

545 ) 

546 legacy_id = await session.rooms.on_creation_request( 

547 cast(str, form_values["group_name"]), 

548 cast(list[str], form_values.get("contacts", [])), 

549 ) 

550 muc = await session.rooms.get_or_create(legacy_id) 

551 return TableResult( 

552 description=f"Your new group: xmpp:{muc.jid}?join", 

553 fields=[FormField("name"), FormField("jid", type="jid-single")], 

554 items=[{"name": muc.name, "jid": muc.jid}], 

555 jids_are_mucs=True, 

556 ) 

557 

558 

559class Preferences(Command): 

560 NAME = "⚙️ Preferences" 

561 HELP = "Customize the gateway behaviour to your liking" 

562 CHAT_COMMAND = "preferences" 

563 NODE = "https://slidge.im/command/core/preferences" 

564 ACCESS = CommandAccess.USER 

565 

566 async def run( 

567 self, 

568 session: "AnySession | None", 

569 _ifrom: JID, 

570 *_: str, 

571 ) -> FormSession: 

572 fields = deepcopy(self.xmpp.PREFERENCES) 

573 assert session is not None 

574 current = session.user.preferences 

575 for field in fields: 

576 field.value = current.get(field.var, field.value) # type:ignore 

577 return Form( 

578 title="Preferences", 

579 instructions=self.HELP, 

580 fields=fields, 

581 handler=self.finish, # type:ignore 

582 handler_kwargs={"previous": current}, 

583 ) 

584 

585 async def finish( 

586 self, 

587 form_values: UserPreferences, 

588 session: "AnySession | None", 

589 *_: Any, # noqa:ANN401 

590 previous: JSONSerializable, 

591 ) -> str: 

592 assert session is not None 

593 if previous == form_values: 

594 return "No preference was changed" 

595 

596 previous = previous.copy() 

597 user = session.user 

598 user.preferences.update(form_values) # type:ignore 

599 self.xmpp.store.users.update(user) 

600 

601 with contextlib.suppress(NotImplementedError): 

602 await session.on_preferences(previous, form_values) 

603 

604 if not previous["sync_avatar"] and form_values["sync_avatar"]: 

605 await self.xmpp.fetch_user_avatar(session) 

606 else: 

607 user.avatar_hash = None 

608 

609 return "Your preferences have been updated." 

610 

611 

612class Unregister(Command): 

613 NAME = "❌ Unregister from the gateway" 

614 HELP = "Unregister from the gateway" 

615 CHAT_COMMAND = "unregister" 

616 NODE = "https://slidge.im/command/core/unregister" 

617 ACCESS = CommandAccess.USER 

618 

619 async def run( 

620 self, session: "AnySession | None", _ifrom: JID, *_: str 

621 ) -> ConfirmationSession[AnySession]: 

622 return ConfirmationSession[AnySession]( 

623 prompt=f"Are you sure you want to unregister from '{self.xmpp.boundjid}'?", 

624 success=f"You are not registered to '{self.xmpp.boundjid}' anymore.", 

625 handler=self.unregister, 

626 ) 

627 

628 async def unregister(self, session: "AnySession | None", _ifrom: JID) -> str: 

629 assert session is not None 

630 await self.xmpp.unregister_user(session.user) 

631 return "You are not registered anymore. Bye!" 

632 

633 

634class LeaveGroup(Command): 

635 NAME = HELP = "❌ Leave a legacy group" 

636 CHAT_COMMAND = "leave-group" 

637 NODE = ROOMS.node + "/" + CHAT_COMMAND 

638 ACCESS = CommandAccess.USER_LOGGED 

639 CATEGORY = ROOMS 

640 

641 async def run( 

642 self, 

643 session: "AnySession | None", 

644 ifrom: JID, 

645 *_: str, 

646 ) -> FormSession: 

647 assert session is not None 

648 await session.ready 

649 rooms = sorted(session.rooms, key=lambda g: g.DISCO_NAME.casefold()) 

650 return FormSession( 

651 title="Leave a group", 

652 instructions="Select the group you want to leave", 

653 fields=[ 

654 FormField( 

655 "room", 

656 "Group name", 

657 type="list-single", 

658 options=[ 

659 {"label": g.name or str(g.legacy_id), "value": str(i)} 

660 for i, g in enumerate(rooms) 

661 ], 

662 ) 

663 ], 

664 handler=self.confirm, 

665 handler_args=(rooms,), 

666 ) 

667 

668 async def confirm( 

669 self, 

670 form_values: FormValues, 

671 _session: "AnySession | None", 

672 _ifrom: JID, 

673 rooms: list[AnyRoom], 

674 ) -> Confirmation: 

675 group = rooms[int(form_values["room"])] # type:ignore 

676 return Confirmation( 

677 prompt=f"Are you sure you want to leave the group '{group.name}'?", 

678 handler=self.finish, 

679 handler_args=(group,), 

680 ) 

681 

682 @staticmethod 

683 async def finish(session: AnySession, _ifrom: JID, group: AnyRoom) -> None: 

684 await group.on_leave() 

685 await session.rooms.remove(group, reason="You left this group via slidge.") 

686 

687 

688class InviteInRooms(Command): 

689 NAME = "💌 Re-invite me in my rooms" 

690 HELP = "Ask the gateway to send invitations for all your private rooms" 

691 CHAT_COMMAND = "re-invite" 

692 NODE = ROOMS.node + "/" + CHAT_COMMAND 

693 ACCESS = CommandAccess.USER_LOGGED 

694 CATEGORY = ROOMS 

695 

696 async def run(self, session: "AnySession | None", _ifrom: JID, *_: str) -> None: 

697 assert session is not None 

698 await session.ready 

699 for muc in session.rooms: 

700 if muc.type == RoomType.GROUP: 

701 session.send_gateway_invite( 

702 muc, reason="You asked to be re-invited in all rooms." 

703 ) 

704 

705 

706async def _get_updated_spaces(session: AnySession) -> list[Space]: 

707 await session.ready 

708 await session.rooms.ready 

709 return sorted(session.spaces._db_rows, key=lambda s: s.name or str(s.legacy_id))