Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,18 @@ edition = "2024"
[features]

[dependencies]
anyhow = "1"
bytes = "1"
chrono = "0.4"
clap = { version = "4", features = ["derive"] }
dotenvy = "0.15"
indexmap = "2"
reqwest = { version = "0.13", features = ["hickory-dns"] }
rustls = "0.23"
semver = "1"
serde = "1"
sonic-rs = "0.5"
serde_yaml_ng = "0.10" # Should replace this with a better maintained YAML 1.2 supporting alternative
sonic-rs = "0.5"
tokio = { version = "1", features = ["full"] }
tokio-cron-scheduler = { version = "0.15", features = ["english"] }
tokio-util = "0.7"
Expand Down
4 changes: 2 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct Config {
}

impl Config {
pub fn new(file_path: &Path) -> Result<Box<Self>, ()> {
pub fn new(file_path: &Path) -> Result<Self, ()> {
info!("Loading and parsing the config file");

let file_bytes = match fs::read(file_path) {
Expand All @@ -29,7 +29,7 @@ impl Config {
};

match serde_yaml_ng::from_slice::<Config>(&file_bytes) {
Ok(config) => Ok(Box::new(config)), // TODO: Env var interpolation, maybe via YAML 1.2's' `!val`
Ok(config) => Ok(config), // TODO: Env var interpolation
Err(err) => {
error!(
"An error occurred while trying to deserialize the config file YAML to a struct: {err}"
Expand Down
2 changes: 1 addition & 1 deletion src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct HttpClient {
client: Client,
}

const USER_AGENT: &str = "celarye/discord-bot";
static USER_AGENT: &str = "celarye/discord-bot";

impl HttpClient {
pub fn new(http_client_timeout_seconds: u64) -> Result<Self, ()> {
Expand Down
72 changes: 19 additions & 53 deletions src/http/registry.rs
Original file line number Diff line number Diff line change
@@ -1,72 +1,38 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright © 2026 Eduard Smet */

use std::{
str::FromStr,
sync::{Arc, LazyLock},
};
use std::str::FromStr;

use anyhow::{Context, Error, Result};
use reqwest::StatusCode;
use tracing::{debug, error};
use tracing::debug;
use url::{ParseError, Url};

use crate::http::HttpClient;

static DEFAULT_REGISTRY_URL: LazyLock<Url> = LazyLock::new(|| {
Url::parse("https://raw.githubusercontent.com/celarye/discord-bot-plugins/refs/heads/master/")
.unwrap()
});

impl HttpClient {
pub async fn get_file_from_registry(
&self,
registry: &Arc<Option<String>>,
path: &str,
) -> Result<Vec<u8>, ()> {
let url = match Self::parse_url(registry, path) {
Ok(url) => url,
Err(err) => {
error!(
"An error occurred while trying to construct a valid URL from the provided registry and path: {err}"
);
return Err(());
}
};
pub async fn get_file_from_registry(&self, registry: &str, path: &str) -> Result<Vec<u8>> {
let url = Self::parse_url(registry, path).context("An error occurred while trying to construct a valid URL from the provided registry and path")?;

debug!("Requested registry file: {url}");

match self.client.get(url).send().await {
Ok(raw_response) => {
if raw_response.status() != StatusCode::OK {
error!(
"The response was undesired, status code: {}",
raw_response.status(),
);
return Err(());
}
let response = self.client.get(url).send().await?;

match raw_response.bytes().await {
Ok(response) => Ok(response.to_vec()),
Err(err) => {
error!(
"Something went wrong while getting the raw bytes from the response, error: {err}"
);
Err(())
}
}
}
Err(err) => {
error!("Something went wrong while making the request, error: {err}");
Err(())
}
if response.status() != StatusCode::OK {
return Err(Error::msg(format!(
"The response was undesired, status code: {}",
response.status()
)));
}
}

fn parse_url(registry: &Arc<Option<String>>, path: &str) -> Result<Url, ParseError> {
if let Some(registry) = registry.as_deref() {
return Url::from_str(registry)?.join(path);
}
Ok(response
.bytes()
.await
.context("Something went wrong while getting the raw bytes from the response")?
.to_vec())
}

DEFAULT_REGISTRY_URL.join(path)
fn parse_url(registry: &str, path: &str) -> Result<Url, ParseError> {
Url::from_str(&format!("https://{registry}/"))?.join(path)
}
}
8 changes: 4 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use std::os::unix::process::CommandExt;

use std::{
collections::VecDeque,
collections::{HashMap, VecDeque},
env,
ffi::OsString,
path::{Path, PathBuf},
Expand Down Expand Up @@ -139,18 +139,18 @@ fn initialization(

async fn registry_get_plugins(
http_client_timeout_seconds: u64,
config: Box<Config>,
config: Config,
plugin_directory: PathBuf,
cache: bool,
) -> Result<Vec<AvailablePlugin>, ()> {
) -> Result<HashMap<String, AvailablePlugin>, ()> {
let http_client = Arc::new(HttpClient::new(http_client_timeout_seconds)?);

registry::get_plugins(http_client, config, plugin_directory, cache).await
}

async fn plugin_initializations(
runtime: Arc<Runtime>,
available_plugins: Vec<AvailablePlugin>,
available_plugins: HashMap<String, AvailablePlugin>,
plugin_registrations: Arc<RwLock<PluginRegistrations>>,
config_directory: &Path,
) -> Result<(), ()> {
Expand Down
6 changes: 4 additions & 2 deletions src/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod runtime;

use std::collections::{HashMap, HashSet};

use semver::Version;
use serde::{Deserialize, Deserializer};
use serde_yaml_ng::Value;
use twilight_model::id::{Id, marker::CommandMarker};
Expand All @@ -15,7 +16,7 @@ use crate::plugins::discord_bot::plugin::plugin_types::SupportedRegistrations;

wasmtime::component::bindgen!({ imports: { default: async }, exports: { default: async } });

#[derive(Deserialize)]
#[derive(Clone, Deserialize)]
pub struct ConfigPlugin {
pub plugin: String,
pub cache: Option<bool>,
Expand Down Expand Up @@ -86,8 +87,9 @@ impl<'de> Deserialize<'de> for SupportedRegistrations {
}

pub struct AvailablePlugin {
pub registry_id: String,
pub id: String,
pub version: String,
pub version: Version,
pub permissions: SupportedRegistrations,
pub environment: Option<HashMap<String, String>>,
pub settings: Option<Value>,
Expand Down
Loading
Loading