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

Commit

Permalink
minor changes
Browse files Browse the repository at this point in the history
start work at modrinth plugin system
  • Loading branch information
TOwInOK committed Mar 3, 2024
1 parent ef23f11 commit 27a7dad
Show file tree
Hide file tree
Showing 10 changed files with 147 additions and 144 deletions.
21 changes: 1 addition & 20 deletions src/config/datapack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,4 @@ pub struct Datapack {
paper: Option<Vec<String>>,
//List of plugins to stop updating
frozen: Option<Vec<String>>,
}

impl Datapack {
// fn new(
// modrinth: Option<Vec<String>>,
// spigot: Option<Vec<String>>,
// paper: Option<Vec<String>>,
// frozen: Option<Vec<String>>,
// ) -> Self {
// Self {
// modrinth,
// spigot,
// paper,
// frozen,
// }
// }
// pub fn default() -> Self {
// Datapack::new(None, None, None, None)
// }
}
}
63 changes: 43 additions & 20 deletions src/config/downloader.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
use std::{env, path::PathBuf};
use crate::config::DownloadErrors;
use log::warn;
use log::{info, trace};
use sha1::Sha1;
use md5::Md5;
use sha1::Digest as Digest1;
use sha2::Sha256;
use sha1::Sha1;
use sha2::Digest as Digest256;
use md5::Md5;
use sha2::Sha256;
use std::collections::HashMap;
use std::{env, path::PathBuf};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use crate::config::DownloadErrors;

use super::{CompareHashError, ConfigErrors};


pub struct Downloader();

impl Downloader {

///Get all info about for download core
//We need to get sha* or md5 for checking it
pub async fn download_core(freeze: bool, link:String, hash: ChooseHash) -> Result<(), DownloadErrors> {
pub async fn download_core(
freeze: bool,
link: String,
hash: ChooseHash,
) -> Result<(), DownloadErrors> {
if freeze {
info!("Мы не нуждаемся в загрузке");
warn!("Загрузка ядра была отключена!\n
Если это ваша первая загрузка, то отключите параметр freeze");
return Ok(());
}
let (content, result_str) = Self::get_file(&link, hash.clone()).await?;
Expand All @@ -31,23 +36,38 @@ impl Downloader {
Ok(())
} else {
trace!("Hash файла: {}\nHash ожидалось: {:#?}", result_str, &hash);
Err(DownloadErrors::DownloadCorrupt("Файл получен с ошибками!".to_string()))
Err(DownloadErrors::DownloadCorrupt(
"Файл получен с ошибками!".to_string(),
))
}
}

///### This func needs to download plugins, not to choose list of plugin to download.
///
///## `[lh]` is map contains values: `[Mode to download, Hash of mod]`
pub async fn download_plugins(lh: HashMap<String, String>, version: String) -> Result<(), DownloadErrors> {
//use version to download file only for this version
//safe file like `[name-version.jar]`
todo!()
}

async fn get_file(link: &str, hash: ChooseHash) -> Result<(Vec<u8>, ChooseHash), ConfigErrors> {
let response = reqwest::get(link).await?;
let content = response.bytes().await?;
let hash = hash.calculate_hash(&*content).await?;
Ok((content.to_vec(), hash))
}



async fn save_file(content: Vec<u8>, current_dir: PathBuf, link: &str) -> tokio::io::Result<()> {
async fn save_file(
content: Vec<u8>,
current_dir: PathBuf,
link: &str,
) -> tokio::io::Result<()> {
let path_buf = PathBuf::from(link);
let fname = current_dir.join(path_buf.file_name().unwrap_or_else(|| std::ffi::OsStr::new("tmp.bin")));
let fname = current_dir.join(
path_buf
.file_name()
.unwrap_or_else(|| std::ffi::OsStr::new("tmp.bin")),
);
let mut file = tokio::fs::File::create(fname).await?;
file.write_all(&content).await?;
Ok(())
Expand All @@ -62,7 +82,10 @@ pub enum ChooseHash {
}

impl ChooseHash {
async fn calculate_hash(self, mut reader: impl tokio::io::AsyncRead + Unpin) -> Result<Self, CompareHashError> {
async fn calculate_hash(
self,
mut reader: impl tokio::io::AsyncRead + Unpin,
) -> Result<Self, CompareHashError> {
match self {
ChooseHash::SHA1(_) => {
let mut hashed = <Sha1 as Digest1>::new();
Expand All @@ -75,7 +98,7 @@ impl ChooseHash {
}
let result = hashed.finalize();
Ok(ChooseHash::SHA1(format!("{:x}", result)))
},
}
ChooseHash::SHA256(_) => {
let mut hashed = <Sha256 as Digest256>::new();
let mut buffer = [0; 4096];
Expand All @@ -87,7 +110,7 @@ impl ChooseHash {
}
let result = hashed.finalize();
Ok(ChooseHash::SHA256(format!("{:x}", result)))
},
}
ChooseHash::MD5(_) => {
let mut hashed = <Md5 as md5::Digest>::new();
let mut buffer = [0; 4096];
Expand All @@ -99,7 +122,7 @@ impl ChooseHash {
}
let result = hashed.finalize();
Ok(ChooseHash::MD5(format!("{:x}", result)))
},
}
}
}
}
Expand All @@ -112,4 +135,4 @@ impl std::fmt::Display for ChooseHash {
ChooseHash::MD5(hash) => write!(f, "MD5: {}", hash),
}
}
}
}
10 changes: 4 additions & 6 deletions src/config/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,6 @@ impl From<reqwest::Error> for DownloadErrors {
}
}



#[derive(Error, Debug)]
pub enum CompareHashError {
#[error("Конвертация Sha1 проведена не успешно : {0}")]
Expand All @@ -70,9 +68,9 @@ pub enum CompareHashError {
impl From<CompareHashError> for ConfigErrors {
fn from(value: CompareHashError) -> Self {
match value {
CompareHashError::SHA1(msg) => ConfigErrors::LoadCorrupt(msg.to_string()),
CompareHashError::SHA256(msg) => ConfigErrors::LoadCorrupt(msg.to_string()),
CompareHashError::MD5(msg) => ConfigErrors::LoadCorrupt(msg.to_string()),
CompareHashError::SHA1(msg) => ConfigErrors::LoadCorrupt(msg.to_string()),
CompareHashError::SHA256(msg) => ConfigErrors::LoadCorrupt(msg.to_string()),
CompareHashError::MD5(msg) => ConfigErrors::LoadCorrupt(msg.to_string()),
}
}
}
}
42 changes: 18 additions & 24 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
mod datapack;
mod downloader;
mod errors;
mod models;
mod plugin;
mod version;
mod downloader;


use downloader::Downloader;
use datapack::*;
use downloader::Downloader;
use errors::*;
use log::info;
use models::vanilla::Vanilla;
Expand Down Expand Up @@ -51,36 +50,31 @@ impl Config {

pub async fn download_all(self) -> Result<(), DownloadErrors> {
//download core
self.choose_core().await
self.choose_core().await?;
self.choose_plugin().await
}

///Function download core by info in [`Config`]
async fn choose_core(self) -> Result<(), DownloadErrors> {
match self.version {
async fn choose_core(&self) -> Result<(), DownloadErrors> {
match &self.version {
//Download vanilla
Versions::Vanilla(ver, freeze) => {
let (link, hash) = Vanilla::find(&*ver).await?;
Downloader::download_core(freeze, link, hash).await
let (link, hash) = Vanilla::find(&**ver).await?;
Downloader::download_core(*freeze, link, hash).await
}

Versions::Purpur(_, _) => todo!(),
Versions::Paper(_, _) => todo!(),
Versions::Spigot(_, _) => todo!(),
Versions::Bucket(_, _) => todo!(),
}
}
}




async fn download_plugins() -> Result<(), DownloadErrors> {
todo!()
}
async fn download_mods() -> Result<(), DownloadErrors> {
todo!()
}
async fn download_datapacks() -> Result<(), DownloadErrors> {
todo!()
}

async fn choose_plugin(&self) -> Result<(), DownloadErrors> {
if let Some(plugins) = &self.plugins {

todo!()
} else {
info!("Нет плагинов для скачивания");
Ok(())
}
}
}
67 changes: 0 additions & 67 deletions src/config/models/item.rs

This file was deleted.

2 changes: 1 addition & 1 deletion src/config/models/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod item;
pub mod modrinth;
pub mod vanilla;
71 changes: 71 additions & 0 deletions src/config/models/modrinth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use std::collections::HashMap;

use md5::digest::typenum::Mod;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;

use crate::config::downloader::ChooseHash;

pub type Name = String;
pub type Hash = ChooseHash;
pub type ProjectID = String;
pub type PluginID = String;
pub type About = (Hash, ProjectID, PluginID);

pub struct Modrinth {
plugin: HashMap<Name, About>
}
///# Example
///we have cdn like this: `https://cdn.modrinth.com/data/PROJECT_ID/versions/ID/NAME-LOADER-VERSION.jar`
///we can take `[project_id]` -> `AANobbMI`
///we can take `[id]` -> `4GyXKCLd`
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModrinthData {
//Always change ich version
pub id: PluginID,
//Stable token.
pub project_id: ProjectID,
pub files: Vec<File>,
pub dependencies: Vec<Dependency>,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct File {
pub hashes: Hashes,
pub url: String,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Hashes {
pub sha1: String,
// pub sha512: String,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Dependency {
#[serde(rename = "version_id")]
pub version_id: Value,
#[serde(rename = "file_name")]
pub file_name: Value,
#[serde(rename = "dependency_type")]
pub dependency_type: String,
}


impl Modrinth {
///Convert Vector of data to hashmap
///for download files
pub async fn convert(data: Vec<ModrinthData>) -> Self {
let hashmap: HashMap<Name, About> = HashMap::new();
data.iter().map(|x|
{

});
todo!()
}
}
Loading

0 comments on commit 27a7dad

Please sign in to comment.