src/base.rs

708 lines · 20225 bytes

  1use std::collections::{HashMap, HashSet};
  2use std::hash::Hash;
  3use std::sync::Arc;
  4use std::time::{Duration, Instant};
  5
  6use tokio::sync::Mutex as AsyncMutex;
  7use tracing::warn;
  8
  9use matrix_sdk::{
 10    encryption::verification::SasVerification,
 11    room::Joined,
 12    ruma::{
 13        events::room::message::{
 14            OriginalRoomMessageEvent,
 15            Relation,
 16            Replacement,
 17            RoomMessageEvent,
 18            RoomMessageEventContent,
 19        },
 20        events::tag::{TagName, Tags},
 21        EventId,
 22        OwnedEventId,
 23        OwnedRoomId,
 24        OwnedUserId,
 25        RoomId,
 26    },
 27};
 28
 29use modalkit::{
 30    editing::{
 31        action::{Action, UIError, UIResult},
 32        application::{
 33            ApplicationAction,
 34            ApplicationContentId,
 35            ApplicationError,
 36            ApplicationInfo,
 37            ApplicationStore,
 38            ApplicationWindowId,
 39        },
 40        context::EditContext,
 41        store::Store,
 42    },
 43    env::vim::{
 44        command::{CommandContext, VimCommand, VimCommandMachine},
 45        keybindings::VimMachine,
 46        VimContext,
 47    },
 48    input::bindings::SequenceStatus,
 49    input::key::TerminalKey,
 50    tui::{
 51        buffer::Buffer,
 52        layout::{Alignment, Rect},
 53        text::{Span, Spans},
 54        widgets::{Paragraph, Widget},
 55    },
 56};
 57
 58use crate::{
 59    message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
 60    worker::Requester,
 61    ApplicationSettings,
 62};
 63
 64const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
 65
 66#[derive(Clone, Debug, Eq, PartialEq)]
 67pub enum IambInfo {}
 68
 69#[derive(Clone, Debug, Eq, PartialEq)]
 70pub enum VerifyAction {
 71    Accept,
 72    Cancel,
 73    Confirm,
 74    Mismatch,
 75}
 76
 77#[derive(Clone, Debug, Eq, PartialEq)]
 78pub enum MessageAction {
 79    /// Cance the current reply or edit.
 80    Cancel,
 81
 82    /// Download an attachment to the given path.
 83    ///
 84    /// The second argument controls whether to overwrite any already existing file at the
 85    /// destination path, or to open the attachment after downloading.
 86    Download(Option<String>, DownloadFlags),
 87
 88    /// Edit a sent message.
 89    Edit,
 90
 91    /// Redact a message.
 92    Redact(Option<String>),
 93
 94    /// Reply to a message.
 95    Reply,
 96}
 97
 98bitflags::bitflags! {
 99    pub struct DownloadFlags: u32 {
100        const NONE = 0b00000000;
101
102        /// Overwrite file if it already exists.
103        const FORCE = 0b00000001;
104
105        /// Open file after downloading.
106        const OPEN = 0b00000010;
107    }
108}
109
110#[derive(Clone, Debug, Eq, PartialEq)]
111pub enum RoomField {
112    Name,
113    Tag(TagName),
114    Topic,
115}
116
117#[derive(Clone, Debug, Eq, PartialEq)]
118pub enum RoomAction {
119    InviteAccept,
120    InviteReject,
121    InviteSend(OwnedUserId),
122    Members(Box<CommandContext<ProgramContext>>),
123    Set(RoomField, String),
124    Unset(RoomField),
125}
126
127#[derive(Clone, Debug, Eq, PartialEq)]
128pub enum SendAction {
129    Submit,
130    Upload(String),
131}
132
133#[derive(Clone, Debug, Eq, PartialEq)]
134pub enum IambAction {
135    Message(MessageAction),
136    Room(RoomAction),
137    Send(SendAction),
138    Verify(VerifyAction, String),
139    VerifyRequest(String),
140    ToggleScrollbackFocus,
141}
142
143impl From<MessageAction> for IambAction {
144    fn from(act: MessageAction) -> Self {
145        IambAction::Message(act)
146    }
147}
148
149impl From<RoomAction> for IambAction {
150    fn from(act: RoomAction) -> Self {
151        IambAction::Room(act)
152    }
153}
154
155impl From<SendAction> for IambAction {
156    fn from(act: SendAction) -> Self {
157        IambAction::Send(act)
158    }
159}
160
161impl ApplicationAction for IambAction {
162    fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
163        match self {
164            IambAction::Message(..) => SequenceStatus::Break,
165            IambAction::Room(..) => SequenceStatus::Break,
166            IambAction::Send(..) => SequenceStatus::Break,
167            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
168            IambAction::Verify(..) => SequenceStatus::Break,
169            IambAction::VerifyRequest(..) => SequenceStatus::Break,
170        }
171    }
172
173    fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
174        match self {
175            IambAction::Message(..) => SequenceStatus::Atom,
176            IambAction::Room(..) => SequenceStatus::Atom,
177            IambAction::Send(..) => SequenceStatus::Atom,
178            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
179            IambAction::Verify(..) => SequenceStatus::Atom,
180            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
181        }
182    }
183
184    fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
185        match self {
186            IambAction::Message(..) => SequenceStatus::Ignore,
187            IambAction::Room(..) => SequenceStatus::Ignore,
188            IambAction::Send(..) => SequenceStatus::Ignore,
189            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
190            IambAction::Verify(..) => SequenceStatus::Ignore,
191            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
192        }
193    }
194
195    fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
196        match self {
197            IambAction::Message(..) => false,
198            IambAction::Room(..) => false,
199            IambAction::Send(..) => false,
200            IambAction::ToggleScrollbackFocus => false,
201            IambAction::Verify(..) => false,
202            IambAction::VerifyRequest(..) => false,
203        }
204    }
205}
206
207impl From<RoomAction> for ProgramAction {
208    fn from(act: RoomAction) -> Self {
209        IambAction::from(act).into()
210    }
211}
212
213impl From<IambAction> for ProgramAction {
214    fn from(act: IambAction) -> Self {
215        Action::Application(act)
216    }
217}
218
219pub type ProgramAction = Action<IambInfo>;
220pub type ProgramContext = VimContext<IambInfo>;
221pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
222pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
223pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
224pub type ProgramStore = Store<IambInfo>;
225pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
226
227pub type IambResult<T> = UIResult<T, IambInfo>;
228
229pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
230
231#[derive(thiserror::Error, Debug)]
232pub enum IambError {
233    #[error("Invalid user identifier: {0}")]
234    InvalidUserId(String),
235
236    #[error("Invalid verification user/device pair: {0}")]
237    InvalidVerificationId(String),
238
239    #[error("Cryptographic storage error: {0}")]
240    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
241
242    #[error("HTTP client error: {0}")]
243    Http(#[from] matrix_sdk::HttpError),
244
245    #[error("Matrix client error: {0}")]
246    Matrix(#[from] matrix_sdk::Error),
247
248    #[error("Matrix client storage error: {0}")]
249    Store(#[from] matrix_sdk::StoreError),
250
251    #[error("Serialization/deserialization error: {0}")]
252    Serde(#[from] serde_json::Error),
253
254    #[error("Selected message does not have any attachments")]
255    NoAttachment,
256
257    #[error("No message currently selected")]
258    NoSelectedMessage,
259
260    #[error("Current window is not a room or space")]
261    NoSelectedRoomOrSpace,
262
263    #[error("Current window is not a room")]
264    NoSelectedRoom,
265
266    #[error("You do not have a current invitation to this room")]
267    NotInvited,
268
269    #[error("You need to join the room before you can do that")]
270    NotJoined,
271
272    #[error("Unknown room identifier: {0}")]
273    UnknownRoom(OwnedRoomId),
274
275    #[error("Verification request error: {0}")]
276    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
277}
278
279impl From<IambError> for UIError<IambInfo> {
280    fn from(err: IambError) -> Self {
281        UIError::Application(err)
282    }
283}
284
285impl ApplicationError for IambError {}
286
287#[derive(Default)]
288pub enum RoomFetchStatus {
289    Done,
290    HaveMore(String),
291    #[default]
292    NotStarted,
293}
294
295#[derive(Default)]
296pub struct RoomInfo {
297    pub name: Option<String>,
298    pub tags: Option<Tags>,
299
300    pub keys: HashMap<OwnedEventId, MessageKey>,
301    pub messages: Messages,
302
303    pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
304    pub read_till: Option<OwnedEventId>,
305
306    pub fetch_id: RoomFetchStatus,
307    pub fetch_last: Option<Instant>,
308    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
309}
310
311impl RoomInfo {
312    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
313        self.messages.get(self.keys.get(event_id)?)
314    }
315
316    pub fn insert_edit(&mut self, msg: Replacement) {
317        let event_id = msg.event_id;
318        let new_content = msg.new_content;
319
320        let key = if let Some(k) = self.keys.get(&event_id) {
321            k
322        } else {
323            return;
324        };
325
326        let msg = if let Some(msg) = self.messages.get_mut(key) {
327            msg
328        } else {
329            return;
330        };
331
332        match &mut msg.event {
333            MessageEvent::Original(orig) => {
334                orig.content = *new_content;
335            },
336            MessageEvent::Local(_, content) => {
337                *content = new_content;
338            },
339            MessageEvent::Redacted(_) => {
340                return;
341            },
342        }
343    }
344
345    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
346        let event_id = msg.event_id().to_owned();
347        let key = (msg.origin_server_ts().into(), event_id.clone());
348
349        self.keys.insert(event_id.clone(), key.clone());
350        self.messages.insert(key, msg.into());
351
352        // Remove any echo.
353        let key = (MessageTimeStamp::LocalEcho, event_id);
354        let _ = self.messages.remove(&key);
355    }
356
357    pub fn insert(&mut self, msg: RoomMessageEvent) {
358        match msg {
359            RoomMessageEvent::Original(OriginalRoomMessageEvent {
360                content:
361                    RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
362                ..
363            }) => self.insert_edit(repl),
364            _ => self.insert_message(msg),
365        }
366    }
367
368    fn recently_fetched(&self) -> bool {
369        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
370    }
371
372    fn get_typers(&self) -> &[OwnedUserId] {
373        if let Some((t, users)) = &self.users_typing {
374            if t.elapsed() < Duration::from_secs(4) {
375                return users.as_ref();
376            } else {
377                return &[];
378            }
379        } else {
380            return &[];
381        }
382    }
383
384    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Spans<'a> {
385        let typers = self.get_typers();
386        let n = typers.len();
387
388        match n {
389            0 => Spans(vec![]),
390            1 => {
391                let user = settings.get_user_span(typers[0].as_ref());
392
393                Spans(vec![user, Span::from(" is typing...")])
394            },
395            2 => {
396                let user1 = settings.get_user_span(typers[0].as_ref());
397                let user2 = settings.get_user_span(typers[1].as_ref());
398
399                Spans(vec![
400                    user1,
401                    Span::raw(" and "),
402                    user2,
403                    Span::from(" are typing..."),
404                ])
405            },
406            n if n < 5 => Spans::from("Several people are typing..."),
407            _ => Spans::from("Many people are typing..."),
408        }
409    }
410
411    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
412        self.users_typing = (Instant::now(), user_ids).into();
413    }
414
415    pub fn render_typing(
416        &mut self,
417        area: Rect,
418        buf: &mut Buffer,
419        settings: &ApplicationSettings,
420    ) -> Rect {
421        if area.height <= 2 || area.width <= 20 {
422            return area;
423        }
424
425        if !settings.tunables.typing_notice_display {
426            return area;
427        }
428
429        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
430        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
431
432        Paragraph::new(self.get_typing_spans(settings))
433            .alignment(Alignment::Center)
434            .render(bar, buf);
435
436        return top;
437    }
438}
439
440pub struct ChatStore {
441    pub worker: Requester,
442    pub rooms: HashMap<OwnedRoomId, RoomInfo>,
443    pub names: HashMap<String, OwnedRoomId>,
444    pub verifications: HashMap<String, SasVerification>,
445    pub settings: ApplicationSettings,
446    pub need_load: HashSet<OwnedRoomId>,
447}
448
449impl ChatStore {
450    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
451        ChatStore {
452            worker,
453            settings,
454
455            names: Default::default(),
456            rooms: Default::default(),
457            verifications: Default::default(),
458            need_load: Default::default(),
459        }
460    }
461
462    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
463        self.worker.client.get_joined_room(room_id)
464    }
465
466    pub fn get_room_title(&self, room_id: &RoomId) -> String {
467        self.rooms
468            .get(room_id)
469            .and_then(|i| i.name.as_ref())
470            .map(String::from)
471            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
472    }
473
474    pub async fn set_receipts(&mut self, receipts: Vec<(OwnedRoomId, Receipts)>) {
475        let mut updates = vec![];
476
477        for (room_id, receipts) in receipts.into_iter() {
478            if let Some(info) = self.rooms.get_mut(&room_id) {
479                info.receipts = receipts;
480
481                if let Some(read_till) = info.read_till.take() {
482                    updates.push((room_id, read_till));
483                }
484            }
485        }
486
487        for (room_id, read_till) in updates.into_iter() {
488            if let Some(room) = self.worker.client.get_joined_room(&room_id) {
489                let _ = room.read_receipt(read_till.as_ref()).await;
490            }
491        }
492    }
493
494    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
495        self.need_load.insert(room_id);
496    }
497
498    pub fn load_older(&mut self, limit: u32) {
499        let ChatStore { need_load, rooms, worker, .. } = self;
500
501        for room_id in std::mem::take(need_load).into_iter() {
502            let info = rooms.entry(room_id.clone()).or_default();
503
504            if info.recently_fetched() {
505                need_load.insert(room_id);
506                continue;
507            } else {
508                info.fetch_last = Instant::now().into();
509            }
510
511            let fetch_id = match &info.fetch_id {
512                RoomFetchStatus::Done => continue,
513                RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
514                RoomFetchStatus::NotStarted => None,
515            };
516
517            let res = worker.load_older(room_id.clone(), fetch_id, limit);
518
519            match res {
520                Ok((fetch_id, msgs)) => {
521                    for msg in msgs.into_iter() {
522                        info.insert(msg);
523                    }
524
525                    info.fetch_id =
526                        fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
527                },
528                Err(e) => {
529                    warn!(
530                        room_id = room_id.as_str(),
531                        err = e.to_string(),
532                        "Failed to load older messages"
533                    );
534
535                    // Wait and try again.
536                    need_load.insert(room_id);
537                },
538            }
539        }
540    }
541
542    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
543        self.rooms.entry(room_id).or_default()
544    }
545
546    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
547        self.rooms.entry(room_id.to_owned()).or_default().name = name.to_string().into();
548    }
549
550    pub fn insert_sas(&mut self, sas: SasVerification) {
551        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
552
553        self.verifications.insert(key, sas);
554    }
555}
556
557impl ApplicationStore for ChatStore {}
558
559#[derive(Clone, Debug, Eq, Hash, PartialEq)]
560pub enum IambId {
561    Room(OwnedRoomId),
562    DirectList,
563    MemberList(OwnedRoomId),
564    RoomList,
565    SpaceList,
566    VerifyList,
567    Welcome,
568}
569
570impl ApplicationWindowId for IambId {}
571
572#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
573pub enum RoomFocus {
574    Scrollback,
575    MessageBar,
576}
577
578impl RoomFocus {
579    pub fn is_scrollback(&self) -> bool {
580        matches!(self, RoomFocus::Scrollback)
581    }
582
583    pub fn is_msgbar(&self) -> bool {
584        matches!(self, RoomFocus::MessageBar)
585    }
586}
587
588#[derive(Clone, Debug, Eq, Hash, PartialEq)]
589pub enum IambBufferId {
590    Command,
591    Room(OwnedRoomId, RoomFocus),
592    DirectList,
593    MemberList(OwnedRoomId),
594    RoomList,
595    SpaceList,
596    VerifyList,
597    Welcome,
598}
599
600impl IambBufferId {
601    pub fn to_window(&self) -> Option<IambId> {
602        match self {
603            IambBufferId::Command => None,
604            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
605            IambBufferId::DirectList => Some(IambId::DirectList),
606            IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
607            IambBufferId::RoomList => Some(IambId::RoomList),
608            IambBufferId::SpaceList => Some(IambId::SpaceList),
609            IambBufferId::VerifyList => Some(IambId::VerifyList),
610            IambBufferId::Welcome => Some(IambId::Welcome),
611        }
612    }
613}
614
615impl ApplicationContentId for IambBufferId {}
616
617impl ApplicationInfo for IambInfo {
618    type Error = IambError;
619    type Store = ChatStore;
620    type Action = IambAction;
621    type WindowId = IambId;
622    type ContentId = IambBufferId;
623}
624
625#[cfg(test)]
626pub mod tests {
627    use super::*;
628    use crate::config::user_style_from_color;
629    use crate::tests::*;
630    use modalkit::tui::style::Color;
631
632    #[test]
633    fn test_typing_spans() {
634        let mut info = RoomInfo::default();
635        let settings = mock_settings();
636
637        let users0 = vec![];
638        let users1 = vec![TEST_USER1.clone()];
639        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
640        let users4 = vec![
641            TEST_USER1.clone(),
642            TEST_USER2.clone(),
643            TEST_USER3.clone(),
644            TEST_USER4.clone(),
645        ];
646        let users5 = vec![
647            TEST_USER1.clone(),
648            TEST_USER2.clone(),
649            TEST_USER3.clone(),
650            TEST_USER4.clone(),
651            TEST_USER5.clone(),
652        ];
653
654        // Nothing set.
655        assert_eq!(info.users_typing, None);
656        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
657
658        // Empty typing list.
659        info.set_typing(users0);
660        assert!(info.users_typing.is_some());
661        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
662
663        // Single user typing.
664        info.set_typing(users1);
665        assert!(info.users_typing.is_some());
666        assert_eq!(
667            info.get_typing_spans(&settings),
668            Spans(vec![
669                Span::styled("@user1:example.com", user_style("@user1:example.com")),
670                Span::from(" is typing...")
671            ])
672        );
673
674        // Two users typing.
675        info.set_typing(users2);
676        assert!(info.users_typing.is_some());
677        assert_eq!(
678            info.get_typing_spans(&settings),
679            Spans(vec![
680                Span::styled("@user1:example.com", user_style("@user1:example.com")),
681                Span::raw(" and "),
682                Span::styled("@user2:example.com", user_style("@user2:example.com")),
683                Span::raw(" are typing...")
684            ])
685        );
686
687        // Four users typing.
688        info.set_typing(users4);
689        assert!(info.users_typing.is_some());
690        assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
691
692        // Five users typing.
693        info.set_typing(users5);
694        assert!(info.users_typing.is_some());
695        assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
696
697        // Test that USER5 gets rendered using the configured color and name.
698        info.set_typing(vec![TEST_USER5.clone()]);
699        assert!(info.users_typing.is_some());
700        assert_eq!(
701            info.get_typing_spans(&settings),
702            Spans(vec![
703                Span::styled("USER 5", user_style_from_color(Color::Black)),
704                Span::from(" is typing...")
705            ])
706        );
707    }
708}