From 9346ac04ad4120b8ae7dfa926d508ca27eea0da3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:22:39 +0200 Subject: [PATCH] Mod browser (2/3): install, update and remove, with `horizon-launcher mods` browser::installed installs a pack and its required dependencies into resourcepacks/ or shaderpacks/, every file checked before any download (a dependency that is a Java mod stops it) and checksum-verified on the way in; mod-browser.json records source, version, file and checksum. Update swaps the file, remove deletes only what the browser installed (a player's own file of the same name is never overwritten). A modpack is downloaded, checked, and imported through the Modpacks page's pipeline. The CLI gains `mods list|search|install|update|remove`. Co-Authored-By: Claude Opus 5.5 --- docs/mod-browser.md | 25 +++ launcher/README.md | 5 + launcher/src/browser.rs | 23 ++- launcher/src/browser/installed.rs | 260 ++++++++++++++++++++++++ launcher/src/browser/installed/tests.rs | 252 +++++++++++++++++++++++ launcher/src/cli.rs | 211 +++++++++++++++++++ 6 files changed, 774 insertions(+), 2 deletions(-) create mode 100644 launcher/src/browser/installed.rs create mode 100644 launcher/src/browser/installed/tests.rs diff --git a/docs/mod-browser.md b/docs/mod-browser.md index 888a64bb8..b7a9176c5 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -30,6 +30,31 @@ never offered for install. else removes the part file and installs nothing. - A file whose source lists no checksum is refused. +## Installing, updating, removing + +`mod-browser.json` beside `options.txt` lists every file the browser installed: its source, project, version, file +and the checksum it was checked against. The browser replaces or removes only the files it lists; a file of the +same name the player put there is never overwritten. + +- **Install** picks the newest version that runs, then its required dependencies, checked before any download: a + dependency that isn't a pack Horizon loads (a Java mod) stops the install. Dependencies go in first. A resource + pack still has to be turned on in the game's Resource Packs screen, and a shader pack in Video Settings > Shader + Packs, as in vanilla and Iris. +- **Update** installs the newer version and removes the old file. +- **Remove** deletes the file and its entry. Packs installed as dependencies stay. +- **A modpack** is downloaded (checked the same way) into `ports/downloads/` and imported on the Modpacks page, + which says what of it Horizon runs and ports it. + +From a terminal (or an agent): + +```sh +horizon-launcher mods search faithful # --kind resource|shader|modpack, --everything, --source +horizon-launcher mods install faithful-32x # id or slug; a modpack is imported +horizon-launcher mods list # --json +horizon-launcher mods update [faithful-32x] [--check] +horizon-launcher mods remove faithful-32x +``` + ## Sources **Modrinth.** The public API (`api.modrinth.com/v2`) needs no key. The launcher names itself in its user agent, as diff --git a/launcher/README.md b/launcher/README.md index d6168dbb4..e95d72649 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -139,6 +139,11 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher modpack port [--from ] [--version ] get the jars and carry them over horizon-launcher modpack play [--version ] play it as its own profile horizon-launcher modpack remove + horizon-launcher mods [list] what the mod browser installed (docs/mod-browser.md) + horizon-launcher mods search [--kind resource|shader|modpack] [--everything] [--source modrinth|curseforge] + horizon-launcher mods install checksum checked, with what it needs; a modpack is imported + horizon-launcher mods update [] [--check] + horizon-launcher mods remove horizon-launcher servers [list] the servers hosted from the launcher, and whether they run horizon-launcher servers create [--name N] [--seed S | --copy-world DIR] [--mode M] [--difficulty D] [--max-players N] [--open] [--check-accounts] [--player NAME]... --accept-eula diff --git a/launcher/src/browser.rs b/launcher/src/browser.rs index 7010024f4..49ec1e696 100644 --- a/launcher/src/browser.rs +++ b/launcher/src/browser.rs @@ -7,14 +7,18 @@ //! page). Java mod jars don't run in Horizon (docs/mods.md), so they are never searched. pub mod curseforge; pub mod download; +pub mod installed; pub mod modrinth; +use serde::{Deserialize, Serialize}; + /// The Minecraft version Horizon plays. A version port updates it with the other `"26.3"` sites /// (docs/version-ports.md). pub const GAME: &str = "26.3"; /// What a project is, as far as Horizon is concerned. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] pub enum Kind { ResourcePack, ShaderPack, @@ -43,7 +47,8 @@ impl Kind { } /// Where a project comes from. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] pub enum SourceId { Modrinth, CurseForge, @@ -194,6 +199,15 @@ pub trait Source: Send + Sync { fn project(&self, id: &str) -> Result; /// Versions, newest first. fn versions(&self, project: &Project) -> Result, String>; + /// Downloads one of its files into `folder`, checked ([`download::fetch`]). + fn fetch( + &self, + file: &FileRef, + folder: &std::path::Path, + progress: &dyn Fn(f32), + ) -> Result { + download::fetch(file, folder, progress) + } } /// The sources this launcher can use: Modrinth always, CurseForge when it has an API key. @@ -205,6 +219,11 @@ pub fn sources() -> Vec> { all } +/// The source of that id, when this launcher can use it. +pub fn source(id: SourceId) -> Option> { + sources().into_iter().find(|s| s.id() == id) +} + /// The loaders a Java shader pack may name that Horizon translates. const SHADER_LOADERS: [&str; 2] = ["iris", "optifine"]; diff --git a/launcher/src/browser/installed.rs b/launcher/src/browser/installed.rs new file mode 100644 index 000000000..d1aac1af5 --- /dev/null +++ b/launcher/src/browser/installed.rs @@ -0,0 +1,260 @@ +//! What the browser installed into the game folder, and installing, updating and removing it. +//! +//! `mod-browser.json` beside `options.txt` lists each file the browser put in `resourcepacks/` +//! or `shaderpacks/`: where it came from, its version and its checksum. Files the player put +//! there themselves are never touched: the browser only replaces or removes what it lists. +use super::{pick, safe_name, Kind, Project, Source, SourceId, Support, Version}; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; + +const MANIFEST: &str = "mod-browser.json"; +/// How deep required dependencies are followed. +const MAX_DEPTH: usize = 4; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Entry { + pub source: SourceId, + pub project: String, + pub slug: String, + pub title: String, + pub kind: Kind, + pub version: String, + pub number: String, + /// Relative to the game folder: `resourcepacks/`. + pub file: String, + /// The checksum the download was checked against: `SHA-512:`. + pub checksum: String, + pub page: String, + /// Installed because another pack needs it. + #[serde(default)] + pub dependency: bool, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Installed { + pub entries: Vec, +} + +impl Installed { + pub fn load(home: &Path) -> Self { + fs::read_to_string(home.join(MANIFEST)) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + + pub fn save(&self, home: &Path) -> Result<(), String> { + let path = home.join(MANIFEST); + let part = home.join(format!(".{MANIFEST}.part")); + let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; + fs::create_dir_all(home).map_err(|e| format!("{}: {e}", home.display()))?; + fs::write(&part, text).map_err(|e| format!("{}: {e}", part.display()))?; + fs::rename(&part, &path).map_err(|e| format!("{}: {e}", path.display())) + } + + pub fn find(&self, source: SourceId, project: &str) -> Option<&Entry> { + self.entries + .iter() + .find(|e| e.source == source && e.project == project) + } + + /// By project id or slug, as the CLI takes them. + pub fn lookup(&self, name: &str) -> Option<&Entry> { + self.entries + .iter() + .find(|e| e.project == name || e.slug == name) + } +} + +/// One file to install: the project, the version chosen and why it was pulled in. +#[derive(Clone, Debug)] +pub struct Step { + pub project: Project, + pub version: Version, + pub dependency: bool, +} + +/// What installing `project` takes, dependencies first, checked before any byte is downloaded: +/// every file runs in Horizon and has a version to install. +pub fn plan(source: &dyn Source, project: &Project, everything: bool) -> Result, String> { + if project.kind.folder().is_none() { + return Err(format!( + "{} is a modpack: it is imported on the Modpacks page.", + project.title + )); + } + let mut steps = Vec::new(); + add(source, project.clone(), everything, false, 0, &mut steps)?; + Ok(steps) +} + +fn add( + source: &dyn Source, + project: Project, + everything: bool, + dependency: bool, + depth: usize, + steps: &mut Vec, +) -> Result<(), String> { + if steps.iter().any(|s| s.project.id == project.id) { + return Ok(()); + } + if depth > MAX_DEPTH { + return Err(format!("{}'s dependencies go too deep.", project.title)); + } + if let Support::No(why) = project.support() { + return Err(format!("{} doesn't run in Horizon: {why}", project.title)); + } + let versions = source.versions(&project)?; + let Some(version) = pick(project.kind, &versions, everything).cloned() else { + return Err(match versions.iter().find_map(|v| v.blocked.clone()) { + Some(why) => format!("{} can't be installed from here: {why}", project.title), + None => format!("{} has no version Horizon runs.", project.title), + }); + }; + for id in &version.required { + let needed = source.project(id).map_err(|_| { + format!( + "{} needs {id} on {}, which isn't a pack Horizon loads (a Java mod?).", + project.title, + source.id().label() + ) + })?; + if needed.kind.folder().is_none() { + return Err(format!( + "{} needs the modpack {}.", + project.title, needed.title + )); + } + add(source, needed, everything, true, depth + 1, steps)?; + } + steps.push(Step { + project, + version, + dependency, + }); + Ok(()) +} + +/// Installs `project` (and what it needs) into the game folder `home`. A project already +/// installed is updated to the version chosen. `progress` gets a line per file and the fraction. +pub fn install( + source: &dyn Source, + project: &Project, + everything: bool, + home: &Path, + progress: &dyn Fn(&str, f32), +) -> Result, String> { + let steps = plan(source, project, everything)?; + let mut installed = Installed::load(home); + let mut done = Vec::new(); + for step in steps { + let p = &step.project; + let old = installed.find(p.source, &p.id).cloned(); + if old.as_ref().is_some_and(|o| o.version == step.version.id) { + done.push(old.expect("checked")); + continue; + } + let file = step + .version + .file() + .expect("pick keeps versions with a file"); + let folder_name = p.kind.folder().expect("plan keeps folder kinds"); + let name = safe_name(&file.name) + .ok_or_else(|| format!("{:?} isn't a plain file name.", file.name))?; + let relative = format!("{folder_name}/{name}"); + let owner = installed.entries.iter().find(|e| e.file == relative); + let ours = owner.is_some_and(|e| e.source == p.source && e.project == p.id); + if home.join(&relative).exists() && !ours { + return Err(match owner { + Some(e) => format!( + "{relative} belongs to {}, installed from the browser.", + e.title + ), + None => format!( + "{relative} is already there and wasn't installed by the browser: move it \ + away first, or keep it." + ), + }); + } + let line = format!("{} {}", p.title, step.version.number); + let path = source.fetch(file, &home.join(folder_name), &|f| progress(&line, f))?; + let (algo, hash) = file.checksum().expect("fetch checks for one"); + if let Some(old) = &old { + if old.file != relative { + let _ = fs::remove_file(home.join(&old.file)); + } + } + let entry = Entry { + source: p.source, + project: p.id.clone(), + slug: p.slug.clone(), + title: p.title.clone(), + kind: p.kind, + version: step.version.id.clone(), + number: step.version.number.clone(), + file: relative, + checksum: format!("{algo}:{hash}"), + page: p.page.clone(), + // Asked for by the player once: it stays theirs. + dependency: step.dependency && old.as_ref().is_none_or(|o| o.dependency), + }; + debug_assert!(path.ends_with(name)); + installed + .entries + .retain(|e| !(e.source == p.source && e.project == p.id)); + installed.entries.push(entry.clone()); + installed.save(home)?; + done.push(entry); + } + Ok(done) +} + +/// Removes what the browser installed for `name` (a project id or slug): its file and its entry. +pub fn remove(home: &Path, name: &str) -> Result { + let mut installed = Installed::load(home); + let entry = installed + .lookup(name) + .cloned() + .ok_or_else(|| format!("{name} wasn't installed by the browser."))?; + match fs::remove_file(home.join(&entry.file)) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("{}: {e}", entry.file)), + } + installed + .entries + .retain(|e| !(e.source == entry.source && e.project == entry.project)); + installed.save(home)?; + Ok(entry) +} + +/// The newer version `entry` can be updated to, if any. +pub fn update_for(source: &dyn Source, entry: &Entry) -> Result, String> { + let project = source.project(&entry.project)?; + let versions = source.versions(&project)?; + Ok(pick(project.kind, &versions, true) + .filter(|v| v.id != entry.version) + .cloned()) +} + +/// Downloads a modpack's file, checked, into `folder` (kept there: the import reads it). +pub fn fetch_modpack( + source: &dyn Source, + project: &Project, + folder: &Path, + progress: &dyn Fn(f32), +) -> Result { + if project.kind != Kind::Modpack { + return Err(format!("{} isn't a modpack.", project.title)); + } + let versions = source.versions(project)?; + let version = pick(Kind::Modpack, &versions, true) + .ok_or_else(|| format!("{} has no file to download.", project.title))?; + let file = version.file().expect("pick keeps versions with a file"); + source.fetch(file, folder, progress) +} + +#[cfg(test)] +mod tests; diff --git a/launcher/src/browser/installed/tests.rs b/launcher/src/browser/installed/tests.rs new file mode 100644 index 000000000..33dc525ab --- /dev/null +++ b/launcher/src/browser/installed/tests.rs @@ -0,0 +1,252 @@ +use super::*; +use crate::browser::{download, FileRef, Query, GAME}; +use sha2::Digest; +use std::collections::HashMap; +use std::sync::Mutex; + +/// A source in memory: projects, their versions, and the bytes each file URL serves. +#[derive(Default)] +struct Fake { + projects: HashMap, + versions: Mutex>>, + bytes: Mutex>>, +} + +impl Source for Fake { + fn id(&self) -> SourceId { + SourceId::Modrinth + } + fn search(&self, _: &Query) -> Result, String> { + Ok(self.projects.values().cloned().collect()) + } + fn project(&self, id: &str) -> Result { + self.projects + .get(id) + .cloned() + .ok_or_else(|| "not a pack".into()) + } + fn versions(&self, p: &Project) -> Result, String> { + Ok(self + .versions + .lock() + .unwrap() + .get(&p.id) + .cloned() + .unwrap_or_default()) + } + fn fetch( + &self, + file: &FileRef, + folder: &Path, + progress: &dyn Fn(f32), + ) -> Result { + let body = self + .bytes + .lock() + .unwrap() + .get(&file.url) + .cloned() + .unwrap_or_default(); + download::save(file, &body[..], folder, progress) + } +} + +fn project(id: &str, kind: Kind) -> Project { + Project { + source: SourceId::Modrinth, + id: id.into(), + slug: format!("{id}-slug"), + title: format!("Pack {id}"), + summary: String::new(), + author: String::new(), + downloads: 0, + page: format!("https://modrinth.com/resourcepack/{id}-slug"), + icon: None, + license: "MIT".into(), + kind, + game_versions: vec![GAME.into()], + loaders: vec![if kind == Kind::ShaderPack { + "iris" + } else { + "minecraft" + } + .into()], + } +} + +impl Fake { + fn add(&mut self, p: Project) { + self.projects.insert(p.id.clone(), p); + } + /// A new newest version of `id`, its file serving `body`; `tamper` serves other bytes. + fn release(&self, id: &str, number: &str, needs: &[&str], body: &[u8], tamper: bool) { + let url = format!("https://cdn.modrinth.com/data/{id}/versions/{number}/{id}-{number}.zip"); + let file = FileRef { + url: url.clone(), + name: format!("{id}-{number}.zip"), + size: body.len() as u64, + sha512: Some( + sha2::Sha512::digest(body) + .iter() + .map(|b| format!("{b:02x}")) + .collect(), + ), + sha1: None, + primary: true, + }; + let version = Version { + id: format!("{id}@{number}"), + number: number.into(), + published: number.into(), + game_versions: vec![GAME.into()], + loaders: self.projects[id].loaders.clone(), + files: vec![file], + required: needs.iter().map(|s| s.to_string()).collect(), + blocked: None, + }; + let mut served = body.to_vec(); + if tamper { + served[0] ^= 1; + } + self.bytes.lock().unwrap().insert(url, served); + let mut versions = self.versions.lock().unwrap(); + versions.entry(id.into()).or_default().insert(0, version); + } +} + +fn home(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("horizon-installed-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +const NONE: &dyn Fn(&str, f32) = &|_, _| {}; + +#[test] +fn installs_with_dependencies_then_updates_and_removes() { + let home = home("cycle"); + let mut fake = Fake::default(); + fake.add(project("base", Kind::ResourcePack)); + fake.add(project("addon", Kind::ResourcePack)); + fake.release("base", "1", &[], b"base pack", false); + fake.release("addon", "1", &["base"], b"addon pack", false); + let addon = fake.project("addon").unwrap(); + + let done = install(&fake, &addon, false, &home, NONE).unwrap(); + let files: Vec<&str> = done.iter().map(|e| e.file.as_str()).collect(); + assert_eq!( + files, + ["resourcepacks/base-1.zip", "resourcepacks/addon-1.zip"] + ); + assert!(done[0].dependency && !done[1].dependency); + assert!(done[1].checksum.starts_with("SHA-512:")); + assert_eq!( + fs::read(home.join("resourcepacks/addon-1.zip")).unwrap(), + b"addon pack" + ); + assert_eq!(Installed::load(&home).entries.len(), 2); + + // Installing again with nothing new downloads nothing. + fs::remove_file(home.join("resourcepacks/base-1.zip")).unwrap(); + install(&fake, &addon, false, &home, NONE).unwrap(); + assert!(!home.join("resourcepacks/base-1.zip").exists()); + + // An update replaces the old file. + fake.release("addon", "2", &["base"], b"addon pack v2", false); + let entry = Installed::load(&home).lookup("addon").cloned().unwrap(); + assert_eq!(update_for(&fake, &entry).unwrap().unwrap().number, "2"); + install(&fake, &addon, false, &home, NONE).unwrap(); + assert!(!home.join("resourcepacks/addon-1.zip").exists()); + assert_eq!( + fs::read(home.join("resourcepacks/addon-2.zip")).unwrap(), + b"addon pack v2" + ); + let entry = Installed::load(&home) + .lookup("addon-slug") + .cloned() + .unwrap(); + assert_eq!(entry.number, "2"); + assert!(update_for(&fake, &entry).unwrap().is_none()); + + let removed = remove(&home, "addon").unwrap(); + assert_eq!(removed.project, "addon"); + assert!(!home.join("resourcepacks/addon-2.zip").exists()); + assert!(remove(&home, "addon").is_err()); + assert_eq!(Installed::load(&home).entries.len(), 1); + fs::remove_dir_all(&home).unwrap(); +} + +#[test] +fn nothing_is_installed_when_a_check_fails() { + let home = home("refuse"); + let mut fake = Fake::default(); + fake.add(project("good", Kind::ResourcePack)); + fake.add(project("bad", Kind::ResourcePack)); + fake.add(project("needs-mod", Kind::ResourcePack)); + fake.release("good", "1", &[], b"good", false); + fake.release("bad", "1", &[], b"tampered", true); + fake.release("needs-mod", "1", &["sodium"], b"x", false); + + let e = install(&fake, &fake.project("bad").unwrap(), false, &home, NONE).unwrap_err(); + assert!(e.contains("checksum doesn't match"), "{e}"); + let e = install( + &fake, + &fake.project("needs-mod").unwrap(), + false, + &home, + NONE, + ) + .unwrap_err(); + assert!(e.contains("needs sodium"), "{e}"); + assert!( + !home.join("resourcepacks").exists() + || fs::read_dir(home.join("resourcepacks")).unwrap().count() == 0 + ); + assert!(Installed::load(&home).entries.is_empty()); + + // The player's own file of the same name is never replaced. + fs::create_dir_all(home.join("resourcepacks")).unwrap(); + fs::write(home.join("resourcepacks/good-1.zip"), b"mine").unwrap(); + let e = install(&fake, &fake.project("good").unwrap(), false, &home, NONE).unwrap_err(); + assert!(e.contains("wasn't installed by the browser"), "{e}"); + assert_eq!( + fs::read(home.join("resourcepacks/good-1.zip")).unwrap(), + b"mine" + ); + assert!(remove(&home, "good").is_err()); + assert!(home.join("resourcepacks/good-1.zip").exists()); + + // What doesn't run is refused before anything is asked for. + let mut canvas = project("canvas", Kind::ShaderPack); + canvas.loaders = vec!["canvas".into()]; + fake.add(canvas.clone()); + assert!(install(&fake, &canvas, true, &home, NONE) + .unwrap_err() + .contains("doesn't run")); + let pack = project("pack", Kind::Modpack); + assert!(plan(&fake, &pack, false) + .unwrap_err() + .contains("Modpacks page")); + fs::remove_dir_all(&home).unwrap(); +} + +#[test] +fn shader_packs_go_to_their_folder_and_modpacks_download_checked() { + let home = home("kinds"); + let mut fake = Fake::default(); + fake.add(project("bsl", Kind::ShaderPack)); + fake.release("bsl", "10", &[], b"shaders", false); + install(&fake, &fake.project("bsl").unwrap(), false, &home, NONE).unwrap(); + assert!(home.join("shaderpacks/bsl-10.zip").is_file()); + + fake.add(project("atm", Kind::Modpack)); + fake.release("atm", "1", &[], b"mrpack", false); + let downloads = home.join("downloads"); + let path = fetch_modpack(&fake, &fake.project("atm").unwrap(), &downloads, &|_| {}).unwrap(); + assert_eq!(fs::read(path).unwrap(), b"mrpack"); + fake.release("atm", "2", &[], b"mrpack 2", true); + assert!(fetch_modpack(&fake, &fake.project("atm").unwrap(), &downloads, &|_| {}).is_err()); + assert!(!downloads.join("atm-2.zip").exists()); + fs::remove_dir_all(&home).unwrap(); +} diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index a43529db0..6dcb4b975 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -155,6 +155,68 @@ enum ModpackCmd { Remove { pack: String }, } +#[derive(Subcommand)] +enum ModsCmd { + /// What the browser installed (the default) + List, + /// Search for packs Horizon loads + Search { + text: Vec, + #[arg(long, value_enum, default_value_t = KindArg::Resource)] + kind: KindArg, + /// Also what was made for other versions or runs only partly, each marked + #[arg(long)] + everything: bool, + #[arg(long, value_enum, default_value_t = SourceArg::Modrinth)] + source: SourceArg, + }, + /// Install a pack and what it needs, by its id or slug (checksums checked); a modpack is + /// imported on the Modpacks page + Install { + project: String, + /// Allow a version made for another Minecraft version + #[arg(long)] + everything: bool, + #[arg(long, value_enum, default_value_t = SourceArg::Modrinth)] + source: SourceArg, + }, + /// Update what the browser installed (or one pack) + Update { + project: Option, + /// Only say what is newer + #[arg(long)] + check: bool, + }, + /// Remove a pack the browser installed + Remove { project: String }, +} + +#[derive(Clone, Copy, clap::ValueEnum)] +enum KindArg { + Resource, + Shader, + Modpack, +} + +#[derive(Clone, Copy, clap::ValueEnum)] +enum SourceArg { + Modrinth, + Curseforge, +} + +impl SourceArg { + fn get(self) -> Result, String> { + use horizon_launcher::browser::{self, SourceId}; + let id = match self { + SourceArg::Modrinth => SourceId::Modrinth, + SourceArg::Curseforge => SourceId::CurseForge, + }; + browser::source(id).ok_or_else(|| { + "CurseForge needs an API key: HORIZON_CURSEFORGE_API_KEY (docs/mod-browser.md).".into() + }) + } +} + #[derive(Subcommand)] enum Cmd { /// List Horizon releases, or the installed versions @@ -257,6 +319,12 @@ enum Cmd { #[command(subcommand)] action: Option, }, + /// The mod browser: resource packs, shader packs and modpacks from Modrinth (and CurseForge + /// with a key), each file checked against its checksum (docs/mod-browser.md) + Mods { + #[command(subcommand)] + action: Option, + }, /// Servers hosted with horizon-server (the Servers page): list them, create one, or run any /// horizon-server command on one Servers { @@ -523,6 +591,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } } Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?, + Cmd::Mods { action } => mods(action.unwrap_or(ModsCmd::List), as_json)?, Cmd::Servers { action } => servers(action.unwrap_or(ServersCmd::List), as_json)?, Cmd::Mcp => unreachable!(), } @@ -821,6 +890,148 @@ fn servers(action: ServersCmd, as_json: bool) -> Result<(), String> { Ok(()) } +fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { + use horizon_launcher::browser::{installed, Kind, Query}; + use horizon_launcher::modpacks; + let home = backend::game_home(); + let entry_json = |e: &installed::Entry| serde_json::to_value(e).unwrap_or_default(); + let line = |label: &str, f: f32| progress(label.to_string())(f); + match action { + ModsCmd::List => { + let list = installed::Installed::load(&home).entries; + if as_json { + json(list.iter().map(entry_json).collect()); + } else if list.is_empty() { + println!( + "Nothing installed from the browser yet: horizon-launcher mods search " + ); + } + for e in list.iter().filter(|_| !as_json) { + println!( + "{} {} ({}, {})\n {} {}", + e.title, + e.number, + e.source.label(), + e.slug, + e.file, + e.checksum + ); + } + } + ModsCmd::Search { + text, + kind, + everything, + source, + } => { + let kind = match kind { + KindArg::Resource => Kind::ResourcePack, + KindArg::Shader => Kind::ShaderPack, + KindArg::Modpack => Kind::Modpack, + }; + let query = Query { + everything, + ..Query::new(&text.join(" "), kind) + }; + let found = source.get()?.search(&query)?; + if as_json { + json(found.iter().map(|p| { + let support = p.support(); + serde_json::json!({ + "id": p.id, "slug": p.slug, "title": p.title, "summary": p.summary, + "author": p.author, "downloads": p.downloads, "page": p.page, + "license": p.license, "support": support.label(), "reason": support.reason(), + }) + }).collect()); + } else { + for p in &found { + let support = p.support(); + println!( + "{} ({}) {} ยท {} downloads\n {}", + p.title, + p.slug, + support.label(), + p.downloads, + p.summary + ); + if let Some(why) = support.reason() { + println!(" {why}"); + } + } + } + } + ModsCmd::Install { + project, + everything, + source, + } => { + let source = source.get()?; + let p = source.project(&project)?; + if p.kind == Kind::Modpack { + let folder = modpacks::ports_dir().join("downloads"); + let file = + installed::fetch_modpack(&*source, &p, &folder, &progress(p.title.clone()))?; + let log = &|line: String| eprintln!("{line}"); + let pack = modpacks::import(&file, log)?; + println!( + "Imported {} ({}): horizon-launcher modpack port {}", + pack.title(), + pack.summary(), + pack.slug + ); + return Ok(()); + } + let done = installed::install(&*source, &p, everything, &home, &line)?; + if as_json { + json(done.iter().map(entry_json).collect()); + } + for e in done.iter().filter(|_| !as_json) { + println!("{} {}: {} ({})", e.title, e.number, e.file, e.checksum); + } + } + ModsCmd::Update { project, check } => { + let list = installed::Installed::load(&home).entries; + let chosen: Vec<_> = list + .iter() + .filter(|e| { + project + .as_deref() + .is_none_or(|n| e.project == n || e.slug == n) + }) + .collect(); + if chosen.is_empty() { + return Err(match project { + Some(n) => format!("{n} wasn't installed by the browser."), + None => "Nothing installed from the browser yet.".into(), + }); + } + for e in chosen { + let Some(source) = horizon_launcher::browser::source(e.source) else { + println!("{}: {} isn't available here.", e.title, e.source.label()); + continue; + }; + match installed::update_for(&*source, e)? { + None => println!("{} {}: up to date.", e.title, e.number), + Some(v) if check => { + println!("{} {}: {} is available.", e.title, e.number, v.number) + } + Some(_) => { + let p = source.project(&e.project)?; + for done in installed::install(&*source, &p, true, &home, &line)? { + println!("{} {}: {}", done.title, done.number, done.file); + } + } + } + } + } + ModsCmd::Remove { project } => { + let e = installed::remove(&home, &project)?; + println!("Removed {} ({}).", e.title, e.file); + } + } + Ok(()) +} + fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { use horizon_launcher::modpacks::{self, Imported}; use horizon_port_pack::report::Status;