src/config.rs

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