src/config.rs

701 lines · 22246 bytes

  1use std::borrow::Cow;
  2use std::collections::hash_map::DefaultHasher;
  3use std::collections::HashMap;
  4use std::fmt;
  5use std::fs::File;
  6use std::hash::{Hash, Hasher};
  7use std::io::BufReader;
  8use std::path::{Path, PathBuf};
  9use std::process;
 10
 11use clap::Parser;
 12use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
 13use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
 14use tracing::Level;
 15use url::Url;
 16
 17use modalkit::tui::{
 18    style::{Color, Modifier as StyleModifier, Style},
 19    text::Span,
 20};
 21
 22use super::base::IambId;
 23
 24macro_rules! usage {
 25    ( $($args: tt)* ) => {
 26        println!($($args)*);
 27        process::exit(2);
 28    }
 29}
 30
 31const DEFAULT_REQ_TIMEOUT: u64 = 120;
 32
 33const COLORS: [Color; 13] = [
 34    Color::Blue,
 35    Color::Cyan,
 36    Color::Green,
 37    Color::LightBlue,
 38    Color::LightGreen,
 39    Color::LightCyan,
 40    Color::LightMagenta,
 41    Color::LightRed,
 42    Color::LightYellow,
 43    Color::Magenta,
 44    Color::Red,
 45    Color::Reset,
 46    Color::Yellow,
 47];
 48
 49pub fn user_color(user: &str) -> Color {
 50    let mut hasher = DefaultHasher::new();
 51    user.hash(&mut hasher);
 52    let color = hasher.finish() as usize % COLORS.len();
 53
 54    COLORS[color]
 55}
 56
 57pub fn user_style_from_color(color: Color) -> Style {
 58    Style::default().fg(color).add_modifier(StyleModifier::BOLD)
 59}
 60
 61fn is_profile_char(c: char) -> bool {
 62    c.is_ascii_alphanumeric() || c == '.' || c == '-'
 63}
 64
 65fn validate_profile_name(name: &str) -> bool {
 66    if name.is_empty() {
 67        return false;
 68    }
 69
 70    let mut chars = name.chars();
 71
 72    if !chars.next().map_or(false, |c| c.is_ascii_alphanumeric()) {
 73        return false;
 74    }
 75
 76    name.chars().all(is_profile_char)
 77}
 78
 79fn validate_profile_names(names: &HashMap<String, ProfileConfig>) {
 80    for name in names.keys() {
 81        if validate_profile_name(name.as_str()) {
 82            continue;
 83        }
 84
 85        usage!(
 86            "{:?} is not a valid profile name.\n\n\
 87            Profile names can only contain the characters \
 88            a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.",
 89            name
 90        );
 91    }
 92}
 93
 94const VERSION: &str = match option_env!("VERGEN_GIT_SHA") {
 95    None => env!("CARGO_PKG_VERSION"),
 96    Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"),
 97};
 98
 99#[derive(Parser)]
100#[clap(version = VERSION, about, long_about = None)]
101#[clap(propagate_version = true)]
102pub struct Iamb {
103    #[clap(short = 'P', long, value_parser)]
104    pub profile: Option<String>,
105
106    #[clap(short = 'C', long, value_parser)]
107    pub config_directory: Option<PathBuf>,
108}
109
110#[derive(thiserror::Error, Debug)]
111pub enum ConfigError {
112    #[error("Error reading configuration file: {0}")]
113    IO(#[from] std::io::Error),
114
115    #[error("Error loading configuration file: {0}")]
116    Invalid(#[from] serde_json::Error),
117}
118
119#[derive(Clone, Debug, Eq, PartialEq)]
120pub struct LogLevel(pub Level);
121pub struct LogLevelVisitor;
122
123impl From<LogLevel> for Level {
124    fn from(level: LogLevel) -> Level {
125        level.0
126    }
127}
128
129impl<'de> Visitor<'de> for LogLevelVisitor {
130    type Value = LogLevel;
131
132    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
133        formatter.write_str("a valid log level (e.g. \"warn\" or \"debug\")")
134    }
135
136    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
137    where
138        E: SerdeError,
139    {
140        match value {
141            "info" => Ok(LogLevel(Level::INFO)),
142            "debug" => Ok(LogLevel(Level::DEBUG)),
143            "warn" => Ok(LogLevel(Level::WARN)),
144            "error" => Ok(LogLevel(Level::ERROR)),
145            "trace" => Ok(LogLevel(Level::TRACE)),
146            _ => Err(E::custom("Could not parse log level")),
147        }
148    }
149}
150
151impl<'de> Deserialize<'de> for LogLevel {
152    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
153    where
154        D: Deserializer<'de>,
155    {
156        deserializer.deserialize_str(LogLevelVisitor)
157    }
158}
159
160#[derive(Clone, Debug, Eq, PartialEq)]
161pub struct UserColor(pub Color);
162pub struct UserColorVisitor;
163
164impl<'de> Visitor<'de> for UserColorVisitor {
165    type Value = UserColor;
166
167    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
168        formatter.write_str("a valid color")
169    }
170
171    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
172    where
173        E: SerdeError,
174    {
175        match value {
176            "none" => Ok(UserColor(Color::Reset)),
177            "red" => Ok(UserColor(Color::Red)),
178            "black" => Ok(UserColor(Color::Black)),
179            "green" => Ok(UserColor(Color::Green)),
180            "yellow" => Ok(UserColor(Color::Yellow)),
181            "blue" => Ok(UserColor(Color::Blue)),
182            "magenta" => Ok(UserColor(Color::Magenta)),
183            "cyan" => Ok(UserColor(Color::Cyan)),
184            "gray" => Ok(UserColor(Color::Gray)),
185            "dark-gray" => Ok(UserColor(Color::DarkGray)),
186            "light-red" => Ok(UserColor(Color::LightRed)),
187            "light-green" => Ok(UserColor(Color::LightGreen)),
188            "light-yellow" => Ok(UserColor(Color::LightYellow)),
189            "light-blue" => Ok(UserColor(Color::LightBlue)),
190            "light-magenta" => Ok(UserColor(Color::LightMagenta)),
191            "light-cyan" => Ok(UserColor(Color::LightCyan)),
192            "white" => Ok(UserColor(Color::White)),
193            _ => Err(E::custom("Could not parse color")),
194        }
195    }
196}
197
198impl<'de> Deserialize<'de> for UserColor {
199    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
200    where
201        D: Deserializer<'de>,
202    {
203        deserializer.deserialize_str(UserColorVisitor)
204    }
205}
206
207#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
208pub struct UserDisplayTunables {
209    pub color: Option<UserColor>,
210    pub name: Option<String>,
211}
212
213pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
214
215fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> {
216    match (a, b) {
217        (Some(a), None) => Some(a),
218        (None, Some(b)) => Some(b),
219        (Some(mut a), Some(b)) => {
220            for (k, v) in b {
221                a.insert(k, v);
222            }
223
224            Some(a)
225        },
226        (None, None) => None,
227    }
228}
229
230#[derive(Clone)]
231pub struct TunableValues {
232    pub log_level: Level,
233    pub reaction_display: bool,
234    pub reaction_shortcode_display: bool,
235    pub read_receipt_send: bool,
236    pub read_receipt_display: bool,
237    pub request_timeout: u64,
238    pub typing_notice_send: bool,
239    pub typing_notice_display: bool,
240    pub users: UserOverrides,
241    pub default_room: Option<String>,
242    pub open_command: Option<Vec<String>>,
243}
244
245#[derive(Clone, Default, Deserialize)]
246pub struct Tunables {
247    pub log_level: Option<LogLevel>,
248    pub reaction_display: Option<bool>,
249    pub reaction_shortcode_display: Option<bool>,
250    pub read_receipt_send: Option<bool>,
251    pub read_receipt_display: Option<bool>,
252    pub request_timeout: Option<u64>,
253    pub typing_notice_send: Option<bool>,
254    pub typing_notice_display: Option<bool>,
255    pub users: Option<UserOverrides>,
256    pub default_room: Option<String>,
257    pub open_command: Option<Vec<String>>,
258}
259
260impl Tunables {
261    fn merge(self, other: Self) -> Self {
262        Tunables {
263            log_level: self.log_level.or(other.log_level),
264            reaction_display: self.reaction_display.or(other.reaction_display),
265            reaction_shortcode_display: self
266                .reaction_shortcode_display
267                .or(other.reaction_shortcode_display),
268            read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
269            read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
270            request_timeout: self.request_timeout.or(other.request_timeout),
271            typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
272            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
273            users: merge_users(self.users, other.users),
274            default_room: self.default_room.or(other.default_room),
275            open_command: self.open_command.or(other.open_command),
276        }
277    }
278
279    fn values(self) -> TunableValues {
280        TunableValues {
281            log_level: self.log_level.map(Level::from).unwrap_or(Level::INFO),
282            reaction_display: self.reaction_display.unwrap_or(true),
283            reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
284            read_receipt_send: self.read_receipt_send.unwrap_or(true),
285            read_receipt_display: self.read_receipt_display.unwrap_or(true),
286            request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
287            typing_notice_send: self.typing_notice_send.unwrap_or(true),
288            typing_notice_display: self.typing_notice_display.unwrap_or(true),
289            users: self.users.unwrap_or_default(),
290            default_room: self.default_room,
291            open_command: self.open_command,
292        }
293    }
294}
295
296#[derive(Clone)]
297pub struct DirectoryValues {
298    pub cache: PathBuf,
299    pub logs: PathBuf,
300    pub downloads: PathBuf,
301}
302
303#[derive(Clone, Default, Deserialize)]
304pub struct Directories {
305    pub cache: Option<PathBuf>,
306    pub logs: Option<PathBuf>,
307    pub downloads: Option<PathBuf>,
308}
309
310impl Directories {
311    fn merge(self, other: Self) -> Self {
312        Directories {
313            cache: self.cache.or(other.cache),
314            logs: self.logs.or(other.logs),
315            downloads: self.downloads.or(other.downloads),
316        }
317    }
318
319    fn values(self) -> DirectoryValues {
320        let cache = self
321            .cache
322            .or_else(|| {
323                let mut dir = dirs::cache_dir()?;
324                dir.push("iamb");
325                dir.into()
326            })
327            .expect("no dirs.cache value configured!");
328
329        let logs = self.logs.unwrap_or_else(|| {
330            let mut dir = cache.clone();
331            dir.push("logs");
332            dir
333        });
334
335        let downloads = self
336            .downloads
337            .or_else(dirs::download_dir)
338            .expect("no dirs.downloads value configured!");
339
340        DirectoryValues { cache, logs, downloads }
341    }
342}
343
344#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
345#[serde(untagged)]
346pub enum WindowPath {
347    AliasId(OwnedRoomAliasId),
348    RoomId(OwnedRoomId),
349    UserId(OwnedUserId),
350    Window(IambId),
351}
352
353#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
354#[serde(untagged, deny_unknown_fields)]
355pub enum WindowLayout {
356    Window { window: WindowPath },
357    Split { split: Vec<WindowLayout> },
358}
359
360#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
361#[serde(rename_all = "lowercase", tag = "style")]
362pub enum Layout {
363    /// Restore the layout from the previous session.
364    #[default]
365    Restore,
366
367    /// Open a single window using the `default_room` value.
368    New,
369
370    /// Open the window layouts described under `tabs`.
371    Config { tabs: Vec<WindowLayout> },
372}
373
374#[derive(Clone, Deserialize)]
375pub struct ProfileConfig {
376    pub user_id: OwnedUserId,
377    pub url: Url,
378    pub settings: Option<Tunables>,
379    pub dirs: Option<Directories>,
380    pub layout: Option<Layout>,
381}
382
383#[derive(Clone, Deserialize)]
384pub struct IambConfig {
385    pub profiles: HashMap<String, ProfileConfig>,
386    pub default_profile: Option<String>,
387    pub settings: Option<Tunables>,
388    pub dirs: Option<Directories>,
389    pub layout: Option<Layout>,
390}
391
392impl IambConfig {
393    pub fn load(config_json: &Path) -> Result<Self, ConfigError> {
394        if !config_json.is_file() {
395            usage!(
396                "Please create a configuration file at {}\n\n\
397                For more information try '--help'",
398                config_json.display(),
399            );
400        }
401
402        let file = File::open(config_json)?;
403        let reader = BufReader::new(file);
404        let config = serde_json::from_reader(reader)?;
405
406        Ok(config)
407    }
408}
409
410#[derive(Clone)]
411pub struct ApplicationSettings {
412    pub matrix_dir: PathBuf,
413    pub layout_json: PathBuf,
414    pub session_json: PathBuf,
415    pub profile_name: String,
416    pub profile: ProfileConfig,
417    pub tunables: TunableValues,
418    pub dirs: DirectoryValues,
419    pub layout: Layout,
420}
421
422impl ApplicationSettings {
423    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
424        let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
425            usage!(
426                "No user configuration directory found;\
427                please specify one via -C.\n\n
428                For more information try '--help'"
429            );
430        });
431        config_dir.push("iamb");
432        let mut config_json = config_dir.clone();
433        config_json.push("config.json");
434
435        let IambConfig {
436            mut profiles,
437            default_profile,
438            dirs,
439            settings: global,
440            layout,
441        } = IambConfig::load(config_json.as_path())?;
442
443        validate_profile_names(&profiles);
444
445        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
446            profiles.remove_entry(&profile).unwrap_or_else(|| {
447                usage!(
448                    "No configured profile with the name {:?} in {}",
449                    profile,
450                    config_json.display()
451                );
452            })
453        } else if profiles.len() == 1 {
454            profiles.into_iter().next().unwrap()
455        } else {
456            usage!(
457                "No profile specified. \
458                Please use -P or add \"default_profile\" to {}.\n\n\
459                For more information try '--help'",
460                config_json.display()
461            );
462        };
463
464        let layout = profile.layout.take().or(layout).unwrap_or_default();
465
466        let tunables = global.unwrap_or_default();
467        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
468        let tunables = tunables.values();
469
470        let dirs = dirs.unwrap_or_default();
471        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
472        let dirs = dirs.values();
473
474        // Set up paths that live inside the profile's data directory.
475        let mut profile_dir = config_dir.clone();
476        profile_dir.push("profiles");
477        profile_dir.push(profile_name.as_str());
478
479        let mut matrix_dir = profile_dir.clone();
480        matrix_dir.push("matrix");
481
482        let mut session_json = profile_dir;
483        session_json.push("session.json");
484
485        // Set up paths that live inside the profile's cache directory.
486        let mut cache_dir = dirs.cache.clone();
487        cache_dir.push("profiles");
488        cache_dir.push(profile_name.as_str());
489
490        let mut layout_json = cache_dir.clone();
491        layout_json.push("layout.json");
492
493        let settings = ApplicationSettings {
494            matrix_dir,
495            layout_json,
496            session_json,
497            profile_name,
498            profile,
499            tunables,
500            dirs,
501            layout,
502        };
503
504        Ok(settings)
505    }
506
507    pub fn get_user_char_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
508        let (color, c) = self
509            .tunables
510            .users
511            .get(user_id)
512            .map(|user| {
513                (
514                    user.color.as_ref().map(|c| c.0),
515                    user.name.as_ref().and_then(|s| s.chars().next()),
516                )
517            })
518            .unwrap_or_default();
519
520        let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
521        let style = user_style_from_color(color);
522
523        let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
524
525        Span::styled(String::from(c), style)
526    }
527
528    pub fn get_user_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
529        let (color, name) = self
530            .tunables
531            .users
532            .get(user_id)
533            .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
534            .unwrap_or_default();
535
536        let user_id = user_id.as_str();
537        let color = color.unwrap_or_else(|| user_color(user_id));
538        let style = user_style_from_color(color);
539        let name = name.unwrap_or(Cow::Borrowed(user_id));
540
541        Span::styled(name, style)
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548    use matrix_sdk::ruma::user_id;
549    use std::convert::TryFrom;
550
551    #[test]
552    fn test_profile_name_invalid() {
553        assert_eq!(validate_profile_name(""), false);
554        assert_eq!(validate_profile_name(" "), false);
555        assert_eq!(validate_profile_name("a b"), false);
556        assert_eq!(validate_profile_name("foo^bar"), false);
557        assert_eq!(validate_profile_name("FOO/BAR"), false);
558        assert_eq!(validate_profile_name("-b-c"), false);
559        assert_eq!(validate_profile_name("-B-c"), false);
560        assert_eq!(validate_profile_name(".b-c"), false);
561        assert_eq!(validate_profile_name(".B-c"), false);
562    }
563
564    #[test]
565    fn test_profile_name_valid() {
566        assert_eq!(validate_profile_name("foo"), true);
567        assert_eq!(validate_profile_name("FOO"), true);
568        assert_eq!(validate_profile_name("a-b-c"), true);
569        assert_eq!(validate_profile_name("a-B-c"), true);
570        assert_eq!(validate_profile_name("a.b-c"), true);
571        assert_eq!(validate_profile_name("a.B-c"), true);
572    }
573
574    #[test]
575    fn test_merge_users() {
576        let a = None;
577        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
578            color: Some(UserColor(Color::Red)),
579            name: Some("Hello".into()),
580        })]
581        .into_iter()
582        .collect::<HashMap<_, _>>();
583        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
584            color: Some(UserColor(Color::Green)),
585            name: Some("World".into()),
586        })]
587        .into_iter()
588        .collect::<HashMap<_, _>>();
589
590        let res = merge_users(a.clone(), a.clone());
591        assert_eq!(res, None);
592
593        let res = merge_users(a.clone(), Some(b.clone()));
594        assert_eq!(res, Some(b.clone()));
595
596        let res = merge_users(Some(b.clone()), a.clone());
597        assert_eq!(res, Some(b.clone()));
598
599        let res = merge_users(Some(b.clone()), Some(b.clone()));
600        assert_eq!(res, Some(b.clone()));
601
602        let res = merge_users(Some(b.clone()), Some(c.clone()));
603        assert_eq!(res, Some(c.clone()));
604
605        let res = merge_users(Some(c.clone()), Some(b.clone()));
606        assert_eq!(res, Some(b.clone()));
607    }
608
609    #[test]
610    fn test_parse_tunables() {
611        let res: Tunables = serde_json::from_str("{}").unwrap();
612        assert_eq!(res.typing_notice_send, None);
613        assert_eq!(res.typing_notice_display, None);
614        assert_eq!(res.users, None);
615
616        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
617        assert_eq!(res.typing_notice_send, Some(true));
618        assert_eq!(res.typing_notice_display, None);
619        assert_eq!(res.users, None);
620
621        let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
622        assert_eq!(res.typing_notice_send, Some(false));
623        assert_eq!(res.typing_notice_display, None);
624        assert_eq!(res.users, None);
625
626        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
627        assert_eq!(res.typing_notice_send, None);
628        assert_eq!(res.typing_notice_display, None);
629        assert_eq!(res.users, Some(HashMap::new()));
630
631        let res: Tunables = serde_json::from_str(
632            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
633        )
634        .unwrap();
635        assert_eq!(res.typing_notice_send, None);
636        assert_eq!(res.typing_notice_display, None);
637        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
638            color: Some(UserColor(Color::Black)),
639            name: Some("Tim".into()),
640        })];
641        assert_eq!(res.users, Some(users.into_iter().collect()));
642    }
643
644    #[test]
645    fn test_parse_layout() {
646        let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
647        let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
648        let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
649        let dms = WindowPath::Window(IambId::DirectList);
650        let welcome = WindowPath::Window(IambId::Welcome);
651
652        let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
653        assert_eq!(res, Layout::Restore);
654
655        let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
656        assert_eq!(res, Layout::New);
657
658        let res: Layout = serde_json::from_str(
659            "{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
660        )
661        .unwrap();
662        assert_eq!(res, Layout::Config {
663            tabs: vec![WindowLayout::Window { window: user.clone() }]
664        });
665
666        let res: Layout = serde_json::from_str(
667            "{\
668            \"style\": \"config\",\
669            \"tabs\": [\
670                {\"split\":[\
671                    {\"window\":\"@user:example.com\"},\
672                    {\"window\":\"#room:example.com\"}\
673                ]},\
674                {\"split\":[\
675                    {\"window\":\"!room:example.com\"},\
676                    {\"split\":[\
677                        {\"window\":\"iamb://dms\"},\
678                        {\"window\":\"iamb://welcome\"}\
679                    ]}\
680                ]}\
681            ]}",
682        )
683        .unwrap();
684        let split1 = WindowLayout::Split {
685            split: vec![
686                WindowLayout::Window { window: user.clone() },
687                WindowLayout::Window { window: alias },
688            ],
689        };
690        let split2 = WindowLayout::Split {
691            split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
692                window: welcome,
693            }],
694        };
695        let split3 = WindowLayout::Split {
696            split: vec![WindowLayout::Window { window: room }, split2],
697        };
698        let tabs = vec![split1, split3];
699        assert_eq!(res, Layout::Config { tabs });
700    }
701}