Skip to content
This repository has been archived by the owner on Dec 12, 2024. It is now read-only.

Commit

Permalink
add interface for errors.
Browse files Browse the repository at this point in the history
use trace instead debug
  • Loading branch information
TOwInOK committed Mar 3, 2024
1 parent 6e27464 commit b7a0aa2
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 102 deletions.
6 changes: 3 additions & 3 deletions config.toml
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
37 changes: 37 additions & 0 deletions src/config/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,45 @@ pub enum DownloadErrors {
DownloadCorrupt(String),
}

// Реализация From для преобразования std::io::Error в DownloadErrors
impl From<std::io::Error> 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<DownloadErrors> for ConfigErrors {
fn from(value: DownloadErrors) -> Self {
match value {
DownloadErrors::DownloadCorrupt(msg) => ConfigErrors::LoadCorrupt(msg),
}
}
}

// Реализация From для преобразования ConfigErrors в DownloadErrors
impl From<ConfigErrors> 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<reqwest::Error> for ConfigErrors {
fn from(value: reqwest::Error) -> Self {
ConfigErrors::LoadCorrupt(value.to_string())
}
}
101 changes: 27 additions & 74 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<Config, ConfigErrors> {
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!()
}

Expand All @@ -81,44 +63,10 @@ impl Config {
}

///Function download core by info in [`Config`]
async fn download_core(self) -> Result<Option<()>, DownloadErrors> {
async fn download_core(self) -> Result<Option<String>, 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 {
Expand All @@ -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!(),
}
}
}
41 changes: 19 additions & 22 deletions src/config/models/vanilla.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use log::debug;
use log::info;
use log::trace;
use log::warn;
use serde::Deserialize;
use serde::Serialize;
Expand Down Expand Up @@ -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<String, ConfigErrors> {
pub async fn find_version(mut version: &str) -> Result<String, ConfigErrors> {
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))
})
Expand Down
10 changes: 7 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(),
Expand Down

0 comments on commit b7a0aa2

Please sign in to comment.