src/config.rs

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