Commit 4571788678

45717886787b1d1e5aca25e75124ca2e061fb177

parent: 9a1adfb287

Unregistered key

lymkwi <mg.minetest@gmail.com> · 2024-08-01 06:51 UTC
committer: <noreply@github.com>

Implement set/unset/show for alternative and canonical aliases (#279)

Layout: unified · split

docs/iamb.1 +12
@@ -130,6 +130,18 @@ Remove a tag from the currently focused room.
130130Set the topic of the currently focused room.
131131.It Sy ":room topic unset"
132132Unset the topic of the currently focused room.
133.It Sy ":room alias set [alias]"
134Create and point the given alias to the room.
135.It Sy ":room alias unset [alias]"
136Delete the provided alias from the room's alternative alias list.
137.It Sy ":room alias show"
138Show alternative aliases to the room, if any are set.
139.It Sy ":room canon set [alias]"
140Set the room's canonical alias to the one provided, and make the previous one an alternative alias.
141.It Sy ":room canon unset [alias]"
142Delete the room's canonical alias.
143.It Sy ":room canon show"
144Show the room's canonical alias, if any is set.
133145.El
134146
135147.Sh "WINDOW COMMANDS"
src/base.rs +20
@@ -369,6 +369,15 @@ pub enum RoomField {
369369
370370 /// The room topic.
371371 Topic,
372
373 /// The room's entire list of alternative aliases.
374 Aliases,
375
376 /// A specific alternative alias to the room.
377 Alias(String),
378
379 /// The room's canonical alias.
380 CanonicalAlias,
372381}
373382
374383/// An action that operates on a focused room.
@@ -397,6 +406,9 @@ pub enum RoomAction {
397406
398407 /// Unset a room property.
399408 Unset(RoomField),
409
410 /// List the values in a list room property.
411 Show(RoomField),
400412}
401413
402414/// An action that sends a message to a room.
@@ -596,6 +608,10 @@ pub enum IambError {
596608 #[error("Invalid user identifier: {0}")]
597609 InvalidUserId(String),
598610
611 /// An invalid user identifier was specified.
612 #[error("Invalid room alias: {0}")]
613 InvalidRoomAlias(String),
614
599615 /// An invalid verification identifier was specified.
600616 #[error("Invalid verification user/device pair: {0}")]
601617 InvalidVerificationId(String),
@@ -659,6 +675,10 @@ pub enum IambError {
659675 #[error("Unknown room identifier: {0}")]
660676 UnknownRoom(OwnedRoomId),
661677
678 /// An invalid room alias id was specified.
679 #[error("Invalid room alias id: {0}")]
680 InvalidRoomAliasId(#[from] matrix_sdk::ruma::IdParseError),
681
662682 /// A failure occurred during verification.
663683 #[error("Verification request error: {0}")]
664684 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
src/commands.rs +36
@@ -454,6 +454,42 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
454454 ("tag", "unset", Some(s)) => RoomAction::Unset(RoomField::Tag(tag_name(s)?)).into(),
455455 ("tag", "unset", None) => return Result::Err(CommandError::InvalidArgument),
456456
457 // :room aliases show
458 ("alias", "show", None) => RoomAction::Show(RoomField::Aliases).into(),
459 ("alias", "show", Some(_)) => return Result::Err(CommandError::InvalidArgument),
460
461 // :room aliases unset <alias>
462 ("alias", "unset", Some(s)) => RoomAction::Unset(RoomField::Alias(s)).into(),
463 ("alias", "unset", None) => return Result::Err(CommandError::InvalidArgument),
464
465 // :room aliases set <alias>
466 ("alias", "set", Some(s)) => RoomAction::Set(RoomField::Alias(s), "".into()).into(),
467 ("alias", "set", None) => return Result::Err(CommandError::InvalidArgument),
468
469 // :room canonicalalias show
470 ("canonicalalias" | "canon", "show", None) => {
471 RoomAction::Show(RoomField::CanonicalAlias).into()
472 },
473 ("canonicalalias" | "canon", "show", Some(_)) => {
474 return Result::Err(CommandError::InvalidArgument)
475 },
476
477 // :room canonicalalias set
478 ("canonicalalias" | "canon", "set", Some(s)) => {
479 RoomAction::Set(RoomField::CanonicalAlias, s).into()
480 },
481 ("canonicalalias" | "canon", "set", None) => {
482 return Result::Err(CommandError::InvalidArgument)
483 },
484
485 // :room canonicalalias unset
486 ("canonicalalias" | "canon", "unset", None) => {
487 RoomAction::Unset(RoomField::CanonicalAlias).into()
488 },
489 ("canonicalalias" | "canon", "unset", Some(_)) => {
490 return Result::Err(CommandError::InvalidArgument)
491 },
492
457493 _ => return Result::Err(CommandError::InvalidArgument),
458494 };
459495
src/windows/room/mod.rs +209 −2
@@ -1,12 +1,26 @@
11//! # Windows for Matrix rooms and spaces
2use std::collections::HashSet;
3
24use matrix_sdk::{
35 room::Room as MatrixRoom,
46 ruma::{
7 api::client::{
8 alias::{
9 create_alias::v3::Request as CreateAliasRequest,
10 delete_alias::v3::Request as DeleteAliasRequest,
11 },
12 error::ErrorKind as ClientApiErrorKind,
13 },
514 events::{
6 room::{name::RoomNameEventContent, topic::RoomTopicEventContent},
15 room::{
16 canonical_alias::RoomCanonicalAliasEventContent,
17 name::RoomNameEventContent,
18 topic::RoomTopicEventContent,
19 },
720 tag::{TagInfo, Tags},
821 },
922 OwnedEventId,
23 OwnedRoomAliasId,
1024 RoomId,
1125 },
1226 DisplayName,
@@ -53,6 +67,8 @@ use crate::base::{
5367use self::chat::ChatState;
5468use self::space::{Space, SpaceState};
5569
70use std::convert::TryFrom;
71
5672mod chat;
5773mod scrollback;
5874mod space;
@@ -182,7 +198,7 @@ impl RoomState {
182198 pub async fn room_command(
183199 &mut self,
184200 act: RoomAction,
185 _: ProgramContext,
201 ctx: ProgramContext,
186202 store: &mut ProgramStore,
187203 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
188204 match act {
@@ -280,6 +296,87 @@ impl RoomState {
280296 let ev = RoomTopicEventContent::new(value);
281297 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
282298 },
299 RoomField::CanonicalAlias => {
300 let client = &mut store.application.worker.client;
301
302 let Ok(orai) = OwnedRoomAliasId::try_from(value.as_str()) else {
303 let err = IambError::InvalidRoomAlias(value);
304
305 return Err(err.into());
306 };
307
308 let mut alt_aliases =
309 room.alt_aliases().into_iter().collect::<HashSet<_>>();
310 let canonical_old = room.canonical_alias();
311
312 // If the room's alias is already that, ignore it
313 if canonical_old.as_ref() == Some(&orai) {
314 let msg = format!("The canonical room alias is already {orai}");
315
316 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
317 }
318
319 // Try creating the room alias on the server.
320 let alias_create_req =
321 CreateAliasRequest::new(orai.clone(), room.room_id().into());
322 if let Err(e) = client.send(alias_create_req, None).await {
323 if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
324 // Ignore when it already exists.
325 } else {
326 return Err(IambError::from(e).into());
327 }
328 }
329
330 // Demote the previous one to an alt alias.
331 alt_aliases.extend(canonical_old);
332
333 // At this point the room alias definitely exists, and we can update the
334 // state event.
335 let mut ev = RoomCanonicalAliasEventContent::new();
336 ev.alias = Some(orai);
337 ev.alt_aliases = alt_aliases.into_iter().collect();
338 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
339 },
340 RoomField::Alias(alias) => {
341 let client = &mut store.application.worker.client;
342
343 let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
344 let err = IambError::InvalidRoomAlias(alias);
345
346 return Err(err.into());
347 };
348
349 let mut alt_aliases =
350 room.alt_aliases().into_iter().collect::<HashSet<_>>();
351 let canonical = room.canonical_alias();
352
353 if alt_aliases.contains(&orai) || canonical.as_ref() == Some(&orai) {
354 let msg = format!("The alias {orai} already maps to this room");
355
356 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
357 } else {
358 alt_aliases.insert(orai.clone());
359 }
360
361 // If the room alias does not exist on the server, create it
362 let alias_create_req = CreateAliasRequest::new(orai, room.room_id().into());
363 if let Err(e) = client.send(alias_create_req, None).await {
364 if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
365 // Ignore when it already exists.
366 } else {
367 return Err(IambError::from(e).into());
368 }
369 }
370
371 // And add it to the aliases in the state event.
372 let mut ev = RoomCanonicalAliasEventContent::new();
373 ev.alias = canonical;
374 ev.alt_aliases = alt_aliases.into_iter().collect();
375 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
376 },
377 RoomField::Aliases => {
378 // This never happens, aliases is only used for showing
379 },
283380 }
284381
285382 Ok(vec![])
@@ -302,10 +399,120 @@ impl RoomState {
302399 let ev = RoomTopicEventContent::new("".into());
303400 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
304401 },
402 RoomField::CanonicalAlias => {
403 let Some(alias_to_destroy) = room.canonical_alias() else {
404 let msg = format!("This room has no canonical alias to unset");
405
406 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
407 };
408
409 // Remove the canonical alias from the state event.
410 let mut ev = RoomCanonicalAliasEventContent::new();
411 ev.alias = None;
412 ev.alt_aliases = room.alt_aliases();
413 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
414
415 // And then unmap it on the server.
416 let del_req = DeleteAliasRequest::new(alias_to_destroy);
417 let _ = store
418 .application
419 .worker
420 .client
421 .send(del_req, None)
422 .await
423 .map_err(IambError::from)?;
424 },
425 RoomField::Alias(alias) => {
426 let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
427 let err = IambError::InvalidRoomAlias(alias);
428
429 return Err(err.into());
430 };
431
432 let alt_aliases = room.alt_aliases();
433 let canonical = room.canonical_alias();
434
435 if !alt_aliases.contains(&orai) && canonical.as_ref() != Some(&orai) {
436 let msg = format!("The alias {orai:?} isn't mapped to this room");
437
438 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
439 }
440
441 // Remove the alias from the state event if it's in it.
442 let mut ev = RoomCanonicalAliasEventContent::new();
443 ev.alias = canonical.filter(|canon| canon != &orai);
444 ev.alt_aliases = alt_aliases;
445 ev.alt_aliases.retain(|in_orai| in_orai != &orai);
446 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
447
448 // And then unmap it on the server.
449 let del_req = DeleteAliasRequest::new(orai);
450 let _ = store
451 .application
452 .worker
453 .client
454 .send(del_req, None)
455 .await
456 .map_err(IambError::from)?;
457 },
458 RoomField::Aliases => {
459 // This will not happen, you cannot unset all aliases
460 },
305461 }
306462
307463 Ok(vec![])
308464 },
465 RoomAction::Show(field) => {
466 let room = store
467 .application
468 .get_joined_room(self.id())
469 .ok_or(UIError::Application(IambError::NotJoined))?;
470
471 let msg = match field {
472 RoomField::Name => {
473 match room.name() {
474 None => "Room has no name".into(),
475 Some(name) => format!("Room name: {name:?}"),
476 }
477 },
478 RoomField::Topic => {
479 match room.topic() {
480 None => "Room has no topic".into(),
481 Some(topic) => format!("Room topic: {topic:?}"),
482 }
483 },
484 RoomField::Aliases => {
485 let aliases = room
486 .alt_aliases()
487 .iter()
488 .map(OwnedRoomAliasId::to_string)
489 .collect::<Vec<String>>();
490
491 if aliases.is_empty() {
492 "No alternative aliases in room".into()
493 } else {
494 format!("Alternative aliases: {}.", aliases.join(", "))
495 }
496 },
497 RoomField::CanonicalAlias => {
498 match room.canonical_alias() {
499 None => "No canonical alias for room".into(),
500 Some(can) => format!("Canonical alias: {can}"),
501 }
502 },
503 RoomField::Tag(_) => {
504 format!("Cannot currently show value for a tag")
505 },
506 RoomField::Alias(_) => {
507 format!("Cannot show a single alias; use `:room aliases show` instead.")
508 },
509 };
510
511 let msg = InfoMessage::Pager(msg);
512 let act = Action::ShowInfoMessage(msg);
513
514 Ok(vec![(act, ctx)])
515 },
309516 }
310517 }
311518