Skip to content

The only downloader you need. 下载器的集大成者。

feat(i18n): sync 脚本支持生成 Android 字符串资源

XiaoYouChR710746fac9a9
diff --git a/scripts/sync_i18n_res.py b/scripts/sync_i18n_res.py
index 67ee24c0..10f55ec9 100644
--- a/scripts/sync_i18n_res.py
+++ b/scripts/sync_i18n_res.py
@@ -1,8 +1,10 @@
+import hashlib
import os
import re
import shutil
import subprocess
import sys
+import xml.etree.ElementTree as ET
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
@@ -21,6 +23,25 @@ I18N_DIR = ASSETS_DIR / "i18n"
QRC_PATH = ASSETS_DIR / "resources.qrc"
RESOURCES_RCC = ASSETS_DIR / "resources.rcc"
+ENGINE_CONTEXTS = ["TaskErrors", "BinaryRuntime"]
+
+COMPOSE_RES_DIR = REPO / "compose" / "app" / "src" / "main" / "res"
+COMPOSE_I18N_KT = (
+ REPO / "compose" / "app" / "src" / "main" / "java" / "io" / "github"
+ / "xiaoyouchr" / "ghostdownloader" / "i18n" / "EngineStrings.kt"
+)
+ANDROID_STRINGS_FILE = "strings_engine.xml"
+ANDROID_LOCALE_FOLDERS = {
+ "en_US": "values",
+ "zh_CN": "values-zh-rCN",
+ "zh_TW": "values-zh-rTW",
+ "zh_HK": "values-zh-rHK",
+ "ja_JP": "values-ja",
+ "ru_RU": "values-ru",
+ "pt_BR": "values-pt-rBR",
+ "es_ES": "values-es",
+}
+
def findTool(name: str) -> str:
path = shutil.which(name)
@@ -83,6 +104,76 @@ def updateQrcI18n() -> None:
QRC_PATH.write_text(text, encoding="utf-8")
+def readCatalog(locale: str) -> dict[str, tuple[str, str]]:
+ root = ET.parse(I18N_DIR / f"gd3.{locale}.ts").getroot()
+ entries: dict[str, tuple[str, str]] = {}
+ for context in root.findall("context"):
+ ctxName = context.findtext("name")
+ if ctxName not in ENGINE_CONTEXTS:
+ continue
+ for message in context.findall("message"):
+ source = message.findtext("source") or ""
+ node = message.find("translation")
+ if locale == "zh_CN":
+ text = source
+ elif node is None or node.get("type") == "unfinished":
+ continue
+ else:
+ text = (node.text or "").strip()
+ if source and text:
+ digest = hashlib.sha1(source.encode("utf-8")).hexdigest()[:8]
+ resName = f"engine_{ctxName.lower()}_{digest}"
+ entries[resName] = (source, text)
+ return entries
+
+
+def buildAndroidStrings() -> None:
+ source = readCatalog("zh_CN")
+ if not source:
+ raise SystemExit(f"No messages found for contexts {ENGINE_CONTEXTS}")
+
+ nameToSource = {}
+ for name, (text, _) in source.items():
+ if name in nameToSource:
+ raise SystemExit(f"resourceName collision: {text!r} vs {nameToSource[name]!r}")
+ nameToSource[name] = text
+
+ for locale, folder in ANDROID_LOCALE_FOLDERS.items():
+ entries = readCatalog(locale)
+ if locale == "en_US":
+ entries = {name: entries.get(name, source[name]) for name in source}
+ if not entries:
+ continue
+ target = COMPOSE_RES_DIR / folder
+ target.mkdir(parents=True, exist_ok=True)
+ xmlLines = ["<!-- Generated by scripts/sync_i18n_res.py -->", "<resources>"]
+ for resource in sorted(entries):
+ text = entries[resource][1]
+ for old, new in (("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"),
+ ("'", "\\'"), ('"', '\\"')):
+ text = text.replace(old, new)
+ xmlLines.append(
+ f' <string name="{resource}" formatted="false">{text}</string>'
+ )
+ xmlLines.append("</resources>")
+ (target / ANDROID_STRINGS_FILE).write_text("\n".join(xmlLines) + "\n", encoding="utf-8")
+
+ COMPOSE_I18N_KT.parent.mkdir(parents=True, exist_ok=True)
+ ktLines = [
+ "// Generated by scripts/sync_i18n_res.py",
+ "package io.github.xiaoyouchr.ghostdownloader.i18n",
+ "",
+ "import io.github.xiaoyouchr.ghostdownloader.R",
+ "",
+ "internal val engineStrings: Map<String, Int> = mapOf(",
+ ]
+ for resource in sorted(source):
+ text = source[resource][0].replace("\\", "\\\\").replace('"', '\\"')
+ ktLines.append(f' "{text}" to R.string.{resource},')
+ ktLines.append(")")
+ COMPOSE_I18N_KT.write_text("\n".join(ktLines) + "\n", encoding="utf-8")
+
+
def buildResources() -> None:
rcc = findTool("pyside6-rcc")
subprocess.run([
@@ -99,6 +190,7 @@ def main() -> int:
updateTsFiles(sources)
buildQmFiles()
updateQrcI18n()
+ buildAndroidStrings()
buildResources()
return 0