src/windows/room/mod.rs

1061 lines · 39611 bytes

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