src/windows/room/mod.rs

1060 lines · 39526 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            room.privacy_settings()
 264                .update_join_rule(rule)
 265                .await
 266                .map_err(IambError::from)?;
 267            Ok(vec![])
 268        },
 269        RoomAction::SetDirect(is_direct) => {
 270            let room = store
 271                .application
 272                .get_joined_room(id)
 273                .ok_or(UIError::Application(IambError::NotJoined))?;
 274
 275            room.set_is_direct(is_direct).await.map_err(IambError::from)?;
 276
 277            Ok(vec![])
 278        },
 279        RoomAction::SetUnread(is_unread) => {
 280            let room = store
 281                .application
 282                .get_joined_room(id)
 283                .ok_or(UIError::Application(IambError::NotJoined))?;
 284
 285            room.set_unread_flag(is_unread).await.map_err(IambError::from)?;
 286
 287            if !is_unread {
 288                let user_id = store.application.settings.profile.user_id.clone();
 289                let info = store.application.get_room_info(id.to_owned());
 290                let messages = info.get_thread(None).expect("room main timeline doesn't exist");
 291                if let Some((key, _)) = messages.last_key_value() &&
 292                    let Some(event_id) = key.id.as_origin()
 293                {
 294                    info.set_receipt(
 295                        matrix_sdk::ruma::events::receipt::ReceiptThread::Main,
 296                        user_id,
 297                        event_id.to_owned(),
 298                    );
 299                }
 300            }
 301
 302            Ok(vec![])
 303        },
 304        RoomAction::Set(field, value) => {
 305            let room = store
 306                .application
 307                .get_joined_room(id)
 308                .ok_or(UIError::Application(IambError::NotJoined))?;
 309
 310            match field {
 311                RoomField::History => {
 312                    let visibility = hist_visibility_mode(value)?;
 313                    let ev = RoomHistoryVisibilityEventContent::new(visibility);
 314                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 315                },
 316                RoomField::Name => {
 317                    let ev = RoomNameEventContent::new(value);
 318                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 319                },
 320                RoomField::Tag(tag) => {
 321                    let mut info = TagInfo::new();
 322                    info.order = Some(1.0);
 323
 324                    let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
 325                },
 326                RoomField::Topic => {
 327                    let ev = RoomTopicEventContent::new(value);
 328                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 329                },
 330                RoomField::NotificationMode => {
 331                    let mode = notification_mode(value)?;
 332                    let client = &store.application.worker.client;
 333                    let notifications = client.notification_settings().await;
 334
 335                    notifications
 336                        .set_room_notification_mode(id, mode)
 337                        .await
 338                        .map_err(IambError::from)?;
 339                },
 340                RoomField::CanonicalAlias => {
 341                    let client = &mut store.application.worker.client;
 342
 343                    let Ok(orai) = OwnedRoomAliasId::try_from(value.as_str()) else {
 344                        let err = IambError::InvalidRoomAlias(value);
 345
 346                        return Err(err.into());
 347                    };
 348
 349                    let mut alt_aliases = room.alt_aliases().into_iter().collect::<HashSet<_>>();
 350                    let canonical_old = room.canonical_alias();
 351
 352                    // If the room's alias is already that, ignore it
 353                    if canonical_old.as_ref() == Some(&orai) {
 354                        let msg = format!("The canonical room alias is already {orai}");
 355
 356                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 357                    }
 358
 359                    // Try creating the room alias on the server.
 360                    if let Err(e) = client.create_room_alias(&orai, room.room_id()).await {
 361                        if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
 362                            // Ignore when it already exists.
 363                        } else {
 364                            return Err(IambError::from(e).into());
 365                        }
 366                    }
 367
 368                    // Demote the previous one to an alt alias.
 369                    alt_aliases.extend(canonical_old);
 370
 371                    // At this point the room alias definitely exists, and we can update the
 372                    // state event.
 373                    let mut ev = RoomCanonicalAliasEventContent::new();
 374                    ev.alias = Some(orai);
 375                    ev.alt_aliases = alt_aliases.into_iter().collect();
 376                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 377                },
 378                RoomField::Alias(alias) => {
 379                    let client = &mut store.application.worker.client;
 380
 381                    let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
 382                        let err = IambError::InvalidRoomAlias(alias);
 383
 384                        return Err(err.into());
 385                    };
 386
 387                    let mut alt_aliases = room.alt_aliases().into_iter().collect::<HashSet<_>>();
 388                    let canonical = room.canonical_alias();
 389
 390                    if alt_aliases.contains(&orai) || canonical.as_ref() == Some(&orai) {
 391                        let msg = format!("The alias {orai} already maps to this room");
 392
 393                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 394                    } else {
 395                        alt_aliases.insert(orai.clone());
 396                    }
 397
 398                    // If the room alias does not exist on the server, create it
 399                    if let Err(e) = client.create_room_alias(&orai, room.room_id()).await {
 400                        if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
 401                            // Ignore when it already exists.
 402                        } else {
 403                            return Err(IambError::from(e).into());
 404                        }
 405                    }
 406
 407                    // And add it to the aliases in the state event.
 408                    let mut ev = RoomCanonicalAliasEventContent::new();
 409                    ev.alias = canonical;
 410                    ev.alt_aliases = alt_aliases.into_iter().collect();
 411                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 412                },
 413                RoomField::UserName => {
 414                    room.set_own_member_display_name(Some(value))
 415                        .await
 416                        .map_err(IambError::from)?;
 417                },
 418                RoomField::Access | RoomField::Aliases | RoomField::Id | RoomField::Version => {
 419                    // These variants exist for RoomAction::Show, so we never actually get here.
 420                },
 421            }
 422
 423            Ok(vec![])
 424        },
 425        RoomAction::Unset(field) => {
 426            let room = store
 427                .application
 428                .get_joined_room(id)
 429                .ok_or(UIError::Application(IambError::NotJoined))?;
 430
 431            match field {
 432                RoomField::History => {
 433                    let visibility = HistoryVisibility::Joined;
 434                    let ev = RoomHistoryVisibilityEventContent::new(visibility);
 435                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 436                },
 437                RoomField::Name => {
 438                    let ev = RoomNameEventContent::new("".into());
 439                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 440                },
 441                RoomField::Tag(tag) => {
 442                    let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
 443                },
 444                RoomField::Topic => {
 445                    let ev = RoomTopicEventContent::new("".into());
 446                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 447                },
 448                RoomField::NotificationMode => {
 449                    let client = &store.application.worker.client;
 450                    let notifications = client.notification_settings().await;
 451
 452                    notifications
 453                        .delete_user_defined_room_rules(id)
 454                        .await
 455                        .map_err(IambError::from)?;
 456                },
 457                RoomField::CanonicalAlias => {
 458                    let Some(alias_to_destroy) = room.canonical_alias() else {
 459                        let msg = "This room has no canonical alias to unset";
 460
 461                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 462                    };
 463
 464                    // Remove the canonical alias from the state event.
 465                    let mut ev = RoomCanonicalAliasEventContent::new();
 466                    ev.alias = None;
 467                    ev.alt_aliases = room.alt_aliases();
 468                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 469
 470                    // And then unmap it on the server.
 471                    store
 472                        .application
 473                        .worker
 474                        .client
 475                        .remove_room_alias(&alias_to_destroy)
 476                        .await
 477                        .map_err(IambError::from)?;
 478                },
 479                RoomField::Alias(alias) => {
 480                    let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
 481                        let err = IambError::InvalidRoomAlias(alias);
 482
 483                        return Err(err.into());
 484                    };
 485
 486                    let alt_aliases = room.alt_aliases();
 487                    let canonical = room.canonical_alias();
 488
 489                    if !alt_aliases.contains(&orai) && canonical.as_ref() != Some(&orai) {
 490                        let msg = format!("The alias {orai:?} isn't mapped to this room");
 491
 492                        return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
 493                    }
 494
 495                    // Remove the alias from the state event if it's in it.
 496                    let mut ev = RoomCanonicalAliasEventContent::new();
 497                    ev.alias = canonical.filter(|canon| canon != &orai);
 498                    ev.alt_aliases = alt_aliases;
 499                    ev.alt_aliases.retain(|in_orai| in_orai != &orai);
 500                    let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
 501
 502                    // And then unmap it on the server.
 503                    store
 504                        .application
 505                        .worker
 506                        .client
 507                        .remove_room_alias(&orai)
 508                        .await
 509                        .map_err(IambError::from)?;
 510                },
 511                RoomField::UserName => {
 512                    room.set_own_member_display_name(None).await.map_err(IambError::from)?;
 513                },
 514                RoomField::Access | RoomField::Aliases | RoomField::Id | RoomField::Version => {
 515                    // These variants exist for RoomAction::Show, so we never actually get here.
 516                },
 517            }
 518
 519            Ok(vec![])
 520        },
 521        RoomAction::Show(field) => {
 522            let room = store
 523                .application
 524                .get_joined_room(id)
 525                .ok_or(UIError::Application(IambError::NotJoined))?;
 526
 527            let msg = match field {
 528                RoomField::History => {
 529                    let visibility = room.history_visibility();
 530                    let visibility = visibility.as_ref().map(|v| v.as_str());
 531                    format!("Room history visibility: {}", visibility.unwrap_or("<unknown>"))
 532                },
 533                RoomField::Id => {
 534                    let id = room.room_id();
 535                    format!("Room identifier: {id}")
 536                },
 537                RoomField::Version => {
 538                    let v = room.version();
 539                    let v = v.as_ref().map(|v| v.as_str()).unwrap_or("<version unknown>");
 540                    format!("Room version: {v}")
 541                },
 542                RoomField::Name => {
 543                    match room.name() {
 544                        None => "Room has no name".into(),
 545                        Some(name) => format!("Room name: {name:?}"),
 546                    }
 547                },
 548                RoomField::Topic => {
 549                    match room.topic() {
 550                        None => "Room has no topic".into(),
 551                        Some(topic) => format!("Room topic: {topic:?}"),
 552                    }
 553                },
 554                RoomField::NotificationMode => {
 555                    let client = &store.application.worker.client;
 556                    let notifications = client.notification_settings().await;
 557                    let mode = notifications.get_user_defined_room_notification_mode(id).await;
 558
 559                    let level = match mode {
 560                        Some(RoomNotificationMode::Mute) => "mute",
 561                        Some(RoomNotificationMode::MentionsAndKeywordsOnly) => "keywords",
 562                        Some(RoomNotificationMode::AllMessages) => "all",
 563                        None => "default",
 564                    };
 565
 566                    format!("Room notification level: {level:?}")
 567                },
 568                RoomField::Access => {
 569                    let show_restrictions = |rs: JoinRestrictions| {
 570                        rs.allow
 571                            .into_iter()
 572                            .map(|a| {
 573                                match a {
 574                                    AllowRule::RoomMembership(m) => {
 575                                        if let Some(alias) =
 576                                            store.application.get_joined_room_alias(&m.room_id)
 577                                        {
 578                                            format!("members of {} ({alias})", m.room_id)
 579                                        } else {
 580                                            format!("members of {}", m.room_id)
 581                                        }
 582                                    },
 583                                    other => format!("{other:?}"),
 584                                }
 585                            })
 586                            .collect::<Vec<_>>()
 587                            .join(", ")
 588                    };
 589
 590                    let desc = match room.join_rule() {
 591                        None => "<unknown>".into(),
 592                        Some(JoinRule::Invite) => "invite".into(),
 593                        Some(JoinRule::Knock) => "knock".into(),
 594                        Some(JoinRule::Private) => "private".into(),
 595                        Some(JoinRule::Public) => "public".into(),
 596                        Some(JoinRule::Restricted(restrictions)) => {
 597                            let allowing = show_restrictions(restrictions);
 598                            if allowing.is_empty() {
 599                                "restricted".into()
 600                            } else {
 601                                format!("restricted, allowing {allowing}")
 602                            }
 603                        },
 604                        Some(JoinRule::KnockRestricted(restrictions)) => {
 605                            let allowing = show_restrictions(restrictions);
 606                            if allowing.is_empty() {
 607                                "knock-restricted".into()
 608                            } else {
 609                                format!("knock-restricted, allowing {allowing}")
 610                            }
 611                        },
 612                        Some(other) => format!("{other:?}"),
 613                    };
 614
 615                    format!("Room join rules are set to: {desc}")
 616                },
 617                RoomField::Aliases => {
 618                    let aliases = room
 619                        .alt_aliases()
 620                        .iter()
 621                        .map(OwnedRoomAliasId::to_string)
 622                        .collect::<Vec<String>>();
 623
 624                    if aliases.is_empty() {
 625                        "No alternative aliases in room".into()
 626                    } else {
 627                        format!("Alternative aliases: {}.", aliases.join(", "))
 628                    }
 629                },
 630                RoomField::CanonicalAlias => {
 631                    match room.canonical_alias() {
 632                        None => "No canonical alias for room".into(),
 633                        Some(can) => format!("Canonical alias: {can}"),
 634                    }
 635                },
 636                RoomField::Tag(_) => "Cannot currently show value for a tag".into(),
 637                RoomField::Alias(_) => {
 638                    "Cannot show a single alias; use `:room aliases show` instead.".into()
 639                },
 640                RoomField::UserName => {
 641                    let user_id = &store.application.settings.profile.user_id;
 642                    let Some(member) = room.get_member(user_id).await.map_err(IambError::from)?
 643                    else {
 644                        let msg = "Cannot find membership data".into();
 645                        return Err(IambError::Custom(msg))?;
 646                    };
 647
 648                    match member.display_name() {
 649                        Some(name) => format!("User name: \"{name}\""),
 650                        None => "No user name set".into(),
 651                    }
 652                },
 653            };
 654
 655            let msg = InfoMessage::Pager(msg);
 656            let act = Action::ShowInfoMessage(msg);
 657
 658            Ok(vec![(act, ctx)])
 659        },
 660        RoomAction::Upgrade(new_version, additional_creators, false) => {
 661            let room = worker.client.get_room(id).ok_or(IambError::NotJoined)?;
 662            let alias = room.canonical_alias();
 663            let name = alias.as_ref().map(|c| c.as_str()).unwrap_or_else(|| id.as_str());
 664            let msg = format!(
 665                "Are you sure you want to upgrade {name} to version {new_version} with {} additional creators set?",
 666                additional_creators.len()
 667            );
 668            let upgrade =
 669                IambAction::Room(RoomAction::Upgrade(new_version, additional_creators, true));
 670            let prompt = PromptYesNo::new(msg, vec![Action::from(upgrade)]);
 671            let prompt = Box::new(prompt);
 672
 673            Err(UIError::NeedConfirm(prompt))
 674        },
 675        RoomAction::Upgrade(new_version, additional_creators, true) => {
 676            let mut request = UpgradeRoomRequest::new(id.to_owned(), new_version);
 677            request.additional_creators = additional_creators;
 678
 679            let response = worker.client.send(request).await.map_err(IambError::from)?;
 680            let id = IambId::Room(response.replacement_room, None);
 681            let target = OpenTarget::Application(id);
 682            let act = WindowAction::Switch(target);
 683
 684            Ok(vec![(act.into(), ctx)])
 685        },
 686    }
 687}
 688
 689/// State for a Matrix room or space.
 690///
 691/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
 692/// that operations like sending and accepting invites, opening the members window, etc., all work
 693/// similarly.
 694pub enum RoomState {
 695    Chat(Box<ChatState>),
 696    Space(Box<SpaceState>),
 697}
 698
 699impl From<ChatState> for RoomState {
 700    fn from(chat: ChatState) -> Self {
 701        RoomState::Chat(Box::new(chat))
 702    }
 703}
 704
 705impl From<SpaceState> for RoomState {
 706    fn from(space: SpaceState) -> Self {
 707        RoomState::Space(Box::new(space))
 708    }
 709}
 710
 711impl RoomState {
 712    pub fn new(
 713        room: MatrixRoom,
 714        thread: Option<OwnedEventId>,
 715        name: RoomDisplayName,
 716        tags: Option<Tags>,
 717        store: &mut ProgramStore,
 718    ) -> Self {
 719        let room_id = room.room_id().to_owned();
 720        let info = store.application.get_room_info(room_id);
 721        info.name = name.to_string().into();
 722        info.tags = tags;
 723
 724        if room.is_space() {
 725            SpaceState::new(room).into()
 726        } else {
 727            ChatState::new(room, thread, store).into()
 728        }
 729    }
 730
 731    pub fn thread(&self) -> Option<&OwnedEventId> {
 732        match self {
 733            RoomState::Chat(chat) => chat.thread(),
 734            RoomState::Space(_) => None,
 735        }
 736    }
 737
 738    pub fn refresh_room(&mut self, store: &mut ProgramStore) {
 739        match self {
 740            RoomState::Chat(chat) => chat.refresh_room(store),
 741            RoomState::Space(space) => space.refresh_room(store),
 742        }
 743    }
 744
 745    fn draw_invite(
 746        &self,
 747        invited: &MatrixRoom,
 748        area: Rect,
 749        buf: &mut Buffer,
 750        store: &mut ProgramStore,
 751    ) {
 752        let inviter = store.application.worker.get_inviter(invited.clone());
 753
 754        let name = match invited.canonical_alias() {
 755            Some(alias) => alias.to_string(),
 756            None => format!("{:?}", store.application.get_room_title(self.id())),
 757        };
 758
 759        let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
 760
 761        if let Ok(Some(inviter)) = &inviter {
 762            let info = store.application.rooms.get_or_default(self.id().to_owned());
 763            invited.push(Span::from(" by "));
 764            invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
 765        }
 766
 767        let l1 = Line::from(invited);
 768        let l2 = Line::from(
 769            "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
 770        );
 771        let text = Text::from(vec![l1, l2]);
 772
 773        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 774
 775        return;
 776    }
 777
 778    fn draw_knock(
 779        &self,
 780        knocked: &MatrixRoom,
 781        area: Rect,
 782        buf: &mut Buffer,
 783        store: &mut ProgramStore,
 784    ) {
 785        let name = match knocked.canonical_alias() {
 786            Some(alias) => alias.to_string(),
 787            None => format!("{:?}", store.application.get_room_title(self.id())),
 788        };
 789
 790        let l1 = Line::from(format!(
 791            "Your request to join {name} is pending review by room moderators."
 792        ));
 793        let l2 = Line::from("You can run `:leave` to withdraw your knock request.");
 794        let text = Text::from(vec![l1, l2]);
 795
 796        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 797
 798        return;
 799    }
 800
 801    fn draw_left(&self, room: &MatrixRoom, area: Rect, buf: &mut Buffer, store: &mut ProgramStore) {
 802        let name = match room.canonical_alias() {
 803            Some(alias) => alias.to_string(),
 804            None => format!("{:?}", store.application.get_room_title(self.id())),
 805        };
 806
 807        let mut lines = vec![Line::from(format!("You have left {name}!"))];
 808
 809        if room.is_public().is_some_and(|b| b) {
 810            lines.push(Line::from(format!("You can run `:join {name}` to rejoin.")));
 811        }
 812
 813        let text = Text::from(lines);
 814
 815        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
 816
 817        return;
 818    }
 819
 820    pub async fn message_command(
 821        &mut self,
 822        act: MessageAction,
 823        ctx: ProgramContext,
 824        store: &mut ProgramStore,
 825    ) -> IambResult<EditInfo> {
 826        match self {
 827            RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
 828            RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
 829        }
 830    }
 831
 832    pub async fn space_command(
 833        &mut self,
 834        act: SpaceAction,
 835        ctx: ProgramContext,
 836        store: &mut ProgramStore,
 837    ) -> IambResult<EditInfo> {
 838        match self {
 839            RoomState::Space(space) => space.space_command(act, ctx, store).await,
 840            RoomState::Chat(_) => Err(IambError::NoSelectedSpace.into()),
 841        }
 842    }
 843
 844    pub async fn send_command(
 845        &mut self,
 846        act: SendAction,
 847        ctx: ProgramContext,
 848        store: &mut ProgramStore,
 849    ) -> IambResult<EditInfo> {
 850        match self {
 851            RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
 852            RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
 853        }
 854    }
 855
 856    pub fn get_title(&self, store: &mut ProgramStore) -> Line<'_> {
 857        let room = store.application.worker.client.get_room(self.id());
 858
 859        let title = store.application.get_room_title(self.id());
 860        let style = Style::default().add_modifier(StyleModifier::BOLD);
 861        let mut spans = vec![];
 862
 863        if let RoomState::Chat(chat) = self &&
 864            chat.thread().is_some()
 865        {
 866            spans.push("Thread in ".into());
 867        }
 868
 869        spans.push(Span::styled(title, style));
 870
 871        if let Some(room) = room {
 872            let encryption_settings = &store.application.settings.tunables.encryption;
 873            let encryption_indicator = encryption_settings
 874                .get_indicator(EncryptionIndicatorLocation::TITLE, room.encryption_state());
 875            spans.extend(encryption_indicator);
 876        }
 877
 878        match self.room().topic() {
 879            Some(desc) if !desc.is_empty() => {
 880                spans.push(" (".into());
 881                spans.push(desc.into());
 882                spans.push(")".into());
 883            },
 884            _ => {
 885                spans.push(" ".into());
 886            },
 887        }
 888
 889        Line::from(spans)
 890    }
 891
 892    pub fn focus_toggle(&mut self) {
 893        match self {
 894            RoomState::Chat(chat) => chat.focus_toggle(),
 895            RoomState::Space(_) => return,
 896        }
 897    }
 898
 899    pub fn room(&self) -> &MatrixRoom {
 900        match self {
 901            RoomState::Chat(chat) => chat.room(),
 902            RoomState::Space(space) => space.room(),
 903        }
 904    }
 905
 906    pub fn id(&self) -> &RoomId {
 907        match self {
 908            RoomState::Chat(chat) => chat.id(),
 909            RoomState::Space(space) => space.id(),
 910        }
 911    }
 912}
 913
 914impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 915    fn editor_command(
 916        &mut self,
 917        act: &EditorAction,
 918        ctx: &ProgramContext,
 919        store: &mut ProgramStore,
 920    ) -> EditResult<EditInfo, IambInfo> {
 921        delegate!(self, w => w.editor_command(act, ctx, store))
 922    }
 923}
 924
 925impl Jumpable<ProgramContext, IambInfo> for RoomState {
 926    fn jump(
 927        &mut self,
 928        list: PositionList,
 929        dir: MoveDir1D,
 930        count: usize,
 931        ctx: &ProgramContext,
 932    ) -> IambResult<usize> {
 933        delegate!(self, w => w.jump(list, dir, count, ctx))
 934    }
 935}
 936
 937impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 938    fn scroll(
 939        &mut self,
 940        style: &ScrollStyle,
 941        ctx: &ProgramContext,
 942        store: &mut ProgramStore,
 943    ) -> EditResult<EditInfo, IambInfo> {
 944        delegate!(self, w => w.scroll(style, ctx, store))
 945    }
 946}
 947
 948impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
 949    fn prompt(
 950        &mut self,
 951        act: &PromptAction,
 952        ctx: &ProgramContext,
 953        store: &mut ProgramStore,
 954    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 955        delegate!(self, w => w.prompt(act, ctx, store))
 956    }
 957}
 958
 959impl TerminalCursor for RoomState {
 960    fn get_term_cursor(&self) -> Option<TermOffset> {
 961        delegate!(self, w => w.get_term_cursor())
 962    }
 963
 964    fn hide_term_cursor(&self) -> bool {
 965        delegate!(self, w => w.hide_term_cursor())
 966    }
 967}
 968
 969impl WindowOps<IambInfo> for RoomState {
 970    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
 971        if self.room().state() != MatrixRoomState::Joined {
 972            self.refresh_room(store);
 973        }
 974
 975        match self.room().state() {
 976            MatrixRoomState::Invited => return self.draw_invite(self.room(), area, buf, store),
 977            MatrixRoomState::Knocked => return self.draw_knock(self.room(), area, buf, store),
 978            MatrixRoomState::Left => return self.draw_left(self.room(), area, buf, store),
 979            _ => (),
 980        }
 981
 982        match self {
 983            RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
 984            RoomState::Space(space) => {
 985                Space::new(store).focus(focused).render(area, buf, space);
 986            },
 987        }
 988    }
 989
 990    fn dup(&self, store: &mut ProgramStore) -> Self {
 991        match self {
 992            RoomState::Chat(chat) => RoomState::Chat(Box::new(chat.dup(store))),
 993            RoomState::Space(space) => RoomState::Space(Box::new(space.dup(store))),
 994        }
 995    }
 996
 997    fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
 998        match self {
 999            RoomState::Chat(chat) => chat.close(flags, store),
1000            RoomState::Space(space) => space.close(flags, store),
1001        }
1002    }
1003
1004    fn write(
1005        &mut self,
1006        path: Option<&str>,
1007        flags: WriteFlags,
1008        store: &mut ProgramStore,
1009    ) -> IambResult<EditInfo> {
1010        match self {
1011            RoomState::Chat(chat) => chat.write(path, flags, store),
1012            RoomState::Space(space) => space.write(path, flags, store),
1013        }
1014    }
1015
1016    fn get_completions(&self) -> Option<CompletionList> {
1017        match self {
1018            RoomState::Chat(chat) => chat.get_completions(),
1019            RoomState::Space(space) => space.get_completions(),
1020        }
1021    }
1022
1023    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
1024        match self {
1025            RoomState::Chat(chat) => chat.get_cursor_word(style),
1026            RoomState::Space(space) => space.get_cursor_word(style),
1027        }
1028    }
1029
1030    fn get_selected_word(&self) -> Option<String> {
1031        match self {
1032            RoomState::Chat(chat) => chat.get_selected_word(),
1033            RoomState::Space(space) => space.get_selected_word(),
1034        }
1035    }
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040    use super::*;
1041
1042    #[test]
1043    fn test_parse_room_notification_level() {
1044        let tests = vec![
1045            ("mute", RoomNotificationMode::Mute),
1046            ("mentions", RoomNotificationMode::MentionsAndKeywordsOnly),
1047            ("keywords", RoomNotificationMode::MentionsAndKeywordsOnly),
1048            ("all", RoomNotificationMode::AllMessages),
1049        ];
1050
1051        for (input, expect) in tests {
1052            let res = notification_mode(input).unwrap();
1053            assert_eq!(expect, res);
1054        }
1055
1056        assert!(notification_mode("invalid").is_err());
1057        assert!(notification_mode("not a level").is_err());
1058        assert!(notification_mode("@user:example.com").is_err());
1059    }
1060}