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

Commit

Permalink
Added the option to download purpur #3
Browse files Browse the repository at this point in the history
Made a more convenient separation.
Now lock is not part of config

Добавлена возможность скачать purpur
Сделано более удобное разделение.
Теперь lock не является частью config
  • Loading branch information
TOwInOK committed Mar 23, 2024
1 parent 6450a8b commit b5177a7
Show file tree
Hide file tree
Showing 23 changed files with 560 additions and 53 deletions.
4 changes: 2 additions & 2 deletions Sample of config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

# Секция ядра / Core section
[core]
# Выбери один из вариантов: vanila, spigot, bucket, paper, purpur
# Choose one of the options: vanilla, spigot, bucket, paper, purpur
# Выбери один из вариантов: vanilla, spigot, bucket, paper, purpur, forge, neoForge, fabric, folia, waterfall, velocity
# Choose one of the options: vanilla, spigot, bucket, paper, purpur, forge, neoForge, fabric, folia, waterfall, velocity
provider = "paper"
# Версия сервера (например, "1.14.4" или специальный код)
# Server version (e.g., "1.14.4" or a special code)
Expand Down
4 changes: 2 additions & 2 deletions config.lock
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[[metaData]]

[metaData.Core]
name = "Paper"
version = "1.20.1"
name = "Purpur"
version = "1.15"
6 changes: 3 additions & 3 deletions config.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[core]
# Выбери один из вариантов: vanilla, spigot, bucket, paper, purpur, forge, neoForge, fabric
provider = "paper"
version = "1.20.1"
# Выбери один из вариантов: vanilla, spigot, bucket, paper, purpur, forge, neoForge, fabric, folia, waterfall, velocity
provider = "purpur"
version = "1.15"
# build = "459"
# Замораживать ли объекты при наличии в системе
freeze = false
Expand Down
19 changes: 12 additions & 7 deletions src/config/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@ pub struct Core {
#[serde(rename_all = "lowercase")]
pub enum Provider {
#[default]
Vanilla,
Paper,
Folia,
Purpur,
Fabric,
Forge,
NeoForge,
Vanilla, // done
Paper,// done
Folia, // done
Purpur, // in work, good api
Fabric, // in work, api with out hash
//https://meta.fabricmc.net/v2/versions/game <- version check /v2/versions/intermediary give only stable
// or https://meta.fabricmc.net/v1/versions/game/1.14.4. Если нет версии, ответ пуст.

Forge, //no api
NeoForge, //worst api
Waterfall, // done
Velocity // done
}
1 change: 0 additions & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
pub mod additions;
pub mod core;
pub mod lock;
pub mod plugins;
pub mod versions;

Expand Down
3 changes: 3 additions & 0 deletions src/downloader/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub enum ChooseHash {
SHA1(String),
SHA256(String),
MD5(String),
None,
}

impl ChooseHash {
Expand Down Expand Up @@ -52,6 +53,7 @@ impl ChooseHash {
let result = hashed.finalize();
e.eq(&format!("{:x}", result))
}
ChooseHash::None => true,
}
}
}
Expand All @@ -62,6 +64,7 @@ impl std::fmt::Display for ChooseHash {
ChooseHash::SHA1(hash) => write!(f, "SHA1: {}", hash),
ChooseHash::SHA256(hash) => write!(f, "SHA256: {}", hash),
ChooseHash::MD5(hash) => write!(f, "MD5: {}", hash),
ChooseHash::None => write!(f, "None hash"),
}
}
}
30 changes: 16 additions & 14 deletions src/downloader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ use std::fs::File;
use std::io::Write;
use std::path::Path;
use log::{debug, info};

use self::{hash::ChooseHash, models::vanilla::Vanilla};
use crate::{
config::{
core::Provider, lock::{Lock, Meta, MetaData}, plugins::Sources, Config
},
downloader::models::{model::ModelCore, papermc::Paper},
errors::errors::DownloadErrors,
core::Provider, plugins::Sources, Config
}, downloader::models::{cores::{folia::Folia, paper::Paper, purpur::Purpur, vanilla::Vanilla, velocity::Velocity, waterfall::Waterfall}, model::ModelCore}, errors::errors::DownloadErrors, lock::lock::{Lock, Meta, MetaData}
};

use self::hash::ChooseHash;


#[derive(Debug)]
pub struct Downloader<'config, 'lock>{
Expand All @@ -39,17 +37,15 @@ impl<'config, 'lock> Downloader<'config, 'lock>{
async fn check_core(&mut self) -> Result<(), DownloadErrors> {
info!("Start to match provider of core");
match &self.config.core.provider {
Provider::Vanilla => {
Vanilla::download(self).await
}
Provider::Paper => {
Paper::download(self).await
},
Provider::Folia => todo!(),
Provider::Purpur => todo!(),
Provider::Vanilla => Vanilla::download(self).await,
Provider::Paper => Paper::download(self).await,
Provider::Folia => Folia::download(self).await,
Provider::Purpur => Purpur::download(self).await,
Provider::Fabric => todo!(),
Provider::Forge => todo!(),
Provider::NeoForge => todo!(),
Provider::Waterfall => Waterfall::download(self).await,
Provider::Velocity => Velocity::download(self).await,
}
}
///Check plugins and add it into list for download.
Expand Down Expand Up @@ -81,10 +77,15 @@ impl<'config, 'lock> Downloader<'config, 'lock>{
link: String,
hash: ChooseHash,
) -> Result<(), DownloadErrors> {
//delete all cores from meta and dir
self.lock.delete_core(&self.config.additions.path_to_core).await?;
//download
get_file(link, hash, &self.config.additions.path_to_core, name).await?;
//get meta data
let meta = Meta::Core(MetaData::new(name.to_string(), self.config.core.version.clone()));
//push to lock
self.lock.add(meta).await;
//save lock
self.lock.save().await?;
Ok(())
}
Expand All @@ -106,6 +107,7 @@ async fn get_file(

// Check hash
if hash.calculate_hash(&*content).await {
info!("Hash same");
let mut name = name.to_owned();
name.push_str(".jar");
let file_name = Path::new(&name); // Name of file
Expand Down
1 change: 1 addition & 0 deletions src/downloader/models/cores/fabric.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
//no hash
126 changes: 126 additions & 0 deletions src/downloader/models/cores/folia.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
use log::{debug, info};
use serde::{Deserialize, Serialize};


use crate::{downloader::{hash::ChooseHash, models::model::ModelCore, Downloader}, errors::errors::{ConfigErrors, DownloadErrors}, lock::lock::{ExistState, Meta, MetaData}};

pub enum Folia{}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VersionList {
pub versions: Vec<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BuildList {
pub builds: Vec<u16>,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Url {
pub downloads: Downloads,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Downloads {
pub application: Application,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Application {
pub name: String,
pub sha256: String,
}

impl ModelCore for Folia {
//find build and push link
async fn find(version: &crate::config::versions::Versions, build: &str) -> Result<(String, ChooseHash), ConfigErrors> {
let version = Self::find_version(version).await?;
let verlink = format!("https://api.papermc.io/v2/projects/paper/versions/{}", version);
info!("Get BuildList");
let buildlist: BuildList = reqwest::get(verlink).await?.json().await?;
let buildList = buildlist.builds;
if !build.is_empty() {
let build: u16 = build.parse().unwrap();
if buildList.contains(&build) {
info!("Find build, download");
let buildlink = format!("https://api.papermc.io/v2/projects/paper/versions/{}/builds/{}",version, build);
info!("Get Url");
let url: Url = reqwest::get(&buildlink).await?.json().await?;
return Ok((format!("{}/downloads/{}",buildlink, url.downloads.application.name), ChooseHash::SHA256(url.downloads.application.sha256)))
}
else {
Err(ConfigErrors::LoadCorrupt(format!("No one build like: {} find", build)))
}
} else {
info!("Download latest build");
let lastbuild = buildList.last().unwrap();
info!("Get Url");
let buildlink = format!("https://api.papermc.io/v2/projects/paper/versions/{}/builds/{}",version, lastbuild);
let url: Url = reqwest::get(&buildlink).await?.json().await?;
return Ok((format!("{}/downloads/{}",buildlink, url.downloads.application.name), ChooseHash::SHA256(url.downloads.application.sha256)))
}
}

//Find version in version list, if exist give out version or give error
async fn find_version(version: &crate::config::versions::Versions) -> Result<String, ConfigErrors> {
let link = "https://api.papermc.io/v2/projects/paper";
let verlist: VersionList = reqwest::get(link).await?.json().await?;
let verlist = verlist.versions;
match version {
crate::config::versions::Versions::Version(ver) => {
if verlist.contains(ver) {
Ok(ver.to_string())
} else {
Err(ConfigErrors::LoadCorrupt(format!("No one version ->{}<- find", ver)))
}
},
crate::config::versions::Versions::Latest => {
match verlist.last() {
Some(e) => Ok(e.to_string()),
None => Err(ConfigErrors::LoadCorrupt("No one version find".to_string())),
}
},
}
}

async fn download<'config, 'lock>(downloader: &mut Downloader<'config, 'lock>) -> Result<(), DownloadErrors> {
let core_name = "Folia";
info!("Find {}!", core_name);
//Find version to download
let (link, hash) = Folia::find(&downloader.config.core.version, &downloader.config.core.build).await?;

debug!("Find {} link: {}, hash: {}",core_name, &link, &hash);
info!("Start to download core!");
//Need to update or download?
match downloader.lock.exist(&Meta::Core(MetaData { name: core_name.to_string(), version: downloader.config.core.version.clone() })).await {
ExistState::Exist => {
info!("Check freeze and force_update");
if downloader.config.core.freeze && !downloader.config.core.force_update {
info!("Core has iced");
return Ok(());
};
if downloader.config.core.force_update {
downloader.config.core.force_update = false;
info!("Force update core!");
return downloader.download_core(core_name, link, hash).await
}
info!("Core doesn't need to download");
return Ok(());
},
ExistState::DifferentVersion => {
info!("Check freeze and force_update");
if downloader.config.core.freeze && !downloader.config.core.force_update {
info!("Core has iced");
return Ok(());
};
info!("Core have different version, Download!");
downloader.download_core(core_name, link, hash).await
},
ExistState::None => {
info!("No one core find, Download!");
downloader.download_core(core_name, link, hash).await
},
}
}
}
Empty file.
6 changes: 6 additions & 0 deletions src/downloader/models/cores/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pub mod vanilla;
pub mod paper;
pub mod folia;
pub mod velocity;
pub mod waterfall;
pub mod purpur;
File renamed without changes.
Empty file.
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use std::fmt::format;

use log::{debug, info, trace};
use log::{debug, info};
use serde::{Deserialize, Serialize};

use crate::{config::lock::{ExistState, Meta, MetaData}, downloader::{hash::ChooseHash, Downloader}, errors::errors::{ConfigErrors, DownloadErrors}};
use crate::{downloader::{hash::ChooseHash, models::model::ModelCore, Downloader}, errors::errors::{ConfigErrors, DownloadErrors}, lock::lock::{ExistState, Meta, MetaData}};

use super::model::ModelCore;

pub enum Paper{}

Expand Down
Loading

0 comments on commit b5177a7

Please sign in to comment.