src/config.rs

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