From 450adbef7319e8b3b27921d6612fab58e01f2b67 Mon Sep 17 00:00:00 2001 From: Benjamin BERTRAND <8989169+benjaminbrtrd@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:56:16 +0100 Subject: [PATCH 1/2] CurseForge installs, a New instance wizard, version switching - Discover installs mods, resource packs, shader packs and datapacks from CurseForge with their required mods, opens CurseForge project pages, and filters by several versions, loaders and categories on CurseForge and Modrinth. - New instance is a wizard: version and loader or a modpack, then optional mods, packs and datapacks, installed once the instance is ready. - Modpack pages list their content for every source. - Installed content has a Versions dialog; a modpack instance can switch to another pack version. - Content updates are checked at start; files show their source and type, and remember where they were installed from. - UI fixes: inspector layout, dialogs, chevrons, galleries. Co-Authored-By: Claude Opus 5.5 --- crates/cubby-atlauncher/src/contents.rs | 102 +++ crates/cubby-atlauncher/src/lib.rs | 2 + crates/cubby-atlauncher/src/model.rs | 20 + .../cubby-atlauncher/tests/contents_live.rs | 18 + crates/cubby-common/src/packs.rs | 125 +++ crates/cubby-curseforge/src/api.rs | 13 + crates/cubby-curseforge/src/browse.rs | 150 +++- crates/cubby-curseforge/src/client.rs | 2 + crates/cubby-curseforge/src/content.rs | 366 +++++++++ crates/cubby-curseforge/src/lib.rs | 11 +- crates/cubby-curseforge/src/pack_contents.rs | 244 ++++++ crates/cubby-curseforge/src/plan.rs | 12 +- .../cubby-curseforge/tests/contents_live.rs | 28 + crates/cubby-curseforge/tests/resolve.rs | 124 +++ crates/cubby-ftb/src/api.rs | 6 + crates/cubby-ftb/src/contents.rs | 73 ++ crates/cubby-ftb/src/lib.rs | 2 + crates/cubby-ftb/tests/contents_live.rs | 19 + crates/cubby-instance/src/settings.rs | 2 +- crates/cubby-modrinth/src/api.rs | 9 + crates/cubby-modrinth/src/browse.rs | 49 +- crates/cubby-modrinth/src/client.rs | 19 +- crates/cubby-modrinth/src/contents.rs | 195 +++++ crates/cubby-modrinth/src/datapacks.rs | 43 + crates/cubby-modrinth/src/install.rs | 72 +- crates/cubby-modrinth/src/lib.rs | 3 + crates/cubby-modrinth/src/local.rs | 1 + crates/cubby-modrinth/src/model.rs | 9 + crates/cubby-modrinth/tests/contents_live.rs | 23 + .../tests/fixtures/modrinth.index.json | 57 ++ crates/cubby-modrinth/tests/live.rs | 2 + crates/cubby-packinstall/src/install.rs | 67 ++ crates/cubby-packinstall/tests/live.rs | 2 + crates/cubby-technic/src/client.rs | 4 +- crates/cubby-technic/src/contents.rs | 88 +++ crates/cubby-technic/src/lib.rs | 2 + crates/cubby-technic/src/model.rs | 12 + crates/cubby-technic/tests/contents_live.rs | 17 + .../tests/fixtures/solder_build_mods.json | 46 ++ src-tauri/src/cf_resources.rs | 745 ++++++++++++++++-- src-tauri/src/commands/discover.rs | 20 +- src-tauri/src/commands/instances.rs | 8 + src-tauri/src/commands/launch.rs | 5 + src-tauri/src/commands/mod.rs | 4 +- src-tauri/src/dto.rs | 8 + src-tauri/src/extras.rs | 364 +++++++++ src-tauri/src/lib.rs | 15 + src-tauri/src/origins.rs | 54 ++ src-tauri/src/packs.rs | 239 +++++- src-tauri/src/state.rs | 3 + ui/src/App.svelte | 34 +- ui/src/lib/api.ts | 48 +- ui/src/lib/cubby/Dialog.svelte | 15 +- ui/src/lib/cubby/Inspector.svelte | 2 +- ui/src/lib/cubby/ModRow.svelte | 9 + ui/src/lib/cubby/SourceMark.svelte | 30 + ui/src/lib/cubby/TitleBar.svelte | 6 +- ui/src/lib/cubby/data.ts | 5 +- ui/src/lib/cubby/index.ts | 1 + ui/src/lib/cubby/types.ts | 6 + ui/src/lib/dev/mock.ts | 255 +++++- ui/src/lib/dev/mockContents.ts | 127 +++ ui/src/lib/i18n/fr-11.ts | 71 ++ ui/src/lib/i18n/fr-12.ts | 29 + ui/src/lib/i18n/fr-13.ts | 159 ++++ ui/src/lib/i18n/fr.ts | 6 + ui/src/lib/state.svelte.ts | 267 ++++++- ui/src/lib/types.ts | 134 +++- ui/src/lib/views/create/CustomForm.svelte | 587 -------------- ui/src/lib/views/create/Identity.svelte | 31 +- ui/src/lib/views/create/LinkSource.svelte | 27 +- ui/src/lib/views/create/NewInstance.svelte | 245 ------ ui/src/lib/views/create/PackPage.svelte | 91 ++- ui/src/lib/views/create/PackRoute.svelte | 66 ++ ui/src/lib/views/create/PresetCards.svelte | 13 +- .../lib/views/create/ProviderBrowser.svelte | 392 --------- ui/src/lib/views/create/QuickStart.svelte | 34 - .../views/create/wizard/ContentStep.svelte | 468 +++++++++++ .../lib/views/create/wizard/GameStep.svelte | 498 ++++++++++++ .../lib/views/create/wizard/PackStep.svelte | 301 +++++++ .../lib/views/create/wizard/ReviewStep.svelte | 235 ++++++ .../lib/views/create/wizard/StartStep.svelte | 130 +++ ui/src/lib/views/create/wizard/Summary.svelte | 202 +++++ ui/src/lib/views/create/wizard/Wizard.svelte | 347 ++++++++ .../views/create/wizard/WizardAside.svelte | 71 ++ ui/src/lib/views/create/wizard/kinds.ts | 19 + .../lib/views/create/wizard/state.svelte.ts | 234 ++++++ ui/src/lib/views/discover/CfInstall.svelte | 429 ++++++++++ .../lib/views/discover/DatapackInstall.svelte | 7 +- ui/src/lib/views/discover/Discover.svelte | 217 +++-- ui/src/lib/views/discover/InstallPanel.svelte | 19 +- .../views/discover/PackContentsList.svelte | 351 +++++++++ ui/src/lib/views/discover/Picker.svelte | 4 + ui/src/lib/views/discover/ProjectPage.svelte | 147 +++- ui/src/lib/views/discover/packContents.ts | 20 + .../views/discover/project/GalleryTab.svelte | 12 +- .../discover/project/ProjectAside.svelte | 27 +- .../discover/project/ProjectHeader.svelte | 12 +- ui/src/lib/views/discover/project/shared.ts | 2 +- .../views/instance-page/InstancePage.svelte | 56 +- ui/src/lib/views/instance-page/ModsTab.svelte | 76 +- .../views/instance-page/OverviewTab.svelte | 16 +- .../instance-page/PackVersionDialog.svelte | 160 ++++ .../instance-page/ResourcePacksTab.svelte | 27 +- .../views/instance-page/ScreenshotsTab.svelte | 2 +- .../lib/views/instance-page/ServersTab.svelte | 2 +- .../views/instance-page/SettingsTab.svelte | 2 +- .../lib/views/instance-page/ShadersTab.svelte | 25 +- .../views/instance-page/VersionDialog.svelte | 89 +++ .../views/instance-page/WorldDatapacks.svelte | 28 +- .../lib/views/instance-page/WorldsTab.svelte | 2 +- ui/src/lib/views/library/InstanceCard.svelte | 2 + ui/src/lib/views/settings/Settings.svelte | 4 +- ui/src/styles/cubby.css | 16 +- ui/src/styles/inspector.css | 17 +- 115 files changed, 8838 insertions(+), 1632 deletions(-) create mode 100644 crates/cubby-atlauncher/src/contents.rs create mode 100644 crates/cubby-atlauncher/tests/contents_live.rs create mode 100644 crates/cubby-curseforge/src/content.rs create mode 100644 crates/cubby-curseforge/src/pack_contents.rs create mode 100644 crates/cubby-curseforge/tests/contents_live.rs create mode 100644 crates/cubby-curseforge/tests/resolve.rs create mode 100644 crates/cubby-ftb/src/contents.rs create mode 100644 crates/cubby-ftb/tests/contents_live.rs create mode 100644 crates/cubby-modrinth/src/contents.rs create mode 100644 crates/cubby-modrinth/tests/contents_live.rs create mode 100644 crates/cubby-modrinth/tests/fixtures/modrinth.index.json create mode 100644 crates/cubby-technic/src/contents.rs create mode 100644 crates/cubby-technic/tests/contents_live.rs create mode 100644 crates/cubby-technic/tests/fixtures/solder_build_mods.json create mode 100644 src-tauri/src/extras.rs create mode 100644 src-tauri/src/origins.rs create mode 100644 ui/src/lib/cubby/SourceMark.svelte create mode 100644 ui/src/lib/dev/mockContents.ts create mode 100644 ui/src/lib/i18n/fr-11.ts create mode 100644 ui/src/lib/i18n/fr-12.ts create mode 100644 ui/src/lib/i18n/fr-13.ts delete mode 100644 ui/src/lib/views/create/CustomForm.svelte delete mode 100644 ui/src/lib/views/create/NewInstance.svelte create mode 100644 ui/src/lib/views/create/PackRoute.svelte delete mode 100644 ui/src/lib/views/create/ProviderBrowser.svelte delete mode 100644 ui/src/lib/views/create/QuickStart.svelte create mode 100644 ui/src/lib/views/create/wizard/ContentStep.svelte create mode 100644 ui/src/lib/views/create/wizard/GameStep.svelte create mode 100644 ui/src/lib/views/create/wizard/PackStep.svelte create mode 100644 ui/src/lib/views/create/wizard/ReviewStep.svelte create mode 100644 ui/src/lib/views/create/wizard/StartStep.svelte create mode 100644 ui/src/lib/views/create/wizard/Summary.svelte create mode 100644 ui/src/lib/views/create/wizard/Wizard.svelte create mode 100644 ui/src/lib/views/create/wizard/WizardAside.svelte create mode 100644 ui/src/lib/views/create/wizard/kinds.ts create mode 100644 ui/src/lib/views/create/wizard/state.svelte.ts create mode 100644 ui/src/lib/views/discover/CfInstall.svelte create mode 100644 ui/src/lib/views/discover/PackContentsList.svelte create mode 100644 ui/src/lib/views/discover/packContents.ts create mode 100644 ui/src/lib/views/instance-page/PackVersionDialog.svelte create mode 100644 ui/src/lib/views/instance-page/VersionDialog.svelte diff --git a/crates/cubby-atlauncher/src/contents.rs b/crates/cubby-atlauncher/src/contents.rs new file mode 100644 index 0000000..9e1d19e --- /dev/null +++ b/crates/cubby-atlauncher/src/contents.rs @@ -0,0 +1,102 @@ +//! What a version of an ATLauncher pack contains, from its manifest (`Configs.json`): the mods with their +//! names and versions, which optional, and the CurseForge project of those that come from there. + +use cubby_common::packs::{sort_contents, ContentSite, PackContentItem, PackContentKind}; + +use crate::model::{AtlManifest, AtlMod}; +use crate::modtypes::ModKind; + +/// What a mod type installs, as listed content; `None` for configs, loaders and server files. +fn content_kind(m: &AtlMod) -> Option { + let kind = ModKind::parse(&m.kind); + let kind = match kind { + ModKind::Extract => ModKind::parse(m.extract_to.as_deref().unwrap_or_default()), + ModKind::Decomp => ModKind::parse(m.decomp_type.as_deref().unwrap_or_default()), + other => other, + }; + match kind { + ModKind::Mods | ModKind::Flan | ModKind::Dependency | ModKind::Ic2Lib | ModKind::DenLib | ModKind::Coremods | ModKind::Jar => Some(PackContentKind::Mod), + ModKind::TexturePack | ModKind::ResourcePack | ModKind::TexturePackExtract | ModKind::ResourcePackExtract => Some(PackContentKind::ResourcePack), + ModKind::ShaderPack => Some(PackContentKind::Shader), + _ => None, + } +} + +/// The mods, resource packs and shader packs a client gets from this manifest (optional ones marked), whether +/// or not the player would pick the optional ones. +pub fn manifest_contents(manifest: &AtlManifest) -> Vec { + let mut out = Vec::new(); + for m in manifest.mods.iter().filter(|m| m.client && !m.name.trim().is_empty()) { + let Some(kind) = content_kind(m) else { continue }; + let name = m.name.trim().to_string(); + let mut item = PackContentItem::from_file(&m.file, kind); + item.name = name; + item.file_name = Some(m.file.trim().to_string()).filter(|f| !f.is_empty()); + item.version = Some(m.version.trim().to_string()).filter(|v| !v.is_empty()); + item.optional = m.optional; + item.description = Some(m.description.trim().to_string()).filter(|d| !d.is_empty()); + // ATLauncher writes "Unknown" when it doesn't know + item.authors = m.authors.iter().map(|a| a.trim().to_string()).filter(|a| !a.is_empty() && !a.eq_ignore_ascii_case("unknown")).collect(); + item.page_url = m.website.clone().filter(|u| u.starts_with("https://") || u.starts_with("http://")); + if let Some(id) = m.curse_id { + item.site = Some(ContentSite::Curseforge); + item.project_id = Some(id.to_string()); + } + out.push(item); + } + sort_contents(&mut out); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + fn manifest(name: &str) -> AtlManifest { + let bytes = std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + #[test] + fn lists_client_mods_with_their_projects() { + let items = manifest_contents(&manifest("manifest_pixelmon.json")); + assert!(!items.iter().any(|i| i.name == "Pixelmon Server"), "server-only"); + let jei = items.iter().find(|i| i.name == "Just Enough Items (JEI)").unwrap(); + assert_eq!(jei.site, Some(ContentSite::Curseforge)); + assert_eq!(jei.project_id.as_deref(), Some("238222")); + assert_eq!(jei.kind, PackContentKind::Mod); + let pixelmon = items.iter().find(|i| i.name == "Pixelmon").unwrap(); + assert_eq!(pixelmon.version.as_deref(), Some("9.4.2")); + assert_eq!(pixelmon.site, None); + assert_eq!(pixelmon.page_url.as_deref(), Some("https://www.pixelmonmod.com/")); + let raw = manifest("manifest_pixelmon.json"); + let raw_jei = raw.mods.iter().find(|m| m.name == "Just Enough Items (JEI)").unwrap(); + assert_eq!(jei.authors, raw_jei.authors.iter().filter(|a| *a != "Unknown").cloned().collect::>()); + assert_eq!(jei.description.as_deref(), Some(raw_jei.description.trim()).filter(|d| !d.is_empty())); + let ost = items.iter().find(|i| i.name == "The Pixelmon Mod OST").unwrap(); + assert_eq!(ost.kind, PackContentKind::ResourcePack); + assert_eq!(items.last().unwrap().kind, PackContentKind::ResourcePack, "mods come first"); + assert_eq!(items.len(), 14); + } + + #[test] + fn marks_optional_mods() { + let m = manifest("manifest_optional.json"); + let items = manifest_contents(&m); + let optional: Vec<&str> = items.iter().filter(|i| i.optional).map(|i| i.name.as_str()).collect(); + let expected: Vec<&str> = m.mods.iter().filter(|x| x.client && x.optional && content_kind(x).is_some()).map(|x| x.name.as_str()).collect(); + assert!(!optional.is_empty()); + assert_eq!(optional.len(), expected.len()); + assert!(items.iter().any(|i| i.name == "Base Mod" && !i.optional)); + } + + #[test] + fn reads_curse_ids_as_numbers_or_text() { + let m: AtlMod = serde_json::from_str(r#"{"name":"A","curse_id":"238222","curse_file_id":0}"#).unwrap(); + assert_eq!(m.curse_id, Some(238222)); + assert_eq!(m.curse_file_id, None); + let m: AtlMod = serde_json::from_str(r#"{"name":"A","curseForgeProjectId":12,"curse_file_id":null}"#).unwrap(); + assert_eq!(m.curse_id, Some(12)); + } +} diff --git a/crates/cubby-atlauncher/src/lib.rs b/crates/cubby-atlauncher/src/lib.rs index 99c9314..dbce141 100644 --- a/crates/cubby-atlauncher/src/lib.rs +++ b/crates/cubby-atlauncher/src/lib.rs @@ -2,6 +2,7 @@ //! and its optional mods, and turn it into a [`PackPlan`](cubby_common::packs::PackPlan). mod client; +mod contents; mod index; mod model; mod modtypes; @@ -10,6 +11,7 @@ mod plan; #[cfg(test)] mod plan_tests; +pub use contents::manifest_contents; pub use client::{AtLauncherClient, AtlPlan, ATL_BASE}; pub use index::safe_name; pub use model::{AtlLibrary, AtlManifest, AtlMod, LoaderMetadata, ManifestConfigs, ManifestLoader, ManifestMessages}; diff --git a/crates/cubby-atlauncher/src/model.rs b/crates/cubby-atlauncher/src/model.rs index 81cf128..4f10e9e 100644 --- a/crates/cubby-atlauncher/src/model.rs +++ b/crates/cubby-atlauncher/src/model.rs @@ -191,6 +191,26 @@ pub struct AtlMod { /// Installed on the client. Like Prism, a missing flag means "no". #[serde(default, deserialize_with = "nullable")] pub client: bool, + /// The mod's web page. + #[serde(default)] + pub website: Option, + #[serde(default, deserialize_with = "nullable")] + pub authors: Vec, + /// The CurseForge project of the mod, when it comes from there. + #[serde(default, rename = "curse_id", alias = "curseForgeProjectId", deserialize_with = "lenient_id")] + pub curse_id: Option, + #[serde(default, rename = "curse_file_id", alias = "curseForgeFileId", deserialize_with = "lenient_id")] + pub curse_file_id: Option, +} + +/// An id that may be a number, a string or null; 0 and anything unreadable read as `None`. +fn lenient_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + Ok(match Option::::deserialize(deserializer)? { + Some(serde_json::Value::Number(n)) => n.as_u64(), + Some(serde_json::Value::String(s)) => s.trim().parse().ok(), + _ => None, + } + .filter(|id| *id != 0)) } /// One entry of `libraries`. diff --git a/crates/cubby-atlauncher/tests/contents_live.rs b/crates/cubby-atlauncher/tests/contents_live.rs new file mode 100644 index 0000000..12fb01c --- /dev/null +++ b/crates/cubby-atlauncher/tests/contents_live.rs @@ -0,0 +1,18 @@ +//! Lists the contents of a real ATLauncher pack version. Needs network; run with `-- --ignored --nocapture`. + +use cubby_atlauncher::{manifest_contents, AtLauncherClient}; +use cubby_common::net::Http; + +#[tokio::test] +#[ignore = "needs network"] +async fn lists_a_pack() { + let atl = AtLauncherClient::new(Http::new().unwrap()); + let pack = atl.packs().await.unwrap().remove(0); + let version = atl.versions(&pack.id).await.unwrap().remove(0); + let items = manifest_contents(&atl.manifest(&pack.id, &version.id).await.unwrap()); + println!("{} {}: {} items", pack.name, version.name, items.len()); + for i in items.iter().take(10) { + println!(" {:?} {} {:?} {:?} {:?} optional={}", i.kind, i.name, i.version, i.project_id, i.page_url, i.optional); + } + assert!(!items.is_empty()); +} diff --git a/crates/cubby-common/src/packs.rs b/crates/cubby-common/src/packs.rs index 60602a5..a56e2b4 100644 --- a/crates/cubby-common/src/packs.rs +++ b/crates/cubby-common/src/packs.rs @@ -138,6 +138,101 @@ pub struct PackPlan { pub recommended_memory_mib: Option, } +/// What a file listed in a pack is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum PackContentKind { + #[serde(rename = "mod")] + Mod, + #[serde(rename = "resourcepack")] + ResourcePack, + #[serde(rename = "shader")] + Shader, +} + +impl PackContentKind { + /// The kind of a file by the folder it goes to (`mods/…`, `resourcepacks/…`, `shaderpacks/…`); `None` for + /// anything else (configs, scripts…). + pub fn of_path(path: &str) -> Option { + let path = path.replace('\\', "/"); + let path = path.trim_start_matches("./"); + let (folder, rest) = path.split_once('/')?; + if rest.is_empty() { + return None; + } + match folder.to_ascii_lowercase().as_str() { + "mods" | "coremods" => Some(Self::Mod), + "resourcepacks" | "texturepacks" => Some(Self::ResourcePack), + "shaderpacks" => Some(Self::Shader), + _ => None, + } + } +} + +/// Where the project of a listed file lives, when it is known. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ContentSite { + Modrinth, + Curseforge, +} + +/// A mod, resource pack or shader pack a version of a pack installs. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PackContentItem { + /// The project's name when known, else what the pack calls the file. + pub name: String, + pub file_name: Option, + /// The file's version number, when the provider gives one. + pub version: Option, + pub kind: PackContentKind, + pub icon_url: Option, + /// The site `project_id` belongs to. + pub site: Option, + pub project_id: Option, + /// Web page of the project. + pub page_url: Option, + /// The player may leave it out (ATLauncher optional mods, CurseForge `required: false`, Modrinth + /// `env.client: optional`). + pub optional: bool, + /// One line about the project, when its source says. + pub description: Option, + pub authors: Vec, + /// Modrinth-style category keys ("library", "optimization"…), for the kind of mod it is. + pub categories: Vec, +} + +impl PackContentItem { + /// An item known only by its file name: the name is the file name without its extension. + pub fn from_file(file_name: &str, kind: PackContentKind) -> Self { + let stem = file_name.rsplit_once('.').map(|(s, _)| s).filter(|s| !s.is_empty()).unwrap_or(file_name); + Self { + name: stem.to_string(), + file_name: Some(file_name.to_string()).filter(|f| !f.is_empty()), + version: None, + kind, + icon_url: None, + site: None, + project_id: None, + page_url: None, + optional: false, + description: None, + authors: Vec::new(), + categories: Vec::new(), + } + } +} + +/// Mods first, then resource packs, then shader packs; by name in each. +pub fn sort_contents(items: &mut [PackContentItem]) { + let rank = |k: PackContentKind| match k { + PackContentKind::Mod => 0, + PackContentKind::ResourcePack => 1, + PackContentKind::Shader => 2, + }; + items.sort_by(|a, b| rank(a.kind).cmp(&rank(b.kind)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))); +} + /// Rejects absolute paths, `..`, drive letters and empty segments; returns the cleaned relative path. pub fn safe_relative_path(path: &str) -> Option { let path = path.replace('\\', "/"); @@ -168,4 +263,34 @@ mod tests { assert_eq!(safe_relative_path("C:/x"), None); assert_eq!(safe_relative_path(""), None); } + + #[test] + fn content_kinds_by_folder() { + assert_eq!(PackContentKind::of_path("mods/a.jar"), Some(PackContentKind::Mod)); + assert_eq!(PackContentKind::of_path("./mods/a.jar"), Some(PackContentKind::Mod)); + assert_eq!(PackContentKind::of_path("resourcepacks\\Faithful.zip"), Some(PackContentKind::ResourcePack)); + assert_eq!(PackContentKind::of_path("shaderpacks/BSL.zip"), Some(PackContentKind::Shader)); + assert_eq!(PackContentKind::of_path("config/a.toml"), None); + assert_eq!(PackContentKind::of_path("mods/"), None); + assert_eq!(PackContentKind::of_path("options.txt"), None); + } + + #[test] + fn items_from_files_and_order() { + let a = PackContentItem::from_file("sodium-0.5.8.jar", PackContentKind::Mod); + assert_eq!(a.name, "sodium-0.5.8"); + assert_eq!(a.file_name.as_deref(), Some("sodium-0.5.8.jar")); + let mut items = vec![ + PackContentItem::from_file("Zed.zip", PackContentKind::Shader), + PackContentItem::from_file("b.zip", PackContentKind::ResourcePack), + PackContentItem::from_file("Beta.jar", PackContentKind::Mod), + PackContentItem::from_file("alpha.jar", PackContentKind::Mod), + ]; + sort_contents(&mut items); + let names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect(); + assert_eq!(names, ["alpha", "Beta", "b", "Zed"]); + let json = serde_json::to_value(&items[0]).unwrap(); + assert_eq!(json["kind"], "mod"); + assert_eq!(json["fileName"], "alpha.jar"); + } } diff --git a/crates/cubby-curseforge/src/api.rs b/crates/cubby-curseforge/src/api.rs index 99fef8d..59bcc5b 100644 --- a/crates/cubby-curseforge/src/api.rs +++ b/crates/cubby-curseforge/src/api.rs @@ -44,6 +44,8 @@ pub struct Mod { pub logo: Option, pub screenshots: Vec, pub latest_files_indexes: Vec, + pub categories: Vec, + pub date_created: Option, pub date_modified: Option, /// `Some(false)`: the author doesn't let third-party launchers download the files. pub allow_mod_distribution: Option, @@ -93,7 +95,18 @@ pub struct File { pub file_date: Option, pub file_length: Option, pub download_url: Option, + pub download_count: f64, pub game_versions: Vec, + pub dependencies: Vec, +} + +/// A project a file needs or works with. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct FileDependency { + pub mod_id: u64, + /// 1 embedded library, 2 optional, 3 required, 4 tool, 5 incompatible, 6 include. + pub relation_type: u8, } #[derive(Debug, Clone, Default, Deserialize)] diff --git a/crates/cubby-curseforge/src/browse.rs b/crates/cubby-curseforge/src/browse.rs index 4997a2e..f1b2bd4 100644 --- a/crates/cubby-curseforge/src/browse.rs +++ b/crates/cubby-curseforge/src/browse.rs @@ -4,7 +4,7 @@ use cubby_common::packs::{PackChannel, PackLoaderKind, PackPage, PackSort, PackS use cubby_common::Result; use crate::api; -use crate::client::{CurseForgeClient, GAME_ID, MODPACK_CLASS_ID, MOD_CLASS_ID, RESOURCE_PACK_CLASS_ID, SHADER_CLASS_ID}; +use crate::client::{CurseForgeClient, DATAPACK_CLASS_ID, GAME_ID, MODPACK_CLASS_ID, MOD_CLASS_ID, RESOURCE_PACK_CLASS_ID, SHADER_CLASS_ID}; /// CurseForge refuses `index + pageSize` above this. const MAX_WINDOW: u32 = 10_000; @@ -37,6 +37,9 @@ pub struct CfProject { pub description_html: String, pub links: CfLinks, pub screenshots: Vec, + /// Category names. + pub categories: Vec, + pub created: Option, } /// `sortField` of the search API: 1 Featured, 2 Popularity, 3 LastUpdated, 4 Name, 6 TotalDownloads, @@ -51,22 +54,33 @@ pub(crate) fn sort_params(sort: PackSort) -> (u8, &'static str) { } } -/// What a resource search looks for. Modpacks have their own search ([`CurseForgeClient::search`]). +/// What a resource search looks for. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ResourceKind { Mod, ResourcePack, Shader, + /// Goes into a world (`saves//datapacks`). + Datapack, + /// Searched with filters here; installed through the modpack plans. + Modpack, } impl ResourceKind { - fn class_id(self) -> u32 { + pub fn class_id(self) -> u32 { match self { ResourceKind::Mod => MOD_CLASS_ID, ResourceKind::ResourcePack => RESOURCE_PACK_CLASS_ID, ResourceKind::Shader => SHADER_CLASS_ID, + ResourceKind::Datapack => DATAPACK_CLASS_ID, + ResourceKind::Modpack => MODPACK_CLASS_ID, } } + + /// Mods and modpacks are made for a loader; packs and datapacks aren't. + pub fn has_loader(self) -> bool { + matches!(self, ResourceKind::Mod | ResourceKind::Modpack) + } } /// A category players can filter a resource search by. @@ -76,23 +90,30 @@ pub struct ResourceCategory { pub name: String, } -/// A search for mods, resource packs or shader packs. +/// Most game versions one search takes (`gameVersions`). +pub const MAX_SEARCH_VERSIONS: usize = 4; +/// Most loaders one search takes (`modLoaderTypes`). +pub const MAX_SEARCH_LOADERS: usize = 5; +/// Most categories one search takes (`categoryIds`). +pub const MAX_SEARCH_CATEGORIES: usize = 10; + +/// A search for mods, resource packs, shader packs, datapacks or modpacks. #[derive(Debug, Clone)] pub struct ResourceQuery { pub kind: ResourceKind, pub text: String, - /// Only files for this Minecraft version. - pub game_version: Option, - /// Only mods for this loader (resource packs and shaders have none). - pub loader: Option, - /// One category id (CurseForge filters by one at a time). - pub category: Option, + /// Only projects with files for one of these Minecraft versions (at most [`MAX_SEARCH_VERSIONS`]). + pub game_versions: Vec, + /// Only projects for one of these loaders (mods and modpacks; at most [`MAX_SEARCH_LOADERS`]). + pub loaders: Vec, + /// Category ids (at most [`MAX_SEARCH_CATEGORIES`]). + pub categories: Vec, pub sort: PackSort, pub offset: u32, pub limit: u32, } -fn loader_code(loader: PackLoaderKind) -> u8 { +pub(crate) fn loader_code(loader: PackLoaderKind) -> u8 { match loader { PackLoaderKind::Forge => 1, PackLoaderKind::Fabric => 4, @@ -101,6 +122,31 @@ fn loader_code(loader: PackLoaderKind) -> u8 { } } +/// The `ModLoaderType` names `modLoaderTypes=[...]` takes. +fn loader_enum_name(loader: PackLoaderKind) -> &'static str { + match loader { + PackLoaderKind::Forge => "Forge", + PackLoaderKind::Fabric => "Fabric", + PackLoaderKind::Quilt => "Quilt", + PackLoaderKind::NeoForge => "NeoForge", + } +} + +fn unique(items: impl IntoIterator, max: usize) -> Vec { + let mut out: Vec = Vec::new(); + for item in items { + if !out.contains(&item) { + out.push(item); + } + } + out.truncate(max); + out +} + +/// The list parameters of the search API: one value goes in the single parameter (`gameVersion`, +/// `categoryId`), several in the list one (`gameVersions=["1.20.1","1.21.1"]`, `categoryIds=[1,2]`, +/// `modLoaderTypes=[Fabric,Quilt]`). `modLoaderType` alone needs a `gameVersion`, so a loader without exactly +/// one version uses the list form. pub(crate) fn resource_params(q: &ResourceQuery) -> Vec<(&'static str, String)> { let mut params = search_params(&q.text, q.sort, q.offset, q.limit); for (name, value) in &mut params { @@ -108,14 +154,25 @@ pub(crate) fn resource_params(q: &ResourceQuery) -> Vec<(&'static str, String)> *value = q.kind.class_id().to_string(); } } - if let Some(version) = q.game_version.as_deref().map(str::trim).filter(|v| !v.is_empty()) { - params.push(("gameVersion", version.to_string())); + let versions = unique(q.game_versions.iter().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()), MAX_SEARCH_VERSIONS); + match versions.as_slice() { + [] => {} + [one] => params.push(("gameVersion", one.clone())), + many => params.push(("gameVersions", serde_json::to_string(many).unwrap_or_default())), } - if let Some(id) = q.category { - params.push(("categoryId", id.to_string())); + let categories = unique(q.categories.iter().copied(), MAX_SEARCH_CATEGORIES); + match categories.as_slice() { + [] => {} + [one] => params.push(("categoryId", one.to_string())), + many => params.push(("categoryIds", format!("[{}]", many.iter().map(u64::to_string).collect::>().join(",")))), } - if let (ResourceKind::Mod, Some(loader)) = (q.kind, q.loader) { - params.push(("modLoaderType", loader_code(loader).to_string())); + if q.kind.has_loader() { + let loaders = unique(q.loaders.iter().copied(), MAX_SEARCH_LOADERS); + match loaders.as_slice() { + [] => {} + [one] if versions.len() == 1 => params.push(("modLoaderType", loader_code(*one).to_string())), + many => params.push(("modLoaderTypes", format!("[{}]", many.iter().map(|l| loader_enum_name(*l)).collect::>().join(",")))), + } } params } @@ -139,7 +196,7 @@ pub(crate) fn search_params(query: &str, sort: PackSort, offset: u32, limit: u32 params } -fn loader_from_index(code: Option) -> Option { +pub(crate) fn loader_from_index(code: Option) -> Option { match code? { 1 => Some(PackLoaderKind::Forge), 4 => Some(PackLoaderKind::Fabric), @@ -149,7 +206,7 @@ fn loader_from_index(code: Option) -> Option { } } -fn loader_from_name(name: &str) -> Option { +pub(crate) fn loader_from_name(name: &str) -> Option { match name.to_ascii_lowercase().as_str() { "forge" => Some(PackLoaderKind::Forge), "fabric" => Some(PackLoaderKind::Fabric), @@ -170,7 +227,7 @@ fn version_key(s: &str) -> Vec { } /// Sorted newest first, without duplicates. -fn sorted_versions(versions: impl Iterator) -> Vec { +pub(crate) fn sorted_versions(versions: impl Iterator) -> Vec { let mut out: Vec = versions.filter(|v| is_release_version(v)).collect(); out.sort_by_key(|v| std::cmp::Reverse(version_key(v))); out.dedup(); @@ -214,6 +271,8 @@ pub(crate) fn project_from_mod(m: &api::Mod, description_html: String) -> CfProj .iter() .filter_map(|s| Some(CfScreenshot { title: s.title.clone().filter(|t| !t.is_empty()), url: s.url.clone().filter(|u| !u.is_empty())?, thumbnail_url: s.thumbnail_url.clone() })) .collect(), + categories: m.categories.iter().map(|c| c.name.trim().to_string()).filter(|n| !n.is_empty()).collect(), + created: m.date_created.clone(), } } @@ -243,14 +302,14 @@ impl CurseForgeClient { Ok(PackPage { hits: response.data.iter().map(summary_from_mod).collect(), total: response.pagination.map(|p| p.total_count) }) } - /// Mods, resource packs or shader packs matching the query. + /// Projects of any kind matching the query, with the filters CurseForge applies itself. pub async fn search_resources(&self, query: &ResourceQuery) -> Result { let params = resource_params(query); let response: api::Envelope> = self.get("/v1/mods/search", ¶ms, "CurseForge search").await?; Ok(PackPage { hits: response.data.iter().map(summary_from_mod).collect(), total: response.pagination.map(|p| p.total_count) }) } - /// The categories of mods, resource packs or shader packs, by name. + /// The categories of a kind of project, by name. pub async fn resource_categories(&self, kind: ResourceKind) -> Result> { let class = kind.class_id(); let query = [("gameId", GAME_ID.to_string()), ("classId", class.to_string())]; @@ -271,7 +330,7 @@ impl CurseForgeClient { self.search("", PackSort::Downloads, 0, 20).await } - /// A modpack page. `id` is the CurseForge project id. + /// A project page (modpack, mod, pack or datapack). `id` is the CurseForge project id. pub async fn pack(&self, id: u64) -> Result { let project: api::Envelope = self.get(&format!("/v1/mods/{id}"), &[], &format!("CurseForge modpack {id}")).await?; // The description is secondary: a failure there still shows the page. @@ -339,7 +398,16 @@ mod tests { #[test] fn resource_search_params() { - let mut q = ResourceQuery { kind: ResourceKind::Mod, text: "sodium".into(), game_version: Some(" 1.21.1 ".into()), loader: Some(PackLoaderKind::Fabric), category: Some(409), sort: PackSort::Downloads, offset: 0, limit: 20 }; + let mut q = ResourceQuery { + kind: ResourceKind::Mod, + text: "sodium".into(), + game_versions: vec![" 1.21.1 ".into()], + loaders: vec![PackLoaderKind::Fabric], + categories: vec![409], + sort: PackSort::Downloads, + offset: 0, + limit: 20, + }; let get = |p: &[(&str, String)], k: &str| p.iter().find(|(n, _)| *n == k).map(|(_, v)| v.clone()); let p = resource_params(&q); assert_eq!(get(&p, "classId").as_deref(), Some("6")); @@ -351,12 +419,42 @@ mod tests { q.kind = ResourceKind::Shader; let p = resource_params(&q); assert_eq!(get(&p, "classId").as_deref(), Some("6552")); - assert!(get(&p, "modLoaderType").is_none()); + assert!(get(&p, "modLoaderType").is_none() && get(&p, "modLoaderTypes").is_none()); q.kind = ResourceKind::ResourcePack; - q.game_version = None; + q.game_versions = Vec::new(); let p = resource_params(&q); assert_eq!(get(&p, "classId").as_deref(), Some("12")); assert!(get(&p, "gameVersion").is_none()); + q.kind = ResourceKind::Datapack; + assert_eq!(get(&resource_params(&q), "classId").as_deref(), Some("6945")); + } + + #[test] + fn several_filters_use_the_list_parameters() { + let q = ResourceQuery { + kind: ResourceKind::Modpack, + text: String::new(), + game_versions: vec!["1.21.1".into(), "1.20.1".into(), "1.21.1".into(), "1.19.2".into(), "1.18.2".into(), "1.16.5".into()], + loaders: vec![PackLoaderKind::Fabric, PackLoaderKind::Quilt], + categories: vec![1, 2, 2, 3], + sort: PackSort::Relevance, + offset: 0, + limit: 20, + }; + let p = resource_params(&q); + let get = |k: &str| p.iter().find(|(n, _)| *n == k).map(|(_, v)| v.clone()); + assert_eq!(get("classId").as_deref(), Some("4471")); + // at most 4 versions, without duplicates + assert_eq!(get("gameVersions").as_deref(), Some(r#"["1.21.1","1.20.1","1.19.2","1.18.2"]"#)); + assert!(get("gameVersion").is_none()); + assert_eq!(get("categoryIds").as_deref(), Some("[1,2,3]")); + assert_eq!(get("modLoaderTypes").as_deref(), Some("[Fabric,Quilt]")); + assert!(get("modLoaderType").is_none()); + + // one loader without one version: modLoaderType alone needs a gameVersion + let q = ResourceQuery { game_versions: Vec::new(), loaders: vec![PackLoaderKind::NeoForge], ..q }; + let p = resource_params(&q); + assert_eq!(p.iter().find(|(n, _)| *n == "modLoaderTypes").map(|(_, v)| v.as_str()), Some("[NeoForge]")); } #[test] diff --git a/crates/cubby-curseforge/src/client.rs b/crates/cubby-curseforge/src/client.rs index be6ccd7..85709a3 100644 --- a/crates/cubby-curseforge/src/client.rs +++ b/crates/cubby-curseforge/src/client.rs @@ -19,6 +19,8 @@ pub const MOD_CLASS_ID: u32 = 6; pub const RESOURCE_PACK_CLASS_ID: u32 = 12; /// "Shaders" class of Minecraft. pub const SHADER_CLASS_ID: u32 = 6552; +/// "Data Packs" class of Minecraft. +pub const DATAPACK_CLASS_ID: u32 = 6945; const RATE_LIMIT_RETRIES: usize = 2; const KEY_VARIABLE: &str = "CUBBY_CURSEFORGE_API_KEY"; diff --git a/crates/cubby-curseforge/src/content.rs b/crates/cubby-curseforge/src/content.rs new file mode 100644 index 0000000..a4a0e29 --- /dev/null +++ b/crates/cubby-curseforge/src/content.rs @@ -0,0 +1,366 @@ +//! Mods, resource packs, shader packs and datapacks installed one at a time from CurseForge: the files of a +//! project, the best one for an instance, and the required projects it pulls in. +//! +//! A file without a `downloadUrl` is blocked by its author for third-party launchers: the player downloads it +//! from [`CfProjectBrief::download_page`]. + +use std::collections::HashSet; + +use serde::Serialize; +use cubby_common::packs::{PackChannel, PackLoaderKind}; +use cubby_common::{Error, Result}; + +use crate::api; +use crate::browse::{loader_from_name, sorted_versions}; +use crate::client::CurseForgeClient; + +const SITE: &str = "https://www.curseforge.com/minecraft"; +const PAGE_SIZE: u64 = 50; +/// Pages of `/files` read for one Minecraft version: the best file is among the newest. +const VERSION_PAGES: u64 = 4; +/// Required projects followed, at most (a guard against odd dependency graphs). +const MAX_DEPENDENCIES: usize = 60; +const MAX_DEPTH: usize = 6; +/// `relationType` of a required dependency. +const REQUIRED: u8 = 3; + +/// A file of a project. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CfFile { + pub id: u64, + pub project_id: u64, + /// The display name, else the file name. + pub name: String, + pub file_name: String, + pub channel: PackChannel, + /// Minecraft releases, newest first. + pub minecraft: Vec, + pub loaders: Vec, + pub released: Option, + pub size: Option, + pub downloads: u64, + /// Lowercase hex. + pub sha1: Option, + /// `None`: the author doesn't let launchers download it. + pub download_url: Option, + /// Projects this file requires. + pub required: Vec, +} + +impl From<&api::File> for CfFile { + fn from(f: &api::File) -> Self { + let mut loaders: Vec = Vec::new(); + for l in f.game_versions.iter().filter_map(|v| loader_from_name(v)) { + if !loaders.contains(&l) { + loaders.push(l); + } + } + let mut required: Vec = Vec::new(); + for d in f.dependencies.iter().filter(|d| d.relation_type == REQUIRED && d.mod_id != 0 && d.mod_id != f.mod_id) { + if !required.contains(&d.mod_id) { + required.push(d.mod_id); + } + } + CfFile { + id: f.id, + project_id: f.mod_id, + name: if f.display_name.trim().is_empty() { f.file_name.clone() } else { f.display_name.trim().to_string() }, + file_name: f.file_name.clone(), + channel: match f.release_type { + 2 => PackChannel::Beta, + 3 => PackChannel::Alpha, + _ => PackChannel::Release, + }, + minecraft: sorted_versions(f.game_versions.iter().cloned()), + loaders, + released: f.file_date.clone(), + size: f.file_length, + downloads: f.download_count.max(0.0) as u64, + sha1: f.sha1(), + download_url: f.download_url.as_deref().map(str::trim).filter(|u| !u.is_empty()).map(str::to_string), + required, + } + } +} + +/// What a project is, for an install plan. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CfProjectBrief { + pub id: u64, + pub name: String, + pub slug: String, + pub class_id: Option, + pub icon_url: Option, + /// The project's page on curseforge.com. + pub page_url: String, +} + +impl CfProjectBrief { + /// Where the player downloads `file_id` by hand. + pub fn download_page(&self, file_id: u64) -> String { + format!("{}/download/{file_id}", self.page_url.trim_end_matches('/')) + } +} + +/// Section of the website for a class of projects. +fn class_section(class_id: Option) -> &'static str { + match class_id { + Some(12) => "texture-packs", + Some(6552) => "shaders", + Some(6945) => "data-packs", + Some(4471) => "modpacks", + Some(17) => "worlds", + _ => "mc-mods", + } +} + +pub(crate) fn brief_from_mod(m: &api::Mod) -> CfProjectBrief { + let page_url = match m.links.website_url.as_deref().map(|u| u.trim_end_matches('/')).filter(|u| !u.is_empty()) { + Some(url) => url.to_string(), + None if !m.slug.is_empty() => format!("{SITE}/{}/{}", class_section(m.class_id), m.slug), + None => format!("https://www.curseforge.com/projects/{}", m.id), + }; + CfProjectBrief { + id: m.id, + name: if m.name.trim().is_empty() { format!("Project {}", m.id) } else { m.name.trim().to_string() }, + slug: m.slug.clone(), + class_id: m.class_id, + icon_url: m.logo.as_ref().and_then(|l| l.thumbnail_url.clone().or_else(|| l.url.clone())).filter(|u| !u.is_empty()), + page_url, + } +} + +/// The Minecraft version and loaders a file must suit. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FileTarget { + pub game_version: Option, + /// Loaders whose mods run on the instance (a Quilt instance also runs Fabric mods); empty = any. + pub loaders: Vec, +} + +impl FileTarget { + /// The file lists the Minecraft version, and one of the loaders when it names loaders at all (resource + /// packs, shader packs and datapacks name none). + pub fn fits(&self, file: &CfFile) -> bool { + let version = self.game_version.as_deref().is_none_or(|v| file.minecraft.iter().any(|m| m == v)); + let loader = self.loaders.is_empty() || file.loaders.is_empty() || file.loaders.iter().any(|l| self.loaders.contains(l)); + version && loader + } +} + +fn channel_rank(c: PackChannel) -> u8 { + match c { + PackChannel::Release => 0, + PackChannel::Beta => 1, + PackChannel::Alpha => 2, + } +} + +/// The file to install for `target`: the newest release that fits, else the newest beta, else the newest alpha. +pub fn best_file<'a>(files: &'a [CfFile], target: &FileTarget) -> Option<&'a CfFile> { + files + .iter() + .filter(|f| target.fits(f)) + .min_by(|a, b| channel_rank(a.channel).cmp(&channel_rank(b.channel)).then_with(|| b.released.cmp(&a.released)).then_with(|| b.id.cmp(&a.id))) +} + +/// A project of an install plan and the file chosen for it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Resolved { + pub project: CfProjectBrief, + /// `None`: no file suits the target (a missing dependency). + pub file: Option, + /// Pulled in by another project. + pub dependency: bool, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ModIds<'a> { + mod_ids: &'a [u64], +} + +fn newest_first(files: &mut [CfFile]) { + files.sort_by(|a, b| b.released.cmp(&a.released).then(b.id.cmp(&a.id))); +} + +impl CurseForgeClient { + /// Every file of a project, newest first. + pub async fn project_files(&self, id: u64) -> Result> { + let files = self.files_raw(id).await?; + Ok(files.iter().map(CfFile::from).collect()) + } + + /// The newest files of a project for a Minecraft version (all versions when `None`), newest first. + pub async fn files_for_version(&self, id: u64, game_version: Option<&str>) -> Result> { + let mut out: Vec = Vec::new(); + for page in 0..VERSION_PAGES { + let mut query = vec![("index", (page * PAGE_SIZE).to_string()), ("pageSize", PAGE_SIZE.to_string())]; + if let Some(v) = game_version.map(str::trim).filter(|v| !v.is_empty()) { + query.push(("gameVersion", v.to_string())); + } + let response: api::Envelope> = self.get(&format!("/v1/mods/{id}/files"), &query, &format!("files of CurseForge project {id}")).await?; + let got = response.data.len() as u64; + out.extend(response.data.iter().map(CfFile::from)); + let total = response.pagination.map(|p| p.total_count).unwrap_or(0); + if got < PAGE_SIZE || out.len() as u64 >= total { + break; + } + } + newest_first(&mut out); + Ok(out) + } + + /// One file of a project. + pub async fn file(&self, project_id: u64, file_id: u64) -> Result { + Ok(CfFile::from(&self.file_raw(project_id, file_id).await?)) + } + + /// The projects with these ids that CurseForge knows, in no particular order. + pub async fn projects(&self, ids: &[u64]) -> Result> { + let mut out = Vec::new(); + for chunk in ids.chunks(500) { + let response: api::Envelope> = self.post("/v1/mods", &ModIds { mod_ids: chunk }, "CurseForge projects").await?; + out.extend(response.data.iter().map(brief_from_mod)); + } + Ok(out) + } + + /// The project with the file to install (`file_id`, else the best one for `target`), then the projects + /// its file requires, level by level. `skip` leaves out a required project (already in the instance) and + /// what it would require in turn. The requested project comes back even without a suitable file. + pub async fn resolve(&self, project_id: u64, file_id: Option, target: &FileTarget, skip: impl Fn(&CfProjectBrief) -> bool) -> Result> { + let project = self.projects(&[project_id]).await?.into_iter().next().ok_or_else(|| Error::NotFound(format!("CurseForge project {project_id}")))?; + let file = match file_id { + Some(id) => Some(self.file(project_id, id).await?), + None => best_file(&self.files_for_version(project_id, target.game_version.as_deref()).await?, target).cloned(), + }; + let mut next: Vec = file.as_ref().map(|f| f.required.clone()).unwrap_or_default(); + let mut out = vec![Resolved { project, file, dependency: false }]; + let mut seen: HashSet = HashSet::from([project_id]); + + for _ in 0..MAX_DEPTH { + let ids: Vec = next.drain(..).filter(|id| seen.insert(*id)).collect(); + if ids.is_empty() || out.len() > MAX_DEPENDENCIES { + break; + } + let briefs = self.projects(&ids).await?; + for id in ids { + let brief = briefs.iter().find(|b| b.id == id).cloned().unwrap_or_else(|| CfProjectBrief { + id, + name: format!("Project {id}"), + slug: String::new(), + class_id: None, + icon_url: None, + page_url: format!("https://www.curseforge.com/projects/{id}"), + }); + if skip(&brief) { + continue; + } + let file = match self.files_for_version(id, target.game_version.as_deref()).await { + Ok(files) => best_file(&files, target).cloned(), + Err(Error::NotFound(_)) => None, + Err(e) => return Err(e), + }; + if let Some(f) = &file { + next.extend(f.required.iter().copied()); + } + out.push(Resolved { project: brief, file, dependency: true }); + } + } + Ok(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(id: u64, channel: PackChannel, released: &str, mc: &[&str], loaders: &[PackLoaderKind]) -> CfFile { + CfFile { + id, + project_id: 1, + name: format!("f{id}"), + file_name: format!("f{id}.jar"), + channel, + minecraft: mc.iter().map(|s| s.to_string()).collect(), + loaders: loaders.to_vec(), + released: Some(released.to_string()), + size: Some(10), + downloads: 0, + sha1: None, + download_url: None, + required: Vec::new(), + } + } + + #[test] + fn best_file_prefers_newest_release_that_fits() { + use PackChannel::*; + use PackLoaderKind::*; + let files = vec![ + file(5, Beta, "2026-05-01", &["1.21.1"], &[Fabric]), + file(4, Release, "2026-04-01", &["1.21.1"], &[NeoForge]), + file(3, Release, "2026-03-01", &["1.21.1"], &[Fabric]), + file(2, Release, "2026-02-01", &["1.21.1"], &[Fabric]), + file(1, Release, "2026-06-01", &["1.20.1"], &[Fabric]), + ]; + let target = FileTarget { game_version: Some("1.21.1".into()), loaders: vec![Fabric] }; + assert_eq!(best_file(&files, &target).map(|f| f.id), Some(3)); + // a Quilt instance runs Fabric mods + let quilt = FileTarget { game_version: Some("1.21.1".into()), loaders: vec![Quilt, Fabric] }; + assert_eq!(best_file(&files, &quilt).map(|f| f.id), Some(3)); + // only a beta fits + let only_beta = vec![files[0].clone(), files[1].clone()]; + assert_eq!(best_file(&only_beta, &target).map(|f| f.id), Some(5)); + // nothing for this version + let old = FileTarget { game_version: Some("1.12.2".into()), loaders: vec![Fabric] }; + assert!(best_file(&files, &old).is_none()); + // packs name no loader: any loader target accepts them + let pack = vec![file(9, Release, "2026-01-01", &["1.21.1"], &[])]; + assert_eq!(best_file(&pack, &target).map(|f| f.id), Some(9)); + } + + #[test] + fn file_maps_from_the_api() { + let raw = api::File { + id: 77, + mod_id: 10, + display_name: " ".into(), + file_name: "thing-1.0.jar".into(), + release_type: 2, + hashes: vec![api::Hash { value: "ABC".into(), algo: 1 }], + file_date: Some("2026-01-01".into()), + file_length: Some(42), + download_url: Some("".into()), + game_versions: vec!["1.21.1".into(), "Fabric".into(), "Client".into(), "Quilt".into(), "1.21".into()], + download_count: 5.0, + dependencies: vec![ + api::FileDependency { mod_id: 306612, relation_type: 3 }, + api::FileDependency { mod_id: 306612, relation_type: 3 }, + api::FileDependency { mod_id: 5, relation_type: 2 }, + api::FileDependency { mod_id: 10, relation_type: 3 }, + ], + }; + let f = CfFile::from(&raw); + assert_eq!(f.name, "thing-1.0.jar"); + assert_eq!(f.channel, PackChannel::Beta); + assert_eq!(f.minecraft, vec!["1.21.1".to_string(), "1.21".to_string()]); + assert_eq!(f.loaders, vec![PackLoaderKind::Fabric, PackLoaderKind::Quilt]); + assert_eq!(f.sha1.as_deref(), Some("abc")); + // an empty URL is a blocked file + assert_eq!(f.download_url, None); + // only required projects, once, never itself + assert_eq!(f.required, vec![306612]); + } + + #[test] + fn brief_has_a_page() { + let m = api::Mod { id: 3, name: "Jade".into(), slug: "jade".into(), class_id: Some(6), ..Default::default() }; + let b = brief_from_mod(&m); + assert_eq!(b.page_url, "https://www.curseforge.com/minecraft/mc-mods/jade"); + assert_eq!(b.download_page(99), "https://www.curseforge.com/minecraft/mc-mods/jade/download/99"); + let m = api::Mod { id: 4, slug: "x".into(), class_id: Some(6945), ..Default::default() }; + assert_eq!(brief_from_mod(&m).page_url, "https://www.curseforge.com/minecraft/data-packs/x"); + } +} diff --git a/crates/cubby-curseforge/src/lib.rs b/crates/cubby-curseforge/src/lib.rs index 6521035..3260927 100644 --- a/crates/cubby-curseforge/src/lib.rs +++ b/crates/cubby-curseforge/src/lib.rs @@ -1,15 +1,20 @@ -//! CurseForge modpacks: browse the catalogue, plan an install and read a modpack `.zip`. +//! CurseForge: browse the catalogue, plan modpack installs, read a modpack `.zip`, and install mods, +//! resource packs, shader packs and datapacks one at a time. //! //! The API needs a key, which is not in the sources; see [`api_key_from_env`]. mod api; mod browse; mod client; +mod content; mod export; mod manifest; +mod pack_contents; mod plan; -pub use browse::{CfLinks, CfProject, CfScreenshot, ResourceCategory, ResourceKind, ResourceQuery}; -pub use client::{api_key_from_env, api_key_with_source, ApiKeySource, CurseForgeClient, API_BASE, GAME_ID, MODPACK_CLASS_ID, MOD_CLASS_ID, RESOURCE_PACK_CLASS_ID, SHADER_CLASS_ID}; +pub use browse::{CfLinks, CfProject, CfScreenshot, ResourceCategory, ResourceKind, ResourceQuery, MAX_SEARCH_CATEGORIES, MAX_SEARCH_LOADERS, MAX_SEARCH_VERSIONS}; +pub use content::{best_file, CfFile, CfProjectBrief, FileTarget, Resolved}; +pub use client::{api_key_from_env, api_key_with_source, ApiKeySource, CurseForgeClient, API_BASE, GAME_ID, MODPACK_CLASS_ID, MOD_CLASS_ID, RESOURCE_PACK_CLASS_ID, SHADER_CLASS_ID, DATAPACK_CLASS_ID}; pub use export::{export_curseforge, fingerprint, CfExportSpec}; +pub use pack_contents::manifest_contents; pub use manifest::{parse_manifest, read_manifest, CfManifest, CfManifestFile, CfMinecraft, CfModLoader}; diff --git a/crates/cubby-curseforge/src/pack_contents.rs b/crates/cubby-curseforge/src/pack_contents.rs new file mode 100644 index 0000000..df6527f --- /dev/null +++ b/crates/cubby-curseforge/src/pack_contents.rs @@ -0,0 +1,244 @@ +//! What a CurseForge modpack file contains. CurseForge has no endpoint for a pack's manifest, so the pack's +//! zip is downloaded to read `manifest.json` (then deleted); one bulk `/v1/mods/files` and one bulk `/v1/mods` +//! call name the files. + +use std::collections::{HashMap, HashSet}; +use std::path::Path; + +use cubby_common::net::{ensure_file, Download}; +use cubby_common::packs::{sort_contents, ContentSite, PackContentItem, PackContentKind}; +use cubby_common::{Error, Result}; + +use crate::api; +use crate::client::CurseForgeClient; +use crate::content::brief_from_mod; +use crate::manifest::{read_manifest, CfManifest}; +use crate::plan::{unique, FileIds, ModIds, IDS_PER_REQUEST}; + +/// The kind of content a project class installs; `None` for classes that aren't mods, resource packs or +/// shader packs (worlds, datapacks…). +fn kind_of_class(class_id: Option) -> Option { + match class_id { + Some(12) => Some(PackContentKind::ResourcePack), + Some(6552) => Some(PackContentKind::Shader), + Some(17) | Some(6945) => None, + _ => Some(PackContentKind::Mod), + } +} + +/// Modrinth-style keys for the CurseForge categories that say what kind of mod a project is. +fn category_keys(categories: &[api::Category]) -> Vec { + let mut out: Vec = Vec::new(); + for c in categories { + let slug = c.slug.to_ascii_lowercase(); + let key = if slug.contains("library") || slug == "api" || slug.ends_with("-api") { + "library".to_string() + } else if slug.contains("performance") { + "optimization".to_string() + } else { + slug + }; + if !key.is_empty() && !out.contains(&key) { + out.push(key); + } + } + out +} + +/// What the project says about itself: name (when `rename`), icon, page, summary, authors and categories. +fn describe(item: &mut PackContentItem, project: &api::Mod, rename: bool) { + let brief = brief_from_mod(project); + if rename { + item.name = brief.name; + } + item.icon_url = brief.icon_url.or(item.icon_url.take()); + item.page_url = Some(brief.page_url); + item.description = Some(project.summary.trim().to_string()).filter(|s| !s.is_empty()); + item.authors = project.authors.iter().map(|a| a.name.trim().to_string()).filter(|a| !a.is_empty()).collect(); + item.categories = category_keys(&project.categories); +} + +/// The mods, resource packs and shader packs of a manifest, named from the API answers (`files` and +/// `projects`). A file the API no longer knows is still listed, by its project id. +pub fn manifest_contents(manifest: &CfManifest, files: &[api::File], projects: &[api::Mod]) -> Vec { + let files: HashMap = files.iter().map(|f| (f.id, f)).collect(); + let projects: HashMap = projects.iter().map(|p| (p.id, p)).collect(); + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for entry in &manifest.files { + if !seen.insert(entry.file_id) { + continue; + } + let project = projects.get(&entry.project_id).copied(); + let Some(kind) = kind_of_class(project.and_then(|p| p.class_id)) else { continue }; + let file = files.get(&entry.file_id).copied(); + let mut item = match file.map(|f| f.file_name.trim()).filter(|n| !n.is_empty()) { + Some(name) => PackContentItem::from_file(name, kind), + None => PackContentItem { file_name: None, ..PackContentItem::from_file(&format!("Project {}", entry.project_id), kind) }, + }; + if let Some(display) = file.map(|f| f.display_name.trim()).filter(|n| !n.is_empty()) { + item.name = display.to_string(); + } + item.site = Some(ContentSite::Curseforge); + item.project_id = Some(entry.project_id.to_string()); + item.optional = !entry.required; + if let Some(project) = project { + describe(&mut item, project, true); + // the file's display name, when it says more than the project's name or the file name + let stem = item.file_name.as_deref().map(|f| f.rsplit_once('.').map_or(f, |(s, _)| s)).unwrap_or_default(); + item.version = file + .map(|f| f.display_name.trim().to_string()) + .filter(|d| !d.is_empty() && *d != item.name && Some(d.as_str()) != item.file_name.as_deref() && d != stem); + } else { + item.page_url = Some(format!("https://www.curseforge.com/projects/{}", entry.project_id)); + } + out.push(item); + } + sort_contents(&mut out); + out +} + +impl CurseForgeClient { + /// Describes the CurseForge projects in `items` (packs of other sources that name them by id) with one + /// bulk call. `rename`: the items are named after their files, the project's name is better. + pub async fn describe_contents(&self, items: &mut [PackContentItem], rename: bool) -> Result<()> { + let ids: Vec = unique(items.iter().filter(|i| i.site == Some(ContentSite::Curseforge)).filter_map(|i| i.project_id.as_deref()?.parse().ok())); + let mut projects = Vec::new(); + for chunk in ids.chunks(IDS_PER_REQUEST) { + let response: api::Envelope> = self.post("/v1/mods", &ModIds { mod_ids: chunk }, "the projects of the pack").await?; + projects.extend(response.data); + } + describe_items(items, &projects, rename); + Ok(()) + } + + /// The mods, resource packs and shader packs of the file `file_id` of the modpack `pack_id`. The pack's zip + /// is downloaded into `cache_dir` to read its manifest, then deleted. + pub async fn pack_contents(&self, pack_id: u64, file_id: u64, cache_dir: &Path) -> Result> { + let file = self.file_raw(pack_id, file_id).await?; + let url = file + .download_url + .as_deref() + .map(str::trim) + .filter(|u| !u.is_empty()) + .ok_or_else(|| Error::Other("The author of this modpack doesn't let launchers download it, so Cubby can't read which mods it has.".into()))? + .to_string(); + let archive = cache_dir.join(format!("contents-{pack_id}-{file_id}.zip")); + let mut job = Download::new(url, &archive); + if let Some(sha1) = file.sha1() { + job = job.with_sha1(sha1); + } + if let Some(size) = file.file_length { + job = job.with_size(size); + } + ensure_file(&self.http, &job).await?; + let path = archive.clone(); + let manifest = tokio::task::spawn_blocking(move || read_manifest(&path)).await.map_err(|e| Error::Other(e.to_string())); + if let Err(e) = std::fs::remove_file(&archive) { + tracing::debug!("could not remove {}: {e}", archive.display()); + } + let manifest = manifest??; + + let file_ids = unique(manifest.files.iter().map(|f| f.file_id)); + let mod_ids = unique(manifest.files.iter().map(|f| f.project_id)); + let mut files = Vec::new(); + for chunk in file_ids.chunks(IDS_PER_REQUEST) { + let response: api::Envelope> = self.post("/v1/mods/files", &FileIds { file_ids: chunk }, "the files of the pack").await?; + files.extend(response.data); + } + let mut projects = Vec::new(); + for chunk in mod_ids.chunks(IDS_PER_REQUEST) { + let response: api::Envelope> = self.post("/v1/mods", &ModIds { mod_ids: chunk }, "the projects of the pack").await?; + projects.extend(response.data); + } + Ok(manifest_contents(&manifest, &files, &projects)) + } +} + +/// [`CurseForgeClient::describe_contents`] once the projects are fetched. +pub(crate) fn describe_items(items: &mut [PackContentItem], projects: &[api::Mod], rename: bool) { + let by_id: HashMap = projects.iter().map(|p| (p.id.to_string(), p)).collect(); + for item in items.iter_mut().filter(|i| i.site == Some(ContentSite::Curseforge)) { + if let Some(project) = item.project_id.as_ref().and_then(|id| by_id.get(id)) { + describe(item, project, rename); + } + } + sort_contents(items); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::manifest::parse_manifest; + + fn fixture(name: &str) -> Vec { + std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap() + } + + fn resolved() -> (CfManifest, Vec, Vec) { + let manifest = parse_manifest(&fixture("manifest_forge.json")).unwrap(); + let files: api::Envelope> = serde_json::from_slice(&fixture("files_resolve.json")).unwrap(); + let mods: api::Envelope> = serde_json::from_slice(&fixture("mods_resolve.json")).unwrap(); + (manifest, files.data, mods.data) + } + + #[test] + fn lists_the_manifest_with_project_names() { + let (manifest, files, mods) = resolved(); + let items = manifest_contents(&manifest, &files, &mods); + let names: Vec<(&str, PackContentKind)> = items.iter().map(|i| (i.name.as_str(), i.kind)).collect(); + assert_eq!( + names, + [ + ("Blocked Mod", PackContentKind::Mod), + ("CDN-able", PackContentKind::Mod), + ("Just Enough Items", PackContentKind::Mod), + ("Optional extra", PackContentKind::Mod), + ("Faithful", PackContentKind::ResourcePack), + ("Complementary", PackContentKind::Shader), + ] + ); + let jei = &items[2]; + assert_eq!(jei.site, Some(ContentSite::Curseforge)); + assert_eq!(jei.project_id.as_deref(), Some("1001")); + assert_eq!(jei.file_name.as_deref(), Some("jei-1.20.1-forge-15.3.0.4.jar")); + assert_eq!(jei.version.as_deref(), Some("JEI 15.3.0.4")); + assert!(jei.page_url.as_deref().unwrap().contains("jei")); + assert!(!jei.optional); + assert_eq!(jei.authors, mods.iter().find(|m| m.id == 1001).unwrap().authors.iter().map(|a| a.name.clone()).collect::>()); + assert!(items[3].optional, "required: false in the manifest"); + assert_eq!(items[3].version, None, "a display name equal to the project's name says nothing more"); + let mut files = files; + files[0].display_name = "jei-1.20.1-forge-15.3.0.4.jar".into(); + let items = manifest_contents(&manifest, &files, &mods); + assert_eq!(items[2].version, None, "nor does one equal to the file name"); + } + + #[test] + fn describes_projects_named_by_id() { + let (_, _, mut mods) = resolved(); + mods[0].summary = "Shows recipes.".into(); + mods[0].categories = vec![api::Category { slug: "api-and-library".into(), ..Default::default() }, api::Category { slug: "performance".into(), ..Default::default() }]; + let mut items = vec![ + PackContentItem { site: Some(ContentSite::Curseforge), project_id: Some("1001".into()), ..PackContentItem::from_file("jei-15.jar", PackContentKind::Mod) }, + PackContentItem::from_file("other.jar", PackContentKind::Mod), + ]; + describe_items(&mut items, &mods, true); + let jei = items.iter().find(|i| i.project_id.is_some()).unwrap(); + assert_eq!(jei.name, "Just Enough Items"); + assert_eq!(jei.file_name.as_deref(), Some("jei-15.jar")); + assert_eq!(jei.description.as_deref(), Some("Shows recipes.")); + assert_eq!(jei.categories, ["library", "optimization"]); + let other = items.iter().find(|i| i.project_id.is_none()).unwrap(); + assert_eq!(other.name, "other"); + } + + #[test] + fn unknown_files_and_projects_stay_listed() { + let (manifest, _, _) = resolved(); + let items = manifest_contents(&manifest, &[], &[]); + assert_eq!(items.len(), manifest.files.len()); + assert!(items.iter().all(|i| i.kind == PackContentKind::Mod && i.page_url.as_deref().unwrap().starts_with("https://www.curseforge.com/projects/"))); + assert!(items.iter().any(|i| i.name == "Project 1001")); + } +} diff --git a/crates/cubby-curseforge/src/plan.rs b/crates/cubby-curseforge/src/plan.rs index c40d819..f400881 100644 --- a/crates/cubby-curseforge/src/plan.rs +++ b/crates/cubby-curseforge/src/plan.rs @@ -16,7 +16,7 @@ use crate::api; use crate::client::CurseForgeClient; use crate::manifest::{read_manifest, zip_has_folder, CfManifest}; -const IDS_PER_REQUEST: usize = 500; +pub(crate) const IDS_PER_REQUEST: usize = 500; const SITE: &str = "https://www.curseforge.com/minecraft"; /// Game folder where a project of this class goes, and the class slug used on the website. @@ -137,14 +137,14 @@ pub(crate) fn build_plan(manifest: &CfManifest, files: &[api::File], projects: & #[derive(Serialize)] #[serde(rename_all = "camelCase")] -struct FileIds<'a> { - file_ids: &'a [u64], +pub(crate) struct FileIds<'a> { + pub(crate) file_ids: &'a [u64], } #[derive(Serialize)] #[serde(rename_all = "camelCase")] -struct ModIds<'a> { - mod_ids: &'a [u64], +pub(crate) struct ModIds<'a> { + pub(crate) mod_ids: &'a [u64], } impl CurseForgeClient { @@ -221,7 +221,7 @@ impl CurseForgeClient { } } -fn unique(ids: impl Iterator) -> Vec { +pub(crate) fn unique(ids: impl Iterator) -> Vec { let mut seen = HashSet::new(); ids.filter(|id| seen.insert(*id)).collect() } diff --git a/crates/cubby-curseforge/tests/contents_live.rs b/crates/cubby-curseforge/tests/contents_live.rs new file mode 100644 index 0000000..a70d604 --- /dev/null +++ b/crates/cubby-curseforge/tests/contents_live.rs @@ -0,0 +1,28 @@ +//! Lists the contents of a real CurseForge modpack file. Needs network and `CUBBY_CURSEFORGE_API_KEY`; run with +//! `-- --ignored --nocapture`. + +use cubby_common::net::Http; +use cubby_common::packs::PackSort; +use cubby_curseforge::{api_key_from_env, CurseForgeClient}; + +#[tokio::test] +#[ignore = "needs network and a CurseForge API key"] +async fn lists_a_popular_pack() { + let Some(key) = api_key_from_env() else { + println!("no CurseForge API key: skipped"); + return; + }; + let client = CurseForgeClient::new(Http::new().unwrap(), key); + let pack = client.search("", PackSort::Downloads, 0, 1).await.unwrap().hits.remove(0); + let version = client.versions(pack.id.parse().unwrap()).await.unwrap().remove(0); + let dir = std::env::temp_dir().join(format!("cubby-cf-contents-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let items = client.pack_contents(pack.id.parse().unwrap(), version.id.parse().unwrap(), &dir).await.unwrap(); + println!("{} {}: {} items", pack.name, version.name, items.len()); + for i in items.iter().take(10) { + println!(" {:?} {} {:?} {:?} optional={}", i.kind, i.name, i.version, i.page_url, i.optional); + } + assert!(items.len() > 5); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the pack zip is deleted"); + let _ = std::fs::remove_dir(&dir); +} diff --git a/crates/cubby-curseforge/tests/resolve.rs b/crates/cubby-curseforge/tests/resolve.rs new file mode 100644 index 0000000..8b3a7a7 --- /dev/null +++ b/crates/cubby-curseforge/tests/resolve.rs @@ -0,0 +1,124 @@ +//! Resolving a mod and the projects it requires, against a tiny local HTTP server with hand-written answers. + +use std::sync::{Arc, Mutex}; + +use cubby_common::net::Http; +use cubby_common::packs::PackLoaderKind; +use cubby_curseforge::{CurseForgeClient, FileTarget}; +use serde_json::{json, Value}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +fn project(id: u64, name: &str) -> Value { + json!({ "id": id, "name": name, "slug": name.to_lowercase().replace(' ', "-"), "classId": 6, "links": {} }) +} + +fn file(id: u64, mod_id: u64, date: &str, versions: &[&str], requires: &[u64]) -> Value { + json!({ + "id": id, "modId": mod_id, "displayName": format!("file {id}"), "fileName": format!("f{id}.jar"), + "releaseType": 1, "fileDate": date, "fileLength": 100, "downloadUrl": format!("https://cdn.example/f{id}.jar"), + "hashes": [{ "value": format!("{id:040}"), "algo": 1 }], + "gameVersions": versions, + "dependencies": requires.iter().map(|m| json!({ "modId": m, "relationType": 3 })).collect::>(), + }) +} + +fn files_of(id: u64) -> Vec { + match id { + // the mod: an older NeoForge file and the Fabric one + 100 => vec![file(1001, 100, "2026-05-01", &["1.21.1", "NeoForge"], &[]), file(1002, 100, "2026-04-01", &["1.21.1", "Fabric"], &[200, 300])], + 200 => vec![file(2001, 200, "2026-05-01", &["1.21.1", "Fabric"], &[])], + 300 => vec![file(3001, 300, "2026-05-01", &["1.21.1", "Fabric"], &[400, 100])], + // nothing for Fabric + 400 => vec![file(4001, 400, "2026-05-01", &["1.21.1", "Forge"], &[])], + _ => Vec::new(), + } +} + +async fn serve() -> (String, Arc>>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Vec::new())); + let seen2 = seen.clone(); + tokio::spawn(async move { + loop { + let Ok((mut socket, _)) = listener.accept().await else { return }; + let seen = seen2.clone(); + tokio::spawn(async move { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let (head_end, len) = loop { + let n = socket.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + return; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_ascii_lowercase(); + let len = head.lines().find_map(|l| l.strip_prefix("content-length:")).and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + break (pos + 4, len); + } + }; + while buf.len() < head_end + len { + let n = socket.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + } + let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); + let mut first = head.lines().next().unwrap_or("").split(' '); + let (method, target) = (first.next().unwrap_or("").to_string(), first.next().unwrap_or("").to_string()); + let body: Value = serde_json::from_slice(&buf[head_end..]).unwrap_or(Value::Null); + seen.lock().unwrap().push(format!("{method} {target}")); + let path = target.split('?').next().unwrap_or(""); + let answer = if method == "POST" && path == "/v1/mods" { + let names = [(100, "My Mod"), (200, "Fabric API"), (300, "Some Lib"), (400, "Forge Only")]; + let ids: Vec = body["modIds"].as_array().unwrap().iter().filter_map(Value::as_u64).collect(); + Some(json!({ "data": names.iter().filter(|(id, _)| ids.contains(id)).map(|(id, n)| project(*id, n)).collect::>() })) + } else if let Some(id) = path.strip_prefix("/v1/mods/").and_then(|r| r.strip_suffix("/files")).and_then(|id| id.parse::().ok()) { + let data = files_of(id); + Some(json!({ "data": data, "pagination": { "index": 0, "pageSize": 50, "resultCount": data.len(), "totalCount": data.len() } })) + } else { + None + }; + let (status, payload) = match answer { + Some(v) => (200, v.to_string()), + None => (404, "not found".to_string()), + }; + let header = format!("HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", payload.len()); + let _ = socket.write_all(header.as_bytes()).await; + let _ = socket.write_all(payload.as_bytes()).await; + let _ = socket.shutdown().await; + }); + } + }); + (base, seen) +} + +#[tokio::test] +async fn resolves_required_projects_for_the_instance() { + let (base, seen) = serve().await; + let cf = CurseForgeClient::with_base_url(Http::new().unwrap(), "k".into(), base); + let target = FileTarget { game_version: Some("1.21.1".into()), loaders: vec![PackLoaderKind::Fabric] }; + + // Fabric API is already in the instance + let plan = cf.resolve(100, None, &target, |p| p.slug == "fabric-api").await.unwrap(); + let ids: Vec<(u64, Option, bool)> = plan.iter().map(|r| (r.project.id, r.file.as_ref().map(|f| f.id), r.dependency)).collect(); + assert_eq!(ids, vec![(100, Some(1002), false), (300, Some(3001), true), (400, None, true)]); + assert_eq!(plan[0].file.as_ref().unwrap().download_url.as_deref(), Some("https://cdn.example/f1002.jar")); + assert_eq!(plan[2].project.name, "Forge Only"); + + // the files are asked for the instance's Minecraft version + assert!(seen.lock().unwrap().iter().any(|r| r.starts_with("GET /v1/mods/100/files?") && r.contains("gameVersion=1.21.1"))); + + // a chosen file is used as it is + let unknown = cf.resolve(100, Some(1001), &target, |_| false).await; + // `/v1/mods/100/files/1001` isn't served: the error says so + assert!(unknown.is_err()); + + // no suitable file: the requested project still comes back, without a file + let none = cf.resolve(400, None, &target, |_| false).await.unwrap(); + assert_eq!(none.len(), 1); + assert!(none[0].file.is_none()); +} diff --git a/crates/cubby-ftb/src/api.rs b/crates/cubby-ftb/src/api.rs index 26c5a1a..84ef35f 100644 --- a/crates/cubby-ftb/src/api.rs +++ b/crates/cubby-ftb/src/api.rs @@ -158,6 +158,12 @@ pub struct File { pub size: Option, #[serde(default)] pub serveronly: bool, + /// The player may leave it out. + #[serde(default)] + pub optional: bool, + /// "mod", "resource", "config", "script"… + #[serde(default, rename = "type", deserialize_with = "null_default")] + pub kind: String, #[serde(default)] pub curseforge: Option, } diff --git a/crates/cubby-ftb/src/contents.rs b/crates/cubby-ftb/src/contents.rs new file mode 100644 index 0000000..0a1dcd5 --- /dev/null +++ b/crates/cubby-ftb/src/contents.rs @@ -0,0 +1,73 @@ +//! What a version of an FTB pack contains: its file list, which names CurseForge projects for most mods. + +use cubby_common::packs::{sort_contents, ContentSite, PackContentItem, PackContentKind}; +use cubby_common::Result; + +use crate::api; +use crate::client::{parse_id, FtbClient}; +use crate::plan::curseforge_page_url; + +/// The mods, resource packs and shader packs of a version, by file name (server-only files left out). A file +/// that comes from CurseForge carries its project id, for the app to name it. +pub fn version_contents(version: &api::VersionDetail) -> Vec { + let mut out = Vec::new(); + for file in version.files.iter().filter(|f| !f.serveronly && !f.name.is_empty()) { + let path = format!("{}/{}", file.path.trim_end_matches(['/', '\\']), file.name); + let kind = match PackContentKind::of_path(&path) { + Some(kind) => kind, + None if file.kind.eq_ignore_ascii_case("mod") => PackContentKind::Mod, + None => continue, + }; + let mut item = PackContentItem::from_file(&file.name, kind); + item.optional = file.optional; + if let Some(cf) = &file.curseforge { + let project = cf.project.clone().into_string(); + if !project.is_empty() && project != "0" { + item.page_url = Some(curseforge_page_url(&project)); + item.site = Some(ContentSite::Curseforge); + item.project_id = Some(project); + } + } + out.push(item); + } + sort_contents(&mut out); + out +} + +impl FtbClient { + /// The mods, resource packs and shader packs of version `version_id` of pack `pack_id`. + pub async fn contents(&self, pack_id: &str, version_id: &str) -> Result> { + let version = self.version_raw(parse_id(pack_id, "modpack")?, parse_id(version_id, "version")?).await?; + Ok(version_contents(&version)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + fn version(name: &str) -> api::VersionDetail { + let bytes = std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + #[test] + fn lists_mods_not_configs() { + let items = version_contents(&version("version_100_12632.json")); + let names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect(); + assert_eq!(names, ["AdvancedPeripherals-1.18.2-0.7.31r", "Applied-Botanics-1.0.3", "Applied-Mekanistics-1.2.2"]); + assert_eq!(items[0].file_name.as_deref(), Some("AdvancedPeripherals-1.18.2-0.7.31r.jar")); + assert_eq!(items[0].site, Some(ContentSite::Curseforge)); + assert_eq!(items[0].project_id.as_deref(), Some("431725")); + assert_eq!(items[0].page_url.as_deref(), Some("https://www.curseforge.com/projects/431725")); + assert!(items.iter().all(|i| i.kind == PackContentKind::Mod && !i.optional)); + } + + #[test] + fn leaves_out_server_only_files() { + let items = version_contents(&version("version_114_serveronly.json")); + let names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect(); + assert_eq!(names, ["extremesoundmuffler-3.39-forge-1.19.2", "ftbpromoter-19.2.52"]); + } +} diff --git a/crates/cubby-ftb/src/lib.rs b/crates/cubby-ftb/src/lib.rs index fd5e287..eeb0cc9 100644 --- a/crates/cubby-ftb/src/lib.rs +++ b/crates/cubby-ftb/src/lib.rs @@ -4,8 +4,10 @@ pub mod api; mod browse; mod client; +mod contents; mod plan; pub use browse::PackDetails; +pub use contents::version_contents; pub use client::{FtbClient, API_BASE, LEGACY_API_BASE}; pub use plan::curseforge_page_url; diff --git a/crates/cubby-ftb/tests/contents_live.rs b/crates/cubby-ftb/tests/contents_live.rs new file mode 100644 index 0000000..fe0fd68 --- /dev/null +++ b/crates/cubby-ftb/tests/contents_live.rs @@ -0,0 +1,19 @@ +//! Lists the contents of a real FTB pack version. Needs network; run with `-- --ignored --nocapture`. + +use cubby_common::net::Http; +use cubby_common::packs::PackSort; +use cubby_ftb::FtbClient; + +#[tokio::test] +#[ignore = "needs network"] +async fn lists_a_popular_pack() { + let ftb = FtbClient::new(Http::new().unwrap()); + let pack = ftb.search("", PackSort::Downloads, 0, 1).await.unwrap().hits.remove(0); + let version = ftb.versions(&pack.id).await.unwrap().remove(0); + let items = ftb.contents(&pack.id, &version.id).await.unwrap(); + println!("{} {}: {} items", pack.name, version.name, items.len()); + for i in items.iter().take(10) { + println!(" {:?} {} {:?} {:?} optional={}", i.kind, i.name, i.project_id, i.page_url, i.optional); + } + assert!(items.len() > 5); +} diff --git a/crates/cubby-instance/src/settings.rs b/crates/cubby-instance/src/settings.rs index fdaf77b..38197d2 100644 --- a/crates/cubby-instance/src/settings.rs +++ b/crates/cubby-instance/src/settings.rs @@ -137,7 +137,7 @@ pub struct Settings { /// Use Atkinson Hyperlegible instead of the regular UI fonts. pub hyperlegible: bool, pub reduce_motion: bool, - /// Check installed content for updates on Modrinth when an instance is opened. + /// Check installed content for updates on Modrinth when Cubby starts and when an instance is opened. pub check_updates: bool, pub accent: String, pub frame_mode: FrameMode, diff --git a/crates/cubby-modrinth/src/api.rs b/crates/cubby-modrinth/src/api.rs index 565960d..702a349 100644 --- a/crates/cubby-modrinth/src/api.rs +++ b/crates/cubby-modrinth/src/api.rs @@ -66,6 +66,9 @@ pub struct SearchHit { pub struct Project { #[serde(deserialize_with = "nullable")] pub id: String, + /// Id of the project's team (`GET /teams?ids=[...]`). + #[serde(deserialize_with = "nullable")] + pub team: String, #[serde(deserialize_with = "nullable")] pub slug: String, #[serde(deserialize_with = "nullable")] @@ -131,8 +134,12 @@ pub struct License { #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct GalleryItem { + /// A small copy, 350 px wide (`…_350.webp`). #[serde(deserialize_with = "nullable")] pub url: String, + /// The image as uploaded. Absent on older answers. + #[serde(deserialize_with = "nullable")] + pub raw_url: String, pub featured: bool, pub title: Option, pub description: Option, @@ -143,6 +150,8 @@ pub struct GalleryItem { #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct TeamMember { + #[serde(deserialize_with = "nullable")] + pub team_id: String, pub user: User, #[serde(deserialize_with = "nullable")] pub role: String, diff --git a/crates/cubby-modrinth/src/browse.rs b/crates/cubby-modrinth/src/browse.rs index b601642..9b9f2f9 100644 --- a/crates/cubby-modrinth/src/browse.rs +++ b/crates/cubby-modrinth/src/browse.rs @@ -21,10 +21,16 @@ const PACK_LOADERS: &[&str] = &["minecraft", "iris", "optifine", "canvas", "vani /// Modrinth search facets for a query: an AND of OR-groups. pub fn facets(q: &SearchQuery) -> Vec> { let mut out = vec![vec![format!("project_type:{}", q.kind.as_str())]]; - if let Some(version) = q.game_version.as_deref().filter(|v| !v.is_empty()) { + let versions: Vec<&str> = q.game_versions.iter().map(|v| v.trim()).filter(|v| !v.is_empty()).collect(); + if !versions.is_empty() { + out.push(versions.iter().map(|v| format!("versions:{v}")).collect()); + } else if let Some(version) = q.game_version.as_deref().filter(|v| !v.is_empty()) { out.push(vec![format!("versions:{version}")]); } - if matches!(q.kind, ProjectKind::Mod | ProjectKind::Modpack) { + let loaders: Vec<&str> = q.loaders.iter().map(|l| l.trim()).filter(|l| !l.is_empty() && *l != "vanilla").collect(); + if !loaders.is_empty() && matches!(q.kind, ProjectKind::Mod | ProjectKind::Modpack) { + out.push(loaders.iter().map(|l| format!("categories:{l}")).collect()); + } else if matches!(q.kind, ProjectKind::Mod | ProjectKind::Modpack) { // A Quilt instance runs Fabric mods too; a modpack must be for the loader itself. let loaders = match q.kind { ProjectKind::Mod => mod_loaders(q.loader.as_deref()), @@ -100,7 +106,7 @@ pub(crate) fn project_from_api(p: api::Project, author: String) -> Project { categories.extend(p.additional_categories.iter().filter(|c| !p.categories.contains(c)).cloned()); let mut gallery = p.gallery.clone(); gallery.sort_by_key(|g| (!g.featured, g.ordering)); - let featured_image = gallery.first().map(|g| g.url.clone()); + let featured_image = gallery.first().map(|g| full_url(g).to_owned()); let link = |u: &Option| u.clone().filter(|u| !u.trim().is_empty()); Project { hit: ProjectHit { @@ -125,7 +131,11 @@ pub(crate) fn project_from_api(p: api::Project, author: String) -> Project { }, gallery: gallery .into_iter() - .map(|g| GalleryImage { url: g.url, title: g.title, description: g.description, featured: g.featured }) + .map(|g| { + let url = full_url(&g).to_owned(); + let thumb_url = Some(g.url).filter(|t| !t.is_empty() && *t != url); + GalleryImage { url, thumb_url, title: g.title, description: g.description, featured: g.featured } + }) .collect(), links: Links { source: link(&p.source_url), @@ -289,6 +299,11 @@ impl Modrinth { } } +/// The uploaded image: Modrinth's `url` is a copy 350 px wide. +fn full_url(g: &crate::api::GalleryItem) -> &str { + if g.raw_url.is_empty() { &g.url } else { &g.raw_url } +} + #[cfg(test)] mod tests { use super::*; @@ -299,6 +314,8 @@ mod tests { kind, game_version: None, loader: None, + game_versions: Vec::new(), + loaders: Vec::new(), categories: Vec::new(), environment: None, sort: Sort::Relevance, @@ -307,6 +324,22 @@ mod tests { } } + #[test] + fn several_versions_and_loaders_match_any_of_them() { + let mut q = query(ProjectKind::Modpack); + q.game_version = Some("1.21.1".into()); + q.game_versions = vec!["1.20.1".into(), " ".into(), "1.21.1".into()]; + q.loaders = vec!["fabric".into(), "neoforge".into()]; + assert_eq!( + facets(&q), + vec![vec!["project_type:modpack"], vec!["versions:1.20.1", "versions:1.21.1"], vec!["categories:fabric", "categories:neoforge"]] + ); + // packs have no loader + let mut q = query(ProjectKind::ResourcePack); + q.loaders = vec!["fabric".into()]; + assert_eq!(facets(&q), [["project_type:resourcepack"]]); + } + #[test] fn facets_for_each_kind() { assert_eq!(facets(&query(ProjectKind::Mod)), [["project_type:mod"]]); @@ -395,7 +428,7 @@ mod tests { "categories":["adventure"],"additional_categories":["magic","adventure"],"source_url":"https://src","issues_url":"", "donation_urls":[{"id":"patreon","platform":"Patreon","url":"https://patreon"}],"followers":5, "license":{"id":"MIT","name":"MIT License","url":null},"versions":["a","b","c"], - "gallery":[{"url":"https://g1","featured":false,"ordering":0},{"url":"https://g2","featured":true,"title":"Main","ordering":1}]}"##, + "gallery":[{"url":"https://g1","featured":false,"ordering":0},{"url":"https://g2_350.webp","raw_url":"https://g2.png","featured":true,"title":"Main","ordering":1}]}"##, ) .unwrap(); let members: Vec = serde_json::from_str( @@ -408,8 +441,10 @@ mod tests { assert_eq!(p.hit.categories, ["adventure", "magic"]); assert_eq!(p.hit.license.as_deref(), Some("MIT")); assert_eq!(p.version_count, 3); - assert_eq!(p.gallery[0].url, "https://g2"); - assert_eq!(p.hit.featured_image.as_deref(), Some("https://g2")); + // full size for the banner and the viewer, the 350 px copy for thumbnails + assert_eq!((p.gallery[0].url.as_str(), p.gallery[0].thumb_url.as_deref()), ("https://g2.png", Some("https://g2_350.webp"))); + assert_eq!(p.hit.featured_image.as_deref(), Some("https://g2.png")); + assert_eq!((p.gallery[1].url.as_str(), p.gallery[1].thumb_url.as_deref()), ("https://g1", None)); assert_eq!(p.links.source.as_deref(), Some("https://src")); assert_eq!(p.links.issues, None); assert_eq!(p.links.donation, [Donation { platform: "Patreon".into(), url: "https://patreon".into() }]); diff --git a/crates/cubby-modrinth/src/client.rs b/crates/cubby-modrinth/src/client.rs index cee98be..e3e022b 100644 --- a/crates/cubby-modrinth/src/client.rs +++ b/crates/cubby-modrinth/src/client.rs @@ -129,6 +129,18 @@ impl Modrinth { Ok(out) } + /// The members of teams, by team id, in batches; one list per team Modrinth knows. + pub(crate) async fn teams_raw(&self, ids: &[String]) -> Result>> { + let mut out = Vec::new(); + for chunk in dedup(ids).chunks(IDS_PER_REQUEST) { + chunk.iter().try_for_each(|id| check_id(id))?; + let ids = serde_json::to_string(chunk).map_err(|e| Error::Other(e.to_string()))?; + let mut part: Vec> = self.get("/teams", &[("ids", ids)], "Modrinth teams").await?; + out.append(&mut part); + } + Ok(out) + } + /// Versions by id, in batches. Unknown ids are left out. pub(crate) async fn versions_raw(&self, ids: &[String]) -> Result> { let mut out = Vec::new(); @@ -176,17 +188,20 @@ impl Modrinth { /// `POST /version_files/update`: for each SHA-1, the newest version of its project for these loaders /// and game versions. - pub(crate) async fn latest_versions(&self, hashes: &[String], loaders: &[String], game_versions: &[String]) -> Result> { + /// `version_types` ("release", "beta", "alpha") limits the channels looked at; empty for all of them. + pub(crate) async fn latest_versions(&self, hashes: &[String], loaders: &[String], game_versions: &[String], version_types: &[&str]) -> Result> { #[derive(Serialize)] struct Body<'a> { hashes: &'a [String], algorithm: &'static str, loaders: &'a [String], game_versions: &'a [String], + #[serde(skip_serializing_if = "<[_]>::is_empty")] + version_types: &'a [&'a str], } let mut out = HashMap::new(); for chunk in dedup(hashes).chunks(HASHES_PER_REQUEST) { - let body = Body { hashes: chunk, algorithm: "sha1", loaders, game_versions }; + let body = Body { hashes: chunk, algorithm: "sha1", loaders, game_versions, version_types }; let part: HashMap = self.post("/version_files/update", &body, "Modrinth updates").await?; out.extend(part.into_iter().map(|(k, v)| (k.to_lowercase(), v))); } diff --git a/crates/cubby-modrinth/src/contents.rs b/crates/cubby-modrinth/src/contents.rs new file mode 100644 index 0000000..7ba74ea --- /dev/null +++ b/crates/cubby-modrinth/src/contents.rs @@ -0,0 +1,195 @@ +//! What a modpack version contains: the mods, resource packs and shader packs its `modrinth.index.json` lists, +//! named with one bulk `projects` call (and one bulk `versions` call for their version numbers). + +use std::collections::HashMap; +use std::path::Path; + +use cubby_common::packs::{sort_contents, ContentSite, PackContentItem, PackContentKind}; +use cubby_common::Result; + +use crate::api; +use crate::client::Modrinth; +use crate::mrpack::MrpackIndex; + +const CDN_DATA: &str = "https://cdn.modrinth.com/data/"; + +/// The project and version ids in a Modrinth CDN address +/// (`https://cdn.modrinth.com/data//versions//`). +pub fn ids_from_cdn_url(url: &str) -> Option<(String, String)> { + let rest = url.strip_prefix(CDN_DATA)?; + let mut parts = rest.split('/'); + let project = parts.next()?; + if parts.next()? != "versions" { + return None; + } + let version = parts.next()?; + parts.next()?; // the file name + let ok = |id: &str| !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric()); + (ok(project) && ok(version)).then(|| (project.to_string(), version.to_string())) +} + +/// The content files of a pack index, before the projects are looked up: named after their files, with the +/// Modrinth project (and version, in `version`) of the files hosted on Modrinth. Files the client doesn't +/// use, configs and other files outside `mods/`, `resourcepacks/` and `shaderpacks/` are left out. +pub fn index_contents(index: &MrpackIndex) -> Vec { + let mut out = Vec::new(); + for file in &index.files { + let client = file.env.as_ref().and_then(|e| e.client.as_deref()); + if client == Some("unsupported") { + continue; + } + let Some(kind) = PackContentKind::of_path(&file.path) else { continue }; + let file_name = file.path.rsplit(['/', '\\']).next().unwrap_or(&file.path); + let mut item = PackContentItem::from_file(file_name, kind); + item.optional = client == Some("optional"); + if let Some((project, version)) = file.downloads.iter().find_map(|u| ids_from_cdn_url(u)) { + item.site = Some(ContentSite::Modrinth); + item.project_id = Some(project); + item.version = Some(version); + } + out.push(item); + } + out +} + +/// The owner of each team (else its first member), by team id. +pub(crate) fn team_owners(teams: &[Vec]) -> HashMap { + let mut out = HashMap::new(); + for members in teams { + let owner = members.iter().find(|m| m.is_owner == Some(true) || m.role.eq_ignore_ascii_case("owner")).or_else(|| members.iter().min_by_key(|m| m.ordering)); + if let Some(m) = owner.filter(|m| !m.team_id.is_empty() && !m.user.username.is_empty()) { + out.insert(m.team_id.clone(), m.user.username.clone()); + } + } + out +} + +/// Fills in the names, icons, pages, descriptions, owners, categories and version numbers of `items` (from +/// [`index_contents`]) from the projects, versions and team owners Modrinth knows. An item whose version isn't +/// known keeps no version number. +pub(crate) fn name_contents(items: &mut [PackContentItem], projects: &[api::Project], versions: &[api::Version], owners: &HashMap) { + let projects: HashMap<&str, &api::Project> = projects.iter().map(|p| (p.id.as_str(), p)).collect(); + let versions: HashMap<&str, &api::Version> = versions.iter().map(|v| (v.id.as_str(), v)).collect(); + for item in items.iter_mut().filter(|i| i.site == Some(ContentSite::Modrinth)) { + let version_id = item.version.take(); + item.version = version_id.as_deref().and_then(|id| versions.get(id)).map(|v| v.version_number.trim().to_string()).filter(|v| !v.is_empty()); + let Some(project) = item.project_id.as_deref().and_then(|id| projects.get(id)) else { continue }; + if !project.title.trim().is_empty() { + item.name = project.title.trim().to_string(); + } + item.icon_url = project.icon_url.clone().filter(|u| !u.is_empty()); + item.description = Some(project.description.trim().to_string()).filter(|d| !d.is_empty()); + item.authors = owners.get(&project.team).cloned().into_iter().collect(); + item.categories = project.categories.clone(); + if !project.slug.is_empty() { + let section = if project.project_type.is_empty() { "mod" } else { project.project_type.as_str() }; + item.page_url = Some(format!("https://modrinth.com/{section}/{}", project.slug)); + } + } +} + +impl Modrinth { + /// The mods, resource packs and shader packs of the modpack version `version_id`. The `.mrpack` is + /// downloaded into `cache_dir` to read its index, then deleted. + pub async fn pack_contents(&self, version_id: &str, cache_dir: &Path) -> Result> { + let pack = self.fetch_modpack(version_id, cache_dir).await?; + if let Err(e) = std::fs::remove_file(&pack.archive) { + tracing::debug!("could not remove {}: {e}", pack.archive.display()); + } + let mut items = index_contents(&pack.index); + let project_ids: Vec = items.iter().filter_map(|i| i.project_id.clone()).collect(); + let version_ids: Vec = items.iter().filter(|i| i.project_id.is_some()).filter_map(|i| i.version.clone()).collect(); + if !project_ids.is_empty() { + let (projects, versions) = futures::try_join!(self.projects_raw(&project_ids), self.versions_raw(&version_ids))?; + // the owners are cosmetic: a failed call leaves the items without + let team_ids: Vec = projects.iter().map(|p| p.team.clone()).filter(|t| !t.is_empty()).collect(); + let owners = match self.teams_raw(&team_ids).await { + Ok(teams) => team_owners(&teams), + Err(e) => { + tracing::debug!("no team owners for the pack contents: {e}"); + HashMap::new() + } + }; + name_contents(&mut items, &projects, &versions, &owners); + } + sort_contents(&mut items); + Ok(items) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture(name: &str) -> Vec { + std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap() + } + + #[test] + fn cdn_urls() { + assert_eq!( + ids_from_cdn_url("https://cdn.modrinth.com/data/AANobbMI/versions/IZskON6d/sodium-fabric-0.5.8%2Bmc1.20.1.jar"), + Some(("AANobbMI".to_string(), "IZskON6d".to_string())) + ); + assert_eq!(ids_from_cdn_url("https://cdn.modrinth.com/data/AANobbMI/versions/IZskON6d/"), Some(("AANobbMI".into(), "IZskON6d".into()))); + assert_eq!(ids_from_cdn_url("https://cdn.modrinth.com/data/AANobbMI/images/x.png"), None); + assert_eq!(ids_from_cdn_url("https://github.com/a/b/releases/download/1/x.jar"), None); + assert_eq!(ids_from_cdn_url("https://cdn.modrinth.com/data/../versions/x/y.jar"), None); + } + + #[test] + fn index_lists_content_files() { + let index = MrpackIndex::parse(&fixture("modrinth.index.json")).unwrap(); + let items = index_contents(&index); + let names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect(); + // the server-only mod and the config file are left out + assert_eq!(names, ["sodium-fabric-0.5.8+mc1.20.1", "iris-mc1.20.1-1.7.0", "custom-mod", "FreshAnimations_v1.9", "ComplementaryReimagined_r5.2"]); + assert_eq!(items[0].site, Some(ContentSite::Modrinth)); + assert_eq!(items[0].project_id.as_deref(), Some("AANobbMI")); + assert_eq!(items[0].version.as_deref(), Some("IZskON6d")); + assert_eq!(items[0].kind, PackContentKind::Mod); + assert!(items[1].optional); + assert_eq!(items[2].site, None, "a file hosted elsewhere has no project"); + assert_eq!(items[3].kind, PackContentKind::ResourcePack); + assert_eq!(items[4].kind, PackContentKind::Shader); + } + + #[test] + fn projects_name_the_files() { + let index = MrpackIndex::parse(&fixture("modrinth.index.json")).unwrap(); + let mut items = index_contents(&index); + let project = api::Project { + id: "AANobbMI".into(), + slug: "sodium".into(), + project_type: "mod".into(), + title: "Sodium".into(), + icon_url: Some("https://cdn.modrinth.com/data/AANobbMI/icon.png".into()), + team: "4reLOAKe".into(), + description: "The fastest rendering optimization mod.".into(), + categories: vec!["optimization".into()], + ..Default::default() + }; + let version = api::Version { id: "IZskON6d".into(), project_id: "AANobbMI".into(), version_number: "mc1.20.1-0.5.8".into(), ..Default::default() }; + let member = |name: &str, owner: bool, ordering: i64| api::TeamMember { + team_id: "4reLOAKe".into(), + user: api::User { id: name.into(), username: name.into() }, + role: if owner { "Owner".into() } else { "Member".into() }, + is_owner: Some(owner), + ordering, + }; + let owners = team_owners(&[vec![member("helper", false, 0), member("jellysquid3", true, 1)]]); + name_contents(&mut items, &[project], &[version], &owners); + assert_eq!(items[0].authors, ["jellysquid3"]); + assert_eq!(items[0].description.as_deref(), Some("The fastest rendering optimization mod.")); + assert_eq!(items[0].categories, ["optimization"]); + assert_eq!(items[0].name, "Sodium"); + assert_eq!(items[0].version.as_deref(), Some("mc1.20.1-0.5.8")); + assert_eq!(items[0].page_url.as_deref(), Some("https://modrinth.com/mod/sodium")); + assert!(items[0].icon_url.is_some()); + // unknown to Modrinth: keeps its file name, loses the version id + assert_eq!(items[1].name, "iris-mc1.20.1-1.7.0"); + assert_eq!(items[1].version, None); + sort_contents(&mut items); + assert_eq!(items[0].name, "custom-mod"); + } +} diff --git a/crates/cubby-modrinth/src/datapacks.rs b/crates/cubby-modrinth/src/datapacks.rs index 1551657..f6f0812 100644 --- a/crates/cubby-modrinth/src/datapacks.rs +++ b/crates/cubby-modrinth/src/datapacks.rs @@ -3,9 +3,22 @@ use cubby_common::{Error, Result}; +use std::collections::HashMap; +use std::path::PathBuf; + use crate::client::Modrinth; use crate::model::FileInfo; +/// The Modrinth project and version a file on disk is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileProject { + pub project_id: String, + pub slug: String, + pub title: String, + pub version_id: String, + pub version_number: String, +} + impl Modrinth { /// The `.zip` of a datapack version: `version_id`, else the newest version of the project for `game_version`. pub async fn datapack_file(&self, id_or_slug: &str, version_id: Option<&str>, game_version: &str) -> Result { @@ -33,4 +46,34 @@ impl Modrinth { sha1: file.hashes.get("sha1").cloned().unwrap_or_default().to_lowercase(), }) } + + /// The Modrinth project of each file, by SHA-1, in the order given; `None` for a file Modrinth doesn't know + /// or that can't be read. For files outside the instance folders, like a world's datapacks. + pub async fn identify_paths(&self, paths: &[PathBuf]) -> Result>> { + let mut hashes = Vec::with_capacity(paths.len()); + for path in paths { + hashes.push(self.sha1_of(path).await.ok()); + } + let known: Vec = hashes.iter().flatten().cloned().collect(); + if known.is_empty() { + return Ok(vec![None; paths.len()]); + } + let versions = self.version_files(&known).await?; + let ids: Vec = versions.values().map(|v| v.project_id.clone()).collect(); + let projects: HashMap = self.projects_raw(&ids).await?.into_iter().map(|p| (p.id.clone(), p)).collect(); + Ok(hashes + .iter() + .map(|h| { + let v = versions.get(h.as_ref()?)?; + let p = projects.get(&v.project_id); + Some(FileProject { + project_id: v.project_id.clone(), + slug: p.map(|p| p.slug.clone()).unwrap_or_default(), + title: p.map(|p| p.title.clone()).unwrap_or_else(|| v.name.clone()), + version_id: v.id.clone(), + version_number: v.version_number.clone(), + }) + }) + .collect()) + } } diff --git a/crates/cubby-modrinth/src/install.rs b/crates/cubby-modrinth/src/install.rs index b2a6af0..6dea96b 100644 --- a/crates/cubby-modrinth/src/install.rs +++ b/crates/cubby-modrinth/src/install.rs @@ -107,6 +107,19 @@ fn update_loaders(folder: Folder, target: &Target) -> Vec { } } +/// Every value [`update_channels`] gives. +const UPDATE_CHANNEL_SETS: [&[&str]; 3] = [&["release"], &["release", "beta"], &[]]; + +/// The channels an installed version may be updated to: never a less stable one. A release only gets releases, a +/// beta gets releases and betas, an alpha (or a version Modrinth doesn't describe) gets anything (empty: no filter). +fn update_channels(current: Option<&api::Version>) -> &'static [&'static str] { + match current.map(|v| v.version_type.as_str()) { + Some("release") => UPDATE_CHANNEL_SETS[0], + Some("beta") => UPDATE_CHANNEL_SETS[1], + _ => UPDATE_CHANNEL_SETS[2], + } +} + /// A file with a newer version, and that version's primary file. struct PendingUpdate { local: LocalFile, @@ -158,16 +171,26 @@ impl Modrinth { Ok(Applied { renamed, error: first_error }) } - /// Newest version of each file (by SHA-1) for the target, from `/version_files/update`, one request per folder. - async fn latest_for(&self, files: &[&LocalFile], target: &Target) -> Result> { + /// Newest version of each file (by SHA-1) for the target, from `/version_files/update`: one request per + /// folder and per channel the file may move to (see [`update_channels`]); `current` is each file's version. + async fn latest_for(&self, files: &[&LocalFile], target: &Target, current: &HashMap) -> Result> { let mut out = HashMap::new(); for folder in Folder::ALL { - let hashes: Vec = files.iter().filter(|f| f.folder == folder).map(|f| f.sha1.clone()).collect(); let loaders = update_loaders(folder, target); - if hashes.is_empty() || loaders.is_empty() { + if loaders.is_empty() { continue; } - out.extend(self.latest_versions(&hashes, &loaders, std::slice::from_ref(&target.game_version)).await?); + for channels in UPDATE_CHANNEL_SETS { + let hashes: Vec = files + .iter() + .filter(|f| f.folder == folder && update_channels(current.get(&f.sha1)) == channels) + .map(|f| f.sha1.clone()) + .collect(); + if hashes.is_empty() { + continue; + } + out.extend(self.latest_versions(&hashes, &loaders, std::slice::from_ref(&target.game_version), channels).await?); + } } Ok(out) } @@ -192,7 +215,7 @@ impl Modrinth { let files = self.local_files(game_dir).await; let current = self.identify(&files).await?; let known: Vec = files.into_iter().filter(|f| current.contains_key(&f.sha1)).collect(); - let latest = self.latest_for(&known.iter().collect::>(), target).await?; + let latest = self.latest_for(&known.iter().collect::>(), target, ¤t).await?; let pending = Self::pending_updates(known, &latest, Some(¤t)); if pending.is_empty() { return Ok(Vec::new()); @@ -250,8 +273,10 @@ impl Modrinth { } } let files = self.hash_files(selected).await; - let latest = self.latest_for(&files.iter().collect::>(), target).await?; - let pending = Self::pending_updates(files, &latest, None); + // the installed versions decide which channels an update may come from + let current = self.identify(&files).await?; + let latest = self.latest_for(&files.iter().collect::>(), target, ¤t).await?; + let pending = Self::pending_updates(files, &latest, Some(¤t)); if pending.is_empty() { emit(sink, task, "Done", 1, 1); return Ok(Applied::default()); @@ -394,6 +419,18 @@ mod tests { } } + #[test] + fn updates_never_go_to_a_less_stable_channel() { + let v = |t: &str| api::Version { version_type: t.into(), ..Default::default() }; + assert_eq!(update_channels(Some(&v("release"))), ["release"]); + assert_eq!(update_channels(Some(&v("beta"))), ["release", "beta"]); + assert!(update_channels(Some(&v("alpha"))).is_empty(), "an alpha may move to anything"); + assert!(update_channels(None).is_empty()); + for t in ["release", "beta", "alpha", ""] { + assert!(UPDATE_CHANNEL_SETS.contains(&update_channels(Some(&v(t)))), "every set is asked for"); + } + } + #[test] fn pending_updates_skip_current_versions() { let files = vec![ @@ -436,10 +473,27 @@ mod tests { let current = m.version_files(std::slice::from_ref(&sha1)).await.unwrap(); assert_eq!(current.get(&sha1).map(|v| v.id.as_str()), Some(oldest.id.as_str())); let local = local(Folder::Mods, "lithium.jar", &sha1, true); - let latest = m.latest_for(&[&local], &target).await.unwrap(); + let latest = m.latest_for(&[&local], &target, ¤t).await.unwrap(); assert_eq!(latest.get(&sha1).map(|v| v.id.as_str()), Some(newest.id.as_str())); } + /// A release file is only offered releases, even when the project's newest version is a beta. + #[tokio::test] + #[ignore = "needs network"] + async fn live_release_stays_on_releases() { + let m = Modrinth::new(Http::new().unwrap()); + let target = Target::new("1.21.1", Some("fabric")); + let mut versions = m.project_versions_raw("sodium", &target.mod_loaders(), std::slice::from_ref(&target.game_version)).await.unwrap(); + versions.sort_by_key(|v| v.published_millis()); + let oldest_release = versions.iter().find(|v| v.version_type == "release").expect("Sodium has releases for 1.21.1"); + let sha1 = oldest_release.primary_file().unwrap().sha1().unwrap().to_lowercase(); + let current = m.version_files(std::slice::from_ref(&sha1)).await.unwrap(); + let local = local(Folder::Mods, "sodium.jar", &sha1, true); + let latest = m.latest_for(&[&local], &target, ¤t).await.unwrap(); + let newest_release = versions.iter().rev().find(|v| v.version_type == "release").unwrap(); + assert_eq!(latest.get(&sha1).map(|v| v.id.as_str()), Some(newest_release.id.as_str())); + } + #[tokio::test] async fn modpack_without_downloads_extracts_overrides() { use std::io::Write; diff --git a/crates/cubby-modrinth/src/lib.rs b/crates/cubby-modrinth/src/lib.rs index 5e09cc9..50adfff 100644 --- a/crates/cubby-modrinth/src/lib.rs +++ b/crates/cubby-modrinth/src/lib.rs @@ -4,6 +4,7 @@ pub mod api; mod browse; mod client; +mod contents; mod datapacks; mod export; mod install; @@ -13,6 +14,8 @@ pub mod mrpack; mod resolve; pub use browse::{facets, search_params}; +pub use contents::{ids_from_cdn_url, index_contents}; +pub use datapacks::FileProject; pub use export::{pack_dependencies, ExportSpec, ExportSummary}; pub use client::{Modrinth, API_BASE, USER_AGENT}; pub use model::*; diff --git a/crates/cubby-modrinth/src/local.rs b/crates/cubby-modrinth/src/local.rs index 50b7302..8b6f299 100644 --- a/crates/cubby-modrinth/src/local.rs +++ b/crates/cubby-modrinth/src/local.rs @@ -151,6 +151,7 @@ impl Modrinth { title: project.map(|p| p.title.clone()).filter(|t| !t.is_empty()).unwrap_or_else(|| f.file_name.clone()), icon_url: project.and_then(|p| p.icon_url.clone()).filter(|u| !u.is_empty()), version_number: version.version_number.clone(), + categories: project.map(|p| p.categories.iter().chain(&p.additional_categories).cloned().collect()).unwrap_or_default(), file_name: f.file_name, }) }) diff --git a/crates/cubby-modrinth/src/model.rs b/crates/cubby-modrinth/src/model.rs index 512aa36..7d0bd29 100644 --- a/crates/cubby-modrinth/src/model.rs +++ b/crates/cubby-modrinth/src/model.rs @@ -146,6 +146,10 @@ pub struct SearchQuery { pub game_version: Option, /// Launcher loader key: "vanilla", "fabric", "quilt", "forge", "neoforge". pub loader: Option, + /// Any of these game versions; used instead of `game_version` when not empty. + pub game_versions: Vec, + /// Any of these loaders (mods and modpacks); used instead of `loader` when not empty. + pub loaders: Vec, /// Category slugs, all required. pub categories: Vec, pub environment: Option, @@ -217,7 +221,10 @@ pub struct SearchResults { #[derive(Debug, Clone, PartialEq)] pub struct GalleryImage { + /// The image at full size: for the banner and the viewer. pub url: String, + /// A small copy for thumbnails, when the site has one. + pub thumb_url: Option, pub title: Option, pub description: Option, pub featured: bool, @@ -361,6 +368,8 @@ pub struct ContentSource { pub title: String, pub icon_url: Option, pub version_number: String, + /// The project's categories ("library", "optimization"...), main and additional. + pub categories: Vec, } /// A newer compatible version of an installed file. diff --git a/crates/cubby-modrinth/tests/contents_live.rs b/crates/cubby-modrinth/tests/contents_live.rs new file mode 100644 index 0000000..2b5b7cd --- /dev/null +++ b/crates/cubby-modrinth/tests/contents_live.rs @@ -0,0 +1,23 @@ +//! Lists the contents of a real modpack version. Needs network; run with `-- --ignored --nocapture`. + +use cubby_common::net::Http; +use cubby_modrinth::Modrinth; + +#[tokio::test] +#[ignore = "needs network"] +async fn lists_a_popular_modpack() { + let modrinth = Modrinth::new(Http::new().unwrap()); + let version = modrinth.versions("fabulously-optimized", None, None).await.unwrap().remove(0); + let dir = std::env::temp_dir().join(format!("cubby-contents-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let items = modrinth.pack_contents(&version.id, &dir).await.unwrap(); + println!("Fabulously Optimized {}: {} items", version.version_number, items.len()); + for i in &items { + println!(" {:?} {} {:?} by {:?} cats={:?}", i.kind, i.name, i.version, i.authors, i.categories); + } + assert!(items.len() > 5); + assert!(items.iter().filter(|i| !i.authors.is_empty()).count() > items.len() / 2, "most have an owner"); + assert!(items.iter().filter(|i| i.icon_url.is_some()).count() > items.len() / 2, "most are named from Modrinth"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the .mrpack is deleted"); + let _ = std::fs::remove_dir(&dir); +} diff --git a/crates/cubby-modrinth/tests/fixtures/modrinth.index.json b/crates/cubby-modrinth/tests/fixtures/modrinth.index.json new file mode 100644 index 0000000..56db9f6 --- /dev/null +++ b/crates/cubby-modrinth/tests/fixtures/modrinth.index.json @@ -0,0 +1,57 @@ +{ + "formatVersion": 1, + "game": "minecraft", + "versionId": "1.4.0", + "name": "Fixture Pack", + "summary": "A small pack for the contents tests", + "files": [ + { + "path": "mods/sodium-fabric-0.5.8+mc1.20.1.jar", + "hashes": { "sha1": "a0b6a0b6a0b6a0b6a0b6a0b6a0b6a0b6a0b6a0b6", "sha512": "00" }, + "env": { "client": "required", "server": "unsupported" }, + "downloads": ["https://cdn.modrinth.com/data/AANobbMI/versions/IZskON6d/sodium-fabric-0.5.8%2Bmc1.20.1.jar"], + "fileSize": 1032140 + }, + { + "path": "mods/iris-mc1.20.1-1.7.0.jar", + "hashes": { "sha1": "b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1" }, + "env": { "client": "optional", "server": "unsupported" }, + "downloads": ["https://cdn.modrinth.com/data/YL57xq9U/versions/s5eFLITc/iris-mc1.20.1-1.7.0.jar"], + "fileSize": 2253840 + }, + { + "path": "mods/server-only-tool.jar", + "hashes": { "sha1": "c2c2c2c2c2c2c2c2c2c2c2c2c2c2c2c2c2c2c2c2" }, + "env": { "client": "unsupported", "server": "required" }, + "downloads": ["https://cdn.modrinth.com/data/P7dR8mSH/versions/aaaaaaaa/server-only-tool.jar"], + "fileSize": 1000 + }, + { + "path": "mods/custom-mod.jar", + "hashes": { "sha1": "d3d3d3d3d3d3d3d3d3d3d3d3d3d3d3d3d3d3d3d3" }, + "downloads": ["https://github.com/example/custom-mod/releases/download/1.0/custom-mod.jar"], + "fileSize": 2000 + }, + { + "path": "config/sodium-options.json", + "hashes": { "sha1": "e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4" }, + "downloads": ["https://cdn.modrinth.com/data/AANobbMI/versions/IZskON6d/sodium-options.json"], + "fileSize": 300 + }, + { + "path": "resourcepacks/FreshAnimations_v1.9.zip", + "hashes": { "sha1": "f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5f5" }, + "env": { "client": "required", "server": "unsupported" }, + "downloads": ["https://cdn.modrinth.com/data/50dA9Sha/versions/u0g7XcV4/FreshAnimations_v1.9.zip"], + "fileSize": 4000000 + }, + { + "path": "shaderpacks/ComplementaryReimagined_r5.2.zip", + "hashes": { "sha1": "a6a6a6a6a6a6a6a6a6a6a6a6a6a6a6a6a6a6a6a6" }, + "env": { "client": "required", "server": "unsupported" }, + "downloads": ["https://cdn.modrinth.com/data/HVnmMxH1/versions/Ffn2RvQn/ComplementaryReimagined_r5.2.zip"], + "fileSize": 500000 + } + ], + "dependencies": { "minecraft": "1.20.1", "fabric-loader": "0.15.11" } +} diff --git a/crates/cubby-modrinth/tests/live.rs b/crates/cubby-modrinth/tests/live.rs index 072e776..9c70353 100644 --- a/crates/cubby-modrinth/tests/live.rs +++ b/crates/cubby-modrinth/tests/live.rs @@ -25,6 +25,8 @@ async fn search_mods_and_shaders() { kind: ProjectKind::Mod, game_version: Some("1.21.1".into()), loader: Some("quilt".into()), + game_versions: Vec::new(), + loaders: Vec::new(), categories: vec!["optimization".into()], environment: Some(Environment::Client), sort: Sort::Downloads, diff --git a/crates/cubby-packinstall/src/install.rs b/crates/cubby-packinstall/src/install.rs index 3c9c75b..4be9c11 100644 --- a/crates/cubby-packinstall/src/install.rs +++ b/crates/cubby-packinstall/src/install.rs @@ -208,6 +208,56 @@ pub fn extract_overrides(archive: &Path, prefix: &str, game_dir: &Path, mut on_p Ok(done) } +// Switching versions + +/// Folders whose files belong to the pack: an old version's file there that the new version doesn't have is +/// removed when switching. Configs and the rest are overwritten by the new version's overrides instead. +const PACK_CONTENT: [&str; 3] = ["mods", "resourcepacks", "shaderpacks"]; + +/// The files a plan puts in the game directory: downloads, files to get by hand, and its overrides' files. +pub fn plan_paths(plan: &PackPlan) -> Result> { + let mut out: Vec = plan.files.iter().map(|f| f.path.clone()).chain(plan.blocked.iter().map(|b| b.path.clone())).collect(); + for o in &plan.overrides { + let file = fs::File::open(&o.archive).map_err(|e| Error::io(&o.archive, e))?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| Error::Other(format!("{} isn't a valid zip file ({e}).", o.archive.display())))?; + let mut prefix = o.prefix.replace('\\', "/").trim_start_matches("./").to_string(); + if !prefix.is_empty() && !prefix.ends_with('/') { + prefix.push('/'); + } + for i in 0..zip.len() { + let Ok(entry) = zip.by_index(i) else { continue }; + if entry.is_dir() { + continue; + } + let name = entry.name().replace('\\', "/"); + if let Some(path) = name.strip_prefix(prefix.as_str()).and_then(safe_relative_path) { + out.push(path); + } + } + } + Ok(out) +} + +/// The old version's pack files (in mods, resourcepacks, shaderpacks) that the new version doesn't have: +/// the ones to remove before installing the new version. An optional file turned off (".disabled") counts as +/// the file itself. +pub fn switch_removals(old: &[PathBuf], new: &[PathBuf]) -> Vec { + let base = |p: &Path| -> PathBuf { + let s = p.to_string_lossy().replace('\\', "/"); + PathBuf::from(s.strip_suffix(".disabled").unwrap_or(&s)) + }; + let keep: HashSet = new.iter().map(|p| base(p)).collect(); + let mut out: Vec = Vec::new(); + for p in old { + let first = p.components().next().map(|c| c.as_os_str().to_string_lossy().to_string()).unwrap_or_default(); + let b = base(p); + if PACK_CONTENT.contains(&first.as_str()) && !keep.contains(&b) && !out.contains(&b) { + out.push(b); + } + } + out +} + // Local files /// The two kinds of modpack file the player can import. @@ -416,6 +466,23 @@ fn copy_into_place(source: &Path, target: &Path) -> std::io::Result<()> { #[cfg(test)] mod tests { + + #[test] + fn switching_removes_old_pack_files_only() { + let old = vec![ + PathBuf::from("mods/a-1.jar"), + PathBuf::from("mods/b-1.jar.disabled"), + PathBuf::from("mods/kept.jar"), + PathBuf::from("config/a.toml"), + PathBuf::from("resourcepacks/old.zip"), + ]; + let new = vec![PathBuf::from("mods/a-2.jar"), PathBuf::from("mods/kept.jar.disabled"), PathBuf::from("config/a.toml")]; + assert_eq!( + switch_removals(&old, &new), + vec![PathBuf::from("mods/a-1.jar"), PathBuf::from("mods/b-1.jar"), PathBuf::from("resourcepacks/old.zip")] + ); + } + use super::*; use cubby_common::events::NoopSink; diff --git a/crates/cubby-packinstall/tests/live.rs b/crates/cubby-packinstall/tests/live.rs index 6a9d49e..7e3143e 100644 --- a/crates/cubby-packinstall/tests/live.rs +++ b/crates/cubby-packinstall/tests/live.rs @@ -85,6 +85,8 @@ async fn mrpack_file_installs_and_is_kept() { kind: cubby_modrinth::ProjectKind::Modpack, game_version: None, loader: None, + game_versions: Vec::new(), + loaders: Vec::new(), categories: vec![], environment: None, sort: cubby_modrinth::Sort::Relevance, diff --git a/crates/cubby-technic/src/client.rs b/crates/cubby-technic/src/client.rs index 22857bf..7eb17e7 100644 --- a/crates/cubby-technic/src/client.rs +++ b/crates/cubby-technic/src/client.rs @@ -122,7 +122,7 @@ impl TechnicClient { // plumbing /// GET and decode; 404 becomes `Error::NotFound`. - async fn get(&self, url: &Url, what: &str) -> Result { + pub(crate) async fn get(&self, url: &Url, what: &str) -> Result { let response = self.http.client().get(url.clone()).send().await.map_err(|e| Error::http(url.as_str(), e))?; let status = response.status().as_u16(); if status == 404 { @@ -137,7 +137,7 @@ impl TechnicClient { } /// Slugs and builds go into a URL path: nothing that could change the path is accepted. -fn check_segment(s: &str) -> Result<&str> { +pub(crate) fn check_segment(s: &str) -> Result<&str> { if s.is_empty() || s == "." || s == ".." || s.len() > 200 || s.chars().any(|c| c.is_control() || c == '/' || c == '\\') { return Err(Error::Other(format!("\"{s}\" isn't a valid pack or build name."))); } diff --git a/crates/cubby-technic/src/contents.rs b/crates/cubby-technic/src/contents.rs new file mode 100644 index 0000000..5cb55a0 --- /dev/null +++ b/crates/cubby-technic/src/contents.rs @@ -0,0 +1,88 @@ +//! What a build of a Technic pack contains. A Solder build lists its mods (with display names and pages when +//! the server answers `?include=mods`); a pack that is a single zip has no list short of downloading it. + +use cubby_common::packs::{sort_contents, PackContentItem, PackContentKind}; +use cubby_common::{Error, Result}; + +use crate::client::{check_segment, make_url, TechnicClient}; +use crate::model::SolderBuild; + +/// Solder entries that are the loader rather than a mod. +const LOADER_SLUGS: [&str; 8] = ["forge", "minecraftforge", "neoforge", "fabric", "fabric-loader", "fabricloader", "quilt", "quilt-loader"]; + +/// The mods of a Solder build, the loader left out. +pub fn build_contents(build: &SolderBuild) -> Vec { + let mut out = Vec::new(); + for m in build.mods.iter().filter(|m| !m.name.trim().is_empty()) { + if LOADER_SLUGS.contains(&m.name.trim().to_ascii_lowercase().as_str()) { + continue; + } + let file = m.url.rsplit('/').next().unwrap_or_default(); + let mut item = PackContentItem::from_file(file, PackContentKind::Mod); + item.name = m.pretty_name.as_deref().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(m.name.trim()).to_string(); + item.version = Some(m.version.trim().to_string()).filter(|v| !v.is_empty()); + item.page_url = m.link.clone().filter(|l| l.starts_with("https://") || l.starts_with("http://")); + item.description = m.description.as_deref().map(str::trim).filter(|d| !d.is_empty()).map(str::to_string); + item.authors = m.author.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(str::to_string).into_iter().collect(); + out.push(item); + } + sort_contents(&mut out); + out +} + +impl TechnicClient { + /// The mods of build `version_id` of a pack; `None` for a pack that is a single zip, which doesn't list them. + pub async fn contents(&self, slug: &str, version_id: &str) -> Result>> { + let pack = self.pack(slug).await?; + if !pack.is_solder() { + return Ok(None); + } + let version_id = version_id.trim(); + if version_id.is_empty() { + return Err(Error::Other(format!("Choose a version of {}.", pack.display_name))); + } + let root = pack.solder_url.as_deref().unwrap_or_default(); + // Display names come with `include=mods`; a server that doesn't take it still answers the plain build. + let url = make_url(root, &["modpack", check_segment(&pack.name)?, check_segment(version_id)?], &[("include", "mods")])?; + let detailed = self.get::(&url, &format!("build {version_id} of {}", pack.display_name)).await; + let build = match detailed { + Ok(build) => build, + Err(e) => { + tracing::debug!("Solder build {version_id} of {slug} with include=mods: {e}"); + self.solder_build(&pack, version_id).await? + } + }; + Ok(Some(build_contents(&build))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Path; + + fn build(name: &str) -> SolderBuild { + let bytes = std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + #[test] + fn lists_the_mods_of_a_build() { + let items = build_contents(&build("solder_build_1122.json")); + let names: Vec<(&str, Option<&str>)> = items.iter().map(|i| (i.name.as_str(), i.version.as_deref())).collect(); + assert_eq!(names, [("additionalbanners", Some("1.12.2-1.1.77")), ("additionalpipes", Some("1.12.2-6.0.0.9-technic"))]); + assert_eq!(items[0].file_name.as_deref(), Some("additionalbanners-1.12.2-1.1.77.zip")); + assert!(items.iter().all(|i| i.site.is_none() && !i.optional)); + } + + #[test] + fn uses_display_names_and_leaves_out_the_loader() { + let items = build_contents(&build("solder_build_mods.json")); + let names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect(); + assert_eq!(names, ["Applied Energistics 2", "jei"]); + assert_eq!(items[0].page_url.as_deref(), Some("https://appliedenergistics.org")); + assert_eq!(items[0].authors, ["AlgorithmX2"]); + assert!(items[0].description.as_deref().unwrap().starts_with("A mod about matter")); + assert_eq!(items[1].page_url, None, "not a web address"); + } +} diff --git a/crates/cubby-technic/src/lib.rs b/crates/cubby-technic/src/lib.rs index 3f7ca4c..3675081 100644 --- a/crates/cubby-technic/src/lib.rs +++ b/crates/cubby-technic/src/lib.rs @@ -1,10 +1,12 @@ //! Technic Platform modpacks: browse packs and plan installs of both single-zip and Solder packs. mod client; +mod contents; mod detect; mod model; mod plan; +pub use contents::build_contents; pub use client::{TechnicClient, API_BASE, API_BUILD}; pub use detect::{detect, Detected}; pub use model::{SolderBuild, SolderMod, TechnicPack}; diff --git a/crates/cubby-technic/src/model.rs b/crates/cubby-technic/src/model.rs index 024e5a6..c562c70 100644 --- a/crates/cubby-technic/src/model.rs +++ b/crates/cubby-technic/src/model.rs @@ -54,6 +54,18 @@ pub struct SolderMod { pub url: String, #[serde(default)] pub filesize: Option, + /// The mod's display name, when the build was asked `?include=mods`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pretty_name: Option, + /// The mod's web page (`?include=mods`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link: Option, + /// `?include=mods`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub author: Option, + /// `?include=mods`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, } /// A Solder build: `GET {solder}/modpack/{slug}/{build}`. diff --git a/crates/cubby-technic/tests/contents_live.rs b/crates/cubby-technic/tests/contents_live.rs new file mode 100644 index 0000000..50fc0a9 --- /dev/null +++ b/crates/cubby-technic/tests/contents_live.rs @@ -0,0 +1,17 @@ +//! Lists the contents of a real Technic Solder build. Needs network; run with `-- --ignored --nocapture`. + +use cubby_common::net::Http; +use cubby_technic::TechnicClient; + +#[tokio::test] +#[ignore = "needs network"] +async fn lists_a_solder_build() { + let technic = TechnicClient::new(Http::new().unwrap()); + let version = technic.versions("tekkitmain").await.unwrap().remove(0); + let items = technic.contents("tekkitmain", &version.id).await.unwrap().expect("a Solder pack lists its mods"); + println!("Tekkit {}: {} items", version.name, items.len()); + for i in items.iter().take(10) { + println!(" {} {:?} {:?}", i.name, i.version, i.page_url); + } + assert!(items.len() > 5); +} diff --git a/crates/cubby-technic/tests/fixtures/solder_build_mods.json b/crates/cubby-technic/tests/fixtures/solder_build_mods.json new file mode 100644 index 0000000..18adfb1 --- /dev/null +++ b/crates/cubby-technic/tests/fixtures/solder_build_mods.json @@ -0,0 +1,46 @@ +{ + "minecraft": "1.12.2", + "forge": null, + "java": "1.8", + "memory": "4096", + "mods": [ + { + "id": 12, + "name": "forge", + "version": "1.12.2-14.23.5.2860", + "md5": "2d5a8a1b1c5e8b4f0f3a8d4a3c9b2e10", + "filesize": 4500000, + "url": "https://mirror.example.net/mods/forge/forge-1.12.2-14.23.5.2860.zip", + "pretty_name": "Minecraft Forge", + "author": "LexManos", + "description": "", + "link": "https://files.minecraftforge.net", + "donate": null + }, + { + "id": 40, + "name": "appliedenergistics2", + "version": "rv6-stable-7", + "md5": "f4d7c6a2e9b0c1d2e3f4a5b6c7d8e9f0", + "filesize": 4800000, + "url": "https://mirror.example.net/mods/appliedenergistics2/appliedenergistics2-rv6-stable-7.zip", + "pretty_name": "Applied Energistics 2", + "author": "AlgorithmX2", + "description": "A mod about matter, energy and using them to conjure items.", + "link": "https://appliedenergistics.org", + "donate": null + }, + { + "id": 41, + "name": "jei", + "version": "1.12.2-4.16.1.302", + "md5": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", + "filesize": 600000, + "url": "https://mirror.example.net/mods/jei/jei-1.12.2-4.16.1.302.zip", + "pretty_name": "", + "author": "mezz", + "link": "javascript:alert(1)", + "donate": null + } + ] +} diff --git a/src-tauri/src/cf_resources.rs b/src-tauri/src/cf_resources.rs index 205042a..3480687 100644 --- a/src-tauri/src/cf_resources.rs +++ b/src-tauri/src/cf_resources.rs @@ -1,28 +1,52 @@ -//! CurseForge mods, resource packs and shader packs for Discover, shaped like the Modrinth results so the -//! same cards show them. Modpacks have their own commands in `packs.rs`. +//! CurseForge mods, resource packs, shader packs and datapacks for Discover: searched with CurseForge's own +//! filters, shaped like the Modrinth results so the same cards show them, and installed straight into the +//! instance (or the world, for a datapack) with the projects they require. Modpacks have their own commands in +//! `packs.rs`. -use cubby_common::packs::{PackLoaderKind, PackSort}; -use cubby_curseforge::{ResourceKind, ResourceQuery}; -use serde::Serialize; -use tauri::State; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; -use crate::dto::{ProjectHitDto, ProjectQueryDto, SearchResultsDto}; +use cubby_common::net::Download; +use cubby_common::packs::{PackChannel, PackLoaderKind, PackSort}; +use cubby_curseforge::{best_file, CfFile, CurseForgeClient, FileTarget, ResourceKind, ResourceQuery}; +use cubby_instance::Instance; +use cubby_modrinth::{Folder, InstallPlan, PlanItem, Reason}; +use serde::{Deserialize, Serialize}; +use tauri::{AppHandle, Manager, State}; + +use crate::commands::{download_concurrency, ensure_stopped, run_task, CmdResult, OrMessage, PackSelection}; +use crate::dto::{GalleryImageDto, ProjectDto, ProjectHitDto, ProjectLinksDto, ProjectQueryDto, SearchResultsDto}; use crate::state::Core; const KEY_MESSAGE: &str = "CurseForge needs an API key. Add yours in Settings."; -fn kind_of(kind: &str) -> Result { +fn client(core: &Core) -> CmdResult { + core.curseforge().ok_or_else(|| KEY_MESSAGE.to_string()) +} + +fn kind_of(kind: &str) -> CmdResult { match kind { "mod" => Ok(ResourceKind::Mod), "shader" => Ok(ResourceKind::Shader), "resourcepack" => Ok(ResourceKind::ResourcePack), - "modpack" => Err("CurseForge modpacks are browsed with the modpack commands.".into()), + "datapack" => Ok(ResourceKind::Datapack), + "modpack" => Ok(ResourceKind::Modpack), other => Err(format!("Unknown project type: {other}.")), } } -fn loader_of(key: &str) -> Option { - match key { +fn kind_name(kind: ResourceKind) -> &'static str { + match kind { + ResourceKind::Mod => "mod", + ResourceKind::Shader => "shader", + ResourceKind::ResourcePack => "resourcepack", + ResourceKind::Datapack => "datapack", + ResourceKind::Modpack => "modpack", + } +} + +pub(crate) fn loader_of(key: &str) -> Option { + match key.trim().to_ascii_lowercase().as_str() { "fabric" => Some(PackLoaderKind::Fabric), "quilt" => Some(PackLoaderKind::Quilt), "forge" => Some(PackLoaderKind::Forge), @@ -31,11 +55,21 @@ fn loader_of(key: &str) -> Option { } } +/// Loaders whose mods run with the launcher loader `key`: a Quilt instance also runs Fabric mods. +fn runs_with(key: &str) -> Vec { + match loader_of(key) { + Some(PackLoaderKind::Quilt) => vec![PackLoaderKind::Quilt, PackLoaderKind::Fabric], + Some(l) => vec![l], + None => Vec::new(), + } +} + fn sort_of(sort: &str) -> PackSort { match sort { "downloads" | "follows" => PackSort::Downloads, "updated" => PackSort::Updated, "newest" => PackSort::Newest, + "name" => PackSort::Name, _ => PackSort::Relevance, } } @@ -49,6 +83,24 @@ fn loader_name(kind: PackLoaderKind) -> &'static str { } } +fn channel_name(c: PackChannel) -> &'static str { + match c { + PackChannel::Release => "release", + PackChannel::Beta => "beta", + PackChannel::Alpha => "alpha", + } +} + +fn parse_id(id: &str, what: &str) -> CmdResult { + id.trim().parse().map_err(|_| format!("{id:?} isn't a valid CurseForge {what} ID.")) +} + +fn instance_loader(inst: &Instance) -> String { + crate::dto::LoaderDto::from(&inst.loader).kind +} + +// Search + #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct CategoryDto { @@ -56,63 +108,638 @@ pub struct CategoryDto { pub name: String, } -/// The categories of mods, shader packs or resource packs on CurseForge. +/// Filters on top of a search query, applied by the source itself (CurseForge or Modrinth): several +/// Minecraft versions and loaders, and (CurseForge) category ids. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct SearchFiltersDto { + /// Minecraft versions (CurseForge takes 4 at most). + pub game_versions: Vec, + /// Launcher loader keys ("fabric", "neoforge"...). + pub loaders: Vec, + /// Category ids (CurseForge takes 10 at most). + pub categories: Vec, +} + +impl SearchFiltersDto { + fn loaders(&self) -> Vec { + self.loaders.iter().filter_map(|l| loader_of(l)).collect() + } + + fn categories(&self) -> Vec { + self.categories.iter().filter_map(|c| c.trim().parse().ok()).collect() + } +} + +/// The categories of a kind of project on CurseForge. #[tauri::command] -pub async fn curseforge_categories(core: State<'_, Core>, kind: String) -> Result, String> { - let client = core.curseforge().ok_or_else(|| KEY_MESSAGE.to_string())?; - let categories = client.resource_categories(kind_of(&kind)?).await.map_err(crate::dto::message)?; +pub async fn curseforge_categories(core: State<'_, Core>, kind: String) -> CmdResult> { + let categories = client(&core)?.resource_categories(kind_of(&kind)?).await.msg()?; Ok(categories.into_iter().map(|c| CategoryDto { id: c.id.to_string(), name: c.name }).collect()) } -/// Searches CurseForge with the same query the Modrinth search takes. Categories and the client/server -/// filter are Modrinth's: only the first category (a CurseForge category id) is used. +/// Searches CurseForge with the query the Modrinth search takes, plus CurseForge's own filters. `query.categories` +/// are CurseForge category ids. The instance's version and loader (`query.gameVersion`, `query.loader`) apply +/// when the filters name none. #[tauri::command] -pub async fn curseforge_search(core: State<'_, Core>, query: ProjectQueryDto) -> Result { - let client = core.curseforge().ok_or_else(|| KEY_MESSAGE.to_string())?; +pub async fn curseforge_search(core: State<'_, Core>, query: ProjectQueryDto, filters: Option) -> CmdResult { + let filters = filters.unwrap_or_default(); let kind = kind_of(&query.kind)?; - let wanted = ResourceQuery { - kind, - text: query.query.clone(), - game_version: query.game_version.clone(), - loader: query.loader.as_deref().and_then(loader_of), - category: query.categories.first().and_then(|c| c.trim().parse().ok()), - sort: sort_of(&query.sort), - offset: query.offset, - limit: query.limit, + let game_versions = if filters.game_versions.is_empty() { query.game_version.clone().into_iter().collect() } else { filters.game_versions.clone() }; + let loaders = if filters.loaders.is_empty() { query.loader.as_deref().map(runs_with).unwrap_or_default() } else { filters.loaders() }; + let mut categories: Vec = query.categories.iter().filter_map(|c| c.trim().parse().ok()).collect(); + categories.extend(filters.categories()); + let wanted = ResourceQuery { kind, text: query.query.clone(), game_versions, loaders, categories, sort: sort_of(&query.sort), offset: query.offset, limit: query.limit }; + let page = client(&core)?.search_resources(&wanted).await.msg()?; + let hits: Vec = page.hits.into_iter().map(|h| hit_dto(h, kind)).collect(); + let total = page.total.unwrap_or(hits.len() as u64); + Ok(SearchResultsDto { hits, total, offset: query.offset, limit: query.limit }) +} + +/// A search hit or project summary in the shape of a Modrinth hit. +fn hit_dto(h: cubby_common::packs::PackSummary, kind: ResourceKind) -> ProjectHitDto { + let updated = h.updated.clone().unwrap_or_default(); + ProjectHitDto { + id: h.id, + slug: h.website_url.as_deref().and_then(|u| u.trim_end_matches('/').rsplit('/').next()).unwrap_or_default().to_string(), + kind: kind_name(kind), + title: h.name, + author: h.authors.first().cloned().unwrap_or_default(), + summary: h.summary, + icon_url: h.icon_url, + categories: Vec::new(), + downloads: h.downloads.unwrap_or(0), + follows: 0, + published: updated.clone(), + updated, + game_versions: h.minecraft, + loaders: h.loaders.into_iter().map(|l| loader_name(l).to_string()).collect(), + client_side: "unknown", + server_side: "unknown", + license: None, + featured_image: None, + } +} + +/// A CurseForge project page, in the shape of a Modrinth one (`Project` in types.ts) plus where it comes from. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CfProjectPageDto { + #[serde(flatten)] + pub project: ProjectDto, + /// Always "curseforge". + pub source: &'static str, + /// The project's page on curseforge.com. + pub page_url: String, +} + +/// A CurseForge project page: summary, description (HTML, sanitized by the page), screenshots and links. +#[tauri::command] +pub async fn curseforge_project(core: State<'_, Core>, project_id: String, kind: String) -> CmdResult { + let kind = kind_of(&kind)?; + let p = client(&core)?.pack(parse_id(&project_id, "project")?).await.msg()?; + let page_url = p.links.website.clone().or_else(|| p.summary.website_url.clone()).unwrap_or_else(|| format!("https://www.curseforge.com/projects/{project_id}")); + let mut hit = hit_dto(p.summary, kind); + if hit.slug.is_empty() { + hit.slug = p.slug.clone(); + } + hit.categories = p.categories; + if let Some(created) = p.created.filter(|c| !c.is_empty()) { + hit.published = created; + } + hit.featured_image = p.screenshots.first().map(|s| s.url.clone()); + let project = ProjectDto { + hit, + body: p.description_html, + gallery: p + .screenshots + .iter() + .enumerate() + .map(|(i, s)| GalleryImageDto { url: s.url.clone(), thumb_url: s.thumbnail_url.clone().filter(|t| !t.is_empty()), title: s.title.clone(), description: None, featured: i == 0 }) + .collect(), + links: ProjectLinksDto { source: p.links.source, issues: p.links.issues, wiki: p.links.wiki, discord: None, donation: Vec::new() }, + version_count: 0, }; - let page = client.search_resources(&wanted).await.map_err(crate::dto::message)?; - let kind_name: &'static str = match kind { - ResourceKind::Mod => "mod", - ResourceKind::Shader => "shader", - ResourceKind::ResourcePack => "resourcepack", + Ok(CfProjectPageDto { project, source: "curseforge", page_url }) +} + +/// CurseForge modpacks with CurseForge's filters, for `pack_search`. +pub(crate) async fn search_modpacks(core: &Core, text: &str, sort: PackSort, offset: u32, limit: u32, filters: &SearchFiltersDto) -> CmdResult { + let wanted = ResourceQuery { + kind: ResourceKind::Modpack, + text: text.to_string(), + game_versions: filters.game_versions.clone(), + loaders: filters.loaders(), + categories: filters.categories(), + sort, + offset, + limit, }; - let hits: Vec = page - .hits - .into_iter() - .map(|h| { - let updated = h.updated.clone().unwrap_or_default(); - ProjectHitDto { - id: h.id, - slug: h.website_url.as_deref().and_then(|u| u.rsplit('/').next()).unwrap_or_default().to_string(), - kind: kind_name, - title: h.name, - author: h.authors.first().cloned().unwrap_or_default(), - summary: h.summary, - icon_url: h.icon_url, - categories: Vec::new(), - downloads: h.downloads.unwrap_or(0), - follows: 0, - published: updated.clone(), - updated, - game_versions: h.minecraft, - loaders: h.loaders.into_iter().map(|l| loader_name(l).to_string()).collect(), - client_side: "unknown", - server_side: "unknown", - license: None, - featured_image: None, + client(core)?.search_resources(&wanted).await.msg() +} + +// What's in an instance + +/// A content file of the instance that CurseForge knows. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CfInstalledDto { + pub project_id: String, + pub file_id: String, + pub file_name: String, + /// "mods", "resourcepacks" or "shaderpacks". + pub folder: &'static str, + /// Cubby downloaded this file from CurseForge (it may be on Modrinth too). + pub from_curseforge: bool, +} + +const FOLDERS: [Folder; 3] = [Folder::Mods, Folder::ResourcePacks, Folder::ShaderPacks]; + +/// Mods (`.jar`, `.zip`, also disabled), resource packs and shader packs (`.zip`) of the game directory. +fn content_files(game_dir: &Path) -> Vec<(Folder, String, PathBuf)> { + let mut out = Vec::new(); + for folder in FOLDERS { + let Ok(rd) = std::fs::read_dir(game_dir.join(folder.as_str())) else { continue }; + for entry in rd.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let lower = name.to_lowercase(); + let base = lower.strip_suffix(".disabled").filter(|_| folder == Folder::Mods).unwrap_or(&lower); + let wanted = match folder { + Folder::Mods => base.ends_with(".jar") || base.ends_with(".zip"), + _ => lower.ends_with(".zip"), + }; + if wanted && !name.starts_with('.') && entry.path().is_file() { + out.push((folder, name, entry.path())); } + } + } + out +} + +/// The CurseForge fingerprint of each file, read again only when its size or modification time changed. +fn fingerprints(core: &Core, files: &[(Folder, String, PathBuf)]) -> Vec> { + files + .iter() + .map(|(_, _, path)| { + let meta = std::fs::metadata(path).ok()?; + let (size, modified) = (meta.len(), meta.modified().ok()?); + if let Some((s, m, print)) = core.cf_prints.lock().expect("fingerprint cache").get(path).copied() + && s == size + && m == modified + { + return Some(print); + } + let bytes = std::fs::read(path).ok()?; + let print = cubby_curseforge::fingerprint(&bytes); + core.cf_prints.lock().expect("fingerprint cache").insert(path.clone(), (size, modified, print)); + Some(print) + }) + .collect() +} + +#[derive(Debug, Clone)] +struct InstalledFile { + project_id: u64, + file_id: u64, + folder: Folder, + file_name: String, +} + +/// The files of the game directory CurseForge knows, by exact fingerprint. +async fn installed_files(app: &AppHandle, cf: &CurseForgeClient, game_dir: &Path) -> CmdResult> { + let dir = game_dir.to_path_buf(); + let app2 = app.clone(); + let (files, prints) = crate::commands::blocking(move || { + let core = app2.state::(); + let files = content_files(&dir); + let prints = fingerprints(&core, &files); + Ok((files, prints)) + }) + .await?; + let known: Vec = prints.iter().flatten().copied().collect(); + if known.is_empty() { + return Ok(Vec::new()); + } + let matches = cf.match_fingerprints(&known).await.msg()?; + Ok(files + .into_iter() + .zip(prints) + .filter_map(|((folder, file_name, _), print)| { + let (project_id, file_id) = *matches.get(&print?)?; + Some(InstalledFile { project_id, file_id, folder, file_name }) + }) + .collect()) +} + +/// The mods, resource packs and shader packs of the instance that come from CurseForge. +#[tauri::command] +pub async fn curseforge_installed(app: AppHandle, core: State<'_, Core>, instance_id: String) -> CmdResult> { + let inst = core.store.get(&instance_id).msg()?; + let cf = client(&core)?; + let files = installed_files(&app, &cf, &core.store.game_dir(&inst)).await?; + let origins = crate::origins::load(&core.paths.instance(&inst.id)); + Ok(files + .into_iter() + .map(|f| CfInstalledDto { + from_curseforge: origins.get(&crate::origins::key(f.folder.as_str(), &f.file_name)).is_some_and(|s| s == "curseforge"), + project_id: f.project_id.to_string(), + file_id: f.file_id.to_string(), + file_name: f.file_name, + folder: f.folder.as_str(), + }) + .collect()) +} + +// Files + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CfFileDto { + pub id: String, + pub name: String, + pub file_name: String, + pub channel: &'static str, + pub game_versions: Vec, + pub loaders: Vec, + pub released: Option, + pub size: Option, + pub downloads: u64, + /// False: the author only lets it be downloaded on curseforge.com. + pub downloadable: bool, +} + +impl From<&CfFile> for CfFileDto { + fn from(f: &CfFile) -> Self { + Self { + id: f.id.to_string(), + name: f.name.clone(), + file_name: f.file_name.clone(), + channel: channel_name(f.channel), + game_versions: f.minecraft.clone(), + loaders: f.loaders.iter().map(|l| loader_name(*l).to_string()).collect(), + released: f.released.clone(), + size: f.size, + downloads: f.downloads, + downloadable: f.download_url.is_some(), + } + } +} + +/// The newest files of a project, for a Minecraft version (every version when `None`), newest first. +#[tauri::command] +pub async fn curseforge_files(core: State<'_, Core>, project_id: String, game_version: Option) -> CmdResult> { + let id = parse_id(&project_id, "project")?; + let files = client(&core)?.files_for_version(id, game_version.as_deref()).await.msg()?; + Ok(files.iter().map(CfFileDto::from).collect()) +} + +// Datapacks of a world + +/// A datapack of a world that Modrinth or CurseForge knows. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DatapackSourceDto { + pub file_name: String, + /// "modrinth" or "curseforge". + pub source: &'static str, + pub project_id: String, + pub title: String, +} + +/// The `.zip` datapacks of a world found on Modrinth (by SHA-1) or else on CurseForge (by fingerprint, with a key). +#[tauri::command] +pub async fn datapack_sources(app: AppHandle, core: State<'_, Core>, id: String, world: String) -> CmdResult> { + let inst = core.store.get(&id).msg()?; + let game = core.store.game_dir(&inst); + let files: Vec<(String, PathBuf)> = cubby_instance::list_datapacks(&game, &world) + .msg()? + .into_iter() + .filter(|d| !d.is_dir && d.file_name.to_lowercase().ends_with(".zip")) + .filter_map(|d| { + let on = cubby_instance::datapack_path(&game, &world, &d.file_name).ok()?; + let path = if d.enabled { on } else { on.parent()?.with_file_name("datapacks.disabled").join(&d.file_name) }; + Some((d.file_name, path)) }) .collect(); - let total = page.total.unwrap_or(hits.len() as u64); - Ok(SearchResultsDto { hits, total, offset: query.offset, limit: query.limit }) + if files.is_empty() { + return Ok(Vec::new()); + } + let paths: Vec = files.iter().map(|(_, p)| p.clone()).collect(); + let modrinth = core.modrinth.identify_paths(&paths).await.unwrap_or_else(|e| { + log::warn!("couldn't identify datapacks on Modrinth: {e}"); + vec![None; paths.len()] + }); + let mut out = Vec::new(); + let mut rest = Vec::new(); + for ((name, path), found) in files.into_iter().zip(modrinth) { + match found { + Some(p) => out.push(DatapackSourceDto { file_name: name, source: "modrinth", project_id: p.project_id, title: p.title }), + None => rest.push((name, path)), + } + } + if let (Some(cf), false) = (core.curseforge(), rest.is_empty()) { + let app2 = app.clone(); + let paths: Vec = rest.iter().map(|(_, p)| p.clone()).collect(); + let prints = crate::commands::blocking(move || { + let core = app2.state::(); + let files: Vec<(Folder, String, PathBuf)> = paths.into_iter().map(|p| (Folder::Mods, String::new(), p)).collect(); + Ok(fingerprints(&core, &files)) + }) + .await?; + let known: Vec = prints.iter().flatten().copied().collect(); + if !known.is_empty() { + let matches = cf.match_fingerprints(&known).await.unwrap_or_default(); + let ids: Vec = matches.values().map(|(project, _)| *project).collect(); + let names = cf.projects(&ids).await.unwrap_or_default(); + for ((name, _), print) in rest.into_iter().zip(prints) { + let Some((project, _)) = print.and_then(|p| matches.get(&p)) else { continue }; + let title = names.iter().find(|b| b.id == *project).map(|b| b.name.clone()).unwrap_or_else(|| name.clone()); + out.push(DatapackSourceDto { file_name: name, source: "curseforge", project_id: project.to_string(), title }); + } + } + } + Ok(out) +} + +// Install plans + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CfPlanItemDto { + pub project_id: String, + pub file_id: String, + pub title: String, + pub icon_url: Option, + pub page_url: String, + pub file_name: String, + pub size: u64, + /// "requested" or "dependency". + pub reason: &'static str, + /// This very file is already in the instance. + pub installed: bool, + /// The file another version of the project left, replaced by this one. + pub replaces: Option, + /// The author only lets it be downloaded on curseforge.com: the page to get it from. + pub manual_url: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CfMissingDto { + pub project_id: String, + pub title: String, + pub page_url: String, +} + +/// What installing a CurseForge project into an instance would do. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CfPlanDto { + pub instance_id: String, + /// The requested project first, then the projects it requires that the instance doesn't have. + pub items: Vec, + /// Required projects with no file for this instance. + pub missing: Vec, + /// Bytes downloaded by Cubby. + pub download_bytes: u64, +} + +struct Planned { + dto: CfPlanDto, + /// What Cubby downloads, as an install plan the Modrinth downloader runs. + downloads: InstallPlan, +} + +fn folder_for(kind: ResourceKind) -> CmdResult { + match kind { + ResourceKind::Mod => Ok(Folder::Mods), + ResourceKind::ResourcePack => Ok(Folder::ResourcePacks), + ResourceKind::Shader => Ok(Folder::ShaderPacks), + ResourceKind::Datapack => Err("Datapacks go into a world: use curseforge_install_datapack.".into()), + ResourceKind::Modpack => Err("CurseForge modpacks are installed as new instances.".into()), + } +} + +/// Folder of a required project, by its class (`None` for what doesn't go into the instance's folders). +fn folder_of_class(class_id: Option) -> Option { + match class_id { + None | Some(6) => Some(Folder::Mods), + Some(12) => Some(Folder::ResourcePacks), + Some(6552) => Some(Folder::ShaderPacks), + _ => None, + } +} + +async fn plan(app: &AppHandle, core: &Core, inst: &Instance, project_id: u64, file_id: Option, kind: ResourceKind) -> CmdResult { + let folder = folder_for(kind)?; + let cf = client(core)?; + let game_dir = core.store.game_dir(inst); + let loaders = if kind == ResourceKind::Mod { runs_with(&instance_loader(inst)) } else { Vec::new() }; + if kind == ResourceKind::Mod && loaders.is_empty() { + return Err(format!("{} is Vanilla: mods need a loader like Fabric, Quilt, Forge or NeoForge. Pick another instance, or create one with a loader.", inst.name)); + } + let target = FileTarget { game_version: Some(inst.minecraft.clone()), loaders }; + + let installed = installed_files(app, &cf, &game_dir).await?; + let installed_ids: HashSet = installed.iter().map(|f| f.project_id).collect(); + // Projects found on Modrinth (same slug on both sites): a required library installed from Modrinth stays. + let modrinth_slugs: HashSet = if kind == ResourceKind::Mod { + core.modrinth.content_sources(&game_dir).await.map(|s| s.into_iter().map(|c| c.slug).collect()).unwrap_or_default() + } else { + HashSet::new() + }; + let resolved = cf + .resolve(project_id, file_id, &target, |p| installed_ids.contains(&p.id) || (!p.slug.is_empty() && modrinth_slugs.contains(&p.slug))) + .await + .msg()?; + + let mut items = Vec::new(); + let mut missing = Vec::new(); + let mut downloads = Vec::new(); + for (i, r) in resolved.into_iter().enumerate() { + let requested = i == 0; + let Some(file) = r.file else { + if requested { + let what = if kind == ResourceKind::Mod { format!("Minecraft {} with {}", inst.minecraft, crate::dto::LoaderDto::from(&inst.loader).kind) } else { format!("Minecraft {}", inst.minecraft) }; + return Err(format!("No file of {} is made for {what}. Pick a file from the list, or another instance.", r.project.name)); + } + missing.push(CfMissingDto { project_id: r.project.id.to_string(), title: r.project.name.clone(), page_url: r.project.page_url.clone() }); + continue; + }; + let item_folder = if requested { folder } else { + match folder_of_class(r.project.class_id) { + Some(f) => f, + None => continue, + } + }; + let same = installed.iter().find(|f| f.project_id == r.project.id); + let already = same.is_some_and(|f| f.file_id == file.id); + let replaces = same.filter(|f| f.file_id != file.id).map(|f| (f.folder, f.file_name.clone())); + let manual_url = match (&file.download_url, &file.sha1) { + (Some(_), Some(_)) => None, + _ => Some(r.project.download_page(file.id)), + }; + if !already + && manual_url.is_none() + && let (Some(url), Some(sha1)) = (&file.download_url, &file.sha1) + { + downloads.push(PlanItem { + project_id: r.project.id.to_string(), + version_id: file.id.to_string(), + title: r.project.name.clone(), + version_number: file.name.clone(), + file_name: file.file_name.clone(), + size: file.size.unwrap_or(0), + url: url.clone(), + sha1: sha1.clone(), + reason: if requested { Reason::Requested } else { Reason::Dependency }, + installed: same.is_some(), + folder: item_folder, + download: true, + replaces: replaces.clone(), + }); + } + items.push(CfPlanItemDto { + project_id: r.project.id.to_string(), + file_id: file.id.to_string(), + title: r.project.name.clone(), + icon_url: r.project.icon_url.clone(), + page_url: r.project.page_url.clone(), + file_name: file.file_name.clone(), + size: file.size.unwrap_or(0), + reason: if requested { "requested" } else { "dependency" }, + installed: already, + replaces: replaces.map(|(_, name)| name), + manual_url, + }); + } + let download_bytes = downloads.iter().map(|d| d.size).sum(); + Ok(Planned { + dto: CfPlanDto { instance_id: inst.id.clone(), items, missing, download_bytes }, + downloads: InstallPlan { items: downloads, missing: Vec::new(), conflicts: Vec::new(), download_bytes }, + }) +} + +/// What installing a CurseForge project (`file_id`, else the best file for the instance) would do. +#[tauri::command] +pub async fn curseforge_plan(app: AppHandle, core: State<'_, Core>, instance_id: String, kind: String, project_id: String, file_id: Option) -> CmdResult { + let inst = core.store.get(&instance_id).msg()?; + let file = file_id.as_deref().map(|f| parse_id(f, "file")).transpose()?; + Ok(plan(&app, &core, &inst, parse_id(&project_id, "project")?, file, kind_of(&kind)?).await?.dto) +} + +/// Plans again, then downloads the project and the projects it requires into the instance (task +/// `install:`). Files only offered on curseforge.com are left out: the plan lists them. Returns when done. +#[tauri::command] +pub async fn curseforge_install(app: AppHandle, core: State<'_, Core>, instance_id: String, kind: String, project_id: String, file_id: Option) -> CmdResult { + let inst = core.store.get(&instance_id).msg()?; + ensure_stopped(&core, &inst.id)?; + let kind = kind_of(&kind)?; + let project = parse_id(&project_id, "project")?; + let file = file_id.as_deref().map(|f| parse_id(f, "file")).transpose()?; + run_task(&app, format!("install:{}", inst.id), move |app, task| async move { + let core = app.state::(); + core.sink.progress(&task, "Checking dependencies", 0, 1); + install_planned(&app, &core, &inst, project, file, kind, &task).await.map(|(dto, _)| dto) + }) + .await +} + +/// Plans a CurseForge project for the instance and downloads it with what it requires, inside a running task. +/// Returns the plan and the files downloaded as (folder, file name). +pub(crate) async fn install_planned(app: &AppHandle, core: &Core, inst: &Instance, project: u64, file: Option, kind: ResourceKind, task: &str) -> CmdResult<(CfPlanDto, Vec<(Folder, String)>)> { + let planned = plan(app, core, inst, project, file, kind).await?; + let game_dir = core.store.game_dir(inst); + let mut downloaded = Vec::new(); + if !planned.downloads.items.is_empty() { + let selection = PackSelection::capture(&game_dir); + let applied = core.modrinth.install(&planned.downloads, &game_dir, download_concurrency(core), core.sink.as_ref(), task).await.msg()?; + selection.follow(&game_dir, &applied.renamed); + let files: Vec<(&str, &str)> = planned.downloads.items.iter().map(|i| (i.folder.as_str(), i.file_name.as_str())).collect(); + crate::origins::record(&core.paths.instance(&inst.id), &files, "curseforge"); + downloaded = planned.downloads.items.iter().map(|i| (i.folder, i.file_name.clone())).collect(); + applied.into_result().msg()?; + } + Ok((planned.dto, downloaded)) +} + +/// The kind of project for a launcher key ("mod", "resourcepack", "shader", "datapack"). +pub(crate) fn resource_kind(kind: &str) -> CmdResult { + kind_of(kind) +} + +pub(crate) fn parse_project_id(id: &str) -> CmdResult { + parse_id(id, "project") +} + +/// Downloads a CurseForge datapack (`file_id`, else its newest `.zip` for the instance's Minecraft version) into +/// a world. Returns the file name. +#[tauri::command] +pub async fn curseforge_install_datapack(core: State<'_, Core>, id: String, world: String, project_id: String, file_id: Option) -> CmdResult { + let inst = core.store.get(&id).msg()?; + let project_id = parse_id(&project_id, "project")?; + let file_id = file_id.as_deref().map(|f| parse_id(f, "file")).transpose()?; + download_datapack(&core, &inst, &world, project_id, file_id).await +} + +/// Downloads a CurseForge datapack (`file_id`, else its newest `.zip` for the instance's Minecraft version) into a +/// world of the instance. Returns the file name. +pub(crate) async fn download_datapack(core: &Core, inst: &Instance, world: &str, project_id: u64, file_id: Option) -> CmdResult { + let cf = client(core)?; + let project = cf.projects(&[project_id]).await.msg()?.into_iter().next().ok_or_else(|| "CurseForge doesn't know this datapack.".to_string())?; + let is_zip = |f: &CfFile| f.file_name.to_lowercase().ends_with(".zip"); + let file = match file_id { + Some(fid) => cf.file(project_id, fid).await.msg()?, + None => { + let files: Vec = cf.files_for_version(project_id, Some(&inst.minecraft)).await.msg()?.into_iter().filter(is_zip).collect(); + let target = FileTarget { game_version: Some(inst.minecraft.clone()), loaders: Vec::new() }; + best_file(&files, &target).cloned().ok_or_else(|| format!("No datapack file of {} is made for Minecraft {}.", project.name, inst.minecraft))? + } + }; + if !is_zip(&file) { + return Err(format!("{} isn't a datapack .zip: it can't go into a world.", file.file_name)); + } + let Some(url) = file.download_url.clone() else { + return Err(format!("The author of {} only lets it be downloaded on CurseForge: {}", project.name, project.download_page(file.id))); + }; + let path = cubby_instance::datapack_path(&core.store.game_dir(inst), world, &file.file_name).msg()?; + let mut job = Download::new(url, &path); + if let Some(size) = file.size { + job = job.with_size(size); + } + if let Some(sha1) = file.sha1.clone() { + job = job.with_sha1(sha1); + } + cubby_common::net::ensure_file(&core.http, &job).await.msg()?; + Ok(file.file_name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quilt_runs_fabric_mods() { + assert_eq!(runs_with("quilt"), vec![PackLoaderKind::Quilt, PackLoaderKind::Fabric]); + assert_eq!(runs_with("neoforge"), vec![PackLoaderKind::NeoForge]); + assert!(runs_with("vanilla").is_empty()); + } + + #[test] + fn content_files_lists_what_curseforge_can_know() { + let dir = std::env::temp_dir().join(format!("cubby-cf-content-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for (folder, name) in [("mods", "a.jar"), ("mods", "b.jar.disabled"), ("mods", "notes.txt"), ("resourcepacks", "r.zip"), ("resourcepacks", "folder-pack"), ("shaderpacks", "s.zip"), ("shaderpacks", "s.zip.txt")] { + std::fs::create_dir_all(dir.join(folder)).unwrap(); + if name == "folder-pack" { + std::fs::create_dir_all(dir.join(folder).join(name)).unwrap(); + } else { + std::fs::write(dir.join(folder).join(name), b"x").unwrap(); + } + } + let mut names: Vec = content_files(&dir).into_iter().map(|(f, n, _)| format!("{}/{n}", f.as_str())).collect(); + names.sort(); + assert_eq!(names, vec!["mods/a.jar", "mods/b.jar.disabled", "resourcepacks/r.zip", "shaderpacks/s.zip"]); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src-tauri/src/commands/discover.rs b/src-tauri/src/commands/discover.rs index 51cd57b..e3e372b 100644 --- a/src-tauri/src/commands/discover.rs +++ b/src-tauri/src/commands/discover.rs @@ -5,7 +5,7 @@ use super::*; // Discover (Modrinth) /// Game version and loader of an instance, as Modrinth sees them. -pub(super) fn target_of(inst: &Instance) -> Target { +pub(crate) fn target_of(inst: &Instance) -> Target { Target::new( inst.minecraft.clone(), Some(dto::LoaderDto::from(&inst.loader).kind.as_str()), @@ -13,13 +13,13 @@ pub(super) fn target_of(inst: &Instance) -> Target { } /// Active resource packs and shader pack, carried over when an install or update renames their files. -pub(super) struct PackSelection { +pub(crate) struct PackSelection { resource: Vec, shader: Option, } impl PackSelection { - fn capture(game_dir: &Path) -> Self { + pub(crate) fn capture(game_dir: &Path) -> Self { Self { resource: cubby_instance::list_packs(game_dir, PackKind::Resource) .into_iter() @@ -33,7 +33,7 @@ impl PackSelection { } } - fn follow(&self, game_dir: &Path, renamed: &[Renamed]) { + pub(crate) fn follow(&self, game_dir: &Path, renamed: &[Renamed]) { let new_name = |folder: Folder, old: &str| { renamed .iter() @@ -80,11 +80,17 @@ impl PackSelection { } #[tauri::command] +/// `filters`: several Minecraft versions and loaders, used instead of the query's own version and loader. pub async fn search_projects( core: State<'_, Core>, query: ProjectQueryDto, + filters: Option, ) -> CmdResult { - let query = SearchQuery::try_from(query)?; + let mut query = SearchQuery::try_from(query)?; + if let Some(f) = filters { + query.game_versions = f.game_versions; + query.loaders = f.loaders; + } Ok(core.modrinth.search(&query).await.msg()?.into()) } @@ -167,6 +173,8 @@ pub async fn install_version( .await .msg()?; selection.follow(&game_dir, &applied.renamed); + let files: Vec<(&str, &str)> = plan.items.iter().filter(|i| i.download).map(|i| (i.folder.as_str(), i.file_name.as_str())).collect(); + crate::origins::record(&core.paths.instance(&inst.id), &files, "modrinth"); applied.into_result().msg().map(|_| ()) }, ) @@ -237,6 +245,8 @@ pub async fn install_versions( .await .msg()?; selection.follow(&game_dir, &applied.renamed); + let files: Vec<(&str, &str)> = plan.items.iter().filter(|i| i.download).map(|i| (i.folder.as_str(), i.file_name.as_str())).collect(); + crate::origins::record(&core.paths.instance(&inst.id), &files, "modrinth"); applied.into_result().msg().map(|_| ()) }, ) diff --git a/src-tauri/src/commands/instances.rs b/src-tauri/src/commands/instances.rs index b9b4875..9f78337 100644 --- a/src-tauri/src/commands/instances.rs +++ b/src-tauri/src/commands/instances.rs @@ -200,6 +200,14 @@ pub async fn list_loader_versions( .msg() } +/// The Minecraft versions a loader runs on, newest first (snapshots included where the loader has them). +#[tauri::command] +pub async fn loader_game_versions(core: State<'_, Core>, kind: String) -> CmdResult> { + cubby_meta::game_versions_supported(&core.http, loader_kind(&kind)?) + .await + .msg() +} + /// Cubby's own icon, for a desktop shortcut: the app executable on Windows (it holds the icon), the bundle's /// `.icns` on macOS, an installed PNG on Linux. `None` in development builds without a bundle. fn app_icon() -> Option { diff --git a/src-tauri/src/commands/launch.rs b/src-tauri/src/commands/launch.rs index 7dfb1ed..20c192f 100644 --- a/src-tauri/src/commands/launch.rs +++ b/src-tauri/src/commands/launch.rs @@ -215,6 +215,11 @@ pub async fn launch_instance( { log::warn!("could not record the play session of {id}: {e}"); } + // Datapacks picked for new worlds go into the worlds this session created. + let added = crate::extras::apply_world_datapacks(&core, &id).await; + if added > 0 { + log::info!("added {added} datapack(s) to the new worlds of {id}"); + } // Makes the UI reload the instances with the new play time. core.sink.finished(&format!("session:{id}"), None); match settings.on_launch { diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index e216234..153423d 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -110,7 +110,7 @@ where })) } -async fn run_task( +pub(crate) async fn run_task( app: &AppHandle, task: String, work: impl FnOnce(AppHandle, String) -> Fut, @@ -131,7 +131,7 @@ where } } -fn ensure_stopped(core: &Core, id: &str) -> CmdResult<()> { +pub(crate) fn ensure_stopped(core: &Core, id: &str) -> CmdResult<()> { if core.games.is_running(id) { return Err("Close the game before changing this instance.".into()); } diff --git a/src-tauri/src/dto.rs b/src-tauri/src/dto.rs index a6393ff..135d2da 100644 --- a/src-tauri/src/dto.rs +++ b/src-tauri/src/dto.rs @@ -569,6 +569,8 @@ impl TryFrom for modrinth::SearchQuery { kind: project_kind(&q.kind)?, game_version: q.game_version.filter(|v| !v.trim().is_empty()), loader: q.loader.filter(|l| !l.trim().is_empty()), + game_versions: Vec::new(), + loaders: Vec::new(), categories: q.categories, environment, sort: modrinth::Sort::parse(&q.sort), @@ -650,7 +652,10 @@ impl From for SearchResultsDto { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct GalleryImageDto { + /// Full size. pub url: String, + /// A small copy for thumbnails. + pub thumb_url: Option, pub title: Option, pub description: Option, pub featured: bool, @@ -695,6 +700,7 @@ impl From for ProjectDto { .into_iter() .map(|g| GalleryImageDto { url: g.url, + thumb_url: g.thumb_url, title: g.title, description: g.description, featured: g.featured, @@ -891,6 +897,7 @@ pub struct ContentSourceDto { pub title: String, pub icon_url: Option, pub version_number: String, + pub categories: Vec, } impl From for ContentSourceDto { @@ -903,6 +910,7 @@ impl From for ContentSourceDto { title: s.title, icon_url: s.icon_url, version_number: s.version_number, + categories: s.categories, } } } diff --git a/src-tauri/src/extras.rs b/src-tauri/src/extras.rs new file mode 100644 index 0000000..477d829 --- /dev/null +++ b/src-tauri/src/extras.rs @@ -0,0 +1,364 @@ +//! What the New instance wizard adds to a new instance: mods, resource packs, shader packs and datapacks from +//! Modrinth or CurseForge, installed once the instance (and its modpack, if any) is ready. +//! +//! Datapacks belong to worlds, and a new instance has none. On a modded instance, a Modrinth datapack that also +//! ships as a mod for the instance's loader is installed as that mod, so it shapes every world from its creation. +//! The others wait in `/world-datapacks.json` and go into each new world when the game closes +//! ([`apply_world_datapacks`]); each world remembers what it got in `/cubby-datapacks.json`. + +use std::collections::BTreeSet; +use std::path::Path; +use std::time::Duration; + +use cubby_common::net::Download; +use cubby_instance::Instance; +use cubby_modrinth::{Folder, ProjectVersion}; +use serde::{Deserialize, Serialize}; +use tauri::{AppHandle, Manager, State}; + +use crate::commands::{download_concurrency, run_task, target_of, CmdResult, OrMessage, PackSelection}; +use crate::state::Core; + +const PENDING_FILE: &str = "world-datapacks.json"; +const WORLD_MARKER: &str = "cubby-datapacks.json"; +/// How long to wait for the modpack install the extras follow. +const PACK_WAIT: Duration = Duration::from_secs(4 * 60 * 60); + +/// One project picked in the wizard. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExtraDto { + /// "modrinth" or "curseforge". + pub source: String, + pub project_id: String, + /// "mod", "resourcepack", "shader" or "datapack". + pub kind: String, + pub title: String, +} + +/// What `install_extras` did. +#[derive(Debug, Clone, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ExtrasReportDto { + /// Files downloaded, the required mods included. + pub installed: usize, + /// Projects with nothing for the instance's Minecraft version and loader. + pub missing: Vec, + /// Datapacks waiting for the instance's new worlds. + pub pending_datapacks: usize, +} + +/// A datapack waiting for new worlds. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PendingDatapack { + pub source: String, + pub project_id: String, + pub title: String, +} + +impl PendingDatapack { + fn key(&self) -> String { + format!("{}:{}", self.source, self.project_id) + } +} + +// Bookkeeping + +pub(crate) fn load_pending(instance_dir: &Path) -> Vec { + std::fs::read(instance_dir.join(PENDING_FILE)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() +} + +/// Adds datapacks to the pending list (each project once). +fn add_pending(instance_dir: &Path, add: &[PendingDatapack]) -> std::io::Result<()> { + let mut list = load_pending(instance_dir); + for p in add { + if !list.iter().any(|x| x.key() == p.key()) { + list.push(p.clone()); + } + } + std::fs::write(instance_dir.join(PENDING_FILE), serde_json::to_vec_pretty(&list).map_err(std::io::Error::other)?) +} + +/// The pending datapacks a world hasn't got yet. +fn missing_in_world(world_dir: &Path, pending: &[PendingDatapack]) -> Vec { + let done = applied_keys(world_dir); + pending.iter().filter(|p| !done.contains(&p.key())).cloned().collect() +} + +fn applied_keys(world_dir: &Path) -> BTreeSet { + std::fs::read(world_dir.join(WORLD_MARKER)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() +} + +fn mark_applied(world_dir: &Path, keys: &[String]) -> std::io::Result<()> { + let mut done = applied_keys(world_dir); + done.extend(keys.iter().cloned()); + std::fs::write(world_dir.join(WORLD_MARKER), serde_json::to_vec_pretty(&done).map_err(std::io::Error::other)?) +} + +// Installing + +/// The newest release among the versions (else the newest version), newest first as given. +fn best_version(versions: &[ProjectVersion]) -> Option<&ProjectVersion> { + versions.iter().find(|v| v.channel == "release").or_else(|| versions.first()) +} + +fn loader_key(inst: &Instance) -> String { + crate::dto::LoaderDto::from(&inst.loader).kind +} + +/// Waits while the instance's modpack installs; `Err` when the instance went away meanwhile (a failed install). +async fn wait_for_pack(core: &Core, id: &str) -> CmdResult { + let task = format!("modpack:{id}"); + let started = std::time::Instant::now(); + while core.tasks.lock().expect("tasks lock").contains(&task) { + if started.elapsed() > PACK_WAIT { + return Err("The modpack is still installing. Add the rest from the instance once it's done.".into()); + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + core.store.get(id).map_err(|_| "The instance is gone: its modpack couldn't be installed.".to_string()) +} + +/// Installs the projects picked in the wizard into a new instance (task `install:`), after its modpack when +/// it has one (with no project, it only waits for the modpack). `turn_on` turns the new resource packs and shader +/// pack on. Returns when done. +#[tauri::command] +pub async fn install_extras(app: AppHandle, core: State<'_, Core>, instance_id: String, items: Vec, turn_on: bool) -> CmdResult { + // First the modpack, if one is installing: "Create and play" waits on this even with nothing to add. + let inst = wait_for_pack(&core, &instance_id).await?; + if items.is_empty() { + return Ok(ExtrasReportDto::default()); + } + crate::commands::ensure_stopped(&core, &inst.id)?; + run_task(&app, format!("install:{}", inst.id), move |app, task| async move { + let core = app.state::(); + install_items(&app, &core, &inst, &items, turn_on, &task).await + }) + .await +} + +async fn install_items(app: &AppHandle, core: &Core, inst: &Instance, items: &[ExtraDto], turn_on: bool, task: &str) -> CmdResult { + let game_dir = core.store.game_dir(inst); + let loader = loader_key(inst); + let modded = loader != "vanilla"; + let mut report = ExtrasReportDto::default(); + let mut version_ids: Vec = Vec::new(); + let mut pending: Vec = Vec::new(); + let mut cf_items: Vec<&ExtraDto> = Vec::new(); + core.sink.progress(task, "Finding versions", 0, items.len() as u64); + + for (i, item) in items.iter().enumerate() { + core.sink.progress(task, "Finding versions", i as u64, items.len() as u64); + let wait = || PendingDatapack { source: item.source.clone(), project_id: item.project_id.clone(), title: item.title.clone() }; + match (item.source.as_str(), item.kind.as_str()) { + ("modrinth", "datapack") => { + // A datapack that also ships as a mod for this loader shapes worlds from their creation. + let as_mod = if modded { + core.modrinth + .versions(&item.project_id, Some(&inst.minecraft), Some(&loader)) + .await + .ok() + .and_then(|vs| best_version(&vs.into_iter().filter(|v| v.loaders.iter().any(|l| l == &loader)).collect::>()).map(|v| v.id.clone())) + } else { + None + }; + match as_mod { + Some(id) => version_ids.push(id), + None => pending.push(wait()), + } + } + ("curseforge", "datapack") => pending.push(wait()), + ("modrinth", kind) => { + let mod_loader = (kind == "mod").then_some(loader.as_str()); + match core.modrinth.versions(&item.project_id, Some(&inst.minecraft), mod_loader).await { + Ok(vs) => match best_version(&vs) { + Some(v) => version_ids.push(v.id.clone()), + None => report.missing.push(item.title.clone()), + }, + Err(e) => { + log::warn!("no version of {} for {}: {e}", item.title, inst.id); + report.missing.push(item.title.clone()); + } + } + } + ("curseforge", _) => cf_items.push(item), + (other, _) => return Err(format!("Unknown source: {other}.")), + } + } + + let mut new_files: Vec<(Folder, String)> = Vec::new(); + if !version_ids.is_empty() { + let plan = core.modrinth.plan_install_many(&version_ids, &target_of(inst), &game_dir).await.msg()?; + let selection = PackSelection::capture(&game_dir); + let applied = core.modrinth.install(&plan, &game_dir, download_concurrency(core), core.sink.as_ref(), task).await.msg()?; + selection.follow(&game_dir, &applied.renamed); + let files: Vec<(&str, &str)> = plan.items.iter().filter(|i| i.download).map(|i| (i.folder.as_str(), i.file_name.as_str())).collect(); + crate::origins::record(&core.paths.instance(&inst.id), &files, "modrinth"); + new_files.extend(plan.items.iter().filter(|i| i.download).map(|i| (i.folder, i.file_name.clone()))); + report.missing.extend(plan.missing.iter().filter_map(|m| m.title.clone())); + applied.into_result().msg()?; + } + for item in cf_items { + let (Ok(kind), Ok(project)) = (crate::cf_resources::resource_kind(&item.kind), crate::cf_resources::parse_project_id(&item.project_id)) else { + report.missing.push(item.title.clone()); + continue; + }; + match crate::cf_resources::install_planned(app, core, inst, project, None, kind, task).await { + Ok((_, files)) => new_files.extend(files), + Err(e) => { + log::warn!("couldn't install {} from CurseForge: {e}", item.title); + report.missing.push(item.title.clone()); + } + } + } + report.installed = new_files.len(); + + if turn_on { + let packs: Vec = new_files.iter().filter(|(f, _)| *f == Folder::ResourcePacks).map(|(_, n)| n.clone()).collect(); + if !packs.is_empty() { + let mut on = packs; + on.extend(cubby_instance::list_packs(&game_dir, cubby_instance::PackKind::Resource).into_iter().filter(|p| p.enabled).map(|p| p.file_name)); + on.dedup(); + if let Err(e) = cubby_instance::set_resource_packs(&game_dir, &on) { + log::warn!("couldn't turn the new resource packs on: {e}"); + } + } + if let Some((_, shader)) = new_files.iter().find(|(f, _)| *f == Folder::ShaderPacks) + && let Err(e) = cubby_instance::set_shader_pack(&game_dir, Some(shader)) + { + log::warn!("couldn't turn the shader pack on: {e}"); + } + } + + if !pending.is_empty() { + add_pending(&core.paths.instance(&inst.id), &pending).map_err(|e| format!("Couldn't save the datapacks for new worlds: {e}"))?; + report.pending_datapacks = load_pending(&core.paths.instance(&inst.id)).len(); + } + core.sink.progress(task, "Done", 1, 1); + Ok(report) +} + +// Datapacks for new worlds + +/// Puts the instance's pending datapacks into each world that hasn't got them. Failures are logged: a world gets +/// what downloaded, and the rest is tried again next time. Returns how many datapacks went into worlds. +pub(crate) async fn apply_world_datapacks(core: &Core, id: &str) -> usize { + let instance_dir = core.paths.instance(id); + let pending = load_pending(&instance_dir); + if pending.is_empty() { + return 0; + } + let Ok(inst) = core.store.get(id) else { return 0 }; + let game_dir = core.store.game_dir(&inst); + let mut added = 0; + for world in cubby_instance::list_worlds(&game_dir) { + let world_dir = game_dir.join("saves").join(&world.folder_name); + let todo = missing_in_world(&world_dir, &pending); + let mut done = Vec::new(); + for p in todo { + match download_into_world(core, &inst, &world.folder_name, &p).await { + Ok(()) => { + added += 1; + done.push(p.key()); + } + Err(e) => log::warn!("couldn't add the datapack {} to {}: {e}", p.title, world.folder_name), + } + } + if !done.is_empty() + && let Err(e) = mark_applied(&world_dir, &done) + { + log::warn!("couldn't remember the datapacks of {}: {e}", world.folder_name); + } + } + added +} + +async fn download_into_world(core: &Core, inst: &Instance, world: &str, p: &PendingDatapack) -> CmdResult<()> { + match p.source.as_str() { + "modrinth" => { + let file = core.modrinth.datapack_file(&p.project_id, None, &inst.minecraft).await.msg()?; + let path = cubby_instance::datapack_path(&core.store.game_dir(inst), world, &file.file_name).msg()?; + let mut job = Download::new(file.url, &path).with_size(file.size); + if file.sha1.len() == 40 { + job = job.with_sha1(file.sha1); + } + cubby_common::net::ensure_file(&core.http, &job).await.msg() + } + "curseforge" => crate::cf_resources::download_datapack(core, inst, world, crate::cf_resources::parse_project_id(&p.project_id)?, None).await.map(|_| ()), + other => Err(format!("Unknown source: {other}.")), + } +} + +/// Puts the instance's datapacks for new worlds into the worlds that haven't got them yet. Returns how many. +#[tauri::command] +pub async fn apply_world_datapacks_now(core: State<'_, Core>, instance_id: String) -> CmdResult { + core.store.get(&instance_id).msg()?; + Ok(apply_world_datapacks(&core, &instance_id).await) +} + +/// The datapacks waiting for the instance's new worlds. +#[tauri::command] +pub fn world_datapacks(core: State<'_, Core>, instance_id: String) -> Vec { + load_pending(&core.paths.instance(&instance_id)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("cubby-extras-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn dp(source: &str, id: &str) -> PendingDatapack { + PendingDatapack { source: source.into(), project_id: id.into(), title: id.into() } + } + + #[test] + fn pending_list_keeps_each_project_once() { + let dir = temp("pending"); + assert!(load_pending(&dir).is_empty()); + add_pending(&dir, &[dp("modrinth", "terralith"), dp("curseforge", "123")]).unwrap(); + add_pending(&dir, &[dp("modrinth", "terralith"), dp("modrinth", "incendium")]).unwrap(); + let keys: Vec = load_pending(&dir).iter().map(PendingDatapack::key).collect(); + assert_eq!(keys, vec!["modrinth:terralith", "curseforge:123", "modrinth:incendium"]); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_world_gets_each_datapack_once() { + let world = temp("world"); + let pending = vec![dp("modrinth", "terralith"), dp("curseforge", "123")]; + assert_eq!(missing_in_world(&world, &pending).len(), 2); + mark_applied(&world, &["modrinth:terralith".to_string()]).unwrap(); + assert_eq!(missing_in_world(&world, &pending), vec![dp("curseforge", "123")]); + mark_applied(&world, &["curseforge:123".to_string()]).unwrap(); + assert!(missing_in_world(&world, &pending).is_empty()); + let _ = std::fs::remove_dir_all(&world); + } + + #[test] + fn releases_come_first() { + let v = |id: &str, channel: &str| ProjectVersion { + id: id.into(), + project_id: "p".into(), + name: id.into(), + version_number: id.into(), + channel: channel.into(), + game_versions: vec![], + loaders: vec![], + published: String::new(), + downloads: 0, + changelog: String::new(), + files: vec![], + dependencies: vec![], + }; + assert_eq!(best_version(&[v("b2", "beta"), v("r1", "release")]).map(|x| x.id.as_str()), Some("r1")); + assert_eq!(best_version(&[v("b2", "beta"), v("a1", "alpha")]).map(|x| x.id.as_str()), Some("b2")); + assert!(best_version(&[]).is_none()); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index e235a6a..19a5a7d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -4,6 +4,8 @@ mod cf_resources; mod commands; mod dto; mod events; +mod extras; +mod origins; mod packs; mod state; mod update; @@ -60,6 +62,7 @@ pub fn run() { commands::instances::create_desktop_shortcut, commands::instances::list_versions, commands::instances::list_loader_versions, + commands::instances::loader_game_versions, commands::content::list_mods, commands::content::set_mod_enabled, commands::content::remove_mod, @@ -113,6 +116,16 @@ pub fn run() { commands::discover::apply_updates, cf_resources::curseforge_search, cf_resources::curseforge_categories, + cf_resources::curseforge_installed, + cf_resources::curseforge_files, + cf_resources::curseforge_project, + cf_resources::datapack_sources, + cf_resources::curseforge_plan, + cf_resources::curseforge_install, + cf_resources::curseforge_install_datapack, + extras::install_extras, + extras::apply_world_datapacks_now, + extras::world_datapacks, update::check_update, update::download_update, update::install_update, @@ -122,9 +135,11 @@ pub fn run() { commands::content::delete_world, packs::pack_providers, packs::pack_search, + packs::change_pack_version, packs::pack_details, packs::pack_versions, packs::pack_optional_mods, + packs::pack_contents, packs::install_pack, packs::pick_pack_file, packs::inspect_pack_file, diff --git a/src-tauri/src/origins.rs b/src-tauri/src/origins.rs new file mode 100644 index 0000000..35092a6 --- /dev/null +++ b/src-tauri/src/origins.rs @@ -0,0 +1,54 @@ +//! Where Cubby downloaded each content file of an instance from, in `/content-origins.json` +//! (`{"mods/x.jar": "curseforge"}`). The same file is often on Modrinth and CurseForge: identifying it by hash +//! finds both, and this says which one the player picked. + +use std::collections::BTreeMap; +use std::path::Path; + +const FILE: &str = "content-origins.json"; + +/// `folder/file name` → "modrinth" or "curseforge". +pub type Origins = BTreeMap; + +pub fn load(instance_dir: &Path) -> Origins { + std::fs::read(instance_dir.join(FILE)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() +} + +/// Records that these files (`(folder, file name)`) came from `source`. A file name with ".disabled" counts +/// as the file itself. Failures are only logged: the origin is a hint. +pub fn record(instance_dir: &Path, files: &[(&str, &str)], source: &str) { + if files.is_empty() { + return; + } + let mut origins = load(instance_dir); + for (folder, name) in files { + origins.insert(key(folder, name), source.to_string()); + } + let written = serde_json::to_vec_pretty(&origins).map_err(std::io::Error::other).and_then(|b| std::fs::write(instance_dir.join(FILE), b)); + if let Err(e) = written { + log::warn!("could not record where content came from: {e}"); + } +} + +pub fn key(folder: &str, name: &str) -> String { + format!("{folder}/{}", name.strip_suffix(".disabled").unwrap_or(name)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_and_reads_back() { + let dir = std::env::temp_dir().join(format!("cubby-origins-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + assert!(load(&dir).is_empty()); + record(&dir, &[("mods", "a.jar"), ("mods", "b.jar.disabled")], "curseforge"); + record(&dir, &[("mods", "a.jar")], "modrinth"); + let o = load(&dir); + assert_eq!(o.get("mods/a.jar").map(String::as_str), Some("modrinth")); + assert_eq!(o.get(&key("mods", "b.jar")).map(String::as_str), Some("curseforge")); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src-tauri/src/packs.rs b/src-tauri/src/packs.rs index d955227..a41de2c 100644 --- a/src-tauri/src/packs.rs +++ b/src-tauri/src/packs.rs @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf}; use futures::StreamExt; use serde::{Deserialize, Serialize}; -use cubby_common::packs::{PackChannel, PackLoaderKind, PackPage, PackPlan, PackSort, PackSummary, PackVersion}; +use cubby_common::packs::{ContentSite, PackChannel, PackContentItem, PackLoaderKind, PackPage, PackPlan, PackSort, PackSummary, PackVersion}; use cubby_curseforge::CurseForgeClient; use cubby_instance::{Instance, Loader, ModpackInfo, NewInstance}; use cubby_modrinth::{ProjectKind, SearchQuery, Sort}; @@ -31,7 +31,7 @@ const LEGACY_TECHNIC_MESSAGE: &str = "This Technic pack uses Minecraft 1.5.2 or // Types shared with the UI -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ProviderId { Modrinth, @@ -205,7 +205,9 @@ fn technic_summary(pack: &cubby_technic::TechnicPack) -> PackSummary { } #[tauri::command] -pub async fn pack_search(core: State<'_, Core>, provider: ProviderId, query: String, sort: PackSort, offset: u32) -> CmdResult { +/// `filters` (Minecraft versions, loaders, categories) apply to CurseForge, which filters itself; the UI +/// filters the other sources' results. +pub async fn pack_search(core: State<'_, Core>, provider: ProviderId, query: String, sort: PackSort, offset: u32, filters: Option) -> CmdResult { let query = query.trim(); match provider { ProviderId::Modrinth => { @@ -220,6 +222,8 @@ pub async fn pack_search(core: State<'_, Core>, provider: ProviderId, query: Str kind: ProjectKind::Modpack, game_version: None, loader: None, + game_versions: Vec::new(), + loaders: Vec::new(), categories: Vec::new(), environment: None, sort, @@ -229,7 +233,10 @@ pub async fn pack_search(core: State<'_, Core>, provider: ProviderId, query: Str let results = core.modrinth.search(&q).await.msg()?; Ok(PackPage { total: Some(results.total), hits: results.hits.into_iter().map(modrinth_summary).collect() }) } - ProviderId::Curseforge => require_curseforge(&core)?.search(query, sort, offset, PAGE_SIZE).await.msg(), + ProviderId::Curseforge => match filters { + Some(filters) => crate::cf_resources::search_modpacks(&core, query, sort, offset, PAGE_SIZE, &filters).await, + None => require_curseforge(&core)?.search(query, sort, offset, PAGE_SIZE).await.msg(), + }, ProviderId::Ftb => core.ftb.search(query, sort, offset, PAGE_SIZE).await.msg(), ProviderId::Atlauncher => { let page = core.atlauncher.search(query, sort).await.msg()?; @@ -390,6 +397,98 @@ pub async fn pack_optional_mods(core: State<'_, Core>, provider: ProviderId, id: .collect()) } +// What a pack version contains + +/// Pack versions whose contents are remembered (they don't change once published). +const CONTENTS_CACHE_SIZE: usize = 40; +const SINGLE_ZIP_MESSAGE: &str = "This pack is a single download that doesn't list its mods. You'll see them in the instance once it's installed."; + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PackContentsDto { + items: Vec, + /// Why there is no list, for a pack whose source doesn't give one. + unavailable: Option, +} + +type ContentsKey = (ProviderId, String, String); + +fn contents_cache() -> &'static std::sync::Mutex> { + static CACHE: std::sync::OnceLock>> = std::sync::OnceLock::new(); + CACHE.get_or_init(Default::default) +} + +fn cached_contents(key: &ContentsKey) -> Option { + let cache = contents_cache().lock().unwrap_or_else(|e| e.into_inner()); + cache.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) +} + +fn remember_contents(key: ContentsKey, value: PackContentsDto) { + let mut cache = contents_cache().lock().unwrap_or_else(|e| e.into_inner()); + cache.retain(|(k, _)| *k != key); + if cache.len() >= CONTENTS_CACHE_SIZE { + cache.remove(0); + } + cache.push((key, value)); +} + +/// Describes the CurseForge projects in `items` (FTB and ATLauncher packs name them by id): name (when `rename`, +/// the items being named after their files), icon, page, summary, authors. Without a CurseForge key, or when the +/// call fails, the items stay as they are. +async fn describe_curseforge_items(core: &Core, items: &mut [PackContentItem], rename: bool) { + if !items.iter().any(|i| i.site == Some(ContentSite::Curseforge)) { + return; + } + let Some(client) = core.curseforge() else { return }; + if let Err(e) = client.describe_contents(items, rename).await { + log::warn!("couldn't describe the CurseForge projects of a pack: {e}"); + } +} + +async fn contents_inner(core: &Core, provider: ProviderId, pack_id: &str, version_id: &str) -> CmdResult { + let listed = |items| PackContentsDto { items, unavailable: None }; + match provider { + ProviderId::Modrinth => Ok(listed(core.modrinth.pack_contents(version_id, &cache_dir(core, "contents")?).await.msg()?)), + ProviderId::Curseforge => { + let client = require_curseforge(core)?; + let items = client.pack_contents(parse_id(pack_id, "CurseForge pack")?, parse_id(version_id, "CurseForge file")?, &cache_dir(core, "contents")?).await.msg()?; + Ok(listed(items)) + } + ProviderId::Ftb => { + let mut items = core.ftb.contents(pack_id, version_id).await.msg()?; + describe_curseforge_items(core, &mut items, true).await; + Ok(listed(items)) + } + ProviderId::Atlauncher => { + let manifest = core.atlauncher.manifest(pack_id, version_id).await.msg()?; + let mut items = cubby_atlauncher::manifest_contents(&manifest); + describe_curseforge_items(core, &mut items, false).await; + Ok(listed(items)) + } + ProviderId::Technic => Ok(match core.technic.contents(pack_id, version_id).await.msg()? { + Some(items) => listed(items), + None => PackContentsDto { items: Vec::new(), unavailable: Some(SINGLE_ZIP_MESSAGE.to_string()) }, + }), + } +} + +/// The mods, resource packs and shader packs one version of a pack installs, from the cheapest data its source +/// has: a Modrinth `.mrpack` index or a CurseForge `manifest.json` (the pack file is downloaded, read and +/// deleted), an FTB version, an ATLauncher manifest, a Technic Solder build. Remembered per version. +#[tauri::command] +pub async fn pack_contents(core: State<'_, Core>, provider: ProviderId, pack_id: String, version_id: String) -> CmdResult { + let key = (provider, pack_id.trim().to_string(), version_id.trim().to_string()); + if key.2.is_empty() { + return Err("Choose a version of the pack.".into()); + } + if let Some(hit) = cached_contents(&key) { + return Ok(hit); + } + let contents = contents_inner(&core, provider, &key.1, &key.2).await?; + remember_contents(key, contents.clone()); + Ok(contents) +} + // Installing /// Where the plan of an install comes from. @@ -581,6 +680,138 @@ async fn install_source(core: &Core, task: &str, id: &str, source: Source, name_ Ok(()) } +// Switching the pack version of an instance + +fn provider_of(name: &str) -> CmdResult { + match name { + "modrinth" | "" => Ok(ProviderId::Modrinth), + "curseforge" => Ok(ProviderId::Curseforge), + "ftb" => Ok(ProviderId::Ftb), + "atlauncher" => Ok(ProviderId::Atlauncher), + "technic" => Ok(ProviderId::Technic), + other => Err(format!("Unknown modpack source: {other}.")), + } +} + +/// A version of a pack as an install plan, whatever the provider (a Modrinth `.mrpack` is downloaded, then +/// planned like a file). The plan owns its archives: remove them with `remove_plan_archives` when not installed. +async fn plan_version(core: &Core, provider: ProviderId, pack_id: &str, version_id: &str) -> CmdResult { + if provider != ProviderId::Modrinth { + return plan_provider(core, provider, pack_id, version_id, None).await; + } + let pack = core.modrinth.fetch_modpack(version_id, &cache_dir(core, "modrinth")?).await.msg()?; + let archive = pack.archive.clone(); + let mut plan = match blocking(move || pack_install::plan_from_mrpack(&archive).msg()).await { + Ok(plan) => plan, + Err(e) => { + let _ = std::fs::remove_file(&pack.archive); + return Err(e); + } + }; + plan.provider = "modrinth".into(); + plan.pack_id = pack.project_id; + plan.version_id = pack.version_id; + plan.title = pack.title; + plan.version_name = pack.version_number; + plan.icon_url = pack.icon_url; + Ok(plan) +} + +/// Moves a file of the game directory to `/.trash//`. +fn trash_into(game_dir: &Path, into: &str, rel: &Path) -> std::io::Result<()> { + let src = game_dir.join(rel); + if !src.is_file() { + return Ok(()); + } + let dest = game_dir.join(".trash").join(into).join(rel); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::rename(&src, &dest) +} + +/// Switches an instance installed from a modpack to another version of that pack, older or newer (task +/// `modpack:`). The old version's mods, resource packs and shader packs that the new one doesn't have go to +/// `/.trash/modpack-/`, then the new version installs over the instance: its files, its +/// Minecraft version and loader, and its overrides (pack configs are replaced). Worlds, screenshots and the files +/// the player added stay. Returns when done. +#[tauri::command] +pub async fn change_pack_version(app: AppHandle, core: State<'_, Core>, instance_id: String, version_id: String) -> CmdResult<()> { + let inst = core.store.get(&instance_id).msg()?; + let info = inst.modpack.clone().ok_or_else(|| "This instance wasn't installed from a modpack.".to_string())?; + let provider = provider_of(info.provider.as_deref().unwrap_or("modrinth"))?; + let version_id = version_id.trim().to_string(); + if version_id.is_empty() || version_id == info.version_id { + return Err("This version of the pack is the one installed.".into()); + } + if provider == ProviderId::Curseforge { + require_curseforge(&core)?; + } + commands::ensure_stopped(&core, &inst.id)?; + commands::run_task(&app, format!("modpack:{}", inst.id), move |app, task| async move { + let core = app.state::(); + core.sink.progress(&task, "Preparing the modpack", 0, 3); + let new = plan_version(&core, provider, &info.project_id, &version_id).await?; + core.sink.progress(&task, "Comparing with the installed version", 1, 3); + // The installed version's files: a version gone from the provider leaves them where they are. + let old_paths = match plan_version(&core, provider, &info.project_id, &info.version_id).await { + Ok(old) => { + let paths = pack_install::plan_paths(&old); + pack_install::remove_plan_archives(&old); + paths.unwrap_or_else(|e| { + log::warn!("couldn't list the files of the installed pack version: {e}"); + Vec::new() + }) + } + Err(e) => { + log::warn!("couldn't read the installed version {} of the pack: {e}", info.version_id); + Vec::new() + } + }; + let new_paths = match pack_install::plan_paths(&new) { + Ok(p) => p, + Err(e) => { + pack_install::remove_plan_archives(&new); + return Err(dto_message(e)); + } + }; + let mut inst = core.store.get(&inst.id).msg()?; + let game_dir = core.store.game_dir(&inst); + let stamp = cubby_instance::backup_stamp(); + let into = format!("modpack-{stamp}"); + for rel in pack_install::switch_removals(&old_paths, &new_paths) { + for path in [rel.clone(), PathBuf::from(format!("{}.disabled", rel.to_string_lossy()))] { + if let Err(e) = trash_into(&game_dir, &into, &path) { + log::warn!("couldn't move {} to the trash: {e}", path.display()); + } + } + } + core.sink.progress(&task, "Installing the new version", 2, 3); + inst.minecraft = new.minecraft.clone(); + inst.loader = loader_of(&new.loader); + inst.modpack = Some(ModpackInfo { + provider: Some(new.provider.clone()), + project_id: if new.pack_id.is_empty() { info.project_id.clone() } else { new.pack_id.clone() }, + version_id: new.version_id.clone(), + title: if new.title.trim().is_empty() { info.title.clone() } else { new.title.clone() }, + version_number: new.version_name.clone(), + }); + core.store.save(&inst).msg()?; + let installed = pack_install::install_pack_plan(&core.http, &new, &game_dir, download_concurrency(&core), true, core.sink.as_ref(), &task).await.msg()?; + let missing = installed.blocked.iter().filter(|b| !b.found(&game_dir)).count(); + pack_install::save_blocked(&core.paths.instance(&inst.id), &installed.blocked).map_err(|e| format!("Couldn't save the list of files to download by hand: {e}"))?; + if missing > 0 { + core.sink.progress(&task, &format!("{missing} file(s) must be downloaded by hand"), 1, 1); + } + Ok(()) + }) + .await +} + +fn dto_message(e: cubby_common::Error) -> String { + crate::dto::message(e) +} + async fn plan_provider(core: &Core, provider: ProviderId, pack_id: &str, version_id: &str, optional: Option>) -> CmdResult { let cache = cache_dir(core, provider.as_str())?; match provider { diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 1f21e97..c723591 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -43,6 +43,8 @@ pub struct Core { pub discord: Option, /// Games running, oldest first, with what Discord shows for each: the newest one is shown. pub playing: Mutex>, + /// CurseForge fingerprints of content files, kept while a file's size and modification time stay the same. + pub cf_prints: Mutex>, } impl Core { @@ -78,6 +80,7 @@ impl Core { total_memory_mb: crate::commands::total_memory_mb(), discord: cubby_discord::client_id().map(cubby_discord::Presence::new), playing: Mutex::new(Vec::new()), + cf_prints: Mutex::new(std::collections::HashMap::new()), paths, }) } diff --git a/ui/src/App.svelte b/ui/src/App.svelte index 6d18087..da851b3 100644 --- a/ui/src/App.svelte +++ b/ui/src/App.svelte @@ -3,7 +3,8 @@ import { app, sectionOf } from './lib/state.svelte' import { windowAction } from './lib/api' import { setLanguage, t } from './lib/i18n.svelte' - import { Button, Hotbar, TitleBar, Tooltips, type HotbarItem } from './lib/cubby' + import { Button, Hotbar, Icon, TitleBar, Tooltips, type HotbarItem } from './lib/cubby' + import PackRoute from './lib/views/create/PackRoute.svelte' import Toasts from './lib/views/shell/Toasts.svelte' import Palette from './lib/views/shell/Palette.svelte' import UpdateBanner from './lib/views/shell/UpdateBanner.svelte' @@ -11,7 +12,7 @@ import Library from './lib/views/library/Library.svelte' import DeleteInstanceDialog from './lib/views/library/DeleteInstanceDialog.svelte' import ImportDialog from './lib/views/library/ImportDialog.svelte' - import NewInstance from './lib/views/create/NewInstance.svelte' + import Wizard from './lib/views/create/wizard/Wizard.svelte' import InstancePage from './lib/views/instance-page/InstancePage.svelte' import Running from './lib/views/play/Running.svelte' import Crash from './lib/views/play/Crash.svelte' @@ -120,14 +121,30 @@ e.preventDefault() app.paletteOpen = false go(SLOTS[Number(e.key) - 1]) - } else if (e.altKey && !ctrl && e.key === 'ArrowLeft') { + } else if ((e.altKey && !ctrl && e.key === 'ArrowLeft') || (e.metaKey && !e.shiftKey && e.key === '[')) { e.preventDefault() app.back() + } else if ((e.altKey && !ctrl && e.key === 'ArrowRight') || (e.metaKey && !e.shiftKey && e.key === ']')) { + e.preventDefault() + app.forward() } } + + /** The mouse's side buttons: Back and Forward, as in a browser. */ + function onmouseup(e: MouseEvent) { + if (onboarding || (e.button !== 3 && e.button !== 4)) return + e.preventDefault() + if (e.button === 3) app.back() + else app.forward() + } - + + +{#snippet navButtons()} + + +{/snippet} {#snippet accountHead()} @@ -139,6 +156,7 @@ app.navigate({ name: 'accounts' })} onSearch={() => (app.paletteOpen = true)} onMinimize={() => windowAction('minimize')} @@ -163,12 +181,16 @@ {:else if app.route.name === 'crash'} {#key app.route.id}{/key} {:else if app.route.name === 'create'} - + {:else if app.route.name === 'discover'} {:else if app.route.name === 'project'} {#key app.route.idOrSlug} - + + {/key} + {:else if app.route.name === 'pack'} + {#key `${app.route.provider}:${app.route.id}`} + {/key} {:else if app.route.name === 'downloads'} diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 8be5dc0..eca83c1 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -6,6 +6,13 @@ import type { AppUpdate, ContentSource, BlockedFile, + CfFile, + SearchFilters, + CfInstalled, + CfPlan, + DatapackSource, + ExtrasReport, + WizardExtra, ContentUpdate, DataFolder, WorldMapImage, @@ -21,6 +28,7 @@ import type { DefaultSkin, VersionBrief, Project, + ProjectKind, ProjectQuery, ProjectVersion, SearchResults, @@ -38,6 +46,7 @@ import type { LoaderVersion, LogLine, OptionalMod, + PackContents, PackDetails, PackFileInfo, PackPage, @@ -93,6 +102,8 @@ export const api = { listVersions: () => call('list_versions'), listLoaderVersions: (kind: LoaderKind, game: string) => call('list_loader_versions', { kind, game }), + /** The Minecraft versions a loader runs on, newest first. */ + loaderGameVersions: (kind: LoaderKind) => call('loader_game_versions', { kind }), listMods: (id: string) => call('list_mods', { id }), setModEnabled: (id: string, fileName: string, enabled: boolean) => call('set_mod_enabled', { id, fileName, enabled }), @@ -144,11 +155,33 @@ export const api = { listJava: () => call('list_java'), // Discover (Modrinth) - /** Mods, shader packs and resource packs from CurseForge, in the shape of searchProjects. */ - curseforgeSearch: (query: ProjectQuery) => call('curseforge_search', { query }), - /** The categories CurseForge sorts mods, shader packs or resource packs into (ids are strings). */ + /** CurseForge projects in the shape of searchProjects. `query.categories` are CurseForge ids; `filters` override the query's version and loader. */ + curseforgeSearch: (query: ProjectQuery, filters: SearchFilters | null = null) => call('curseforge_search', { query, filters }), + /** The categories CurseForge sorts a kind of project into (ids are strings). */ curseforgeCategories: (kind: string) => call<{ id: string; name: string }[]>('curseforge_categories', { kind }), - searchProjects: (query: ProjectQuery) => call('search_projects', { query }), + /** The instance's mods, resource packs and shader packs that come from CurseForge (by fingerprint). */ + curseforgeInstalled: (instanceId: string) => call('curseforge_installed', { instanceId }), + /** A CurseForge project page, shaped like a Modrinth one (`source: 'curseforge'`, description in HTML). */ + curseforgeProject: (projectId: string, kind: ProjectKind) => call('curseforge_project', { projectId, kind }), + /** The newest files of a CurseForge project for a Minecraft version (null = every version), newest first. */ + curseforgeFiles: (projectId: string, gameVersion: string | null) => call('curseforge_files', { projectId, gameVersion }), + /** What installing a CurseForge project (`fileId`, else the best file) into the instance would do, with the projects it requires. */ + curseforgePlan: (instanceId: string, kind: ProjectKind, projectId: string, fileId: string | null) => + call('curseforge_plan', { instanceId, kind, projectId, fileId }), + /** Installs a CurseForge project and what it requires (task `install:`). Returns the plan that ran: its `manualUrl` items still need a download by hand. */ + curseforgeInstall: (instanceId: string, kind: ProjectKind, projectId: string, fileId: string | null) => + call('curseforge_install', { instanceId, kind, projectId, fileId }), + /** Installs what the New instance wizard picked (task `install:`), after the instance's modpack if one is installing. Returns when done. */ + installExtras: (instanceId: string, items: WizardExtra[], turnOn: boolean) => call('install_extras', { instanceId, items, turnOn }), + /** The datapacks waiting for the instance's new worlds. */ + worldDatapacks: (instanceId: string) => call[]>('world_datapacks', { instanceId }), + /** The datapacks of a world that Modrinth (by SHA-1) or CurseForge (by fingerprint) knows. */ + datapackSources: (id: string, world: string) => call('datapack_sources', { id, world }), + /** Downloads a CurseForge datapack into a world; returns the file name. */ + curseforgeInstallDatapack: (id: string, world: string, projectId: string, fileId: string | null) => + call('curseforge_install_datapack', { id, world, projectId, fileId }), + /** `filters`: several Minecraft versions and loaders, instead of the query's own (categories stay in the query). */ + searchProjects: (query: ProjectQuery, filters: SearchFilters | null = null) => call('search_projects', { query, filters }), getProject: (idOrSlug: string) => call('get_project', { idOrSlug }), /** Newest first. `gameVersion` / `loader` null = every version. */ listProjectVersions: (idOrSlug: string, gameVersion: string | null, loader: LoaderKind | null) => @@ -193,11 +226,16 @@ export const api = { /** ATLauncher, CurseForge, FTB, Modrinth, Technic (in that order). */ packProviders: () => call('pack_providers'), /** 20 per page; an empty query lists the featured packs. */ - packSearch: (provider: ProviderId, query: string, sort: PackSort, offset: number) => call('pack_search', { provider, query, sort, offset }), + packSearch: (provider: ProviderId, query: string, sort: PackSort, offset: number, filters: SearchFilters | null = null) => + call('pack_search', { provider, query, sort, offset, filters }), packDetails: (provider: ProviderId, id: string) => call('pack_details', { provider, id }), packVersions: (provider: ProviderId, id: string) => call('pack_versions', { provider, id }), /** Empty for every provider but ATLauncher. */ + /** Switches an instance installed from a modpack to another version of the pack (task `modpack:`); returns when done. */ + changePackVersion: (instanceId: string, versionId: string) => call('change_pack_version', { instanceId, versionId }), packOptionalMods: (provider: ProviderId, id: string, versionId: string) => call('pack_optional_mods', { provider, id, versionId }), + /** The mods, resource packs and shader packs one version of a pack installs (remembered per version). */ + packContents: (provider: ProviderId, packId: string, versionId: string) => call('pack_contents', { provider, packId, versionId }), /** Creates the instance and returns it right away; the install runs as task `modpack:`. `optionalMods`: names of the ticked optional mods (installed exactly); null = the pack's default selection. */ installPack: (provider: ProviderId, packId: string, versionId: string, name: string, group: string | null, icon: string | null, optionalMods: string[] | null) => call('install_pack', { provider, packId, versionId, name, group, icon, optionalMods }), diff --git a/ui/src/lib/cubby/Dialog.svelte b/ui/src/lib/cubby/Dialog.svelte index 8e481be..a8f44a1 100644 --- a/ui/src/lib/cubby/Dialog.svelte +++ b/ui/src/lib/cubby/Dialog.svelte @@ -23,6 +23,18 @@ const tid = $props.id(); let dialog: HTMLDivElement | undefined = $state(); + // Modal with onClose: a click on the dim layer around it closes it, like Esc. Only when the press started there + // too, so a text selection dragged out of the dialog doesn't close it. + let downOutside = false; + function layerDown(e: PointerEvent) { + downOutside = !inline && !!onClose && e.button === 0 && e.target === e.currentTarget; + } + function layerClick(e: MouseEvent) { + const close = downOutside && e.target === e.currentTarget; + downOutside = false; + if (close) onClose?.(); + } + // Modal (not inline): focus goes to the first field, else the least destructive action (actions list Cancel first), // else the first control; Tab and Shift Tab stay inside; Esc calls onClose; focus returns where it was on close. $effect(() => { @@ -74,7 +86,8 @@ }); -
+ +
- + {#if danger.hint}

{danger.hint}

{/if}
{/if} diff --git a/ui/src/lib/cubby/ModRow.svelte b/ui/src/lib/cubby/ModRow.svelte index 4de7368..e3e1ca3 100644 --- a/ui/src/lib/cubby/ModRow.svelte +++ b/ui/src/lib/cubby/ModRow.svelte @@ -4,6 +4,7 @@ import Icon from './Icon.svelte'; import IconButton from './IconButton.svelte'; import StatusTag from './StatusTag.svelte'; + import SourceMark from './SourceMark.svelte'; import Switch from './Switch.svelte'; import type { ModRowProps } from './types'; @@ -18,6 +19,8 @@ toggleLabel, update, warning, + source, + kind, actions, moreLabel, onMore, @@ -40,6 +43,12 @@ {name} {#if version}{version}{/if} {#if authors}{authors}{/if} + {#if kind || source} + + {#if kind}{kind.label}{/if} + {#if source}{/if} + + {/if}
{#if description}

{description}

{/if} {#if update || warning} diff --git a/ui/src/lib/cubby/SourceMark.svelte b/ui/src/lib/cubby/SourceMark.svelte new file mode 100644 index 0000000..824999d --- /dev/null +++ b/ui/src/lib/cubby/SourceMark.svelte @@ -0,0 +1,30 @@ + + + + + {#if tone === 'local'} + + {:else} + + {/if} + {label} + + + diff --git a/ui/src/lib/cubby/TitleBar.svelte b/ui/src/lib/cubby/TitleBar.svelte index 3bcec0b..e0051e5 100644 --- a/ui/src/lib/cubby/TitleBar.svelte +++ b/ui/src/lib/cubby/TitleBar.svelte @@ -19,13 +19,17 @@ onMaximize, onClose, children, + nav, class: className, }: TitleBarProps = $props();
-
+
+ + {#if nav}
{@render nav()}
{/if} +
- {/each} -
- {/if} -

{CHANNEL_HINT[channel]}

- - - -
-
-

{t('Mod loader')}

- {t('A loader lets the game run mods. You can change it later.')} - - {#if loader !== 'vanilla'} - {t('Loader version')} - ({ id: lv.version, lv })) ?? []} - value={loaderVersion} - onSelect={(v) => (loaderVersion = v)} - label={t('{name} version', { name: loaderInfo.name })} - buttonLabel={t('Loader version')} - variant="block" - disabled={!loaderVersions?.length} - listWidth={240} - option={loaderOption} - > - {#snippet trigger()} - {#if loaderVersions === null} - {t('Loading…')} - {:else if loaderVersion} - {loaderVersion}{loaderVersion === recommended ? t(' (recommended)') : ''} - {:else} - {t('None available')} - {/if} - {/snippet} - - {/if} -
- -
- {#each LOADERS as l (l.kind)} - {@const on = l.kind === loader} - - {/each} -
- {#if loaderMissing} -

- - {#if loaderError} - {t('Couldn\'t load {name} versions: {loaderError}', { name: loaderInfo.name, loaderError })} - - {:else} - {t('{name} has no version for Minecraft', { name: loaderInfo.name })} {minecraft}{t('. Pick another version or loader.')} - {/if} -

- {/if} -
- - - - - - -{#snippet retryVersions()} - -{/snippet} - - diff --git a/ui/src/lib/views/create/Identity.svelte b/ui/src/lib/views/create/Identity.svelte index c9023be..b801c4e 100644 --- a/ui/src/lib/views/create/Identity.svelte +++ b/ui/src/lib/views/create/Identity.svelte @@ -1,18 +1,30 @@ diff --git a/ui/src/lib/views/create/LinkSource.svelte b/ui/src/lib/views/create/LinkSource.svelte index e4039bf..656bda6 100644 --- a/ui/src/lib/views/create/LinkSource.svelte +++ b/ui/src/lib/views/create/LinkSource.svelte @@ -100,6 +100,7 @@ + + diff --git a/ui/src/lib/views/create/PackPage.svelte b/ui/src/lib/views/create/PackPage.svelte index f1b850f..6e029b6 100644 --- a/ui/src/lib/views/create/PackPage.svelte +++ b/ui/src/lib/views/create/PackPage.svelte @@ -4,14 +4,17 @@ import { untrack } from 'svelte' import { api } from '../../api' import { Banner, Button, Dialog, Icon, InstanceIcon, MetaChip, Switch, type Ground, type Motif } from '../../cubby' - import { compactNum, date, loaderName, plural, relativeTime } from '../../format' + import { compactNum, date, loaderName, num, plural, relativeTime } from '../../format' import { projectArt } from '../../icon' import { app } from '../../state.svelte' import type { OptionalMod, PackDetails, PackProvider, PackSummary, PackVersion } from '../../types' import Markdown from '../discover/Markdown.svelte' + import PackContentsList from '../discover/PackContentsList.svelte' + import { loadPackContents } from '../discover/packContents' import Picker from '../discover/Picker.svelte' import Identity, { iconValue } from './Identity.svelte' import { CHANNEL_WORD, mcSpan, paragraphs } from './packs' + import { wizard } from './wizard/state.svelte' interface Props { provider: PackProvider @@ -63,7 +66,18 @@ // version - let versionId = $state(null) + // Back to this page shows the version picked when it was left + let versionId = $state(untrack(() => app.recall('versionId') ?? null)) + $effect(() => app.keep('versionId', versionId)) + /** Where Back goes when it isn't Discover (an instance, another page): the crumbs lead there. */ + const from = $derived(app.previous && app.previous.name !== 'discover' ? app.previous : null) + /** Opened from the New instance wizard: Pick sets its modpack and goes back to it, instead of installing here. */ + const forWizard = $derived(app.previous?.name === 'create') + function pickForWizard() { + if (!chosen) return + wizard.choosePack(provider.id, summary, versions, chosen.id) + app.back() + } const chosen = $derived(versions?.find((v) => v.id === versionId) ?? versions?.find((v) => v.channel === 'release') ?? versions?.[0]) const newest = $derived(versions?.find((v) => v.channel === 'release') ?? versions?.[0]) const versionItems = $derived((versions ?? []).map((v) => ({ id: v.id, v }))) @@ -177,6 +191,26 @@ } } + // content: the count next to the heading + + let contentCount = $state(null) + $effect(() => { + const v = chosen?.id + const p = provider.id + const id = summary.id + contentCount = null + if (!v) return + let stale = false + loadPackContents(p, id, v) + .then((c) => { + if (!stale && !c.unavailable) contentCount = c.items.length + }) + .catch(() => {}) + return () => { + stale = true + } + }) + // links and gallery function open(e: MouseEvent, url: string) { @@ -199,10 +233,16 @@
-
+
{#if viewing !== null && gallery[viewing]} {#snippet viewerActions()} {#if gallery.length > 1} - + {/if} {/snippet} @@ -512,6 +571,11 @@ align-items: center; gap: 6px; } + .heading-count { + display: flex; + align-items: center; + gap: var(--space-2); + } section { display: flex; flex-direction: column; @@ -671,4 +735,15 @@ .aside :global(.wide) { width: 100%; } + /* every crumb on the same line: the Back one is a button with an icon, the others plain text */ + .crumbs > li { + display: flex; + align-items: center; + } + .back { + display: inline-flex; + align-items: center; + gap: 2px; + line-height: 22px; + } diff --git a/ui/src/lib/views/create/PackRoute.svelte b/ui/src/lib/views/create/PackRoute.svelte new file mode 100644 index 0000000..c08d623 --- /dev/null +++ b/ui/src/lib/views/create/PackRoute.svelte @@ -0,0 +1,66 @@ + + + +{#if provider && summary} + app.back()} /> +{:else if error || app.providersError} +
+ {#snippet actions()} + + + {/snippet} + {error ?? app.providersError} +
+{:else} +

{t('Loading the modpack…')}

+{/if} + + diff --git a/ui/src/lib/views/create/PresetCards.svelte b/ui/src/lib/views/create/PresetCards.svelte index ed2c5ed..2163006 100644 --- a/ui/src/lib/views/create/PresetCards.svelte +++ b/ui/src/lib/views/create/PresetCards.svelte @@ -11,7 +11,8 @@ import { t } from '../../i18n.svelte' import { addressProblem, discoverPerformanceMods, findNewest, hostOf, presetSpec, type Newest, type Preset } from './presets' - let { align = 'center' }: { align?: 'center' | 'start' } = $props() + /** `grid`: equal columns that line up with a grid of the same width (the wizard's Start step). */ + let { align = 'center' }: { align?: 'center' | 'start' | 'grid' } = $props() let newest = $state(null) let busy = $state(null) @@ -60,7 +61,7 @@ } -
+
@@ -146,6 +147,14 @@ .presets.is-start { justify-content: flex-start; } + .presets.is-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + } + .presets.is-grid .preset { + width: auto; + min-width: 0; + } .preset { width: 320px; display: flex; diff --git a/ui/src/lib/views/create/ProviderBrowser.svelte b/ui/src/lib/views/create/ProviderBrowser.svelte deleted file mode 100644 index 44bb412..0000000 --- a/ui/src/lib/views/create/ProviderBrowser.svelte +++ /dev/null @@ -1,392 +0,0 @@ - - - -{#if selected} - (selected = null)} /> -{:else} -
-
-

{provider.name}

- {#if provider.available} - - - {#if sorts.length > 1} - (picked = id as PackSort)} label={t('Sort by')} buttonLabel={t('Sort by {sort}. Change', { sort: sortLabel })} variant="ghost" listWidth={200}> - {#snippet trigger()}{t('Sort:')} {sortLabel}{/snippet} - {#snippet option(item, on)}{item.label}{/snippet} - - {/if} - {/if} -
- - {#if !provider.available} -
- -

{t('{name} needs setup', { name: provider.name })}

-

{provider.reason ?? t('{name} isn\'t available right now.', { name: provider.name })}

- {#if provider.id === 'curseforge'} - - {/if} -
- {:else} -

- {#if loading} - {t('Searching {name}…', { name: provider.name })} - {:else if error} -   - {:else if query.trim()} - {t('{n} for “{query}”.', { n: total != null ? plural(total, 'pack', 'packs') : plural(hits.length, 'pack', 'packs'), query: query.trim() })} - {:else} - {total != null ? t('{n} on {name}.', { n: plural(total, 'pack', 'packs'), name: provider.name }) : t('Packs on {name}.', { name: provider.name })} - {t('Each one installs as a new instance.')} - {/if} -

- -
- {#if error} - {#snippet retry()}{/snippet} - - {offline ? t('Check your internet connection, then try again.') : error} - - {:else if loading} - - {t('Loading packs')} - {:else if !hits.length} -
- -

{t('No packs found')}

-

- {query.trim() ? t('Nothing on {name} matches “{query}”. Check the spelling or try fewer words.', { name: provider.name, query: query.trim() }) : t('{name} has no packs to show right now.', { name: provider.name })} -

- {#if query.trim()}{/if} -
- {:else} -
    - {#each hits as h (h.id)} -
  • - -
  • - {/each} -
- {#if moreError} -

{t('Couldn\'t load more. {moreError}', { moreError })}

- {/if} - {#if hasMore || moreError} -
- {:else if provider.paged && hits.length > PAGE} -

{t('That\'s everything.')}

- {/if} - {/if} -
- {/if} -
-{/if} - - diff --git a/ui/src/lib/views/create/QuickStart.svelte b/ui/src/lib/views/create/QuickStart.svelte deleted file mode 100644 index 50b4f60..0000000 --- a/ui/src/lib/views/create/QuickStart.svelte +++ /dev/null @@ -1,34 +0,0 @@ - - - -
-

{t('Quick start')}

-

{t('Pick one and Cubby sets it up and starts the game. You can change the version, mods and everything else later.')}

- -
- - diff --git a/ui/src/lib/views/create/wizard/ContentStep.svelte b/ui/src/lib/views/create/wizard/ContentStep.svelte new file mode 100644 index 0000000..7a7acf8 --- /dev/null +++ b/ui/src/lib/views/create/wizard/ContentStep.svelte @@ -0,0 +1,468 @@ + + + +
+ {#if tabs[0] === 'mod'} +

{w.path === 'modpack' ? t('Add mods on top of the pack') : t('Add mods')}

+

{t('Only what’s made for {game} is shown. The mods they need are added for you.', { game: gameLine || '—' })}

+ {:else if tabs[0] === 'datapack'} +

{t('Datapacks for new worlds')}

+

{t('Datapacks add biomes, structures or rules to a world, without mods. Cubby adds these to each new world of this instance when you close the game, so biome and structure datapacks shape the parts you explore after that.')}

+ {#if w.gameLoader && w.gameLoader !== 'vanilla'} +

{t('Datapacks that also come as a mod for {loader} are installed as that mod: they shape every world from the start.', { loader: loaderName(w.gameLoader) })}

+ {/if} + {:else} +

{t('Make it look your way')}

+

{t('Resource packs change textures and sounds. A shader pack changes light, shadows and water. Neither changes the gameplay.')}

+ {/if} +
+ +{#if tabs.length > 1} + (tab = id as PickKind)} /> +{/if} + +{#if blocked} + {#snippet toGame()}{/snippet} + + {tab === 'mod' ? t('Pick Fabric, Quilt or NeoForge in Game to add mods, or skip this step.') : t('Shader packs run through Iris, a mod: pick Fabric or NeoForge in Game.')} + +{:else} + {#if tab === 'shader' && w.shaderNeedsIris} + {#snippet addIris()}{/snippet} + {t('Iris is the mod that loads shader packs, and Sodium makes it fast. Add both with the shader pack.')} + {/if} + + {#if tab === 'mod' && types.length > 1} +
+ {t('Type')} + {#each types as [id, label, icon] (id)} + {@const on = modType === id} + + {/each} +
+ {/if} + +
+ + {#if sources.length > 1} +
+ {#each sources as o (o.value)} + + {/each} +
+ {/if} +
+ +
+ {#if error} + {#snippet retry()}{/snippet} + {error} + {:else if hits === null} +

{t('Searching…')}

+ {:else if !hits.length} +

{query ? t('Nothing matches “{query}”. Check the spelling or try fewer words.', { query }) : t('Nothing here works with {game} yet.', { game: gameLine })}

+ {:else} +
    + {#each hits as h (h.id)} + {@const p = toPick(h)} + {@const on = w.has(p)} +
  • + +
    + + + {#if h.author}{t('by {author}', { author: h.author })}{/if} + + {h.summary} +
    + + {#if h.downloads}{compactNum(h.downloads)}{/if} + {#if typeOf(h.categories, h.kind)} + {@const ty = typeOf(h.categories, h.kind)!} + {ty.label} + {/if} + + +
  • + {/each} +
+ {#if read < total} + + {/if} + {/if} +
+{/if} + + diff --git a/ui/src/lib/views/create/wizard/GameStep.svelte b/ui/src/lib/views/create/wizard/GameStep.svelte new file mode 100644 index 0000000..7ffd460 --- /dev/null +++ b/ui/src/lib/views/create/wizard/GameStep.svelte @@ -0,0 +1,498 @@ + + + + + +{#snippet loaderOption(item: { id: string; lv: LoaderVersion })} + {item.lv.version} + {#if item.lv.version === recommended}{t('Recommended')}{:else if !item.lv.stable}{t('Beta')}{/if} +{/snippet} + +{#snippet retryVersions()} + +{/snippet} + +
+
+

{t('Loader')}

+

{t('What runs your mods. Each mod is made for one loader. Pick it first: the versions below are the ones it runs on.')}

+
+ +
+ {#each LOADERS as l (l.kind)} + {@const on = l.kind === w.loader} + + {/each} +
+
+ +
+
+

{t('Minecraft version')}

+ {#if channels.length > 1} + (channel = v as Channel)} /> + {/if} +
+ {#if supportedError} +

+ + {t('Couldn’t check which versions {name} runs on: every version is shown. {error}', { name: loaderInfo.name, error: supportedError })} + +

+ {/if} + {#if versionsError} + {versionsError} + {:else if pool === null} +

{checking ? t('Finding the versions {name} runs on…', { name: loaderInfo.name }) : t('Loading versions…')}

+ {:else} + {#if featured && latest} + {@const on = latest.id === w.minecraft} + + {/if} +
+

{featured ? t('Other versions') : t('Versions')}

+
+
+ {#if !shown.length && !featured} +

{query.trim() ? t('No version matches “{versionQuery}”.', { versionQuery: query.trim() }) : t('{name} runs on no version of this kind.', { name: loaderInfo.name })}

+ {:else if shown.length} + +
rovingKeys(e, shown.length, shownIndex, (to) => (w.minecraft = shown[to].id))}> + {#each shown as v, i (v.id)} + {@const on = v.id === w.minecraft} + + {/each} +
+ {/if} + {#if !query.trim() && (hidden > 0 || everything)} +
+ {/if} +

{CHANNEL_HINT[channel]}

+ {/if} + + {#if w.loader !== 'vanilla' && pool} +
+ {t('{name} version', { name: loaderInfo.name })} + ({ id: lv.version, lv })) ?? []} + value={w.loaderVersion} + onSelect={(v) => (w.loaderVersion = v)} + label={t('{name} version', { name: loaderInfo.name })} + buttonLabel={t('Loader version')} + variant="block" + disabled={!loaderVersions?.length} + listWidth={240} + option={loaderOption} + > + {#snippet trigger()} + {#if loaderVersions === null} + {t('Loading…')} + {:else if w.loaderVersion} + {w.loaderVersion}{w.loaderVersion === recommended ? t(' (recommended)') : ''} + {:else} + {t('None available')} + {/if} + {/snippet} + + {t('The recommended one is right for almost everyone.')} +
+ {/if} + {#if loaderMissing} +

+ + {#if loaderError} + {t('Couldn\'t load {name} versions: {loaderError}', { name: loaderInfo.name, loaderError })} + + {:else} + {t('{name} has no version for Minecraft', { name: loaderInfo.name })} {w.minecraft}{t('. Pick another version or loader.')} + {/if} +

+ {/if} +
+ + diff --git a/ui/src/lib/views/create/wizard/PackStep.svelte b/ui/src/lib/views/create/wizard/PackStep.svelte new file mode 100644 index 0000000..309f490 --- /dev/null +++ b/ui/src/lib/views/create/wizard/PackStep.svelte @@ -0,0 +1,301 @@ + + + +
+

{t('Pick a modpack')}

+

{t('It sets the Minecraft version, the loader and the mods. You can add more mods after.')}

+
+ +
+ {#each providers as p (p.id)} + + {/each} +
+ + + +{#if w.pack} +
+ +
+ {w.pack.name} + {t('by {author}', { author: w.pack.authors.join(', ') || '—' })} +
+
+ {t('Version')} + {#if w.packVersionsError} + {w.packVersionsError} + {:else if !w.packVersions} + {t('Loading versions…')} + {:else if !w.packVersions.length} + {t('This pack has no version to install.')} + {:else} + (w.packVersionId = id)} label={t('Version')} listWidth={320}> + {#snippet trigger()} + {@const v = w.packVersion} + + {v?.name ?? '—'} + {#if v}{meta(v)}{/if} + + {/snippet} + {#snippet option(item)} + + {item.v.name} + {meta(item.v)}{#if item.v.released} · {relativeTime(item.v.released, '')}{/if} + + {/snippet} + + {/if} +
+
+{/if} + +{#if error} + {#snippet retry()}{/snippet} + {error} +{:else if hits === null} +

{t('Searching {name}…', { name: provider?.name ?? '' })}

+{:else if !hits.length} +

{t('No modpack matches “{query}”.', { query })}

+{:else} +
    + {#each hits as p (p.id)} + {@const on = w.pack?.id === p.id} +
  • + + +

    {p.summary}

    +
    + {#if p.minecraft[0]}{p.minecraft[0]}{/if} + {#if p.loaders[0]}{loaderName(p.loaders[0])}{/if} + {#if p.downloads}{t('{n} downloads', { n: compactNum(p.downloads) })}{/if} + + +
    +
  • + {/each} +
+{/if} + + diff --git a/ui/src/lib/views/create/wizard/ReviewStep.svelte b/ui/src/lib/views/create/wizard/ReviewStep.svelte new file mode 100644 index 0000000..2afbf6f --- /dev/null +++ b/ui/src/lib/views/create/wizard/ReviewStep.svelte @@ -0,0 +1,235 @@ + + + +
+

{t('Name it and create it')}

+

{t('Everything downloads when you create the instance. You can keep using Cubby meanwhile.')}

+
+ +
+
+

{t('Name, group and icon')}

+
+
+ +
+ { + w.nameTouched = true + onName?.() + }} + /> + + + {#each app.groups as g (g.name)}{/each} + +
+
+ +
+ (w.iconTouched = true)} + onImport={() => fileInput?.click()} + /> +
+
+
+ +
+

{t('What Cubby installs')}

+
    + {#each rows as r (r.step)} +
  • + + {r.title}{r.detail} + +
  • + {/each} +
+ {#if w.shaderNeedsIris} +

{t('The shader pack needs Iris.')}

+ {/if} + {#if hasLooks} + (w.turnOn = v)} label={t('Turn the packs on')} hint={t('The resource packs go on top, and the shader pack is used, the first time you play.')} /> + {/if} +
+
+ + + + diff --git a/ui/src/lib/views/create/wizard/StartStep.svelte b/ui/src/lib/views/create/wizard/StartStep.svelte new file mode 100644 index 0000000..bf5229c --- /dev/null +++ b/ui/src/lib/views/create/wizard/StartStep.svelte @@ -0,0 +1,130 @@ + + + +
+

{t('How do you want to start?')}

+

{t('You can add or remove anything later, from the instance.')}

+
+ +
+ {#each CHOICES as c (c.id)} + {@const on = w.path === c.id} + + {/each} +
+ +{#if w.path === 'import'} +
+ (w.importFrom = v as 'file' | 'link')} /> +
+ {#if w.importFrom === 'file'}{:else}{/if} +
+
+{:else} +
+

{t('Or start in one click')}

+

{t('Cubby sets it up and starts the game right away.')}

+ +
+{/if} + + diff --git a/ui/src/lib/views/create/wizard/Summary.svelte b/ui/src/lib/views/create/wizard/Summary.svelte new file mode 100644 index 0000000..9b097b0 --- /dev/null +++ b/ui/src/lib/views/create/wizard/Summary.svelte @@ -0,0 +1,202 @@ + + + + + + diff --git a/ui/src/lib/views/create/wizard/Wizard.svelte b/ui/src/lib/views/create/wizard/Wizard.svelte new file mode 100644 index 0000000..9e794d6 --- /dev/null +++ b/ui/src/lib/views/create/wizard/Wizard.svelte @@ -0,0 +1,347 @@ + + + + + +
+
+
+
+

+ + {t('New instance')} +

+

{t('New instance')}

+
+ +
+ + {#if steps.length > 1} +
    + {#each steps as s, i (s.id)} +
  1. + +
  2. + {/each} +
+ {/if} + +
+ {#if w.step === 'start'} + + {:else if w.step === 'game'} + {#if w.path === 'modpack'}{:else}{/if} + {:else if w.step === 'mods'} + + {:else if w.step === 'looks'} + + {:else if w.step === 'datapacks'} + + {:else} + (nameError = undefined)} onChange={go} /> + {/if} +
+ + {#if steps.length > 1} +
+ + + {#if blocker}{blocker}{:else}{t('Step {n} of {total}', { n: index + 1, total: steps.length })}{/if} + {#if current?.optional}{/if} + {#if last} + + + {:else} + + {/if} +
+ {/if} +
+ + {#if steps.length > 1}{/if} +
+ + diff --git a/ui/src/lib/views/create/wizard/WizardAside.svelte b/ui/src/lib/views/create/wizard/WizardAside.svelte new file mode 100644 index 0000000..f23a81e --- /dev/null +++ b/ui/src/lib/views/create/wizard/WizardAside.svelte @@ -0,0 +1,71 @@ + + + +
+

{t('Your new instance')}

+ {#if target}

{t('For {target}.', { target })}

{/if} + {#if !fits} +

{t('Nothing says it runs on {version}.', { version: w.gameVersion ?? '' })}

+ {/if} + {#if on} + + + {:else} + + {#if replaces}

{t('It takes the place of {title}: one shader pack at a time.', { title: replaces })}

{/if} +

{t('Back to the new instance. It installs when you create it.')}

+ {/if} +
+ + diff --git a/ui/src/lib/views/create/wizard/kinds.ts b/ui/src/lib/views/create/wizard/kinds.ts new file mode 100644 index 0000000..53e8151 --- /dev/null +++ b/ui/src/lib/views/create/wizard/kinds.ts @@ -0,0 +1,19 @@ +// What a project is, from its categories, as an icon and a word: the same three types as the instance's Mods tab. +import { t } from '../../../i18n.svelte' +import type { IconName } from '../../../cubby' +import type { ProjectKind } from '../../../types' + +export interface ProjectType { + icon: IconName + label: string +} + +/** Mods only: a library other mods need, a performance mod, or content. Null when nothing says (CurseForge hits). */ +export function typeOf(categories: string[], kind: ProjectKind): ProjectType | null { + if (kind !== 'mod') return null + const cats = categories.map((c) => c.toLowerCase()) + if (cats.some((c) => c === 'library' || c.includes('api and library'))) return { icon: 'wrench', label: t('Library') } + if (cats.some((c) => c === 'optimization' || c.includes('performance'))) return { icon: 'memory', label: t('Performance') } + if (!cats.length) return null + return { icon: 'cube', label: t('Content') } +} diff --git a/ui/src/lib/views/create/wizard/state.svelte.ts b/ui/src/lib/views/create/wizard/state.svelte.ts new file mode 100644 index 0000000..4077040 --- /dev/null +++ b/ui/src/lib/views/create/wizard/state.svelte.ts @@ -0,0 +1,234 @@ +// The New instance wizard's choices, kept at module level: leaving the screen and coming back keeps them, until +// an instance is created. +import { t } from '../../../i18n.svelte' +import { api } from '../../../api' +import { loaderName } from '../../../format' +import type { Ground, Motif } from '../../../cubby' +import type { LoaderKind, PackProvider, PackSummary, PackVersion, ProviderId, WizardExtra } from '../../../types' + +export type WizardPath = 'custom' | 'modpack' | 'import' +export type StepId = 'start' | 'game' | 'mods' | 'looks' | 'datapacks' | 'review' +export type PickKind = WizardExtra['kind'] + +/** A project picked for the new instance. */ +export interface Pick extends WizardExtra { + iconUrl: string | null + author: string +} + +export interface StepInfo { + id: StepId + label: string + sub: string + optional: boolean +} + +export const STEP_ORDER: StepId[] = ['start', 'game', 'mods', 'looks', 'datapacks', 'review'] + +/** Mods several players add first, by Modrinth slug: sets of quick picks. */ +export const QUICK_PICKS: { id: string; label: string; icon: 'update' | 'cube' | 'globe'; mods: { slug: string; title: string; author: string }[] }[] = [ + { + id: 'performance', + label: 'Performance set', + icon: 'update', + mods: [ + { slug: 'sodium', title: 'Sodium', author: 'CaffeineMC' }, + { slug: 'lithium', title: 'Lithium', author: 'CaffeineMC' }, + { slug: 'ferrite-core', title: 'FerriteCore', author: 'malte0811' }, + { slug: 'entityculling', title: 'EntityCulling', author: 'tr7zw' }, + ], + }, + { + id: 'shaders', + label: 'Ready for shaders', + icon: 'cube', + mods: [ + { slug: 'iris', title: 'Iris Shaders', author: 'coderbot, IMS' }, + { slug: 'sodium', title: 'Sodium', author: 'CaffeineMC' }, + ], + }, + { + id: 'map', + label: 'Map and info', + icon: 'globe', + mods: [ + { slug: 'xaeros-minimap', title: 'Xaero’s Minimap', author: 'xaero96' }, + { slug: 'jade', title: 'Jade', author: 'Snownee' }, + ], + }, +] + +export const pickKey = (p: Pick | WizardExtra) => `${p.source}:${p.kind}:${p.projectId}` + +class WizardState { + step = $state('start') + path = $state('custom') + /** Import: from a file, or from a link. */ + importFrom = $state<'file' | 'link'>('file') + + // custom + minecraft = $state(null) + loader = $state('fabric') + loaderVersion = $state(null) + + // modpack + provider = $state('modrinth') + pack = $state(null) + packVersions = $state(null) + packVersionId = $state(null) + packVersionsError = $state(null) + + picks = $state([]) + turnOn = $state(true) + + // identity + name = $state('') + nameTouched = $state(false) + group = $state('') + motif = $state() + ground = $state() + src = $state(null) + iconTouched = $state(false) + + get packVersion(): PackVersion | null { + return this.packVersions?.find((v) => v.id === this.packVersionId) ?? null + } + + /** The Minecraft version content is looked up for. */ + get gameVersion(): string | null { + return this.path === 'modpack' ? (this.packVersion?.minecraft ?? this.pack?.minecraft[0] ?? null) : this.minecraft + } + + /** The loader content is looked up for; null when a pack doesn't say. */ + get gameLoader(): LoaderKind | null { + if (this.path !== 'modpack') return this.loader + return this.packVersion?.loader ?? this.pack?.loaders[0] ?? null + } + + get vanilla(): boolean { + return this.path === 'custom' && this.loader === 'vanilla' + } + + get defaultName(): string { + if (this.path === 'modpack') return this.pack?.name ?? t('New modpack') + if (!this.minecraft) return t('New instance') + return `${this.loader === 'vanilla' ? 'Minecraft' : loaderName(this.loader)} ${this.minecraft}` + } + + get shownName(): string { + return this.name.trim() || this.defaultName + } + + /** Every step but Start is shown for building or a pack; an import only has Start. */ + get steps(): StepInfo[] { + if (this.path === 'import') return [{ id: 'start', label: t('Start'), sub: t('Import'), optional: false }] + const pack = this.path === 'modpack' + const game = this.gameVersion ? `${this.gameVersion}${this.gameLoader ? ` · ${loaderName(this.gameLoader)}` : ''}` : t('Not picked yet') + return [ + { id: 'start', label: t('Start'), sub: pack ? t('From a modpack') : t('Build your own'), optional: false }, + { id: 'game', label: pack ? t('Modpack') : t('Game'), sub: pack ? (this.pack?.name ?? t('Not picked yet')) : game, optional: false }, + { id: 'mods', label: pack ? t('Extra mods') : t('Mods'), sub: t('Optional'), optional: true }, + { id: 'looks', label: t('Looks'), sub: t('Optional'), optional: true }, + { id: 'datapacks', label: t('Datapacks'), sub: t('Optional'), optional: true }, + { id: 'review', label: t('Review'), sub: t('Name and create'), optional: false }, + ] + } + + picked(kind: PickKind): Pick[] { + return this.picks.filter((p) => p.kind === kind) + } + + /** Picks a modpack, with one of its versions: the one given (from its page), else its newest release once loaded. */ + choosePack(provider: ProviderId, pack: PackSummary, versions?: PackVersion[] | null, versionId?: string | null) { + const same = this.pack?.id === pack.id && this.provider === provider + this.provider = provider + this.pack = pack + if (versions?.length) { + this.packVersions = versions + this.packVersionId = versionId ?? (versions.find((v) => v.channel === 'release') ?? versions[0]).id + this.packVersionsError = null + return + } + if (same && this.packVersions) return + this.packVersions = null + this.packVersionId = null + this.packVersionsError = null + api + .packVersions(provider, pack.id) + .then((list) => { + if (this.pack?.id !== pack.id) return + this.packVersions = list + this.packVersionId = (list.find((v) => v.channel === 'release') ?? list[0])?.id ?? null + }) + .catch((e) => { + if (this.pack?.id === pack.id) this.packVersionsError = typeof e === 'string' ? e : e instanceof Error ? e.message : String(e) + }) + } + + has(p: Pick | WizardExtra): boolean { + return this.picks.some((x) => pickKey(x) === pickKey(p)) + } + + toggle(p: Pick) { + if (this.has(p)) this.remove(p) + else this.add(p) + } + + add(p: Pick) { + if (this.has(p)) return + // one shader pack at a time + const rest = p.kind === 'shader' ? this.picks.filter((x) => x.kind !== 'shader') : this.picks + this.picks = [...rest, p] + } + + remove(p: Pick | WizardExtra) { + this.picks = this.picks.filter((x) => pickKey(x) !== pickKey(p)) + } + + /** The shader pack needs Iris and the player hasn't added it (a pack may have it: not checked there). */ + get shaderNeedsIris(): boolean { + return this.path === 'custom' && this.picked('shader').length > 0 && !this.picks.some((p) => p.kind === 'mod' && p.source === 'modrinth' && p.projectId === 'iris') + } + + addIris() { + for (const m of QUICK_PICKS.find((q) => q.id === 'shaders')!.mods) this.add({ source: 'modrinth', projectId: m.slug, kind: 'mod', title: m.title, author: m.author, iconUrl: null }) + } + + /** Changing the version, loader or pack keeps the picks: Cubby finds each one's version for the instance. */ + reset() { + this.step = 'start' + this.path = 'custom' + this.minecraft = null + this.loader = 'fabric' + this.loaderVersion = null + this.pack = null + this.packVersions = null + this.packVersionId = null + this.packVersionsError = null + this.picks = [] + this.turnOn = true + this.name = '' + this.nameTouched = false + this.group = '' + this.src = null + this.iconTouched = false + } + + /** Opens on what the rest of the app asked for (`app.newSource`). */ + openOn(source: 'quick' | 'custom' | 'import' | 'link' | ProviderId, providers: PackProvider[] | null) { + if (source === 'custom') { + this.path = 'custom' + this.step = 'game' + } else if (source === 'import' || source === 'link') { + this.path = 'import' + this.importFrom = source === 'link' ? 'link' : 'file' + this.step = 'start' + } else if (source !== 'quick' && providers?.some((p) => p.id === source)) { + this.path = 'modpack' + this.provider = source + this.step = 'game' + } + } +} + +export const wizard = new WizardState() diff --git a/ui/src/lib/views/discover/CfInstall.svelte b/ui/src/lib/views/discover/CfInstall.svelte new file mode 100644 index 0000000..eeacdcd --- /dev/null +++ b/ui/src/lib/views/discover/CfInstall.svelte @@ -0,0 +1,429 @@ + + + +
+ {#if !compact}

{t('Install')}

{/if} +
+ {t('Install to')} + +
+ {#if isDatapack} +
+ {t('Into world')} + +
+ {/if} + + {#if !target} +

{t('Create an instance first: {many} go into one.', { many: words.many })}

+ {:else} + {#if filesError} + {#snippet retry()}{#if !all}{/if}{/snippet} + {filesError} + {:else if usable === null} +

{t('Loading files…')}

+ {:else if !usable.length} +

+ {everyVersion || all + ? t('{title} has no file Cubby can install.', { title: project.title }) + : t('{title} has no file for Minecraft {mc}.', { title: project.title, mc: target.minecraft })} +

+ {#if !everyVersion && !all}{/if} + {:else if chosen} +
+ {t('File')} + (fileId = id)} label={t('File')} listWidth={380}> + {#snippet trigger()} + + {chosen.name} + {fileMeta(chosen)} + + {/snippet} + {#snippet option(item)} + + {item.f.name} + {fileMeta(item.f)}{#if item.f.released} · {relativeTime(item.f.released, '')}{/if} + + {/snippet} + + {#if !everyVersion && !all} + + {/if} +
+ + {#if !chosenFits} +

+ {kind === 'mod' ? t('This file isn’t made for {name}: the game may not start with it.', { name: target.name }) : t('This file isn’t made for Minecraft {mc}. It may not load.', { mc: target.minecraft })} +

+ {/if} + + {#if !chosen.downloadable} + + {t('Its author only lets it be downloaded on curseforge.com. Download it there, then add it to {name}.', { name: target.name })} + + + {:else} + {#if !isDatapack} +
+ {#if planError} +

{t('Couldn\'t check it: {planError}', { planError })}

+ {:else if !current} + + {:else} + {#if main?.replaces && !main.installed} +

{t('{name} has another version:', { name: target.name })} {main.replaces}{t('. Cubby replaces it.')}

+ {/if} + {#if deps.length || current.missing.length} +

{t('Also needed')}

+
    + {#each deps as d (d.projectId)} +
  • + + + {d.title} + {d.manualUrl ? t('Only on CurseForge: download it by hand') : t('Added with it · {size}', { size: bytes(d.size) })} + + {#if d.manualUrl}{/if} +
  • + {/each} + {#each current.missing as m (m.projectId)} +
  • + + + {m.title} + {t('No file for {name}', { name: target.name })} + + +
  • + {/each} +
+ {:else if !main?.installed} +

{t('Nothing else needed: everything it requires is already in {name}.', { name: target.name })}

+ {/if} + {#if current.downloadBytes > 0} +

{t('{n} to download', { n: bytes(current.downloadBytes) })}{manualDeps.length ? t(', and {n} to get from CurseForge.', { n: plural(manualDeps.length, 'file', 'files') }) : '.'}

+ {/if} + {/if} +
+ {/if} + + {#if task && !isDatapack} +
+ +

{t('Installing to {name}. You can keep browsing.', { name: target.name })}

+
+ {:else if isDone} +
+ {isDatapack ? t('In the world') : t('In {name}', { name: target.name })} + {#if (isDatapack || words.tab) && !inInstance} + + {/if} +
+ {:else} + {#if failed}{failed}{/if} + + {#if running}

{t('Close the game first.')}

{/if} + {/if} + {/if} + {/if} + {/if} + + {#if compact}{/if} +
+ + diff --git a/ui/src/lib/views/discover/DatapackInstall.svelte b/ui/src/lib/views/discover/DatapackInstall.svelte index 509ce0b..2886f26 100644 --- a/ui/src/lib/views/discover/DatapackInstall.svelte +++ b/ui/src/lib/views/discover/DatapackInstall.svelte @@ -21,9 +21,11 @@ compact?: boolean /** Called when a link of the panel leaves the screen (to close a dialog). */ onLeave?: () => void + /** Changing the version of a datapack already in the world: its file, moved to the trash once the new one is in. */ + replaces?: string } - let { project, versions: given, versionsError = null, compact = false, onLeave }: Props = $props() + let { project, versions: given, versionsError = null, compact = false, onLeave, replaces }: Props = $props() function message(e: unknown): string { return typeof e === 'string' ? e : e instanceof Error ? e.message : JSON.stringify(e) @@ -81,7 +83,8 @@ busy = true const k = key try { - await api.installDatapack(target.id, app.targetWorld, project.id, chosen.id) + const file = await api.installDatapack(target.id, app.targetWorld, project.id, chosen.id) + if (replaces && replaces !== file) await api.removeDatapack(target.id, app.targetWorld, replaces).catch(() => {}) done = [...done, k] app.toast(t('{title} is in the world. It loads the next time you open it.', { title: project.title }), 'success') } catch (e) { diff --git a/ui/src/lib/views/discover/Discover.svelte b/ui/src/lib/views/discover/Discover.svelte index b8ebb37..b6933df 100644 --- a/ui/src/lib/views/discover/Discover.svelte +++ b/ui/src/lib/views/discover/Discover.svelte @@ -5,6 +5,8 @@ /** The "Popular modpacks" and "Make it look better" picks, loaded once per session. */ let picks: Promise<{ pack: ProjectHit | null; shader: ProjectHit | null; resource: ProjectHit | null }> | null = null + /** Minecraft releases, newest first, for the version filters; loaded once per session. */ + let releases: Promise | null = null + +
+ {#if !versionId && !loadingVersions} +

{t('This pack has no version to look into yet.')}

+ {:else if error} +
+

{t('Couldn\'t load the contents of this version. {error}', { error })}

+ +
+ {:else if !versionId || !contents} +
+

{versionId ? t('Reading the pack\'s list of files…') : t('Loading the versions…')}

+
+ + {:else if contents.unavailable} +

{t(contents.unavailable)}

+ {:else if !items.length} +

{t('This version doesn\'t list any mods.')}

+ {:else} +
+

+ {#if versionName}{t('Version')} {versionName}{' · '}{/if}{summary}{#if optionalCount}{' · '}{tn(optionalCount, 'optional', 'optional')}{/if} +

+ {#if items.length > SEARCH_FROM} + + {/if} +
+ + {#if !shown.length} +
+

{t('Nothing in this version matches “{query}”.', { query: query.trim() })}

+ +
+ {:else} + {#each GROUPS as g (g.kind)} + {@const list = visible.filter((i) => i.kind === g.kind)} + {#if list.length} +
+ {#if mixed}

{g.title} {num(shown.filter((i) => i.kind === g.kind).length)}

{/if} +
+ {#each list as i, n (n + i.name + (i.fileName ?? ''))} + {@const kind = modKind(i)} +
+ {#if openable(i)} + + + {/if} +
+ {#if i.iconUrl}{:else}{/if} +
+
+ {i.name} + {#if i.version ?? i.fileName}{i.version ?? i.fileName}{/if} + {#if i.authors.length}{t('by {authors}', { authors: i.authors.join(', ') })}{/if} + {#if i.optional}{t('optional')}{/if} + {#if kind} + + {kind.label} + + {/if} +
+ {#if i.description}

{i.description}

{/if} +
+
+
+ {/each} +
+
+ {/if} + {/each} + {#if shown.length > visible.length} +
+ {t('Showing {n} of {n2}', { n: num(visible.length), n2: num(shown.length) })} + +
+ {/if} + {/if} + {/if} +
+ + diff --git a/ui/src/lib/views/discover/Picker.svelte b/ui/src/lib/views/discover/Picker.svelte index 791d4a4..9e32970 100644 --- a/ui/src/lib/views/discover/Picker.svelte +++ b/ui/src/lib/views/discover/Picker.svelte @@ -205,6 +205,10 @@ color: var(--ink); cursor: pointer; } + /* The tight start padding is for a picker that opens on an emblem (an instance, a world); text gets the usual one. */ + .trigger:not(.ghost):not(:has(> .content > .cb-instance-icon:first-child, > .content > img:first-child, > .content > .thumb:first-child)) { + padding-inline-start: var(--space-3); + } .trigger.field { background: var(--field); border: var(--border-block) solid var(--outline); diff --git a/ui/src/lib/views/discover/ProjectPage.svelte b/ui/src/lib/views/discover/ProjectPage.svelte index 6654dca..a889038 100644 --- a/ui/src/lib/views/discover/ProjectPage.svelte +++ b/ui/src/lib/views/discover/ProjectPage.svelte @@ -1,28 +1,53 @@ - -{#if kind === 'datapack'} +{#if cf} + +{:else if kind === 'datapack'} {:else} @@ -56,14 +73,14 @@

{t('Details')}

{#if project.license}
{t('License')}
{project.license}
{/if} - {#if kind === 'mod' && side}
{t('Runs on')}
{side}
{/if} + {#if kind === 'mod' && side && !cf}
{t('Runs on')}
{side}
{/if} {#if project.gameVersions.length}
Minecraft
{mcRange(project.gameVersions)}
{/if} {#if project.loaders.length && kind !== 'resourcepack'}
{kind === 'shader' ? t('Runs with') : 'Loaders'}
{(kind === 'shader' ? project.loaders : modLoadersOf(project.loaders)).map(loaderLabel).join(', ') || '—'}
{/if}
{t('Versions')}
{num(Math.max(project.versionCount, versions?.length ?? 0))}
-
{t('Source')}
Modrinth
+
{t('Source')}
{cf ? 'CurseForge' : 'Modrinth'}
{t('Since')}
{date(project.published)}
diff --git a/ui/src/lib/views/discover/project/ProjectHeader.svelte b/ui/src/lib/views/discover/project/ProjectHeader.svelte index ed0468e..871ad24 100644 --- a/ui/src/lib/views/discover/project/ProjectHeader.svelte +++ b/ui/src/lib/views/discover/project/ProjectHeader.svelte @@ -14,8 +14,9 @@ const icon = $derived(project.iconUrl ? { src: project.iconUrl } : projectArt(project.slug)) const featured = $derived(project.featuredImage ?? project.gallery.find((g) => g.featured)?.url ?? project.gallery[0]?.url ?? null) - const pageUrl = $derived(modrinthUrl(kind, project.slug)) - const authorUrl = $derived(`https://modrinth.com/user/${encodeURIComponent(project.author)}`) + const cf = $derived(project.source === 'curseforge') + const pageUrl = $derived(project.pageUrl ?? modrinthUrl(kind, project.slug)) + const authorUrl = $derived(cf ? `https://www.curseforge.com/members/${encodeURIComponent(project.author)}` : `https://modrinth.com/user/${encodeURIComponent(project.author)}`) const side = $derived(sideText(project.clientSide, project.serverSide)) const resolution = $derived(resolutionOf(project.categories)) const packMc = $derived(chosen ? newestMc(chosen.gameVersions) : null) @@ -58,14 +59,14 @@
  • {t('{n} downloads', { n: compactNum(project.downloads) })}
  • -
  • {t('{n} followers', { n: compactNum(project.follows) })}
  • + {#if !cf}
  • {t('{n} followers', { n: compactNum(project.follows) })}
  • {/if}
  • {t('Updated {never}', { never: lower(relativeTime(project.updated, 'never')) })}
  • -
  • {t('Source: Modrinth')}
  • +
  • {cf ? t('Source: CurseForge') : t('Source: Modrinth')}
- openUrl(pageUrl)} /> + openUrl(pageUrl)} />
@@ -171,7 +172,6 @@ min-height: 160px; aspect-ratio: 16 / 9; object-fit: cover; - image-rendering: pixelated; box-sizing: border-box; border: var(--border-block) solid var(--edge); box-shadow: var(--shadow-block); diff --git a/ui/src/lib/views/discover/project/shared.ts b/ui/src/lib/views/discover/project/shared.ts index ea8787a..07c85e7 100644 --- a/ui/src/lib/views/discover/project/shared.ts +++ b/ui/src/lib/views/discover/project/shared.ts @@ -36,7 +36,7 @@ export function depStatus(d: Dependency, target: Instance | undefined): { tone: export function openDep(d: Dependency) { const id = d.slug ?? d.projectId - if (id) app.openProject(id, 'mod') + if (id) app.openProject(id, 'mod', undefined, d.title ?? undefined) } /** Opens a web page in the browser. */ diff --git a/ui/src/lib/views/instance-page/InstancePage.svelte b/ui/src/lib/views/instance-page/InstancePage.svelte index c0d2bf5..106ea9a 100644 --- a/ui/src/lib/views/instance-page/InstancePage.svelte +++ b/ui/src/lib/views/instance-page/InstancePage.svelte @@ -3,7 +3,8 @@ import { date, timeOfDay } from '../../format' import { t } from '../../i18n.svelte' import { app } from '../../state.svelte' - import type { ContentSource, ContentUpdate, Instance, ModFile, Pack, ProjectKind, Screenshot, Server, World, UpdateBackup, WorldBackup } from '../../types' + import type { CfInstalled, ContentSource, ContentUpdate, Instance, ModFile, Pack, ProjectKind, Screenshot, Server, World, UpdateBackup, WorldBackup } from '../../types' + import type { VersionTarget } from './VersionDialog.svelte' // Helpers shared by the tabs of this folder (plain hoisted functions, safe to import from the tabs). @@ -58,6 +59,10 @@ /** Files identified on Modrinth, by file name without ".disabled". */ sourceByFile = $derived.by(() => new Map((app.sources[this.id] ?? []).map((s) => [baseFile(s.fileName), s] as const))) + /** Files identified on CurseForge, by file name without ".disabled". */ + cfByFile = $derived.by(() => new Map((app.cfInstalled[this.id] ?? []).map((f) => [baseFile(f.fileName), f] as const))) + /** The project whose versions are shown (Versions dialog). */ + versionsOf = $state(null) /** Available updates, by file name without ".disabled". */ updateByFile = $derived.by(() => new Map((app.updates[this.id] ?? []).map((u) => [baseFile(u.fileName), u] as const))) /** Mods turned on more than once (two files with the same mod name): file name → the other files. */ @@ -99,6 +104,36 @@ return this.sourceByFile.get(baseFile(fileName)) } + /** The file's CurseForge project, when it comes from CurseForge: downloaded from there, or unknown to Modrinth. */ + cfSource(fileName: string): CfInstalled | undefined { + const cf = this.cfByFile.get(baseFile(fileName)) + return cf && (cf.fromCurseforge || !this.source(fileName)) ? cf : undefined + } + + /** Where the file comes from. A file on both sites counts as CurseForge when it was downloaded from there. */ + origin(fileName: string): 'modrinth' | 'curseforge' | 'local' { + return this.cfSource(fileName) ? 'curseforge' : this.source(fileName) ? 'modrinth' : 'local' + } + + /** Where the file comes from, for its logo. */ + sourceTone(fileName: string): 'modrinth' | 'curseforge' | 'local' { + return this.origin(fileName) + } + + /** Where the file comes from, in words: "Modrinth", "CurseForge" or "Local file". */ + sourceName(fileName: string): string { + const o = this.origin(fileName) + return o === 'modrinth' ? 'Modrinth' : o === 'curseforge' ? 'CurseForge' : t('Local file') + } + + /** Where another version of this file can come from, if Modrinth or CurseForge knows it. */ + versionTarget(fileName: string, kind: ProjectKind, title: string): VersionTarget | null { + const cf = this.cfSource(fileName) + const mr = this.source(fileName) + if (cf) return { source: 'curseforge', projectId: cf.projectId, kind, title: mr?.title || title, current: cf.fileId } + return mr ? { source: 'modrinth', projectId: mr.projectId, kind, title: mr.title || title, current: mr.versionId } : null + } + update(fileName: string): ContentUpdate | undefined { return this.updateByFile.get(baseFile(fileName)) } @@ -215,9 +250,15 @@ } /** Opens a Modrinth project page, installing into this instance. */ - project(slug: string, kind: ProjectKind) { + project(slug: string, kind: ProjectKind, title?: string) { + app.setTarget(this.id) + app.openProject(slug, kind, undefined, title) + } + + /** Opens a CurseForge project page, installing into this instance. */ + cfProject(projectId: string, kind: ProjectKind, title?: string) { app.setTarget(this.id) - app.openProject(slug, kind) + app.openProject(projectId, kind, 'curseforge', title) } async duplicate(instance: Instance) { @@ -262,6 +303,7 @@ import WorldsTab from './WorldsTab.svelte' import ScreenshotsTab from './ScreenshotsTab.svelte' import BlockedFilesDialog from './BlockedFilesDialog.svelte' + import VersionDialog from './VersionDialog.svelte' import ServersTab from './ServersTab.svelte' import SettingsTab from './SettingsTab.svelte' @@ -275,6 +317,10 @@ const busy = $derived(!!startedAt || !!task) data.loadAll() + // Files from CurseForge (only with a key: it asks CurseForge by fingerprint). + $effect(() => { + if (app.info?.curseforgeKey) untrack(() => void app.loadCfInstalled(id)) + }) // Check Modrinth for updates when the player asked for it in Settings (again after an update ran). $effect(() => { @@ -549,6 +595,10 @@
{/if} +{#if data.versionsOf} + (data.versionsOf = null)} /> +{/if} + {#if exporting && instance} (exporting = false)} /> {/if} diff --git a/ui/src/lib/views/instance-page/ModsTab.svelte b/ui/src/lib/views/instance-page/ModsTab.svelte index 64a57db..477a178 100644 --- a/ui/src/lib/views/instance-page/ModsTab.svelte +++ b/ui/src/lib/views/instance-page/ModsTab.svelte @@ -9,11 +9,12 @@ import { t } from '../../i18n.svelte' import { tick, untrack } from 'svelte' import { api } from '../../api' - import { Banner, Button, Dialog, Icon, Inspector, InspectorHead, InspectorNotice, InspectorPath, InspectorSection, InspectorStatus, InstanceIcon, MetaChip, ModRow, ProgressBar, SegmentedControl, TextField } from '../../cubby' + import { Banner, Button, Dialog, Icon, Inspector, InspectorHead, InspectorNotice, InspectorPath, InspectorSection, InspectorStatus, InstanceIcon, MetaChip, ModRow, ProgressBar, SegmentedControl, TextField, SourceMark } from '../../cubby' import { bytes, fold, num, plural, relativeTime } from '../../format' import { projectArt } from '../../icon' import { app } from '../../state.svelte' - import type { ContentSource, ContentUpdate, Instance, ModFile } from '../../types' + import type { IconName } from '../../cubby' + import type { CfInstalled, ContentSource, ContentUpdate, Instance, ModFile } from '../../types' import { baseFile, modName, when, type InstanceData } from './InstancePage.svelte' import Markdown from '../discover/Markdown.svelte' @@ -22,15 +23,21 @@ const id = $derived(instance.id) type Filter = 'all' | 'updates' | 'warnings' | 'disabled' - let query = $state('') - let filter = $state('all') - let selected = $state(null) + // Back to the instance shows the tab as it was left: the search, the filter and the mod selected. + let query = $state(untrack(() => app.recall('query') ?? '')) + let filter = $state(untrack(() => app.recall('filter') ?? 'all')) + let selected = $state(untrack(() => app.recall('selected') ?? null)) + $effect(() => { + app.keep('query', query) + app.keep('filter', filter) + app.keep('selected', selected) + }) let limit = $state(60) let removing = $state(null) let removeBusy = $state(false) let asideTitle: HTMLElement | undefined = $state() - type Row = { mod: ModFile; key: string; name: string; search: string; source?: ContentSource; update?: ContentUpdate; twins?: ModFile[] } + type Row = { mod: ModFile; key: string; name: string; search: string; source?: ContentSource; cf?: CfInstalled; update?: ContentUpdate; twins?: ModFile[] } // Recomputed when the files, sources or updates change, not on each keystroke. // A row keeps its key (the file name without ".disabled") when the mod is turned on or off, so focus stays on it; @@ -49,6 +56,7 @@ name, search: fold(`${name} ${mod.fileName} ${mod.description ?? ''} ${mod.authors.join(' ')}`), source: data.source(mod.fileName), + cf: data.cfSource(mod.fileName), update: data.update(mod.fileName), twins: data.twins.get(mod.fileName), } @@ -79,11 +87,39 @@ ) const visible = $derived(shown.slice(0, limit)) - const sel = $derived(rows.find((r) => r.key === selected) ?? null) + /** The selected mod's project: an update renames its file, and the selection follows it to the new one. */ + let selectedProject: string | null = null + /** The last row shown in the panel, kept while its renamed file is being identified. */ + let lastSel: Row | null = null + const found = $derived(rows.find((r) => r.key === selected) ?? null) + const sel = $derived(found ?? (selected ? lastSel : null)) + $effect(() => { + if (found) { + lastSel = found + selectedProject = found.source?.projectId ?? found.cf?.projectId ?? selectedProject + return + } + const pid = selectedProject + const again = pid ? rows.find((r) => (r.source?.projectId ?? r.cf?.projectId) === pid) : undefined + if (again) selected = again.key + }) const updateTask = $derived(app.tasks[`update:${id}`]) const installTask = $derived(app.tasks[`install:${id}`]) const running = $derived(!!app.running[id]) + /** What a mod is, from its Modrinth categories: a library other mods need, a performance mod, or content. */ + function modKind(categories: string[]): { icon: IconName; label: string } { + if (categories.includes('library')) return { icon: 'wrench', label: t('Library') } + if (categories.includes('optimization')) return { icon: 'memory', label: t('Performance') } + return { icon: 'cube', label: t('Content') } + } + + /** Where a file comes from: Modrinth, CurseForge, or neither (added by hand, or from a pack). */ + function sourceTag(r: Row): { label: string; tone: 'modrinth' | 'curseforge' | 'local' } { + const tone = data.origin(r.mod.fileName) + return { label: data.sourceName(r.mod.fileName), tone } + } + function select(r: Row) { selected = r.key void focusPanel() @@ -218,7 +254,7 @@ const authors = (m: ModFile) => (m.authors.length ? `by ${m.authors.join(', ')}` : undefined) -
+
{/each} @@ -345,8 +383,14 @@ {:else if !m.enabled} {/if} - {#if m.enabled}{/if} - {#if sel.source}{/if} + {#if m.enabled}{/if} + {#if sel.source || sel.cf} +
+ {#if sel.source && !sel.cf}{/if} + {#if sel.cf}{/if} + +
+ {/if}
{#if sel.update} {@const lines = notes(sel.update.changelog)} @@ -373,8 +417,11 @@
- {#if kind}
{t('Type')}
{kind}
{/if} -
{t('Source')}
{sel.source ? 'Modrinth' : t('Not found on Modrinth')}
+ {#if sel.source} + {@const k = modKind(sel.source.categories)} +
{t('Type')}
{kind ?? k.label}
+ {:else if kind}
{t('Type')}
{kind}
{/if} +
{t('Source')}
{sel.source || sel.cf ? data.sourceName(m.fileName) : t('Not found on Modrinth or CurseForge')}
{#if project}
{t('Updated')}
{relativeTime(project.updated)}
{/if}
{t('Size')}
{bytes(m.size)}
data.openFolder('mods')} /> @@ -555,4 +602,9 @@ .empty :global(.cb-btn) { margin-top: var(--space-2); } + .with-icon { + display: inline-flex; + align-items: center; + gap: var(--space-2); + } diff --git a/ui/src/lib/views/instance-page/OverviewTab.svelte b/ui/src/lib/views/instance-page/OverviewTab.svelte index 386b670..c2cccf9 100644 --- a/ui/src/lib/views/instance-page/OverviewTab.svelte +++ b/ui/src/lib/views/instance-page/OverviewTab.svelte @@ -7,8 +7,11 @@ import { app, type InstanceTab } from '../../state.svelte' import type { Instance, ServerStatus } from '../../types' import { baseFile, gigabytes, modName, when, type InstanceData } from './InstancePage.svelte' + import PackVersionDialog from './PackVersionDialog.svelte' let { instance, data }: { instance: Instance; data: InstanceData } = $props() + /** The modpack's Versions dialog is open. */ + let packVersions = $state(false) const id = $derived(instance.id) const go = (tab: InstanceTab) => app.openInstance(id, tab) @@ -153,7 +156,7 @@ }) -
+
@@ -263,8 +266,13 @@ {#if instance.modpack}
{t('Modpack')}
- + {#if (instance.modpack.provider ?? 'modrinth') === 'modrinth'} + + {:else} + {instance.modpack.title} + {/if} {instance.modpack.versionNumber} +
{/if}
{t('Folder')}
@@ -382,6 +390,10 @@
+{#if packVersions && instance.modpack} + (packVersions = false)} /> +{/if} + diff --git a/ui/src/lib/views/instance-page/ResourcePacksTab.svelte b/ui/src/lib/views/instance-page/ResourcePacksTab.svelte index 22b94cd..7d5d70e 100644 --- a/ui/src/lib/views/instance-page/ResourcePacksTab.svelte +++ b/ui/src/lib/views/instance-page/ResourcePacksTab.svelte @@ -2,7 +2,7 @@ import { t } from '../../i18n.svelte' import { tick } from 'svelte' import { api } from '../../api' - import { Banner, Button, Icon, IconButton, Inspector, InspectorHead, InspectorPath, InspectorSection, InspectorStatus, InstanceIcon, MetaChip } from '../../cubby' + import { Banner, Button, Icon, IconButton, Inspector, InspectorHead, InspectorPath, InspectorSection, InspectorStatus, InstanceIcon, MetaChip, SourceMark } from '../../cubby' import { bytes, num, relativeTime } from '../../format' import { projectArt } from '../../icon' import { app } from '../../state.svelte' @@ -98,7 +98,7 @@ {/if} {/snippet} -
+
@@ -129,7 +129,7 @@ {@render art(p)}
-

{describe(p)}

+

{describe(p)}

move(i, i - 1)} /> move(i, i + 1)} /> @@ -166,7 +166,7 @@ {@render art(p)}
-

{describe(p)}

+

{describe(p)}

{@render updateButton(p)} @@ -205,11 +205,17 @@ {/if} {#if sel.enabled} - + {:else} - + + {/if} + {#if data.versionTarget(sel.fileName, 'resourcepack', sel.name)} +
+ {#if selSource && !data.cfSource(sel.fileName)}{/if} + {#if data.cfSource(sel.fileName)}{/if} + +
{/if} - {#if selSource}{/if} {#if sel.enabled && on.length > 1} @@ -219,7 +225,7 @@
{t('Kind')}
{sel.isDir ? t('Folder') : t('Zip file')}
-
{t('Source')}
{selSource ? 'Modrinth' : t('Not found on Modrinth')}
+
{t('Source')}
{data.sourceName(sel.fileName)}
{#if sel.modified}
{t('Changed')}
{relativeTime(sel.modified)}
{/if}
{t('Size')}
{bytes(sel.size)}
data.openFolder('resourcepacks')} /> @@ -391,4 +397,9 @@ gap: var(--space-2); margin-top: var(--space-1); } + .with-mark { + display: flex; + align-items: center; + gap: 6px; + } diff --git a/ui/src/lib/views/instance-page/ScreenshotsTab.svelte b/ui/src/lib/views/instance-page/ScreenshotsTab.svelte index b3f0cf5..084bdcc 100644 --- a/ui/src/lib/views/instance-page/ScreenshotsTab.svelte +++ b/ui/src/lib/views/instance-page/ScreenshotsTab.svelte @@ -141,7 +141,7 @@ -
+

{data.screenshots ? plural(shots.length, 'screenshot', 'screenshots') : t('Screenshots')}

diff --git a/ui/src/lib/views/instance-page/ServersTab.svelte b/ui/src/lib/views/instance-page/ServersTab.svelte index b63455b..53bd5d2 100644 --- a/ui/src/lib/views/instance-page/ServersTab.svelte +++ b/ui/src/lib/views/instance-page/ServersTab.svelte @@ -181,7 +181,7 @@ const versionDiffers = $derived(selStatus?.compatible != null ? selStatus.compatible === false : !!selStatus?.version && !selStatus.version.includes(instance.minecraft)) -
+

{data.servers ? plural(servers.length, 'server', 'servers') : t('Servers')}

diff --git a/ui/src/lib/views/instance-page/SettingsTab.svelte b/ui/src/lib/views/instance-page/SettingsTab.svelte index b600ce5..5a55e85 100644 --- a/ui/src/lib/views/instance-page/SettingsTab.svelte +++ b/ui/src/lib/views/instance-page/SettingsTab.svelte @@ -295,7 +295,7 @@ const game = $derived(app.settings?.game) -
+
diff --git a/ui/src/lib/views/instance-page/ShadersTab.svelte b/ui/src/lib/views/instance-page/ShadersTab.svelte index e634da4..6c11d8b 100644 --- a/ui/src/lib/views/instance-page/ShadersTab.svelte +++ b/ui/src/lib/views/instance-page/ShadersTab.svelte @@ -1,7 +1,7 @@ + + + +{#snippet actions()} + +{/snippet} + + +

{t('Pick another version to go back to an older one, or to move to a newer one. Cubby replaces the file that is there.')}

+ {#if error} + {error} + {:else if !project} +

{t('Loading versions…')}

+ {:else if item.source === 'curseforge'} + + {:else if item.datapack} + + {:else} + + {/if} +
+ + diff --git a/ui/src/lib/views/instance-page/WorldDatapacks.svelte b/ui/src/lib/views/instance-page/WorldDatapacks.svelte index c8ed618..75e7c92 100644 --- a/ui/src/lib/views/instance-page/WorldDatapacks.svelte +++ b/ui/src/lib/views/instance-page/WorldDatapacks.svelte @@ -3,10 +3,11 @@