src/config.rs

495 lines · 14754 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(|| {
241                let mut dir = dirs::cache_dir()?;
242                dir.push("iamb");
243                dir.into()
244            })
245            .expect("no dirs.cache value configured!");
246
247        let logs = self.logs.unwrap_or_else(|| {
248            let mut dir = cache.clone();
249            dir.push("logs");
250            dir
251        });
252
253        let downloads = self
254            .downloads
255            .or_else(dirs::download_dir)
256            .expect("no dirs.download value configured!");
257
258        DirectoryValues { cache, logs, downloads }
259    }
260}
261
262#[derive(Clone, Deserialize)]
263pub struct ProfileConfig {
264    pub user_id: OwnedUserId,
265    pub url: Url,
266    pub settings: Option<Tunables>,
267    pub dirs: Option<Directories>,
268}
269
270#[derive(Clone, Deserialize)]
271pub struct IambConfig {
272    pub profiles: HashMap<String, ProfileConfig>,
273    pub default_profile: Option<String>,
274    pub settings: Option<Tunables>,
275    pub dirs: Option<Directories>,
276}
277
278impl IambConfig {
279    pub fn load(config_json: &Path) -> Result<Self, ConfigError> {
280        if !config_json.is_file() {
281            usage!(
282                "Please create a configuration file at {}\n\n\
283                For more information try '--help'",
284                config_json.display(),
285            );
286        }
287
288        let file = File::open(config_json)?;
289        let reader = BufReader::new(file);
290        let config = serde_json::from_reader(reader)?;
291
292        Ok(config)
293    }
294}
295
296#[derive(Clone)]
297pub struct ApplicationSettings {
298    pub matrix_dir: PathBuf,
299    pub session_json: PathBuf,
300    pub profile_name: String,
301    pub profile: ProfileConfig,
302    pub tunables: TunableValues,
303    pub dirs: DirectoryValues,
304}
305
306impl ApplicationSettings {
307    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
308        let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
309            usage!(
310                "No user configuration directory found;\
311                please specify one via -C.\n\n
312                For more information try '--help'"
313            );
314        });
315        config_dir.push("iamb");
316        let mut config_json = config_dir.clone();
317        config_json.push("config.json");
318
319        let IambConfig {
320            mut profiles,
321            default_profile,
322            dirs,
323            settings: global,
324        } = IambConfig::load(config_json.as_path())?;
325
326        validate_profile_names(&profiles);
327
328        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
329            profiles.remove_entry(&profile).unwrap_or_else(|| {
330                usage!(
331                    "No configured profile with the name {:?} in {}",
332                    profile,
333                    config_json.display()
334                );
335            })
336        } else if profiles.len() == 1 {
337            profiles.into_iter().next().unwrap()
338        } else {
339            usage!(
340                "No profile specified. \
341                Please use -P or add \"default_profile\" to {}.\n\n\
342                For more information try '--help'",
343                config_json.display()
344            );
345        };
346
347        let tunables = global.unwrap_or_default();
348        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
349        let tunables = tunables.values();
350
351        let mut profile_dir = config_dir.clone();
352        profile_dir.push("profiles");
353        profile_dir.push(profile_name.as_str());
354
355        let mut matrix_dir = profile_dir.clone();
356        matrix_dir.push("matrix");
357
358        let mut session_json = profile_dir;
359        session_json.push("session.json");
360
361        let dirs = dirs.unwrap_or_default();
362        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
363        let dirs = dirs.values();
364
365        let settings = ApplicationSettings {
366            matrix_dir,
367            session_json,
368            profile_name,
369            profile,
370            tunables,
371            dirs,
372        };
373
374        Ok(settings)
375    }
376
377    pub fn get_user_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
378        if let Some(user) = self.tunables.users.get(user_id) {
379            let color = if let Some(UserColor(c)) = user.color {
380                c
381            } else {
382                user_color(user_id.as_str())
383            };
384
385            let style = user_style_from_color(color);
386
387            if let Some(name) = &user.name {
388                Span::styled(name.clone(), style)
389            } else {
390                Span::styled(user_id.as_str(), style)
391            }
392        } else {
393            Span::styled(user_id.as_str(), user_style(user_id.as_str()))
394        }
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401    use matrix_sdk::ruma::user_id;
402
403    #[test]
404    fn test_profile_name_invalid() {
405        assert_eq!(validate_profile_name(""), false);
406        assert_eq!(validate_profile_name(" "), false);
407        assert_eq!(validate_profile_name("a b"), false);
408        assert_eq!(validate_profile_name("foo^bar"), false);
409        assert_eq!(validate_profile_name("FOO/BAR"), false);
410        assert_eq!(validate_profile_name("-b-c"), false);
411        assert_eq!(validate_profile_name("-B-c"), false);
412        assert_eq!(validate_profile_name(".b-c"), false);
413        assert_eq!(validate_profile_name(".B-c"), false);
414    }
415
416    #[test]
417    fn test_profile_name_valid() {
418        assert_eq!(validate_profile_name("foo"), true);
419        assert_eq!(validate_profile_name("FOO"), true);
420        assert_eq!(validate_profile_name("a-b-c"), true);
421        assert_eq!(validate_profile_name("a-B-c"), true);
422        assert_eq!(validate_profile_name("a.b-c"), true);
423        assert_eq!(validate_profile_name("a.B-c"), true);
424    }
425
426    #[test]
427    fn test_merge_users() {
428        let a = None;
429        let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
430            color: Some(UserColor(Color::Red)),
431            name: Some("Hello".into()),
432        })]
433        .into_iter()
434        .collect::<HashMap<_, _>>();
435        let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
436            color: Some(UserColor(Color::Green)),
437            name: Some("World".into()),
438        })]
439        .into_iter()
440        .collect::<HashMap<_, _>>();
441
442        let res = merge_users(a.clone(), a.clone());
443        assert_eq!(res, None);
444
445        let res = merge_users(a.clone(), Some(b.clone()));
446        assert_eq!(res, Some(b.clone()));
447
448        let res = merge_users(Some(b.clone()), a.clone());
449        assert_eq!(res, Some(b.clone()));
450
451        let res = merge_users(Some(b.clone()), Some(b.clone()));
452        assert_eq!(res, Some(b.clone()));
453
454        let res = merge_users(Some(b.clone()), Some(c.clone()));
455        assert_eq!(res, Some(c.clone()));
456
457        let res = merge_users(Some(c.clone()), Some(b.clone()));
458        assert_eq!(res, Some(b.clone()));
459    }
460
461    #[test]
462    fn test_parse_tunables() {
463        let res: Tunables = serde_json::from_str("{}").unwrap();
464        assert_eq!(res.typing_notice, None);
465        assert_eq!(res.typing_notice_display, None);
466        assert_eq!(res.users, None);
467
468        let res: Tunables = serde_json::from_str("{\"typing_notice\": true}").unwrap();
469        assert_eq!(res.typing_notice, Some(true));
470        assert_eq!(res.typing_notice_display, None);
471        assert_eq!(res.users, None);
472
473        let res: Tunables = serde_json::from_str("{\"typing_notice\": false}").unwrap();
474        assert_eq!(res.typing_notice, Some(false));
475        assert_eq!(res.typing_notice_display, None);
476        assert_eq!(res.users, None);
477
478        let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
479        assert_eq!(res.typing_notice, None);
480        assert_eq!(res.typing_notice_display, None);
481        assert_eq!(res.users, Some(HashMap::new()));
482
483        let res: Tunables = serde_json::from_str(
484            "{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
485        )
486        .unwrap();
487        assert_eq!(res.typing_notice, None);
488        assert_eq!(res.typing_notice_display, None);
489        let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
490            color: Some(UserColor(Color::Black)),
491            name: Some("Tim".into()),
492        })];
493        assert_eq!(res.users, Some(users.into_iter().collect()));
494    }
495}