diff --git a/README.md b/README.md index 559f8aa..0224584 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,16 @@ A Windows desktop app for building and maintaining Minecraft modpacks. It create projects and installs real mods from Modrinth, with every change reviewed before it is applied. Awake Launcher is not required. -> **What's new in 1.3.1:** see [docs/releases/v1.3.1.md](docs/releases/v1.3.1.md). +> **What's new in 1.3.3:** see [docs/releases/v1.3.3.md](docs/releases/v1.3.3.md). -**Version 1.3.1 · Windows x64 · English, ไทย, 简体中文, 繁體中文 · GPL-3.0-only** +**Version 1.3.3 · Windows x64 · English, ไทย, 简体中文, 繁體中文 · GPL-3.0-only** ## Install -1. Download `Awake-Modpack-Manager-v1.3.1-Windows-x64-Setup.exe` from the +1. Download `Awake-Modpack-Manager-v1.3.3-Windows-x64-Setup.exe` from the [latest release](https://github.com/awakenginexe/Awake-Modpack-Manager/releases/latest). 2. Optional: check it against `SHA256SUMS.txt` from the same release - (`Get-FileHash .\Awake-Modpack-Manager-v1.3.1-Windows-x64-Setup.exe`). + (`Get-FileHash .\Awake-Modpack-Manager-v1.3.3-Windows-x64-Setup.exe`). 3. Run the installer. It installs for your Windows user only (no administrator rights) into `%LOCALAPPDATA%\Awake Modpack Manager`. The installer is **not code-signed** yet, so Windows SmartScreen may warn that it is from an diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 8452f22..9745fe3 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,10 +1,10 @@ -# Development checkpoint: Manager 1.3.1 and Native Core 0.4.2 +# Development checkpoint: Manager 1.3.3 and Native Core 0.4.2 -Unreleased until the owner approves the pull request and tags `v1.3.1`. +Unreleased until the owner approves the pull request and tags `v1.3.3`. ## Where things are -- Manager: branch `release/1.3.1`. `npm ci`, then `npm test`, `npm run typecheck`, `cargo test --manifest-path src-tauri/Cargo.toml --lib`. +- Manager: branch `release/1.3.3`. `npm ci`, then `npm test`, `npm run typecheck`, `cargo test --manifest-path src-tauri/Cargo.toml --lib`. - Native Core: Awake Launcher branch `release/3.2.2`. `.github/workflows/native-core-package.yml` builds it with the recorded toolchain and commits a delivery under `native-core/redistribution//`. `scripts/helper-pin.json` pins that delivery. - Release: pushing a version tag runs `.github/workflows/awake-beta.yml`, which builds, verifies, assembles every asset and publishes the release. `SHA256SUMS.txt` is required by in-app updates. @@ -12,8 +12,9 @@ Unreleased until the owner approves the pull request and tags `v1.3.1`. - `src-tauri/src/providers.rs`: five modpack catalogs, pack downloads, batched project metadata and update lookups. The CurseForge key stays in the host and the helper's environment. - `src-tauri/src/updater.rs`: GitHub release check and checksum-verified installer run. -- `src-tauri/src/desktop.rs`: content folders of a project or managed Launcher instance (list a folder, edit a text file, view an image (1.3.1), add files, Recycle Bin), shell open. Mods are never touched here. +- `src-tauri/src/desktop.rs`: content folders of a project or managed Launcher instance (list a folder, edit a text file, view an image (1.3.1), add files, Recycle Bin), shell open. Mods are not changed here, except `fix_modified` (1.3.3): on the user's request it puts back the exact file the helper recorded for a mod changed outside the Manager (hash-checked download, changed file backed up), or drops that record. - `src-tauri/src/content.rs` (1.3.0): resource pack and shader search, versions and direct, checksum-verified install into `resourcepacks` / `shaderpacks`. +- `src-tauri/src/manual.rs` (1.3.2): restricted CurseForge mods. Names the exact file and its download page, then moves the SHA-1-matching jar from Downloads (or a picked file) into `mods`. The helper lists it as a manual file. - `HelperClient.installPack`: one local operation over fetch, upload, create, prepare and apply. A failure removes the created project. - FTB versions become a generated `.mrpack` manifest; ATLauncher and Technic become a CurseForge-format archive of overrides. - Native Core: `workspaces.delete`, `workspaces.rename`, `imports.prepare` with `packAuthoritative`, `removeInventoryIds` and `allowLoaderUpdate`, a helper-only hash cache, batched provider reads and parallel downloads. diff --git a/docs/releases/v1.3.2.md b/docs/releases/v1.3.2.md new file mode 100644 index 0000000..b251e37 --- /dev/null +++ b/docs/releases/v1.3.2.md @@ -0,0 +1,21 @@ +# Awake Modpack Manager 1.3.2 + +Works with **Awake Launcher 3.2.2**. No Launcher update is needed. + +## Added + +- **Mods that can only be downloaded from the CurseForge website.** Some authors turn off third-party distribution, and checking a plan with one of their mods used to stop at "CurseForge project does not allow third-party distribution". The Review page now lists those mods with an **Open download page** button: CurseForge starts the download after a few seconds, the Manager notices the file in your Downloads folder, moves it into the pack and takes the install out of the draft. Check the plan again for the rest of the draft. +- **Open all** opens every download page at once when there is more than one. +- **Choose downloaded file…** is for a download that went somewhere else, or a Downloads folder that is not in its usual place. + +## How it behaves + +- A file is taken only if its SHA-1 is the one CurseForge lists for that exact version, whatever the browser named it. Anything else in Downloads is left alone, and so is a download still in progress. +- Nothing in `mods` is overwritten. If another file already has the name, the download stays where it is. +- The Downloads folder is only looked at while the Review page is waiting for one of these files. +- A mod added this way shows as a manually added file: the helper does not track it, so the Manager does not offer updates for it. A CurseForge export still recognises it by its fingerprint. +- Only mods in your draft are offered. A restricted mod that is pulled in as a dependency still stops the check; add it to the draft yourself to get its download button. + +## Not verified on a real machine yet + +The demo data and the automated tests cover the Review page, and the host's file matching and move have their own tests. Still unverified: the whole flow in the desktop app against CurseForge and a real Downloads folder. diff --git a/docs/releases/v1.3.3.md b/docs/releases/v1.3.3.md new file mode 100644 index 0000000..4f8208d --- /dev/null +++ b/docs/releases/v1.3.3.md @@ -0,0 +1,18 @@ +# Awake Modpack Manager 1.3.3 + +Works with **Awake Launcher 3.2.2**. No Launcher update is needed. + +## Fixed + +- **Changes kept getting rolled back with "Applied metadata did not verify."** After applying, the helper re-checks every tracked mod, not only the ones that changed. If any mod's jar no longer matched what the helper recorded, for example because a different build of that mod was copied into the pack, every apply was rolled back, even one that only installed an unrelated mod. Review & apply now warns about this before you apply. It lists the mods changed outside the Manager and offers two fixes: + - **Restore originals** downloads the recorded file again and puts it back only if its hashes match the record exactly. Your changed file is copied first to `%LOCALAPPDATA%\AwakeModpackManager\policy-backups\`. If the download doesn't match, nothing changes. + - **Keep my files** leaves your file as it is and stops tracking it. Use this when a pack ships its own build of a mod on purpose. The Manager won't offer updates for that mod any more. + +## Changed + +- **History lists the newest operation first.** +- **History shows which mods each change touched:** installed, removed, updated (old → new version), enabled or disabled. A change that failed or was rolled back is labelled as not applied. Long lists start folded. The list is kept on this computer for the last 200 applies. Changes made before 1.3.3 have no list, because the helper never recorded mod names. + +## Not verified on a real machine yet + +The demo data and the automated tests cover both pages, and the host's restore and keep logic has its own tests. Still unverified: Restore originals in the desktop app against a real instance and Modrinth. diff --git a/package-lock.json b/package-lock.json index 6f5800e..121211b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "awake-modpack-manager", - "version": "1.3.1", + "version": "1.3.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "awake-modpack-manager", - "version": "1.3.1", + "version": "1.3.3", "license": "GPL-3.0-only", "dependencies": { "@lucide/vue": "1.59.0", diff --git a/package.json b/package.json index a970c45..9b32e09 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "awake-modpack-manager", "private": true, - "version": "1.3.1", + "version": "1.3.3", "license": "GPL-3.0-only", "type": "module", "engines": { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 3f27215..8b100df 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -224,7 +224,7 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "awake-modpack-manager" -version = "1.3.1" +version = "1.3.3" dependencies = [ "md-5", "serde", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 5d89067..0bfdab0 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "awake-modpack-manager" -version = "1.3.1" +version = "1.3.3" description = "Awake Modpack Manager desktop host" license = "GPL-3.0-only" repository = "https://github.com/awakenginexe/Awake-Modpack-Manager" diff --git a/src-tauri/src/desktop.rs b/src-tauri/src/desktop.rs index ac0fec4..feffc3a 100644 --- a/src-tauri/src/desktop.rs +++ b/src-tauri/src/desktop.rs @@ -1,12 +1,13 @@ //! Desktop integration: opening folders and links with the shell, and managing the non-mod content //! (config, scripts, resource packs, shaders...) of a project or of a Launcher instance managed here. //! -//! Mods are never touched here: they belong to the native helper's reviewed transactions. Everything +//! Mods are never changed here: they belong to the native helper's reviewed transactions. The one exception, +//! `fix_modified`, only puts back the exact file the helper recorded, after the user asked for it. Everything //! else stays inside one of the content folders below, never follows a link out of it, and is only //! ever removed to the Recycle Bin. use crate::helper::manager_data_dir; -use crate::providers::{err, HostResult}; +use crate::providers::{err, HostError, HostResult}; use serde::Serialize; use serde_json::Value; use std::collections::HashSet; @@ -344,6 +345,77 @@ pub async fn workspace_forget_missing(workspace: String) -> HostResult(path: &Path) -> HostResult { + let mut digest = D::new(); + std::io::copy(&mut fs::File::open(path).or_else(|e| err("io", e.to_string()))?, &mut digest).or_else(|e| err("io", e.to_string()))?; + Ok(crate::providers::hex(&digest.finalize())) +} + +/// Tracked mods whose bytes no longer match the helper's record, which makes the helper roll back every apply. +/// `restore` puts back the recorded file, only once a fresh download hashes exactly as recorded, after copying the +/// changed file to `backup_dir`. Otherwise the record is dropped and the changed file stays as an untracked mod. +/// Returns the file names fixed; a file that matches its record already is left alone. +pub fn fix_modified(game: &Path, backup_dir: &Path, files: &[String], restore: bool, fetch: impl Fn(&str, &Path, u64) -> HostResult<()>) -> HostResult> { + use sha2::{Sha256, Sha512}; + let path = game.parent().unwrap_or(game).join(".awake-integration").join("policies.json"); + let io = |e: std::io::Error| HostError { code: "io", message: e.to_string() }; + let mut doc: Value = serde_json::from_str(&fs::read_to_string(&path).map_err(io)?).or_else(|_| err("invalid", "This project's mod records are damaged."))?; + let before = doc.clone(); + let mods = game.join("mods"); + let wanted: HashSet = files.iter().map(|f| f.to_lowercase().trim_end_matches(".disabled").to_string()).collect(); + let Some(projects) = doc["projects"].as_object_mut() else { return err("invalid", "This project's mod records are damaged.") }; + let keys: Vec = projects.iter().filter(|(_, e)| wanted.contains(&e["fileName"].as_str().unwrap_or_default().to_lowercase())).map(|(k, _)| k.clone()).collect(); + let mut fixed = vec![]; + for key in keys { + let entry = projects[&key].clone(); + let name = entry["fileName"].as_str().unwrap_or_default().to_string(); + let Some(jar) = [name.clone(), format!("{name}.disabled")].into_iter().map(|n| mods.join(n)).find(|p| p.is_file()) else { continue }; + let recorded = entry["sha256"].as_str().unwrap_or_default(); + if file_hash::(&jar)? == recorded { + continue; + } + if restore { + let artifact = &entry["version"]["files"][0]; + let (Some(url), Some(sha512)) = (artifact["url"].as_str(), artifact["sha512"].as_str()) else { + return err("unsupported", format!("{name} cannot be downloaded again here. Keep your file instead.")); + }; + let size = artifact["size"].as_u64().or_else(|| artifact["size"].as_str()?.parse().ok()).unwrap_or(1 << 30); + let tmp = mods.join(format!(".{name}.awake-restore")); + let checked = fetch(url, &tmp, size).and_then(|_| { + if file_hash::(&tmp)? == sha512 && file_hash::(&tmp)? == recorded { Ok(()) } else { err("integrity", format!("The download of {name} did not match its record; nothing was changed.")) } + }); + if let Err(e) = checked { + let _ = fs::remove_file(&tmp); + return Err(e); + } + fs::create_dir_all(backup_dir).map_err(io)?; + fs::copy(&jar, backup_dir.join(jar.file_name().unwrap_or_default())).map_err(io)?; + fs::rename(&tmp, &jar).map_err(io)?; + } else { + projects.remove(&key); + } + fixed.push(name); + } + if !restore && !fixed.is_empty() { + fs::create_dir_all(backup_dir).map_err(io)?; + fs::write(backup_dir.join("policies.json"), before.to_string()).map_err(io)?; + crate::files::write_atomic(&path, doc.to_string().as_bytes(), false).or_else(|m| err("io", m))?; + } + Ok(fixed) +} + +#[tauri::command] +pub async fn workspace_fix_modified(workspace: String, files: Vec, restore: bool) -> HostResult> { + tauri::async_runtime::spawn_blocking(move || { + let game = crate::export::game_folder(&workspace)?; + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let backup = manager_data_dir().or_else(|m| err("io", m))?.join("policy-backups").join(format!("{workspace}-{stamp}")); + fix_modified(&game, &backup, &files, restore, |url, to, limit| crate::providers::download(None, url, &[], to, limit, |_| {})) + }) + .await + .unwrap_or_else(|e| err("internal", e.to_string())) +} + #[cfg(windows)] fn shell_open(target: &str) -> HostResult<()> { use std::os::windows::ffi::OsStrExt; @@ -574,6 +646,45 @@ mod tests { fs::remove_dir_all(&root).unwrap(); } + #[test] + fn fixing_modified_mods_restores_only_a_verified_download_or_forgets_the_record() { + use sha2::{Digest, Sha256, Sha512}; + let root = std::env::temp_dir().join(format!("awake-mm-fixmod-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let (game, policies, backup) = (root.join("minecraft"), root.join(".awake-integration").join("policies.json"), root.join("backups")); + fs::create_dir_all(game.join("mods")).unwrap(); + fs::create_dir_all(policies.parent().unwrap()).unwrap(); + let good = b"original jar"; + let h = |b: &[u8]| (crate::providers::hex(&Sha256::digest(b)), crate::providers::hex(&Sha512::digest(b))); + let (s256, s512) = h(good); + let entry = |file: &str| serde_json::json!({"fileName": file, "sha256": s256, "version": {"files": [{"url": "https://x/a", "sha512": s512, "size": good.len()}]}}); + let doc = serde_json::json!({"projects": {"a": entry("a.jar"), "b": entry("b.jar"), "ok": entry("ok.jar")}}); + fs::write(&policies, doc.to_string()).unwrap(); + fs::write(game.join("mods").join("a.jar"), "changed").unwrap(); + fs::write(game.join("mods").join("b.jar.disabled"), "changed").unwrap(); + fs::write(game.join("mods").join("ok.jar"), good).unwrap(); + let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + + // A download that does not hash as recorded changes nothing and leaves no temp file. + let bad = |_: &str, to: &Path, _: u64| { fs::write(to, "tampered").unwrap(); Ok(()) }; + assert!(fix_modified(&game, &backup, &names(&["a.jar"]), true, bad).is_err()); + assert_eq!(fs::read(game.join("mods").join("a.jar")).unwrap(), b"changed"); + assert_eq!(fs::read_dir(game.join("mods")).unwrap().count(), 3); + + let fetch = |_: &str, to: &Path, _: u64| { fs::write(to, good).unwrap(); Ok(()) }; + assert_eq!(fix_modified(&game, &backup, &names(&["a.jar", "ok.jar"]), true, fetch).unwrap(), ["a.jar"]); + assert_eq!(fs::read(game.join("mods").join("a.jar")).unwrap(), good); + assert_eq!(fs::read(backup.join("a.jar")).unwrap(), b"changed"); + + // Keeping the changed file drops only its record; the file stays. + assert_eq!(fix_modified(&game, &backup, &names(&["b.jar.disabled"]), false, fetch).unwrap(), ["b.jar"]); + let after: Value = serde_json::from_str(&fs::read_to_string(&policies).unwrap()).unwrap(); + assert!(after["projects"].get("b").is_none() && after["projects"].get("a").is_some()); + assert_eq!(fs::read(game.join("mods").join("b.jar.disabled")).unwrap(), b"changed"); + assert_eq!(serde_json::from_str::(&fs::read_to_string(backup.join("policies.json")).unwrap()).unwrap(), doc); + fs::remove_dir_all(&root).unwrap(); + } + #[test] fn workspaces_are_named_by_uuid_only() { assert!(is_uuid("0f1e2d3c-4b5a-4968-8778-695a4b3c2d1e")); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a48f88d..e45f209 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -13,6 +13,7 @@ mod desktop; mod discovery; mod files; mod helper; +mod manual; mod pipe; mod profile_access; mod providers; @@ -114,7 +115,10 @@ pub fn run() { content::content_search, content::content_versions, content::content_install, + manual::manual_sources, + manual::manual_claim, desktop::workspace_forget_missing, + desktop::workspace_fix_modified, desktop::workspace_open, desktop::open_url, desktop::app_info, diff --git a/src-tauri/src/manual.rs b/src-tauri/src/manual.rs new file mode 100644 index 0000000..be4d812 --- /dev/null +++ b/src-tauri/src/manual.rs @@ -0,0 +1,191 @@ +//! Mods whose CurseForge author turned off third-party distribution. The helper may not download +//! them, so the user downloads each one in their browser and the Manager takes exactly that file +//! from the Downloads folder (or one they pick) into the project's `mods` folder. +//! +//! This is the one place the host puts a mod file in place itself: the helper has no way to accept +//! a local file. A file is taken only if its SHA-1 is the one CurseForge lists, and nothing in +//! `mods` is ever overwritten. The helper then lists it as a manually added file. + +use crate::providers::{blocking, cf_get, cf_post, curseforge_key, encode, err, hex, s, HostResult}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha1::{Digest, Sha1}; +use std::fs; +use std::path::{Path, PathBuf}; +use tauri_plugin_dialog::DialogExt; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Item { + project_id: String, + #[serde(default)] + version_id: Option, +} + +/// One file the user has to download by hand. +#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] +#[serde(rename_all = "camelCase")] +pub struct Wanted { + project_id: String, + name: String, + file_name: String, + sha1: String, + size: u64, + /// CurseForge's own download page for this file: it starts the download after a few seconds. + url: String, +} + +/// The newest file for this game version and loader, stable releases first. +pub fn newest_file(project: &Value, minecraft: &str, loader: i64) -> Option { + project["latestFilesIndexes"].as_array()?.iter() + .filter(|f| f["gameVersion"] == minecraft && (loader == 0 || f["modLoader"] == loader)) + .max_by_key(|f| (f["releaseType"] == 1, f["fileId"].as_i64().unwrap_or(0)))?["fileId"].as_i64() +} + +/// A mod file name that can only ever name a jar directly inside `mods`. +fn jar_name(name: &str) -> bool { + !name.is_empty() && name.len() <= 200 && !name.starts_with(['.', ' ']) && name.to_ascii_lowercase().ends_with(".jar") && !name.chars().any(|c| c.is_control() || r#"<>:"/\|?*"#.contains(c)) +} + +pub fn wanted(project: &Value, file: &Value) -> Option { + let page = s(&project["links"], "websiteUrl"); + let sha1 = file["hashes"].as_array()?.iter().find(|h| h["algo"] == 1).map(|h| s(h, "value").to_ascii_lowercase())?; + let (id, file_name) = (file["id"].as_i64()?, s(file, "fileName")); + // Without a checksum there is no telling which download is the right one, so it is not offered. + (page.starts_with("https://www.curseforge.com/") && sha1.len() == 40 && jar_name(file_name)).then(|| Wanted { + project_id: project["id"].as_i64().unwrap_or(0).to_string(), + name: s(project, "name").into(), + file_name: file_name.into(), + sha1, + size: file["fileLength"].as_u64().unwrap_or(0), + url: format!("{}/download/{id}", page.trim_end_matches('/')), + }) +} + +/// Which of these CurseForge projects must be downloaded by hand, and the exact file for each. +#[tauri::command] +pub async fn manual_sources(items: Vec, minecraft_version: String, loader: String) -> HostResult> { + blocking(move || { + if curseforge_key().is_none() { + return Ok(vec![]); + } + let loader = match loader.as_str() { "forge" => 1, "fabric" => 4, "quilt" => 5, "neoforge" => 6, _ => 0 }; + let ids: Vec = items.iter().filter_map(|i| i.project_id.parse().ok()).collect(); + let mut out = vec![]; + for chunk in ids.chunks(500) { + let page = cf_post("/mods", &json!({"modIds": chunk, "filterPcOnly": false}))?; + for project in page["data"].as_array().into_iter().flatten().filter(|p| p["allowModDistribution"] == false) { + let id = project["id"].as_i64().unwrap_or(0); + let chosen = items.iter().find(|i| i.project_id == id.to_string()).and_then(|i| i.version_id.as_ref()?.parse::().ok()); + let Some(file_id) = chosen.or_else(|| newest_file(project, &minecraft_version, loader)) else { continue }; + let file = cf_get(&format!("/mods/{id}/files/{}", encode(&file_id.to_string())))?; + out.extend(wanted(project, &file["data"])); + } + } + Ok(out) + }) + .await +} + +fn sha1_of(path: &Path) -> Option { + let mut hash = Sha1::new(); + std::io::copy(&mut fs::File::open(path).ok()?, &mut hash).ok()?; + Some(hex(&hash.finalize())) +} + +/// Move each wanted file found among `candidates` into `mods`. Returns the project ids now in place. +pub fn claim(mods: &Path, wanted: &[Wanted], candidates: &[PathBuf]) -> HostResult> { + let mut done = vec![]; + for w in wanted.iter().filter(|w| jar_name(&w.file_name) && w.sha1.len() == 40) { + let target = mods.join(&w.file_name); + if fs::symlink_metadata(&target).is_ok() { + // Already there from an earlier pass. A different file of the same name is left alone. + if sha1_of(&target).as_deref() == Some(&w.sha1) { + done.push(w.project_id.clone()); + } + continue; + } + // Size first, so a folder full of other jars is not hashed on every pass. A download still + // in progress has another name or another size, and never the right checksum. + let found = candidates.iter().find(|p| fs::metadata(p).is_ok_and(|m| m.is_file() && m.len() == w.size) && sha1_of(p).as_deref() == Some(&w.sha1)); + let Some(source) = found else { continue }; + fs::create_dir_all(mods).or_else(|e| err("io", e.to_string()))?; + if fs::rename(source, &target).is_err() { + // Downloads on another drive: copy under a temporary name, then remove the download. + let partial = mods.join(format!(".{}.{}.partial", w.file_name, std::process::id())); + if let Err(e) = fs::copy(source, &partial).and_then(|_| fs::rename(&partial, &target)) { + let _ = fs::remove_file(&partial); + return err("io", format!("{}: {e}", w.file_name)); + } + let _ = fs::remove_file(source); + } + done.push(w.project_id.clone()); + } + Ok(done) +} + +fn jars_in(dir: &Path) -> Vec { + fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar"))).collect() +} + +/// Look for the wanted files in Downloads, or (`pick`) in files the user chooses, and move the ones +/// found into the project's `mods` folder. None when the user cancels the file dialog. +#[tauri::command] +pub async fn manual_claim(app: tauri::AppHandle, workspace: String, wanted: Vec, pick: bool) -> HostResult>> { + blocking(move || { + let mods = crate::export::game_folder(&workspace)?.join("mods"); + let candidates = if pick { + let Some(picked) = app.dialog().file().add_filter("Jar", &["jar"]).blocking_pick_files() else { return Ok(None) }; + picked.into_iter().filter_map(|p| p.into_path().ok()).collect() + } else { + // shortcut: assumes Downloads is %USERPROFILE%\Downloads; a moved Downloads folder or another + // browser folder goes through the file dialog. Upgrade to SHGetKnownFolderPath if that bites. + std::env::var_os("USERPROFILE").map_or(vec![], |home| jars_in(&Path::new(&home).join("Downloads"))) + }; + claim(&mods, &wanted, &candidates).map(Some) + }) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_exact_file_is_named_with_its_download_page() { + let project = json!({"id": 7, "name": "LuckPerms GUI", "allowModDistribution": false, "links": {"websiteUrl": "https://www.curseforge.com/minecraft/mc-mods/luckperms-gui"}, + "latestFilesIndexes": [{"gameVersion": "1.20.1", "modLoader": 1, "releaseType": 2, "fileId": 30}, {"gameVersion": "1.20.1", "modLoader": 1, "releaseType": 1, "fileId": 20}, {"gameVersion": "1.20.1", "modLoader": 4, "releaseType": 1, "fileId": 40}, {"gameVersion": "1.21", "modLoader": 1, "releaseType": 1, "fileId": 50}]}); + assert_eq!(newest_file(&project, "1.20.1", 1), Some(20), "a release beats a newer beta"); + assert_eq!(newest_file(&project, "1.19", 1), None); + let file = json!({"id": 20, "fileName": "lpgui-1.0.jar", "fileLength": 3, "hashes": [{"algo": 2, "value": "x"}, {"algo": 1, "value": "A9993E364706816ABA3E25717850C26C9CD0D89D"}]}); + let w = wanted(&project, &file).unwrap(); + assert_eq!(w, Wanted { project_id: "7".into(), name: "LuckPerms GUI".into(), file_name: "lpgui-1.0.jar".into(), sha1: "a9993e364706816aba3e25717850c26c9cd0d89d".into(), size: 3, url: "https://www.curseforge.com/minecraft/mc-mods/luckperms-gui/download/20".into() }); + assert_eq!(wanted(&project, &json!({"id": 20, "fileName": "../evil.jar", "hashes": file["hashes"]})), None); + assert_eq!(wanted(&project, &json!({"id": 20, "fileName": "a.jar", "hashes": []})), None, "no checksum, no offer"); + } + + #[test] + fn only_the_file_with_the_listed_checksum_is_moved_and_nothing_is_overwritten() { + let root = std::env::temp_dir().join(format!("awake-mm-manual-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let (downloads, mods) = (root.join("dl"), root.join("mods")); + fs::create_dir_all(&downloads).unwrap(); + // sha1("abc"); the browser renamed the download, and a same-size impostor sits next to it. + let w = |id: &str, name: &str| Wanted { project_id: id.into(), name: id.into(), file_name: name.into(), sha1: "a9993e364706816aba3e25717850c26c9cd0d89d".into(), size: 3, url: String::new() }; + fs::write(downloads.join("mod (1).jar"), "abc").unwrap(); + fs::write(downloads.join("other.jar"), "xyz").unwrap(); + fs::write(downloads.join("notes.txt"), "abc").unwrap(); + assert_eq!(jars_in(&downloads).len(), 2); + assert!(claim(&mods, &[w("1", "mod.jar")], &[downloads.join("other.jar")]).unwrap().is_empty()); + assert_eq!(claim(&mods, &[w("1", "mod.jar"), w("2", "..\\up.jar")], &jars_in(&downloads)).unwrap(), ["1"]); + assert_eq!(fs::read_to_string(mods.join("mod.jar")).unwrap(), "abc"); + assert!(!downloads.join("mod (1).jar").exists() && downloads.join("other.jar").exists()); + assert_eq!(claim(&mods, &[w("1", "mod.jar")], &[]).unwrap(), ["1"], "already in place"); + // A different file already has the name: it stays, and the download is not taken. + fs::write(mods.join("taken.jar"), "old").unwrap(); + fs::write(downloads.join("taken.jar"), "abc").unwrap(); + assert!(claim(&mods, &[w("3", "taken.jar")], &jars_in(&downloads)).unwrap().is_empty()); + assert_eq!(fs::read_to_string(mods.join("taken.jar")).unwrap(), "old"); + fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 0a48499..0655543 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "Awake Modpack Manager", - "version": "1.3.1", + "version": "1.3.3", "identifier": "io.github.awakenginexe.AwakeModpackManager", "build": { "frontendDist": "../dist", diff --git a/src/backend/ManagerBackend.ts b/src/backend/ManagerBackend.ts index a2544f4..fbaf898 100644 --- a/src/backend/ManagerBackend.ts +++ b/src/backend/ManagerBackend.ts @@ -1,7 +1,7 @@ import type { Accepted, ImportInspection, LoaderKind, WorkspaceSnapshot, ProjectVersion, ProviderId, VersionCatalog, ApplyRequest, ContentArea, ContentEntry, CreateInstanceRequest, Draft, ExportFormat, ExportReport, ExportRequest, Handshake, InstallPackRequest, PackSearchPage, PackSearchQuery, PackVersion, InstanceSummary, InstanceWarning, Installation, ModInventory, - OperationStatus, RecoveryStatus, ResolvedPlan, SearchPage, SearchQuery, DependencyResolution, VersionRef, WorkspaceExportItem, ExportFileMatch, ExportRestriction, InstanceZipResult, + OperationStatus, RecoveryStatus, ResolvedPlan, SearchPage, SearchQuery, DependencyResolution, VersionRef, WorkspaceExportItem, ExportFileMatch, ExportRestriction, InstanceZipResult, ManualDownload, AddedContent, ContentImage, ContentKind, ContentSearchPage, ContentSearchQuery, ContentTextFile, ContentVersion, InstalledContent, ProviderInfo } from './contract'; import type { LauncherProfile } from './launcher/transport'; import type { ProjectDetail } from './host'; @@ -120,6 +120,13 @@ export interface ManagerBackend { exportMatches?(instanceId: string, target: ProviderId, fileNames: string[]): Promise; /** Which of these CurseForge projects players must download by hand. */ exportRestricted?(instanceId: string, projectIds: string[]): Promise; + /** Which of these CurseForge installs the helper may not download, with the exact file to get by hand. */ + manualDownloads?(instanceId: string, items: { projectId: string; versionId?: string }[]): Promise; + /** + * Move those files, once downloaded, into the instance's mods folder: from Downloads, or (`pick`) from + * files the user chooses. Resolves with the project ids now in place; null when the user cancels. + */ + claimManualDownloads?(instanceId: string, wanted: ManualDownload[], pick: boolean): Promise; /** Describe exactly these mods for a provider format, asking the provider only for what that format needs. */ prepareExport?(instanceId: string, format: 'mrpack' | 'curseforge', entries: WorkspaceExportItem[], onProgress?: (done: number, total: number) => void): Promise; /** Save the whole pack, mod files included, where the user chooses. Null when they cancel. */ @@ -135,6 +142,8 @@ export interface ManagerBackend { openFolder?(instanceId: string, area?: ContentArea, folder?: string): Promise; /** Forget tracked mods whose file was deleted outside the Manager; the helper refuses every plan until then. Resolves with their file names. */ forgetMissingMods?(instanceId: string): Promise; + /** Mods changed outside the Manager make the helper roll back every apply: put back their recorded file, or stop tracking them. Resolves with their file names. */ + fixModifiedMods?(instanceId: string, fileNames: string[], restore: boolean): Promise; /** Helper: connect a Launcher instance in place, keeping its files where they are. Resolves once finished. */ adoptInstance?(path: string): Promise; diff --git a/src/backend/composite.ts b/src/backend/composite.ts index c992ada..ba07d3e 100644 --- a/src/backend/composite.ts +++ b/src/backend/composite.ts @@ -231,8 +231,11 @@ export function createCompositeBackend(helper: ManagerBackend, launcher: Manager }, discardImport: (token) => (helper.discardImport ? helper.discardImport(token) : noHelper()), forgetMissingMods: (id) => { const b = byInstance(id).backend; return b.forgetMissingMods ? b.forgetMissingMods(id) : noHelper(); }, + fixModifiedMods: (id, names, restore) => { const b = byInstance(id).backend; return b.fixModifiedMods ? b.fixModifiedMods(id, names, restore) : noHelper(); }, exportMatches: (id, target, names) => { const b = byInstance(id).backend; return b.exportMatches ? b.exportMatches(id, target, names) : noHelper(); }, exportRestricted: (id, ids) => { const b = byInstance(id).backend; return b.exportRestricted ? b.exportRestricted(id, ids) : noHelper(); }, + manualDownloads: async (id, items) => byInstance(id).backend.manualDownloads?.(id, items) ?? [], + claimManualDownloads: async (id, wanted, pick) => byInstance(id).backend.claimManualDownloads?.(id, wanted, pick) ?? [], prepareExport: (id, format, entries, onProgress) => { const b = byInstance(id).backend; return b.prepareExport ? b.prepareExport(id, format, entries, onProgress) : noHelper(); }, exportInstanceZip: (id, meta, onProgress) => { const b = byInstance(id).backend; return b.exportInstanceZip ? b.exportInstanceZip(id, meta, onProgress) : noHelper(); }, snapshotWorkspace: (id, onProgress) => { const b = byInstance(id).backend; return b.snapshotWorkspace ? b.snapshotWorkspace(id, onProgress) : noHelper(); }, diff --git a/src/backend/contract.ts b/src/backend/contract.ts index 71db2e4..020e2b8 100644 --- a/src/backend/contract.ts +++ b/src/backend/contract.ts @@ -473,6 +473,8 @@ export type WorkspaceExportItem = | { kind: 'replaced'; fileName: string; provider: ProviderId; projectId: string; versionId: string; name: string }; /** A CurseForge mod whose author turned off third-party distribution. */ export interface ExportRestriction { projectId: string; name: string; pageUrl?: string } +/** One restricted CurseForge file the user downloads in their browser; `url` is its download page. */ +export interface ManualDownload { projectId: string; name: string; fileName: string; sha1: string; size: number; url: string } export interface InstanceZipResult { path: string; files: number; bytes: number } export interface RecoveryStatus { diff --git a/src/backend/helper/HelperClient.ts b/src/backend/helper/HelperClient.ts index 4876d91..2917c82 100644 --- a/src/backend/helper/HelperClient.ts +++ b/src/backend/helper/HelperClient.ts @@ -854,6 +854,15 @@ export function createHelperClient(options: HelperClientOptions): ManagerBackend const metas = await options.host.projectMeta(projectIds.map((projectId) => ({ provider: 'curseforge' as const, projectId }))); return metas.filter((m) => m.restricted).map((m) => ({ projectId: m.projectId, name: m.name, pageUrl: m.pageUrl })); }, + async manualDownloads(instanceId, items) { + if (!options.host) return []; + const w = workspaceOf(instanceId); + return options.host.manualSources(items, w.minecraftVersion, w.loader.id); + }, + async claimManualDownloads(instanceId, wanted, pick) { + if (!options.host) return []; + return options.host.manualClaim(workspaceOf(instanceId).workspaceId, wanted, pick); + }, async prepareExport(instanceId, format, entries, onProgress) { if (!has('mods.list')) return notYet('export'); const w = workspaceOf(instanceId); @@ -1029,6 +1038,10 @@ export function createHelperClient(options: HelperClientOptions): ManagerBackend if (!options.host) return notYet('cleaning up'); return options.host.workspaceForgetMissing(workspaceOf(instanceId).workspaceId); }, + async fixModifiedMods(instanceId, fileNames, restore) { + if (!options.host) return notYet('fixing changed mods'); + return options.host.workspaceFixModified(workspaceOf(instanceId).workspaceId, fileNames, restore); + }, async openFolder(instanceId, area, folder) { await options.host?.workspaceOpen(workspaceOf(instanceId).workspaceId, area, folder); }, diff --git a/src/backend/host.ts b/src/backend/host.ts index b2a9cd4..2eb85b8 100644 --- a/src/backend/host.ts +++ b/src/backend/host.ts @@ -1,4 +1,4 @@ -import { BackendError, type AddedContent, type ContentEntry, type ContentImage, type ContentKind, type ContentSearchPage, type ContentSearchQuery, type ContentTextFile, type ContentVersion, type InstalledContent, type ExportFileMatch, type InstanceZipResult, type PackHit, type PackProviderId, type PackProviderInfo, type PackVersion, type ProviderId } from './contract'; +import { BackendError, type AddedContent, type ContentEntry, type ContentImage, type ContentKind, type ContentSearchPage, type ContentSearchQuery, type ContentTextFile, type ContentVersion, type InstalledContent, type ExportFileMatch, type InstanceZipResult, type ManualDownload, type PackHit, type PackProviderId, type PackProviderInfo, type PackVersion, type ProviderId } from './contract'; /** A pack the desktop host downloaded and verified, ready to upload to the helper. */ export interface FetchedPack { token: string; format: 'mrpack' | 'curseforge'; size: number; sha256: string; notes: string[] } @@ -34,7 +34,11 @@ export interface HostApi { contentInstall(workspace: string, kind: ContentKind, provider: ProviderId, projectId: string, versionId: string, onProgress?: (done: number, total: number) => void): Promise; /** Drop the helper's records of mods whose file is gone. Resolves with the file names forgotten. */ workspaceForgetMissing(workspace: string): Promise; + /** Put back the recorded file of mods changed outside the Manager (`restore`), or stop tracking them. Resolves with the file names fixed. */ + workspaceFixModified(workspace: string, files: string[], restore: boolean): Promise; exportMatch(workspace: string, target: ProviderId, fileNames: string[]): Promise; + manualSources(items: { projectId: string; versionId?: string }[], minecraftVersion: string, loader: string): Promise; + manualClaim(workspace: string, wanted: ManualDownload[], pick: boolean): Promise; exportInstance(workspace: string, meta: { fileName: string; name: string; version: string; minecraft: string; loader: string }, onProgress?: (written: number, total: number) => void): Promise; } @@ -84,8 +88,11 @@ export function createHostApi(): HostApi { }, workspaceRecycle: (workspace, area, paths) => hostInvoke('workspace_recycle', { workspace, area, paths }), workspaceForgetMissing: (workspace) => hostInvoke('workspace_forget_missing', { workspace }), + workspaceFixModified: (workspace, files, restore) => hostInvoke('workspace_fix_modified', { workspace, files, restore }), workspaceOpen: (workspace, area, folder) => hostInvoke('workspace_open', { workspace, area: area ?? null, folder: folder || null }), exportMatch: (workspace, target, fileNames) => hostInvoke('export_match', { workspace, target, fileNames }), + manualSources: (items, minecraftVersion, loader) => hostInvoke('manual_sources', { items, minecraftVersion, loader }), + manualClaim: (workspace, wanted, pick) => hostInvoke('manual_claim', { workspace, wanted, pick }), async exportInstance(workspace, meta, onProgress) { const { listen } = await import('@tauri-apps/api/event'); const stop = await listen<{ done: number; total: number }>('export-progress', (e) => onProgress?.(e.payload.done, e.payload.total)); diff --git a/src/backend/mock/MockBackend.ts b/src/backend/mock/MockBackend.ts index 0d16343..0996f38 100644 --- a/src/backend/mock/MockBackend.ts +++ b/src/backend/mock/MockBackend.ts @@ -1,4 +1,4 @@ -import type { AddedContent, ContentHit, ContentImage, ContentKind, ContentSearchPage, ContentSearchQuery, ContentTextFile, ContentVersion, ExportFileMatch, ExportRestriction, InstalledContent, InstanceZipResult, ProviderId, WorkspaceExportItem, WorkspaceSnapshot } from '../contract'; +import type { AddedContent, ContentHit, ContentImage, ContentKind, ContentSearchPage, ContentSearchQuery, ContentTextFile, ContentVersion, ExportFileMatch, ExportRestriction, InstalledContent, InstanceZipResult, ManualDownload, ProviderId, WorkspaceExportItem, WorkspaceSnapshot } from '../contract'; import { ALL_CAPABILITIES, BackendError, TERMINAL_STATES, type Accepted, type ApplyRequest, type Capability, type ContentArea, type ContentEntry, type CreateInstanceRequest, @@ -234,12 +234,26 @@ export class MockBackend implements ManagerBackend { const inst = this.instance(draft.instanceId); if (inst.revision !== draft.baseRevision) throw new BackendError('stale-revision', 'The instance changed since this draft was made.'); if (!inst.manageable) throw new BackendError('instance-busy', inst.blockedReason ?? 'Instance cannot be managed now.'); + if (this.restrictedIn(draft.changes).length) throw new BackendError('provider-restricted', 'CurseForge project does not allow third-party distribution.', 'PROVIDER_RESTRICTED'); const plan = this.resolve(draft); this.plans.set(plan.planId, { plan, draft }); return plan; }); } + /** Demo: every 13th CurseForge project has third-party distribution turned off. */ + private restrictedIn(changes: { kind: string; provider?: string; projectId?: string }[]) { + return changes.flatMap((c) => (c.kind === 'install' && c.provider === 'curseforge' && Number(c.projectId!.split('-')[1]) % 13 === 0 ? [c.projectId!] : [])); + } + async manualDownloads(_instanceId: string, items: { projectId: string }[]): Promise { + return this.restrictedIn(items.map((i) => ({ kind: 'install', provider: 'curseforge', projectId: i.projectId }))) + .map((id) => ({ projectId: id, name: `Restricted demo mod ${id}`, fileName: `${id}.jar`, sha1: 'a'.repeat(40), size: 1000, url: 'https://www.curseforge.com/minecraft/mc-mods' })); + } + /** Demo: nothing ever arrives in Downloads; choosing a file "finds" every download. */ + async claimManualDownloads(_instanceId: string, wanted: ManualDownload[], pick: boolean): Promise { + return pick ? wanted.map((w) => w.projectId) : []; + } + preparePlan(planId: string): Promise { return this.call(() => { const stored = this.plans.get(planId); @@ -556,6 +570,14 @@ export class MockBackend implements ManagerBackend { }); } async openFolder(): Promise { /* nothing to open for demo data */ } + fixModifiedMods(instanceId: string, fileNames: string[], restore: boolean): Promise { + return this.call(() => { + const mods = (this.inventories.get(instanceId) ?? []).filter((m) => m.locallyModified && fileNames.includes(m.fileName)); + // Restoring puts the recorded file back; keeping it leaves the file as a manual, untracked mod. + for (const m of mods) Object.assign(m, restore ? { locallyModified: false } : { locallyModified: false, source: 'manual', projectId: undefined }); + return mods.map((m) => m.fileName); + }); + } /* ----- resource packs & shaders ----- */ diff --git a/src/components/ManualDownloads.vue b/src/components/ManualDownloads.vue new file mode 100644 index 0000000..921981f --- /dev/null +++ b/src/components/ManualDownloads.vue @@ -0,0 +1,98 @@ + + + + + diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 29279dd..ad9dbda 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -341,6 +341,15 @@ export const en = { cleanMissing: "Clean up missing mods", cleanMissingHint: "A mod this pack tracks was deleted outside the Manager. Clean up to forget it and check again; no file is touched.", cleanMissingDone: "Forgot missing mods: {names}", + modifiedModsTitle: "Mods changed outside the Manager: {count}", + modifiedModsHint: "{names}. Changes can't be applied until this is fixed. Restore the original file, or keep yours and stop tracking it.", + modifiedModsRestore: "Restore originals", + modifiedModsKeep: "Keep my files", + modifiedModsKeepHint: "Your files stay as they are, but the Manager stops tracking and updating them.", + modifiedModsRestored: "Restored: {names}. Your changed files were backed up.", + modifiedModsKept: "No longer tracked: {names}", + historyChanged: "Changed {count} mods", + historyTried: "Tried to change {count} mods (not applied)", refreshModsHint: "Read the mods folder again, to pick up files added or removed outside the Manager.", discardDraft: 'Discard draft', discardConfirm: 'Discard all {count} changes?', @@ -693,6 +702,14 @@ export const en = { exportOpenPage: "Open page", exportOpenNext: "Open next {count}", skipRestricted: "its author does not allow third-party distribution", + manualTitle: "Download from CurseForge yourself ({count})", + manualHint: "The author only allows downloads from the CurseForge website. Open the page and the download starts after a few seconds. The Manager watches your Downloads folder and adds the file to the pack by itself.", + manualOpen: "Open download page", + manualOpenAll: "Open all", + manualPick: "Choose downloaded file…", + manualWaiting: "Waiting for {file}", + manualAdded: "Added to the pack: {names}", + manualNoMatch: "None of the chosen files is one of these downloads.", shareWorking: "Connecting {name} so you can manage it here. Large packs can take a minute.", shareLoading: "Loading {name}'s mods…", shareReleasing: "Giving {name} back to Awake Launcher…", diff --git a/src/i18n/th.ts b/src/i18n/th.ts index 49703a4..871417a 100644 --- a/src/i18n/th.ts +++ b/src/i18n/th.ts @@ -343,6 +343,15 @@ export const th: Catalog = { cleanMissing: "ล้างม็อดที่หายไป", cleanMissingHint: "ม็อดที่แพ็กนี้ติดตามอยู่ถูกลบจากนอก Manager กดล้างเพื่อเลิกติดตามแล้วตรวจสอบอีกครั้ง โดยไม่แตะไฟล์ใด ๆ", cleanMissingDone: "เลิกติดตามม็อดที่หายไปแล้ว: {names}", + modifiedModsTitle: "ม็อดที่ถูกแก้ไขนอก Manager: {count}", + modifiedModsHint: "{names} จะใช้การเปลี่ยนแปลงไม่ได้จนกว่าจะแก้ไข กู้คืนไฟล์ต้นฉบับ หรือเก็บไฟล์ของคุณไว้และเลิกติดตาม", + modifiedModsRestore: "กู้คืนไฟล์ต้นฉบับ", + modifiedModsKeep: "เก็บไฟล์ของฉันไว้", + modifiedModsKeepHint: "ไฟล์ของคุณจะอยู่เหมือนเดิม แต่ Manager จะเลิกติดตามและอัปเดตไฟล์นั้น", + modifiedModsRestored: "กู้คืนแล้ว: {names} สำรองไฟล์ที่ถูกแก้ไขไว้แล้ว", + modifiedModsKept: "เลิกติดตามแล้ว: {names}", + historyChanged: "เปลี่ยน {count} ม็อด", + historyTried: "พยายามเปลี่ยน {count} ม็อด (ไม่ได้ใช้)", refreshModsHint: "อ่านโฟลเดอร์ม็อดใหม่ เพื่อดูไฟล์ที่เพิ่มหรือลบจากนอก Manager", discardDraft: 'ทิ้งฉบับร่าง', discardConfirm: 'ทิ้งการเปลี่ยนแปลงทั้ง {count} รายการหรือไม่?', @@ -695,6 +704,14 @@ export const th: Catalog = { exportOpenPage: "เปิดหน้าม็อด", exportOpenNext: "เปิดอีก {count} หน้า", skipRestricted: "ผู้สร้างไม่อนุญาตให้แจกจ่ายผ่านบุคคลที่สาม", + manualTitle: "ต้องดาวน์โหลดจาก CurseForge เอง ({count})", + manualHint: "ผู้สร้างอนุญาตให้ดาวน์โหลดจากเว็บไซต์ CurseForge เท่านั้น เปิดหน้าเว็บแล้วการดาวน์โหลดจะเริ่มในไม่กี่วินาที Manager จะคอยดูโฟลเดอร์ Downloads และเพิ่มไฟล์เข้าแพ็กให้เอง", + manualOpen: "เปิดหน้าดาวน์โหลด", + manualOpenAll: "เปิดทั้งหมด", + manualPick: "เลือกไฟล์ที่ดาวน์โหลดแล้ว…", + manualWaiting: "กำลังรอ {file}", + manualAdded: "เพิ่มเข้าแพ็กแล้ว: {names}", + manualNoMatch: "ไฟล์ที่เลือกไม่ตรงกับไฟล์ที่ต้องดาวน์โหลด", shareWorking: "กำลังเชื่อมต่อ {name} เพื่อจัดการจากที่นี่ แพ็กขนาดใหญ่อาจใช้เวลาสักครู่", shareLoading: "กำลังโหลดม็อดของ {name}…", shareReleasing: "กำลังคืนสิทธิ์ {name} ให้ Awake Launcher…", diff --git a/src/i18n/zh-CN.ts b/src/i18n/zh-CN.ts index acd1c99..a79c063 100644 --- a/src/i18n/zh-CN.ts +++ b/src/i18n/zh-CN.ts @@ -343,6 +343,15 @@ export const zhCN: Catalog = { cleanMissing: "清理缺失的模组", cleanMissingHint: "此整合包跟踪的某个模组已在 Manager 之外被删除。清理后会忘记它并重新检查,不会改动任何文件。", cleanMissingDone: "已忘记缺失的模组:{names}", + modifiedModsTitle: "在 Manager 之外被修改的模组:{count}", + modifiedModsHint: "{names}。修复之前无法应用更改。请恢复原始文件,或保留你的文件并停止跟踪。", + modifiedModsRestore: "恢复原始文件", + modifiedModsKeep: "保留我的文件", + modifiedModsKeepHint: "你的文件保持不变,但 Manager 将停止跟踪和更新它们。", + modifiedModsRestored: "已恢复:{names}。已备份你修改过的文件。", + modifiedModsKept: "已停止跟踪:{names}", + historyChanged: "更改了 {count} 个模组", + historyTried: "尝试更改 {count} 个模组(未应用)", refreshModsHint: "重新读取模组文件夹,以发现在 Manager 之外添加或删除的文件。", discardDraft: '丢弃草稿', discardConfirm: '确定丢弃全部 {count} 项更改吗?', @@ -695,6 +704,14 @@ export const zhCN: Catalog = { exportOpenPage: "打开页面", exportOpenNext: "打开接下来 {count} 个", skipRestricted: "作者不允许第三方分发", + manualTitle: "需要自行从 CurseForge 下载({count})", + manualHint: "作者只允许从 CurseForge 网站下载。打开页面后,下载会在几秒后开始。Manager 会留意你的“下载”文件夹,并自动把文件加入整合包。", + manualOpen: "打开下载页面", + manualOpenAll: "全部打开", + manualPick: "选择已下载的文件…", + manualWaiting: "正在等待 {file}", + manualAdded: "已加入整合包:{names}", + manualNoMatch: "所选文件都不是这些下载项。", shareWorking: "正在连接 {name},以便在此管理。大型整合包可能需要一分钟左右。", shareLoading: "正在加载 {name} 的模组…", shareReleasing: "正在将 {name} 交还给 Awake Launcher…", diff --git a/src/i18n/zh-TW.ts b/src/i18n/zh-TW.ts index ae5e9e3..c59e570 100644 --- a/src/i18n/zh-TW.ts +++ b/src/i18n/zh-TW.ts @@ -343,6 +343,15 @@ export const zhTW: Catalog = { cleanMissing: "清理遺失的模組", cleanMissingHint: "此模組包追蹤的某個模組已在 Manager 之外被刪除。清理後會忘記它並重新檢查,不會更動任何檔案。", cleanMissingDone: "已忘記遺失的模組:{names}", + modifiedModsTitle: "在 Manager 之外被修改的模組:{count}", + modifiedModsHint: "{names}。修正之前無法套用變更。請還原原始檔案,或保留你的檔案並停止追蹤。", + modifiedModsRestore: "還原原始檔案", + modifiedModsKeep: "保留我的檔案", + modifiedModsKeepHint: "你的檔案保持不變,但 Manager 將停止追蹤和更新它們。", + modifiedModsRestored: "已還原:{names}。已備份你修改過的檔案。", + modifiedModsKept: "已停止追蹤:{names}", + historyChanged: "變更了 {count} 個模組", + historyTried: "嘗試變更 {count} 個模組(未套用)", refreshModsHint: "重新讀取模組資料夾,以找出在 Manager 之外新增或刪除的檔案。", discardDraft: '捨棄草稿', discardConfirm: '確定要捨棄全部 {count} 項變更嗎?', @@ -695,6 +704,14 @@ export const zhTW: Catalog = { exportOpenPage: "開啟頁面", exportOpenNext: "開啟接下來 {count} 個", skipRestricted: "作者不允許第三方散布", + manualTitle: "需要自行從 CurseForge 下載({count})", + manualHint: "作者只允許從 CurseForge 網站下載。開啟頁面後,下載會在幾秒後開始。Manager 會留意你的「下載」資料夾,並自動把檔案加入模組包。", + manualOpen: "開啟下載頁面", + manualOpenAll: "全部開啟", + manualPick: "選擇已下載的檔案…", + manualWaiting: "正在等待 {file}", + manualAdded: "已加入模組包:{names}", + manualNoMatch: "所選檔案都不是這些下載項目。", shareWorking: "正在連接 {name},以便在此管理。大型整合包可能需要一分鐘左右。", shareLoading: "正在載入 {name} 的模組…", shareReleasing: "正在將 {name} 交還給 Awake Launcher…", diff --git a/src/state/session.ts b/src/state/session.ts index 91599d5..ad6e26d 100644 --- a/src/state/session.ts +++ b/src/state/session.ts @@ -1,8 +1,11 @@ import { computed, inject, reactive, ref, shallowRef, watch, type InjectionKey } from 'vue'; import { BackendError, isLauncherWait, type Capability, type CreateInstanceRequest, type DependencyResolution, type Draft, type ExportRequest, type Handshake, - type InstallPackRequest, type InstanceSummary, type InstanceWarning, type Installation, type ModInventory, type OperationStatus, type ResolvedPlan, type VersionRef, + type InstallPackRequest, type InstanceSummary, type InstanceWarning, type Installation, type ModInventory, type OperationStatus, type PlanAction, type ResolvedPlan, type VersionRef, } from '../backend/contract'; + +/** One mod an applied plan changed, kept for History. Versions are display names. */ +export interface OpChange { action: PlanAction; name: string; from?: string; to?: string } import type { ConnectionState, ManagerBackend } from '../backend/ManagerBackend'; import { isComposite } from '../backend/composite'; import { isStale, newDraft, rebase } from '../domain/draft'; @@ -54,6 +57,16 @@ export function createSession(backend: ManagerBackend, { pollMs = 1500 } = {}) { const drafts = ref>(load('drafts', {})); const pins = ref>(load('pins', {})); const exportIncludes = ref>(load('exportIncludes', {})); + /** What each applied plan changed, by operation id: the helper's history has no mod names. */ + const opChanges = ref>(load('opChanges', {})); + function recordChanges(ids: string[], plan: ResolvedPlan) { + const items = plan.items.filter((i) => i.action !== 'keep').map((i): OpChange => ({ action: i.action, name: i.name, ...(i.from ? { from: i.from.name } : {}), ...(i.to ? { to: i.to.name } : {}) })); + const next = { ...opChanges.value }; + for (const id of ids) next[id] = items; + // shortcut: keeps the newest 200 applies so local storage stays small; move to a file if people want a longer log. + opChanges.value = Object.fromEntries(Object.entries(next).slice(-200)); + save('opChanges', opChanges.value); + } const review = reactive({ phase: 'idle' as ReviewPhase, plan: null as ResolvedPlan | null, @@ -324,6 +337,18 @@ export function createSession(backend: ManagerBackend, { pollMs = 1500 } = {}) { } } + /** Tracked mods whose file was changed outside the Manager: the helper rolls back every apply while one is listed. */ + const modifiedMods = computed(() => (backend.fixModifiedMods ? (inventory.value?.mods ?? []).filter((m) => m.locallyModified) : [])); + /** Restore their recorded files (or stop tracking them), reload the mods, then check the draft again if one was checked. */ + async function fixModifiedMods(restore: boolean) { + const id = state.instanceId; + if (!id || !backend.fixModifiedMods || !modifiedMods.value.length) return []; + const fixed = await backend.fixModifiedMods(id, modifiedMods.value.map((m) => m.fileName), restore); + await loadInventory(); + if (review.plan || review.phase === 'failed') await validate(); + return fixed; + } + /** The policy a mod will have after the draft: its pending policy change, else what the helper reports. */ function policyOf(key: string) { const c = draft.value?.changes.find((x) => x.kind === 'policy' && x.modKey === key); @@ -410,9 +435,11 @@ export function createSession(backend: ManagerBackend, { pollMs = 1500 } = {}) { } pending = { key: crypto.randomUUID(), instanceId: prepared.instanceId, planId: prepared.planId, planHash: prepared.planHash, baseRevision: prepared.baseRevision }; save('pendingApply', pending); + recordChanges([prepared.planId], prepared); review.phase = 'applying'; try { const { operationId } = await backend.applyPlan(applyRequest(pending)); + if (operationId !== prepared.planId) recordChanges([operationId], prepared); await track(operationId); } catch (e) { const err = asError(e); @@ -641,7 +668,7 @@ export function createSession(backend: ManagerBackend, { pollMs = 1500 } = {}) { can, instance, draft, pinned, planOutdated, policies, policyOf, packHandshake, connect, refreshInstances, selectInstance, loadInventory, checkUpdates, deleteInstance, renameInstance, preparePackUpdate, setDraft, discardDraft, rebaseDraft, setPinned, setExcluded, prepareImport, - validate, apply, acceptChangedPlan, resetReview, missingTracked, forgetMissingMods, + validate, apply, acceptChangedPlan, resetReview, missingTracked, forgetMissingMods, modifiedMods, fixModifiedMods, opChanges, refreshOperations, cancelOperation, runRecovery, createInstance, installPack, startExport, launch, startLauncher, makeProfilePrivate, }; } diff --git a/src/views/HistoryView.vue b/src/views/HistoryView.vue index b07055f..0d0dd50 100644 --- a/src/views/HistoryView.vue +++ b/src/views/HistoryView.vue @@ -1,11 +1,14 @@