src/config.rs

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