src/main.rs

974 lines · 30699 bytes

  1//! # iamb
  2//!
  3//! The iamb client loops over user input and commands, and turns them into actions, [some of
  4//! which][IambAction] are specific to iamb, and [some of which][Action] come from [modalkit]. When
  5//! adding new functionality, you will usually want to extend [IambAction] or one of its variants
  6//! (like [RoomAction][base::RoomAction]), and then add an appropriate [command][commands] or
  7//! [keybinding][keybindings].
  8//!
  9//! For more complicated changes, you may need to update [the async worker thread][worker], which
 10//! handles background Matrix tasks with [matrix-rust-sdk][matrix_sdk].
 11//!
 12//! Most rendering logic lives under the [windows] module, but [Matrix messages][message] have
 13//! their own module.
 14#![allow(clippy::manual_range_contains)]
 15#![allow(clippy::needless_return)]
 16#![allow(clippy::result_large_err)]
 17#![allow(clippy::bool_assert_comparison)]
 18use std::collections::VecDeque;
 19use std::convert::TryFrom;
 20use std::fmt::Display;
 21use std::fs::{create_dir_all, File};
 22use std::io::{stdout, BufWriter, Stdout, Write};
 23use std::ops::DerefMut;
 24use std::process;
 25use std::sync::atomic::{AtomicUsize, Ordering};
 26use std::sync::Arc;
 27use std::time::{Duration, Instant};
 28
 29use clap::Parser;
 30use matrix_sdk::crypto::encrypt_room_key_export;
 31use matrix_sdk::ruma::api::client::error::ErrorKind;
 32use matrix_sdk::ruma::OwnedUserId;
 33use modalkit::keybindings::InputBindings;
 34use rand::{distributions::Alphanumeric, Rng};
 35use temp_dir::TempDir;
 36use tokio::sync::Mutex as AsyncMutex;
 37use tracing_subscriber::FmtSubscriber;
 38
 39use modalkit::crossterm::{
 40    self,
 41    cursor::Show as CursorShow,
 42    event::{
 43        poll,
 44        read,
 45        DisableBracketedPaste,
 46        DisableFocusChange,
 47        EnableBracketedPaste,
 48        EnableFocusChange,
 49        Event,
 50        KeyEventKind,
 51    },
 52    execute,
 53    terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
 54};
 55
 56use ratatui::{
 57    backend::CrosstermBackend,
 58    layout::Rect,
 59    style::{Color, Style},
 60    text::Span,
 61    widgets::Paragraph,
 62    Terminal,
 63};
 64
 65mod base;
 66mod commands;
 67mod config;
 68mod keybindings;
 69mod message;
 70mod notifications;
 71mod preview;
 72mod sled_export;
 73mod util;
 74mod windows;
 75mod worker;
 76
 77#[cfg(test)]
 78mod tests;
 79
 80use crate::{
 81    base::{
 82        AsyncProgramStore,
 83        ChatStore,
 84        HomeserverAction,
 85        IambAction,
 86        IambError,
 87        IambId,
 88        IambInfo,
 89        IambResult,
 90        ProgramAction,
 91        ProgramContext,
 92        ProgramStore,
 93    },
 94    config::{ApplicationSettings, Iamb},
 95    windows::IambWindow,
 96    worker::{create_room, ClientWorker, LoginStyle, Requester},
 97};
 98
 99use modalkit::{
100    actions::{
101        Action,
102        Commandable,
103        Editable,
104        EditorAction,
105        InsertTextAction,
106        Jumpable,
107        Promptable,
108        Scrollable,
109        TabAction,
110        TabContainer,
111        TabCount,
112        WindowAction,
113        WindowContainer,
114    },
115    editing::{context::Resolve, key::KeyManager, store::Store},
116    errors::{EditError, UIError},
117    key::TerminalKey,
118    keybindings::{
119        dialog::{Pager, PromptYesNo},
120        BindingMachine,
121    },
122    prelude::*,
123    ui::FocusList,
124};
125
126use modalkit_ratatui::{
127    cmdbar::CommandBarState,
128    screen::{Screen, ScreenState, TabLayoutDescription},
129    windows::WindowLayoutDescription,
130    TerminalCursor,
131    TerminalExtOps,
132    Window,
133};
134
135fn config_tab_to_desc(
136    layout: config::WindowLayout,
137    store: &mut ProgramStore,
138) -> IambResult<WindowLayoutDescription<IambInfo>> {
139    let desc = match layout {
140        config::WindowLayout::Window { window } => {
141            let ChatStore { names, worker, .. } = &mut store.application;
142
143            let window = match window {
144                config::WindowPath::UserId(user_id) => {
145                    let name = user_id.to_string();
146                    let room_id = worker.join_room(name.clone())?;
147                    names.insert(name, room_id.clone());
148                    IambId::Room(room_id, None)
149                },
150                config::WindowPath::RoomId(room_id) => IambId::Room(room_id, None),
151                config::WindowPath::AliasId(alias) => {
152                    let name = alias.to_string();
153                    let room_id = worker.join_room(name.clone())?;
154                    names.insert(name, room_id.clone());
155                    IambId::Room(room_id, None)
156                },
157                config::WindowPath::Window(id) => id,
158            };
159
160            WindowLayoutDescription::Window { window, length: None }
161        },
162        config::WindowLayout::Split { split } => {
163            let children = split
164                .into_iter()
165                .map(|child| config_tab_to_desc(child, store))
166                .collect::<IambResult<Vec<_>>>()?;
167
168            WindowLayoutDescription::Split { children, length: None }
169        },
170    };
171
172    Ok(desc)
173}
174
175fn setup_screen(
176    settings: ApplicationSettings,
177    store: &mut ProgramStore,
178) -> IambResult<ScreenState<IambWindow, IambInfo>> {
179    let cmd = CommandBarState::new(store);
180    let dims = crossterm::terminal::size()?;
181    let area = Rect::new(0, 0, dims.0, dims.1);
182
183    match settings.layout {
184        config::Layout::Restore => {
185            if let Ok(layout) = std::fs::read(&settings.layout_json) {
186                let tabs: TabLayoutDescription<IambInfo> =
187                    serde_json::from_slice(&layout).map_err(IambError::from)?;
188                let tabs = tabs.to_layout(area.into(), store)?;
189
190                return Ok(ScreenState::from_list(tabs, cmd));
191            }
192        },
193        config::Layout::New => {},
194        config::Layout::Config { tabs } => {
195            let mut list = FocusList::default();
196
197            for tab in tabs.into_iter() {
198                let tab = config_tab_to_desc(tab, store)?;
199                let tab = tab.to_layout(area.into(), store)?;
200                list.push(tab);
201            }
202
203            return Ok(ScreenState::from_list(list, cmd));
204        },
205    }
206
207    let win = settings
208        .tunables
209        .default_room
210        .and_then(|room| IambWindow::find(room, store).ok())
211        .or_else(|| IambWindow::open(IambId::Welcome, store).ok())
212        .unwrap();
213
214    return Ok(ScreenState::new(win, cmd));
215}
216
217/// The main application state and event loop.
218struct Application {
219    /// Terminal backend.
220    terminal: Terminal<CrosstermBackend<Stdout>>,
221
222    /// State for the Matrix client, editing, etc.
223    store: AsyncProgramStore,
224
225    /// UI state (open tabs, command bar, etc.) to use when rendering.
226    screen: ScreenState<IambWindow, IambInfo>,
227
228    /// Handle to communicate synchronously with the Matrix worker task.
229    worker: Requester,
230
231    /// Mapped keybindings.
232    bindings: KeyManager<TerminalKey, ProgramAction, RepeatType>,
233
234    /// Pending actions to run.
235    actstack: VecDeque<(ProgramAction, ProgramContext)>,
236
237    /// Whether or not the terminal is currently focused.
238    focused: bool,
239
240    /// The tab layout before the last executed [TabAction].
241    last_layout: Option<TabLayoutDescription<IambInfo>>,
242
243    /// Whether we need to do a full redraw (e.g., after running a subprocess).
244    dirty: bool,
245}
246
247impl Application {
248    pub async fn new(
249        settings: ApplicationSettings,
250        store: AsyncProgramStore,
251    ) -> IambResult<Application> {
252        let mut stdout = stdout();
253        crossterm::terminal::enable_raw_mode()?;
254        crossterm::execute!(stdout, EnterAlternateScreen)?;
255        crossterm::execute!(stdout, EnableBracketedPaste)?;
256        crossterm::execute!(stdout, EnableFocusChange)?;
257
258        let title = format!("iamb ({})", settings.profile.user_id);
259        crossterm::execute!(stdout, SetTitle(title))?;
260
261        let backend = CrosstermBackend::new(stdout);
262        let terminal = Terminal::new(backend)?;
263
264        let mut bindings = crate::keybindings::setup_keybindings();
265        settings.setup(&mut bindings);
266        let bindings = KeyManager::new(bindings);
267
268        let mut locked = store.lock().await;
269        let screen = setup_screen(settings, locked.deref_mut())?;
270
271        let worker = locked.application.worker.clone();
272
273        drop(locked);
274
275        let actstack = VecDeque::new();
276
277        Ok(Application {
278            store,
279            worker,
280            terminal,
281            bindings,
282            actstack,
283            screen,
284            focused: true,
285            last_layout: None,
286            dirty: true,
287        })
288    }
289
290    fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> {
291        let bindings = &mut self.bindings;
292        let focused = self.focused;
293        let sstate = &mut self.screen;
294        let term = &mut self.terminal;
295
296        if store.application.ring_bell {
297            store.application.ring_bell = term.backend_mut().write_all(&[7]).is_err();
298        }
299
300        if full {
301            term.clear()?;
302        }
303
304        term.draw(|f| {
305            let area = f.size();
306
307            let modestr = bindings.show_mode();
308            let cursor = bindings.get_cursor_indicator();
309            let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize);
310
311            // Don't show terminal cursor when we show a dialog.
312            let hide_cursor = !dialogstr.is_empty();
313
314            store.application.draw_curr = Some(Instant::now());
315            let screen = Screen::new(store)
316                .show_dialog(dialogstr)
317                .show_mode(modestr)
318                .borders(true)
319                .focus(focused);
320            f.render_stateful_widget(screen, area, sstate);
321
322            if hide_cursor {
323                return;
324            }
325
326            if let Some((cx, cy)) = sstate.get_term_cursor() {
327                if let Some(c) = cursor {
328                    let style = Style::default().fg(Color::Green);
329                    let span = Span::styled(c.to_string(), style);
330                    let para = Paragraph::new(span);
331                    let inner = Rect::new(cx, cy, 1, 1);
332                    f.render_widget(para, inner)
333                }
334                f.set_cursor(cx, cy);
335            }
336        })?;
337
338        Ok(())
339    }
340
341    async fn step(&mut self) -> Result<TerminalKey, std::io::Error> {
342        loop {
343            self.redraw(self.dirty, self.store.clone().lock().await.deref_mut())?;
344            self.dirty = false;
345
346            if !poll(Duration::from_secs(1))? {
347                // Redraw in case there's new messages to show.
348                continue;
349            }
350
351            match read()? {
352                Event::Key(ke) => {
353                    if ke.kind == KeyEventKind::Release {
354                        continue;
355                    }
356
357                    return Ok(ke.into());
358                },
359                Event::Mouse(_) => {
360                    // Do nothing for now.
361                },
362                Event::FocusGained => {
363                    self.focused = true;
364                },
365                Event::FocusLost => {
366                    self.focused = false;
367                },
368                Event::Resize(_, _) => {
369                    // We'll redraw for the new size next time step() is called.
370                },
371                Event::Paste(s) => {
372                    let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
373                    let act = EditorAction::from(act);
374                    let ctx = ProgramContext::default();
375                    let mut store = self.store.lock().await;
376
377                    match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
378                        Ok(None) => {},
379                        Ok(Some(info)) => {
380                            drop(store);
381                            self.handle_info(info);
382                        },
383                        Err(e) => {
384                            self.screen.push_error(e);
385                        },
386                    }
387                },
388            }
389        }
390    }
391
392    fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
393        let mut acts = VecDeque::from(acts);
394        acts.append(&mut self.actstack);
395        self.actstack = acts;
396    }
397
398    fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
399        if let res @ Some(_) = self.actstack.pop_front() {
400            return res;
401        }
402
403        if keyskip {
404            return None;
405        } else {
406            return self.bindings.pop();
407        }
408    }
409
410    async fn action_run(
411        &mut self,
412        action: ProgramAction,
413        ctx: ProgramContext,
414        store: &mut ProgramStore,
415    ) -> IambResult<EditInfo> {
416        let info = match action {
417            // Do nothing.
418            Action::NoOp => None,
419
420            Action::Editor(act) => {
421                match self.screen.editor_command(&act, &ctx, store) {
422                    Ok(info) => info,
423                    Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
424                        // Switch to the right window.
425                        if let Some(winid) = content.to_window() {
426                            let open = OpenTarget::Application(winid);
427                            let open = WindowAction::Switch(open);
428                            let _ = self.screen.window_command(&open, &ctx, store)?;
429
430                            // Run command again.
431                            self.screen.editor_command(&act, &ctx, store)?
432                        } else {
433                            return Err(EditError::WrongBuffer(content).into());
434                        }
435                    },
436                    Err(err) => return Err(err.into()),
437                }
438            },
439
440            // Simple delegations.
441            Action::Application(act) => self.iamb_run(act, ctx, store).await?,
442            Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
443            Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
444            Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
445            Action::ShowInfoMessage(info) => Some(info),
446            Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
447
448            Action::Jump(l, dir, count) => {
449                let count = ctx.resolve(&count);
450                let _ = self.screen.jump(l, dir, count, &ctx)?;
451
452                None
453            },
454            Action::Suspend => {
455                self.terminal.program_suspend()?;
456
457                None
458            },
459
460            // UI actions.
461            Action::Tab(cmd) => {
462                if let TabAction::Close(_, _) = &cmd {
463                    self.last_layout = self.screen.as_description().into();
464                }
465
466                self.screen.tab_command(&cmd, &ctx, store)?
467            },
468            Action::RedrawScreen => {
469                self.screen.clear_message();
470                self.redraw(true, store)?;
471
472                None
473            },
474
475            // Actions that create more Actions.
476            Action::Prompt(act) => {
477                let acts = self.screen.prompt(&act, &ctx, store)?;
478                self.action_prepend(acts);
479
480                None
481            },
482            Action::Command(act) => {
483                let acts = store.application.cmds.command(&act, &ctx)?;
484                self.action_prepend(acts);
485
486                None
487            },
488            Action::Repeat(rt) => {
489                self.bindings.repeat(rt, Some(ctx));
490
491                None
492            },
493
494            // Unimplemented.
495            Action::KeywordLookup => {
496                // XXX: implement
497                None
498            },
499
500            _ => {
501                // XXX: log unhandled actions? print message?
502                None
503            },
504        };
505
506        return Ok(info);
507    }
508
509    async fn iamb_run(
510        &mut self,
511        action: IambAction,
512        ctx: ProgramContext,
513        store: &mut ProgramStore,
514    ) -> IambResult<EditInfo> {
515        if action.scribbles() {
516            self.dirty = true;
517        }
518
519        let info = match action {
520            IambAction::ToggleScrollbackFocus => {
521                self.screen.current_window_mut()?.focus_toggle();
522
523                None
524            },
525
526            IambAction::Homeserver(act) => {
527                let acts = self.homeserver_command(act, ctx, store).await?;
528                self.action_prepend(acts);
529
530                None
531            },
532            IambAction::Message(act) => {
533                self.screen.current_window_mut()?.message_command(act, ctx, store).await?
534            },
535            IambAction::Room(act) => {
536                let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
537                self.action_prepend(acts);
538
539                None
540            },
541            IambAction::Send(act) => {
542                self.screen.current_window_mut()?.send_command(act, ctx, store).await?
543            },
544
545            IambAction::OpenLink(url) => {
546                tokio::task::spawn_blocking(move || {
547                    return open::that(url);
548                });
549
550                None
551            },
552
553            IambAction::Verify(act, user_dev) => {
554                if let Some(sas) = store.application.verifications.get(&user_dev) {
555                    self.worker.verify(act, sas.clone())?
556                } else {
557                    return Err(IambError::InvalidVerificationId(user_dev).into());
558                }
559            },
560            IambAction::VerifyRequest(user_id) => {
561                if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
562                    self.worker.verify_request(user_id)?
563                } else {
564                    return Err(IambError::InvalidUserId(user_id).into());
565                }
566            },
567        };
568
569        Ok(info)
570    }
571
572    async fn homeserver_command(
573        &mut self,
574        action: HomeserverAction,
575        ctx: ProgramContext,
576        store: &mut ProgramStore,
577    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
578        match action {
579            HomeserverAction::CreateRoom(alias, vis, flags) => {
580                let client = &store.application.worker.client;
581                let room_id = create_room(client, alias, vis, flags).await?;
582                let room = IambId::Room(room_id, None);
583                let target = OpenTarget::Application(room);
584                let action = WindowAction::Switch(target);
585
586                Ok(vec![(action.into(), ctx)])
587            },
588            HomeserverAction::Logout(user, true) => {
589                self.worker.logout(user)?;
590                let flags = CloseFlags::QUIT | CloseFlags::FORCE;
591                let act = TabAction::Close(TabTarget::All, flags);
592
593                Ok(vec![(act.into(), ctx)])
594            },
595            HomeserverAction::Logout(user, false) => {
596                let msg = "Would you like to logout?";
597                let act = IambAction::from(HomeserverAction::Logout(user, true));
598                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
599                let prompt = Box::new(prompt);
600
601                Err(UIError::NeedConfirm(prompt))
602            },
603        }
604    }
605
606    fn handle_info(&mut self, info: InfoMessage) {
607        match info {
608            InfoMessage::Message(info) => {
609                self.screen.push_info(info);
610            },
611            InfoMessage::Pager(text) => {
612                let pager = Box::new(Pager::new(text, vec![]));
613                self.bindings.run_dialog(pager);
614            },
615        }
616    }
617
618    pub async fn run(&mut self) -> Result<(), std::io::Error> {
619        self.terminal.clear()?;
620
621        let store = self.store.clone();
622
623        while self.screen.tabs() != 0 {
624            let key = self.step().await?;
625
626            self.bindings.input_key(key);
627
628            let mut locked = store.lock().await;
629            let mut keyskip = false;
630
631            while let Some((action, ctx)) = self.action_pop(keyskip) {
632                match self.action_run(action, ctx, locked.deref_mut()).await {
633                    Ok(None) => {
634                        // Continue processing.
635                        continue;
636                    },
637                    Ok(Some(info)) => {
638                        self.handle_info(info);
639
640                        // Continue processing; we'll redraw later.
641                        continue;
642                    },
643                    Err(
644                        UIError::NeedConfirm(dialog) |
645                        UIError::EditingFailure(EditError::NeedConfirm(dialog)),
646                    ) => {
647                        self.bindings.run_dialog(dialog);
648                        continue;
649                    },
650                    Err(e) => {
651                        self.screen.push_error(e);
652
653                        // Skip processing any more keypress Actions until the next key.
654                        keyskip = true;
655                        continue;
656                    },
657                }
658            }
659        }
660
661        if let Some(ref layout) = self.last_layout {
662            let locked = self.store.lock().await;
663            let path = locked.application.settings.layout_json.as_path();
664            path.parent().map(create_dir_all).transpose()?;
665
666            let file = File::create(path)?;
667            let writer = BufWriter::new(file);
668
669            if let Err(e) = serde_json::to_writer(writer, layout) {
670                tracing::error!("Failed to save window layout while exiting: {}", e);
671            }
672        }
673
674        crossterm::terminal::disable_raw_mode()?;
675        execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
676        self.terminal.show_cursor()?;
677
678        return Ok(());
679    }
680}
681
682fn gen_passphrase() -> String {
683    rand::thread_rng()
684        .sample_iter(&Alphanumeric)
685        .take(20)
686        .map(char::from)
687        .collect()
688}
689
690fn read_response(question: &str) -> String {
691    println!("{question}");
692    let mut input = String::new();
693    let _ = std::io::stdin().read_line(&mut input);
694    input
695}
696
697fn read_yesno(question: &str) -> Option<char> {
698    read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
699}
700
701async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
702    if settings.session_json.is_file() {
703        let session = settings.read_session(&settings.session_json)?;
704        worker.login(LoginStyle::SessionRestore(session.into()))?;
705
706        return Ok(());
707    }
708
709    if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
710        let session = settings.read_session(&settings.session_json_old)?;
711        worker.login(LoginStyle::SessionRestore(session.into()))?;
712
713        return Ok(());
714    }
715
716    loop {
717        let login_style =
718            match read_response("Please select login type: [p]assword / [s]ingle sign on")
719                .chars()
720                .next()
721                .map(|c| c.to_ascii_lowercase())
722            {
723                None | Some('p') => {
724                    let password = rpassword::prompt_password("Password: ")?;
725                    LoginStyle::Password(password)
726                },
727                Some('s') => LoginStyle::SingleSignOn,
728                Some(_) => {
729                    println!("Failed to login. Please enter 'p' or 's'");
730                    continue;
731                },
732            };
733
734        match worker.login(login_style) {
735            Ok(info) => {
736                if let Some(msg) = info {
737                    println!("{msg}");
738                }
739
740                break;
741            },
742            Err(err) => {
743                println!("Failed to login: {err}");
744                continue;
745            },
746        }
747    }
748
749    Ok(())
750}
751
752fn print_exit<T: Display, N>(v: T) -> N {
753    eprintln!("{v}");
754    process::exit(2);
755}
756
757// We can't access the OlmMachine directly, so write the keys to a temporary
758// file first, and then import them later.
759async fn check_import_keys(
760    settings: &ApplicationSettings,
761) -> IambResult<Option<(temp_dir::TempDir, String)>> {
762    let do_import = settings.sled_dir.is_dir() && !settings.sqlite_dir.is_dir();
763
764    if !do_import {
765        return Ok(None);
766    }
767
768    let question = format!(
769        "Found old sled store in {}. Would you like to export room keys from it? [y]es/[n]o",
770        settings.sled_dir.display()
771    );
772
773    loop {
774        match read_yesno(&question) {
775            Some('y') => {
776                break;
777            },
778            Some('n') => {
779                return Ok(None);
780            },
781            Some(_) | None => {
782                continue;
783            },
784        }
785    }
786
787    let keys = sled_export::export_room_keys(&settings.sled_dir).await?;
788    let passphrase = gen_passphrase();
789
790    println!("* Encrypting {} room keys with the passphrase {passphrase:?}...", keys.len());
791
792    let encrypted = match encrypt_room_key_export(&keys, &passphrase, 500000) {
793        Ok(encrypted) => encrypted,
794        Err(e) => {
795            format!("* Failed to encrypt room keys during export: {e}");
796            process::exit(2);
797        },
798    };
799
800    let tmpdir = TempDir::new()?;
801    let exported = tmpdir.child("keys");
802
803    println!("* Writing encrypted room keys to {}...", exported.display());
804    tokio::fs::write(&exported, &encrypted).await?;
805
806    Ok(Some((tmpdir, passphrase)))
807}
808
809async fn login_upgrade(
810    keydir: TempDir,
811    passphrase: String,
812    worker: &Requester,
813    settings: &ApplicationSettings,
814    store: &AsyncProgramStore,
815) -> IambResult<()> {
816    println!(
817        "Please log in for {} to import the room keys into a new session",
818        settings.profile.user_id
819    );
820
821    login(worker, settings).await?;
822
823    println!("* Importing room keys...");
824
825    let exported = keydir.child("keys");
826    let imported = worker.client.encryption().import_room_keys(exported, &passphrase).await;
827
828    match imported {
829        Ok(res) => {
830            println!(
831                "* Successfully imported {} out of {} keys",
832                res.imported_count, res.total_count
833            );
834            let _ = keydir.cleanup();
835        },
836        Err(e) => {
837            println!(
838                "Failed to import room keys from {}/keys: {e}\n\n\
839                They have been encrypted with the passphrase {passphrase:?}.\
840                Please save them and try importing them manually instead\n",
841                keydir.path().display()
842            );
843
844            loop {
845                match read_yesno("Would you like to continue logging in? [y]es/[n]o") {
846                    Some('y') => break,
847                    Some('n') => print_exit("* Exiting..."),
848                    Some(_) | None => continue,
849                }
850            }
851        },
852    }
853
854    println!("* Syncing...");
855    worker::do_first_sync(&worker.client, store)
856        .await
857        .map_err(IambError::from)?;
858
859    Ok(())
860}
861
862async fn login_normal(
863    worker: &Requester,
864    settings: &ApplicationSettings,
865    store: &AsyncProgramStore,
866) -> IambResult<()> {
867    println!("* Logging in for {}...", settings.profile.user_id);
868    login(worker, settings).await?;
869    worker::do_first_sync(&worker.client, store)
870        .await
871        .map_err(IambError::from)?;
872    Ok(())
873}
874
875async fn run(settings: ApplicationSettings) -> IambResult<()> {
876    // Get old keys the first time we run w/ the upgraded SDK.
877    let import_keys = check_import_keys(&settings).await?;
878
879    // Set up client state.
880    create_dir_all(settings.sqlite_dir.as_path())?;
881    let client = worker::create_client(&settings).await;
882
883    // Set up the async worker thread and global store.
884    let worker = ClientWorker::spawn(client.clone(), settings.clone()).await;
885    let store = ChatStore::new(worker.clone(), settings.clone());
886    let store = Store::new(store);
887    let store = Arc::new(AsyncMutex::new(store));
888    worker.init(store.clone());
889
890    let res = if let Some((keydir, pass)) = import_keys {
891        login_upgrade(keydir, pass, &worker, &settings, &store).await
892    } else {
893        login_normal(&worker, &settings, &store).await
894    };
895
896    match res {
897        Err(UIError::Application(IambError::Matrix(e))) => {
898            if let Some(ErrorKind::UnknownToken { .. }) = e.client_api_error_kind() {
899                print_exit("Server did not recognize our API token; did you log out from this session elsewhere?")
900            } else {
901                print_exit(e)
902            }
903        },
904        Err(e) => print_exit(e),
905        Ok(()) => (),
906    }
907
908    fn restore_tty() {
909        let _ = crossterm::terminal::disable_raw_mode();
910        let _ = crossterm::execute!(stdout(), DisableBracketedPaste);
911        let _ = crossterm::execute!(stdout(), DisableFocusChange);
912        let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
913        let _ = crossterm::execute!(stdout(), CursorShow);
914    }
915
916    // Make sure panics clean up the terminal properly.
917    let orig_hook = std::panic::take_hook();
918    std::panic::set_hook(Box::new(move |panic_info| {
919        restore_tty();
920        orig_hook(panic_info);
921        process::exit(1);
922    }));
923
924    let mut application = Application::new(settings, store).await?;
925
926    // We can now run the application.
927    application.run().await?;
928    restore_tty();
929
930    Ok(())
931}
932
933fn main() -> IambResult<()> {
934    // Parse command-line flags.
935    let iamb = Iamb::parse();
936
937    // Load configuration and set up the Matrix SDK.
938    let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
939
940    // Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
941    #[cfg(unix)]
942    unsafe {
943        libc::umask(0o077);
944    };
945
946    // Set up the tracing subscriber so we can log client messages.
947    let log_prefix = format!("iamb-log-{}", settings.profile_name);
948    let log_dir = settings.dirs.logs.as_path();
949
950    let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
951    let (appender, guard) = tracing_appender::non_blocking(appender);
952
953    let subscriber = FmtSubscriber::builder()
954        .with_writer(appender)
955        .with_max_level(settings.tunables.log_level)
956        .finish();
957    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
958
959    let rt = tokio::runtime::Builder::new_multi_thread()
960        .enable_all()
961        .worker_threads(2)
962        .thread_name_fn(|| {
963            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
964            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
965            format!("iamb-worker-{id}")
966        })
967        .build()
968        .unwrap();
969
970    rt.block_on(async move { run(settings).await })?;
971
972    drop(guard);
973    process::exit(0);
974}