src/config.rs

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