From 015855f3d894ab79d5c1743a01d359f1d25bb2f2 Mon Sep 17 00:00:00 2001 From: smildka48 Date: Tue, 10 Nov 2026 23:07:20 +0700 Subject: [PATCH] release: Awake Modpack Manager 1.3.0 Files works for Launcher instances managed here, and is no longer read-only. It lists one folder at a time, edits text files in place, adds picked files without replacing any, and still removes only to the Recycle Bin. A save is refused when the file changed on disk while it was open, and a link below a content folder is never followed. Browse has three shelves in the sidebar: Mods, Resource packs and Shaders. The two new ones search Modrinth and CurseForge from the desktop host and install one checksum-verified zip straight into resourcepacks or shaderpacks. Mods still change only through a reviewed plan. No helper or Launcher change: this release works with Awake Launcher 3.2.2 and Native Core 0.4.2. Co-authored-by: awakenginexe <267649137+awakenginexe@users.noreply.github.com> Co-Authored-By: Claude --- README.md | 8 +- docs/HANDOFF.md | 9 +- docs/releases/v1.3.0.md | 33 ++ package-lock.json | 4 +- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/src/content.rs | 501 +++++++++++++++++++++++++++++ src-tauri/src/desktop.rs | 299 +++++++++++++++-- src-tauri/src/lib.rs | 16 +- src-tauri/src/providers.rs | 20 +- src-tauri/tauri.conf.json | 2 +- src/App.vue | 83 +++-- src/backend/ManagerBackend.ts | 19 +- src/backend/composite.ts | 12 +- src/backend/contract.ts | 50 ++- src/backend/helper/HelperClient.ts | 45 ++- src/backend/host.ts | 29 +- src/backend/mock/MockBackend.ts | 120 ++++++- src/backend/mock/fixtures.ts | 38 ++- src/i18n/en.ts | 41 ++- src/i18n/th.ts | 41 ++- src/i18n/zh-CN.ts | 41 ++- src/i18n/zh-TW.ts | 41 ++- src/state/nav.ts | 15 + src/views/ContentBrowseView.vue | 297 +++++++++++++++++ src/views/FilesView.vue | 260 ++++++++++++--- tests/files.test.ts | 245 ++++++++++++++ tests/v030.test.ts | 6 + 29 files changed, 2125 insertions(+), 156 deletions(-) create mode 100644 docs/releases/v1.3.0.md create mode 100644 src-tauri/src/content.rs create mode 100644 src/state/nav.ts create mode 100644 src/views/ContentBrowseView.vue create mode 100644 tests/files.test.ts diff --git a/README.md b/README.md index b194dd8..79be9ab 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.2.3:** see [docs/releases/v1.2.3.md](docs/releases/v1.2.3.md). +> **What's new in 1.3.0:** see [docs/releases/v1.3.0.md](docs/releases/v1.3.0.md). -**Version 1.2.3 · Windows x64 · English, ไทย, 简体中文, 繁體中文 · GPL-3.0-only** +**Version 1.3.0 · Windows x64 · English, ไทย, 简体中文, 繁體中文 · GPL-3.0-only** ## Install -1. Download `Awake-Modpack-Manager-v1.2.3-Windows-x64-Setup.exe` from the +1. Download `Awake-Modpack-Manager-v1.3.0-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.2.3-Windows-x64-Setup.exe`). + (`Get-FileHash .\Awake-Modpack-Manager-v1.3.0-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 9524a20..cf84d69 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,10 +1,10 @@ -# Development checkpoint: Manager 1.2.3 and Native Core 0.4.2 +# Development checkpoint: Manager 1.3.0 and Native Core 0.4.2 -Unreleased until the owner approves the pull request and tags `v1.2.3`. +Unreleased until the owner approves the pull request and tags `v1.3.0`. ## Where things are -- Manager: branch `release/1.2.3`. `npm ci`, then `npm test`, `npm run typecheck`, `cargo test --manifest-path src-tauri/Cargo.toml --lib`. +- Manager: branch `release/1.3.0`. `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,7 +12,8 @@ Unreleased until the owner approves the pull request and tags `v1.2.3`. - `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`: project content listing and 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, add files, Recycle Bin), shell open. Mods are never touched here. +- `src-tauri/src/content.rs` (1.3.0): resource pack and shader search, versions and direct, checksum-verified install into `resourcepacks` / `shaderpacks`. - `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.0.md b/docs/releases/v1.3.0.md new file mode 100644 index 0000000..c3f2258 --- /dev/null +++ b/docs/releases/v1.3.0.md @@ -0,0 +1,33 @@ +# Awake Modpack Manager 1.3.0 + +Works with **Awake Launcher 3.2.2**. No Launcher update is needed. + +## Added + +- **Files works, for Launcher instances too.** The Files page used to answer "The Manager helper in this build does not support file listing yet" for every Launcher instance managed here, and was read-only everywhere else. It now shows the configs, default configs, KubeJS, scripts, resource packs and shader packs of any instance you manage here, one folder at a time, with a filter for the folder on screen. +- **Edit configs and scripts in place.** Click a text file to open it, change it and save (Ctrl+S). A save never overwrites a file that changed on disk while it was open, for example a config the game rewrote: you are told and can open the new version. Windows line endings are kept. Files over 2 MB and files that are not text are left to other programs. +- **Add files and remove them.** "Add files" copies files you pick into the folder on screen and never replaces one that is already there. Removing still goes to the Windows Recycle Bin, after a confirmation. +- **Browse resource packs and shaders.** Browse now has three shelves in the sidebar: Mods, Resource packs and Shaders. The two new ones search Modrinth and CurseForge, can be limited to the instance's Minecraft version, show each version with its file, size and (for shaders) what loads it, and install with one click. + +## How resource packs and shaders install + +They are zip files the game only reads, with no loader or dependencies to resolve, so they do not go through "Review & apply". An install is one download from the provider's own CDN, checked against the provider's checksum, written under a temporary name and then moved into `resourcepacks` or `shaderpacks`. Installing a version whose file is already there replaces that file. Nothing else in the pack changes, and mods still only change through a reviewed plan. + +Shaders need a shader mod in the pack, such as Iris or Oculus. Resource packs and shaders are turned on in the game's own options. + +CurseForge authors can turn off downloads outside the CurseForge website. For those, the Manager says so and links the page: download it there and use "Add files". + +## Changed + +- Files no longer shows "included in export" for Manager projects and managed instances: their exports take these folders whole (Instance zip) or from the pack archive, so the tick boxes did nothing there. +- The Files and Browse pages tell you to turn on "Manage mods here" for a Launcher instance that is not managed here yet, instead of "Not available in this version yet". + +## Safety + +- The Manager's desktop host now writes inside six content folders of an instance (`config`, `defaultconfigs`, `kubejs`, `scripts`, `resourcepacks`, `shaderpacks`), and only when you save, add, install or remove something. It never writes to `mods`, worlds or anything else. +- A link or junction inside one of those folders is never followed, so nothing can be read, saved or removed outside them. +- Only a file whose name ends in `.zip` is ever installed from a provider. + +## Not verified on a real machine yet + +The demo data and the automated tests cover these screens. Against live Modrinth, search, versions and a real download, checksum check and install into a scratch folder were run through the host's own code. Still unverified: the screens in the desktop app against a real Launcher instance, and anything on CurseForge (this development machine has no CurseForge key; the live CurseForge test for search and versions runs in the GitHub checks). diff --git a/package-lock.json b/package-lock.json index 6f4afa3..844036c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "awake-modpack-manager", - "version": "1.2.3", + "version": "1.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "awake-modpack-manager", - "version": "1.2.3", + "version": "1.3.0", "license": "GPL-3.0-only", "dependencies": { "@lucide/vue": "1.59.0", diff --git a/package.json b/package.json index 111a7e4..17f5ecc 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "awake-modpack-manager", "private": true, - "version": "1.2.3", + "version": "1.3.0", "license": "GPL-3.0-only", "type": "module", "engines": { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 37e00e2..29fe642 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -224,7 +224,7 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "awake-modpack-manager" -version = "1.2.3" +version = "1.3.0" dependencies = [ "md-5", "serde", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 6bc44ea..6ab9c26 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "awake-modpack-manager" -version = "1.2.3" +version = "1.3.0" 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/content.rs b/src-tauri/src/content.rs new file mode 100644 index 0000000..fffaaad --- /dev/null +++ b/src-tauri/src/content.rs @@ -0,0 +1,501 @@ +//! Resource packs and shader packs from Modrinth and CurseForge: search, versions, and installing +//! one into a project's `resourcepacks` or `shaderpacks` folder. +//! +//! Unlike mods these are plain zip files the game only reads, with no loader or dependencies to +//! resolve, so they do not go through the helper's reviewed plans. An install is one verified +//! download from the provider's own CDN, written under a temporary name and renamed into place. + +use crate::providers::{blocking, cf_get, download, encode, err, get_json, hex, host_of, release_name, s, safe_id, HostError, HostResult}; +use serde::Serialize; +use serde_json::Value; +use sha1::Sha1; +use sha2::{Digest, Sha512}; +use std::fs; +use std::path::Path; +use tauri::Emitter; + +const MODRINTH: &str = "https://api.modrinth.com/v2"; +const DOWNLOAD_MAX: u64 = 1 << 30; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum Kind { + ResourcePack, + Shader, +} +impl Kind { + pub fn parse(kind: &str) -> HostResult { + match kind { + "resourcepack" => Ok(Self::ResourcePack), + "shader" => Ok(Self::Shader), + _ => err("invalid", "Unknown content type."), + } + } + /// Modrinth's project type, which is also the path segment of its project pages. + fn modrinth(self) -> &'static str { + if self == Self::ResourcePack { "resourcepack" } else { "shader" } + } + /// CurseForge's class for Minecraft (game 432): 12 is Resource Packs, 6552 is Shaders. + fn curseforge_class(self) -> u32 { + if self == Self::ResourcePack { 12 } else { 6552 } + } + fn folder(self) -> &'static str { + if self == Self::ResourcePack { "resourcepacks" } else { "shaderpacks" } + } +} + +#[derive(Serialize, Debug, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ContentHit { + provider: &'static str, + project_id: String, + name: String, + author: String, + summary: String, + #[serde(skip_serializing_if = "Option::is_none")] + icon_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + downloads: Option, + #[serde(skip_serializing_if = "Option::is_none")] + page_url: Option, +} +#[derive(Serialize, Debug)] +pub struct ContentPage { + hits: Vec, + total: u64, +} +#[derive(Serialize, Debug, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ContentVersion { + id: String, + name: String, + version_number: String, + #[serde(skip_serializing_if = "Option::is_none")] + release_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + published_at: Option, + file_name: String, + #[serde(skip_serializing_if = "Option::is_none")] + size_bytes: Option, + game_versions: Vec, + /// What can load it, as the provider tags it (Iris, OptiFine...). Empty for resource packs. + loaders: Vec, +} + +fn strings(v: &Value) -> Vec { + v.as_array().map_or(vec![], |a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()) +} +fn web_url(v: &Value) -> Option { + v.as_str().filter(|u| u.starts_with("https://")).map(Into::into) +} + +pub fn modrinth_search_url(kind: Kind, text: &str, minecraft: &str, offset: u32, limit: u32) -> String { + let mut facets = format!(r#"[["project_type:{}"]"#, kind.modrinth()); + if !minecraft.is_empty() { + facets.push_str(&format!(r#",["versions:{minecraft}"]"#)); + } + facets.push(']'); + let index = if text.trim().is_empty() { "downloads" } else { "relevance" }; + format!("{MODRINTH}/search?query={}&facets={}&index={index}&offset={offset}&limit={limit}", encode(text), encode(&facets)) +} +pub fn parse_modrinth_hits(kind: Kind, page: &Value) -> Vec { + page["hits"].as_array().map_or(vec![], |list| { + list.iter() + .map(|h| ContentHit { + provider: "modrinth", + project_id: s(h, "project_id").into(), + name: s(h, "title").into(), + author: s(h, "author").into(), + summary: s(h, "description").into(), + icon_url: web_url(&h["icon_url"]), + downloads: h["downloads"].as_f64(), + page_url: Some(format!("https://modrinth.com/{}/{}", kind.modrinth(), s(h, "slug"))).filter(|_| !s(h, "slug").is_empty()), + }) + .collect() + }) +} + +pub fn curseforge_search_path(kind: Kind, text: &str, minecraft: &str, offset: u32, limit: u32) -> String { + let limit = limit.min(50).min(10000u32.saturating_sub(offset)).max(1); + let version = if minecraft.is_empty() { String::new() } else { format!("&gameVersion={}", encode(minecraft)) }; + format!("/mods/search?gameId=432&classId={}&sortField=2&sortOrder=desc&searchFilter={}{version}&index={offset}&pageSize={limit}", kind.curseforge_class(), encode(text)) +} +pub fn parse_curseforge_hits(page: &Value) -> Vec { + page["data"].as_array().map_or(vec![], |list| { + list.iter() + .map(|h| ContentHit { + provider: "curseforge", + project_id: h["id"].as_i64().unwrap_or(0).to_string(), + name: s(h, "name").into(), + author: h["authors"][0]["name"].as_str().unwrap_or("").into(), + summary: s(h, "summary").into(), + icon_url: web_url(&h["logo"]["thumbnailUrl"]), + downloads: h["downloadCount"].as_f64(), + page_url: web_url(&h["links"]["websiteUrl"]), + }) + .collect() + }) +} + +#[tauri::command] +pub async fn content_search(provider: String, kind: String, text: String, minecraft_version: String, offset: u32, limit: u32) -> HostResult { + blocking(move || { + let kind = Kind::parse(&kind)?; + let minecraft = if minecraft_version.is_empty() { "" } else { safe_id(&minecraft_version)? }; + let limit = limit.clamp(1, 60); + match provider.as_str() { + "modrinth" => { + let page = get_json(&modrinth_search_url(kind, &text, minecraft, offset, limit))?; + Ok(ContentPage { hits: parse_modrinth_hits(kind, &page), total: page["total_hits"].as_u64().unwrap_or(0) }) + } + "curseforge" => { + let page = cf_get(&curseforge_search_path(kind, &text, minecraft, offset, limit))?; + Ok(ContentPage { hits: parse_curseforge_hits(&page), total: page["pagination"]["totalCount"].as_u64().unwrap_or(0).min(10000) }) + } + _ => err("invalid", "Unknown provider."), + } + }) + .await +} + +fn modrinth_file(version: &Value) -> Option<&Value> { + let files = version["files"].as_array()?; + files.iter().find(|f| f["primary"] == true).or(files.first()) +} +pub fn parse_modrinth_versions(list: &Value) -> Vec { + list.as_array().map_or(vec![], |all| { + all.iter() + .filter_map(|v| { + let file = modrinth_file(v)?; + Some(ContentVersion { + id: s(v, "id").into(), + name: s(v, "name").into(), + version_number: s(v, "version_number").into(), + release_type: v["version_type"].as_str().map(Into::into), + published_at: v["date_published"].as_str().map(Into::into), + file_name: s(file, "filename").into(), + size_bytes: file["size"].as_u64(), + game_versions: strings(&v["game_versions"]), + // "minecraft" only says it is a resource pack. + loaders: strings(&v["loaders"]).into_iter().filter(|l| l != "minecraft").collect(), + }) + }) + .collect() + }) +} +pub fn parse_curseforge_versions(page: &Value) -> Vec { + page["data"].as_array().map_or(vec![], |all| { + all.iter() + .map(|f| { + let (game_versions, loaders): (Vec, Vec) = strings(&f["gameVersions"]).into_iter().partition(|t| t.chars().next().is_some_and(|c| c.is_ascii_digit())); + ContentVersion { + id: f["id"].as_i64().unwrap_or(0).to_string(), + name: s(f, "displayName").into(), + version_number: s(f, "displayName").into(), + release_type: f["releaseType"].as_i64().and_then(release_name), + published_at: f["fileDate"].as_str().map(Into::into), + file_name: s(f, "fileName").into(), + size_bytes: f["fileLength"].as_u64(), + game_versions, + loaders, + } + }) + .collect() + }) +} + +/// Versions of a project, newest first; only those for `minecraft_version` when one is given. +#[tauri::command] +pub async fn content_versions(provider: String, project_id: String, minecraft_version: String) -> HostResult> { + blocking(move || { + let id = safe_id(&project_id)?; + let minecraft = if minecraft_version.is_empty() { "" } else { safe_id(&minecraft_version)? }; + match provider.as_str() { + "modrinth" => { + let filter = if minecraft.is_empty() { String::new() } else { format!("?game_versions={}", encode(&format!(r#"["{minecraft}"]"#))) }; + Ok(parse_modrinth_versions(&get_json(&format!("{MODRINTH}/project/{}/version{filter}", encode(id)))?)) + } + "curseforge" => { + let filter = if minecraft.is_empty() { String::new() } else { format!("&gameVersion={}", encode(minecraft)) }; + Ok(parse_curseforge_versions(&cf_get(&format!("/mods/{}/files?index=0&pageSize=50{filter}", encode(id)))?)) + } + _ => err("invalid", "Unknown provider."), + } + }) + .await +} + +/// A provider's file name as it may be written into a pack folder: one plain `.zip` name. +pub fn pack_file_name(name: &str) -> HostResult<&str> { + const RESERVED: [&str; 22] = ["con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"]; + let lower = name.to_ascii_lowercase(); + let plain = !name.is_empty() && name.len() <= 200 && !name.starts_with(['.', ' ']) && !name.chars().any(|c| c.is_control() || r#"<>:"/\|?*"#.contains(c)); + if plain && lower.ends_with(".zip") && !RESERVED.contains(&lower.split('.').next().unwrap_or("")) { + Ok(name) + } else { + err("restricted", format!("The provider lists \"{name}\" for this version, which is not a pack zip the Manager can install.")) + } +} + +/// What to download for one version: (url, file name, size, sha512 or sha1). +type Source = (String, String, u64, Checksum); +#[derive(Debug, PartialEq)] +pub enum Checksum { + Sha512(String), + Sha1(String), + None, +} + +pub fn modrinth_source(version: &Value, project_id: &str) -> HostResult { + if s(version, "project_id") != project_id { + return err("invalid", "That version belongs to another project."); + } + let file = modrinth_file(version).ok_or(HostError { code: "not-found", message: "This version has no file.".into() })?; + let url = s(file, "url"); + if host_of(url) != "cdn.modrinth.com" || !url.starts_with("https://") { + return err("restricted", "This version's file is not hosted on Modrinth."); + } + let sha512 = s(&file["hashes"], "sha512").to_ascii_lowercase(); + if sha512.len() != 128 { + return err("restricted", "Modrinth lists no checksum for this file."); + } + Ok((url.into(), pack_file_name(s(file, "filename"))?.into(), file["size"].as_u64().unwrap_or(0), Checksum::Sha512(sha512))) +} + +pub fn curseforge_source(kind: Kind, project: &Value, file: &Value) -> HostResult { + if project["classId"].as_u64() != Some(u64::from(kind.curseforge_class())) { + return err("invalid", "That CurseForge project is a different kind of content."); + } + let url = file["downloadUrl"].as_str().unwrap_or(""); + if url.is_empty() || project["allowModDistribution"] == false { + let page = web_url(&project["links"]["websiteUrl"]).unwrap_or_default(); + return err("manual-download", format!("Its author only allows downloads from the CurseForge website. Download it there, then use \"Add files\" on the Files page. {page}").trim().to_string()); + } + if !url.starts_with("https://") || !["edge.forgecdn.net", "mediafilez.forgecdn.net"].contains(&host_of(url).as_str()) { + return err("restricted", "CurseForge returned an unexpected download host."); + } + let sha1 = file["hashes"].as_array().and_then(|h| h.iter().find(|x| x["algo"] == 1)).map(|x| s(x, "value").to_ascii_lowercase()).filter(|h| h.len() == 40); + Ok((url.into(), pack_file_name(s(file, "fileName"))?.into(), file["fileLength"].as_u64().unwrap_or(0), sha1.map_or(Checksum::None, Checksum::Sha1))) +} + +fn digest(path: &Path) -> HostResult { + let mut hash = D::new(); + let mut input = fs::File::open(path).or_else(|e| err("io", e.to_string()))?; + std::io::copy(&mut input, &mut hash).or_else(|e| err("io", e.to_string()))?; + Ok(hex(&hash.finalize())) +} + +/// Put a downloaded, verified file in place. Returns whether it replaced a file of the same name. +pub fn place(partial: &Path, target: &Path, checksum: &Checksum) -> HostResult { + let matches = match checksum { + Checksum::Sha512(expected) => digest::(partial)? == *expected, + Checksum::Sha1(expected) => digest::(partial)? == *expected, + Checksum::None => true, + }; + if !matches { + return err("integrity", "The download does not match the provider's checksum, so it was not installed."); + } + let replaced = match fs::symlink_metadata(target) { + Ok(meta) if meta.is_file() => true, + Ok(_) => return err("invalid", "Something that is not a file already has this name."), + Err(_) => false, + }; + fs::rename(partial, target).or_else(|e| err("io", format!("Could not put the file in place: {e}")))?; + Ok(replaced) +} + +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Installed { + file_name: String, + replaced: bool, +} +#[derive(Serialize, Clone)] +struct InstallProgress { + job: String, + done: u64, + total: u64, +} + +/// Download one version's file into `dir` and put it in place once it is verified. A failure +/// leaves the folder as it was. +pub fn install_into(dir: &Path, (url, file_name, _, checksum): &Source, progress: impl FnMut(u64)) -> HostResult { + fs::create_dir_all(dir).or_else(|e| err("io", format!("Could not prepare {}: {e}", dir.display())))?; + let partial = dir.join(format!(".{file_name}.{}.partial", std::process::id())); + let result = download(None, url, &[], &partial, DOWNLOAD_MAX, progress).and_then(|_| place(&partial, &dir.join(file_name), checksum)); + if result.is_err() { + let _ = fs::remove_file(&partial); + } + result +} + +#[tauri::command] +pub async fn content_install(app: tauri::AppHandle, workspace: String, provider: String, kind: String, project_id: String, version_id: String, job: String) -> HostResult { + blocking(move || { + let kind = Kind::parse(&kind)?; + let (project_id, version_id) = (safe_id(&project_id)?, safe_id(&version_id)?); + let source = match provider.as_str() { + "modrinth" => modrinth_source(&get_json(&format!("{MODRINTH}/version/{}", encode(version_id)))?, project_id)?, + "curseforge" => { + let project = cf_get(&format!("/mods/{}", encode(project_id)))?; + let file = cf_get(&format!("/mods/{}/files/{}", encode(project_id), encode(version_id)))?; + curseforge_source(kind, &project["data"], &file["data"])? + } + _ => return err("invalid", "Unknown provider."), + }; + let dir = crate::export::game_folder(&workspace)?.join(kind.folder()); + let total = source.2; + let replaced = install_into(&dir, &source, |done| { + let _ = app.emit("content-progress", InstallProgress { job: job.clone(), done, total }); + })?; + Ok(Installed { file_name: source.1, replaced }) + }) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// Real Modrinth, through this host's own requests. `cargo test -- --ignored live_`. + #[test] + #[ignore] + fn live_modrinth_lists_resource_packs_and_shaders() { + for kind in [Kind::ResourcePack, Kind::Shader] { + let page = get_json(&modrinth_search_url(kind, "", "1.20.1", 0, 10)).expect("search"); + let hits = parse_modrinth_hits(kind, &page); + assert_eq!(hits.len(), 10, "{kind:?}"); + assert!(page["hits"].as_array().unwrap().iter().all(|h| h["project_type"] == kind.modrinth())); + let versions = parse_modrinth_versions(&get_json(&format!("{MODRINTH}/project/{}/version?game_versions={}", hits[0].project_id, encode(r#"["1.20.1"]"#))).expect("versions")); + assert!(!versions.is_empty() && pack_file_name(&versions[0].file_name).is_ok(), "{kind:?}: {:?}", versions.first()); + let version = get_json(&format!("{MODRINTH}/version/{}", versions[0].id)).expect("version"); + assert!(modrinth_source(&version, &hits[0].project_id).is_ok()); + } + } + + /// A real download from Modrinth's CDN into a scratch folder, checked and put in place. + #[test] + #[ignore] + fn live_modrinth_installs_a_verified_pack() { + let page = get_json(&modrinth_search_url(Kind::Shader, "", "1.20.1", 0, 20)).expect("search"); + // The smallest of a few popular shaders keeps this quick. + let (project, version) = parse_modrinth_hits(Kind::Shader, &page).into_iter().take(6).filter_map(|hit| { + let versions = parse_modrinth_versions(&get_json(&format!("{MODRINTH}/project/{}/version?game_versions={}", hit.project_id, encode(r#"["1.20.1"]"#))).ok()?); + Some((hit.project_id, versions.into_iter().next()?)) + }).min_by_key(|(_, v)| v.size_bytes.unwrap_or(u64::MAX)).expect("a shader with a version"); + let source = modrinth_source(&get_json(&format!("{MODRINTH}/version/{}", version.id)).expect("version"), &project).expect("source"); + let dir = std::env::temp_dir().join(format!("awake-mm-live-install-{}", std::process::id())).join("shaderpacks"); + let mut seen = 0; + assert!(!install_into(&dir, &source, |done| seen = done).expect("install")); + let placed = fs::metadata(dir.join(&source.1)).expect("the pack is in the folder"); + assert_eq!((placed.len(), seen), (source.2, source.2), "{}", source.1); + assert!(zip::ZipArchive::new(fs::File::open(dir.join(&source.1)).unwrap()).is_ok(), "a readable zip"); + assert!(install_into(&dir, &source, |_| {}).expect("again"), "the same version replaces its file"); + assert_eq!(fs::read_dir(&dir).unwrap().count(), 1, "no temp file left behind"); + // A wrong checksum installs nothing and leaves nothing behind. + let other = dir.with_file_name("refused"); + let bad = (source.0.clone(), source.1.clone(), source.2, Checksum::Sha512("0".repeat(128))); + assert_eq!(install_into(&other, &bad, |_| {}).unwrap_err().code, "integrity"); + assert_eq!(fs::read_dir(&other).unwrap().count(), 0); + fs::remove_dir_all(dir.parent().unwrap()).unwrap(); + } + + /// Real CurseForge. Needs the key from GitHub Actions; a build without one skips it. + #[test] + #[ignore] + fn curseforge_live_resource_packs_and_shaders() { + if crate::providers::curseforge_key().is_none() { + return; + } + for kind in [Kind::ResourcePack, Kind::Shader] { + let page = cf_get(&curseforge_search_path(kind, "", "1.20.1", 0, 10)).expect("search"); + let hits = parse_curseforge_hits(&page); + assert!(!hits.is_empty(), "{kind:?}"); + assert!(page["data"].as_array().unwrap().iter().all(|h| h["classId"] == kind.curseforge_class()), "{kind:?}"); + let versions = parse_curseforge_versions(&cf_get(&format!("/mods/{}/files?index=0&pageSize=50&gameVersion=1.20.1", hits[0].project_id)).expect("files")); + assert!(!versions.is_empty() && versions[0].file_name.to_lowercase().ends_with(".zip"), "{kind:?}: {:?}", versions.first()); + } + } + + #[test] + fn searches_ask_each_provider_for_the_right_kind() { + let m = modrinth_search_url(Kind::Shader, "bsl shaders", "1.20.1", 30, 30); + assert!(m.contains(&encode(r#"[["project_type:shader"],["versions:1.20.1"]]"#)) && m.contains("index=relevance&offset=30&limit=30") && m.contains("query=bsl%20shaders")); + let all = modrinth_search_url(Kind::ResourcePack, "", "", 0, 30); + assert!(all.contains(&encode(r#"[["project_type:resourcepack"]]"#)) && all.contains("index=downloads")); + assert!(curseforge_search_path(Kind::ResourcePack, "", "1.20.1", 0, 30).contains("classId=12&") && curseforge_search_path(Kind::ResourcePack, "", "1.20.1", 0, 30).contains("&gameVersion=1.20.1")); + let cf = curseforge_search_path(Kind::Shader, "a&b", "", 9990, 30); + assert!(cf.contains("classId=6552&") && cf.contains("searchFilter=a%26b") && cf.ends_with("&index=9990&pageSize=10") && !cf.contains("gameVersion")); + } + + #[test] + fn hits_and_versions_are_read_from_both_providers() { + let page = json!({"hits": [{"project_id": "HVnmMxH1", "slug": "complementary-reimagined", "title": "Complementary", "author": "EminGT", "description": "Shaders", "downloads": 7.0, "icon_url": "https://cdn.modrinth.com/i.webp"}], "total_hits": 1}); + let hit = &parse_modrinth_hits(Kind::Shader, &page)[0]; + assert_eq!((hit.project_id.as_str(), hit.page_url.as_deref(), hit.icon_url.as_deref()), ("HVnmMxH1", Some("https://modrinth.com/shader/complementary-reimagined"), Some("https://cdn.modrinth.com/i.webp"))); + let versions = parse_modrinth_versions(&json!([ + {"id": "v2", "name": "r5.9", "version_number": "r5.9", "version_type": "release", "date_published": "2026-09-15T06:35:41Z", "game_versions": ["1.20.1"], "loaders": ["iris", "optifine"], + "files": [{"filename": "extra.txt", "primary": false}, {"filename": "Complementary_r5.9.zip", "primary": true, "size": 600}]}, + {"id": "v1", "name": "Faithful", "version_number": "1.20", "game_versions": ["1.20.1"], "loaders": ["minecraft"], "files": [{"filename": "Faithful.zip"}]}, + {"id": "v0", "files": []}])); + assert_eq!(versions.len(), 2); + assert_eq!((versions[0].file_name.as_str(), versions[0].size_bytes, versions[0].loaders.len()), ("Complementary_r5.9.zip", Some(600), 2)); + assert!(versions[1].loaders.is_empty()); + + let cf = json!({"data": [{"id": 9, "name": "BSL", "summary": "s", "authors": [{"name": "capt"}], "logo": {"thumbnailUrl": "https://media.forgecdn.net/a.png"}, "downloadCount": 3.0, "links": {"websiteUrl": "https://www.curseforge.com/minecraft/shaders/bsl"}}, {"id": 10, "name": "No logo", "logo": null, "links": {"websiteUrl": "javascript:alert(1)"}}]}); + let hits = parse_curseforge_hits(&cf); + assert_eq!((hits[0].project_id.as_str(), hits[0].author.as_str(), hits[0].page_url.is_some()), ("9", "capt", true)); + assert_eq!((hits[1].icon_url.as_ref(), hits[1].page_url.as_ref()), (None, None)); + let files = parse_curseforge_versions(&json!({"data": [{"id": 77, "displayName": "BSL v8", "fileName": "BSL_v8.zip", "fileLength": 5, "releaseType": 2, "fileDate": "2026-01-01T00:00:00Z", "gameVersions": ["1.20.1", "Iris", "1.19.4", "OptiFine"]}]})); + assert_eq!((files[0].id.as_str(), files[0].release_type.as_deref(), &files[0].game_versions, &files[0].loaders), ("77", Some("beta"), &vec!["1.20.1".to_string(), "1.19.4".to_string()], &vec!["Iris".to_string(), "OptiFine".to_string()])); + } + + #[test] + fn only_a_plain_zip_name_is_written_into_a_pack_folder() { + for fine in ["Faithful 32x - 1.20.1.zip", "§6Fancy!§r.ZIP", "Complementary_r5.9.3.zip"] { + assert!(pack_file_name(fine).is_ok(), "{fine}"); + } + for bad in ["", "evil.jar", "pack.zip.exe", "../pack.zip", "a/b.zip", "a\\b.zip", "C:pack.zip", ".hidden.zip", "con.zip", "pack\n.zip", "what?.zip"] { + assert_eq!(pack_file_name(bad).unwrap_err().code, "restricted", "{bad}"); + } + } + + #[test] + fn a_download_comes_only_from_the_providers_own_cdn_with_a_checksum() { + let sha = "ab".repeat(64); + let file = |url: &str| json!({"project_id": "proj", "files": [{"url": url, "filename": "p.zip", "size": 9, "primary": true, "hashes": {"sha512": sha}}]}); + assert_eq!(modrinth_source(&file("https://cdn.modrinth.com/data/x/p.zip"), "proj").unwrap(), ("https://cdn.modrinth.com/data/x/p.zip".to_string(), "p.zip".to_string(), 9, Checksum::Sha512(sha.clone()))); + assert_eq!(modrinth_source(&file("https://cdn.modrinth.com/data/x/p.zip"), "other").unwrap_err().code, "invalid"); + assert_eq!(modrinth_source(&file("https://evil.example/p.zip"), "proj").unwrap_err().code, "restricted"); + assert_eq!(modrinth_source(&file("http://cdn.modrinth.com/p.zip"), "proj").unwrap_err().code, "restricted"); + assert_eq!(modrinth_source(&json!({"project_id": "proj", "files": [{"url": "https://cdn.modrinth.com/p.zip", "filename": "p.zip", "hashes": {}}]}), "proj").unwrap_err().code, "restricted"); + + let project = json!({"classId": 6552, "allowModDistribution": true, "links": {"websiteUrl": "https://www.curseforge.com/minecraft/shaders/bsl"}}); + let cf_file = json!({"downloadUrl": "https://edge.forgecdn.net/files/1/2/BSL.zip", "fileName": "BSL.zip", "fileLength": 4, "hashes": [{"algo": 2, "value": "md5"}, {"algo": 1, "value": "C".repeat(40)}]}); + assert_eq!(curseforge_source(Kind::Shader, &project, &cf_file).unwrap().3, Checksum::Sha1("c".repeat(40))); + assert_eq!(curseforge_source(Kind::ResourcePack, &project, &cf_file).unwrap_err().code, "invalid", "a shader is not a resource pack"); + assert_eq!(curseforge_source(Kind::Shader, &json!({"classId": 6552, "allowModDistribution": false}), &cf_file).unwrap_err().code, "manual-download"); + assert_eq!(curseforge_source(Kind::Shader, &project, &json!({"downloadUrl": null, "fileName": "BSL.zip"})).unwrap_err().code, "manual-download"); + assert_eq!(curseforge_source(Kind::Shader, &project, &json!({"downloadUrl": "https://evil.example/BSL.zip", "fileName": "BSL.zip"})).unwrap_err().code, "restricted"); + assert_eq!(curseforge_source(Kind::Shader, &project, &json!({"downloadUrl": "https://edge.forgecdn.net/x", "fileName": "BSL.jar"})).unwrap_err().code, "restricted"); + } + + #[test] + fn a_download_is_only_put_in_place_when_its_checksum_matches() { + let dir = std::env::temp_dir().join(format!("awake-mm-content-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let (partial, target) = (dir.join(".p.zip.partial"), dir.join("p.zip")); + fs::write(&partial, "pack").unwrap(); + assert_eq!(place(&partial, &target, &Checksum::Sha1("0".repeat(40))).unwrap_err().code, "integrity"); + assert!(!target.exists()); + let sha1 = hex(&Sha1::digest(b"pack")); + assert!(!place(&partial, &target, &Checksum::Sha1(sha1)).unwrap()); + assert_eq!(fs::read_to_string(&target).unwrap(), "pack"); + // The same file name again replaces it, and says so. + fs::write(&partial, "pack 2").unwrap(); + assert!(place(&partial, &target, &Checksum::Sha512(hex(&Sha512::digest(b"pack 2")))).unwrap()); + assert_eq!(fs::read_to_string(&target).unwrap(), "pack 2"); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/src-tauri/src/desktop.rs b/src-tauri/src/desktop.rs index d89dc65..66695f2 100644 --- a/src-tauri/src/desktop.rs +++ b/src-tauri/src/desktop.rs @@ -1,7 +1,9 @@ -//! Desktop integration: opening folders and links with the shell, and reading or recycling the -//! non-mod content of a Manager workspace (config, resource packs, shaders...). +//! 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. +//! Mods are never touched here: they belong to the native helper's reviewed transactions. 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}; @@ -10,19 +12,20 @@ use serde_json::Value; use std::collections::HashSet; use std::fs; use std::path::{Component, Path, PathBuf}; +use tauri_plugin_dialog::DialogExt; const AREAS: [&str; 6] = ["config", "defaultconfigs", "kubejs", "scripts", "resourcepacks", "shaderpacks"]; const LIST_MAX: usize = 20_000; +/// The largest text file the built-in editor opens or saves. +const TEXT_MAX: u64 = 2 << 20; pub fn is_uuid(id: &str) -> bool { id.len() == 36 && id.bytes().enumerate().all(|(i, b)| if [8, 13, 18, 23].contains(&i) { b == b'-' } else { b.is_ascii_hexdigit() }) } +/// The game folder of a project, or of a Launcher instance managed here. fn game_dir(workspace: &str) -> HostResult { - if !is_uuid(workspace) { - return err("invalid", "Unknown project."); - } - Ok(manager_data_dir().or_else(|m| err("io", m))?.join("core").join("workspaces").join(workspace).join(".minecraft")) + crate::export::game_folder(workspace) } /// `area/relative/path` under the game folder, with no way out of it. @@ -46,40 +49,171 @@ pub struct ContentRow { modified_ms: Option, } -fn walk(root: &Path, dir: &Path, out: &mut Vec) { - let Ok(entries) = fs::read_dir(dir) else { return }; - for entry in entries.flatten() { +/// Like `content_path`, and no folder on the way down from the area is a link: a junction inside +/// `config` must never lead a read, a save or a removal somewhere else on the disk. The area folder +/// itself may be one, since sharing `resourcepacks` between instances that way is a common setup. +pub fn checked_path(game: &Path, area: &str, relative: &str) -> HostResult { + let path = content_path(game, area, relative)?; + let mut at = game.join(area); + for part in Path::new(relative).components() { + at.push(part); + if fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink()) { + return err("invalid", "Links to other folders are not opened here."); + } + } + Ok(path) +} + +fn modified_ms(meta: &fs::Metadata) -> Option { + meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as u64) +} + +/// What is directly inside `dir`, folders first. Paths are relative to `root`, the area folder. +pub fn list_folder(root: &Path, dir: &Path) -> Vec { + let mut out = vec![]; + for entry in fs::read_dir(dir).into_iter().flatten().flatten() { if out.len() >= LIST_MAX { - return; + break; } let Ok(meta) = fs::symlink_metadata(entry.path()) else { continue }; if meta.file_type().is_symlink() { continue; } let path = entry.path().strip_prefix(root).unwrap_or(&entry.path()).to_string_lossy().replace('\\', "/"); - let modified_ms = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as u64); - if meta.is_dir() { - out.push(ContentRow { path, kind: "directory", size_bytes: None, modified_ms }); - walk(root, &entry.path(), out); - } else { - out.push(ContentRow { path, kind: "file", size_bytes: Some(meta.len()), modified_ms }); - } + let (kind, size_bytes) = if meta.is_dir() { ("directory", None) } else { ("file", Some(meta.len())) }; + out.push(ContentRow { path, kind, size_bytes, modified_ms: modified_ms(&meta) }); + } + out.sort_by_key(|row| (row.kind == "file", row.path.to_lowercase())); + out +} + +#[tauri::command] +pub async fn workspace_list(workspace: String, area: String, folder: Option) -> HostResult> { + tauri::async_runtime::spawn_blocking(move || { + let game = game_dir(&workspace)?; + Ok(list_folder(&content_path(&game, &area, "")?, &checked_path(&game, &area, folder.as_deref().unwrap_or(""))?)) + }) + .await + .unwrap_or_else(|e| err("internal", e.to_string())) +} + +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct TextFile { + text: String, + modified_ms: u64, +} + +fn regular_file(path: &Path) -> HostResult { + match fs::symlink_metadata(path) { + Ok(meta) if meta.is_file() => Ok(meta), + Ok(_) => err("invalid", "That is not a file."), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => err("not-found", "This file is not there any more."), + Err(e) => err("io", e.to_string()), + } +} + +/// A file as text for the editor. Binary files and very large ones are refused, never shown mangled. +pub fn read_text(path: &Path) -> HostResult { + let meta = regular_file(path)?; + if meta.len() > TEXT_MAX { + return err("too-large", "This file is too large to edit here (2 MB at most). Open its folder to edit it in another program."); + } + let bytes = fs::read(path).or_else(|e| err("io", e.to_string()))?; + match String::from_utf8(bytes) { + Ok(text) if !text.contains('\0') => Ok(TextFile { text, modified_ms: modified_ms(&meta).unwrap_or(0) }), + _ => err("not-text", "This is not a text file, so it cannot be edited here."), } } +/// Save an edited file over the one that was opened. Refused if it changed on disk in the meantime, +/// so a config the game rewrote while the editor was open is never silently overwritten. +pub fn write_text(path: &Path, text: &str, expected_modified_ms: u64) -> HostResult { + if text.len() as u64 > TEXT_MAX || text.contains('\0') { + return err("too-large", "This text is too large to save here (2 MB at most)."); + } + let meta = regular_file(path)?; + if modified_ms(&meta).unwrap_or(0) != expected_modified_ms { + return err("conflict", "This file changed on disk after you opened it. Open it again to see the new version."); + } + // A text box only has plain line breaks; keep Windows line endings if the file had them. + let had_crlf = fs::read(path).is_ok_and(|old| old.windows(2).any(|w| w == b"\r\n")); + let plain = text.replace("\r\n", "\n"); + let out = if had_crlf { plain.replace('\n', "\r\n") } else { plain }; + crate::files::write_atomic(path, out.as_bytes(), false).or_else(|m| err("io", m))?; + Ok(fs::metadata(path).ok().as_ref().and_then(modified_ms).unwrap_or(0)) +} + #[tauri::command] -pub async fn workspace_list(workspace: String, area: String) -> HostResult> { +pub async fn workspace_read_text(workspace: String, area: String, path: String) -> HostResult { + tauri::async_runtime::spawn_blocking(move || read_text(&checked_path(&game_dir(&workspace)?, &area, &path)?)) + .await + .unwrap_or_else(|e| err("internal", e.to_string())) +} + +#[tauri::command] +pub async fn workspace_write_text(workspace: String, area: String, path: String, text: String, expected_modified_ms: u64) -> HostResult { tauri::async_runtime::spawn_blocking(move || { - let root = content_path(&game_dir(&workspace)?, &area, "")?; - let mut out = vec![]; - walk(&root, &root, &mut out); - out.sort_by(|a, b| a.path.to_lowercase().cmp(&b.path.to_lowercase())); - Ok(out) + if path.is_empty() { + return err("invalid", "That is not a file."); + } + write_text(&checked_path(&game_dir(&workspace)?, &area, &path)?, &text, expected_modified_ms) }) .await .unwrap_or_else(|e| err("internal", e.to_string())) } +#[derive(Serialize, Debug, Default, PartialEq)] +pub struct AddedFiles { + added: Vec, + /// Already there under the same name; nothing is ever overwritten by adding. + skipped: Vec, +} + +/// Copy files the user picked into a content folder. A copy lands under a temporary name first, so +/// a failed one never leaves half a file where the game would read it. +pub fn add_files(dir: &Path, sources: &[PathBuf]) -> HostResult { + fs::create_dir_all(dir).or_else(|e| err("io", e.to_string()))?; + let mut out = AddedFiles::default(); + for source in sources { + let Some(name) = source.file_name().map(|n| n.to_string_lossy().into_owned()) else { continue }; + if !fs::metadata(source).is_ok_and(|m| m.is_file()) { + return err("invalid", format!("{name} is not a file.")); + } + let target = dir.join(&name); + if fs::symlink_metadata(&target).is_ok() { + out.skipped.push(name); + continue; + } + let partial = dir.join(format!(".{name}.{}.partial", 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!("{name}: {e}")); + } + out.added.push(name); + } + Ok(out) +} + +/// Ask which files to add to a content folder, then copy them in. None when the user cancels. +#[tauri::command] +pub async fn workspace_add_files(app: tauri::AppHandle, workspace: String, area: String, folder: String) -> HostResult> { + let dir = checked_path(&game_dir(&workspace)?, &area, &folder)?; + if !folder.is_empty() && !dir.is_dir() { + return err("not-found", "This folder is not there any more."); + } + let packs = area == "resourcepacks" || area == "shaderpacks"; + let picked = tauri::async_runtime::spawn_blocking(move || { + let dialog = app.dialog().file(); + if packs { dialog.add_filter("Zip", &["zip"]) } else { dialog }.blocking_pick_files() + }) + .await + .or_else(|e| err("internal", e.to_string()))?; + let Some(picked) = picked else { return Ok(None) }; + let sources = picked.into_iter().map(|p| p.into_path().or_else(|e| err("io", e.to_string()))).collect::>>()?; + tauri::async_runtime::spawn_blocking(move || add_files(&dir, &sources).map(Some)).await.unwrap_or_else(|e| err("internal", e.to_string())) +} + #[cfg(windows)] fn recycle(path: &Path) -> HostResult<()> { use std::os::windows::ffi::OsStrExt; @@ -107,7 +241,7 @@ pub async fn workspace_recycle(workspace: String, area: String, paths: Vec HostResult<()> { /// Open a project's game folder, or one of its content folders, in File Explorer. #[tauri::command] -pub fn workspace_open(workspace: String, area: Option) -> HostResult<()> { +pub fn workspace_open(workspace: String, area: Option, folder: Option) -> HostResult<()> { let game = game_dir(&workspace)?; + let inner = folder.as_deref().unwrap_or(""); let path = match area.as_deref() { - Some(a) if !a.is_empty() => content_path(&game, a, "")?, + Some(a) if !a.is_empty() => checked_path(&game, a, inner)?, _ => game, }; if !path.is_dir() { + // Only a content folder that does not exist yet is created; a missing subfolder is an error. + if !inner.is_empty() { + return err("not-found", "This folder is not there any more."); + } fs::create_dir_all(&path).or_else(|e| err("io", e.to_string()))?; } shell_open(&path.to_string_lossy()) @@ -228,6 +367,112 @@ mod tests { assert!(content_path(game, "saves", "w").is_err()); } + fn scratch(name: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!("awake-mm-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + root + } + + #[test] + fn a_folder_lists_only_what_is_directly_inside_it_folders_first() { + let game = scratch("list"); + for file in ["config/b.toml", "config/A.toml", "config/jei/jei.toml", "config/jei/deep/x.cfg"] { + fs::create_dir_all(game.join(file).parent().unwrap()).unwrap(); + fs::write(game.join(file), "x = 1").unwrap(); + } + let root = content_path(&game, "config", "").unwrap(); + let top: Vec<(String, &str)> = list_folder(&root, &root).into_iter().map(|r| (r.path, r.kind)).collect(); + assert_eq!(top, [("jei".to_string(), "directory"), ("A.toml".to_string(), "file"), ("b.toml".to_string(), "file")]); + let inner: Vec = list_folder(&root, &checked_path(&game, "config", "jei").unwrap()).into_iter().map(|r| r.path).collect(); + assert_eq!(inner, ["jei/deep", "jei/jei.toml"]); + assert!(list_folder(&root, &game.join("config").join("missing")).is_empty()); + fs::remove_dir_all(&game).unwrap(); + } + + #[test] + fn text_files_round_trip_and_keep_their_line_endings() { + let game = scratch("text"); + fs::create_dir_all(game.join("config")).unwrap(); + let path = checked_path(&game, "config", "a.toml").unwrap(); + fs::write(&path, "a = 1\r\nb = 2\r\n").unwrap(); + let opened = read_text(&path).unwrap(); + assert_eq!(opened.text, "a = 1\r\nb = 2\r\n"); + // The editor hands back plain line breaks. + write_text(&path, "a = 1\nb = 3\n", opened.modified_ms).unwrap(); + assert_eq!(fs::read_to_string(&path).unwrap(), "a = 1\r\nb = 3\r\n"); + assert_eq!(fs::read_dir(game.join("config")).unwrap().count(), 1, "no temp file left behind"); + // A stale editor cannot overwrite a newer file. + let now = read_text(&path).unwrap().modified_ms; + assert_eq!(write_text(&path, "old", now.wrapping_add(5000)).unwrap_err().code, "conflict"); + assert_eq!(fs::read_to_string(&path).unwrap(), "a = 1\r\nb = 3\r\n"); + let plain = game.join("config").join("plain.txt"); + fs::write(&plain, "x\ny\n").unwrap(); + write_text(&plain, "x\nz\n", read_text(&plain).unwrap().modified_ms).unwrap(); + assert_eq!(fs::read_to_string(&plain).unwrap(), "x\nz\n"); + fs::remove_dir_all(&game).unwrap(); + } + + #[test] + fn the_editor_refuses_what_is_not_an_editable_text_file() { + let game = scratch("refuse"); + let config = game.join("config"); + fs::create_dir_all(config.join("sub")).unwrap(); + fs::write(config.join("data.bin"), [0xffu8, 0xfe, 0x00, 0x41]).unwrap(); + fs::write(config.join("nul.txt"), b"a\0b").unwrap(); + fs::write(config.join("big.txt"), vec![b'a'; TEXT_MAX as usize + 1]).unwrap(); + assert_eq!(read_text(&config.join("data.bin")).unwrap_err().code, "not-text"); + assert_eq!(read_text(&config.join("nul.txt")).unwrap_err().code, "not-text"); + assert_eq!(read_text(&config.join("big.txt")).unwrap_err().code, "too-large"); + assert_eq!(read_text(&config.join("sub")).unwrap_err().code, "invalid"); + assert_eq!(read_text(&config.join("gone.txt")).unwrap_err().code, "not-found"); + // Saving never creates a file or replaces a folder. + assert_eq!(write_text(&config.join("gone.txt"), "x", 0).unwrap_err().code, "not-found"); + assert_eq!(write_text(&config.join("sub"), "x", 0).unwrap_err().code, "invalid"); + assert!(!config.join("gone.txt").exists()); + fs::remove_dir_all(&game).unwrap(); + } + + #[test] + fn adding_files_never_overwrites() { + let root = scratch("add"); + let (from, dir) = (root.join("from"), root.join("game").join("resourcepacks")); + fs::create_dir_all(&from).unwrap(); + fs::write(from.join("a.zip"), "new a").unwrap(); + fs::write(from.join("b.zip"), "new b").unwrap(); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("a.zip"), "old a").unwrap(); + let result = add_files(&dir, &[from.join("a.zip"), from.join("b.zip")]).unwrap(); + assert_eq!(result, AddedFiles { added: vec!["b.zip".into()], skipped: vec!["a.zip".into()] }); + assert_eq!(fs::read_to_string(dir.join("a.zip")).unwrap(), "old a"); + assert_eq!(fs::read_to_string(dir.join("b.zip")).unwrap(), "new b"); + assert_eq!(fs::read_dir(&dir).unwrap().count(), 2, "no temp file left behind"); + assert!(add_files(&dir, std::slice::from_ref(&from)).is_err(), "a folder is not a file"); + fs::remove_dir_all(&root).unwrap(); + } + + #[cfg(windows)] + #[test] + fn links_below_a_content_folder_are_not_followed() { + let game = scratch("links"); + let outside = scratch("links-outside"); + fs::create_dir_all(game.join("config").join("real")).unwrap(); + fs::write(outside.join("secret.txt"), "s").unwrap(); + let link = game.join("config").join("out"); + // A junction needs no special privilege, unlike a symbolic link. + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(&link).arg(&outside).output().is_ok_and(|o| o.status.success()); + assert!(made, "could not create a junction to test with"); + assert!(checked_path(&game, "config", "out/secret.txt").is_err()); + assert!(checked_path(&game, "config", "out").is_err()); + let root = game.join("config"); + assert_eq!(list_folder(&root, &root).into_iter().map(|r| r.path).collect::>(), ["real"]); + fs::remove_dir(&link).unwrap(); + assert!(checked_path(&game, "config", "real/x.toml").is_ok()); + assert!(checked_path(&game, "config", "../mods/a.jar").is_err()); + fs::remove_dir_all(&game).unwrap(); + fs::remove_dir_all(&outside).unwrap(); + } + #[test] fn forgetting_missing_mods_drops_only_records_without_a_file() { let root = std::env::temp_dir().join(format!("awake-mm-forget-{}", std::process::id())); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 61119c3..de6fee3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -2,11 +2,13 @@ //! //! The host is deliberately thin: it discovers Launcher data profiles, opens the Launcher's //! integration named pipe, starts and verifies the Manager's own native helper, and moves -//! length-prefixed frames. All protocol semantics live in TypeScript (`src/backend`). It never reads -//! or writes instance files: its only writes are a user-chosen export file and the Manager's -//! project store (`files.rs`). The one change to a Launcher folder is its Windows permissions, when -//! the user confirms it (`profile_access.rs`). +//! length-prefixed frames. All protocol semantics live in TypeScript (`src/backend`). It never changes +//! mods: those belong to the helper. Its writes are a user-chosen export file, the Manager's +//! project store (`files.rs`), and non-mod content the user edits, adds or installs on the Files and +//! Browse pages (`desktop.rs`, `content.rs`). The one other change to a Launcher folder is its +//! Windows permissions, when the user confirms it (`profile_access.rs`). +mod content; mod desktop; mod discovery; mod files; @@ -105,6 +107,12 @@ pub fn run() { export::export_instance, desktop::workspace_list, desktop::workspace_recycle, + desktop::workspace_read_text, + desktop::workspace_write_text, + desktop::workspace_add_files, + content::content_search, + content::content_versions, + content::content_install, desktop::workspace_forget_missing, desktop::workspace_open, desktop::open_url, diff --git a/src-tauri/src/providers.rs b/src-tauri/src/providers.rs index 4c7620b..43a1a46 100644 --- a/src-tauri/src/providers.rs +++ b/src-tauri/src/providers.rs @@ -51,7 +51,7 @@ pub fn agent(timeout: u64) -> ureq::Agent { ureq::Agent::config_builder().tls_config(ureq::tls::TlsConfig::builder().provider(ureq::tls::TlsProvider::NativeTls).root_certs(ureq::tls::RootCerts::PlatformVerifier).build()).timeout_global(Some(Duration::from_secs(timeout))).max_redirects(6).http_status_as_error(false).user_agent(USER_AGENT).build().into() } -fn status_error(host: &str, status: u16) -> HostResult { +pub(crate) fn status_error(host: &str, status: u16) -> HostResult { match status { 429 => err("rate-limited", format!("{host} is rate limiting requests. Try again in a minute.")), 401 | 403 | 451 => err("restricted", format!("{host} refused this request (HTTP {status}).")), @@ -59,7 +59,7 @@ fn status_error(host: &str, status: u16) -> HostResult { _ => err("network", format!("{host} request failed (HTTP {status}).")), } } -fn host_of(url: &str) -> String { +pub(crate) fn host_of(url: &str) -> String { url.split("://").nth(1).and_then(|r| r.split('/').next()).unwrap_or(url).to_string() } @@ -78,7 +78,7 @@ pub fn get_json(url: &str) -> HostResult { fn cf_key() -> HostResult { curseforge_key().ok_or(HostError { code: "curseforge-disabled", message: "This build has no authorized CurseForge access.".into() }) } -fn cf_get(path: &str) -> HostResult { +pub(crate) fn cf_get(path: &str) -> HostResult { let url = format!("{CURSEFORGE}{path}"); let response = agent(45).get(&url).header("x-api-key", &cf_key()?).header("Accept", "application/json").call().or_else(|e| err("network", format!("CurseForge: {e}")))?; read_json(&url, response) @@ -93,14 +93,14 @@ pub fn cf_post(path: &str, body: &Value) -> HostResult { let response = agent(60).post(&url).header("x-api-key", &cf_key()?).header("Accept", "application/json").send_json(body).or_else(|e| err("network", format!("CurseForge: {e}")))?; read_json(&url, response) } -fn encode(v: &str) -> String { +pub(crate) fn encode(v: &str) -> String { v.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() } -fn s<'a>(v: &'a Value, k: &str) -> &'a str { +pub(crate) fn s<'a>(v: &'a Value, k: &str) -> &'a str { v[k].as_str().unwrap_or("") } /// A pack ID goes into a URL path: allow only what providers actually issue. -fn safe_id(id: &str) -> HostResult<&str> { +pub(crate) fn safe_id(id: &str) -> HostResult<&str> { if !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.+ ".contains(&b)) { Ok(id) } else { err("invalid", "This pack identifier is not valid.") } } @@ -153,7 +153,7 @@ fn cf_loader(n: i64) -> Option { } .map(str::to_string) } -fn release_name(n: i64) -> Option { +pub(crate) fn release_name(n: i64) -> Option { match n { 1 => Some("release"), 2 => Some("beta"), @@ -406,7 +406,7 @@ pub fn pack_providers() -> Vec { }).collect() } -async fn blocking(f: impl FnOnce() -> HostResult + Send + 'static) -> HostResult { +pub(crate) async fn blocking(f: impl FnOnce() -> HostResult + Send + 'static) -> HostResult { tauri::async_runtime::spawn_blocking(f).await.unwrap_or_else(|e| err("internal", e.to_string())) } @@ -463,7 +463,7 @@ struct Progress { total: u64, } -struct Job { +pub(crate) struct Job { app: tauri::AppHandle, id: String, cancel: Arc, @@ -500,7 +500,7 @@ pub fn hex(bytes: &[u8]) -> String { } /// Download `url` to `to`, enforcing a size limit and cancellation. -fn download(job: Option<&Job>, url: &str, headers: &[(&str, String)], to: &Path, limit: u64, mut progress: impl FnMut(u64)) -> HostResult<()> { +pub(crate) fn download(job: Option<&Job>, url: &str, headers: &[(&str, String)], to: &Path, limit: u64, mut progress: impl FnMut(u64)) -> HostResult<()> { // Provider file URLs often contain raw spaces or brackets. let url = &url.replace(' ', "%20").replace('[', "%5B").replace(']', "%5D"); let mut last = None; diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 722cfbe..f7461ac 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.2.3", + "version": "1.3.0", "identifier": "io.github.awakenginexe.AwakeModpackManager", "build": { "frontendDist": "../dist", diff --git a/src/App.vue b/src/App.vue index 6881bc5..f13dc39 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,6 +1,6 @@