From 252fe8e44a3935741566852f55a27076b4374b44 Mon Sep 17 00:00:00 2001 From: objz Date: Sat, 19 Jul 2025 15:14:07 +0200 Subject: [PATCH] feat: add download clients for Mojang API and mod loaders --- src/net/fabric.rs | 210 ++++++++++++++++++++++++ src/net/forge.rs | 172 +++++++++++++++++++ src/net/mod.rs | 116 +++++++++++++ src/net/mojang.rs | 390 ++++++++++++++++++++++++++++++++++++++++++++ src/net/neoforge.rs | 200 +++++++++++++++++++++++ src/net/quilt.rs | 196 ++++++++++++++++++++++ 6 files changed, 1284 insertions(+) create mode 100644 src/net/fabric.rs create mode 100644 src/net/forge.rs create mode 100644 src/net/mod.rs create mode 100644 src/net/mojang.rs create mode 100644 src/net/neoforge.rs create mode 100644 src/net/quilt.rs diff --git a/src/net/fabric.rs b/src/net/fabric.rs new file mode 100644 index 0000000..2366d1e --- /dev/null +++ b/src/net/fabric.rs @@ -0,0 +1,210 @@ +use std::path::Path; + +use serde::Deserialize; + +use crate::net::{download_file, HttpClient, NetError}; +use crate::tui::progress::set_sub_action; + +const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2"; + +#[derive(Debug, Clone, Deserialize)] +pub struct FabricLoaderVersion { + pub loader: FabricVersion, + pub intermediary: FabricVersion, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct FabricVersion { + pub version: String, + #[serde(default)] + pub stable: bool, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FabricProfile { + pub id: String, + pub main_class: String, + pub libraries: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct FabricLibrary { + pub name: String, + pub url: String, +} + +/// `net.fabricmc:fabric-loader:0.16.0` → `net/fabricmc/fabric-loader/0.16.0/fabric-loader-0.16.0.jar` +fn maven_coord_to_path(coord: &str) -> Option { + let parts: Vec<&str> = coord.split(':').collect(); + match parts.as_slice() { + [group, artifact, version] => { + let group_path = group.replace('.', "/"); + Some(format!( + "{}/{}/{}/{}-{}.jar", + group_path, artifact, version, artifact, version + )) + } + _ => None, + } +} + +pub async fn fetch_fabric_versions( + client: &HttpClient, + game_version: &str, +) -> Result, NetError> { + let url = format!("{}/versions/loader/{}", FABRIC_META_BASE, game_version); + + let response = match client.inner().get(&url).send().await { + Ok(r) => r, + Err(e) => { + tracing::error!("Fabric meta GET {} failed: {}", url, e); + return Err(NetError::Http(e)); + } + }; + + if !response.status().is_success() { + let status = response.status().as_u16(); + tracing::error!("Fabric meta HTTP {} for {}", status, url); + return Err(NetError::StatusError { + status, + url: url.clone(), + }); + } + + let versions: Vec = match response.json().await { + Ok(v) => v, + Err(e) => { + tracing::error!("Failed to parse Fabric loader versions: {}", e); + return Err(NetError::Http(e)); + } + }; + + Ok(versions) +} + +pub async fn fetch_fabric_profile( + client: &HttpClient, + game_version: &str, + loader_version: &str, +) -> Result { + let url = format!( + "{}/versions/loader/{}/{}/profile/json", + FABRIC_META_BASE, game_version, loader_version + ); + + let response = match client.inner().get(&url).send().await { + Ok(r) => r, + Err(e) => { + tracing::error!("Fabric profile GET {} failed: {}", url, e); + return Err(NetError::Http(e)); + } + }; + + if !response.status().is_success() { + let status = response.status().as_u16(); + tracing::error!("Fabric profile HTTP {} for {}", status, url); + return Err(NetError::StatusError { + status, + url: url.clone(), + }); + } + + let profile: FabricProfile = match response.json().await { + Ok(p) => p, + Err(e) => { + tracing::error!("Failed to parse Fabric profile: {}", e); + return Err(NetError::Http(e)); + } + }; + + Ok(profile) +} + +pub async fn download_fabric_libraries( + client: &HttpClient, + profile: &FabricProfile, + instance_dir: &Path, +) -> Result<(), NetError> { + let libraries_dir = instance_dir.join(".minecraft").join("libraries"); + + for lib in &profile.libraries { + let maven_path = match maven_coord_to_path(&lib.name) { + Some(p) => p, + None => { + tracing::error!( + "Invalid Maven coordinate in Fabric profile: {}", + lib.name + ); + return Err(NetError::Parse(format!( + "Invalid Maven coordinate: {}", + lib.name + ))); + } + }; + + let dest = libraries_dir.join(&maven_path); + + if dest.exists() { + tracing::debug!("Fabric library already exists: {}", lib.name); + continue; + } + + let base_url = lib.url.trim_end_matches('/'); + let download_url = format!("{}/{}", base_url, maven_path); + + set_sub_action(&lib.name); + tracing::info!("Downloading Fabric library: {}", lib.name); + + match download_file(client, &download_url, &dest, |_, _| {}).await { + Ok(()) => {} + Err(e) => { + tracing::error!( + "Failed to download Fabric library {}: {}", + lib.name, e + ); + return Err(e); + } + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::HttpClient; + + #[tokio::test] + async fn test_fetch_versions() { + let client = HttpClient::new(); + match fetch_fabric_versions(&client, "1.20.1").await { + Ok(versions) => { + assert!( + !versions.is_empty(), + "Should have Fabric versions for 1.20.1" + ); + assert!( + versions[0].loader.version.contains('.'), + "Version should be semver-like" + ); + } + Err(e) => assert!(false, "fetch_fabric_versions failed: {}", e), + } + } + + #[test] + fn test_maven_coord_to_path() { + assert_eq!( + maven_coord_to_path("net.fabricmc:fabric-loader:0.16.0"), + Some("net/fabricmc/fabric-loader/0.16.0/fabric-loader-0.16.0.jar".to_string()) + ); + assert_eq!( + maven_coord_to_path("org.ow2.asm:asm:9.6"), + Some("org/ow2/asm/asm/9.6/asm-9.6.jar".to_string()) + ); + assert_eq!(maven_coord_to_path("invalid"), None); + assert_eq!(maven_coord_to_path("only:two"), None); + } +} diff --git a/src/net/forge.rs b/src/net/forge.rs new file mode 100644 index 0000000..1243d88 --- /dev/null +++ b/src/net/forge.rs @@ -0,0 +1,172 @@ +use std::collections::HashMap; +use std::path::Path; + +use serde::Deserialize; + +use crate::net::{download_file, HttpClient, NetError}; +use crate::tui::progress::set_action; + +const FORGE_PROMOTIONS_URL: &str = + "https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json"; +const FORGE_MAVEN_BASE: &str = "https://maven.minecraftforge.net/net/minecraftforge/forge"; + +#[derive(Debug, Deserialize)] +struct ForgePromotions { + promos: HashMap, +} + +/// Fetch available Forge loader versions for a given Minecraft game version. +/// +/// Queries the Forge promotions JSON and returns unique Forge version strings +/// matching the requested game version (e.g. `"47.2.20"` for game version `"1.20.1"`). +pub async fn fetch_forge_versions( + client: &HttpClient, + game_version: &str, +) -> Result, NetError> { + let response = match client.inner().get(FORGE_PROMOTIONS_URL).send().await { + Ok(r) => r, + Err(e) => { + tracing::error!("GET {} failed: {}", FORGE_PROMOTIONS_URL, e); + return Err(NetError::Http(e)); + } + }; + + if !response.status().is_success() { + let status = response.status().as_u16(); + tracing::error!("HTTP {} for {}", status, FORGE_PROMOTIONS_URL); + return Err(NetError::StatusError { + status, + url: FORGE_PROMOTIONS_URL.to_string(), + }); + } + + let promotions: ForgePromotions = match response.json().await { + Ok(p) => p, + Err(e) => { + tracing::error!("Failed to parse Forge promotions JSON: {}", e); + return Err(NetError::Http(e)); + } + }; + + let prefix = format!("{}-", game_version); + let mut versions: Vec = promotions + .promos + .iter() + .filter(|(key, _)| key.starts_with(&prefix)) + .map(|(_, value)| value.clone()) + .collect(); + + versions.sort(); + versions.dedup(); + Ok(versions) +} + +/// Download the Forge installer JAR for the given game + forge version combo. +/// +/// The installer JAR is saved to `dest`. Progress is reported via the TUI progress system. +pub async fn download_forge_installer( + client: &HttpClient, + game_version: &str, + forge_version: &str, + dest: &Path, +) -> Result<(), NetError> { + let url = format!( + "{}/{game_version}-{forge_version}/forge-{game_version}-{forge_version}-installer.jar", + FORGE_MAVEN_BASE, + game_version = game_version, + forge_version = forge_version, + ); + + set_action(format!( + "Downloading Forge {}-{}...", + game_version, forge_version + )); + + match download_file(client, &url, dest, |downloaded, total| { + crate::tui::progress::set_progress(downloaded, total); + }) + .await + { + Ok(()) => Ok(()), + Err(e) => { + tracing::error!("Failed to download Forge installer from {}: {}", url, e); + Err(e) + } + } +} + +/// Run the Forge installer JAR to install Forge into the instance directory. +/// +/// Requires a Java runtime. The installer is invoked with `--installClient` pointing +/// at the instance's `.minecraft` subdirectory. +pub async fn run_forge_installer( + installer_path: &Path, + instance_dir: &Path, + java_path: &str, +) -> Result<(), NetError> { + use tokio::process::Command; + + set_action("Running Forge installer..."); + + let output = match Command::new(java_path) + .arg("-jar") + .arg(installer_path) + .arg("--installClient") + .arg(instance_dir.join(".minecraft")) + .output() + .await + { + Ok(o) => o, + Err(e) => { + tracing::error!("Failed to launch Forge installer: {}", e); + return Err(NetError::Io(e)); + } + }; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + tracing::error!( + "Forge installer failed (exit {:?}): {} {}", + output.status.code(), + stderr, + stdout + ); + return Err(NetError::Parse(format!( + "Forge installer exited with {:?}", + output.status.code() + ))); + } + + Ok(()) +} + +/// Detect the path to a Java runtime. +/// +/// Checks `JAVA_HOME` first, then falls back to `"java"` assuming it is on `PATH`. +pub fn detect_java_path() -> String { + if let Ok(java_home) = std::env::var("JAVA_HOME") { + let path = std::path::Path::new(&java_home).join("bin").join("java"); + if path.exists() { + return path.to_string_lossy().to_string(); + } + } + "java".to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::HttpClient; + + #[tokio::test] + async fn test_fetch_versions() { + let client = HttpClient::new(); + match fetch_forge_versions(&client, "1.20.1").await { + Ok(versions) => { + assert!(!versions.is_empty(), "Should have Forge versions for 1.20.1"); + } + Err(e) => assert!(false, "fetch_forge_versions failed: {}", e), + } + } +} diff --git a/src/net/mod.rs b/src/net/mod.rs new file mode 100644 index 0000000..de5c449 --- /dev/null +++ b/src/net/mod.rs @@ -0,0 +1,116 @@ +pub mod fabric; +pub mod forge; +pub mod mojang; +pub mod neoforge; +pub mod quilt; + +use std::path::Path; +use reqwest::Client; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum NetError { + #[error("HTTP request failed: {0}")] + Http(#[from] reqwest::Error), + #[error("IO error: {0}")] + Io(#[from] std::io::Error), + #[error("Parse error: {0}")] + Parse(String), + #[error("Server returned error status {status}: {url}")] + StatusError { status: u16, url: String }, +} + +pub struct HttpClient { + inner: Client, +} + +impl HttpClient { + pub fn new() -> Self { + match Client::builder() + .user_agent("mcl/0.1.0 (Minecraft Launcher)") + .timeout(std::time::Duration::from_secs(30)) + .build() + { + Ok(client) => HttpClient { inner: client }, + Err(e) => { + tracing::error!("Failed to build HTTP client: {}", e); + HttpClient { inner: Client::new() } + } + } + } + + pub fn inner(&self) -> &Client { + &self.inner + } +} + +/// Download a file from `url` to `dest`, calling `progress_cb(bytes_downloaded, total_bytes)` as chunks arrive. +/// `total_bytes` is 0 if Content-Length is unknown. +pub async fn download_file( + client: &HttpClient, + url: &str, + dest: &Path, + progress_cb: impl Fn(u64, u64), +) -> Result<(), NetError> { + use tokio::io::AsyncWriteExt; + + let response = match client.inner().get(url).send().await { + Ok(r) => r, + Err(e) => { + tracing::error!("GET {} failed: {}", url, e); + return Err(NetError::Http(e)); + } + }; + + if !response.status().is_success() { + let status = response.status().as_u16(); + tracing::error!("HTTP {} for {}", status, url); + return Err(NetError::StatusError { status, url: url.to_string() }); + } + + let total = response.content_length().unwrap_or(0); + + if let Some(parent) = dest.parent() { + match tokio::fs::create_dir_all(parent).await { + Ok(_) => {} + Err(e) => { + tracing::error!("Failed to create directory {}: {}", parent.display(), e); + return Err(NetError::Io(e)); + } + } + } + + let mut file = match tokio::fs::File::create(dest).await { + Ok(f) => f, + Err(e) => { + tracing::error!("Failed to create file {}: {}", dest.display(), e); + return Err(NetError::Io(e)); + } + }; + + let mut downloaded: u64 = 0; + let mut stream = response; + + loop { + match stream.chunk().await { + Ok(Some(chunk)) => { + match file.write_all(&chunk).await { + Ok(_) => {} + Err(e) => { + tracing::error!("Failed to write chunk to {}: {}", dest.display(), e); + return Err(NetError::Io(e)); + } + } + downloaded += chunk.len() as u64; + progress_cb(downloaded, total); + } + Ok(None) => break, + Err(e) => { + tracing::error!("Failed to read response chunk from {}: {}", url, e); + return Err(NetError::Http(e)); + } + } + } + + Ok(()) +} diff --git a/src/net/mojang.rs b/src/net/mojang.rs new file mode 100644 index 0000000..b93db2e --- /dev/null +++ b/src/net/mojang.rs @@ -0,0 +1,390 @@ +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, +}; + +use serde::Deserialize; +use tokio::task::JoinSet; + +use super::{download_file, HttpClient, NetError}; +use crate::tui::progress::{clear, set_action, set_progress, set_sub_action}; + +const MANIFEST_URL: &str = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"; +const ASSETS_BASE_URL: &str = "https://resources.download.minecraft.net"; +const MAX_CONCURRENT_DOWNLOADS: usize = 10; + +#[derive(Debug, Clone, Deserialize)] +pub struct VersionManifest { + pub latest: LatestVersions, + pub versions: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct LatestVersions { + pub release: String, + pub snapshot: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct VersionEntry { + pub id: String, + #[serde(rename = "type")] + pub version_type: String, + pub url: String, + pub sha1: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VersionMeta { + pub id: String, + pub main_class: String, + pub asset_index: AssetIndex, + pub downloads: VersionDownloads, + pub libraries: Vec, + pub java_version: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct AssetIndex { + pub id: String, + pub url: String, + pub sha1: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct VersionDownloads { + pub client: Download, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Download { + pub url: String, + pub sha1: String, + pub size: u64, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Library { + pub name: String, + pub downloads: LibraryDownloads, + pub rules: Option>, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct LibraryDownloads { + pub artifact: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Artifact { + pub url: String, + pub path: String, + pub sha1: String, + pub size: u64, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Rule { + pub action: String, + pub os: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct OsRule { + pub name: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct JavaVersion { + pub major_version: u32, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct AssetIndexContent { + pub objects: HashMap, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct AssetObject { + pub hash: String, + pub size: u64, +} + +pub async fn fetch_version_manifest(client: &HttpClient) -> Result { + fetch_json(client, MANIFEST_URL).await +} + +pub async fn fetch_version_meta( + client: &HttpClient, + entry: &VersionEntry, +) -> Result { + fetch_json(client, &entry.url).await +} + +pub async fn download_client_jar( + client: &HttpClient, + meta: &VersionMeta, + instance_dir: &Path, +) -> Result<(), NetError> { + set_action("Downloading Minecraft client..."); + + let jar_path = instance_dir + .join(".minecraft") + .join("versions") + .join(&meta.id) + .join(format!("{}.jar", meta.id)); + + let result = download_file(client, &meta.downloads.client.url, &jar_path, |current, total| { + set_progress(current, total); + }) + .await; + + clear(); + result +} + +pub async fn download_libraries( + client: &HttpClient, + meta: &VersionMeta, + instance_dir: &Path, +) -> Result<(), NetError> { + set_action("Downloading libraries..."); + + let mut downloads = Vec::new(); + for library in &meta.libraries { + if !library_allowed_for_current_os(library) { + continue; + } + + let artifact = match &library.downloads.artifact { + Some(artifact) => artifact, + None => continue, + }; + + let destination = instance_dir + .join(".minecraft") + .join("libraries") + .join(&artifact.path); + + downloads.push((artifact.url.clone(), destination, artifact.path.clone())); + } + + let result = run_parallel_downloads(client, downloads, false).await; + clear(); + result +} + +pub async fn download_assets( + client: &HttpClient, + meta: &VersionMeta, + instance_dir: &Path, +) -> Result<(), NetError> { + set_action("Downloading assets..."); + + let asset_index = match fetch_json::(client, &meta.asset_index.url).await { + Ok(index) => index, + Err(e) => { + clear(); + return Err(e); + } + }; + + let mut downloads = Vec::new(); + for object in asset_index.objects.values() { + if object.hash.len() < 2 { + let message = format!("Invalid asset hash for version {}: {}", meta.id, object.hash); + tracing::error!("{}", message); + clear(); + return Err(NetError::Parse(message)); + } + + let prefix = &object.hash[..2]; + let url = format!("{}/{}/{}", ASSETS_BASE_URL, prefix, object.hash); + let destination = instance_dir + .join(".minecraft") + .join("assets") + .join("objects") + .join(prefix) + .join(&object.hash); + + downloads.push((url, destination, object.hash.clone())); + } + + let result = run_parallel_downloads(client, downloads, true).await; + clear(); + result +} + +async fn fetch_json(client: &HttpClient, url: &str) -> Result +where + T: for<'de> Deserialize<'de>, +{ + let response = match client.inner().get(url).send().await { + Ok(response) => response, + Err(e) => { + tracing::error!("Failed to fetch {}: {}", url, e); + return Err(NetError::Http(e)); + } + }; + + if !response.status().is_success() { + let status = response.status().as_u16(); + tracing::error!("HTTP {} from {}", status, url); + return Err(NetError::StatusError { + status, + url: url.to_string(), + }); + } + + match response.json::().await { + Ok(data) => Ok(data), + Err(e) => { + tracing::error!("Failed to parse JSON from {}: {}", url, e); + Err(NetError::Http(e)) + } + } +} + +fn library_allowed_for_current_os(library: &Library) -> bool { + let rules = match &library.rules { + Some(rules) => rules, + None => return true, + }; + + let current_os = mojang_os_name(); + let mut allowed = false; + + for rule in rules { + let matches_os = match &rule.os { + Some(os_rule) => match &os_rule.name { + Some(name) => name == current_os, + None => true, + }, + None => true, + }; + + if !matches_os { + continue; + } + + if rule.action == "disallow" { + return false; + } + + if rule.action == "allow" { + allowed = true; + } + } + + allowed +} + +fn mojang_os_name() -> &'static str { + match std::env::consts::OS { + "macos" => "osx", + other => other, + } +} + +async fn run_parallel_downloads( + client: &HttpClient, + downloads: Vec<(String, PathBuf, String)>, + report_count_progress: bool, +) -> Result<(), NetError> { + let total_downloads = downloads.len() as u64; + let completed = Arc::new(AtomicU64::new(0)); + let mut queue = downloads.into_iter(); + let mut set = JoinSet::new(); + + for _ in 0..MAX_CONCURRENT_DOWNLOADS { + let next_job = match queue.next() { + Some(job) => job, + None => break, + }; + + spawn_download_task(&mut set, client, next_job); + } + + let mut first_error: Option = None; + + while let Some(join_result) = set.join_next().await { + match join_result { + Ok(Ok(label)) => { + let finished = completed.fetch_add(1, Ordering::SeqCst) + 1; + if report_count_progress { + set_progress(finished, total_downloads); + } + set_sub_action(label); + } + Ok(Err(e)) => { + tracing::error!("Download failed: {}", e); + if first_error.is_none() { + first_error = Some(e); + } + } + Err(e) => { + tracing::error!("Task panicked: {}", e); + if first_error.is_none() { + first_error = Some(NetError::Parse(format!("Join error: {}", e))); + } + } + } + + let next_job = match queue.next() { + Some(job) => job, + None => continue, + }; + + spawn_download_task(&mut set, client, next_job); + } + + match first_error { + Some(e) => Err(e), + None => Ok(()), + } +} + +fn spawn_download_task( + set: &mut JoinSet>, + client: &HttpClient, + job: (String, PathBuf, String), +) { + let (url, destination, label) = job; + let task_client = HttpClient { + inner: client.inner().clone(), + }; + + set.spawn(async move { + let label_for_progress = label.clone(); + let result = download_file(&task_client, &url, &destination, |_current, _total| {}).await; + + match result { + Ok(()) => Ok(label_for_progress), + Err(e) => Err(e), + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::HttpClient; + + #[tokio::test] + async fn test_fetch_manifest_contains_1_20_1() { + let client = HttpClient::new(); + match fetch_version_manifest(&client).await { + Ok(manifest) => { + let found = manifest.versions.iter().any(|v| v.id == "1.20.1"); + assert!(found, "1.20.1 should be in the manifest"); + } + Err(e) => assert!(false, "fetch_version_manifest failed: {}", e), + } + } +} diff --git a/src/net/neoforge.rs b/src/net/neoforge.rs new file mode 100644 index 0000000..7c11114 --- /dev/null +++ b/src/net/neoforge.rs @@ -0,0 +1,200 @@ +use std::path::Path; + +use serde::Deserialize; + +use crate::net::{download_file, HttpClient, NetError}; +use crate::tui::progress::set_action; + +const NEOFORGE_MAVEN_BASE: &str = + "https://maven.neoforged.net/releases/net/neoforged/neoforge"; +const NEOFORGE_API_BASE: &str = + "https://maven.neoforged.net/api/maven/versions/releases/net/neoforged/neoforge"; + +#[derive(Debug, Deserialize)] +struct NeoForgeMavenVersions { + versions: Vec, +} + +/// Map a Minecraft game version like "1.21" or "1.20.4" to the NeoForge version +/// prefix (e.g. "21.0." or "20.4."). NeoForge versions encode the MC version as +/// `MAJOR.MINOR.` where MAJOR is the MC major-minor (20 for 1.20.x, 21 for 1.21.x) +/// and MINOR is the MC patch (0 if absent, e.g. "1.21" → "21.0."). +fn game_version_to_neoforge_prefix(game_version: &str) -> Option { + let parts: Vec<&str> = game_version.split('.').collect(); + match parts.as_slice() { + // "1.21" → prefix "21.0." + [_major, minor] => Some(format!("{}.0.", minor)), + // "1.20.4" → prefix "20.4." + [_major, minor, patch] => Some(format!("{}.{}.", minor, patch)), + _ => None, + } +} + +pub async fn fetch_neoforge_versions( + client: &HttpClient, + game_version: &str, +) -> Result, NetError> { + let prefix = match game_version_to_neoforge_prefix(game_version) { + Some(p) => p, + None => { + tracing::error!( + "Cannot map game version '{}' to NeoForge version prefix", + game_version + ); + return Err(NetError::Parse(format!( + "Invalid game version for NeoForge: {}", + game_version + ))); + } + }; + + let response = match client.inner().get(NEOFORGE_API_BASE).send().await { + Ok(r) => r, + Err(e) => { + tracing::error!("GET {} failed: {}", NEOFORGE_API_BASE, e); + return Err(NetError::Http(e)); + } + }; + + if !response.status().is_success() { + let status = response.status().as_u16(); + tracing::error!("HTTP {} for {}", status, NEOFORGE_API_BASE); + return Err(NetError::StatusError { + status, + url: NEOFORGE_API_BASE.to_string(), + }); + } + + let maven_versions: NeoForgeMavenVersions = match response.json().await { + Ok(v) => v, + Err(e) => { + tracing::error!("Failed to parse NeoForge maven versions: {}", e); + return Err(NetError::Http(e)); + } + }; + + let versions: Vec = maven_versions + .versions + .into_iter() + .filter(|v| v.starts_with(&prefix) && !v.contains("-beta") && !v.contains("-alpha")) + .collect(); + + Ok(versions) +} + +pub async fn download_neoforge_installer( + client: &HttpClient, + neoforge_version: &str, + dest: &Path, +) -> Result<(), NetError> { + let url = format!( + "{}/{}/neoforge-{}-installer.jar", + NEOFORGE_MAVEN_BASE, neoforge_version, neoforge_version + ); + + set_action(format!("Downloading NeoForge {}...", neoforge_version)); + + match download_file(client, &url, dest, |downloaded, total| { + crate::tui::progress::set_progress(downloaded, total); + }) + .await + { + Ok(()) => Ok(()), + Err(e) => { + tracing::error!( + "Failed to download NeoForge installer from {}: {}", + url, e + ); + Err(e) + } + } +} + +pub async fn run_neoforge_installer( + installer_path: &Path, + instance_dir: &Path, + java_path: &str, +) -> Result<(), NetError> { + use tokio::process::Command; + + set_action("Running NeoForge installer..."); + + let output = match Command::new(java_path) + .arg("-jar") + .arg(installer_path) + .arg("--installClient") + .arg(instance_dir.join(".minecraft")) + .output() + .await + { + Ok(o) => o, + Err(e) => { + tracing::error!("Failed to launch NeoForge installer: {}", e); + return Err(NetError::Io(e)); + } + }; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + tracing::error!( + "NeoForge installer failed (exit {:?}): {} {}", + output.status.code(), + stderr, + stdout + ); + return Err(NetError::Parse(format!( + "NeoForge installer exited with {:?}", + output.status.code() + ))); + } + + Ok(()) +} + +pub fn detect_java_path() -> String { + if let Ok(java_home) = std::env::var("JAVA_HOME") { + let path = std::path::Path::new(&java_home).join("bin").join("java"); + if path.exists() { + return path.to_string_lossy().to_string(); + } + } + "java".to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::HttpClient; + + #[tokio::test] + async fn test_fetch_versions() { + let client = HttpClient::new(); + match fetch_neoforge_versions(&client, "1.21").await { + Ok(versions) => { + assert!( + !versions.is_empty(), + "Should have NeoForge versions for 1.21" + ); + } + Err(e) => assert!(false, "fetch_neoforge_versions failed: {}", e), + } + } + + #[test] + fn test_game_version_to_neoforge_prefix() { + assert_eq!( + game_version_to_neoforge_prefix("1.21"), + Some("21.0.".to_string()) + ); + assert_eq!( + game_version_to_neoforge_prefix("1.20.4"), + Some("20.4.".to_string()) + ); + assert_eq!( + game_version_to_neoforge_prefix("1.21.1"), + Some("21.1.".to_string()) + ); + assert_eq!(game_version_to_neoforge_prefix("invalid"), None); + } +} diff --git a/src/net/quilt.rs b/src/net/quilt.rs new file mode 100644 index 0000000..f44ccb5 --- /dev/null +++ b/src/net/quilt.rs @@ -0,0 +1,196 @@ +use std::path::Path; + +use serde::Deserialize; + +use crate::net::{download_file, HttpClient, NetError}; +use crate::tui::progress::set_sub_action; + +const QUILT_META_BASE: &str = "https://meta.quiltmc.org/v3"; + +#[derive(Debug, Clone, Deserialize)] +pub struct QuiltLoaderVersion { + pub loader: QuiltVersion, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct QuiltVersion { + pub version: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct QuiltProfile { + pub id: String, + pub main_class: String, + pub libraries: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct QuiltLibrary { + pub name: String, + pub url: String, +} + +/// `org.quiltmc:quilt-loader:0.20.0` → `org/quiltmc/quilt-loader/0.20.0/quilt-loader-0.20.0.jar` +fn maven_coord_to_path(coord: &str) -> Option { + let parts: Vec<&str> = coord.split(':').collect(); + match parts.as_slice() { + [group, artifact, version] => { + let group_path = group.replace('.', "/"); + Some(format!( + "{}/{}/{}/{}-{}.jar", + group_path, artifact, version, artifact, version + )) + } + _ => None, + } +} + +pub async fn fetch_quilt_versions( + client: &HttpClient, + game_version: &str, +) -> Result, NetError> { + let url = format!("{}/versions/loader/{}", QUILT_META_BASE, game_version); + + let response = match client.inner().get(&url).send().await { + Ok(r) => r, + Err(e) => { + tracing::error!("Quilt meta GET {} failed: {}", url, e); + return Err(NetError::Http(e)); + } + }; + + if !response.status().is_success() { + let status = response.status().as_u16(); + tracing::error!("Quilt meta HTTP {} for {}", status, url); + return Err(NetError::StatusError { + status, + url: url.clone(), + }); + } + + let versions: Vec = match response.json().await { + Ok(v) => v, + Err(e) => { + tracing::error!("Failed to parse Quilt loader versions: {}", e); + return Err(NetError::Http(e)); + } + }; + + Ok(versions) +} + +pub async fn fetch_quilt_profile( + client: &HttpClient, + game_version: &str, + loader_version: &str, +) -> Result { + let url = format!( + "{}/versions/loader/{}/{}/profile/json", + QUILT_META_BASE, game_version, loader_version + ); + + let response = match client.inner().get(&url).send().await { + Ok(r) => r, + Err(e) => { + tracing::error!("Quilt profile GET {} failed: {}", url, e); + return Err(NetError::Http(e)); + } + }; + + if !response.status().is_success() { + let status = response.status().as_u16(); + tracing::error!("Quilt profile HTTP {} for {}", status, url); + return Err(NetError::StatusError { + status, + url: url.clone(), + }); + } + + let profile: QuiltProfile = match response.json().await { + Ok(p) => p, + Err(e) => { + tracing::error!("Failed to parse Quilt profile: {}", e); + return Err(NetError::Http(e)); + } + }; + + Ok(profile) +} + +pub async fn download_quilt_libraries( + client: &HttpClient, + profile: &QuiltProfile, + instance_dir: &Path, +) -> Result<(), NetError> { + let libraries_dir = instance_dir.join(".minecraft").join("libraries"); + + for lib in &profile.libraries { + let maven_path = match maven_coord_to_path(&lib.name) { + Some(p) => p, + None => { + tracing::error!( + "Invalid Maven coordinate in Quilt profile: {}", + lib.name + ); + return Err(NetError::Parse(format!( + "Invalid Maven coordinate: {}", + lib.name + ))); + } + }; + + let dest = libraries_dir.join(&maven_path); + + if dest.exists() { + tracing::debug!("Quilt library already exists: {}", lib.name); + continue; + } + + let base_url = lib.url.trim_end_matches('/'); + let download_url = format!("{}/{}", base_url, maven_path); + + set_sub_action(&lib.name); + tracing::info!("Downloading Quilt library: {}", lib.name); + + match download_file(client, &download_url, &dest, |_, _| {}).await { + Ok(()) => {} + Err(e) => { + tracing::error!( + "Failed to download Quilt library {}: {}", + lib.name, e + ); + return Err(e); + } + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::net::HttpClient; + + #[tokio::test] + async fn test_fetch_versions() { + let client = HttpClient::new(); + match fetch_quilt_versions(&client, "1.20.1").await { + Ok(versions) => { + assert!(!versions.is_empty(), "Should have Quilt versions for 1.20.1"); + } + Err(e) => assert!(false, "fetch_quilt_versions failed: {}", e), + } + } + + #[test] + fn test_maven_coord_to_path() { + assert_eq!( + maven_coord_to_path("org.quiltmc:quilt-loader:0.20.0"), + Some("org/quiltmc/quilt-loader/0.20.0/quilt-loader-0.20.0.jar".to_string()) + ); + assert_eq!(maven_coord_to_path("invalid"), None); + assert_eq!(maven_coord_to_path("only:two"), None); + } +}