launcher: Download and prepare, from Mojang, for an account that owns the game
With the owner gate in place, a signed-in owner no longer needs another launcher first (brief mc-download-1, Ludovic 2026-10-27). - The Play page's Resources row offers an owner "Download and prepare" and "From my install"; without an owner it asks to sign in first. - `horizon-launcher prepare --download` does the same. - Every file from Mojang must have the size and sha1 Mojang lists. - The download shows its progress and has Cancel; files already whole are kept, so the next try goes on where it stopped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -36,11 +36,12 @@ MCP: `remove`, needs `confirm: true`.
|
||||
|
||||
## `horizon-launcher prepare`
|
||||
|
||||
Prepare a version's resources from your own Minecraft install.
|
||||
Prepare a version's resources from your own Minecraft install, or from Mojang.
|
||||
|
||||
horizon-launcher prepare
|
||||
|
||||
- `--minecraft`: The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher (default: the launcher's, then every launcher's default)
|
||||
- `--download`: Download Minecraft from Mojang for the signed-in account that owns it, instead of using an install
|
||||
|
||||
MCP: `prepare`.
|
||||
|
||||
|
||||
@@ -93,6 +93,17 @@ possible; the launcher just doesn't offer it on its own.
|
||||
the launcher's tests use accounts in a memory store (`MemoryStore`, and `HORIZON_NO_KEYCHAIN`
|
||||
for the CLI and MCP tests, which then have no owner).
|
||||
|
||||
## Downloading the game for an owner
|
||||
|
||||
Decided 2026-10-27. This is the only exception to "Horizon never downloads the game", and it
|
||||
applies only on the player's machine, for an account the owner gate just asked about. The
|
||||
launcher's "Download and prepare" (`horizon-launcher prepare --download`) fetches the pinned
|
||||
version straight from Mojang (`launcher/src/mojang.rs`): the version file, the client jar,
|
||||
libraries, the asset index and the assets, each checked against the size and sha1 Mojang lists.
|
||||
They go to `minecraft/` in the launcher's data folder, and the preparation runs as usual. The
|
||||
download can be cancelled and goes on where it stopped. CI, agents, harnesses and the repo never
|
||||
download or keep Mojang's files.
|
||||
|
||||
Refresh: the Minecraft token is renewed from the Microsoft refresh token (steps 2-5 with
|
||||
`grant_type=refresh_token`) when it has less than an hour left, before every launch; steps 6-7 run
|
||||
at every launch (the owner gate). A refused
|
||||
|
||||
@@ -24,6 +24,15 @@ The opening, then Play ([clip](docs/opening.webm)):
|
||||
preparation reuses checksum-verified game jars and libraries from the current
|
||||
or another installed Horizon version, so the original Minecraft install is
|
||||
only required when no valid imported copy exists.
|
||||
- **Download and prepare**: for a signed-in account that owns the game (asked again first),
|
||||
the launcher downloads the pinned version from Mojang itself (piston-meta, piston-data,
|
||||
libraries.minecraft.net, resources.download.minecraft.net; never a mirror) into `minecraft/`
|
||||
in its data folder, in the official launcher's layout: the version file, the client jar, this
|
||||
system's libraries, the asset index and the assets. Every file must have the size and sha1
|
||||
Mojang lists. The Play page shows how far it is and has Cancel; files already whole are kept,
|
||||
so the next try goes on from there. **From my install** prepares from the player's own launcher
|
||||
instead, and an install that lacks the version falls back to the download. Without an owner,
|
||||
the Play page asks to sign in first. `horizon-launcher prepare --download`.
|
||||
- **Mods**: search Modrinth (CurseForge support is coming soon) for resource
|
||||
packs and modpacks, each marked Works, Partly or Doesn't run in
|
||||
Horizon; Java mod jars are never offered. Install puts a pack and what it needs in
|
||||
|
||||
@@ -171,5 +171,10 @@
|
||||
"Not now": "Pas maintenant",
|
||||
"Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers.": "Horizon a besoin d'un compte Microsoft qui possède Minecraft: Java Edition, comme les autres launchers.",
|
||||
"Your worlds, offline names and settings stay where they are.": "Vos mondes, vos noms hors ligne et vos réglages restent où ils sont.",
|
||||
"Open {link} in your browser and enter this code:": "Ouvrez {link} dans votre navigateur et entrez ce code :"
|
||||
"Open {link} in your browser and enter this code:": "Ouvrez {link} dans votre navigateur et entrez ce code :",
|
||||
"From my install": "Depuis mon installation",
|
||||
"Download and prepare": "Télécharger et préparer",
|
||||
"Not prepared. Horizon can download Minecraft {version} from Mojang for your account, or use your own install.": "Pas préparé. Horizon peut télécharger Minecraft {version} depuis Mojang pour votre compte, ou utiliser votre propre installation.",
|
||||
"Not prepared. Sign in with the Microsoft account that owns Minecraft {version} first.": "Pas préparé. Connectez-vous d'abord avec le compte Microsoft qui possède Minecraft {version}.",
|
||||
"Cancel": "Annuler"
|
||||
}
|
||||
|
||||
@@ -171,5 +171,10 @@
|
||||
"Not now": "Не сейчас",
|
||||
"Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers.": "Как и другим лаунчерам, Horizon нужен аккаунт Microsoft, у которого есть Minecraft: Java Edition.",
|
||||
"Your worlds, offline names and settings stay where they are.": "Ваши миры, офлайн-имена и настройки остаются на месте.",
|
||||
"Open {link} in your browser and enter this code:": "Откройте {link} в браузере и введите этот код:"
|
||||
"Open {link} in your browser and enter this code:": "Откройте {link} в браузере и введите этот код:",
|
||||
"From my install": "Из моей установки",
|
||||
"Download and prepare": "Скачать и подготовить",
|
||||
"Not prepared. Horizon can download Minecraft {version} from Mojang for your account, or use your own install.": "Не подготовлено. Horizon может скачать Minecraft {version} у Mojang для вашего аккаунта или взять вашу установку.",
|
||||
"Not prepared. Sign in with the Microsoft account that owns Minecraft {version} first.": "Не подготовлено. Сначала войдите в аккаунт Microsoft, у которого есть Minecraft {version}.",
|
||||
"Cancel": "Отмена"
|
||||
}
|
||||
|
||||
+30
-11
@@ -1227,7 +1227,7 @@ fn download_for_owner(
|
||||
sources::Os::MacOs => "osx",
|
||||
sources::Os::Windows => "windows",
|
||||
};
|
||||
mojang::download(pins, dir, os, 8, fetch, log).map_err(|e| {
|
||||
mojang::download(pins, dir, os, 8, fetch, &mojang::CANCEL, log).map_err(|e| {
|
||||
format!("\n • Horizon tried to download {v} from Mojang for {name}, but: {e}")
|
||||
})
|
||||
}
|
||||
@@ -1299,7 +1299,8 @@ fn java(
|
||||
Ok(body)
|
||||
};
|
||||
let runtime = data_dir().join("minecraft").join("runtime");
|
||||
let home = mojang::java_runtime(&component, &runtime, 8, &fetch, log).map_err(|e| {
|
||||
let home = mojang::java_runtime(&component, &runtime, 8, &fetch, &mojang::CANCEL, log)
|
||||
.map_err(|e| {
|
||||
format!("{missing}\n • Horizon also tried to download Minecraft's own Java from Mojang, but: {e}")
|
||||
})?;
|
||||
find(major, &[home]).map(|jdk| jdk.home())
|
||||
@@ -1351,6 +1352,16 @@ fn assets_folder(
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the preparation takes Minecraft's files from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MinecraftFrom {
|
||||
/// The player's own install (any launcher's); Mojang only when none has the version and an
|
||||
/// account that owns the game is signed in.
|
||||
Install,
|
||||
/// Mojang, for the signed-in account that owns the game ("Download and prepare").
|
||||
Mojang,
|
||||
}
|
||||
|
||||
/// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same
|
||||
/// steps: the player's own launcher install, the server jar from that version's own json, and
|
||||
/// Java (and Python, for versions before horizon-prepare). Also returns the Minecraft folder
|
||||
@@ -1359,6 +1370,7 @@ fn assets_folder(
|
||||
pub fn preparer(
|
||||
tag: &str,
|
||||
minecraft: &Path,
|
||||
from: MinecraftFrom,
|
||||
log: &dyn Fn(String),
|
||||
) -> Result<(Preparer, PathBuf), String> {
|
||||
let version = game_version(tag);
|
||||
@@ -1386,16 +1398,23 @@ pub fn preparer(
|
||||
Ok(body)
|
||||
};
|
||||
let linked = data_dir().join("linked-minecraft");
|
||||
let resolved = sources::resolve(minecraft, &pins, &known, &linked, &fetch, log);
|
||||
if reused {
|
||||
assets_folder(resolved, &chosen, &version, log)
|
||||
if from == MinecraftFrom::Mojang {
|
||||
// Straight from Mojang (what is already there and whole is kept), for an owner only.
|
||||
download_for_owner(&pins, &own, &fetch, log)
|
||||
.map_err(|e| e.trim_start_matches("\n • ").to_string())?;
|
||||
own
|
||||
} else {
|
||||
match resolved? {
|
||||
sources::Resolved::Folder(dir) => dir,
|
||||
sources::Resolved::NotFound(checked) => {
|
||||
let not_found = sources::not_found(&version, &checked, minecraft);
|
||||
download_for_owner(&pins, &own, &fetch, log).map_err(|e| not_found + &e)?;
|
||||
own
|
||||
let resolved = sources::resolve(minecraft, &pins, &known, &linked, &fetch, log);
|
||||
if reused {
|
||||
assets_folder(resolved, &chosen, &version, log)
|
||||
} else {
|
||||
match resolved? {
|
||||
sources::Resolved::Folder(dir) => dir,
|
||||
sources::Resolved::NotFound(checked) => {
|
||||
let not_found = sources::not_found(&version, &checked, minecraft);
|
||||
download_for_owner(&pins, &own, &fetch, log).map_err(|e| not_found + &e)?;
|
||||
own
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-4
@@ -548,12 +548,16 @@ enum Cmd {
|
||||
Install { tag: String },
|
||||
/// Remove an installed version
|
||||
Remove { tag: String },
|
||||
/// Prepare a version's resources from your own Minecraft install
|
||||
/// Prepare a version's resources from your own Minecraft install, or from Mojang
|
||||
Prepare {
|
||||
/// The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App,
|
||||
/// ATLauncher or GDLauncher (default: the launcher's, then every launcher's default)
|
||||
#[arg(long)]
|
||||
#[arg(long, conflicts_with = "download")]
|
||||
minecraft: Option<PathBuf>,
|
||||
/// Download Minecraft from Mojang for the signed-in account that owns it, instead of
|
||||
/// using an install
|
||||
#[arg(long)]
|
||||
download: bool,
|
||||
/// The installed version (default: the selected one)
|
||||
#[arg(long)]
|
||||
version: Option<String>,
|
||||
@@ -974,11 +978,20 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
backend::remove_version(&tag)?;
|
||||
println!("Removed {tag}.");
|
||||
}
|
||||
Cmd::Prepare { minecraft, version } => {
|
||||
Cmd::Prepare {
|
||||
minecraft,
|
||||
download,
|
||||
version,
|
||||
} => {
|
||||
let tag = backend::resolve_version(version.as_deref())?;
|
||||
let minecraft = backend::minecraft_dir(minecraft)?;
|
||||
let from = if download {
|
||||
backend::MinecraftFrom::Mojang
|
||||
} else {
|
||||
backend::MinecraftFrom::Install
|
||||
};
|
||||
let (preparer, minecraft) =
|
||||
backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
|
||||
backend::preparer(&tag, &minecraft, from, &|line| eprintln!("{line}"))?;
|
||||
backend::sounds(&tag, &minecraft, &|line| println!("{line}"));
|
||||
match preparer {
|
||||
backend::Preparer::Process(cmd) => attached(cmd)?,
|
||||
|
||||
+78
-8
@@ -1021,10 +1021,13 @@ impl Launcher {
|
||||
});
|
||||
}
|
||||
|
||||
fn prepare(&mut self) {
|
||||
/// Prepares the selected version, its Minecraft files from the player's install or, for an
|
||||
/// owner who asks, from Mojang.
|
||||
fn prepare(&mut self, from: backend::MinecraftFrom) {
|
||||
let Some(tag) = self.selected().cloned() else {
|
||||
return;
|
||||
};
|
||||
horizon_launcher::mojang::CANCEL.store(false, Ordering::Relaxed);
|
||||
let minecraft = self
|
||||
.settings
|
||||
.minecraft_dir
|
||||
@@ -1040,7 +1043,7 @@ impl Launcher {
|
||||
let log = |line| {
|
||||
let _ = tx.send(Msg::Line(Job::Prepare, line));
|
||||
};
|
||||
let result = backend::preparer(&tag, &minecraft, &log)
|
||||
let result = backend::preparer(&tag, &minecraft, from, &log)
|
||||
.inspect(|(_, minecraft)| backend::sounds(&tag, minecraft, &log))
|
||||
.and_then(|(p, _)| match p {
|
||||
backend::Preparer::Process(cmd) => {
|
||||
@@ -2232,10 +2235,22 @@ impl Launcher {
|
||||
.child(play),
|
||||
);
|
||||
|
||||
let resources_value = if self.preparing {
|
||||
tr("Preparing…").to_string()
|
||||
} else {
|
||||
backend::resources_summary(prepared, !silent, &version)
|
||||
// Not prepared: an owner can have Horizon download Minecraft from Mojang; without an
|
||||
// owner there is nothing to play, so signing in comes first.
|
||||
let first = (!prepared && !self.preparing)
|
||||
.then_some(self.owner)
|
||||
.flatten();
|
||||
let resources_value = match first {
|
||||
_ if self.preparing => tr("Preparing…").to_string(),
|
||||
Some(true) => trf(
|
||||
"Not prepared. Horizon can download Minecraft {version} from Mojang for your account, or use your own install.",
|
||||
&[("version", &version)],
|
||||
),
|
||||
Some(false) => trf(
|
||||
"Not prepared. Sign in with the Microsoft account that owns Minecraft {version} first.",
|
||||
&[("version", &version)],
|
||||
),
|
||||
None => backend::resources_summary(prepared, !silent, &version),
|
||||
};
|
||||
let mut prepare = button(
|
||||
"prepare",
|
||||
@@ -2251,10 +2266,44 @@ impl Launcher {
|
||||
prepare = disabled(prepare);
|
||||
} else {
|
||||
prepare = prepare.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.prepare();
|
||||
this.prepare(backend::MinecraftFrom::Install);
|
||||
cx.notify();
|
||||
}));
|
||||
}
|
||||
let prepare = match first {
|
||||
Some(true) => div()
|
||||
.flex()
|
||||
.gap(px(8.))
|
||||
.child(
|
||||
button("prepare-install", "From my install", Kind::Ghost, &t).on_click(
|
||||
cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.prepare(backend::MinecraftFrom::Install);
|
||||
cx.notify();
|
||||
}),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
button(
|
||||
"prepare-download",
|
||||
"Download and prepare",
|
||||
Kind::Secondary,
|
||||
&t,
|
||||
)
|
||||
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.prepare(backend::MinecraftFrom::Mojang);
|
||||
cx.notify();
|
||||
})),
|
||||
),
|
||||
Some(false) => div().child(
|
||||
button("prepare-sign-in", "Sign in", Kind::Secondary, &t).on_click(cx.listener(
|
||||
|this, _: &ClickEvent, _, cx| {
|
||||
this.sign_in_to_play();
|
||||
cx.notify();
|
||||
},
|
||||
)),
|
||||
),
|
||||
None => div().child(prepare),
|
||||
};
|
||||
let minecraft = self.settings.minecraft_dir.as_deref().map_or_else(
|
||||
|| {
|
||||
div()
|
||||
@@ -2394,12 +2443,33 @@ impl Launcher {
|
||||
// looks after pressing Prepare, not below the fold (#666).
|
||||
if self.preparing {
|
||||
let last = self.prepare_log.back().cloned().unwrap_or_default();
|
||||
// A download from Mojang shows how far it is, and can stop (it goes on from there
|
||||
// next time).
|
||||
let download = horizon_launcher::mojang::progress();
|
||||
let cancel = download.map(|_| {
|
||||
button("download-cancel", "Cancel", Kind::Ghost, &t).on_click(|_, _, _| {
|
||||
horizon_launcher::mojang::CANCEL.store(true, Ordering::Relaxed)
|
||||
})
|
||||
});
|
||||
page = page.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(10.))
|
||||
.child(progress_bar(None, &t))
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(12.))
|
||||
.child(progress_bar(
|
||||
download.map(|(done, total)| {
|
||||
let f = done as f32 / total as f32;
|
||||
(f, f)
|
||||
}),
|
||||
&t,
|
||||
))
|
||||
.children(cancel),
|
||||
)
|
||||
.child(
|
||||
text(theme::MICRO)
|
||||
.text_color(t.muted)
|
||||
|
||||
+70
-15
@@ -3,12 +3,16 @@
|
||||
//! jar, this system's libraries and the assets (the sounds), each checked against its sha1,
|
||||
//! in the official launcher's layout in the launcher's data folder. sources.rs then finds them
|
||||
//! there like any launcher's. Nothing of Mojang's is part of Horizon.
|
||||
//!
|
||||
//! Each file is checked against the size and sha1 Mojang lists, and written whole. A download
|
||||
//! stopped half way (cancelled, no network) keeps the files it finished: the next one fetches
|
||||
//! only the rest.
|
||||
|
||||
use crate::sources::{fetch_checked, fetch_manifest, sha1_file, write_file, Fetch, Pins};
|
||||
use crate::sources::{fetch_checked, fetch_manifest, sha1_file, sha1_hex, write_file, Fetch, Pins};
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -16,22 +20,38 @@ const OBJECTS: &str = "https://resources.download.minecraft.net";
|
||||
/// The index of Mojang's Java runtimes, the one the official launcher reads.
|
||||
const JAVA_RUNTIMES: &str = "https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json";
|
||||
|
||||
/// One file to download.
|
||||
/// Set to stop the download under way (the window's Cancel); cleared when a preparation starts.
|
||||
pub static CANCEL: AtomicBool = AtomicBool::new(false);
|
||||
/// The download under way: files done, of how many (0 when none runs).
|
||||
static DONE: AtomicUsize = AtomicUsize::new(0);
|
||||
static TOTAL: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// How far the download under way is, files done of how many; none when none runs.
|
||||
pub fn progress() -> Option<(usize, usize)> {
|
||||
let total = TOTAL.load(Relaxed);
|
||||
(total > 0).then(|| (DONE.load(Relaxed).min(total), total))
|
||||
}
|
||||
|
||||
const CANCELLED: &str = "Download cancelled. Download again to go on where it stopped.";
|
||||
|
||||
/// One file to download, with the size Mojang lists for it when it lists one.
|
||||
struct File {
|
||||
url: String,
|
||||
sha1: String,
|
||||
size: Option<u64>,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
/// Downloads the pinned version into `dir`, `jobs` files at a time; files already there and
|
||||
/// whole are kept. An asset that fails is a line in the log (the game is then partly silent),
|
||||
/// anything else an error.
|
||||
/// anything else an error. `cancel` stops it between files.
|
||||
pub fn download(
|
||||
pins: &Pins,
|
||||
dir: &Path,
|
||||
os: &str,
|
||||
jobs: usize,
|
||||
fetch: Fetch,
|
||||
cancel: &AtomicBool,
|
||||
log: &dyn Fn(String),
|
||||
) -> Result<(), String> {
|
||||
let v = &pins.version;
|
||||
@@ -43,6 +63,7 @@ pub fn download(
|
||||
let mut game = vec![File {
|
||||
url: text(client, "url")?,
|
||||
sha1: pins.client_sha1.clone(),
|
||||
size: client["size"].as_u64(),
|
||||
path: versions.join(format!("{v}.jar")),
|
||||
}];
|
||||
let libraries = manifest["libraries"]
|
||||
@@ -56,6 +77,7 @@ pub fn download(
|
||||
game.push(File {
|
||||
url: text(artifact, "url")?,
|
||||
sha1: text(artifact, "sha1")?,
|
||||
size: artifact["size"].as_u64(),
|
||||
path: dir
|
||||
.join("libraries")
|
||||
.join(relative(&text(artifact, "path")?)?),
|
||||
@@ -65,23 +87,26 @@ pub fn download(
|
||||
"Downloading Minecraft {v} from Mojang: the game and {} libraries",
|
||||
game.len() - 1
|
||||
));
|
||||
fetch_all(&game, jobs, fetch, log)?;
|
||||
fetch_all(&game, jobs, fetch, cancel, log)?;
|
||||
let index = &manifest["assetIndex"];
|
||||
let index = File {
|
||||
url: text(index, "url")?,
|
||||
sha1: text(index, "sha1")?,
|
||||
size: index["size"].as_u64(),
|
||||
path: dir
|
||||
.join("assets/indexes")
|
||||
.join(relative(&format!("{}.json", text(index, "id")?))?),
|
||||
};
|
||||
let assets = fetch_all(std::slice::from_ref(&index), 1, fetch, log)
|
||||
let assets = fetch_all(std::slice::from_ref(&index), 1, fetch, cancel, log)
|
||||
.and_then(|_| objects(&read_json(&index.path)?, dir))
|
||||
.and_then(|objects| {
|
||||
log(format!("Downloading the sounds ({} files)", objects.len()));
|
||||
fetch_all(&objects, jobs, fetch, log)
|
||||
fetch_all(&objects, jobs, fetch, cancel, log)
|
||||
});
|
||||
if let Err(e) = assets {
|
||||
log(format!("The sounds could not all be downloaded: {e}"));
|
||||
match assets {
|
||||
Err(e) if e == CANCELLED => return Err(e),
|
||||
Err(e) => log(format!("The sounds could not all be downloaded: {e}")),
|
||||
Ok(()) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -110,6 +135,7 @@ pub fn java_runtime(
|
||||
runtime: &Path,
|
||||
jobs: usize,
|
||||
fetch: Fetch,
|
||||
cancel: &AtomicBool,
|
||||
log: &dyn Fn(String),
|
||||
) -> Result<PathBuf, String> {
|
||||
let platform = java_platform().ok_or("Mojang has no Java for this system")?;
|
||||
@@ -144,6 +170,7 @@ pub fn java_runtime(
|
||||
downloads.push(File {
|
||||
url: text(raw, "url")?,
|
||||
sha1: text(raw, "sha1")?,
|
||||
size: raw["size"].as_u64(),
|
||||
path,
|
||||
});
|
||||
}
|
||||
@@ -156,7 +183,7 @@ pub fn java_runtime(
|
||||
"Downloading Minecraft's Java {name} from Mojang ({} files)",
|
||||
downloads.len()
|
||||
));
|
||||
fetch_all(&downloads, jobs, fetch, log)?;
|
||||
fetch_all(&downloads, jobs, fetch, cancel, log)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
@@ -243,6 +270,10 @@ fn objects(index: &Value, dir: &Path) -> Result<Vec<File>, String> {
|
||||
let objects = index["objects"]
|
||||
.as_object()
|
||||
.ok_or("The asset index has no objects")?;
|
||||
let sizes: std::collections::HashMap<&str, u64> = objects
|
||||
.values()
|
||||
.filter_map(|o| Some((o["hash"].as_str()?, o["size"].as_u64()?)))
|
||||
.collect();
|
||||
let mut hashes: Vec<&str> = objects
|
||||
.values()
|
||||
.filter_map(|o| o["hash"].as_str())
|
||||
@@ -259,23 +290,42 @@ fn objects(index: &Value, dir: &Path) -> Result<Vec<File>, String> {
|
||||
Ok(File {
|
||||
url: format!("{OBJECTS}/{path}"),
|
||||
sha1: hash.to_string(),
|
||||
size: sizes.get(hash).copied(),
|
||||
path: dir.join("assets/objects").join(path),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Downloads the files not already there, `jobs` at a time, with a line every few seconds;
|
||||
/// stops at the first error.
|
||||
/// One file from Mojang, refused unless it has the size and sha1 Mojang lists.
|
||||
fn fetch_file(fetch: Fetch, file: &File) -> Result<Vec<u8>, String> {
|
||||
let body = fetch(&file.url)?;
|
||||
if let Some(size) = file.size.filter(|&size| size != body.len() as u64) {
|
||||
return Err(format!(
|
||||
"is {} bytes, not the {size} Mojang lists",
|
||||
body.len()
|
||||
));
|
||||
}
|
||||
match sha1_hex(&body) {
|
||||
actual if actual == file.sha1 => Ok(body),
|
||||
actual => Err(format!("is not the one Horizon pins (sha1 {actual})")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads the files not already there, `jobs` at a time, with a line every second; stops at
|
||||
/// the first error, or between files once `cancel` is set.
|
||||
fn fetch_all(
|
||||
files: &[File],
|
||||
jobs: usize,
|
||||
fetch: Fetch,
|
||||
cancel: &AtomicBool,
|
||||
log: &dyn Fn(String),
|
||||
) -> Result<(), String> {
|
||||
let next = AtomicUsize::new(0);
|
||||
let done = AtomicUsize::new(0);
|
||||
let failed = Mutex::new(None);
|
||||
DONE.store(0, Relaxed);
|
||||
TOTAL.store(files.len(), Relaxed);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = (0..jobs.clamp(1, files.len().max(1)))
|
||||
.map(|_| {
|
||||
@@ -284,15 +334,19 @@ fn fetch_all(
|
||||
if failed.lock().unwrap().is_some() {
|
||||
break;
|
||||
}
|
||||
if cancel.load(Relaxed) {
|
||||
failed.lock().unwrap().get_or_insert(CANCELLED.to_string());
|
||||
break;
|
||||
}
|
||||
if sha1_file(&file.path).as_ref() != Some(&file.sha1) {
|
||||
let got = fetch_checked(fetch, &file.url, &file.sha1)
|
||||
let got = fetch_file(fetch, file)
|
||||
.map_err(|e| format!("{} {e}", file.url))
|
||||
.and_then(|body| write_file(&file.path, &body));
|
||||
if let Err(e) = got {
|
||||
failed.lock().unwrap().get_or_insert(e);
|
||||
}
|
||||
}
|
||||
done.fetch_add(1, Relaxed);
|
||||
DONE.store(done.fetch_add(1, Relaxed) + 1, Relaxed);
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -301,11 +355,12 @@ fn fetch_all(
|
||||
while !workers.iter().all(|w| w.is_finished()) {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
waited += 1;
|
||||
if waited % 50 == 0 {
|
||||
if waited % 10 == 0 {
|
||||
log(format!("{} of {} files", done.load(Relaxed), files.len()));
|
||||
}
|
||||
}
|
||||
});
|
||||
TOTAL.store(0, Relaxed);
|
||||
failed.into_inner().unwrap().map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
|
||||
+137
-11
@@ -8,6 +8,8 @@ const COMMON: &[u8] = b"a library every system uses";
|
||||
const LINUX: &[u8] = b"a linux native";
|
||||
const SOUND: &[u8] = b"a fake ogg";
|
||||
const LANG: &[u8] = b"{}";
|
||||
/// Never cancelled.
|
||||
static GO: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// The fake version file, asset index and files, by URL.
|
||||
fn mojang() -> (Pins, HashMap<String, Vec<u8>>) {
|
||||
@@ -28,7 +30,7 @@ fn mojang() -> (Pins, HashMap<String, Vec<u8>>) {
|
||||
"id": "26.3",
|
||||
"assetIndex": {"id": "34", "sha1": sha1_hex(index.as_bytes()),
|
||||
"url": "https://piston-meta.mojang.com/v1/packages/i/34.json"},
|
||||
"downloads": {"client": {"sha1": sha1_hex(CLIENT), "url": "https://piston-data.mojang.com/client.jar"}},
|
||||
"downloads": {"client": {"sha1": sha1_hex(CLIENT), "size": CLIENT.len(), "url": "https://piston-data.mojang.com/client.jar"}},
|
||||
"libraries": [
|
||||
{"name": "org.fake:common:1", "downloads": {"artifact": artifact("common", COMMON)}},
|
||||
{"name": "org.fake:linux:1", "downloads": {"artifact": artifact("linux", LINUX)},
|
||||
@@ -112,9 +114,15 @@ fn an_owner_gets_the_official_layout_with_this_systems_libraries() {
|
||||
};
|
||||
let dir = scratch("layout");
|
||||
let logged = Mutex::new(Vec::new());
|
||||
download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|line| {
|
||||
logged.lock().unwrap().push(line)
|
||||
})
|
||||
download(
|
||||
&pins,
|
||||
&dir,
|
||||
"linux",
|
||||
3,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|line| logged.lock().unwrap().push(line),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fs::read(dir.join("versions/26.3/26.3.jar")).unwrap(),
|
||||
@@ -156,7 +164,16 @@ fn an_owner_gets_the_official_layout_with_this_systems_libraries() {
|
||||
&|_| {},
|
||||
);
|
||||
assert_eq!(found, Ok(Resolved::Folder(dir.clone())));
|
||||
download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|_| {}).unwrap();
|
||||
download(
|
||||
&pins,
|
||||
&dir,
|
||||
"linux",
|
||||
3,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(server.asked(), Vec::<String>::new());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -169,7 +186,16 @@ fn macos_skips_what_its_rules_disallow() {
|
||||
asked: Mutex::new(Vec::new()),
|
||||
};
|
||||
let dir = scratch("osx");
|
||||
download(&pins, &dir, "osx", 2, &|url| server.fetch(url), &|_| {}).unwrap();
|
||||
download(
|
||||
&pins,
|
||||
&dir,
|
||||
"osx",
|
||||
2,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
let libraries = dir.join("libraries/org/fake");
|
||||
assert!(libraries.join("common/1/common-1.jar").is_file());
|
||||
assert!(!libraries.join("linux").exists());
|
||||
@@ -182,14 +208,23 @@ fn a_file_that_is_not_the_pinned_one_stops_the_download() {
|
||||
let (pins, mut files) = mojang();
|
||||
files.insert(
|
||||
"https://piston-data.mojang.com/client.jar".into(),
|
||||
b"something else".to_vec(),
|
||||
b"fake client JAR".to_vec(),
|
||||
);
|
||||
let server = Server {
|
||||
files,
|
||||
asked: Mutex::new(Vec::new()),
|
||||
};
|
||||
let dir = scratch("bad-jar");
|
||||
let error = download(&pins, &dir, "linux", 2, &|url| server.fetch(url), &|_| {}).unwrap_err();
|
||||
let error = download(
|
||||
&pins,
|
||||
&dir,
|
||||
"linux",
|
||||
2,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error.starts_with("https://piston-data.mojang.com/client.jar is not the one Horizon pins"),
|
||||
"{error}"
|
||||
@@ -209,9 +244,15 @@ fn missing_sounds_are_a_line_in_the_log_not_an_error() {
|
||||
};
|
||||
let dir = scratch("no-sound");
|
||||
let logged = Mutex::new(Vec::new());
|
||||
download(&pins, &dir, "linux", 1, &|url| server.fetch(url), &|line| {
|
||||
logged.lock().unwrap().push(line)
|
||||
})
|
||||
download(
|
||||
&pins,
|
||||
&dir,
|
||||
"linux",
|
||||
1,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|line| logged.lock().unwrap().push(line),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(dir.join("versions/26.3/26.3.jar").is_file());
|
||||
let last = logged.lock().unwrap().last().cloned().unwrap();
|
||||
@@ -290,6 +331,7 @@ fn java_runtime_lays_out_mojangs_runtime_with_its_executables_and_links() {
|
||||
&dir,
|
||||
2,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -316,6 +358,7 @@ fn java_runtime_lays_out_mojangs_runtime_with_its_executables_and_links() {
|
||||
&dir,
|
||||
2,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -325,8 +368,91 @@ fn java_runtime_lays_out_mojangs_runtime_with_its_executables_and_links() {
|
||||
&dir,
|
||||
2,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|_| {}
|
||||
)
|
||||
.is_err());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_of_another_size_than_mojang_lists_is_refused() {
|
||||
let (pins, mut files) = mojang();
|
||||
// A cut-off body: its size says so before its sha1.
|
||||
files.insert(
|
||||
"https://piston-data.mojang.com/client.jar".into(),
|
||||
CLIENT[..4].to_vec(),
|
||||
);
|
||||
let server = Server {
|
||||
files,
|
||||
asked: Mutex::new(Vec::new()),
|
||||
};
|
||||
let dir = scratch("size");
|
||||
let error = download(
|
||||
&pins,
|
||||
&dir,
|
||||
"linux",
|
||||
2,
|
||||
&|url| server.fetch(url),
|
||||
&GO,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error.ends_with(&format!(
|
||||
"is 4 bytes, not the {} Mojang lists",
|
||||
CLIENT.len()
|
||||
)),
|
||||
"{error}"
|
||||
);
|
||||
assert!(!dir.join("versions/26.3/26.3.jar").exists());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_download_goes_on_where_it_stopped() {
|
||||
let (pins, files) = mojang();
|
||||
let server = Server {
|
||||
files,
|
||||
asked: Mutex::new(Vec::new()),
|
||||
};
|
||||
let dir = scratch("cancel");
|
||||
let cancel = AtomicBool::new(false);
|
||||
// Cancelled once the client jar has arrived: one job, so nothing after it starts.
|
||||
let fetch = |url: &str| {
|
||||
let body = server.fetch(url);
|
||||
if url.ends_with("client.jar") {
|
||||
cancel.store(true, Relaxed);
|
||||
}
|
||||
body
|
||||
};
|
||||
let error = download(&pins, &dir, "linux", 1, &fetch, &cancel, &|_| {}).unwrap_err();
|
||||
assert_eq!(error, CANCELLED);
|
||||
assert_eq!(
|
||||
fs::read(dir.join("versions/26.3/26.3.jar")).unwrap(),
|
||||
CLIENT
|
||||
);
|
||||
assert!(!dir.join("libraries").exists());
|
||||
// Again: the version file and the jar are kept, only the rest is fetched.
|
||||
cancel.store(false, Relaxed);
|
||||
server.asked();
|
||||
download(
|
||||
&pins,
|
||||
&dir,
|
||||
"linux",
|
||||
1,
|
||||
&|url| server.fetch(url),
|
||||
&cancel,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
let asked = server.asked();
|
||||
assert!(
|
||||
!asked
|
||||
.iter()
|
||||
.any(|u| u.ends_with("client.jar") || u.ends_with("26.3.json")),
|
||||
"{asked:#?}"
|
||||
);
|
||||
assert_eq!(asked.len(), 6, "{asked:#?}");
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -782,7 +782,7 @@ impl Launcher {
|
||||
self.servers.create = None;
|
||||
self.go(Page::Play);
|
||||
if !self.preparing {
|
||||
self.prepare();
|
||||
self.prepare(backend::MinecraftFrom::Install);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user