src/windows/room/mod.rs

1110 lines · 42705 bytes

   1//! # Windows for Matrix rooms and spaces
   2use std::collections::HashSet;
   3
   4use matrix_sdk::RoomDisplayName;
   5use matrix_sdk::notification_settings::RoomNotificationMode;
   6use matrix_sdk::ruma::api::client::room::upgrade_room::v3::Request as UpgradeRoomRequest;
   7use matrix_sdk::ruma::api::error::ErrorKind as ClientApiErrorKind;
   8use matrix_sdk::ruma::events::room::canonical_alias::RoomCanonicalAliasEventContent;
   9use matrix_sdk::ruma::events::room::history_visibility::{
  10    HistoryVisibility,
  11    RoomHistoryVisibilityEventContent,
  12};
  13use matrix_sdk::ruma::events::room::name::RoomNameEventContent;
  14use matrix_sdk::ruma::events::room::topic::RoomTopicEventContent;
  15use matrix_sdk::ruma::events::tag::TagInfo;
  16use matrix_sdk::ruma::room::{AllowRule, Restricted as JoinRestrictions};
  17
  18use crate::base::{MemberUpdateAction, RoomField};
  19use crate::config::EncryptionIndicatorLocation;
  20use crate::prelude::*;
  21use crate::windows::room::chat::ChatState;
  22use crate::windows::room::joining::{Joining, JoiningState};
  23use crate::windows::room::not_joined::{NotJoined, NotJoinedState};
  24use crate::windows::room::space::{Space, SpaceState};
  25
  26mod chat;
  27mod joining;
  28mod not_joined;
  29mod scrollback;
  30mod space;
  31
  32macro_rules! delegate {
  33    ($s: expr, $id: ident => $e: expr) => {
  34        match $s {
  35            RoomState::NotJoined($id) => $e,
  36            RoomState::Joining($id) => $e,
  37            RoomState::Chat($id) => $e,
  38            RoomState::Space($id) => $e,
  39        }
  40    };
  41}
  42
  43fn notification_mode(name: impl Into<String>) -> IambResult<RoomNotificationMode> {
  44    let name = name.into();
  45
  46    let mode = match name.to_lowercase().as_str() {
  47        "mute" => RoomNotificationMode::Mute,
  48        "mentions" | "keywords" => RoomNotificationMode::MentionsAndKeywordsOnly,
  49        "all" => RoomNotificationMode::AllMessages,
  50        _ => return Err(IambError::InvalidNotificationLevel(name).into()),
  51    };
  52
  53    Ok(mode)
  54}
  55
  56fn hist_visibility_mode(name: impl Into<String>) -> IambResult<HistoryVisibility> {
  57    let name = name.into();
  58
  59    let mode = match name.to_lowercase().as_str() {
  60        "invited" => HistoryVisibility::Invited,
  61        "joined" => HistoryVisibility::Joined,
  62        "shared" => HistoryVisibility::Shared,
  63        "world" | "world_readable" => HistoryVisibility::WorldReadable,
  64        _ => return Err(IambError::InvalidHistoryVisibility(name).into()),
  65    };
  66
  67    Ok(mode)
  68}
  69
  70pub async fn room_command(
  71    id: &RoomId,
  72    act: RoomAction,
  73    ctx: ProgramContext,
  74    store: &mut ProgramStore,
  75) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
  76    let worker = &store.application.worker;
  77
  78    match act {
  79        RoomAction::Follow(cmd, dir) => {
  80            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
  81            let room_id = match dir {
  82                MoveDir1D::Next => {
  83                    let successor = room
  84                        .successor_room()
  85                        .ok_or_else(|| UIError::Failure("No successor room found".into()))?;
  86                    successor.room_id
  87                },
  88                MoveDir1D::Previous => {
  89                    let predecessor = room
  90                        .predecessor_room()
  91                        .ok_or_else(|| UIError::Failure("No predecessor room found".into()))?;
  92                    predecessor.room_id
  93                },
  94            };
  95
  96            let id = IambId::Room(room_id.to_owned(), None);
  97            let target = OpenTarget::Application(id);
  98            let act = cmd.switch(target);
  99
 100            Ok(vec![(act, cmd.context.clone())])
 101        },
 102        RoomAction::InviteAccept => {
 103            if let Some(room) = store.application.worker.client.get_room(id) {
 104                room.join().await.map_err(IambError::from)?;
 105                Ok(vec![])
 106            } else {
 107                Err(IambError::NotInvited.into())
 108            }
 109        },
 110        RoomAction::InviteReject => {
 111            if let Some(room) = store.application.worker.client.get_room(id) {
 112                room.leave().await.map_err(IambError::from)?;
 113
 114                Ok(vec![])
 115            } else {
 116                Err(IambError::NotInvited.into())
 117            }
 118        },
 119        RoomAction::InviteSend(user) => {
 120            if let Some(room) = store.application.worker.client.get_room(id) {
 121                room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
 122
 123                Ok(vec![])
 124            } else {
 125                Err(IambError::NotJoined.into())
 126            }
 127        },
 128        RoomAction::KnockAccept(user) => {
 129            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 130            room.invite_user_by_id(&user).await.map_err(IambError::from)?;
 131            Ok(vec![])
 132        },
 133        RoomAction::KnockReject(user, reason) => {
 134            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 135            room.kick_user(&user, reason.as_deref()).await.map_err(IambError::from)?;
 136            Ok(vec![])
 137        },
 138        RoomAction::KnockBan(user, reason) => {
 139            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 140            room.ban_user(&user, reason.as_deref()).await.map_err(IambError::from)?;
 141            Ok(vec![])
 142        },
 143        RoomAction::Leave(skip_confirm) => {
 144            if let Some(room) = store.application.worker.client.get_room(id) {
 145                if skip_confirm {
 146                    room.leave().await.map_err(IambError::from)?;
 147
 148                    Ok(vec![])
 149                } else {
 150                    let msg = "Do you really want to leave this room?";
 151                    let leave = IambAction::Room(RoomAction::Leave(true));
 152                    let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
 153                    let prompt = Box::new(prompt);
 154
 155                    Err(UIError::NeedConfirm(prompt))
 156                }
 157            } else {
 158                Err(IambError::NotJoined.into())
 159            }
 160        },
 161        RoomAction::MemberUpdate(mua, user, reason, skip_confirm) => {
 162            let Some(room) = store.application.worker.client.get_room(id) else {
 163                return Err(IambError::NotJoined.into());
 164            };
 165
 166            let Ok(user_id) = OwnedUserId::try_from(user.as_str()) else {
 167                let err = IambError::InvalidUserId(user);
 168
 169                return Err(err.into());
 170            };
 171
 172            if !skip_confirm {
 173                let msg = format!("Do you really want to {mua} {user} from this room?");
 174                let act = RoomAction::MemberUpdate(mua, user, reason, true);
 175                let act = IambAction::from(act);
 176                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 177                let prompt = Box::new(prompt);
 178
 179                return Err(UIError::NeedConfirm(prompt));
 180            }
 181
 182            match mua {
 183                MemberUpdateAction::Ban => {
 184                    room.ban_user(&user_id, reason.as_deref()).await.map_err(IambError::from)?;
 185                },
 186                MemberUpdateAction::Unban => {
 187                    room.unban_user(&user_id, reason.as_deref())
 188                        .await
 189                        .map_err(IambError::from)?;
 190                },
 191                MemberUpdateAction::Kick => {
 192                    room.kick_user(&user_id, reason.as_deref())
 193                        .await
 194                        .map_err(IambError::from)?;
 195                },
 196            }
 197
 198            Ok(vec![])
 199        },
 200        RoomAction::Members(mut cmd) => {
 201            let id = IambId::MemberList(id.to_owned());
 202            let target = OpenTarget::Application(id);
 203            let cmd = cmd.default_relation(MoveDir1D::Next);
 204
 205            let act = match store.application.settings.tunables.members_split {
 206                Some(dir) => cmd.default_axis(dir.to_axis()).window(target, None),
 207                None => cmd.switch(target),
 208            };
 209
 210            Ok(vec![(act, cmd.context.clone())])
 211        },
 212        RoomAction::SetAccess(rule) => {
 213            let Some(room) = store.application.worker.client.get_room(id) else {
 214                return Err(IambError::NotJoined.into());
 215            };
 216            let rule = rule.into_join_rule(&store.application.worker.client).await?;
 217            room.privacy_settings()
 218                .update_join_rule(rule)
 219                .await
 220                .map_err(IambError::from)?;
 221            Ok(vec![])
 222        },
 223        RoomAction::SetDirect(is_direct) => {
 224            let room = store
 225                .application
 226                .get_joined_room(id)
 227                .ok_or(UIError::Application(IambError::NotJoined))?;
 228
 229            room.set_is_direct(is_direct).await.map_err(IambError::from)?;
 230
 231            Ok(vec![])
 232        },
 233        RoomAction::SetUnread(is_unread) => {
 234            let room = store
 235                .application
 236                .get_joined_room(id)
 237                .ok_or(UIError::Application(IambError::NotJoined))?;
 238
 239            room.set_unread_flag(is_unread).await.map_err(IambError::from)?;
 240
 241            if !is_unread {
 242                let info = store.application.rooms.get_or_default(id.to_owned());
 243
 244                info.fully_read(
 245                    id.to_owned(),
 246                    ReceiptThread::Main,
 247                    worker,
 248                    &store.application.settings,
 249                    &mut store.application.open_notifications,
 250                );
 251            }
 252
 253            Ok(vec![])
 254        },
 255        RoomAction::Set(field, value) => {
 256            let room = store
 257                .application
 258                .get_joined_room(id)
 259                .ok_or(UIError::Application(IambError::NotJoined))?;
 260
 261            match field {
 262                RoomField::History => {
 263                    let visibility = hist_visibility_mode(value)?;
 264                    let ev = RoomHistoryVisibilityEventContent::new(visibility);
 265                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 266                },
 267                RoomField::Name => {
 268                    let ev = RoomNameEventContent::new(value);
 269                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 270                },
 271                RoomField::Tag(tag) => {
 272                    let mut info = TagInfo::new();
 273                    info.order = Some(1.0);
 274
 275                    let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
 276                },
 277                RoomField::Topic => {
 278                    let ev = RoomTopicEventContent::new(value);
 279                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 280                },
 281                RoomField::NotificationMode => {
 282                    let mode = notification_mode(value)?;
 283                    let client = &store.application.worker.client;
 284                    let notifications = client.notification_settings().await;
 285
 286                    notifications
 287                        .set_room_notification_mode(id, mode)
 288                        .await
 289                        .map_err(IambError::from)?;
 290                },
 291                RoomField::CanonicalAlias => {
 292                    let client = &mut store.application.worker.client;
 293
 294                    let Ok(orai) = OwnedRoomAliasId::try_from(value.as_str()) else {
 295                        let err = IambError::InvalidRoomAlias(value);
 296
 297                        return Err(err.into());
 298                    };
 299
 300                    let mut alt_aliases = room.alt_aliases().into_iter().collect::<HashSet<_>>();
 301                    let canonical_old = room.canonical_alias();
 302
 303                    // If the room's alias is already that, ignore it
 304                    if canonical_old.as_ref() == Some(&orai) {
 305                        let msg = format!("The canonical room alias is already {orai}");
 306
 307                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 308                    }
 309
 310                    // Try creating the room alias on the server.
 311                    if let Err(e) = client.create_room_alias(&orai, room.room_id()).await {
 312                        if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
 313                            // Ignore when it already exists.
 314                        } else {
 315                            return Err(IambError::from(e).into());
 316                        }
 317                    }
 318
 319                    // Demote the previous one to an alt alias.
 320                    alt_aliases.extend(canonical_old);
 321
 322                    // At this point the room alias definitely exists, and we can update the
 323                    // state event.
 324                    let mut ev = RoomCanonicalAliasEventContent::new();
 325                    ev.alias = Some(orai);
 326                    ev.alt_aliases = alt_aliases.into_iter().collect();
 327                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 328                },
 329                RoomField::Alias(alias) => {
 330                    let client = &mut store.application.worker.client;
 331
 332                    let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
 333                        let err = IambError::InvalidRoomAlias(alias);
 334
 335                        return Err(err.into());
 336                    };
 337
 338                    let mut alt_aliases = room.alt_aliases().into_iter().collect::<HashSet<_>>();
 339                    let canonical = room.canonical_alias();
 340
 341                    if alt_aliases.contains(&orai) || canonical.as_ref() == Some(&orai) {
 342                        let msg = format!("The alias {orai} already maps to this room");
 343
 344                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 345                    } else {
 346                        alt_aliases.insert(orai.clone());
 347                    }
 348
 349                    // If the room alias does not exist on the server, create it
 350                    if let Err(e) = client.create_room_alias(&orai, room.room_id()).await {
 351                        if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
 352                            // Ignore when it already exists.
 353                        } else {
 354                            return Err(IambError::from(e).into());
 355                        }
 356                    }
 357
 358                    // And add it to the aliases in the state event.
 359                    let mut ev = RoomCanonicalAliasEventContent::new();
 360                    ev.alias = canonical;
 361                    ev.alt_aliases = alt_aliases.into_iter().collect();
 362                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 363                },
 364                RoomField::UserName => {
 365                    room.set_own_member_display_name(Some(value))
 366                        .await
 367                        .map_err(IambError::from)?;
 368                },
 369                RoomField::Access | RoomField::Aliases | RoomField::Id | RoomField::Version => {
 370                    // These variants exist for RoomAction::Show, so we never actually get here.
 371                },
 372            }
 373
 374            Ok(vec![])
 375        },
 376        RoomAction::Unset(field) => {
 377            let room = store
 378                .application
 379                .get_joined_room(id)
 380                .ok_or(UIError::Application(IambError::NotJoined))?;
 381
 382            match field {
 383                RoomField::History => {
 384                    let visibility = HistoryVisibility::Joined;
 385                    let ev = RoomHistoryVisibilityEventContent::new(visibility);
 386                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 387                },
 388                RoomField::Name => {
 389                    let ev = RoomNameEventContent::new("".into());
 390                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 391                },
 392                RoomField::Tag(tag) => {
 393                    let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
 394                },
 395                RoomField::Topic => {
 396                    let ev = RoomTopicEventContent::new("".into());
 397                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 398                },
 399                RoomField::NotificationMode => {
 400                    let client = &store.application.worker.client;
 401                    let notifications = client.notification_settings().await;
 402
 403                    notifications
 404                        .delete_user_defined_room_rules(id)
 405                        .await
 406                        .map_err(IambError::from)?;
 407                },
 408                RoomField::CanonicalAlias => {
 409                    let Some(alias_to_destroy) = room.canonical_alias() else {
 410                        let msg = "This room has no canonical alias to unset";
 411
 412                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 413                    };
 414
 415                    // Remove the canonical alias from the state event.
 416                    let mut ev = RoomCanonicalAliasEventContent::new();
 417                    ev.alias = None;
 418                    ev.alt_aliases = room.alt_aliases();
 419                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 420
 421                    // And then unmap it on the server.
 422                    store
 423                        .application
 424                        .worker
 425                        .client
 426                        .remove_room_alias(&alias_to_destroy)
 427                        .await
 428                        .map_err(IambError::from)?;
 429                },
 430                RoomField::Alias(alias) => {
 431                    let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
 432                        let err = IambError::InvalidRoomAlias(alias);
 433
 434                        return Err(err.into());
 435                    };
 436
 437                    let alt_aliases = room.alt_aliases();
 438                    let canonical = room.canonical_alias();
 439
 440                    if !alt_aliases.contains(&orai) && canonical.as_ref() != Some(&orai) {
 441                        let msg = format!("The alias {orai:?} isn't mapped to this room");
 442
 443                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 444                    }
 445
 446                    // Remove the alias from the state event if it's in it.
 447                    let mut ev = RoomCanonicalAliasEventContent::new();
 448                    ev.alias = canonical.filter(|canon| canon != &orai);
 449                    ev.alt_aliases = alt_aliases;
 450                    ev.alt_aliases.retain(|in_orai| in_orai != &orai);
 451                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 452
 453                    // And then unmap it on the server.
 454                    store
 455                        .application
 456                        .worker
 457                        .client
 458                        .remove_room_alias(&orai)
 459                        .await
 460                        .map_err(IambError::from)?;
 461                },
 462                RoomField::UserName => {
 463                    room.set_own_member_display_name(None).await.map_err(IambError::from)?;
 464                },
 465                RoomField::Access | RoomField::Aliases | RoomField::Id | RoomField::Version => {
 466                    // These variants exist for RoomAction::Show, so we never actually get here.
 467                },
 468            }
 469
 470            Ok(vec![])
 471        },
 472        RoomAction::Show(field) => {
 473            let room = store
 474                .application
 475                .get_joined_room(id)
 476                .ok_or(UIError::Application(IambError::NotJoined))?;
 477
 478            let msg = match field {
 479                RoomField::History => {
 480                    let visibility = room.history_visibility();
 481                    let visibility = visibility.as_ref().map(|v| v.as_str());
 482                    format!("Room history visibility: {}", visibility.unwrap_or("<unknown>"))
 483                },
 484                RoomField::Id => {
 485                    let id = room.room_id();
 486                    format!("Room identifier: {id}")
 487                },
 488                RoomField::Version => {
 489                    let v = room.version();
 490                    let v = v.as_ref().map(|v| v.as_str()).unwrap_or("<version unknown>");
 491                    format!("Room version: {v}")
 492                },
 493                RoomField::Name => {
 494                    match room.name() {
 495                        None => "Room has no name".into(),
 496                        Some(name) => format!("Room name: {name:?}"),
 497                    }
 498                },
 499                RoomField::Topic => {
 500                    match room.topic() {
 501                        None => "Room has no topic".into(),
 502                        Some(topic) => format!("Room topic: {topic:?}"),
 503                    }
 504                },
 505                RoomField::NotificationMode => {
 506                    let client = &store.application.worker.client;
 507                    let notifications = client.notification_settings().await;
 508                    let mode = notifications.get_user_defined_room_notification_mode(id).await;
 509
 510                    let level = match mode {
 511                        Some(RoomNotificationMode::Mute) => "mute",
 512                        Some(RoomNotificationMode::MentionsAndKeywordsOnly) => "keywords",
 513                        Some(RoomNotificationMode::AllMessages) => "all",
 514                        None => "default",
 515                    };
 516
 517                    format!("Room notification level: {level:?}")
 518                },
 519                RoomField::Access => {
 520                    let show_restrictions = |rs: JoinRestrictions| {
 521                        rs.allow
 522                            .into_iter()
 523                            .map(|a| {
 524                                match a {
 525                                    AllowRule::RoomMembership(m) => {
 526                                        if let Some(alias) =
 527                                            store.application.get_joined_room_alias(&m.room_id)
 528                                        {
 529                                            format!("members of {} ({alias})", m.room_id)
 530                                        } else {
 531                                            format!("members of {}", m.room_id)
 532                                        }
 533                                    },
 534                                    other => format!("{other:?}"),
 535                                }
 536                            })
 537                            .collect::<Vec<_>>()
 538                            .join(", ")
 539                    };
 540
 541                    let desc = match room.join_rule() {
 542                        None => "<unknown>".into(),
 543                        Some(JoinRule::Invite) => "invite".into(),
 544                        Some(JoinRule::Knock) => "knock".into(),
 545                        Some(JoinRule::Private) => "private".into(),
 546                        Some(JoinRule::Public) => "public".into(),
 547                        Some(JoinRule::Restricted(restrictions)) => {
 548                            let allowing = show_restrictions(restrictions);
 549                            if allowing.is_empty() {
 550                                "restricted".into()
 551                            } else {
 552                                format!("restricted, allowing {allowing}")
 553                            }
 554                        },
 555                        Some(JoinRule::KnockRestricted(restrictions)) => {
 556                            let allowing = show_restrictions(restrictions);
 557                            if allowing.is_empty() {
 558                                "knock-restricted".into()
 559                            } else {
 560                                format!("knock-restricted, allowing {allowing}")
 561                            }
 562                        },
 563                        Some(other) => format!("{other:?}"),
 564                    };
 565
 566                    format!("Room join rules are set to: {desc}")
 567                },
 568                RoomField::Aliases => {
 569                    let aliases = room
 570                        .alt_aliases()
 571                        .iter()
 572                        .map(OwnedRoomAliasId::to_string)
 573                        .collect::<Vec<String>>();
 574
 575                    if aliases.is_empty() {
 576                        "No alternative aliases in room".into()
 577                    } else {
 578                        format!("Alternative aliases: {}.", aliases.join(", "))
 579                    }
 580                },
 581                RoomField::CanonicalAlias => {
 582                    match room.canonical_alias() {
 583                        None => "No canonical alias for room".into(),
 584                        Some(can) => format!("Canonical alias: {can}"),
 585                    }
 586                },
 587                RoomField::Tag(_) => "Cannot currently show value for a tag".into(),
 588                RoomField::Alias(_) => {
 589                    "Cannot show a single alias; use `:room aliases show` instead.".into()
 590                },
 591                RoomField::UserName => {
 592                    let user_id = &store.application.settings.profile.user_id;
 593                    let Some(member) = room.get_member(user_id).await.map_err(IambError::from)?
 594                    else {
 595                        let msg = "Cannot find membership data".into();
 596                        return Err(IambError::Custom(msg))?;
 597                    };
 598
 599                    match member.display_name() {
 600                        Some(name) => format!("User name: \"{name}\""),
 601                        None => "No user name set".into(),
 602                    }
 603                },
 604            };
 605
 606            let msg = InfoMessage::Pager(msg);
 607            let act = Action::ShowInfoMessage(msg);
 608
 609            Ok(vec![(act, ctx)])
 610        },
 611        RoomAction::Upgrade(new_version, additional_creators, false) => {
 612            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 613            let alias = room.canonical_alias();
 614            let name = alias.as_ref().map(|c| c.as_str()).unwrap_or_else(|| id.as_str());
 615            let msg = format!(
 616                "Are you sure you want to upgrade {name} to version {new_version} with {} additional creators set?",
 617                additional_creators.len()
 618            );
 619            let upgrade =
 620                IambAction::Room(RoomAction::Upgrade(new_version, additional_creators, true));
 621            let prompt = PromptYesNo::new(msg, vec![Action::from(upgrade)]);
 622            let prompt = Box::new(prompt);
 623
 624            Err(UIError::NeedConfirm(prompt))
 625        },
 626        RoomAction::Upgrade(new_version, additional_creators, true) => {
 627            let mut request = UpgradeRoomRequest::new(id.to_owned(), new_version);
 628            request.additional_creators = additional_creators;
 629
 630            let response = worker.client.send(request).await.map_err(IambError::from)?;
 631            let id = IambId::Room(response.replacement_room, None);
 632            let target = OpenTarget::Application(id);
 633            let act = WindowAction::Switch(target);
 634
 635            Ok(vec![(act.into(), ctx)])
 636        },
 637    }
 638}
 639
 640/// State for a Matrix room or space.
 641///
 642/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
 643/// that operations like sending and accepting invites, opening the members window, etc., all work
 644/// similarly.
 645pub enum RoomState {
 646    NotJoined(Box<NotJoinedState>),
 647    Joining(Box<JoiningState>),
 648    Chat(Box<ChatState>),
 649    Space(Box<SpaceState>),
 650}
 651
 652impl From<NotJoinedState> for RoomState {
 653    fn from(chat: NotJoinedState) -> Self {
 654        RoomState::NotJoined(Box::new(chat))
 655    }
 656}
 657
 658impl From<JoiningState> for RoomState {
 659    fn from(chat: JoiningState) -> Self {
 660        RoomState::Joining(Box::new(chat))
 661    }
 662}
 663
 664impl From<ChatState> for RoomState {
 665    fn from(chat: ChatState) -> Self {
 666        RoomState::Chat(Box::new(chat))
 667    }
 668}
 669
 670impl From<SpaceState> for RoomState {
 671    fn from(space: SpaceState) -> Self {
 672        RoomState::Space(Box::new(space))
 673    }
 674}
 675
 676impl RoomState {
 677    pub fn new(
 678        room: MatrixRoom,
 679        thread: Option<OwnedEventId>,
 680        name: RoomDisplayName,
 681        tags: Option<Tags>,
 682        store: &mut ProgramStore,
 683    ) -> Self {
 684        let room_id = room.room_id().to_owned();
 685        let info = store.application.get_room_info(room_id);
 686        info.name = name.to_string().into();
 687        info.tags = tags;
 688
 689        if room.is_space() {
 690            SpaceState::new(room).into()
 691        } else {
 692            ChatState::new(room, thread, store).into()
 693        }
 694    }
 695
 696    pub fn join(name: String, store: &mut ProgramStore) -> Self {
 697        let joining = JoiningState::new(name, store);
 698        Self::from(joining)
 699    }
 700
 701    pub fn not_joined(name: String) -> Self {
 702        Self::from(NotJoinedState::new(name))
 703    }
 704
 705    pub fn window_id(&self) -> IambId {
 706        match self {
 707            RoomState::NotJoined(nj) => IambId::NotJoined(nj.room.clone()),
 708            RoomState::Joining(joining) => IambId::Joining(joining.room.clone()),
 709            RoomState::Chat(chat) => IambId::Room(chat.id().to_owned(), chat.thread().cloned()),
 710            RoomState::Space(space) => IambId::Room(space.id().to_owned(), None),
 711        }
 712    }
 713
 714    pub fn room_state(&self) -> Option<MatrixRoomState> {
 715        match self {
 716            RoomState::NotJoined(_) | RoomState::Joining(_) => None,
 717            RoomState::Chat(chat) => Some(chat.room().state()),
 718            RoomState::Space(space) => Some(space.room().state()),
 719        }
 720    }
 721
 722    pub fn refresh_room(&mut self, store: &mut ProgramStore) {
 723        match self {
 724            RoomState::NotJoined(_) => {},
 725            RoomState::Joining(joining) => {
 726                let joined = joining.room.clone();
 727
 728                let room_id = match joining.try_recv() {
 729                    None => return,
 730                    Some(Ok(room_id)) => room_id.clone(),
 731                    Some(Err(e)) => {
 732                        // We failed to join the room, so show the NotJoined window,
 733                        // and let the user try again if the error was transient:
 734                        *self = NotJoinedState::failed(joined, e).into();
 735                        return;
 736                    },
 737                };
 738
 739                let Ok((room, name, tags)) = store.application.worker.get_room(room_id.clone())
 740                else {
 741                    return;
 742                };
 743
 744                if let Ok(alias) = OwnedRoomAliasId::try_from(joined.as_str()) {
 745                    // If the `:join` was for a room alias, then track it so
 746                    // we can reuse it later for `:join`/`:sp`/etc:
 747                    store.application.names.insert(alias, room_id.clone());
 748                }
 749
 750                store.application.need_load.need_members(room_id);
 751
 752                *self = RoomState::new(room, None, name, tags, store);
 753            },
 754            RoomState::Chat(chat) => chat.refresh_room(store),
 755            RoomState::Space(space) => space.refresh_room(store),
 756        }
 757    }
 758
 759    fn draw_invite(
 760        &self,
 761        invited: &MatrixRoom,
 762        area: Rect,
 763        buf: &mut Buffer,
 764        store: &mut ProgramStore,
 765    ) {
 766        let inviter = store.application.worker.get_inviter(invited.clone());
 767        let room_id = invited.room_id();
 768
 769        let name = match invited.canonical_alias() {
 770            Some(alias) => alias.to_string(),
 771            None => format!("{:?}", store.application.get_room_title(room_id)),
 772        };
 773
 774        let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
 775
 776        if let Ok(Some(inviter)) = &inviter {
 777            let info = store.application.rooms.get_or_default(room_id.to_owned());
 778            invited.push(Span::from(" by "));
 779            invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
 780        }
 781
 782        let l1 = Line::from(invited);
 783        let l2 = Line::from(
 784            "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
 785        );
 786        let text = Text::from(vec![l1, l2]);
 787
 788        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 789
 790        return;
 791    }
 792
 793    fn draw_knock(
 794        &self,
 795        knocked: &MatrixRoom,
 796        area: Rect,
 797        buf: &mut Buffer,
 798        store: &mut ProgramStore,
 799    ) {
 800        let name = match knocked.canonical_alias() {
 801            Some(alias) => alias.to_string(),
 802            None => format!("{:?}", store.application.get_room_title(knocked.room_id())),
 803        };
 804
 805        let l1 = Line::from(format!(
 806            "Your request to join {name} is pending review by room moderators."
 807        ));
 808        let l2 = Line::from("You can run `:leave` to withdraw your knock request.");
 809        let text = Text::from(vec![l1, l2]);
 810
 811        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 812
 813        return;
 814    }
 815
 816    fn draw_left(&self, room: &MatrixRoom, area: Rect, buf: &mut Buffer, store: &mut ProgramStore) {
 817        let name = match room.canonical_alias() {
 818            Some(alias) => alias.to_string(),
 819            None => format!("{:?}", store.application.get_room_title(room.room_id())),
 820        };
 821
 822        let mut lines = vec![Line::from(format!("You have left {name}!"))];
 823
 824        if room.is_public().is_some_and(|b| b) {
 825            lines.push(Line::from(format!("You can run `:join {name}` to rejoin.")));
 826        }
 827
 828        let text = Text::from(lines);
 829
 830        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 831
 832        return;
 833    }
 834
 835    pub async fn message_command(
 836        &mut self,
 837        act: MessageAction,
 838        ctx: ProgramContext,
 839        store: &mut ProgramStore,
 840    ) -> IambResult<EditInfo> {
 841        if let RoomState::Chat(chat) = self {
 842            chat.message_command(act, ctx, store).await
 843        } else {
 844            Err(IambError::NoSelectedMessage.into())
 845        }
 846    }
 847
 848    pub async fn space_command(
 849        &mut self,
 850        act: SpaceAction,
 851        ctx: ProgramContext,
 852        store: &mut ProgramStore,
 853    ) -> IambResult<EditInfo> {
 854        if let RoomState::Space(space) = self {
 855            space.space_command(act, ctx, store).await
 856        } else {
 857            Err(IambError::NoSelectedSpace.into())
 858        }
 859    }
 860
 861    pub async fn send_command(
 862        &mut self,
 863        act: SendAction,
 864        ctx: ProgramContext,
 865        store: &mut ProgramStore,
 866    ) -> IambResult<EditInfo> {
 867        if let RoomState::Chat(chat) = self {
 868            chat.send_command(act, ctx, store).await
 869        } else {
 870            Err(IambError::NoSelectedRoom.into())
 871        }
 872    }
 873
 874    pub fn get_title(&self, store: &mut ProgramStore) -> Line<'_> {
 875        let Some(room) = self.room() else {
 876            return Line::from("Unjoined Room");
 877        };
 878
 879        let room_id = room.room_id();
 880        let title = store.application.get_room_title(room_id);
 881        let style = Style::default().add_modifier(StyleModifier::BOLD);
 882        let mut spans = vec![];
 883
 884        let encryption_settings = &store.application.settings.tunables.encryption;
 885        let encryption_indicator = encryption_settings
 886            .get_indicator(EncryptionIndicatorLocation::TITLE, room.encryption_state());
 887        spans.extend(encryption_indicator);
 888        spans.push(Span::raw(" "));
 889
 890        if let RoomState::Chat(chat) = self &&
 891            chat.thread().is_some()
 892        {
 893            spans.push("Thread in ".into());
 894        }
 895
 896        spans.push(Span::styled(title, style));
 897
 898        match room.topic() {
 899            Some(desc) if !desc.is_empty() => {
 900                spans.push(" (".into());
 901                spans.push(desc.into());
 902                spans.push(")".into());
 903            },
 904            _ => {
 905                spans.push(" ".into());
 906            },
 907        }
 908
 909        Line::from(spans)
 910    }
 911
 912    pub fn get_tab_title(&self, store: &mut ProgramStore) -> Line<'_> {
 913        match self {
 914            RoomState::Space(w) => store.application.get_room_title(w.id()).into(),
 915            RoomState::Chat(w) => store.application.get_room_title(w.id()).into(),
 916            RoomState::NotJoined(_) => Line::from("Unjoined Room"),
 917            RoomState::Joining(w) => {
 918                Line::from(vec![Span::raw("Joining "), Span::raw(w.room.as_str())])
 919            },
 920        }
 921    }
 922
 923    pub fn focus_toggle(&mut self) {
 924        match self {
 925            RoomState::Chat(chat) => chat.focus_toggle(),
 926            RoomState::Joining(_) | RoomState::NotJoined(_) | RoomState::Space(_) => return,
 927        }
 928    }
 929
 930    pub fn room(&self) -> Option<&MatrixRoom> {
 931        match self {
 932            RoomState::Chat(chat) => Some(chat.room()),
 933            RoomState::Space(space) => Some(space.room()),
 934            RoomState::Joining(_) | RoomState::NotJoined(_) => None,
 935        }
 936    }
 937
 938    pub fn id(&self) -> Option<&RoomId> {
 939        match self {
 940            RoomState::Chat(chat) => Some(chat.id()),
 941            RoomState::Space(space) => Some(space.id()),
 942            RoomState::Joining(_) | RoomState::NotJoined(_) => None,
 943        }
 944    }
 945}
 946
 947impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 948    fn editor_command(
 949        &mut self,
 950        act: &EditorAction,
 951        ctx: &ProgramContext,
 952        store: &mut ProgramStore,
 953    ) -> EditResult<EditInfo, IambInfo> {
 954        delegate!(self, w => w.editor_command(act, ctx, store))
 955    }
 956}
 957
 958impl Jumpable<ProgramContext, IambInfo> for RoomState {
 959    fn jump(
 960        &mut self,
 961        list: PositionList,
 962        dir: MoveDir1D,
 963        count: usize,
 964        ctx: &ProgramContext,
 965    ) -> IambResult<usize> {
 966        delegate!(self, w => w.jump(list, dir, count, ctx))
 967    }
 968}
 969
 970impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 971    fn scroll(
 972        &mut self,
 973        style: &ScrollStyle,
 974        ctx: &ProgramContext,
 975        store: &mut ProgramStore,
 976    ) -> EditResult<EditInfo, IambInfo> {
 977        delegate!(self, w => w.scroll(style, ctx, store))
 978    }
 979}
 980
 981impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 982    fn prompt(
 983        &mut self,
 984        act: &PromptAction,
 985        ctx: &ProgramContext,
 986        store: &mut ProgramStore,
 987    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 988        delegate!(self, w => w.prompt(act, ctx, store))
 989    }
 990}
 991
 992impl TerminalCursor for RoomState {
 993    fn get_term_cursor(&self) -> Option<TermOffset> {
 994        delegate!(self, w => w.get_term_cursor())
 995    }
 996
 997    fn hide_term_cursor(&self) -> bool {
 998        delegate!(self, w => w.hide_term_cursor())
 999    }
1000}
1001
1002impl WindowOps<IambInfo> for RoomState {
1003    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
1004        if self.room_state() != Some(MatrixRoomState::Joined) {
1005            self.refresh_room(store);
1006        }
1007
1008        if let Some(room) = self.room() {
1009            match room.state() {
1010                MatrixRoomState::Invited => return self.draw_invite(room, area, buf, store),
1011                MatrixRoomState::Knocked => return self.draw_knock(room, area, buf, store),
1012                MatrixRoomState::Left => return self.draw_left(room, area, buf, store),
1013                _ => (),
1014            }
1015        }
1016
1017        match self {
1018            RoomState::Chat(chat) => {
1019                chat.draw(area, buf, focused, store);
1020            },
1021            RoomState::Joining(state) => {
1022                Joining.render(area, buf, state);
1023            },
1024            RoomState::NotJoined(state) => {
1025                NotJoined.render(area, buf, state);
1026            },
1027            RoomState::Space(space) => {
1028                Space::new(store).focus(focused).render(area, buf, space);
1029            },
1030        }
1031    }
1032
1033    fn dup(&self, store: &mut ProgramStore) -> Self {
1034        match self {
1035            RoomState::Joining(w) => RoomState::join(w.room.clone(), store),
1036            RoomState::NotJoined(w) => RoomState::NotJoined((*w).clone()),
1037            RoomState::Chat(chat) => RoomState::Chat(Box::new(chat.dup(store))),
1038            RoomState::Space(space) => RoomState::Space(Box::new(space.dup(store))),
1039        }
1040    }
1041
1042    fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
1043        match self {
1044            RoomState::NotJoined(_) | RoomState::Joining(_) => true,
1045            RoomState::Chat(chat) => chat.close(flags, store),
1046            RoomState::Space(space) => space.close(flags, store),
1047        }
1048    }
1049
1050    fn write(
1051        &mut self,
1052        path: Option<&str>,
1053        flags: WriteFlags,
1054        store: &mut ProgramStore,
1055    ) -> IambResult<EditInfo> {
1056        match self {
1057            RoomState::NotJoined(_) | RoomState::Joining(_) => Err(EditError::ReadOnly.into()),
1058            RoomState::Chat(chat) => chat.write(path, flags, store),
1059            RoomState::Space(space) => space.write(path, flags, store),
1060        }
1061    }
1062
1063    fn get_completions(&self) -> Option<CompletionList> {
1064        match self {
1065            RoomState::NotJoined(_) | RoomState::Joining(_) => None,
1066            RoomState::Chat(chat) => chat.get_completions(),
1067            RoomState::Space(space) => space.get_completions(),
1068        }
1069    }
1070
1071    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
1072        match self {
1073            RoomState::NotJoined(_) | RoomState::Joining(_) => None,
1074            RoomState::Chat(chat) => chat.get_cursor_word(style),
1075            RoomState::Space(space) => space.get_cursor_word(style),
1076        }
1077    }
1078
1079    fn get_selected_word(&self) -> Option<String> {
1080        match self {
1081            RoomState::NotJoined(_) | RoomState::Joining(_) => None,
1082            RoomState::Chat(chat) => chat.get_selected_word(),
1083            RoomState::Space(space) => space.get_selected_word(),
1084        }
1085    }
1086}
1087
1088#[cfg(test)]
1089mod tests {
1090    use super::*;
1091
1092    #[test]
1093    fn test_parse_room_notification_level() {
1094        let tests = vec![
1095            ("mute", RoomNotificationMode::Mute),
1096            ("mentions", RoomNotificationMode::MentionsAndKeywordsOnly),
1097            ("keywords", RoomNotificationMode::MentionsAndKeywordsOnly),
1098            ("all", RoomNotificationMode::AllMessages),
1099        ];
1100
1101        for (input, expect) in tests {
1102            let res = notification_mode(input).unwrap();
1103            assert_eq!(expect, res);
1104        }
1105
1106        assert!(notification_mode("invalid").is_err());
1107        assert!(notification_mode("not a level").is_err());
1108        assert!(notification_mode("@user:example.com").is_err());
1109    }
1110}