Files
mig1/src/config.rs
T

78 lines
2.1 KiB
Rust

use matrix_sdk::ruma::{OwnedRoomId, OwnedUserId};
use serde::{Deserialize, Serialize};
use std::{path::Path, sync::OnceLock};
static CONFIG: OnceLock<Config> = OnceLock::new();
fn get_config() -> &'static Config {
CONFIG.get_or_init(|| {
toml::from_str(&std::fs::read_to_string(Path::new("config.toml")).expect("无法读配置文件"))
.expect("解析配置文件时发生错误")
})
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub matrix: Option<MatrixBot>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MatrixBot {
pub home_server: String,
pub username: String,
pub password: String,
pub rooms: Vec<Room>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RoomType {
MainRoom, //主房间,用于签到和汇报
SubRoom, //子房间,用于自动踢出,统计(默认)
RecoveryRoom, //恢复房间,用于被踢出用户的恢复,被踢出的用户会自动被邀请到这里
}
fn default_room_type() -> RoomType {
RoomType::SubRoom
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Room {
pub room_id: OwnedRoomId,
#[serde(skip_serializing_if = "Option::is_none")]
pub kick_member_if_they_didnot_checkin_for_long_time: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kick_long_time: Option<isize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub white_list: Option<Vec<OwnedUserId>>,
#[serde(default = "default_room_type")]
pub room_type: RoomType,
}
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("{0} is not exist")]
NonExixtent(String),
}
impl Config {
pub fn get_all() -> &'static Self {
get_config()
}
}
#[cfg(test)]
mod tests {
use crate::config::{Room, RoomType};
#[test]
fn room_test() {
let cfg = r#"room_id="!example:foo.bar"
kick_member_if_they_didnot_checkin_for_long_time=true
kick_long_time=1
white_list=["@example:foo.bar"]
"#;
dbg!(&cfg);
let a: Room = toml::from_str::<Room>(cfg).unwrap();
dbg!(&a);
assert!(matches!(a.room_type, RoomType::SubRoom));
}
}