Skip to content

Commit

Permalink
fix: use snake case and module for configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
oSumAtrIX committed Jul 8, 2022
1 parent 4293dd5 commit 179ad3e
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 67 deletions.
16 changes: 10 additions & 6 deletions configuration.example.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
{
"$schema": "./configuration.schema.json",
"discord-authorization-token": "",
"discord_authorization_token": "",
"administrators": {
"roles": [0],
"users": [0]
},
"thread-introductions": [
"thread_introductions": [
{
"channels": [0],
"message": ""
"response": {
"message": ""
}
}
],
"message-responders": [
"message_responders": [
{
"includes": {
"channels": [0],
Expand All @@ -23,10 +25,12 @@
},
"condition": {
"user": {
"server-age": 2
"server_age": 2
}
},
"message": ""
"response": {
"message": ""
}
}
]
}
11 changes: 5 additions & 6 deletions configuration.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"title": "Configuration schema",
"description": "The Revanced Discord bot configuration schema.",
"type": "object",
"required": ["discord-authorization-token"],
"required": ["discord_authorization_token"],
"properties": {
"discord-authorization-token": {
"discord_authorization_token": {
"type": "string",
"description": "The authorization token for the Discord bot."
},
Expand All @@ -29,7 +29,7 @@
},
"description": "The list of administrators to control the Discord bot."
},
"thread-introductions": {
"thread_introductions": {
"type": "array",
"items": {
"type": "object",
Expand All @@ -48,7 +48,7 @@
"minItems": 1,
"uniqueItems": true
},
"message-responders": {
"message_responders": {
"type": "array",
"items": {
"type": "object",
Expand Down Expand Up @@ -81,7 +81,7 @@
"user": {
"type": "object",
"properties": {
"server-age": {
"server_age": {
"type": "integer",
"description": "The user must be at least this many days old on the server."
}
Expand Down Expand Up @@ -230,7 +230,6 @@
"$ref": "#/$defs/embed",
"description": "The embed to send."
}
},
}
}
}
Expand Down
71 changes: 25 additions & 46 deletions src/configuration.rs → src/configuration/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,50 @@ use std::io::{Error, Read, Write};
use serde::{Deserialize, Serialize};

#[derive(Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BotConfiguration {
#[serde(rename = "discord-authorization-token")]
pub struct Configuration {
pub discord_authorization_token: String,
pub administrators: Administrators,
#[serde(rename = "thread-introductions")]
pub thread_introductions: Vec<Introduction>,
#[serde(rename = "message-responders")]
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)]
#[serde(rename_all = "camelCase")]
pub struct Administrators {
pub roles: Vec<u64>,
pub users: Vec<u64>,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Introduction {
pub channels: Vec<u64>,
pub response: Response,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MessageResponder {
pub includes: Includes,
pub excludes: Excludes,
Expand All @@ -39,14 +56,12 @@ pub struct MessageResponder {
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Response {
pub message: Option<String>,
pub embed: Option<Embed>,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Embed {
pub title: String,
pub description: String,
Expand All @@ -59,91 +74,55 @@ pub struct Embed {
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Field {
pub name: String,
pub value: String,
pub inline: bool,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Footer {
pub text: String,
#[serde(rename = "icon_url")]
pub icon_url: String,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Image {
pub url: String,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Thumbnail {
pub url: String,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Author {
pub name: String,
#[serde(rename = "icon_url")]
pub icon_url: String,
pub url: String,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Includes {
pub channels: Vec<u64>,
#[serde(rename = "match")]
pub match_field: Vec<String>,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Excludes {
pub roles: Vec<u64>,
#[serde(rename = "match")]
pub match_field: Vec<String>,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Condition {
pub user: User,
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct User {
#[serde(rename = "server-age")]
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 change: 1 addition & 0 deletions src/configuration/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod application;
18 changes: 9 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Arc;

use chrono::{DateTime, Duration, NaiveDateTime, Utc};
use configuration::BotConfiguration;
use configuration::application::Configuration;
use log::{error, info, trace, LevelFilter};
use logger::logging::SimpleLogger;
use regex::Regex;
Expand All @@ -17,19 +17,19 @@ mod logger;

static LOGGER: SimpleLogger = SimpleLogger;

struct Configuration;
struct BotConfiguration;

impl TypeMapKey for Configuration {
type Value = Arc<RwLock<BotConfiguration>>;
impl TypeMapKey for BotConfiguration {
type Value = Arc<RwLock<Configuration>>;
}

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
.read()
.await
.get::<Configuration>()
.get::<BotConfiguration>()
.expect("Expected Configuration in TypeMap.")
.clone()
}
Expand All @@ -38,8 +38,8 @@ fn contains_match(strings: &Vec<String>, text: &String) -> bool {
strings.iter().any(|regex| Regex::new(regex).unwrap().is_match(&text))
}

fn load_configuration() -> BotConfiguration {
BotConfiguration::load().expect("Failed to load configuration")
fn load_configuration() -> Configuration {
Configuration::load().expect("Failed to load configuration")
}

#[async_trait]
Expand Down Expand Up @@ -232,7 +232,7 @@ async fn main() {
.await
.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 {
error!("{:?}", why);
Expand Down

0 comments on commit 179ad3e

Please sign in to comment.