diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000000000000000000000000000000000000..ee574cfb9be9648ae6f3eecfa6809704faf139c3 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,48 @@ +#![allow(dead_code)] + +use ini::{Error::Io as IniErrIo, Error::Parse as IniErrParse, Ini}; +use url::Url; + +pub struct Config { + pub display_name: String, // The display name to set for the bot + pub homeserver_url: Url, // The url of the home server, like https://matrix.iiens.net + pub user_name: String, // The true user name + pub user_password: String, // The true user name +} + +pub fn from_file(file_name: &String) -> Result<Config, String> { + return match Ini::load_from_file(file_name) { + Err(IniErrIo(e)) => Err(e.to_string()), + Err(IniErrParse(e)) => Err(e.to_string()), + Ok(conf) => { + let hs_url_str = conf.get_from_or(Some("user"), "homeserver", "https://matrix.org"); + return match Url::parse(hs_url_str) { + Err(e) => Err(e.to_string()), + Ok(hs_url) => Ok(Config { + user_name: conf + .get_from_or(Some("user"), "id", "@some-id:matrix.org") + .to_string(), + user_password: conf + .get_from_or(Some("user"), "password", "no-password") + .to_string(), + display_name: conf + .get_from_or(Some("user"), "display_name", "MGB-Hitagi") + .to_string(), + homeserver_url: hs_url, + }), + }; + } + }; +} + +pub fn write_default(file_name: &String) -> Result<(), String> { + let mut conf = Ini::new(); + conf.with_section(Some("user")) + .set("id", "@some_id:matrix.org") + .set("password", "no-password") + .set("display_name", "MGB-Hitagi"); + return match conf.write_to_file_policy(file_name, ini::EscapePolicy::Everything) { + Ok(()) => Ok(()), + Err(e) => Err(e.to_string()), + }; +}