Update to v0.1.3
Add `safe_download` option to `download_file`.
The function `save_version_manifest` will save to temp location and then replace path to the destination.
Add `check_core_file_exists_and_verify` and `validate_version_manifest` to `version_info.py`.
Add legacy assets check process code to assets.py (missing in the old version)

Launcher
Update to 0.0.9a0
All launching processes now will check core file hash before game started.
The legacy assets will be checked and redownloaded (if corrupted or missing)
Remove launched profile from `launching_profiles` record and cleanup.
Add online mode launching to TestPage.
Add some tests.
This commit is contained in:
wei committed 2026-10-22 21:28:29 +08:00
1 parent b7af7e3469
commit 77c4be7dcf
16 files changed
+1090 -238

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
__version__ = '0.1.2'
__version__ = '0.1.3'
__description__ = """
The core library of the *Launcher*
+146 -45
View File
@@ -1,14 +1,18 @@
from __future__ import annotations
import base64
import copy
import hashlib
import logging
import os
import platform
import random
import string
import zipfile
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import List
from typing import List, Type, Literal
import requests
@@ -20,6 +24,8 @@ THREADED_DOWNLOAD_MAX_WORKERS = 10
logger = logging.getLogger("Launcher.CoreLib")
SUPPORTED_HASH_ALGORITHMS = ["sha1", "sha256", "sha512", "md5"]
class FileObject:
def __init__(self, path: Path, url=None, sha1=None, sha256=None, sha512=None, md5=None, size=None):
self.__path = path
@@ -51,6 +57,16 @@ class FileObject:
return False
def replace_path(self, path: Path):
"""
Replace the target file path
This operation will invalidate the hash cache
:param path:
:return:
"""
self.__path = path
self.invalidate_hash_cache()
def is_same(self, file: FileObject, hash_name="sha256") -> bool:
if hash_name == "sha1":
return self.sha1 == file.sha1
@@ -101,9 +117,9 @@ class FileObject:
return self.sha512 == expected_hash if expected_hash else self.expected_sha512 == self.sha512
def verify_md5(self, expected_hash=None):
return self.md5 == expected_hash if expected_hash else self.expected_sha1 == self.md5
return self.md5 == expected_hash if expected_hash else self.expected_md5 == self.md5
def verify(self, algorithm, expected_hash=None):
def verify(self, algorithm: Literal["sha1", "sha256", "sha512", "md5"], expected_hash=None):
if algorithm == "sha1":
return self.verify_sha1(expected_hash if expected_hash else self.expected_sha1)
@@ -166,66 +182,117 @@ class FileObject:
self.__sha512 = None
self.__md5 = None
def generate_random_suffix():
return "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
def download_file(file: FileObject, overwrite=True, progress_callback: Callable[int]=None) -> FileObject | Exception:
def download_file(file: FileObject, overwrite=True, progress_callback: Callable[int]=None,
safe_download=True, max_temp_suffix_retry=5) -> FileObject | Exception:
"""
Download file from url
Download the file from url
:param file: File (Objected)
:param overwrite: Overwrite existing file
:param overwrite: Overwrites existing file
:param progress_callback: Callback function called with progress information
:param safe_download: Download the file at temp location. If hash matches, Replace the old one with the new one
:param max_temp_suffix_retry: Maximum number of retries for generating a unique temp file suffix
:return:
"""
file.path.parent.mkdir(parents=True, exist_ok=True)
def gen_random(path: Path):
suffix = generate_random_suffix()
new = path.with_suffix(path.suffix + "." + suffix)
if new.exists():
raise Exception("File already exists")
return new
if safe_download:
temp_path: Path | None = attempt(lambda: gen_random(file.path), Exception, max_temp_suffix_retry, logger)
if not temp_path:
raise DownloadException("Failed to generate unique temp file suffix")
target_file = copy.copy(file)
target_file.replace_path(temp_path)
else:
target_file = file
target_file.path.parent.mkdir(parents=True, exist_ok=True)
if file.exists and not overwrite:
raise FileExistsError("File {} already exists. Use overwrite=True to overwrite.".format(file))
raise FileExistsError("File {} already exists. Use overwrite=True to overwrite.".format(target_file))
if file.url is None:
raise ValueError("Target file {} URL cannot be None.".format(file))
if target_file.url is None:
raise ValueError("Target file {} URL cannot be None.".format(target_file))
logger.debug("Downloading file {} to {}".format(file.url, file))
logger.debug("Downloading file {} to {}".format(target_file.url, target_file))
file.invalidate_hash_cache() # Clean cache hash
try:
with requests.get(file.url, stream=True) as r:
r.raise_for_status()
current_chunk = 0
total_bytes = r.headers.get("content-length", None)
logger.debug("URL: {}".format(file.url))
logger.debug("Response code: {}".format(r.status_code))
target_file.invalidate_hash_cache() # Clean cache hash
try:
with requests.get(target_file.url, stream=True) as r:
r.raise_for_status()
current_chunk = 0
total_bytes = r.headers.get("content-length", None)
logger.debug("URL: {}".format(target_file.url))
logger.debug("Response code: {}".format(r.status_code))
with file.path.open("wb") as f:
for chunk in r.iter_content(chunk_size=DEFAULT_DOWNLOAD_CHUNK_SIZE):
if not chunk:
break
with target_file.path.open("wb") as f:
for chunk in r.iter_content(chunk_size=DEFAULT_DOWNLOAD_CHUNK_SIZE):
if not chunk:
break
f.write(chunk)
current_chunk += 1
f.write(chunk)
current_chunk += 1
if callable(progress_callback) and total_bytes is not None:
current_progress = ((current_chunk * DEFAULT_DOWNLOAD_CHUNK_SIZE) / int(total_bytes)) * 100
progress_callback(file.name, current_progress)
except Exception as e:
raise DownloadException(
"An error occurred while downloading file {}. {}".format(file.url, e)
)
if callable(progress_callback) and total_bytes is not None:
current_progress = ((current_chunk * DEFAULT_DOWNLOAD_CHUNK_SIZE) / int(total_bytes)) * 100
progress_callback(target_file.name, current_progress)
except Exception as e:
raise DownloadException(
"An error occurred while downloading file {}. {}".format(target_file.url, e)
)
finally:
target_file.invalidate_hash_cache()
if target_file.expected_sha256 and not target_file.verify_sha256():
raise HashMismatchException("sha256", target_file.sha256, target_file.expected_sha256,
target_file.posix_path)
elif target_file.expected_sha1 and not target_file.verify_sha1():
raise HashMismatchException("sha1", target_file.sha1, target_file.expected_sha1, target_file.posix_path)
elif target_file.expected_md5 and not target_file.verify_md5():
raise HashMismatchException("md5", target_file.md5, target_file.expected_md5, target_file.posix_path)
elif target_file.expected_sha512 and not target_file.verify_sha512():
raise HashMismatchException("sha512", target_file.sha512, target_file.expected_sha512,
target_file.posix_path)
if any([target_file.expected_sha1, target_file.expected_md5, target_file.expected_sha256]):
logger.debug("File hash is match as the expected hash.")
else:
logger.warning("Hash is not checked for file: {}".format(target_file.posix_path))
if safe_download:
try:
os.replace(target_file.path, file.path)
except Exception as e:
logger.error(f"Failed to replace file: {target_file.posix_path}. Error: {str(e)}")
if target_file.exists:
try:
os.remove(target_file.path)
except Exception as second_exc:
logger.error(f"Failed to remove temp file: {target_file.posix_path}. Error: {str(second_exc)}")
raise DownloadException(f"Failed to replace temp file {target_file.path} as {file.path}")
finally:
# Cleanup
file.invalidate_hash_cache()
if file.expected_sha256 and not file.verify_sha256():
raise HashMismatchException("sha256", file.sha256, file.expected_sha256, file.posix_path)
elif file.expected_sha1 and not file.verify_sha1():
raise HashMismatchException("sha1", file.sha1, file.expected_sha1, file.posix_path)
elif file.expected_md5 and not file.verify_md5():
raise HashMismatchException("md5", file.md5, file.expected_md5, file.posix_path)
elif file.expected_sha512 and not file.verify_sha512():
raise HashMismatchException("sha512", file.sha512, file.expected_sha512, file.posix_path)
if any([file.expected_sha1, file.expected_md5, file.expected_sha256]):
logger.debug("File hash is match as the expected hash.")
else:
logger.warning("Hash is not checked for file: {}".format(file.posix_path))
if safe_download:
try:
target_file.path.unlink(missing_ok=True)
except OSError as exc:
logger.warning("Unable to remove temporary download: %s", exc)
return file
@@ -337,4 +404,38 @@ def bytes_to_data_url(image_data: bytes, mime_type: str = "image/png",) -> str:
raise ValueError("mime_type must be a valid image MIME type")
encoded = base64.b64encode(image_data).decode("ascii")
return f"data:{mime_type};base64,{encoded}"
return f"data:{mime_type};base64,{encoded}"
def attempt(function: Callable, exceptions: Type[Exception],
retry: int = 10, logger_obj: logging.Logger | None = None):
"""
Attempt to execute a function with retries and logging.
:param function: The function to attempt. It should throw the specified exception that has written in exceptions
if failed.
:param exceptions: The exception type to catch.
:param retry: The number of retries.
:param logger_obj: The logger object for logging.
:return: The result of the function if successful, None otherwise.
"""
def log_info(message):
if logger_obj:
logger_obj.info(message)
else:
print("INFO: {}".format(message))
def log_error(message):
if logger_obj:
logger_obj.error(message)
else:
print("ERROR: {}".format(message))
for i in range(1, retry+1):
if i > 1:
log_info(f"Attempt {i-1} failed. Retrying...")
try:
return function()
except exceptions as e:
log_error(f"Attempt {i} failed: {e}")
return None
+3
View File
@@ -28,6 +28,9 @@ class HashMismatchException(Exception):
hash_name)
super().__init__(self.message)
class UnsupportedHashAlgorithmException(LauncherException):
user_message = "Unsupported hash algorithm."
class UnsupportedPlatformException(LauncherException):
user_message = "Current platform or architecture is not supported."
+38 -6
View File
@@ -169,6 +169,26 @@ def _check_asset(asset_id: str, asset_data: dict, relative_path: str, assets_dir
"size": expected_size,
}
# Check legacy asset
if legacy_context is not None:
destination: Path | None | FileObject = legacy_context["destination"]
if destination is None:
raise AssetManifestException("Invalid destination path")
if isinstance(destination, FileObject):
destination: Path = destination.path
if destination.is_file():
if no_hash_check and expected_size is not None:
destination_valid = destination.stat().st_size == expected_size
else:
file = FileObject(destination)
destination_valid = file.verify_sha1(hash_raw)
if destination_valid:
legacy_context = None
return file if needs_download else None, legacy_context
def collect_assets_from_manifest(manifest: dict, asset_id: str, assets_dir: Path, launcher_root: Path,
@@ -369,11 +389,23 @@ def download_assets(manifest: dict, assets_dir: Path, launcher_root: Path, no_ha
index_path = Path(assets_dir, "indexes", f"{asset_id}.json")
# Download and save asset manifest
asset_manifest = fetch_and_save_asset_manifest(
manifest,
index_path,
)
# Reuse a valid local index so repairing legacy copies can work offline.
asset_manifest = None
index_sha1 = asset_index.get("sha1")
if index_path.is_file():
try:
if not index_sha1 or FileObject(index_path).verify_sha1(index_sha1):
cached = json.loads(index_path.read_text(encoding="utf-8"))
if isinstance(cached, dict) and isinstance(cached.get("objects"), dict) and cached["objects"]:
asset_manifest = cached
except (OSError, ValueError):
logger.warning("Unable to read cached asset index: %s", index_path)
if asset_manifest is None:
asset_manifest = fetch_and_save_asset_manifest(manifest, index_path)
# Download assets files
assets, legacy_assets = collect_assets_from_manifest(
@@ -452,4 +484,4 @@ def find_correct_assets_dir(asset_id: str, assets_dir: Path, launcher_root: Path
if map_to_resources:
return launcher_root / "resources"
return assets_dir
return assets_dir
+112 -22
View File
@@ -1,14 +1,18 @@
import json
import logging
import tempfile
import warnings
from collections.abc import Callable
from pathlib import Path
from typing import Literal
import requests
from ..common.common import FileObject, download_file
from ..common.common import FileObject, download_file, SUPPORTED_HASH_ALGORITHMS
from ..common.exception import VersionManifestFetchException, NoVersionFoundException, \
NoSpecifiedVersionKeyException, VersionDataKeyNotFoundException, VersionManifestSaveException, HashMismatchException
NoSpecifiedVersionKeyException, VersionDataKeyNotFoundException, VersionManifestSaveException, \
HashMismatchException, UnsupportedHashAlgorithmException
from ..i18n import SUPPORTED_LANGUAGES
MOJANG_VERSION_MANIFEST_V2 = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"
MOJANG_VERSION_MANIFEST = "https://piston-meta.mojang.com/mc/game/version_manifest.json"
@@ -409,7 +413,33 @@ def get_core_file_download_url_and_hash(version_manifest: dict, is_server: bool=
return download_url, sha1
def save_version_manifest(manifest: dict, dest: Path, sha1: str | None=None) -> dict:
def validate_version_manifest(data: dict, version_id: str | None = None) -> None:
"""
Validate the version manifest
:param data:
:param version_id:
:return:
"""
if not isinstance(data, dict):
raise ValueError("Version manifest must be an object")
if version_id is None:
# Validate root manifest
versions = data.get("versions")
if not isinstance(versions, list) or any(
not isinstance(item, dict)
or not isinstance(item.get("id"), str) or not item["id"]
or not isinstance(item.get("url"), str) or not item["url"]
for item in versions
):
raise ValueError("Root manifest must contain a valid versions list")
elif (data.get("id") != version_id
or not any(isinstance(data.get(key), str) and data[key] for key in ("mainClass", "inheritsFrom"))):
# Validate specific version manifest
raise ValueError(f"Invalid manifest for version {version_id}")
def save_version_manifest(manifest: dict | bytes, dest: Path, sha1: str | None=None) -> dict:
"""
Save version manifest with hash verify
:param manifest:
@@ -418,21 +448,22 @@ def save_version_manifest(manifest: dict, dest: Path, sha1: str | None=None) ->
:return:
data: dict
"""
file = FileObject(
path=dest,
sha1=sha1,
)
dest.parent.mkdir(parents=True, exist_ok=True)
temporary = None
try:
method = "wb" if isinstance(manifest, bytes) else "w"
with dest.open(method) as f:
if isinstance(manifest, bytes):
f.write(manifest)
elif isinstance(manifest, dict):
json.dump(manifest, f)
payload = manifest if isinstance(manifest, bytes) else json.dumps(manifest).encode("utf-8")
data = json.loads(payload.decode("utf-8"))
if not isinstance(data, dict):
raise ValueError("Version manifest must be an object")
# Write manifest to temporary file and replace its path as destination
with tempfile.NamedTemporaryFile(dir=dest.parent, prefix=dest.name + ".", suffix=".tmp", delete=False) as f:
temporary = Path(f.name)
f.write(payload)
file = FileObject(temporary, sha1=sha1)
if sha1 is not None and not file.verify_sha1(sha1):
raise HashMismatchException(
"sha1",
@@ -441,16 +472,16 @@ def save_version_manifest(manifest: dict, dest: Path, sha1: str | None=None) ->
file.posix_path
)
if isinstance(manifest, bytes):
# Convert the data back to dict
return json.loads(manifest.decode("utf-8"))
else:
return manifest
temporary.replace(dest)
return data
except Exception as e:
logger.exception(e)
raise VersionManifestSaveException(
"Error saving version manifest:\n{}".format(e)
)
) from e
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
def fetch_and_save_version_manifest(dest: Path, target_version: str=None, root_manifest=None) -> dict | None:
"""
@@ -474,9 +505,16 @@ def fetch_and_save_version_manifest(dest: Path, target_version: str=None, root_m
data = root_manifest
sha1 = None
parsed = json.loads(data.decode("utf-8")) if isinstance(data, bytes) else data
if not isinstance(parsed, dict) or not isinstance(data, (bytes, dict)):
raise ValueError("Manifest is invalid after parsing or fetching.")
validate_version_manifest(parsed, target_version)
return save_version_manifest(data, dest, sha1)
def download_core_file(manifest: dict, destination: Path, is_server=False, raise_for_null_hash=False,
def download_core_file(manifest: dict, destination: Path, is_server=False, raise_for_null_hash=True,
progress_callback: Callable[[str, float], None]=None) -> FileObject:
"""
Download core file from version manifest.
@@ -491,7 +529,6 @@ def download_core_file(manifest: dict, destination: Path, is_server=False, raise
url, sha1 = get_core_file_download_url_and_hash(manifest, is_server=is_server)
destination.parent.mkdir(parents=True, exist_ok=True)
file = FileObject(destination, url=url)
if sha1 is None and raise_for_null_hash:
raise VersionDataKeyNotFoundException(
@@ -500,6 +537,8 @@ def download_core_file(manifest: dict, destination: Path, is_server=False, raise
elif sha1 is None:
logger.warning("Client has no sha1.")
file = FileObject(destination, url=url, sha1=sha1)
if file.exists and file.verify("sha1", sha1):
logger.info(f"Client existed and sha1 matches.")
elif url is not None:
@@ -511,6 +550,57 @@ def download_core_file(manifest: dict, destination: Path, is_server=False, raise
return file
def check_core_file_exists_and_verify(manifest: dict, core_file_path: Path,
is_server=False,
hash_required=True,
algorithm: Literal["sha1", "sha256", "sha512", "md5"]="sha1"):
"""
Check if the core file exists in the specified path and verify its hash.
:param algorithm:
:param manifest:
:param core_file_path:
:param is_server: True if the core file is for a server, False otherwise.
:param hash_required: True if the hash is required to be verified, False otherwise.
:return:
"""
_, _, downloads, _, _, _, _ = find_useful_part_in_specific_version_manifest(manifest)
if not core_file_path.exists():
logger.warning(f"Core file \"{core_file_path.as_posix()}\" does not exist.")
return False
if not downloads:
raise VersionDataKeyNotFoundException(
f"Section \"Downloads\" (Aka core file data) is missing in the manifest."
)
core_data = downloads.get("client" if not is_server else "server", {})
if not core_data:
raise VersionDataKeyNotFoundException(
f"Core file data is missing for {'server' if is_server else 'client'} in the manifest."
)
expected_hash = core_data.get(algorithm, None)
if not expected_hash and hash_required:
raise VersionDataKeyNotFoundException(
f"Hash is missing for {'server' if is_server else 'client'} in the manifest."
)
core_file = FileObject(core_file_path)
if algorithm not in SUPPORTED_HASH_ALGORITHMS:
raise UnsupportedHashAlgorithmException(
f"Provided hash algorithm \"{algorithm}\" is not supported."
)
if expected_hash and not core_file.verify(algorithm, expected_hash):
logger.warning(f"Core file \"{core_file_path.as_posix()}\" hash is different from manifest expected.")
return False
return True
LATEST_VERSION_ALIASES = {
"latest-release": {"displayName": "Latest Release"},