feat(discovery): add CurseForge and modpack browsing

This commit is contained in:
objz committed 2026-07-28 14:12:38 +02:00
1 parent 22d5da9f0d
commit 1742f62cd0
38 files changed
+2384 -135

No files matched your search

+64 -1
View File
@@ -1,5 +1,5 @@
use std::collections::{BTreeMap, HashMap};
use std::io::Read;
use std::io::{Read, Seek};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -227,6 +227,7 @@ pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
let mut file = std::fs::File::open(path)?;
let mut sha1 = sha1::Sha1::new();
let mut sha512 = sha2::Sha512::new();
let mut curseforge_len = 0u32;
let mut buffer = [0u8; 64 * 1024];
loop {
let read = file.read(&mut buffer)?;
@@ -235,10 +236,21 @@ pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
}
sha1.update(&buffer[..read]);
sha512.update(&buffer[..read]);
curseforge_len = curseforge_len.saturating_add(
buffer[..read]
.iter()
.filter(|byte| !matches!(byte, b'\t' | b'\n' | b'\r' | b' '))
.count() as u32,
);
}
file.rewind()?;
let hashes = BTreeMap::from([
("sha1".to_owned(), format!("{:x}", sha1.finalize())),
("sha512".to_owned(), format!("{:x}", sha512.finalize())),
(
"curseforge".to_owned(),
curseforge_fingerprint(&mut file, curseforge_len)?.to_string(),
),
]);
Ok(FileFingerprint {
size: metadata.len(),
@@ -247,6 +259,57 @@ pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
})
}
fn curseforge_fingerprint(reader: &mut impl Read, length: u32) -> std::io::Result<u32> {
const M: u32 = 0x5bd1e995;
let mut hash = 1 ^ length;
let mut block = [0u8; 4];
let mut block_len = 0;
let mut buffer = [0u8; 64 * 1024];
loop {
let read = reader.read(&mut buffer)?;
if read == 0 {
break;
}
for &byte in &buffer[..read] {
if matches!(byte, b'\t' | b'\n' | b'\r' | b' ') {
continue;
}
block[block_len] = byte;
block_len += 1;
if block_len == 4 {
let mut value = u32::from_le_bytes(block);
value = value.wrapping_mul(M);
value ^= value >> 24;
value = value.wrapping_mul(M);
hash = hash.wrapping_mul(M) ^ value;
block_len = 0;
}
}
}
match block_len {
3 => {
hash ^= u32::from(block[2]) << 16;
hash ^= u32::from(block[1]) << 8;
hash ^= u32::from(block[0]);
hash = hash.wrapping_mul(M);
}
2 => {
hash ^= u32::from(block[1]) << 8;
hash ^= u32::from(block[0]);
hash = hash.wrapping_mul(M);
}
1 => {
hash ^= u32::from(block[0]);
hash = hash.wrapping_mul(M);
}
_ => {}
}
hash ^= hash >> 13;
hash = hash.wrapping_mul(M);
hash ^= hash >> 15;
Ok(hash)
}
pub fn fingerprint_metadata(path: &Path) -> Result<FileFingerprint, std::io::Error> {
let metadata = std::fs::metadata(path)?;
let modified_ns = metadata
+153
View File
@@ -182,6 +182,143 @@ impl ContentProvider for ModrinthProvider {
}
}
#[derive(Clone)]
pub struct CurseForgeProvider {
client: crate::net::HttpClient,
api_key: String,
}
impl CurseForgeProvider {
pub fn new(client: crate::net::HttpClient, api_key: impl Into<String>) -> Self {
Self {
client,
api_key: api_key.into(),
}
}
}
#[async_trait]
impl ContentProvider for CurseForgeProvider {
fn id(&self) -> &'static str {
"curseforge"
}
async fn search(
&self,
kind: ContentKind,
query: &str,
instance: &InstanceConfig,
offset: usize,
limit: usize,
) -> Result<DiscoveryResults, crate::net::NetError> {
crate::net::curseforge::search_discovery(
&self.client,
&self.api_key,
kind,
query,
&instance.game_version,
instance.loader,
offset,
limit,
)
.await
}
async fn resolve_files(
&self,
files: &[FingerprintQuery],
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
let mut by_fingerprint = HashMap::<u32, Vec<String>>::new();
for file in files {
if let Some(fingerprint) = file
.fingerprint
.hash("curseforge")
.and_then(|value| value.parse().ok())
{
by_fingerprint
.entry(fingerprint)
.or_default()
.push(file.key.clone());
}
}
let fingerprints = by_fingerprint.keys().copied().collect::<Vec<_>>();
let matches = crate::net::curseforge::resolve_fingerprints(
&self.client,
&self.api_key,
&fingerprints,
)
.await?;
Ok(matches
.into_iter()
.flat_map(|(fingerprint, project_id, version_id)| {
by_fingerprint
.get(&fingerprint)
.cloned()
.unwrap_or_default()
.into_iter()
.map(move |key| ResolvedFile {
key,
project: ProviderProject {
provider: self.id().to_owned(),
project_id: project_id.clone(),
version_id: version_id.clone(),
},
})
})
.collect())
}
async fn project(
&self,
project_id: &str,
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError> {
crate::net::curseforge::fetch_project(&self.client, &self.api_key, project_id).await
}
async fn compatible_versions(
&self,
project_id: &str,
kind: ContentKind,
game_version: &str,
loader: ModLoader,
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
crate::net::curseforge::fetch_versions(
&self.client,
&self.api_key,
project_id,
game_version,
(kind == ContentKind::Mod).then_some(loader),
)
.await
}
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError> {
self.client.get_bytes(url).await
}
async fn download_version(
&self,
version: &VersionInfo,
destination: &std::path::Path,
installed_path: Option<&std::path::Path>,
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError> {
let mut version = version.clone();
crate::net::curseforge::ensure_download_url(&self.client, &self.api_key, &mut version)
.await?;
if let Some(installed_path) = installed_path {
crate::net::modrinth::download_version_file_for_update(
&self.client,
&version,
destination,
installed_path,
)
.await
} else {
crate::net::modrinth::download_version_file(&self.client, &version, destination).await
}
}
}
pub struct ProviderRegistry {
providers: Vec<Box<dyn ContentProvider>>,
}
@@ -193,6 +330,15 @@ impl ProviderRegistry {
}
}
pub fn configured(client: crate::net::HttpClient) -> Self {
let mut providers: Vec<Box<dyn ContentProvider>> =
vec![Box::new(ModrinthProvider::new(client.clone()))];
if let Some(api_key) = crate::config::SETTINGS.content.curseforge_api_key() {
providers.push(Box::new(CurseForgeProvider::new(client, api_key)));
}
Self { providers }
}
pub fn providers(&self) -> &[Box<dyn ContentProvider>] {
&self.providers
}
@@ -204,6 +350,13 @@ impl ProviderRegistry {
.map(Box::as_ref)
.or_else(|| self.providers.first().map(Box::as_ref))
}
pub fn get(&self, id: &str) -> Option<&dyn ContentProvider> {
self.providers
.iter()
.find(|provider| provider.id() == id)
.map(Box::as_ref)
}
}
#[cfg(test)]
+22 -3
View File
@@ -161,7 +161,7 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
match inventory {
Ok(Ok((mut inventory, manifest_path))) => {
let registry = ProviderRegistry::modrinth(client);
let registry = ProviderRegistry::configured(client);
task.set_action(format!("Identifying content for {instance_name}"));
task.set_sub_action(format!("{} file(s) need matching", inventory.queries.len()));
if !inventory.queries.is_empty() {
@@ -365,6 +365,17 @@ fn reconcile_inventory(
providers: Vec::new(),
};
}
let curseforge_unchecked = crate::config::SETTINGS
.content
.curseforge_api_key()
.is_some()
&& provider_was_not_checked(&record.resolution, "curseforge");
if !is_directory && !oversized && curseforge_unchecked {
if record.fingerprint.hash("curseforge").is_none() {
record.fingerprint = fingerprint(&path)?;
}
record.resolution = Resolution::Pending;
}
let should_query = !is_directory
&& !oversized
&& match &record.resolution {
@@ -388,6 +399,14 @@ fn reconcile_inventory(
Ok(Inventory { manifest, queries })
}
fn provider_was_not_checked(resolution: &Resolution, provider: &str) -> bool {
matches!(
resolution,
Resolution::Unmatched { providers, .. }
if !providers.iter().any(|checked| checked == provider)
)
}
async fn resolve_queries(
registry: &ProviderRegistry,
queries: &[FingerprintQuery],
@@ -455,10 +474,10 @@ async fn resolve_queries(
project: project.clone(),
},
_ if !crate::config::SETTINGS.content.ask_on_provider_conflict => {
let preferred = &crate::config::SETTINGS.content.preferred_provider;
let preferred = crate::config::SETTINGS.content.preferred_provider();
if let Some(project) = candidates
.iter()
.find(|project| &project.provider == preferred)
.find(|project| project.provider == preferred)
{
Resolution::Resolved {
project: project.clone(),
+250
View File
@@ -0,0 +1,250 @@
// curseforge modpack archives: manifest.json references provider file ids,
// while the overrides directory contains configs and other bundled files.
use std::io::Read;
use std::path::Path;
use serde::Deserialize;
use crate::feedback::progress;
use crate::instance::{InstanceConfig, InstanceManager, ModLoader};
use super::{ImportSummary, PackFormat};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Manifest {
name: String,
version: String,
minecraft: Minecraft,
#[serde(default)]
files: Vec<ManifestFile>,
#[serde(default = "default_overrides")]
overrides: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Minecraft {
version: String,
#[serde(default)]
mod_loaders: Vec<ManifestLoader>,
}
#[derive(Debug, Deserialize)]
struct ManifestLoader {
id: String,
#[serde(default)]
primary: bool,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ManifestFile {
#[serde(rename = "projectID")]
_project_id: u64,
#[serde(rename = "fileID")]
file_id: u64,
#[serde(default = "required_by_default")]
required: bool,
}
fn default_overrides() -> String {
"overrides".to_owned()
}
fn required_by_default() -> bool {
true
}
fn parse(path: &Path) -> Result<Manifest, String> {
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
let entry = archive
.by_name("manifest.json")
.map_err(|_| "Missing manifest.json in CurseForge pack".to_owned())?;
serde_json::from_reader(entry).map_err(|error| format!("Invalid CurseForge manifest: {error}"))
}
fn loader(manifest: &Manifest) -> (ModLoader, Option<String>) {
let id = manifest
.minecraft
.mod_loaders
.iter()
.find(|loader| loader.primary)
.or_else(|| manifest.minecraft.mod_loaders.first())
.map(|loader| loader.id.as_str());
let Some(id) = id else {
return (ModLoader::Vanilla, None);
};
let (name, version) = id.split_once('-').unwrap_or((id, ""));
let loader = match name.to_ascii_lowercase().as_str() {
"fabric" => ModLoader::Fabric,
"forge" => ModLoader::Forge,
"neoforge" => ModLoader::NeoForge,
"quilt" => ModLoader::Quilt,
_ => ModLoader::Vanilla,
};
(
loader,
(!version.is_empty() && loader != ModLoader::Vanilla).then(|| version.to_owned()),
)
}
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let manifest = parse(path)?;
let (loader, loader_version) = loader(&manifest);
let override_count = count_overrides(path, &manifest.overrides)?;
Ok(ImportSummary {
name: manifest.name,
pack_version: manifest.version,
game_version: manifest.minecraft.version,
loader,
loader_version,
mod_count: manifest.files.iter().filter(|file| file.required).count(),
override_count,
format: PackFormat::CurseForge,
archive_path: path.to_owned(),
})
}
pub async fn execute_import(
summary: &ImportSummary,
manager: &InstanceManager,
) -> Result<InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
progress::set_action(format!("Importing '{name}'..."));
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
let config = manager
.create(
&name,
&summary.game_version,
summary.loader,
summary.loader_version.as_deref(),
)
.await
.map_err(|error| -> Box<dyn std::error::Error + Send + Sync> { Box::new(error) })?;
let minecraft_dir = manager
.instances_dir
.join(&name)
.join(crate::storage::MINECRAFT_DIR_NAME);
let result = async {
let manifest = parse(&summary.archive_path)?;
download_files(&manifest, &minecraft_dir).await?;
extract_overrides(&summary.archive_path, &minecraft_dir, &manifest.overrides)?;
Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
}
.await;
if let Err(error) = result {
super::cleanup_failed_import(manager, &name);
return Err(error);
}
progress::clear();
Ok(config)
}
async fn download_files(
manifest: &Manifest,
minecraft_dir: &Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let api_key = crate::config::SETTINGS
.content
.curseforge_api_key()
.ok_or("CurseForge API key is not configured")?;
let client = crate::net::HttpClient::new();
let ids = manifest
.files
.iter()
.filter(|file| file.required)
.map(|file| file.file_id)
.collect::<Vec<_>>();
let versions = crate::net::curseforge::fetch_file_versions(&client, api_key, &ids).await?;
if versions.len() != ids.len() {
return Err(format!(
"CurseForge returned {} of {} required pack files",
versions.len(),
ids.len()
)
.into());
}
let mods_dir = minecraft_dir.join("mods");
tokio::fs::create_dir_all(&mods_dir).await?;
let total = versions.len();
progress::set_action(format!("Downloading mods... 0/{total}"));
let completed = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let slots = std::sync::Arc::new(tokio::sync::Semaphore::new(10));
let mut tasks = tokio::task::JoinSet::new();
for mut version in versions {
let client = client.clone();
let api_key = api_key.to_owned();
let mods_dir = mods_dir.clone();
let completed = completed.clone();
let slots = slots.clone();
tasks.spawn(async move {
let _permit = slots.acquire_owned().await?;
crate::net::curseforge::ensure_download_url(&client, &api_key, &mut version).await?;
crate::net::modrinth::download_version_file(&client, &version, &mods_dir).await?;
let finished = completed.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {finished}/{total}"));
Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
});
}
while let Some(result) = tasks.join_next().await {
result??;
}
Ok(())
}
fn count_overrides(path: &Path, root: &str) -> Result<usize, String> {
let root = root.trim_matches('/');
if root.is_empty() {
return Ok(0);
}
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
let prefix = format!("{root}/");
Ok(archive
.file_names()
.filter(|name| name.starts_with(&prefix) && !name.ends_with('/'))
.count())
}
fn extract_overrides(
path: &Path,
minecraft_dir: &Path,
root: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
progress::set_action("Extracting overrides...");
let file = std::fs::File::open(path)?;
let mut archive = zip::ZipArchive::new(file)?;
let root = root.trim_matches('/');
if root.is_empty() {
return Ok(());
}
for index in 0..archive.len() {
let mut entry = archive.by_index(index)?;
let enclosed = entry.enclosed_name().ok_or("Unsafe override path")?;
let Ok(relative) = enclosed.strip_prefix(root) else {
continue;
};
if relative.as_os_str().is_empty() {
continue;
}
let destination = minecraft_dir.join(relative);
if entry.is_dir() {
std::fs::create_dir_all(destination)?;
continue;
}
if let Some(parent) = destination.parent() {
std::fs::create_dir_all(parent)?;
}
let mut bytes = Vec::new();
entry.read_to_end(&mut bytes)?;
std::fs::write(destination, bytes)?;
}
Ok(())
}
#[cfg(test)]
#[path = "../tests/import/curseforge.rs"]
mod tests;
+14 -2
View File
@@ -1,6 +1,7 @@
// modpack importing: parses user input, detects pack format from zip contents,
// builds a summary, and delegates the actual import to format-specific modules.
pub mod curseforge;
pub mod mmc;
pub mod mrpack;
@@ -11,6 +12,7 @@ use crate::instance::models::ModLoader;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PackFormat {
CurseForge,
Mrpack,
Mmc,
}
@@ -72,7 +74,7 @@ pub struct ImportSummary {
}
// peeks inside a zip to figure out what format it is.
// checks for modrinth.index.json first, then mmc-pack.json.
// checks provider manifests first, then mmc-pack.json.
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
tracing::debug!("Detecting modpack format for {}", path.display());
let file =
@@ -85,6 +87,11 @@ pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
return Ok(PackFormat::Mrpack);
}
if archive.file_names().any(|name| name == "manifest.json") {
tracing::debug!("Detected CurseForge archive: {}", path.display());
return Ok(PackFormat::CurseForge);
}
// mmc-pack.json can be at root or one directory deep
if archive
.file_names()
@@ -95,7 +102,10 @@ pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
}
tracing::warn!("Unknown modpack archive format: {}", path.display());
Err("Unknown pack format: no modrinth.index.json or mmc-pack.json found".to_string())
Err(
"Unknown pack format: no modrinth.index.json, manifest.json, or mmc-pack.json found"
.to_string(),
)
}
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
@@ -105,6 +115,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
}
let format = detect_format(path)?;
let summary = match format {
PackFormat::CurseForge => curseforge::build_summary(path),
PackFormat::Mrpack => mrpack::build_summary(path),
PackFormat::Mmc => mmc::build_summary(path),
}?;
@@ -165,6 +176,7 @@ pub async fn execute_import(
summary.archive_path.display()
);
match summary.format {
PackFormat::CurseForge => curseforge::execute_import(summary, manager).await,
PackFormat::Mrpack => mrpack::execute_import(summary, manager).await,
PackFormat::Mmc => mmc::execute_import(summary, manager).await,
}
+15
View File
@@ -1,5 +1,20 @@
use super::*;
#[test]
fn curseforge_fingerprint_ignores_whitespace() {
let temp = tempfile::tempdir().unwrap();
let compact = temp.path().join("compact.jar");
let spaced = temp.path().join("spaced.jar");
std::fs::write(&compact, b"abc").unwrap();
std::fs::write(&spaced, b"a b\nc\r\t").unwrap();
let compact = fingerprint(&compact).unwrap();
assert_eq!(compact.hash("curseforge"), Some("1621425345"));
assert_eq!(
compact.hash("curseforge"),
fingerprint(&spaced).unwrap().hash("curseforge")
);
}
#[test]
fn manifest_round_trip_and_lookup_are_exact() {
let temp = tempfile::tempdir().unwrap();
+11
View File
@@ -89,6 +89,17 @@ fn unchanged_saved_index_reuses_fingerprint_and_skips_provider_query() {
assert_eq!(second.manifest.files[0].fingerprint, fingerprint);
}
#[test]
fn newly_configured_provider_retries_an_unmatched_record() {
let resolution = Resolution::Unmatched {
checked_at: chrono::Utc::now().timestamp(),
providers: vec!["modrinth".to_owned()],
};
assert!(provider_was_not_checked(&resolution, "curseforge"));
assert!(!provider_was_not_checked(&resolution, "modrinth"));
}
#[test]
fn directory_packs_are_indexed_without_provider_queries() {
let temp = tempfile::tempdir().unwrap();
+65
View File
@@ -0,0 +1,65 @@
use super::*;
#[test]
fn curseforge_manifest_builds_import_summary() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("pack.zip");
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
zip.start_file("manifest.json", zip::write::SimpleFileOptions::default())
.unwrap();
use std::io::Write;
zip.write_all(
br#"{
"name":"Example",
"version":"1.0",
"minecraft":{
"version":"1.20.1",
"modLoaders":[{"id":"forge-47.2.0","primary":true}]
},
"files":[{"projectID":1,"fileID":2,"required":true}],
"overrides":"overrides"
}"#,
)
.unwrap();
zip.start_file(
"overrides/config/example.txt",
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(b"value").unwrap();
zip.finish().unwrap();
assert_eq!(
super::super::detect_format(&path).unwrap(),
PackFormat::CurseForge
);
let summary = build_summary(&path).unwrap();
assert_eq!(summary.name, "Example");
assert_eq!(summary.loader, ModLoader::Forge);
assert_eq!(summary.loader_version.as_deref(), Some("47.2.0"));
assert_eq!(summary.override_count, 1);
}
#[test]
fn empty_overrides_root_does_not_count_the_manifest() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("pack.zip");
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
zip.start_file("manifest.json", zip::write::SimpleFileOptions::default())
.unwrap();
use std::io::Write;
zip.write_all(
br#"{
"name":"No Overrides",
"version":"1.0",
"minecraft":{"version":"1.20.1"},
"overrides":""
}"#,
)
.unwrap();
zip.finish().unwrap();
assert_eq!(build_summary(&path).unwrap().override_count, 0);
}