src/base.rs

328 lines · 9261 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    ruma::{OwnedRoomId, RoomId},
 12};
 13
 14use modalkit::{
 15    editing::{
 16        action::{Action, UIError, UIResult},
 17        application::{
 18            ApplicationAction,
 19            ApplicationContentId,
 20            ApplicationError,
 21            ApplicationInfo,
 22            ApplicationStore,
 23            ApplicationWindowId,
 24        },
 25        context::EditContext,
 26        store::Store,
 27    },
 28    env::vim::{
 29        command::{VimCommand, VimCommandMachine},
 30        keybindings::VimMachine,
 31        VimContext,
 32    },
 33    input::bindings::SequenceStatus,
 34    input::key::TerminalKey,
 35};
 36
 37use crate::{
 38    message::{Message, Messages},
 39    worker::Requester,
 40    ApplicationSettings,
 41};
 42
 43const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(3);
 44
 45#[derive(Clone, Debug, Eq, PartialEq)]
 46pub enum IambInfo {}
 47
 48#[derive(Clone, Debug, Eq, PartialEq)]
 49pub enum VerifyAction {
 50    Accept,
 51    Cancel,
 52    Confirm,
 53    Mismatch,
 54}
 55
 56#[derive(Clone, Debug, Eq, PartialEq)]
 57pub enum IambAction {
 58    Verify(VerifyAction, String),
 59    VerifyRequest(String),
 60    SendMessage(OwnedRoomId, String),
 61    ToggleScrollbackFocus,
 62}
 63
 64impl ApplicationAction for IambAction {
 65    fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
 66        match self {
 67            IambAction::SendMessage(..) => SequenceStatus::Break,
 68            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
 69            IambAction::Verify(..) => SequenceStatus::Break,
 70            IambAction::VerifyRequest(..) => SequenceStatus::Break,
 71        }
 72    }
 73
 74    fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
 75        match self {
 76            IambAction::SendMessage(..) => SequenceStatus::Atom,
 77            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
 78            IambAction::Verify(..) => SequenceStatus::Atom,
 79            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
 80        }
 81    }
 82
 83    fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
 84        match self {
 85            IambAction::SendMessage(..) => SequenceStatus::Ignore,
 86            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
 87            IambAction::Verify(..) => SequenceStatus::Ignore,
 88            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
 89        }
 90    }
 91
 92    fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
 93        match self {
 94            IambAction::SendMessage(..) => false,
 95            IambAction::ToggleScrollbackFocus => false,
 96            IambAction::Verify(..) => false,
 97            IambAction::VerifyRequest(..) => false,
 98        }
 99    }
100}
101
102impl From<IambAction> for ProgramAction {
103    fn from(act: IambAction) -> Self {
104        Action::Application(act)
105    }
106}
107
108pub type ProgramAction = Action<IambInfo>;
109pub type ProgramContext = VimContext<IambInfo>;
110pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
111pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
112pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
113pub type ProgramStore = Store<IambInfo>;
114pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
115
116pub type IambResult<T> = UIResult<T, IambInfo>;
117
118#[derive(thiserror::Error, Debug)]
119pub enum IambError {
120    #[error("Unknown room identifier: {0}")]
121    InvalidUserId(String),
122
123    #[error("Invalid verification user/device pair: {0}")]
124    InvalidVerificationId(String),
125
126    #[error("Cryptographic storage error: {0}")]
127    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
128
129    #[error("HTTP client error: {0}")]
130    Http(#[from] matrix_sdk::HttpError),
131
132    #[error("Matrix client error: {0}")]
133    Matrix(#[from] matrix_sdk::Error),
134
135    #[error("Matrix client storage error: {0}")]
136    Store(#[from] matrix_sdk::StoreError),
137
138    #[error("Serialization/deserialization error: {0}")]
139    Serde(#[from] serde_json::Error),
140
141    #[error("Unknown room identifier: {0}")]
142    UnknownRoom(OwnedRoomId),
143
144    #[error("Verification request error: {0}")]
145    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
146}
147
148impl From<IambError> for UIError<IambInfo> {
149    fn from(err: IambError) -> Self {
150        UIError::Application(err)
151    }
152}
153
154impl ApplicationError for IambError {}
155
156#[derive(Default)]
157pub enum RoomFetchStatus {
158    Done,
159    HaveMore(String),
160    #[default]
161    NotStarted,
162}
163
164#[derive(Default)]
165pub struct RoomInfo {
166    pub name: Option<String>,
167    pub messages: Messages,
168    pub fetch_id: RoomFetchStatus,
169    pub fetch_last: Option<Instant>,
170}
171
172impl RoomInfo {
173    fn recently_fetched(&self) -> bool {
174        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
175    }
176}
177
178pub struct ChatStore {
179    pub worker: Requester,
180    pub rooms: HashMap<OwnedRoomId, RoomInfo>,
181    pub names: HashMap<String, OwnedRoomId>,
182    pub verifications: HashMap<String, SasVerification>,
183    pub settings: ApplicationSettings,
184    pub need_load: HashSet<OwnedRoomId>,
185}
186
187impl ChatStore {
188    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
189        ChatStore {
190            worker,
191            settings,
192
193            names: Default::default(),
194            rooms: Default::default(),
195            verifications: Default::default(),
196            need_load: Default::default(),
197        }
198    }
199
200    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
201        self.need_load.insert(room_id);
202    }
203
204    pub fn load_older(&mut self, limit: u32) {
205        let ChatStore { need_load, rooms, worker, .. } = self;
206
207        for room_id in std::mem::take(need_load).into_iter() {
208            let info = rooms.entry(room_id.clone()).or_default();
209
210            if info.recently_fetched() {
211                need_load.insert(room_id);
212                continue;
213            } else {
214                info.fetch_last = Instant::now().into();
215            }
216
217            let fetch_id = match &info.fetch_id {
218                RoomFetchStatus::Done => continue,
219                RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
220                RoomFetchStatus::NotStarted => None,
221            };
222
223            let res = worker.load_older(room_id.clone(), fetch_id, limit);
224
225            match res {
226                Ok((fetch_id, msgs)) => {
227                    for msg in msgs.into_iter() {
228                        let key = (msg.origin_server_ts().into(), msg.event_id().to_owned());
229
230                        info.messages.insert(key, Message::from(msg));
231                    }
232
233                    info.fetch_id =
234                        fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
235                },
236                Err(e) => {
237                    warn!(
238                        room_id = room_id.as_str(),
239                        err = e.to_string(),
240                        "Failed to load older messages"
241                    );
242
243                    // Wait and try again.
244                    need_load.insert(room_id);
245                },
246            }
247        }
248    }
249
250    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
251        self.rooms.entry(room_id).or_default()
252    }
253
254    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
255        self.rooms.entry(room_id.to_owned()).or_default().name = name.to_string().into();
256    }
257
258    pub fn insert_sas(&mut self, sas: SasVerification) {
259        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
260
261        self.verifications.insert(key, sas);
262    }
263}
264
265impl ApplicationStore for ChatStore {}
266
267#[derive(Clone, Debug, Eq, Hash, PartialEq)]
268pub enum IambId {
269    Room(OwnedRoomId),
270    DirectList,
271    RoomList,
272    SpaceList,
273    VerifyList,
274    Welcome,
275}
276
277impl ApplicationWindowId for IambId {}
278
279#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
280pub enum RoomFocus {
281    Scrollback,
282    MessageBar,
283}
284
285impl RoomFocus {
286    pub fn is_scrollback(&self) -> bool {
287        matches!(self, RoomFocus::Scrollback)
288    }
289
290    pub fn is_msgbar(&self) -> bool {
291        matches!(self, RoomFocus::MessageBar)
292    }
293}
294
295#[derive(Clone, Debug, Eq, Hash, PartialEq)]
296pub enum IambBufferId {
297    Command,
298    Room(OwnedRoomId, RoomFocus),
299    DirectList,
300    RoomList,
301    SpaceList,
302    VerifyList,
303    Welcome,
304}
305
306impl IambBufferId {
307    pub fn to_window(&self) -> Option<IambId> {
308        match self {
309            IambBufferId::Command => None,
310            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
311            IambBufferId::DirectList => Some(IambId::DirectList),
312            IambBufferId::RoomList => Some(IambId::RoomList),
313            IambBufferId::SpaceList => Some(IambId::SpaceList),
314            IambBufferId::VerifyList => Some(IambId::VerifyList),
315            IambBufferId::Welcome => Some(IambId::Welcome),
316        }
317    }
318}
319
320impl ApplicationContentId for IambBufferId {}
321
322impl ApplicationInfo for IambInfo {
323    type Error = IambError;
324    type Store = ChatStore;
325    type Action = IambAction;
326    type WindowId = IambId;
327    type ContentId = IambBufferId;
328}