use std::{ fs::{self, remove_file, File}, io::{Read, Write}, time::Duration, }; use apis::modrinth::{get_game_versions, GameVersion, GameVersionType}; use errors::MLE; use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; use crate::{ apis, errors::{self, Error}, STYLE_MESSAGE, }; #[derive(Debug, Clone, Deserialize, Serialize)] pub enum VersionLevel { #[serde(rename(serialize = "release", deserialize = "release"))] Release, #[serde(rename(serialize = "snapshot", deserialize = "snapshot"))] Snapshot, Version(String), } /// Checks if update needed (time) /// if yes: get versions, update /// # Errors pub async fn check_game_versions(path: &str, force: bool) -> MLE<()> { let p = ProgressBar::new(1); p.set_style(ProgressStyle::with_template(STYLE_MESSAGE)?); p.set_message("Update minecraft versions"); let creation_time = fs::metadata(path)?.created()?; if !force && creation_time.elapsed()? < Duration::from_secs(60 * 60 * 24) { return Ok(()); } let versions = get_game_versions().await?; remove_file(path)?; let mut file = File::create(path)?; file.write_all(serde_json::to_string_pretty(&versions)?.as_bytes())?; p.finish_with_message("Updated minecraft versions"); Ok(()) } /// Loads game versions from file /// # Errors pub fn load_game_versions(path: &str) -> MLE> { let mut file = File::open(path)?; let mut data = String::new(); file.read_to_string(&mut data)?; let versions: Vec = serde_json::from_str(&data)?; Ok(versions) } impl VersionLevel { #[must_use] pub fn from(str: &str) -> Self { match str { "release" => VersionLevel::Release, "snapshot" => VersionLevel::Snapshot, _ => VersionLevel::Version(String::from(str)), } } /// . /// /// Panics if . /// # Errors pub async fn get( self, versions_path: &str, force_update: bool, ) -> MLE { let path = format!("{versions_path}/versions.json"); check_game_versions(&path, force_update).await?; let mut versions = load_game_versions(&path)?.into_iter(); match self { VersionLevel::Release => { if let Some(release) = versions .find(|ver| ver.version_type == GameVersionType::release) { Ok(release.version) } else { Err(Error::MinecraftVersionNotFound) } } VersionLevel::Snapshot => { if let Some(snapshot) = versions .find(|ver| ver.version_type == GameVersionType::snapshot) { Ok(snapshot.version) } else { Err(Error::MinecraftVersionNotFound) } } VersionLevel::Version(v) => { if versions.any(|ver| ver.version == v) { Ok(v) } else { Err(Error::MinecraftVersionNotFound) } } } } }