Add auto detect java installation support.

This commit is contained in:
2026-07-14 01:13:36 +08:00
parent bd5a1e8974
commit 425f740d8f
9 changed files with 546 additions and 200 deletions
+9 -2
View File
@@ -68,22 +68,26 @@ def replace_placeholders(argument, placeholders: dict) -> str:
class ArgumentMappings:
def __init__(self, player_name="Player", version_name="unknown",
game_directory=None, assets_root=None, assets_index_name=None,
game_directory=None, assets_root=None, legacy_assets_root=None, assets_index_name=None,
auth_uuid="00000001-0002-0003-0004-000000000005",
auth_access_token="", clientid=None, auth_xuid=None,
user_type=None, version_type=None, natives_directory=None,
user_type=None, user_properties=None, version_type=None, natives_directory=None,
launcher_name=None, launcher_version=None,
classpath=None, classpath_separator=None, library_directory=None):
self.player_name = player_name
self.version_name = version_name
self.game_directory = game_directory
self.assets_root = assets_root
self.game_assets = legacy_assets_root
self.assets_index_name = assets_index_name
self.auth_uuid = auth_uuid
self.auth_access_token = auth_access_token
self.clientid = clientid
self.auth_xuid = auth_xuid
self.user_type = user_type
self.user_properties = user_properties
if not isinstance(user_properties, dict):
self.user_properties = {}
self.version_type = version_type
self.natives_directory = natives_directory
self.launcher_name = launcher_name
@@ -98,13 +102,16 @@ class ArgumentMappings:
"version_name": self.version_name,
"game_directory": self.game_directory,
"assets_root": self.assets_root,
"game_assets": self.game_assets,
"assets_index_name": self.assets_index_name,
"auth_uuid": self.auth_uuid,
"auth_session": self.auth_access_token,
"auth_access_token": self.auth_access_token,
"auth_player_name": self.player_name,
"clientid": self.clientid,
"auth_xuid": self.auth_xuid,
"user_type": self.user_type,
"user_properties": self.user_properties,
"version_type": self.version_type,
"natives_directory": self.natives_directory,
"launcher_name": self.launcher_name,
+83 -8
View File
@@ -9,7 +9,8 @@ import requests
from core_lib.common.common import FileObject, download_multiple_files
from core_lib.common.exception import VersionDataKeyNotFoundException, AssetManifestFetchException, \
HashMismatchException, AssetManifestSaveException, AssetDataKeyNotFoundException, DownloadException
HashMismatchException, AssetManifestSaveException, AssetDataKeyNotFoundException, DownloadException, \
AssetManifestException
from core_lib.game.version_info import find_useful_part_in_specific_version_manifest
MOJANG_RESOURCE_ENDPOINT = "https://resources.download.minecraft.net/{beginning}/{hash}"
@@ -103,14 +104,17 @@ def fetch_and_save_asset_manifest(target_version_manifest: dict, destination: Pa
"Error saving version manifest:\n{}".format(e)
)
def _check_asset(asset_id: str, asset_data: dict, relative_path: str, assets_dir: Path, virtual: bool, no_hash_check: bool=False)\
def _check_asset(asset_id: str, asset_data: dict, relative_path: str, assets_dir: Path, launcher_root: Path, virtual: bool,
map_to_resources: bool, no_hash_check: bool=False)\
-> tuple[FileObject | None, dict | None]:
"""
Check if asset exists.
:param asset_data:
:param relative_path:
:param assets_dir:
:param launcher_root:
:param virtual:
:param map_to_resources:
:return:
asset_file: FileObject
legacy_context: dict
@@ -151,15 +155,23 @@ def _check_asset(asset_id: str, asset_data: dict, relative_path: str, assets_dir
if virtual:
legacy_context = {
"file": file,
"target": full_path if virtual else None,
"target": full_path,
"sha1": hash_raw,
"destination": Path(assets_dir, "virtual", asset_id, relative_path) if virtual else None,
"destination": Path(assets_dir, "virtual", asset_id, relative_path),
"size": expected_size,
}
elif map_to_resources:
legacy_context = {
"file": file,
"target": full_path,
"sha1": hash_raw,
"destination": Path(launcher_root, "resources", relative_path),
"size": expected_size,
}
return file if needs_download else None, legacy_context
def collect_assets_from_manifest(manifest: dict, asset_id: str, assets_dir: Path,
def collect_assets_from_manifest(manifest: dict, asset_id: str, assets_dir: Path, launcher_root: Path,
max_workers=ASSET_CHECK_MAX_WORKERS,
no_hash_check=False) -> tuple[list[FileObject], list[dict]]:
"""
@@ -168,6 +180,7 @@ def collect_assets_from_manifest(manifest: dict, asset_id: str, assets_dir: Path
:param manifest:
:param asset_id:
:param assets_dir:
:param launcher_root:
:param max_workers:
:return:
assets: list[FileObject]
@@ -175,6 +188,7 @@ def collect_assets_from_manifest(manifest: dict, asset_id: str, assets_dir: Path
"""
objects = manifest.get("objects", [])
virtual = manifest.get("virtual", False)
map_to_resources = manifest.get("map_to_resources", False)
files = []
legacy_assets = []
@@ -188,7 +202,7 @@ def collect_assets_from_manifest(manifest: dict, asset_id: str, assets_dir: Path
futures = [
executor.submit(
_check_asset,
asset_id, objects[relative_path], relative_path, assets_dir, virtual,
asset_id, objects[relative_path], relative_path, assets_dir, launcher_root, virtual, map_to_resources,
no_hash_check=no_hash_check
)
for relative_path in objects
@@ -341,7 +355,7 @@ def correct_assets_name_and_copy(manifest: dict, assets_dir: Path, output_dir: P
return missing
def download_assets(manifest: dict, assets_dir: Path, no_hash_check: bool=False,
def download_assets(manifest: dict, assets_dir: Path, launcher_root: Path, no_hash_check: bool=False,
progress_callback: Callable[[str, float], None]=None,
redownload_callback: Callable[[list[FileObject]], tuple[bool, list[FileObject]]]=None) -> list[FileObject]:
_, asset_index, _, _, _, _, _ = find_useful_part_in_specific_version_manifest(manifest)
@@ -366,6 +380,7 @@ def download_assets(manifest: dict, assets_dir: Path, no_hash_check: bool=False,
asset_manifest,
asset_id,
assets_dir,
launcher_root,
no_hash_check=no_hash_check,
)
@@ -377,4 +392,64 @@ def download_assets(manifest: dict, assets_dir: Path, no_hash_check: bool=False,
redownload_callback=redownload_callback,
)
return fails
return fails
def check_assets_exist(manifest: dict, assets_dir: Path, launcher_root: Path, no_hash_check: bool=False) -> bool:
_, asset_index, _, _, _, _, _ = find_useful_part_in_specific_version_manifest(manifest)
asset_id = asset_index.get("id")
if not asset_id:
raise VersionDataKeyNotFoundException(
"Asset ID is missing."
)
index_path = Path(assets_dir, "indexes", f"{asset_id}.json")
asset_manifest = None
if not (index_path.exists() and index_path.is_file()):
fetch_and_save_asset_manifest(
manifest,
index_path,
)
with index_path.open() as f:
asset_manifest = json.load(f)
# Download assets files
assets, legacy_assets = collect_assets_from_manifest(
asset_manifest,
asset_id,
assets_dir,
launcher_root,
no_hash_check=no_hash_check,
)
if not assets and not legacy_assets:
return True
return False
def read_exist_assets_indexes(asset_id: str, assets_dir: Path):
return json.loads(Path(assets_dir, "indexes", f"{asset_id}.json").open().read())
def find_correct_assets_dir(asset_id: str, assets_dir: Path, launcher_root: Path, asset_manifest: dict | None=None) -> Path:
try:
if not asset_manifest:
asset_manifest = read_exist_assets_indexes(asset_id, assets_dir)
except FileNotFoundError:
raise AssetManifestException(
"Asset manifest not found in: {} (Index: {})".format(assets_dir, asset_id),
)
virtual = asset_manifest.get("virtual")
map_to_resources = asset_manifest.get("map_to_resources")
if virtual:
return assets_dir / "virtual" / asset_id
if map_to_resources:
return launcher_root / "resources"
return assets_dir
+156 -12
View File
@@ -1,6 +1,7 @@
import json
import logging
import re
import zipfile
from pathlib import Path
from typing import Callable
@@ -81,7 +82,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)
@@ -96,10 +98,12 @@ def is_native_allowed(lib_name, platform_key_name, platform_arch_type, unspecifi
native_os_name = parts[1]
if unspecified_arch_policy == "universal":
arch_type = platform_arch_type
logger.debug(f"This native may for platform \"{native_os_name}\" (\"May\" for all architecture type)")
logger.debug(
f"This native may for platform \"{native_os_name}\" (\"May\" for all architecture type)")
else:
arch_type = unspecified_arch_policy
logger.debug(f"This native may for platform \"{native_os_name}\" and specific architecture type {unspecified_arch_policy}")
logger.debug(
f"This native may for platform \"{native_os_name}\" and specific architecture type {unspecified_arch_policy}")
elif len(parts) == 3: # With architecture type
native_os_name, arch_type = parts[1], parts[2]
@@ -120,7 +124,9 @@ def is_native_allowed(lib_name, platform_key_name, platform_arch_type, unspecifi
return False
def is_legacy_native_allowed(natives, classifiers, platform_rule_name, platform_arch_type, unspecified_arch_policy: str="x86_64") -> tuple[bool, dict | None, str | None]:
def is_legacy_native_allowed(natives, classifiers, platform_rule_name, platform_arch_type,
unspecified_arch_policy: str = "x86_64") -> tuple[bool, dict | None, str | None]:
valid_non_arch_values = {
"universal",
"x86",
@@ -174,10 +180,12 @@ def is_legacy_native_allowed(natives, classifiers, platform_rule_name, platform_
if unspecified_arch_policy == "universal":
universal = True
arch_type = platform_arch_type
logger.debug(f"This native may for platform \"{native_os_name}\" (\"May\" for all architecture type)")
logger.debug(
f"This native may for platform \"{native_os_name}\" (\"May\" for all architecture type)")
else:
arch_type = unspecified_arch_policy
logger.debug(f"This native may for platform \"{native_os_name}\" and specific architecture type {unspecified_arch_policy}")
logger.debug(
f"This native may for platform \"{native_os_name}\" and specific architecture type {unspecified_arch_policy}")
elif len(parts) == 3:
native_os_name, arch_type = parts[1].lower(), parts[2].lower()
logger.debug(f"This native may for platform \"{native_os_name}\" and architecture type \"{arch_type}\"")
@@ -195,6 +203,7 @@ def is_legacy_native_allowed(natives, classifiers, platform_rule_name, platform_
return False, None, None
def generate_relative_path_by_maven_coordinate(maven_coordinate: str, extra=None) -> str | None:
parts = maven_coordinate.split(":")
@@ -213,6 +222,7 @@ def generate_relative_path_by_maven_coordinate(maven_coordinate: str, extra=None
return f"{base_path}/{artifact}/{version}/{filename}.jar"
def remove_duplicate_artifacts(artifacts: list[dict], ignore_null=False, compare_by_name=False) -> list[dict]:
seen = set()
result = []
@@ -238,8 +248,9 @@ def remove_duplicate_artifacts(artifacts: list[dict], ignore_null=False, compare
return result
def generate_formatted_artifact_with_name(lib_name, lib_artifact, libraries_endpoint=MOJANG_LIBRARIES_ENDPOINT,
extra: dict | None=None, relative_args: dict|None=None) -> dict | None:
extra: dict | None = None, relative_args: dict | None = None) -> dict | None:
"""
Generates a formatted artifact
:param lib_name: Library name
@@ -277,6 +288,7 @@ def generate_formatted_artifact_with_name(lib_name, lib_artifact, libraries_endp
return artifact_new
def collect_library_artifacts(specific_version_manifest):
_, _, _, _, libraries, _, _ = find_useful_part_in_specific_version_manifest(specific_version_manifest)
@@ -439,7 +451,8 @@ 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) \
-> tuple[list[FileObject], list[FileObject]]:
"""
Download libraries from a list that contains artifacts
@@ -487,6 +500,7 @@ def download_libraries(artifacts, output_dir, progress_callback: Callable[[str,
return fails, successes
def unzip_natives(filtered, libraries_dir, destination: Path):
"""
Unzip native libraries from a list that contains artifacts
@@ -579,6 +593,136 @@ def check_libraries_exists(manifest: dict, libraries_dir: Path):
return not_found
def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path):
filtered = []
# Convert current platform and architecture type to same formula
_, _, os_version = get_platform_info()
platform_key_name, platform_rule_name, platform_arch_type = get_natives_platform_info()
if platform_key_name is None or platform_arch_type is None or platform_rule_name is None:
raise UnsupportedPlatformException(
f"Unsupported platform: key={platform_key_name}, "
f"rule={platform_rule_name}, arch={platform_arch_type}"
)
_, _, _, _, libraries, _, _ = find_useful_part_in_specific_version_manifest(manifest)
for library in libraries:
name = library.get("name", "")
artifact = library.get("downloads", {}).get("artifact", {})
# For newer Minecraft (VER>1.7.10)
rules = library.get("rules", [])
# For legacy version (VER<1.8)
classifiers = library.get("downloads", {}).get("classifiers", {})
natives = library.get("natives", {})
exclude = library.get("extract", {}).get("exclude", ["META-INF/"]) # For extract use
is_natives = False
# Check if library is a native
if (len(natives) > 0 or bool(re.search(r":natives-[^:]+$", name)) or
any(native.startswith("natives-") for native in classifiers)):
is_natives = True
if not is_natives:
continue
# =============== New rules ===============
# Parse action section
if not is_library_allowed(
rules,
platform_rule_name,
platform_arch_type,
os_version,
):
continue
if is_native_allowed(
name,
platform_key_name,
platform_arch_type,
):
result_artifact = generate_formatted_artifact_with_name(name, artifact, extra={"exclude": exclude,
"flatten": True})
if result_artifact:
filtered.append(result_artifact)
# =============== Old rules ===============
result, result_artifact, classifier = is_legacy_native_allowed(
natives,
classifiers,
platform_rule_name,
platform_arch_type,
)
if not result:
continue
result_artifact = generate_formatted_artifact_with_name(name,
result_artifact,
extra={"exclude": exclude, "flatten": True},
relative_args={
"extra": classifier
})
if result_artifact:
filtered.append(result_artifact)
# Remove duplicate items
items = remove_duplicate_artifacts(filtered)
if not filtered:
raise NativeResolveException(
"No compatible native artifact found.",
user_message="No compatible native library was found for this platform.",
)
elif not items:
raise NativeResolveException(
"No compatible native artifact found. Report developer because this may be a issue"
" at function \"remove_duplicate_artifacts\"",
)
expected = set()
for result_artifact in items:
full_path = libraries_dir / Path(result_artifact["path"])
exclude = result_artifact.get("exclude", []) or []
flatten = result_artifact.get("flatten", False)
if not full_path.is_file() or not full_path.exists():
return False
with zipfile.ZipFile(full_path) as zf:
for member in zf.namelist():
if member.endswith("/"):
continue
if any(member.startswith(item) for item in exclude):
continue
target = Path(member).name if flatten else member
if target:
expected.add(target)
if not expected:
return False
for target in expected:
if not (natives_dir / target).exists():
return False
return True
def check_full_libraries_exists(manifest: dict, libraries_dir: Path, natives_dir: Path) -> bool:
if not check_natives_exists(manifest, libraries_dir, natives_dir) or not check_libraries_exists(manifest, libraries_dir):
return False
return True
def generate_classpath(manifest: dict, libraries_dir: Path, core_file_path: Path):
"""
Generate classpath by using specific version's data
@@ -645,9 +789,11 @@ def generate_classpath(manifest: dict, libraries_dir: Path, core_file_path: Path
return f"{separator}".join(classes)
def download_full_libraries(manifest: dict, libraries_dir: Path, natives_dir: Path,
progress_callback: Callable[[str, float], None]=None,
redownload_callback: Callable[[list[FileObject]], tuple[bool, list[FileObject]]]=None) -> None:
progress_callback: Callable[[str, float], None] = None,
redownload_callback: Callable[
[list[FileObject]], tuple[bool, list[FileObject]]] = None) -> None:
# libraries
libraries = collect_library_artifacts(manifest)
@@ -683,5 +829,3 @@ def download_full_libraries(manifest: dict, libraries_dir: Path, natives_dir: Pa
raise DependencyException(
"Certain libraries download failed. Unable to continue unzip process.\n"
)