From b7a0aa2e2ebf18f9bc734355ab299aac007af3c3 Mon Sep 17 00:00:00 2001 From: TOwInOK <60252419+TOwInOK@users.noreply.github.com> Date: Sun, 3 Mar 2024 15:29:02 +0700 Subject: [PATCH] add interface for errors. use trace instead debug --- config.toml | 6 +-- src/config/errors.rs | 37 +++++++++++++ src/config/mod.rs | 101 ++++++++++------------------------- src/config/models/vanilla.rs | 41 +++++++------- src/main.rs | 10 ++-- 5 files changed, 93 insertions(+), 102 deletions(-) diff --git a/config.toml b/config.toml index ac739aa..47c565d 100644 --- a/config.toml +++ b/config.toml @@ -1,11 +1,11 @@ #Example of config file [version] -#which version you want? [Vanila, Buckit, Spigot, Paper, Purpur] -core = "Vanila" +#which version you want? [Vanil;a, Buckit, Spigot, Paper, Purpur] +core = "Vanilla" #First: any version if they have. #Second: lock version. (stop update) -version = ["1.20.1", false] +version = ["1.20.2", false] #Example: version = ["1.20.1", false] #We are loading version 1.20.1 with the tag FFFw2f #Because the flag is "false", we no longer update this version to newer versions of same verion. diff --git a/src/config/errors.rs b/src/config/errors.rs index a428f45..e7c03ba 100644 --- a/src/config/errors.rs +++ b/src/config/errors.rs @@ -5,8 +5,45 @@ pub enum DownloadErrors { DownloadCorrupt(String), } +// Реализация From для преобразования std::io::Error в DownloadErrors +impl From for DownloadErrors { + fn from(error: std::io::Error) -> Self { + DownloadErrors::DownloadCorrupt(error.to_string()) + } +} + #[derive(Error, Debug)] pub enum ConfigErrors { #[error("Загрузка файла не была успешна: {0}")] LoadCorrupt(String), + #[error("Ошибка чтения файла: {0}")] + ReadError(#[from] std::io::Error), + #[error("Ошибка парсинга TOML: {0}")] + ParseError(#[from] toml::de::Error), +} + +// Реализация From для преобразования DownloadErrors в ConfigErrors +impl From for ConfigErrors { + fn from(value: DownloadErrors) -> Self { + match value { + DownloadErrors::DownloadCorrupt(msg) => ConfigErrors::LoadCorrupt(msg), + } + } +} + +// Реализация From для преобразования ConfigErrors в DownloadErrors +impl From for DownloadErrors { + fn from(value: ConfigErrors) -> Self { + match value { + ConfigErrors::LoadCorrupt(msg) => DownloadErrors::DownloadCorrupt(msg), + ConfigErrors::ReadError(msg) => DownloadErrors::DownloadCorrupt(msg.to_string()), + ConfigErrors::ParseError(msg) => DownloadErrors::DownloadCorrupt(msg.to_string()), + } + } +} + +impl From for ConfigErrors { + fn from(value: reqwest::Error) -> Self { + ConfigErrors::LoadCorrupt(value.to_string()) + } } diff --git a/src/config/mod.rs b/src/config/mod.rs index 69cc1a9..34631bd 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -7,7 +7,7 @@ mod version; use datapack::*; use errors::*; use log::{error, info}; -use models::{vanilla::Vanilla, *}; +use models::vanilla::Vanilla; use plugin::Plugin; use serde::{Deserialize, Serialize}; use tokio::fs; @@ -30,43 +30,25 @@ impl Config { } } - fn default() -> Self { + pub fn default() -> Self { Config::new(Versions::default(), None, None) } - pub async fn load_config(path: String) -> Config { - let toml = { - info!("Загрузка конфигурационного файла..."); - let result = fs::read_to_string(path).await; - match result { - Ok(content) => { - info!("Файл успешно загружен."); - content - } - Err(e) => { - error!( - "Ваш конфигурационный файл не был обнаружен, загружаю стандартные настройки.\nПричина ошибки: {e}" - ); - return Config::default(); - } - } - }; + pub async fn load_config(path: String) -> Result { + info!("Загрузка конфигурационного файла..."); + let toml = fs::read_to_string(&path).await?; + info!("Файл успешно загружен."); + info!("Инициализация конфигурационного файла..."); - let config: Config = match toml::from_str(&toml) { - Ok(parsed_config) => { - info!("Конфигурация успешно инициализированна."); - parsed_config - } - Err(e) => { - error!("Не удалось загрузить конфигурацию, загружаю стандартные настройки.\nПричина ошибки: {e}"); - return Config::default(); - } - }; - config + let config: Config = toml::from_str(&toml)?; + info!("Конфигурация успешно инициализированна."); + + Ok(config) } - pub async fn download(config: Config) -> Result<(), DownloadErrors> { - let file = config.download_core().await; + pub async fn download(self) -> Result<(), DownloadErrors> { + //download core + let file = self.download_core().await; todo!() } @@ -81,44 +63,10 @@ impl Config { } ///Function download core by info in [`Config`] - async fn download_core(self) -> Result, DownloadErrors> { + async fn download_core(self) -> Result, DownloadErrors> { match self.version { //Download purpur - Versions::Purpur(ver, freeze) => { - if freeze { - //We don't need to download - return Ok(None); - } - //use if error - Err(DownloadErrors::DownloadCorrupt("ff".to_string())) - } - //Download paper - Versions::Paper(ver, feeze) => { - if feeze { - //We don't need to download - return Ok(None); - } - //use if error - Err(DownloadErrors::DownloadCorrupt("ff".to_string())) - } - //Download Spigot - Versions::Spigot(ver, freeze) => { - if freeze { - //We don't need to download - return Ok(None); - } - //use if error - Err(DownloadErrors::DownloadCorrupt("ff".to_string())) - } - //Download Bucket - Versions::Bucket(ver, freeze) => { - if freeze { - //We don't need to download - return Ok(None); - } - //use if error - Err(DownloadErrors::DownloadCorrupt("ff".to_string())) - } + //Download Vanilla Versions::Vanilla(ver, freeze) => { if freeze { @@ -128,15 +76,20 @@ impl Config { //use if error // Err(DownloadErrors::DownloadCorrupt("ff".to_string())) // let tmp_dir = Builder::new().temp().map_err(|er| ConfigErrors::LoadCorrupt(er.to_string())); - let _ = match Vanilla::find(&*ver).await { - Ok(_) => {} + match Vanilla::find(&*ver).await { + Ok(_) => { + todo!() + } Err(e) => { - error!("{:#?}", e) + error!("{:#?}", e); + Err(e.into()) } - }; - - todo!() + } } + Versions::Purpur(_, _) => todo!(), + Versions::Paper(_, _) => todo!(), + Versions::Spigot(_, _) => todo!(), + Versions::Bucket(_, _) => todo!(), } } } diff --git a/src/config/models/vanilla.rs b/src/config/models/vanilla.rs index 94915c4..a508b42 100644 --- a/src/config/models/vanilla.rs +++ b/src/config/models/vanilla.rs @@ -1,4 +1,6 @@ +use log::debug; use log::info; +use log::trace; use log::warn; use serde::Deserialize; use serde::Serialize; @@ -83,39 +85,34 @@ impl Server { impl Vanilla { /// Making request to mojang api and find the link to download minecraft.jar pub async fn find(version: &str) -> Result<(), ConfigErrors> { - let link = Vanilla::find_version(version) - .await - .map_err(|e| ConfigErrors::LoadCorrupt(e.to_string()))?; - let response = reqwest::get(link) - .await - .map_err(|e| ConfigErrors::LoadCorrupt(e.to_string()))?; - let download_section: DownloadSection = response - .json() - .await - .map_err(|e| ConfigErrors::LoadCorrupt(e.to_string()))?; - - info!("Check body: {:#?}", &download_section.downloads.server); + let link = Vanilla::find_version(version).await?; + trace!("get link: {}", &link); + let response = reqwest::get(link).await?; + trace!("get response, status of request: {}", &response.status()); + let download_section: DownloadSection = response.json().await?; + info!("Find jar to download!"); + debug!("Check body: {:#?}", &download_section.downloads.server); Ok(()) } ///Return `url` for get a json which contain link to donwload - pub async fn find_version(version: &str) -> Result { + pub async fn find_version(mut version: &str) -> Result { const LINK: &str = "https://launchermeta.mojang.com/mc/game/version_manifest.json"; - let response = reqwest::get(LINK) - .await - .map_err(|e| ConfigErrors::LoadCorrupt(e.to_string()))?; - let vanilla: Vanilla = response - .json() - .await - .map_err(|e| ConfigErrors::LoadCorrupt(e.to_string()))?; - + let response = reqwest::get(LINK).await?; + let vanilla: Vanilla = response.json().await?; + if version == "latest" { + version = &*vanilla.latest.release; + } vanilla .versions .iter() .find(|x| x.version.contains(version)) - .map(|x| x.url.clone()) + .map(|x| { + info!("find version: {}", &x.version); + x.url.clone() + }) .ok_or_else(|| { ConfigErrors::LoadCorrupt(format!("No one version like: {}, not found", version)) }) diff --git a/src/main.rs b/src/main.rs index 84d90c6..6bfbae8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,13 +4,17 @@ use config::Config; #[tokio::main] async fn main() { pretty_env_logger::formatted_builder() - .filter_level(log::LevelFilter::Debug) + .filter_level(log::LevelFilter::Trace) .init(); //Load Config file let path = "./config.toml".to_string(); - let config = Config::load_config(path).await; - log::info!("Config: {:#?}", config); + let config = Config::load_config(path).await.unwrap_or_else(|e| { + log::error!("message: {}", e); + log::warn!("Происходит загрузка стандартного конфига"); + Config::default() + }); + log::debug!("{:#?}", config); match Config::download(config).await { Ok(_) => todo!(), Err(_) => todo!(),