fix: use snake case and module for configuration

This commit is contained in:
oSumAtrIX 2022-07-08 19:21:13 +02:00
parent 4293dd5518
commit 179ad3e824
No known key found for this signature in database
GPG Key ID: A9B3094ACDB604B4
5 changed files with 50 additions and 67 deletions

View File

@ -1,17 +1,19 @@
{ {
"$schema": "./configuration.schema.json", "$schema": "./configuration.schema.json",
"discord-authorization-token": "", "discord_authorization_token": "",
"administrators": { "administrators": {
"roles": [0], "roles": [0],
"users": [0] "users": [0]
}, },
"thread-introductions": [ "thread_introductions": [
{ {
"channels": [0], "channels": [0],
"response": {
"message": "" "message": ""
} }
}
], ],
"message-responders": [ "message_responders": [
{ {
"includes": { "includes": {
"channels": [0], "channels": [0],
@ -23,10 +25,12 @@
}, },
"condition": { "condition": {
"user": { "user": {
"server-age": 2 "server_age": 2
} }
}, },
"response": {
"message": "" "message": ""
} }
}
] ]
} }

View File

@ -4,9 +4,9 @@
"title": "Configuration schema", "title": "Configuration schema",
"description": "The Revanced Discord bot configuration schema.", "description": "The Revanced Discord bot configuration schema.",
"type": "object", "type": "object",
"required": ["discord-authorization-token"], "required": ["discord_authorization_token"],
"properties": { "properties": {
"discord-authorization-token": { "discord_authorization_token": {
"type": "string", "type": "string",
"description": "The authorization token for the Discord bot." "description": "The authorization token for the Discord bot."
}, },
@ -29,7 +29,7 @@
}, },
"description": "The list of administrators to control the Discord bot." "description": "The list of administrators to control the Discord bot."
}, },
"thread-introductions": { "thread_introductions": {
"type": "array", "type": "array",
"items": { "items": {
"type": "object", "type": "object",
@ -48,7 +48,7 @@
"minItems": 1, "minItems": 1,
"uniqueItems": true "uniqueItems": true
}, },
"message-responders": { "message_responders": {
"type": "array", "type": "array",
"items": { "items": {
"type": "object", "type": "object",
@ -81,7 +81,7 @@
"user": { "user": {
"type": "object", "type": "object",
"properties": { "properties": {
"server-age": { "server_age": {
"type": "integer", "type": "integer",
"description": "The user must be at least this many days old on the server." "description": "The user must be at least this many days old on the server."
} }
@ -230,7 +230,6 @@
"$ref": "#/$defs/embed", "$ref": "#/$defs/embed",
"description": "The embed to send." "description": "The embed to send."
} }
},
} }
} }
} }

View File

@ -4,33 +4,50 @@ use std::io::{Error, Read, Write};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Default, Serialize, Deserialize)] #[derive(Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] pub struct Configuration {
pub struct BotConfiguration {
#[serde(rename = "discord-authorization-token")]
pub discord_authorization_token: String, pub discord_authorization_token: String,
pub administrators: Administrators, pub administrators: Administrators,
#[serde(rename = "thread-introductions")]
pub thread_introductions: Vec<Introduction>, pub thread_introductions: Vec<Introduction>,
#[serde(rename = "message-responders")]
pub message_responders: Vec<MessageResponder>, pub message_responders: Vec<MessageResponder>,
} }
impl Configuration {
fn save(&self) -> Result<(), Error> {
let mut file = File::create("configuration.json")?;
let json = serde_json::to_string_pretty(&self)?;
file.write(json.as_bytes())?;
Ok(())
}
pub fn load() -> Result<Configuration, Error> {
let mut file = match File::open("configuration.json") {
Ok(file) => file,
Err(_) => {
let configuration = Configuration::default();
configuration.save()?;
return Ok(configuration);
},
};
let mut buf = String::new();
file.read_to_string(&mut buf)?;
Ok(serde_json::from_str(&buf)?)
}
}
#[derive(Default, Serialize, Deserialize)] #[derive(Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Administrators { pub struct Administrators {
pub roles: Vec<u64>, pub roles: Vec<u64>,
pub users: Vec<u64>, pub users: Vec<u64>,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Introduction { pub struct Introduction {
pub channels: Vec<u64>, pub channels: Vec<u64>,
pub response: Response, pub response: Response,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MessageResponder { pub struct MessageResponder {
pub includes: Includes, pub includes: Includes,
pub excludes: Excludes, pub excludes: Excludes,
@ -39,14 +56,12 @@ pub struct MessageResponder {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Response { pub struct Response {
pub message: Option<String>, pub message: Option<String>,
pub embed: Option<Embed>, pub embed: Option<Embed>,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Embed { pub struct Embed {
pub title: String, pub title: String,
pub description: String, pub description: String,
@ -59,7 +74,6 @@ pub struct Embed {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Field { pub struct Field {
pub name: String, pub name: String,
pub value: String, pub value: String,
@ -67,36 +81,29 @@ pub struct Field {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Footer { pub struct Footer {
pub text: String, pub text: String,
#[serde(rename = "icon_url")]
pub icon_url: String, pub icon_url: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Image { pub struct Image {
pub url: String, pub url: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Thumbnail { pub struct Thumbnail {
pub url: String, pub url: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Author { pub struct Author {
pub name: String, pub name: String,
#[serde(rename = "icon_url")]
pub icon_url: String, pub icon_url: String,
pub url: String, pub url: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Includes { pub struct Includes {
pub channels: Vec<u64>, pub channels: Vec<u64>,
#[serde(rename = "match")] #[serde(rename = "match")]
@ -104,7 +111,6 @@ pub struct Includes {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Excludes { pub struct Excludes {
pub roles: Vec<u64>, pub roles: Vec<u64>,
#[serde(rename = "match")] #[serde(rename = "match")]
@ -112,38 +118,11 @@ pub struct Excludes {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Condition { pub struct Condition {
pub user: User, pub user: User,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct User { pub struct User {
#[serde(rename = "server-age")]
pub server_age: i64, pub server_age: i64,
} }
impl BotConfiguration {
fn save(&self) -> Result<(), Error> {
let mut file = File::create("configuration.json")?;
let json = serde_json::to_string_pretty(&self)?;
file.write(json.as_bytes())?;
Ok(())
}
pub fn load() -> Result<BotConfiguration, Error> {
let mut file = match File::open("configuration.json") {
Ok(file) => file,
Err(_) => {
let configuration = BotConfiguration::default();
configuration.save()?;
return Ok(configuration);
},
};
let mut buf = String::new();
file.read_to_string(&mut buf)?;
Ok(serde_json::from_str(&buf)?)
}
}

1
src/configuration/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod application;

View File

@ -1,7 +1,7 @@
use std::sync::Arc; use std::sync::Arc;
use chrono::{DateTime, Duration, NaiveDateTime, Utc}; use chrono::{DateTime, Duration, NaiveDateTime, Utc};
use configuration::BotConfiguration; use configuration::application::Configuration;
use log::{error, info, trace, LevelFilter}; use log::{error, info, trace, LevelFilter};
use logger::logging::SimpleLogger; use logger::logging::SimpleLogger;
use regex::Regex; use regex::Regex;
@ -17,19 +17,19 @@ mod logger;
static LOGGER: SimpleLogger = SimpleLogger; static LOGGER: SimpleLogger = SimpleLogger;
struct Configuration; struct BotConfiguration;
impl TypeMapKey for Configuration { impl TypeMapKey for BotConfiguration {
type Value = Arc<RwLock<BotConfiguration>>; type Value = Arc<RwLock<Configuration>>;
} }
pub struct Handler; pub struct Handler;
async fn get_configuration_lock(ctx: &Context) -> Arc<RwLock<BotConfiguration>> { async fn get_configuration_lock(ctx: &Context) -> Arc<RwLock<Configuration>> {
ctx.data ctx.data
.read() .read()
.await .await
.get::<Configuration>() .get::<BotConfiguration>()
.expect("Expected Configuration in TypeMap.") .expect("Expected Configuration in TypeMap.")
.clone() .clone()
} }
@ -38,8 +38,8 @@ fn contains_match(strings: &Vec<String>, text: &String) -> bool {
strings.iter().any(|regex| Regex::new(regex).unwrap().is_match(&text)) strings.iter().any(|regex| Regex::new(regex).unwrap().is_match(&text))
} }
fn load_configuration() -> BotConfiguration { fn load_configuration() -> Configuration {
BotConfiguration::load().expect("Failed to load configuration") Configuration::load().expect("Failed to load configuration")
} }
#[async_trait] #[async_trait]
@ -232,7 +232,7 @@ async fn main() {
.await .await
.expect("Failed to create client"); .expect("Failed to create client");
client.data.write().await.insert::<Configuration>(Arc::new(RwLock::new(configuration))); client.data.write().await.insert::<BotConfiguration>(Arc::new(RwLock::new(configuration)));
if let Err(why) = client.start().await { if let Err(why) = client.start().await {
error!("{:?}", why); error!("{:?}", why);