diff --git a/.github/release-notes.md b/.github/release-notes.md
index dcaa504..d47a0ba 100644
--- a/.github/release-notes.md
+++ b/.github/release-notes.md
@@ -11,7 +11,7 @@
| | Download | |
|---|---|---|
| **Windows** 10 and 11 | `Cubby_{{VERSION}}_x64-setup.exe` | If Windows warns about the installer, click *More info*, then *Run anyway*: it isn't signed yet. |
-| **macOS** 11 or later, Apple Silicon | `Cubby_{{VERSION}}_aarch64.dmg` | Drag Cubby to Applications. The first time macOS blocks it because it isn't notarized yet: open *System Settings*, *Privacy & Security*, and click *Open Anyway*. |
+| **macOS** 11 or later, Apple Silicon | `Cubby_{{VERSION}}_aarch64.dmg` | Drag Cubby to Applications. It is signed and notarized by Apple. |
| **macOS** 11 or later, Intel | `Cubby_{{VERSION}}_x64.dmg` | Same as above. |
| **Linux** 64-bit | `Cubby_{{VERSION}}_amd64.AppImage` | Make it executable, then run it. Debian and Ubuntu can use `Cubby_{{VERSION}}_amd64.deb` instead. |
diff --git a/.github/releases/v2026.11.1.md b/.github/releases/v2026.11.1.md
new file mode 100644
index 0000000..2597220
--- /dev/null
+++ b/.github/releases/v2026.11.1.md
@@ -0,0 +1,40 @@
+
A new way to start an instance, CurseForge as a full source next to Modrinth, and the freedom to go back to the version you liked.
+
+
+
+If something breaks, [open an issue](https://github.com/benjaminbrtrd/Cubby/issues/new) with the crash report from the app.
+
+## ✨ What's new
+
+**A wizard for new instances.** *New instance* now walks you through it: start from scratch, from a modpack or from an import, pick the Minecraft version and the loader (or the pack, which sets both), then, if you like, mods, resource packs, a shader pack and datapacks. A summary follows every choice, and everything installs once the instance is ready. Open any mod or pack from the wizard to read its page, then add it from there.
+
+**CurseForge, all the way.** Mods, resource packs, shader packs and datapacks from CurseForge install straight from Discover, like Modrinth ones: Cubby picks the file made for your instance, adds the mods it requires and replaces an older version you already have. Each project has its own page in Cubby, with its description, gallery and every file. Files whose author only allows downloads on curseforge.com get a link to their page.
+
+**Better filters.** Pick several Minecraft versions, loaders and categories at once, on Modrinth and on CurseForge, modpacks included, from every Minecraft release rather than only the newest ones.
+
+**What's in a modpack.** A modpack's page lists its content (mods, resource packs and shader packs) for the version you pick, on every source: Modrinth, CurseForge, FTB, ATLauncher and Technic.
+
+**Go back to an older version.** Every mod, resource pack, shader pack and world datapack from Modrinth or CurseForge has a *Versions* button: pick an older or a newer version and Cubby replaces the file. An instance made from a modpack can switch to another version of the pack: its mods and settings change, your worlds and your own mods stay.
+
+**Updates checked at start.** When Cubby opens, it looks for mod and pack updates in every instance and tells you what it found. Nothing is updated without you, and a mod on a release is only offered releases.
+
+**Where each file comes from.** Mods and packs show the logo of their source (Modrinth, CurseForge or a local file) and an icon for what they are: content, library or performance. A file you installed from CurseForge stays marked as CurseForge, even when Modrinth has the same file.
+
+**Signed for macOS.** The Mac app is signed and notarized by Apple: it opens without the "unidentified developer" warning.
+
+## 🐛 Fixes
+
+- Updating a mod keeps it selected and its panel open: the list no longer flickers while Cubby reads the new files.
+- *Versions* opens on the version you have installed, not on the newest one.
+- *Hide installed* also works for content from CurseForge.
+- CurseForge searches past 10,000 results say "More than 10,000" instead of a capped number.
+- Side panels no longer cut versions and statuses; the delete buttons fill the width, with their hint underneath.
+- Project galleries show full-size pictures.
+- A click outside a dialog closes it.
+- The Play button of a Library card no longer covers its menu.
+- *Previous* buttons have their chevron, like *Next*.
+
+## ⚠️ Good to know
+
+- **Coming from 2026.11.0?** Cubby updates itself.
+- The version filter of the other modpack sources now lists every version, behind *Show all versions*.
diff --git a/Cargo.lock b/Cargo.lock
index eae13a7..9b628c0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -734,7 +734,7 @@ checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
[[package]]
name = "cubby"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"chrono",
"cubby-atlauncher",
@@ -776,7 +776,7 @@ dependencies = [
[[package]]
name = "cubby-atlauncher"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"cubby-common",
"futures",
@@ -792,7 +792,7 @@ dependencies = [
[[package]]
name = "cubby-auth"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"base64 0.23.1",
"chrono",
@@ -807,7 +807,7 @@ dependencies = [
[[package]]
name = "cubby-common"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -824,7 +824,7 @@ dependencies = [
[[package]]
name = "cubby-curseforge"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"cubby-common",
"reqwest 0.12.28",
@@ -837,7 +837,7 @@ dependencies = [
[[package]]
name = "cubby-discord"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"serde",
"serde_json",
@@ -846,7 +846,7 @@ dependencies = [
[[package]]
name = "cubby-ftb"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"chrono",
"cubby-common",
@@ -860,7 +860,7 @@ dependencies = [
[[package]]
name = "cubby-instance"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"chrono",
"cubby-common",
@@ -876,7 +876,7 @@ dependencies = [
[[package]]
name = "cubby-java"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"cubby-common",
"futures",
@@ -889,7 +889,7 @@ dependencies = [
[[package]]
name = "cubby-launch"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"chrono",
"cubby-common",
@@ -903,7 +903,7 @@ dependencies = [
[[package]]
name = "cubby-meta"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"cubby-common",
"cubby-launch",
@@ -916,7 +916,7 @@ dependencies = [
[[package]]
name = "cubby-modrinth"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"chrono",
"cubby-common",
@@ -931,7 +931,7 @@ dependencies = [
[[package]]
name = "cubby-packinstall"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"cubby-common",
"cubby-ftb",
@@ -949,7 +949,7 @@ dependencies = [
[[package]]
name = "cubby-technic"
-version = "2026.11.0"
+version = "2026.11.1"
dependencies = [
"cubby-common",
"reqwest 0.12.28",
diff --git a/Cargo.toml b/Cargo.toml
index 40163be..64f987b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/*", "src-tauri"]
[workspace.package]
-version = "2026.11.0"
+version = "2026.11.1"
edition = "2021"
license = "GPL-3.0-only"
repository = "https://github.com/benjaminbrtrd/Cubby"
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