Update to 0.1.5-alpha

- Add profile icon and launch background customization. Apply same image limitation as official Launcher.
- Add game file hash verification settings.
- Update CoreLib download library hash verification handling.

CoreLib update to v0.1.8
This commit is contained in:
wei committed 2026-11-10 22:05:18 +08:00
1 parent fcd61b3755
commit ca1eac5eb9
19 files changed
+479 -99

No files matched your search

+7 -7
View File
@@ -63,7 +63,7 @@ def fetch_asset_manifest(target_version_manifest: dict, raw=False) -> tuple[dict
"Unable to deserialize asset response data into dictionary: {} ".format(e)
)
def fetch_and_save_asset_manifest(target_version_manifest: dict, destination: Path) -> dict:
def fetch_and_save_asset_manifest(target_version_manifest: dict, destination: Path, *, verify_hash=True) -> dict:
"""
Fetch the asset manifest from target version's manifest and save it.
:param target_version_manifest:
@@ -89,7 +89,7 @@ def fetch_and_save_asset_manifest(target_version_manifest: dict, destination: Pa
with file.path.open("wb") as f:
f.write(data)
if sha1 and not file.verify_sha1(sha1):
if verify_hash and sha1 and not file.verify_sha1(sha1):
raise HashMismatchException(
"sha1",
file.sha1,
@@ -286,7 +286,7 @@ def download_assets_and_copy(assets: list[FileObject], legacy_assets: list[dict]
if old_asset.path.stat().st_size == size:
logger.debug("Asset {} already exists. (no_hash_check=True)".format(target))
return True, None
elif sha1 and old_asset.verify("sha1", sha1):
elif not no_hash_check and sha1 and old_asset.verify("sha1", sha1):
logger.debug("Asset {} already exists.".format(target))
return True, None
@@ -294,7 +294,7 @@ def download_assets_and_copy(assets: list[FileObject], legacy_assets: list[dict]
return True, destination
fails , _ = download_multiple_files(assets, progress_callback=progress_callback,
max_workers=ASSET_DOWNLOAD_MAX_WORKERS)
max_workers=ASSET_DOWNLOAD_MAX_WORKERS, verify_hash=not no_hash_check)
download_ok = len(fails) == 0
@@ -311,7 +311,7 @@ def download_assets_and_copy(assets: list[FileObject], legacy_assets: list[dict]
return fails
# Use thread pool to handle copy file process
with ThreadPoolExecutor(max_workers=ASSET_DOWNLOAD_MAX_WORKERS) as executor:
with ThreadPoolExecutor(max_workers=ASSET_DOWNLOAD_MAX_WORKERS, verify_hash=not no_hash_check) as executor:
futures = [
executor.submit(
__worker,
@@ -395,7 +395,7 @@ def download_assets(manifest: dict, assets_dir: Path, launcher_root: Path, no_ha
if index_path.is_file():
try:
if not index_sha1 or FileObject(index_path).verify_sha1(index_sha1):
if no_hash_check or 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"]:
@@ -405,7 +405,7 @@ def download_assets(manifest: dict, assets_dir: Path, launcher_root: Path, no_ha
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)
asset_manifest = fetch_and_save_asset_manifest(manifest, index_path, verify_hash=not no_hash_check)
# Download assets files
assets, legacy_assets = collect_assets_from_manifest(
+6 -6
View File
@@ -11,7 +11,7 @@ from typing import Callable
import requests
from core_lib.common.exception import LauncherException, AuthenticationSessionException, AuthenticationConnectException, \
AuthenticationException, LauncherHTTPException
AuthenticationException
MICROSOFT_DEVICE_CODE_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode"
MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"
@@ -28,8 +28,8 @@ def auth_exception_handler(request_handler: Callable, request_type: str = "witho
Handle authentication exceptions
:param stage:
:param request_handler:
:param request_type: Set this will change exception type when an error occurs. ("without_token" for process that
don't use token, "with_token" for process that use token. If with token, exception usually throw
:param request_type: Set this will change the exception type when an error occurs. ("without_token" for processes that
don't use token, "with_token" for processes that use token. If with token, exception usually throws
AuthenticationSessionException. If not, throw AuthenticationException instead)
:return:
"""
@@ -58,8 +58,8 @@ def auth_exception_handler(request_handler: Callable, request_type: str = "witho
except (TypeError, ValueError):
pass
# Below are the xsts error code suggestions. Why return that value (error is integer not string) ?
# Maybe it makes international support more easily?
# Below are the xsts error code suggestions. Why return that value (error is integer, not string)?
# Maybe it makes international support more easy?
xsts_suggestions = {
2148916233: "This Microsoft account does not have an Xbox profile. Sign in at xbox.com and create one, then try again.",
2148916235: "Xbox Live is not available for this account's country or region.",
@@ -74,7 +74,7 @@ def auth_exception_handler(request_handler: Callable, request_type: str = "witho
) from e
server_message = response_data.get("Message") or response_data.get("error_description")
# This suggestions can make user happy instead of seeing an HTTP error code
# These suggestions can make user happy instead of seeing an HTTP error code
suggestions = {
400: "The authentication request or session was rejected.",
401: "The login session is invalid or expired. Sign in again.",
+2 -1
View File
@@ -170,7 +170,8 @@ def get_natives_platform_info():
return platform_key_name, platform_rule_name, platform_arch_type
def is_native_allowed(lib_name, platform_key_name, platform_arch_type, unspecified_arch_policy: str = "x86_64") -> bool:
def is_native_allowed(lib_name, platform_key_name, platform_arch_type,
unspecified_arch_policy: str = "x86_64") -> bool:
# Parse native key
match = re.search(r":(natives-[^:]+)$", lib_name)
+66 -13
View File
@@ -2,16 +2,17 @@ import logging
import re
import zipfile
from pathlib import Path, PureWindowsPath
from typing import Callable
from typing import Callable, Literal
from .argument import convert_argument_to_multiple_string, find_game_and_jvm_args, is_argument_allowed
from .library import get_natives_platform_info, is_library_allowed, generate_formatted_artifact_with_name, \
is_native_allowed, is_legacy_native_allowed, remove_duplicate_artifacts
from .libraryx import normalize_library_to_common_struct
from ..common.common import get_platform_info, FileObject, download_multiple_files, unzip, is_valid_zipfile
from ..common.common import get_platform_info, FileObject, download_multiple_files, unzip, is_valid_zipfile, \
SUPPORTED_HASH_ALGORITHMS
from .version_info import find_useful_part_in_specific_version_manifest
from ..common.exception import UnsupportedPlatformException, NativeResolveException, DependencyException, \
VersionDataKeyNotFoundException, DownloadException
VersionDataKeyNotFoundException, DownloadException, HashMismatchException
logger = logging.getLogger("Launcher.CoreLib")
@@ -234,7 +235,7 @@ def collect_native_artifacts(specific_version_manifest):
return items
def download_libraries(artifacts, output_dir, progress_callback: Callable[[str, float], None] = None) \
def download_libraries(artifacts, output_dir, progress_callback: Callable[[str, float], None] = None, *, verify_hash=True) \
-> tuple[list[FileObject], list[FileObject]]:
"""
Download libraries from a list that contains artifacts
@@ -267,13 +268,17 @@ def download_libraries(artifacts, output_dir, progress_callback: Callable[[str,
full_path,
url=url,
sha1=sha1,
sha256=sha256,
sha512=sha512,
)
if sha1 is None:
logger.warning(f"File {full_path} has no SHA1 hash.")
if file.exists:
if sha1 is not None:
if not verify_hash:
valid = full_path.is_file()
elif sha1 is not None:
valid = file.verify("sha1", sha1)
elif sha256 is not None:
valid = file.verify("sha256", sha256)
@@ -290,7 +295,7 @@ def download_libraries(artifacts, output_dir, progress_callback: Callable[[str,
files.append(file)
fails, finished = download_multiple_files(files, progress_callback=progress_callback)
fails, finished = download_multiple_files(files, progress_callback=progress_callback, verify_hash=verify_hash)
successes.extend(finished)
return fails, successes
@@ -328,16 +333,32 @@ def unzip_natives(filtered, libraries_dir, destination: Path):
logger.debug(f"Unzipped {full_path}.")
def check_libraries_exists(manifest: dict, libraries_dir: Path):
def check_libraries_exists_and_verify(manifest, libraries_dir, verify_hash=True,
allow_algorithms=None, *, throw_error_if_missing_hash=False):
"""
Check if libraries are present in the libraries directory
Check if libraries are present in the libraries directory and verify their hash (if required)
:param manifest:
:param libraries_dir:
:param verify_hash: Whether to verify the hash of the library. Defaults to True.
:param throw_error_if_missing_hash: Whether to throw an error if a library is missing a hash. Defaults to False.
(Only working when verify_hash is True)
:param allow_algorithms: The allowed algorithms to use for hash verification. Defaults to SUPPORTED_HASH_ALGORITHMS
(in corelib.common.common)
:return:
not_found: list
"""
libraries = manifest.get("libraries", [])
if allow_algorithms is None:
allow_algorithms = SUPPORTED_HASH_ALGORITHMS
if verify_hash and not allow_algorithms:
raise ValueError("algorithm must be provided if verify_hash is True")
for alog in allow_algorithms or []:
if alog not in SUPPORTED_HASH_ALGORITHMS:
raise ValueError(f"Unsupported algorithm: {alog}")
if not libraries:
raise VersionDataKeyNotFoundException(
"Libraries not found in manifest.",
@@ -379,12 +400,43 @@ def check_libraries_exists(manifest: dict, libraries_dir: Path):
logger.warning(f"Artifact {name} are not valid. Skipping...")
continue
relative_path = artifact.get("path")
relative_path = artifact["path"] # Is safe because generate_formatted_artifact_with_name will check
# the "path" key.
full_path = libraries_dir / Path(relative_path)
if not full_path.is_file() or not full_path.exists():
logger.debug(f"Artifact {name} missing.")
not_found.append(full_path)
continue
if verify_hash:
expected = None
used_alog = None
# Get expected hash
for alog in allow_algorithms or []:
expected = artifact.get(alog, None)
if expected:
used_alog = alog
break
# Verify hash
if used_alog:
f = FileObject(full_path)
if not f.verify(used_alog, expected):
logger.debug(f"Hash mismatch for {full_path} with algorithm {used_alog}")
not_found.append(full_path)
continue
else:
logger.debug(f"Hash match for {full_path} with algorithm {used_alog}")
else:
if throw_error_if_missing_hash:
raise VersionDataKeyNotFoundException(
f"Library {name} does not provide any hash that type is allowed in {allow_algorithms}"
)
# Show warning if there's no support algorithm in the artifact
logger.warning(f"Library {name} does not provide any hash that type is allowed in {allow_algorithms}")
return not_found
@@ -518,16 +570,17 @@ def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path,
def check_full_libraries_exists(manifest: dict, libraries_dir: Path, natives_dir: Path, *,
features: dict | None = None) -> bool:
features=None, verify_hash=True,) -> bool:
natives_exist = check_natives_exists(
manifest,
libraries_dir,
natives_dir,
features=features,
)
missing_libraries = check_libraries_exists(
missing_libraries = check_libraries_exists_and_verify(
manifest,
libraries_dir,
verify_hash=verify_hash,
)
return natives_exist and not missing_libraries
@@ -604,7 +657,7 @@ def download_full_libraries(manifest: dict, libraries_dir: Path, default_natives
progress_callback: Callable[[str, float], None] = None,
redownload_callback: Callable[
[list[FileObject]], tuple[bool, list[FileObject]]] = None, *,
features: dict | None = None) -> None:
features: dict | None = None, verify_hash=True) -> None:
natives_dir = locate_natives_extract_dir_by_manifest(manifest, default_natives_dir, features=features)
# libraries
libraries = collect_library_artifacts(manifest)
@@ -621,7 +674,7 @@ def download_full_libraries(manifest: dict, libraries_dir: Path, default_natives
)
# Start download
fails, successes = download_libraries(full, libraries_dir, progress_callback=progress_callback)
fails, successes = download_libraries(full, libraries_dir, progress_callback=progress_callback, verify_hash=verify_hash)
download_ok = len(fails) == 0
+5 -5
View File
@@ -517,7 +517,7 @@ def fetch_and_save_version_manifest(dest: Path, target_version: str=None, root_m
return save_version_manifest(data, dest, sha1)
def download_core_file(manifest: dict, destination: Path, is_server=False, raise_for_null_hash=True,
progress_callback: Callable[[str, float], None]=None) -> FileObject:
progress_callback: Callable[[str, float], None]=None, *, verify_hash=True) -> FileObject:
"""
Download core file from version manifest.
:param manifest:
@@ -532,7 +532,7 @@ def download_core_file(manifest: dict, destination: Path, is_server=False, raise
destination.parent.mkdir(parents=True, exist_ok=True)
if sha1 is None and raise_for_null_hash:
if verify_hash and sha1 is None and raise_for_null_hash:
raise VersionDataKeyNotFoundException(
"Core file hash is missing. Enable \"raise_for_null_hash\" flag to ignore this exception.\n"
)
@@ -541,10 +541,10 @@ def download_core_file(manifest: dict, destination: Path, is_server=False, raise
file = FileObject(destination, url=url, sha1=sha1)
if file.exists and file.verify("sha1", sha1):
if destination.is_file() and (not verify_hash or file.verify("sha1", sha1)):
logger.info(f"Client existed and sha1 matches.")
elif url is not None:
download_file(file, progress_callback=progress_callback)
download_file(file, progress_callback=progress_callback, verify_hash=verify_hash)
elif not url:
raise VersionDataKeyNotFoundException(
"Core file url is None. Unable to download it."
@@ -567,7 +567,7 @@ def check_core_file_exists_and_verify(manifest: dict, core_file_path: Path,
"""
_, _, downloads, _, _, _, _ = find_useful_part_in_specific_version_manifest(manifest)
if not core_file_path.exists():
if not core_file_path.exists() or not core_file_path.is_file():
logger.warning(f"Core file \"{core_file_path.as_posix()}\" does not exist.")
return False