src/base.rs

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