CoreLib
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:
1 parent
b7af7e3469
commit
77c4be7dcf
16 files changed
+1070
-218
No files matched your search
@@ -99,10 +99,10 @@ If you see `Some runtimes are no longer available after last check`, check wheth
|
||||
then refresh the runtime list or register its new executable path.
|
||||
|
||||
Links for available Java runtimes provider:
|
||||
[Oracle](https://www.java.com/download/)
|
||||
[Eclipse Temurin](https://adoptium.net/)
|
||||
[Azul Zulu](https://www.azul.com/downloads/)
|
||||
[Microsoft Build of OpenJDK](https://www.microsoft.com/openjdk)
|
||||
- [Oracle](https://www.java.com/download/)
|
||||
- [Eclipse Temurin](https://adoptium.net/)
|
||||
- [Azul Zulu](https://www.azul.com/downloads/)
|
||||
- [Microsoft Build of OpenJDK](https://www.microsoft.com/openjdk)
|
||||
|
||||
### No profile selected or profile data cannot be loaded
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
LAUNCHER_VERSION = "0.0.8-alpha"
|
||||
LAUNCHER_VERSION = "0.0.9-alpha"
|
||||
LAUNCHER_NAME = "TapLauncher"
|
||||
LAUNCHER_DIR_NAME = "TapLauncher"
|
||||
MAIN_REPO_URL = "https://repo.weispace.net/wei/Launcher/"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
__version__ = '0.1.2'
|
||||
__version__ = '0.1.3'
|
||||
__description__ = """
|
||||
The core library of the *Launcher*
|
||||
|
||||
|
||||
+129
-28
@@ -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,36 +182,62 @@ 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:
|
||||
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(file.url))
|
||||
logger.debug("URL: {}".format(target_file.url))
|
||||
logger.debug("Response code: {}".format(r.status_code))
|
||||
|
||||
with file.path.open("wb") as f:
|
||||
with target_file.path.open("wb") as f:
|
||||
for chunk in r.iter_content(chunk_size=DEFAULT_DOWNLOAD_CHUNK_SIZE):
|
||||
if not chunk:
|
||||
break
|
||||
@@ -205,27 +247,52 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[
|
||||
|
||||
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)
|
||||
progress_callback(target_file.name, current_progress)
|
||||
except Exception as e:
|
||||
raise DownloadException(
|
||||
"An error occurred while downloading file {}. {}".format(file.url, e)
|
||||
"An error occurred while downloading file {}. {}".format(target_file.url, e)
|
||||
)
|
||||
finally:
|
||||
file.invalidate_hash_cache()
|
||||
target_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 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([file.expected_sha1, file.expected_md5, file.expected_sha256]):
|
||||
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(file.posix_path))
|
||||
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 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
|
||||
|
||||
@@ -338,3 +405,37 @@ def bytes_to_data_url(image_data: bytes, mime_type: str = "image/png",) -> str:
|
||||
|
||||
encoded = base64.b64encode(image_data).decode("ascii")
|
||||
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
|
||||
@@ -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."
|
||||
|
||||
|
||||
+37
-5
@@ -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(
|
||||
|
||||
+112
-22
@@ -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"},
|
||||
|
||||
+112
-129
@@ -1,3 +1,4 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -16,15 +17,14 @@ from PySide6.QtCore import QObject, Signal
|
||||
|
||||
from constant import CLIENT_ID, LAUNCHER_VERSION
|
||||
from core_lib.common.common import FileObject, download_multiple_files
|
||||
from core_lib.common.exception import JavaRuntimeException, VersionManifestFetchException, VersionManifestSaveException, \
|
||||
NoSpecifiedVersionKeyException
|
||||
from core_lib.common.exception import JavaRuntimeException
|
||||
from core_lib.game.argument import ArgumentMappings, generate_launch_command
|
||||
from core_lib.game.asset import check_assets_exist, download_assets, find_correct_assets_dir
|
||||
from core_lib.game.library_core import check_full_libraries_exists, download_full_libraries, generate_classpath
|
||||
from core_lib.game.mod.mod_core import merge_manifest
|
||||
from core_lib.game.version_info import fetch_and_save_version_manifest, get_specific_version_manifest_url_and_hash, \
|
||||
save_version_manifest, find_useful_part_in_specific_version_manifest, download_core_file, get_latest_version, \
|
||||
LATEST_VERSION_ALIASES
|
||||
LATEST_VERSION_ALIASES, check_core_file_exists_and_verify, validate_version_manifest
|
||||
from core_lib.runtime.java import find_java_installations, get_java_version
|
||||
from core_lib.runtime.mojang import download_java_runtimes, fetch_runtime_manifest, get_current_platform_runtime_key
|
||||
from manager.account import AccountManager, LaunchAccount
|
||||
@@ -46,6 +46,10 @@ class ManifestManager:
|
||||
self.app = app
|
||||
self.widget_mgr = app.widget_manager
|
||||
|
||||
# Flags
|
||||
self.use_expired_manifest = False
|
||||
self._manifest_prompt_lock = threading.Lock()
|
||||
|
||||
#
|
||||
# ============ Version Data Cache ============
|
||||
#
|
||||
@@ -64,160 +68,133 @@ class ManifestManager:
|
||||
|
||||
return path
|
||||
|
||||
def _cache_version_manifest(self, specified_ver: str | None = None, root_manifest: dict | None = None) \
|
||||
-> tuple[bool, dict | None]:
|
||||
data = None
|
||||
path = self.switch_between_specific_path(specified_ver)
|
||||
def _cache_version_manifest(self, specified_ver: str | None = None, root_manifest: dict | None = None) -> tuple[bool, dict | None]:
|
||||
try:
|
||||
data = fetch_and_save_version_manifest(path, target_version=specified_ver, root_manifest=root_manifest)
|
||||
except VersionManifestFetchException as e:
|
||||
self.widget_mgr.signal.show_error_message.emit(
|
||||
e.user_message,
|
||||
data = fetch_and_save_version_manifest(
|
||||
self.switch_between_specific_path(specified_ver),
|
||||
target_version=specified_ver, root_manifest=root_manifest,
|
||||
)
|
||||
except VersionManifestSaveException as e:
|
||||
self.widget_mgr.signal.show_error_message.emit(
|
||||
e.user_message,
|
||||
)
|
||||
except Exception as e:
|
||||
self.widget_mgr.signal.show_and_print_error_message.emit(
|
||||
{
|
||||
"error": traceback.format_exception(e),
|
||||
"title": "Cache Error",
|
||||
"message": "An unexpected error occurred while caching version manifest."
|
||||
}
|
||||
)
|
||||
|
||||
return True if data else False, data
|
||||
return True, data
|
||||
except Exception as exc:
|
||||
self.app.logger.warning("Unable to refresh version manifest: %s", exc)
|
||||
return False, None
|
||||
|
||||
def _cache_custom_version_manifest(self, version_id: str, fetch_manifest_handler: Callable[[str], tuple[dict, str | None]]):
|
||||
data = None
|
||||
manifest_sha1 = None
|
||||
path = self.get_specific_version_manifest_path(version_id)
|
||||
|
||||
# Fetch data
|
||||
try:
|
||||
data, manifest_sha1 = fetch_manifest_handler(version_id)
|
||||
except VersionManifestFetchException as e:
|
||||
self.widget_mgr.signal.show_error_message.emit(
|
||||
e.user_message,
|
||||
)
|
||||
except VersionManifestSaveException as e:
|
||||
self.widget_mgr.signal.show_error_message.emit(
|
||||
e.user_message,
|
||||
)
|
||||
except Exception as e:
|
||||
self.widget_mgr.signal.show_and_print_error_message.emit(
|
||||
{
|
||||
"error": traceback.format_exception(e),
|
||||
"title": "Cache Error",
|
||||
"message": "An unexpected error occurred while caching version manifest."
|
||||
}
|
||||
)
|
||||
|
||||
# Save data
|
||||
if data:
|
||||
try:
|
||||
save_version_manifest(data, path, sha1=manifest_sha1)
|
||||
except VersionManifestSaveException as e:
|
||||
self.widget_mgr.signal.show_error_message.emit(
|
||||
e.user_message,
|
||||
)
|
||||
return False, None
|
||||
except Exception as e:
|
||||
self.widget_mgr.signal.show_and_print_error_message.emit(
|
||||
{
|
||||
"error": traceback.format_exception(e),
|
||||
"title": "Cache Error",
|
||||
"message": "An unexpected error occurred while caching version manifest."
|
||||
}
|
||||
)
|
||||
data, sha1 = fetch_manifest_handler(version_id)
|
||||
validate_version_manifest(data, version_id)
|
||||
save_version_manifest(data, self.get_specific_version_manifest_path(version_id), sha1=sha1)
|
||||
return True, data
|
||||
except Exception as exc:
|
||||
self.app.logger.warning("Unable to refresh custom manifest %s: %s", version_id, exc)
|
||||
return False, None
|
||||
|
||||
return True if data else False, data
|
||||
|
||||
def _read_cached_version_manifest(self, specified_ver: str = None) -> dict | None:
|
||||
def _read_cached_version_manifest(self, specified_ver: str | None = None, sha1: str | None = None) -> dict | None:
|
||||
path = self.switch_between_specific_path(specified_ver)
|
||||
if not path.exists():
|
||||
try:
|
||||
if not path.is_file():
|
||||
return None
|
||||
# Read once: the parsed content and the hash must describe the same bytes.
|
||||
payload = path.read_bytes()
|
||||
if sha1 is not None and hashlib.sha1(payload).hexdigest() != sha1:
|
||||
raise ValueError("Cached manifest SHA-1 does not match")
|
||||
data = json.loads(payload.decode("utf-8"))
|
||||
validate_version_manifest(data, specified_ver)
|
||||
return data
|
||||
except (OSError, ValueError) as exc:
|
||||
self.app.logger.warning("Ignoring invalid cached manifest %s: %s", path, exc)
|
||||
return None
|
||||
|
||||
def _cache_is_current(self, path: Path, max_age: int) -> bool:
|
||||
try:
|
||||
return self.use_expired_manifest or time.time() - path.stat().st_mtime < max_age
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def _refresh_or_use_cached(self, fetch: Callable, cached: dict | None, version_id: str | None) -> dict | None:
|
||||
for _ in range(3):
|
||||
try:
|
||||
success, data = fetch()
|
||||
if success:
|
||||
validate_version_manifest(data, version_id)
|
||||
return data
|
||||
except Exception as exc:
|
||||
self.app.logger.warning("Manifest refresh failed: %s", exc)
|
||||
|
||||
if cached is None:
|
||||
self.widget_mgr.signal.show_error_message.emit(
|
||||
"Version manifest missing after check. Please try again later.",
|
||||
"Unable to fetch version manifest and no valid cached manifest is available."
|
||||
)
|
||||
return None
|
||||
|
||||
try:
|
||||
version_manifest = json.loads(path.read_text())
|
||||
return version_manifest
|
||||
except Exception as e:
|
||||
self.widget_mgr.signal.show_and_print_error_message.emit(
|
||||
{
|
||||
"error": traceback.format_exception(e),
|
||||
"title": "Cache Error",
|
||||
"message": "Unable to read version manifest."
|
||||
}
|
||||
# Concurrent background tasks share one session preference and one question.
|
||||
with self._manifest_prompt_lock:
|
||||
if self.use_expired_manifest:
|
||||
return cached
|
||||
|
||||
request = AskForRequest(
|
||||
title="Manifest Manager",
|
||||
message="Unable to fetch the latest manifest. Use the validated cached data "
|
||||
"until the launcher is restarted? The version list may be outdated.",
|
||||
)
|
||||
|
||||
request.use_plain_text = False
|
||||
self.widget_mgr.signal.askyesno.emit(request)
|
||||
|
||||
if not request.wait(120) or request.result() is not True:
|
||||
return None
|
||||
|
||||
def get_cached_version_manifest(self, specified_ver: str = None,
|
||||
max_age: int = 3600) -> dict | None:
|
||||
path = self.switch_between_specific_path(specified_ver)
|
||||
file = FileObject(path)
|
||||
sha1 = None
|
||||
self.use_expired_manifest = True
|
||||
self.widget_mgr.signal.show_warning_message.emit(
|
||||
"Using cached version manifests until restart. Version information may be outdated."
|
||||
)
|
||||
|
||||
return cached
|
||||
|
||||
def get_cached_version_manifest(self, specified_ver: str | None = None, max_age: int = 3600) -> dict | None:
|
||||
"""
|
||||
Get cached version manifest.
|
||||
:param specified_ver:
|
||||
:param max_age:
|
||||
:return:
|
||||
"""
|
||||
root_manifest = None
|
||||
sha1 = None
|
||||
|
||||
if specified_ver:
|
||||
root_manifest = self.get_cached_version_manifest()
|
||||
|
||||
if root_manifest is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
_, sha1 = get_specific_version_manifest_url_and_hash(root_manifest, specified_ver)
|
||||
except NoSpecifiedVersionKeyException as e:
|
||||
self.widget_mgr.signal.show_error_message.emit(
|
||||
f"Version {specified_ver} does not exist in version manifest.\n{e.user_message}"
|
||||
except Exception as exc:
|
||||
self.widget_mgr.signal.show_error_message.emit(str(exc))
|
||||
return None
|
||||
|
||||
path = self.switch_between_specific_path(specified_ver)
|
||||
cached = self._read_cached_version_manifest(specified_ver, sha1=sha1)
|
||||
|
||||
if cached is not None and self._cache_is_current(path, max_age):
|
||||
return cached
|
||||
|
||||
return self._refresh_or_use_cached(
|
||||
lambda: self._cache_version_manifest(specified_ver, root_manifest=root_manifest),
|
||||
cached, specified_ver,
|
||||
)
|
||||
return None
|
||||
|
||||
if file.exists:
|
||||
age = time.time() - path.stat().st_mtime
|
||||
|
||||
# For root manifest
|
||||
if not specified_ver and age < max_age:
|
||||
return self._read_cached_version_manifest()
|
||||
|
||||
# Below are all for specific ver
|
||||
if specified_ver and sha1 is None:
|
||||
self.app.logger.warning("Specified version '{}' hash doesn't exist.".format(specified_ver))
|
||||
|
||||
# Also check sha1
|
||||
if specified_ver and age < max_age and file.verify("sha1", sha1):
|
||||
return self._read_cached_version_manifest(specified_ver)
|
||||
|
||||
result, data = self._cache_version_manifest(specified_ver, root_manifest=root_manifest)
|
||||
|
||||
if not result:
|
||||
return None
|
||||
|
||||
return data
|
||||
|
||||
def get_cached_custom_version_manifest(self, specified_ver: str,
|
||||
fetch_manifest_handler: Callable[[str], tuple[dict, str | None]],
|
||||
max_age=1260000) -> dict | None:
|
||||
path = self.get_specific_version_manifest_path(specified_ver)
|
||||
file = FileObject(path)
|
||||
cached = self._read_cached_version_manifest(specified_ver)
|
||||
|
||||
if file.exists:
|
||||
age = time.time() - path.stat().st_mtime
|
||||
if cached is not None and self._cache_is_current(path, max_age):
|
||||
return cached
|
||||
|
||||
# Check file stat
|
||||
if age < max_age:
|
||||
return self._read_cached_version_manifest(specified_ver)
|
||||
|
||||
result, data = self._cache_custom_version_manifest(specified_ver, fetch_manifest_handler=fetch_manifest_handler)
|
||||
|
||||
if not result:
|
||||
return None
|
||||
|
||||
return data
|
||||
return self._refresh_or_use_cached(
|
||||
lambda: self._cache_custom_version_manifest(specified_ver, fetch_manifest_handler),
|
||||
cached, specified_ver,
|
||||
)
|
||||
|
||||
def create_download_progress_callback(self, progress_title: str):
|
||||
task_id = uuid4().hex
|
||||
@@ -1086,10 +1063,10 @@ class LaunchManager:
|
||||
game_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Check client
|
||||
if not core_file_path.exists():
|
||||
if not check_core_file_exists_and_verify(version_manifest, core_file_path):
|
||||
request = GameFileDownloadRequest(
|
||||
"download_client",
|
||||
(client_version_id, core_file_path, version_manifest,)
|
||||
(client_version_id, core_file_path, version_manifest)
|
||||
)
|
||||
self.game_file_mgr.start_task(request)
|
||||
|
||||
@@ -1294,7 +1271,13 @@ class LaunchManager:
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
|
||||
self.launched_profiles.append(profile.profile_id)
|
||||
|
||||
# Cleanup
|
||||
if profile.profile_id in self.launching_profiles:
|
||||
self.launching_profiles.remove(profile.profile_id)
|
||||
|
||||
result.process = process
|
||||
return result
|
||||
except Exception as e:
|
||||
@@ -1357,7 +1340,7 @@ class LaunchManager:
|
||||
|
||||
try:
|
||||
self.launching_profiles.remove(profile_id)
|
||||
except ValueError:
|
||||
except (ValueError, KeyError,):
|
||||
pass
|
||||
|
||||
self.app.logger.debug(
|
||||
|
||||
+64
-24
@@ -1,6 +1,7 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
import threading
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
@@ -21,9 +22,10 @@ from core_lib.game.library_core import generate_classpath, download_full_librari
|
||||
|
||||
from core_lib.game.version_info import (find_useful_part_in_specific_version_manifest, \
|
||||
get_all_versions, get_available_version_types,
|
||||
download_core_file)
|
||||
download_core_file, check_core_file_exists_and_verify)
|
||||
from core_lib.qt.hack import is_main_thread
|
||||
from core_lib.runtime.java import find_java_installations
|
||||
from manager.account import LaunchAccount
|
||||
from manager.game import ManifestManager, JavaManager
|
||||
from manager.widgets import SelectPathRequest, AskForRequest
|
||||
|
||||
@@ -67,9 +69,9 @@ class TestPage(QWidget):
|
||||
self.button_6.setObjectName("ActionButton")
|
||||
self.button_6.clicked.connect(self.parse_argument)
|
||||
|
||||
self.button_7 = QPushButton(self.app.tr_text("Launch Game! (Offline)"))
|
||||
self.button_7 = QPushButton(self.app.tr_text("Launch Game"))
|
||||
self.button_7.setObjectName("ActionButton")
|
||||
self.button_7.clicked.connect(self.launch_offline_game)
|
||||
self.button_7.clicked.connect(self.launch_game)
|
||||
|
||||
self.ver_dropdown = QComboBox()
|
||||
self.ver_dropdown.setObjectName("Dropdown")
|
||||
@@ -154,6 +156,7 @@ class TestPage(QWidget):
|
||||
self.signals.clean_output.connect(
|
||||
lambda : self.output.clear()
|
||||
)
|
||||
self.signals.set_output.connect(self.output.setPlainText)
|
||||
|
||||
self.load_all_types()
|
||||
|
||||
@@ -165,6 +168,7 @@ class TestPage(QWidget):
|
||||
get_selected_ver = Signal(dict)
|
||||
get_selected_type = Signal(dict)
|
||||
clean_output = Signal()
|
||||
set_output = Signal(str)
|
||||
|
||||
@Slot(dict)
|
||||
def get_selected_ver(self, context: dict):
|
||||
@@ -248,15 +252,18 @@ class TestPage(QWidget):
|
||||
|
||||
def run_test(self):
|
||||
self.button.setDisabled(True)
|
||||
|
||||
try:
|
||||
self.output.clear()
|
||||
ver = self.get_selected_version()
|
||||
|
||||
if not ver:
|
||||
self.button.setDisabled(False)
|
||||
return
|
||||
threading.Thread(target=self._fetch_version_data, args=(ver,), daemon=True).start()
|
||||
|
||||
def _fetch_version_data(self, ver):
|
||||
try:
|
||||
ver_data = self.manifest_mgr.get_cached_version_manifest(ver)
|
||||
if ver_data is None:
|
||||
return
|
||||
|
||||
arguments, asset_index, downloads, java_version, libraries, main_class, legacy_game_args = (
|
||||
find_useful_part_in_specific_version_manifest(ver_data))
|
||||
@@ -277,7 +284,7 @@ class TestPage(QWidget):
|
||||
Extra:
|
||||
minecraftArguments: {legacy_game_args}
|
||||
""")
|
||||
self.output.setPlainText(content)
|
||||
self.signals.set_output.emit(content)
|
||||
except Exception as e:
|
||||
self.widget_mgr.signal.show_and_print_error_message.emit(
|
||||
{
|
||||
@@ -287,7 +294,7 @@ class TestPage(QWidget):
|
||||
}
|
||||
)
|
||||
finally:
|
||||
self.button.setDisabled(False)
|
||||
self.widget_mgr.signal.enable_widget.emit(self.button)
|
||||
|
||||
def run_download_client(self):
|
||||
self.button_2.setDisabled(True)
|
||||
@@ -361,7 +368,7 @@ class TestPage(QWidget):
|
||||
)
|
||||
thread.start()
|
||||
|
||||
def launch_offline_game(self):
|
||||
def launch_game(self):
|
||||
self.button_7.setDisabled(True)
|
||||
|
||||
self.output.clear()
|
||||
@@ -373,7 +380,7 @@ class TestPage(QWidget):
|
||||
return
|
||||
|
||||
thread = threading.Thread(
|
||||
target=self._launch_offline_game,
|
||||
target=self._launch_game,
|
||||
daemon=True,
|
||||
args=(ver,)
|
||||
)
|
||||
@@ -679,15 +686,46 @@ class TestPage(QWidget):
|
||||
finally:
|
||||
self.widget_mgr.signal.enable_widget.emit(self.button_6)
|
||||
|
||||
def _launch_offline_game(self, ver):
|
||||
def _launch_game(self, ver):
|
||||
"""
|
||||
Launch offline game
|
||||
Launch game
|
||||
:param ver:
|
||||
:return:
|
||||
"""
|
||||
|
||||
# Check launch account mode
|
||||
request = AskForRequest(title="GameTest", message="Would you like to launch game in online mode?")
|
||||
request.use_plain_text = False
|
||||
self.widget_mgr.signal.askyesno.emit(request)
|
||||
if not request.wait(120):
|
||||
self.widget_mgr.signal.show_error_message.emit(
|
||||
"Timeout while waiting for user input."
|
||||
)
|
||||
self.widget_mgr.signal.enable_widget.emit(self.button_7)
|
||||
return
|
||||
|
||||
offline = request.result() is not True
|
||||
|
||||
try:
|
||||
current_status = 0 # 0 = fetch version manifest, 1 = check client, 2 = check libraries
|
||||
# , 3 = check assets
|
||||
launch_account: LaunchAccount | None = None
|
||||
if not offline:
|
||||
# Online mode
|
||||
launch_account: LaunchAccount | None = self.app.account_manager.get_launch_account()
|
||||
|
||||
if not launch_account:
|
||||
raise RuntimeError("Select a usage account in account page before use online launch.")
|
||||
|
||||
player_name = launch_account.player_name
|
||||
auth_uuid = launch_account.minecraft_uuid
|
||||
access_token = launch_account.access_token
|
||||
user_type = launch_account.user_type
|
||||
auth_xuid = launch_account.xuid
|
||||
else:
|
||||
player_name = "Player"
|
||||
auth_uuid = "00000000000000000000000000000000"
|
||||
access_token = "0"
|
||||
user_type = "legacy"
|
||||
auth_xuid = "null"
|
||||
|
||||
# Version manifest
|
||||
ver_data = self.manifest_mgr.get_cached_version_manifest(ver)
|
||||
@@ -711,17 +749,14 @@ class TestPage(QWidget):
|
||||
libraries_dir = Path(self.app.work_dir, "libraries")
|
||||
|
||||
# Check client
|
||||
current_status = 1
|
||||
if not core_file_path.exists():
|
||||
if not check_core_file_exists_and_verify(ver_data, core_file_path):
|
||||
download_core_file(ver_data, core_file_path, raise_for_null_hash=True)
|
||||
|
||||
# Libraries
|
||||
current_status = 2
|
||||
if not check_full_libraries_exists(ver_data, libraries_dir, natives_dir):
|
||||
download_full_libraries(ver_data, libraries_dir, natives_dir)
|
||||
|
||||
# Asset
|
||||
current_status = 3
|
||||
default_assets_dir = Path(self.app.work_dir, "assets")
|
||||
if not check_assets_exist(ver_data, default_assets_dir, launcher_root=self.app.work_dir):
|
||||
callback, task_id = self.manifest_mgr.create_download_progress_callback(
|
||||
@@ -744,7 +779,6 @@ class TestPage(QWidget):
|
||||
|
||||
assets_dir = find_correct_assets_dir(asset_id, default_assets_dir, self.app.work_dir)
|
||||
|
||||
current_status = 4
|
||||
classpath = generate_classpath(
|
||||
ver_data,
|
||||
libraries_dir,
|
||||
@@ -753,15 +787,15 @@ class TestPage(QWidget):
|
||||
|
||||
# Mappings
|
||||
arg_maps = ArgumentMappings(
|
||||
player_name="Player",
|
||||
player_name=player_name,
|
||||
version_name=ver,
|
||||
game_directory=game_dir.as_posix(),
|
||||
assets_root=assets_dir.as_posix(),
|
||||
legacy_assets_root=assets_dir,
|
||||
assets_index_name=asset_id,
|
||||
auth_uuid="00000000000000000000000000000000",
|
||||
auth_access_token="0",
|
||||
user_type="legacy",
|
||||
auth_uuid=auth_uuid,
|
||||
auth_access_token=access_token,
|
||||
user_type=user_type,
|
||||
version_type="release",
|
||||
natives_directory=natives_dir.as_posix(),
|
||||
launcher_name="TestLauncher",
|
||||
@@ -770,6 +804,7 @@ class TestPage(QWidget):
|
||||
classpath_separator=";",
|
||||
library_directory=libraries_dir.as_posix(),
|
||||
clientid=CLIENT_ID,
|
||||
auth_xuid=auth_xuid
|
||||
)
|
||||
|
||||
target_args = arguments if arguments else old_args
|
||||
@@ -819,7 +854,12 @@ class TestPage(QWidget):
|
||||
strict_placeholders=False,
|
||||
)
|
||||
|
||||
self.widget_mgr.download_signal.log.emit(f"Launch command: {cmd}")
|
||||
if not offline:
|
||||
safe_cmd = ["<access token>" if value == launch_account.access_token else value for value in cmd]
|
||||
else:
|
||||
safe_cmd = cmd
|
||||
|
||||
self.widget_mgr.download_signal.log.emit(f"Launch command: {safe_cmd}")
|
||||
|
||||
# run it
|
||||
process = subprocess.Popen(
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "testlauncher"
|
||||
version = "0.0.7a0"
|
||||
version = "0.0.9a0"
|
||||
description = "A lightweight Minecraft launcher."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import datetime
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from core_lib.common.exception import ArgumentValueError, AuthenticationException
|
||||
from core_lib.game import authentication
|
||||
from core_lib.game.account import Account, convert_account_data_to_object, create_account, get_account_sample
|
||||
from core_lib.game.argument import ArgumentMappings, generate_launch_command, replace_placeholders
|
||||
from manager import account as account_module
|
||||
from manager.account import AccountDetail, AccountManager, TokenRefreshWorker
|
||||
|
||||
|
||||
XUID = "2535400000000000"
|
||||
|
||||
|
||||
def claims(xuid=XUID, user_hash="user-hash"):
|
||||
return {"DisplayClaims": {"xui": [{"uhs": user_hash, "xid": xuid}]}}
|
||||
|
||||
|
||||
def test_xuid_lookup_reuses_existing_claims(monkeypatch):
|
||||
request = Mock()
|
||||
monkeypatch.setattr(authentication, "get_xsts_token", request)
|
||||
assert authentication.get_xbox_xuid("xbox-token", "user-hash", claims()) == XUID
|
||||
request.assert_not_called()
|
||||
|
||||
|
||||
def test_xuid_lookup_uses_separate_xbox_relying_party(monkeypatch):
|
||||
request = Mock(return_value=("xbox-service-token", claims()))
|
||||
monkeypatch.setattr(authentication, "get_xsts_token", request)
|
||||
assert authentication.get_xbox_xuid("xbox-token", "user-hash", {}) == XUID
|
||||
request.assert_called_once_with("xbox-token", relying_party="https://xboxlive.com")
|
||||
|
||||
|
||||
def test_optional_xuid_lookup_failure_does_not_fail_login(monkeypatch):
|
||||
monkeypatch.setattr(authentication, "get_xsts_token", Mock(side_effect=AuthenticationException("unavailable")))
|
||||
assert authentication.get_xbox_xuid("xbox-token", "user-hash", {}) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [{}, {"DisplayClaims": None}, claims(user_hash="other-user"),
|
||||
claims(xuid="not-a-number"), claims(xuid="9" * 30)])
|
||||
def test_invalid_or_other_user_claims_are_not_used(data):
|
||||
assert authentication.extract_xuid(data, "user-hash") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("xuid", [None, XUID])
|
||||
def test_account_xuid_round_trip_and_launch_mapping(xuid):
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
accounts = get_account_sample()
|
||||
create_account(Account("id", "player", "token", "refresh", now, now, xuid=xuid), accounts)
|
||||
restored = convert_account_data_to_object(accounts, "id")
|
||||
assert restored.xuid == xuid
|
||||
detail = AccountDetail(
|
||||
display_name="player", id="id", username="player", minecraft_uuid="uuid",
|
||||
minecraft_name="player", avatar="", account_type="msa", access_token="token",
|
||||
refresh_token="refresh", access_token_expires_at=now, refresh_token_expires_at=now,
|
||||
user_properties=[], xuid=restored.xuid,
|
||||
)
|
||||
manager = SimpleNamespace(get_current_account_id=lambda: "id", get_account=lambda _: detail,
|
||||
settings_use_system_keyring=False)
|
||||
launch = AccountManager.get_launch_account(manager)
|
||||
maps = ArgumentMappings(auth_xuid=launch.xuid, natives_directory="natives", classpath="client.jar")
|
||||
command = generate_launch_command(maps, "Main", "java", {"game": ["--xuid", "${auth_xuid}"]})
|
||||
assert command[-1] == (xuid or "${auth_xuid}")
|
||||
if xuid is None:
|
||||
with pytest.raises(ArgumentValueError):
|
||||
generate_launch_command(maps, "Main", "java", {"game": ["${auth_xuid}"]}, strict_placeholders=True)
|
||||
|
||||
|
||||
def test_old_account_without_xuid_still_loads():
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
accounts = get_account_sample()
|
||||
raw, _ = create_account(Account("id", "player", "token", "refresh", now, now), accounts)
|
||||
raw.pop("xuid")
|
||||
assert convert_account_data_to_object(accounts, "id").xuid is None
|
||||
|
||||
|
||||
def test_refresh_retains_minecraft_token_audience_and_emits_xuid(monkeypatch):
|
||||
monkeypatch.setattr(account_module, "refresh_microsoft_token", lambda *_: ("microsoft", "refresh", {}))
|
||||
monkeypatch.setattr(account_module, "get_xbox_token_and_user_hash", lambda *_: ("xbox", "user-hash", {}))
|
||||
monkeypatch.setattr(account_module, "get_xsts_token", lambda *_: ("minecraft-xsts", claims()))
|
||||
monkeypatch.setattr(account_module, "get_xbox_xuid", lambda *_: XUID)
|
||||
minecraft_login = Mock(return_value=("minecraft-token", {}))
|
||||
monkeypatch.setattr(account_module, "get_minecraft_access_token", minecraft_login)
|
||||
result, errors = [], []
|
||||
worker = TokenRefreshWorker("id", "refresh", "client")
|
||||
worker.succeeded.connect(lambda account_id, data: result.append(data))
|
||||
worker.failed.connect(lambda *args: errors.append(args))
|
||||
worker.run()
|
||||
assert not errors
|
||||
assert result[0]["xuid"] == XUID
|
||||
minecraft_login.assert_called_once_with("user-hash", "minecraft-xsts")
|
||||
|
||||
|
||||
def test_placeholder_replacement_defaults_to_tolerant_mode():
|
||||
assert replace_placeholders("${missing}/${unset}", {"unset": None}) == "${missing}/${unset}"
|
||||
with pytest.raises(ArgumentValueError):
|
||||
replace_placeholders("${missing}", {}, strict=True)
|
||||
@@ -0,0 +1,85 @@
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from core_lib.game import asset
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def legacy_assets(tmp_path, monkeypatch, request):
|
||||
kind = request.param
|
||||
assets_dir = tmp_path / "assets"
|
||||
content = b"legacy asset payload"
|
||||
digest = hashlib.sha1(content).hexdigest()
|
||||
source = assets_dir / "objects" / digest[:2] / digest
|
||||
source.parent.mkdir(parents=True)
|
||||
source.write_bytes(content)
|
||||
destination = (
|
||||
assets_dir / "virtual" / "fixture" / "sound.ogg"
|
||||
if kind == "virtual" else tmp_path / "resources" / "sound.ogg"
|
||||
)
|
||||
index_data = {kind: True, "objects": {"sound.ogg": {"hash": digest, "size": len(content)}}}
|
||||
index_bytes = json.dumps(index_data).encode("utf-8")
|
||||
index = assets_dir / "indexes" / "fixture.json"
|
||||
index.parent.mkdir(parents=True)
|
||||
index.write_bytes(index_bytes)
|
||||
manifest = {"assetIndex": {"id": "fixture", "sha1": hashlib.sha1(index_bytes).hexdigest()}}
|
||||
monkeypatch.setattr(asset, "find_useful_part_in_specific_version_manifest",
|
||||
lambda value: (None, value["assetIndex"], None, None, None, None, None))
|
||||
|
||||
def deny_network(*args, **kwargs):
|
||||
pytest.fail("Local legacy asset repair must not access the network")
|
||||
|
||||
monkeypatch.setattr(asset.requests, "get", deny_network)
|
||||
return manifest, assets_dir, tmp_path, source, destination, content
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy_assets", ["virtual", "map_to_resources"], indirect=True)
|
||||
def test_complete_legacy_assets_pass_without_network(legacy_assets):
|
||||
manifest, assets_dir, root, source, destination, content = legacy_assets
|
||||
destination.parent.mkdir(parents=True)
|
||||
destination.write_bytes(content)
|
||||
assert asset.check_assets_exist(manifest, assets_dir, root)
|
||||
assert asset.download_assets(manifest, assets_dir, root) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy_assets", ["virtual", "map_to_resources"], indirect=True)
|
||||
@pytest.mark.parametrize("damaged", [False, True])
|
||||
def test_legacy_copy_repaired_from_objects_without_network(legacy_assets, damaged):
|
||||
manifest, assets_dir, root, source, destination, content = legacy_assets
|
||||
if damaged:
|
||||
destination.parent.mkdir(parents=True)
|
||||
# Same size, different content: the default check must verify SHA-1.
|
||||
destination.write_bytes(b"x" * len(content))
|
||||
assert not asset.check_assets_exist(manifest, assets_dir, root)
|
||||
assert asset.download_assets(manifest, assets_dir, root) == []
|
||||
assert destination.read_bytes() == content
|
||||
assert asset.check_assets_exist(manifest, assets_dir, root)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy_assets", ["virtual", "map_to_resources"], indirect=True)
|
||||
def test_missing_object_is_still_reported(legacy_assets):
|
||||
manifest, assets_dir, root, source, destination, content = legacy_assets
|
||||
destination.parent.mkdir(parents=True)
|
||||
destination.write_bytes(content)
|
||||
source.unlink()
|
||||
assert not asset.check_assets_exist(manifest, assets_dir, root)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy_assets", ["virtual", "map_to_resources"], indirect=True)
|
||||
def test_corrupt_cached_index_is_not_trusted(legacy_assets, monkeypatch):
|
||||
manifest, assets_dir, root, source, destination, content = legacy_assets
|
||||
index = assets_dir / "indexes" / "fixture.json"
|
||||
original = json.loads(index.read_text(encoding="utf-8"))
|
||||
index.write_text("{}", encoding="utf-8")
|
||||
fetched = []
|
||||
|
||||
def fetch(version, path):
|
||||
fetched.append(path)
|
||||
return original
|
||||
|
||||
monkeypatch.setattr(asset, "fetch_and_save_asset_manifest", fetch)
|
||||
assert asset.download_assets(manifest, assets_dir, root) == []
|
||||
assert fetched == [index]
|
||||
assert destination.read_bytes() == content
|
||||
@@ -0,0 +1,153 @@
|
||||
import hashlib
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from core_lib.game import version_info
|
||||
from core_lib.common.exception import VersionManifestSaveException
|
||||
from manager.game import ManifestManager
|
||||
from pages.test import TestPage as LauncherTestPage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cache(tmp_path):
|
||||
app = SimpleNamespace(work_dir=tmp_path, widget_manager=MagicMock(), logger=MagicMock())
|
||||
return ManifestManager(app)
|
||||
|
||||
|
||||
def write_cache(cache, data, version=None):
|
||||
path = cache.switch_between_specific_path(version)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = json.dumps(data).encode("utf-8")
|
||||
path.write_bytes(payload)
|
||||
return path, payload
|
||||
|
||||
|
||||
def reply(cache, answer):
|
||||
def respond(request):
|
||||
request.result_queue.put(answer)
|
||||
request.wait_event.set()
|
||||
cache.widget_mgr.signal.askyesno.emit.side_effect = respond
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", [True, False])
|
||||
def test_stale_root_requires_consent_and_only_one_final_notice(cache, monkeypatch, answer):
|
||||
data = {"versions": []}
|
||||
write_cache(cache, data)
|
||||
fetch = MagicMock(side_effect=OSError("offline"))
|
||||
monkeypatch.setattr("manager.game.fetch_and_save_version_manifest", fetch)
|
||||
reply(cache, answer)
|
||||
assert cache.get_cached_version_manifest(max_age=-1) == (data if answer else None)
|
||||
assert fetch.call_count == 3
|
||||
assert cache.use_expired_manifest is answer
|
||||
cache.widget_mgr.signal.askyesno.emit.assert_called_once()
|
||||
cache.widget_mgr.signal.show_error_message.emit.assert_not_called()
|
||||
assert cache.widget_mgr.signal.show_warning_message.emit.call_count == int(answer)
|
||||
if answer:
|
||||
assert cache.get_cached_version_manifest(max_age=-1) == data
|
||||
assert fetch.call_count == 3
|
||||
assert not ManifestManager(cache.app).use_expired_manifest
|
||||
|
||||
|
||||
def test_timeout_does_not_enable_flag(cache, monkeypatch):
|
||||
write_cache(cache, {"versions": []})
|
||||
monkeypatch.setattr(cache, "_cache_version_manifest", lambda *args, **kwargs: (False, None))
|
||||
monkeypatch.setattr("manager.game.AskForRequest.wait", lambda *args: False)
|
||||
assert cache.get_cached_version_manifest(max_age=-1) is None
|
||||
assert not cache.use_expired_manifest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [None, b"{broken", b"[]", b"{}", b'{"versions":[{"id":"x"}]}'])
|
||||
def test_unusable_root_never_asks_or_enables_flag(cache, monkeypatch, payload):
|
||||
if payload is not None:
|
||||
cache.version_manifest_path.parent.mkdir(parents=True)
|
||||
cache.version_manifest_path.write_bytes(payload)
|
||||
fetch = MagicMock(return_value=(False, None))
|
||||
monkeypatch.setattr(cache, "_cache_version_manifest", fetch)
|
||||
assert cache.get_cached_version_manifest(max_age=-1) is None
|
||||
assert fetch.call_count == 3
|
||||
assert not cache.use_expired_manifest
|
||||
cache.widget_mgr.signal.askyesno.emit.assert_not_called()
|
||||
cache.widget_mgr.signal.show_error_message.emit.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tampered", [False, True])
|
||||
def test_specific_version_hash_is_checked_even_when_flag_enabled(cache, monkeypatch, tampered):
|
||||
data = {"id": "fixture", "mainClass": "Main"}
|
||||
path, payload = write_cache(cache, data, "fixture")
|
||||
write_cache(cache, {"versions": [{"id": "fixture", "url": "https://example.invalid",
|
||||
"sha1": hashlib.sha1(payload).hexdigest()}]})
|
||||
if tampered:
|
||||
path.write_text(json.dumps({**data, "mainClass": "Wrong"}), encoding="utf-8")
|
||||
cache.use_expired_manifest = True
|
||||
fetch = MagicMock(return_value=(False, None))
|
||||
monkeypatch.setattr(cache, "_cache_version_manifest", fetch)
|
||||
assert cache.get_cached_version_manifest("fixture", max_age=-1) == (None if tampered else data)
|
||||
assert fetch.call_count == (3 if tampered else 0)
|
||||
cache.widget_mgr.signal.askyesno.emit.assert_not_called()
|
||||
|
||||
|
||||
def test_custom_manifest_shares_fallback_and_session_flag(cache):
|
||||
data = {"id": "loader", "inheritsFrom": "vanilla"}
|
||||
write_cache(cache, data, "loader")
|
||||
fetch = MagicMock(side_effect=OSError("offline"))
|
||||
reply(cache, True)
|
||||
assert cache.get_cached_custom_version_manifest("loader", fetch, max_age=-1) == data
|
||||
assert fetch.call_count == 3
|
||||
assert cache.get_cached_custom_version_manifest("loader", fetch, max_age=-1) == data
|
||||
assert fetch.call_count == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload,sha1", [(b"{broken", None), (b'{"id":"fixture"}', "0" * 40)])
|
||||
def test_failed_save_preserves_original_and_cleans_temporary_files(tmp_path, payload, sha1):
|
||||
path = tmp_path / "manifest.json"
|
||||
path.write_bytes(b"previous content")
|
||||
with pytest.raises(VersionManifestSaveException):
|
||||
version_info.save_version_manifest(payload, path, sha1)
|
||||
assert path.read_bytes() == b"previous content"
|
||||
assert list(tmp_path.iterdir()) == [path]
|
||||
|
||||
|
||||
def test_failed_download_verification_keeps_valid_specific_cache(cache, monkeypatch):
|
||||
data = {"id": "fixture", "mainClass": "Main"}
|
||||
path, payload = write_cache(cache, data, "fixture")
|
||||
root = {"versions": [{"id": "fixture", "url": "https://example.invalid",
|
||||
"sha1": hashlib.sha1(payload).hexdigest()}]}
|
||||
write_cache(cache, root)
|
||||
fetched = MagicMock(return_value=(b'{"id":"fixture","mainClass":"Wrong"}', hashlib.sha1(payload).hexdigest()))
|
||||
monkeypatch.setattr(version_info, "fetch_specific_version_manifest", fetched)
|
||||
reply(cache, True)
|
||||
assert cache.get_cached_version_manifest("fixture", max_age=-1) == data
|
||||
assert fetched.call_count == 3
|
||||
assert path.read_bytes() == payload
|
||||
assert not list(path.parent.glob("*.tmp"))
|
||||
|
||||
|
||||
def test_structurally_invalid_refresh_does_not_replace_cache(tmp_path, monkeypatch):
|
||||
path = tmp_path / "manifest.json"
|
||||
path.write_bytes(b"previous content")
|
||||
monkeypatch.setattr(version_info, "fetch_specific_version_manifest", lambda *args: (b"{}", None))
|
||||
with pytest.raises(ValueError):
|
||||
version_info.fetch_and_save_version_manifest(path, "fixture", {"versions": []})
|
||||
assert path.read_bytes() == b"previous content"
|
||||
|
||||
|
||||
def test_successful_save_preserves_downloaded_bytes(tmp_path):
|
||||
payload = b'{ "id": "fixture", "mainClass": "Main" }'
|
||||
path = tmp_path / "manifest.json"
|
||||
assert version_info.save_version_manifest(payload, path, hashlib.sha1(payload).hexdigest())["id"] == "fixture"
|
||||
assert path.read_bytes() == payload
|
||||
assert list(tmp_path.iterdir()) == [path]
|
||||
|
||||
|
||||
def test_test_page_fetch_runs_in_worker(monkeypatch):
|
||||
page = SimpleNamespace(button=MagicMock(), output=MagicMock(), get_selected_version=lambda: "fixture",
|
||||
_fetch_version_data=MagicMock())
|
||||
worker = MagicMock()
|
||||
monkeypatch.setattr("pages.test.threading.Thread", worker)
|
||||
LauncherTestPage.run_test(page)
|
||||
worker.assert_called_once_with(target=page._fetch_version_data, args=("fixture",), daemon=True)
|
||||
worker.return_value.start.assert_called_once()
|
||||
page._fetch_version_data.assert_not_called()
|
||||
@@ -0,0 +1,85 @@
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
from core_lib.game import argument, library_core
|
||||
from core_lib.game.argument import ArgumentMappings, generate_launch_command
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def windows_platform(monkeypatch):
|
||||
for module in (argument, library_core):
|
||||
monkeypatch.setattr(module, "get_natives_platform_info", lambda: ("windows", "windows", "x86_64"))
|
||||
monkeypatch.setattr(module, "get_platform_info", lambda: ("windows", "amd64", "10.0.26100"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path_argument, subdirectory", [
|
||||
(None, ""),
|
||||
("-Djava.library.path=${natives_directory}", ""),
|
||||
("-Djava.library.path=${natives_directory}/java", "java"),
|
||||
({"value": ["-Djava.library.path=${natives_directory}/java"]}, "java"),
|
||||
({"rules": [{"action": "allow", "os": {"name": "osx"}}],
|
||||
"value": "-Djava.library.path=${natives_directory}/java"}, ""),
|
||||
])
|
||||
def test_download_check_and_command_share_native_directory(tmp_path, monkeypatch, path_argument, subdirectory):
|
||||
libraries_dir = tmp_path / "libraries"
|
||||
natives_root = tmp_path / "natives"
|
||||
archive = libraries_dir / "native.jar"
|
||||
libraries_dir.mkdir()
|
||||
with zipfile.ZipFile(archive, "w") as jar:
|
||||
jar.writestr("windows/example.dll", b"native fixture")
|
||||
jar.writestr("META-INF/MANIFEST.MF", "excluded")
|
||||
|
||||
manifest = {
|
||||
"assetIndex": {"id": "fixture"},
|
||||
"downloads": {"client": {}},
|
||||
"mainClass": "example.Main",
|
||||
"arguments": {"jvm": [] if path_argument is None else [path_argument], "game": ["--demo"]},
|
||||
"libraries": [{
|
||||
"name": "example:native:1:natives-windows",
|
||||
"downloads": {"artifact": {"path": "native.jar"}},
|
||||
}],
|
||||
}
|
||||
# Downloads are stubbed; native selection, extraction and checking use real code.
|
||||
monkeypatch.setattr(library_core, "collect_library_artifacts", lambda _: [])
|
||||
monkeypatch.setattr(library_core, "download_libraries", lambda *args, **kwargs: ([], []))
|
||||
|
||||
assert not library_core.check_natives_exists(manifest, libraries_dir, natives_root)
|
||||
library_core.download_full_libraries(manifest, libraries_dir, natives_root)
|
||||
|
||||
extract_dir = natives_root / subdirectory
|
||||
native_file = extract_dir / "example.dll"
|
||||
assert native_file.read_bytes() == b"native fixture"
|
||||
assert not (extract_dir / "META-INF").exists()
|
||||
assert not (natives_root / "java" / "java").exists()
|
||||
assert library_core.check_full_libraries_exists(manifest, libraries_dir, natives_root)
|
||||
|
||||
command = generate_launch_command(
|
||||
ArgumentMappings(natives_directory=natives_root.as_posix(), classpath="client.jar"),
|
||||
"example.Main", "java", manifest["arguments"],
|
||||
)
|
||||
assert f"-Djava.library.path={extract_dir.as_posix()}" in command
|
||||
assert command[-2:] == ["example.Main", "--demo"]
|
||||
|
||||
native_file.unlink()
|
||||
assert not library_core.check_natives_exists(manifest, libraries_dir, natives_root)
|
||||
|
||||
|
||||
def test_feature_rules_and_last_applicable_property(tmp_path):
|
||||
manifest = {"arguments": {"jvm": [
|
||||
"-Djava.library.path=${natives_directory}",
|
||||
{"rules": [{"action": "allow", "features": {"new_layout": True}}],
|
||||
"value": "-Djava.library.path=${natives_directory}/java"},
|
||||
]}}
|
||||
locate = library_core.locate_natives_extract_dir_by_manifest
|
||||
assert locate(manifest, tmp_path) == tmp_path
|
||||
assert locate(manifest, tmp_path, features={"new_layout": True}) == tmp_path / "java"
|
||||
assert locate({"minecraftArguments": "--demo"}, tmp_path) == tmp_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", ["/../outside", "//absolute", "/C:/outside", "/java;other", "other"])
|
||||
def test_unsupported_native_layout_is_rejected(tmp_path, suffix):
|
||||
with pytest.raises(ValueError):
|
||||
library_core.locate_natives_extract_dir(
|
||||
["-Djava.library.path=${natives_directory}" + suffix], tmp_path,
|
||||
)
|
||||
@@ -164,8 +164,8 @@ def test_account_client_id_is_a_valid_uuid() -> None:
|
||||
manager.load_defaults()
|
||||
|
||||
custom_id = "12345678-1234-5678-9abc-123456789abc"
|
||||
updated = manager.set("account", {"client_id": custom_id})
|
||||
assert str(updated.client_id) == custom_id
|
||||
updated = manager.set("account", {"custom_client_id": custom_id})
|
||||
assert str(updated.custom_client_id) == custom_id
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
manager.set("account", {"client_id": "not-a-client-id"})
|
||||
manager.set("account", {"custom_client_id": "not-a-client-id"})
|
||||
@@ -0,0 +1,181 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QTimer, QEvent, QPointF
|
||||
from PySide6.QtGui import QPalette, QEnterEvent
|
||||
from PySide6.QtWidgets import QApplication, QWidget, QDialog, QMessageBox, QPushButton
|
||||
|
||||
from app import Launcher
|
||||
from core_lib.qt import messagebox
|
||||
from pages.launch_profile import ProfileListItem
|
||||
from pages.manage_profile import ManageProfileItem
|
||||
|
||||
|
||||
class StylesheetApp:
|
||||
locate_styles_path = Launcher.locate_styles_path
|
||||
apply_qss = Launcher.apply_qss
|
||||
apply_theme = Launcher.apply_theme
|
||||
_read_theme_manifest = staticmethod(Launcher._read_theme_manifest)
|
||||
_read_palette = staticmethod(Launcher._read_palette)
|
||||
_palette_from_colors = staticmethod(Launcher._palette_from_colors)
|
||||
|
||||
def __init__(self, root, qt_app):
|
||||
self.qt_app = qt_app
|
||||
self.styles_path = root / "styles"
|
||||
self.styles_path.mkdir()
|
||||
self.theme_dir = root / "custom"
|
||||
(self.theme_dir / "styles").mkdir(parents=True)
|
||||
self.settings_manager = SimpleNamespace(
|
||||
get=lambda *_: SimpleNamespace(theme="custom")
|
||||
)
|
||||
self._system_palette = QPalette(qt_app.palette())
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.setPalette = qt_app.setPalette
|
||||
self.setStyleSheet = qt_app.setStyleSheet
|
||||
self.allWidgets = qt_app.allWidgets
|
||||
|
||||
def _theme_packages(self):
|
||||
return {"custom": self.theme_dir}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def style_app(tmp_path):
|
||||
qt_app = QApplication.instance() or QApplication([])
|
||||
palette = QPalette(qt_app.palette())
|
||||
stylesheet = qt_app.styleSheet()
|
||||
yield StylesheetApp(tmp_path, qt_app)
|
||||
qt_app.setStyleSheet(stylesheet)
|
||||
qt_app.setPalette(palette)
|
||||
|
||||
|
||||
def test_theme_stylesheet_override_and_default_fallback(style_app):
|
||||
default = style_app.styles_path / "main.qss"
|
||||
default.write_text("QWidget { color: red; }", encoding="utf-8")
|
||||
override = style_app.theme_dir / "styles" / "main.qss"
|
||||
assert style_app.locate_styles_path(Path("main.qss")) == default
|
||||
override.mkdir() # A directory is not a usable stylesheet.
|
||||
assert style_app.locate_styles_path(Path("main.qss")) == default
|
||||
override.rmdir()
|
||||
override.write_text("QWidget { color: blue; }", encoding="utf-8")
|
||||
assert style_app.locate_styles_path(Path("main.qss")) == override
|
||||
|
||||
|
||||
def test_switching_theme_reloads_stylesheets(style_app):
|
||||
default_qss = "/* 預設樣式 */ QWidget { color: red; }"
|
||||
default = style_app.styles_path / "main.qss"
|
||||
default.write_text(default_qss, encoding="utf-8")
|
||||
override = style_app.theme_dir / "styles" / "main.qss"
|
||||
override.write_text("QWidget { color: blue; }", encoding="utf-8")
|
||||
widget = QWidget()
|
||||
style_app.apply_qss(Path("main.qss"), widget.setStyleSheet)
|
||||
assert widget.styleSheet() == override.read_text(encoding="utf-8")
|
||||
style_app.apply_theme("system")
|
||||
assert widget.styleSheet() == default_qss
|
||||
assert style_app.locate_styles_path(Path("main.qss")) == default
|
||||
widget.close()
|
||||
|
||||
|
||||
def test_invalid_theme_falls_back_to_default_styles(style_app):
|
||||
default = style_app.styles_path / "main.qss"
|
||||
default.write_text("QWidget { color: red; }", encoding="utf-8")
|
||||
style_app.apply_theme("custom") # Missing palette and manifest.
|
||||
assert style_app._active_theme == "system"
|
||||
assert style_app.locate_styles_path(Path("main.qss")) == default
|
||||
|
||||
|
||||
@pytest.mark.parametrize("theme, background", [("aqua", "#f1f3f7"), ("windows-9x", "#c0c0c0"), ("bliss", "#ece9d8")])
|
||||
def test_message_boxes_follow_application_theme(style_app, theme, background):
|
||||
style_app.theme_dir = Path(__file__).resolve().parents[1] / "resources/themes" / theme
|
||||
style_app.apply_theme("custom")
|
||||
parent = QWidget()
|
||||
boxes = [messagebox.create_messagebox(owner, "Theme", "Message")
|
||||
for owner in (None, parent)]
|
||||
for box in boxes:
|
||||
box.ensurePolished()
|
||||
assert box.testOption(QMessageBox.Option.DontUseNativeDialog)
|
||||
assert box.palette().color(QPalette.ColorRole.Window).name() == background
|
||||
button = box.button(QMessageBox.StandardButton.Ok)
|
||||
button.ensurePolished()
|
||||
assert (button.palette().brush(QPalette.ColorRole.Button).gradient() is not None) == (theme in {"aqua", "bliss"})
|
||||
(style_app.styles_path / "main.qss").write_text("", encoding="utf-8")
|
||||
style_app.apply_theme("system")
|
||||
assert style_app.qt_app.styleSheet() == ""
|
||||
for box in boxes:
|
||||
box.close()
|
||||
|
||||
|
||||
def test_static_question_inherits_aqua(style_app):
|
||||
style_app.theme_dir = Path(__file__).resolve().parents[1] / "resources/themes/aqua"
|
||||
style_app.apply_theme("custom")
|
||||
colors = []
|
||||
|
||||
def accept_question():
|
||||
box = style_app.qt_app.activeModalWidget()
|
||||
colors.append(box.palette().color(QPalette.ColorRole.Window).name())
|
||||
box.button(QMessageBox.StandardButton.Yes).click()
|
||||
|
||||
QTimer.singleShot(0, accept_question)
|
||||
result = QMessageBox.question(None, "Confirm", "Continue?")
|
||||
assert result == QMessageBox.StandardButton.Yes
|
||||
assert colors == ["#f1f3f7"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("question", [False, True])
|
||||
def test_detailed_dialogs_inherit_aqua(style_app, monkeypatch, question):
|
||||
style_app.theme_dir = Path(__file__).resolve().parents[1] / "resources/themes/aqua"
|
||||
style_app.apply_theme("custom")
|
||||
checked = []
|
||||
|
||||
def inspect_dialog(dialog):
|
||||
dialog.ensurePolished()
|
||||
buttons = dialog.findChildren(QPushButton)
|
||||
assert buttons
|
||||
for button in buttons:
|
||||
button.ensurePolished()
|
||||
assert button.palette().brush(QPalette.ColorRole.Button).gradient() is not None
|
||||
checked.append(True)
|
||||
return QDialog.DialogCode.Accepted
|
||||
|
||||
monkeypatch.setattr(QDialog, "exec", inspect_dialog)
|
||||
if question:
|
||||
assert messagebox.ask_yes_no_with_plain_text(None, "Confirm", "Message", "Details")
|
||||
else:
|
||||
messagebox.error_with_plain_text(None, "Error", "Message", "Details")
|
||||
assert checked == [True]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("theme, normal_color", [("aqua", "#626d7e"), ("windows-9x", "#404040"), ("bliss", "#555d69")])
|
||||
@pytest.mark.parametrize("managed", [False, True])
|
||||
def test_profile_label_colors_follow_button_state(style_app, theme, normal_color, managed):
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
style_app.theme_dir = root / "resources/themes" / theme
|
||||
style_app.apply_theme("custom")
|
||||
style_app.icon_dir = root / "resources/icons"
|
||||
profile = SimpleNamespace(icon=str(style_app.icon_dir / "profile_default.png"),
|
||||
display_name="Example", version_id="1.21")
|
||||
container = QWidget()
|
||||
filename = "manage_profile.qss" if managed else "profile.qss"
|
||||
style_app.apply_qss(Path(filename), container.setStyleSheet)
|
||||
row = (ManageProfileItem(style_app, profile, container) if managed
|
||||
else ProfileListItem(profile, container))
|
||||
label = row.findChild(QWidget, "itemVersion")
|
||||
label.ensurePolished()
|
||||
|
||||
def color():
|
||||
return label.palette().color(QPalette.ColorRole.WindowText).name()
|
||||
|
||||
assert color() == normal_color
|
||||
if managed:
|
||||
row.setChecked(True)
|
||||
else:
|
||||
point = QPointF(4, 4)
|
||||
QApplication.sendEvent(row, QEnterEvent(point, point, point))
|
||||
assert color() == "#ffffff"
|
||||
if managed:
|
||||
row.setChecked(False)
|
||||
else:
|
||||
QApplication.sendEvent(row, QEvent(QEvent.Type.Leave))
|
||||
assert color() == normal_color
|
||||
container.close()
|
||||
Reference in new issue
Block a user