src/config.rs

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