Files
myrzx_bot/tools/build_battle_v3.py
T

109 lines
5.9 KiB
Python

"""Repack and sign the prepared V3 SWFs without operating any Android device."""
import hashlib
import json
import subprocess
import uuid
import zipfile
from pathlib import Path
from repack_apk import repack_members
ROOT = Path(__file__).resolve().parent.parent
ANALYSIS = ROOT / "analysis"
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(4 * 1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def run(*args: str) -> None:
subprocess.run(list(map(str, args)), cwd=ROOT, check=True)
def build(mode_filter: str = "both", revision: str = "V3", refresh_air_cache: bool = False, *, build_tools: Path) -> None:
source = ROOT / "\u7267\u7f8a\u4eba\u4e4b\u5fc3_1.9.68.apk"
expected = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
if sha256(source) != expected:
raise ValueError("Original APK digest mismatch")
manifest = {"original_sha256": expected, "packages": []}
for mode, label in (("damage", "\u4f24\u5bb310\u500d"), ("stats", "\u5c5e\u60272\u500d")):
if mode_filter != "both" and mode_filter != mode:
continue
suffix = label + ("_\u7f13\u5b58\u4fee\u590d" if refresh_air_cache else "_\u8bca\u65ad") + revision
unsigned = ANALYSIS / f"{revision.lower()}_{mode}_unsigned.apk"
aligned = ANALYSIS / f"{revision.lower()}_{mode}_aligned.apk"
output = ROOT / f"\u7267\u7f8a\u4eba\u4e4b\u5fc3_1.9.68_{suffix}.apk"
replacements = {"assets/MYRMain.app": ANALYSIS / f"MYRMain_{mode}_{revision.lower()}.app", "assets/MYRDyd.swf": ANALYSIS / "MYRDyd_v3.swf"}
cache_id = None
if refresh_air_cache:
with zipfile.ZipFile(source) as archive:
original_manifest = archive.read("AndroidManifest.xml")
old_id = "978ba13e-4b54-44d5-ae53-24335a039748"
cache_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "myrzx-local-" + mode + "-" + sha256(replacements["assets/MYRMain.app"])))
candidates = [(old_id.encode(enc), cache_id.encode(enc)) for enc in ("utf-8", "utf-16le")]
matching = [(old, new) for old, new in candidates if original_manifest.count(old) == 1]
if len(matching) != 1:
raise ValueError("Expected exactly one original AIR cache UUID string")
old, new = matching[0]
patched_manifest = original_manifest.replace(old, new)
if len(patched_manifest) != len(original_manifest):
raise ValueError("Manifest patch changed string-pool layout")
manifest_path = ANALYSIS / f"{revision.lower()}_{mode}_AndroidManifest.xml"
manifest_path.write_bytes(patched_manifest)
replacements["AndroidManifest.xml"] = manifest_path
print(f"New AIR extracted-code cache ID: {cache_id}", flush=True)
print(f"Repacking {mode}", flush=True)
repack_members(source, replacements, unsigned)
run(build_tools / "zipalign.exe", "-f", "-p", "4", unsigned, aligned)
if refresh_air_cache:
xmltree = subprocess.check_output([str(build_tools / "aapt.exe"), "dump", "xmltree", str(aligned), "AndroidManifest.xml"]).decode("utf-8", errors="replace")
if cache_id not in xmltree or '"uniqueappversionid"' not in xmltree or '"MYRDyd.swf"' not in xmltree:
raise ValueError("Compiled Android manifest validation failed")
(ANALYSIS / f"{revision.lower()}_manifest_dump.txt").write_text(xmltree, encoding="utf-8")
run(build_tools / "apksigner.bat", "sign", "--ks", ANALYSIS / "myrzx-local-test.p12",
"--ks-key-alias", "myrzx-local", "--ks-pass", "pass:myrzx-local-test",
"--key-pass", "pass:myrzx-local-test", "--out", output, aligned)
run(build_tools / "zipalign.exe", "-c", "-p", "4", output)
run(build_tools / "apksigner.bat", "verify", "--verbose", "--print-certs", output)
with zipfile.ZipFile(output) as apk, zipfile.ZipFile(source) as original:
bad = apk.testzip()
if bad is not None:
raise ValueError(f"ZIP CRC failure: {bad}")
changed = []
for entry in original.infolist():
if entry.filename.startswith("META-INF/"):
continue
actual = apk.getinfo(entry.filename)
if (entry.CRC, entry.file_size) != (actual.CRC, actual.file_size):
changed.append(entry.filename)
if sorted(changed) != sorted(replacements):
raise ValueError(f"Unexpected changed members: {changed}")
for member, replacement in replacements.items():
if apk.read(member) != replacement.read_bytes():
raise ValueError(f"Packaged bytes mismatch: {member}")
manifest["packages"].append({"path": output.name, "mode": mode, "sha256": sha256(output),
"size": output.stat().st_size, "changed_members": changed, "air_cache_id": cache_id})
print(f"Verified {output.name}", flush=True)
# These are intermediates created by this build; retain only the signed deliverable.
unsigned.unlink()
aligned.unlink()
(ANALYSIS / f"battle_{revision.lower()}_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"{revision} build and archive/signature checks complete", flush=True)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mode", choices=("both", "damage", "stats"), default="both")
parser.add_argument("--revision", choices=("V3", "V4"), default="V3")
parser.add_argument("--refresh-air-cache", action="store_true")
parser.add_argument("--build-tools", type=Path, required=True, help="Android SDK build-tools directory")
args = parser.parse_args()
build(args.mode, args.revision, args.refresh_air_cache, build_tools=args.build_tools)