src/config.rs

491 lines · 14640 bytes

  1use std::collections::hash_map::DefaultHasher;
  2use std::collections::HashMap;
  3use std::fmt;
  4use std::fs::File;
  5use std::hash::{Hash, Hasher};
  6use std::io::BufReader;
  7use std::path::{Path, PathBuf};
  8use std::process;
  9
 10use clap::Parser;
 11use matrix_sdk::ruma::{OwnedUserId, UserId};
 12use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
 13use url::Url;
 14
 15use modalkit::tui::{
 16    style::{Color, Modifier as StyleModifier, Style},
 17    text::Span,
 18};
 19
 20macro_rules! usage {
 21    ( $($args: tt)* ) => {
 22        println!($($args)*);
 23        process::exit(2);
 24    }
 25}
 26
 27const COLORS: [Color; 13] = [
 28    Color::Blue,
 29    Color::Cyan,
 30    Color::Green,
 31    Color::LightBlue,
 32    Color::LightGreen,
 33    Color::LightCyan,
 34    Color::LightMagenta,
 35    Color::LightRed,
 36    Color::LightYellow,
 37    Color::Magenta,
 38    Color::Red,
 39    Color::Reset,
 40    Color::Yellow,
 41];
 42
 43pub fn user_color(user: &str) -> Color {
 44    let mut hasher = DefaultHasher::new();
 45    user.hash(&mut hasher);
 46    let color = hasher.finish() as usize % COLORS.len();
 47
 48    COLORS[color]
 49}
 50
 51pub fn user_style_from_color(color: Color) -> Style {
 52    Style::default().fg(color).add_modifier(StyleModifier::BOLD)
 53}
 54
 55pub fn user_style(user: &str) -> Style {
 56    user_style_from_color(user_color(user))
 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 UserColor(pub Color);
114pub struct UserColorVisitor;
115
116impl<'de> Visitor<'de> for UserColorVisitor {
117    type Value = UserColor;
118
119    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
120        formatter.write_str("a valid color")
121    }
122
123    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
124    where
125        E: SerdeError,
126    {
127        match value {
128            "none" => Ok(UserColor(Color::Reset)),
129            "red" => Ok(UserColor(Color::Red)),
130            "black" => Ok(UserColor(Color::Black)),
131            "green" => Ok(UserColor(Color::Green)),
132            "yellow" => Ok(UserColor(Color::Yellow)),
133            "blue" => Ok(UserColor(Color::Blue)),
134            "magenta" => Ok(UserColor(Color::Magenta)),
135            "cyan" => Ok(UserColor(Color::Cyan)),
136            "gray" => Ok(UserColor(Color::Gray)),
137            "dark-gray" => Ok(UserColor(Color::DarkGray)),
138            "light-red" => Ok(UserColor(Color::LightRed)),
139            "light-green" => Ok(UserColor(Color::LightGreen)),
140            "light-yellow" => Ok(UserColor(Color::LightYellow)),
141            "light-blue" => Ok(UserColor(Color::LightBlue)),
142            "light-magenta" => Ok(UserColor(Color::LightMagenta)),
143            "light-cyan" => Ok(UserColor(Color::LightCyan)),
144            "white" => Ok(UserColor(Color::White)),
145            _ => Err(E::custom("Could not parse color")),
146        }
147    }
148}
149
150impl<'de> Deserialize<'de> for UserColor {
151    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
152    where
153        D: Deserializer<'de>,
154    {
155        deserializer.deserialize_str(UserColorVisitor)
156    }
157}
158
159#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
160pub struct UserDisplayTunables {
161    pub color: Option<UserColor>,
162    pub name: Option<String>,
163}
164
165pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
166
167fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> {
168    match (a, b) {
169        (Some(a), None) => Some(a),
170        (None, Some(b)) => Some(b),
171        (Some(mut a), Some(b)) => {
172            for (k, v) in b {
173                a.insert(k, v);
174            }
175
176            Some(a)
177        },
178        (None, None) => None,
179    }
180}
181
182#[derive(Clone)]
183pub struct TunableValues {
184    pub typing_notice: bool,
185    pub typing_notice_display: bool,
186    pub users: UserOverrides,
187}
188
189#[derive(Clone, Default, Deserialize)]
190pub struct Tunables {
191    pub typing_notice: Option<bool>,
192    pub typing_notice_display: Option<bool>,
193    pub users: Option<UserOverrides>,
194}
195
196impl Tunables {
197    fn merge(self, other: Self) -> Self {
198        Tunables {
199            typing_notice: self.typing_notice.or(other.typing_notice),
200            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
201            users: merge_users(self.users, other.users),
202        }
203    }
204
205    fn values(self) -> TunableValues {
206        TunableValues {
207            typing_notice: self.typing_notice.unwrap_or(true),
208            typing_notice_display: self.typing_notice.unwrap_or(true),
209            users: self.users.unwrap_or_default(),
210        }
211    }
212}
213
214#[derive(Clone)]
215pub struct DirectoryValues {
216    pub cache: PathBuf,
217    pub logs: PathBuf,
218    pub downloads: PathBuf,
219}
220
221#[derive(Clone, Default, Deserialize)]
222pub struct Directories {
223    pub cache: Option<PathBuf>,
224    pub logs: Option<PathBuf>,
225    pub downloads: Option<PathBuf>,
226}
227
228impl Directories {
229    fn merge(self, other: Self) -> Self {
230        Directories {
231            cache: self.cache.or(other.cache),
232            logs: self.logs.or(other.logs),
233            downloads: self.downloads.or(other.downloads),
234        }
235    }
236
237    fn values(self) -> DirectoryValues {
238        let cache = self
239            .cache
240            .or_else(dirs::cache_dir)
241            .expect("no dirs.cache value configured!");
242
243        let logs = self.logs.unwrap_or_else(|| {
244            let mut dir = cache.clone();
245            dir.push("logs");
246            dir
247        });
248
249        let downloads = self
250            .downloads
251            .or_else(dirs::download_dir)
252            .expect("no dirs.download value configured!");
253
254        DirectoryValues { cache, logs, downloads }
255    }
256}
257
258#[derive(Clone, Deserialize)]
259pub struct ProfileConfig {
260    pub user_id: OwnedUserId,
261    pub url: Url,
262    pub settings: Option<Tunables>,
263    pub dirs: Option<Directories>,
264}
265
266#[derive(Clone, Deserialize)]
267pub struct IambConfig {
268    pub profiles: HashMap<String, ProfileConfig>,
269    pub default_profile: Option<String>,
270    pub settings: Option<Tunables>,
271    pub dirs: Option<Directories>,
272}
273
274impl IambConfig {
275    pub fn load(config_json: &Path) -> Result<Self, ConfigError> {
276        if !config_json.is_file() {
277            usage!(
278                "Please create a configuration file at {}\n\n\
279                For more information try '--help'",
280                config_json.display(),
281            );
282        }
283
284        let file = File::open(config_json)?;
285        let reader = BufReader::new(file);
286        let config = serde_json::from_reader(reader)?;
287
288        Ok(config)
289    }
290}
291
292#[derive(Clone)]
293pub struct ApplicationSettings {
294    pub matrix_dir: PathBuf,
295    pub session_json: PathBuf,
296    pub profile_name: String,
297    pub profile: ProfileConfig,
298    pub tunables: TunableValues,
299    pub dirs: DirectoryValues,
300}
301
302impl ApplicationSettings {
303    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
304        let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
305            usage!(
306                "No user configuration directory found;\
307                please specify one via -C.\n\n
308                For more information try '--help'"
309            );
310        });
311        config_dir.push("iamb");
312        let mut config_json = config_dir.clone();
313        config_json.push("config.json");
314
315        let IambConfig {
316            mut profiles,
317            default_profile,
318            dirs,
319            settings: global,
320        } = IambConfig::load(config_json.as_path())?;
321
322        validate_profile_names(&profiles);
323
324        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
325            profiles.remove_entry(&profile).unwrap_or_else(|| {
326                usage!(
327                    "No configured profile with the name {:?} in {}",
328                    profile,
329                    config_json.display()
330                );
331            })
332        } else if profiles.len() == 1 {
333            profiles.into_iter().next().unwrap()
334        } else {
335            usage!(
336                "No profile specified. \
337                Please use -P or add \"default_profile\" to {}.\n\n\
338                For more information try '--help'",
339                config_json.display()
340            );
341        };
342
343        let tunables = global.unwrap_or_default();
344        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
345        let tunables = tunables.values();
346
347        let mut profile_dir = config_dir.clone();
348        profile_dir.push("profiles");
349        profile_dir.push(profile_name.as_str());
350
351        let mut matrix_dir = profile_dir.clone();
352        matrix_dir.push("matrix");
353
354        let mut session_json = profile_dir;
355        session_json.push("session.json");
356
357        let dirs = dirs.unwrap_or_default();
358        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
359        let dirs = dirs.values();
360
361        let settings = ApplicationSettings {
362            matrix_dir,
363            session_json,
364            profile_name,
365            profile,
366            tunables,
367            dirs,
368        };
369
370        Ok(settings)
371    }
372
373    pub fn get_user_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
374        if let Some(user) = self.tunables.users.get(user_id) {
375            let color = if let Some(UserColor(c)) = user.color {
376                c
377            } else {
378                user_color(user_id.as_str())
379            };
380
381            let style = user_style_from_color(color);
382
383            if let Some(name) = &user.name {
384                Span::styled(name.clone(), style)
385            } else {
386                Span::styled(user_id.as_str(), style)
387            }
388        } else {
389            Span::styled(user_id.as_str(), user_style(user_id.as_str()))
390        }
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397    use matrix_sdk::ruma::user_id;
398
399    #[test]
400    fn test_profile_name_invalid() {
401        assert_eq!(validate_profile_name(""), false);
402        assert_eq!(validate_profile_name(" "), false);
403        assert_eq!(validate_profile_name("a b"), false);
404        assert_eq!(validate_profile_name("foo^bar"), false);
405        assert_eq!(validate_profile_name("FOO/BAR"), false);
406        assert_eq!(validate_profile_name("-b-c"), false);
407        assert_eq!(validate_profile_name("-B-c"), false);
408        assert_eq!(validate_profile_name(".b-c"), false);
409        assert_eq!(validate_profile_name(".B-c"), false);
410    }
411
412    #[test]
413    fn test_profile_name_valid() {
414        assert_eq!(validate_profile_name("foo"), true);
415        assert_eq!(validate_profile_name("FOO"), true);
416        assert_eq!(validate_profile_name("a-b-c"), true);
417        assert_eq!(validate_profile_name("a-B-c"), true);
418        assert_eq!(validate_profile_name("a.b-c"), true);
419        assert_eq!(validate_profile_name("a.B-c"), true);
420    }
421
422    #[test]
423    fn test_merge_users() {
424        let a = None;
425        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
426            color: Some(UserColor(Color::Red)),
427            name: Some("Hello".into()),
428        })]
429        .into_iter()
430        .collect::<HashMap<_, _>>();
431        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
432            color: Some(UserColor(Color::Green)),
433            name: Some("World".into()),
434        })]
435        .into_iter()
436        .collect::<HashMap<_, _>>();
437
438        let res = merge_users(a.clone(), a.clone());
439        assert_eq!(res, None);
440
441        let res = merge_users(a.clone(), Some(b.clone()));
442        assert_eq!(res, Some(b.clone()));
443
444        let res = merge_users(Some(b.clone()), a.clone());
445        assert_eq!(res, Some(b.clone()));
446
447        let res = merge_users(Some(b.clone()), Some(b.clone()));
448        assert_eq!(res, Some(b.clone()));
449
450        let res = merge_users(Some(b.clone()), Some(c.clone()));
451        assert_eq!(res, Some(c.clone()));
452
453        let res = merge_users(Some(c.clone()), Some(b.clone()));
454        assert_eq!(res, Some(b.clone()));
455    }
456
457    #[test]
458    fn test_parse_tunables() {
459        let res: Tunables = serde_json::from_str("{}").unwrap();
460        assert_eq!(res.typing_notice, None);
461        assert_eq!(res.typing_notice_display, None);
462        assert_eq!(res.users, None);
463
464        let res: Tunables = serde_json::from_str("{\"typing_notice\": true}").unwrap();
465        assert_eq!(res.typing_notice, Some(true));
466        assert_eq!(res.typing_notice_display, None);
467        assert_eq!(res.users, None);
468
469        let res: Tunables = serde_json::from_str("{\"typing_notice\": false}").unwrap();
470        assert_eq!(res.typing_notice, Some(false));
471        assert_eq!(res.typing_notice_display, None);
472        assert_eq!(res.users, None);
473
474        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
475        assert_eq!(res.typing_notice, None);
476        assert_eq!(res.typing_notice_display, None);
477        assert_eq!(res.users, Some(HashMap::new()));
478
479        let res: Tunables = serde_json::from_str(
480            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
481        )
482        .unwrap();
483        assert_eq!(res.typing_notice, None);
484        assert_eq!(res.typing_notice_display, None);
485        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
486            color: Some(UserColor(Color::Black)),
487            name: Some("Tim".into()),
488        })];
489        assert_eq!(res.users, Some(users.into_iter().collect()));
490    }
491}