diff --git a/backend/projects.py b/backend/projects.py index bed1911..5bfacb3 100644 --- a/backend/projects.py +++ b/backend/projects.py @@ -68,6 +68,16 @@ LEGACY_PROJECT_DEFINITION = { "dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []}, } +# 英汉大词典(readoorDict,TARGETTYPE == 2)的服务器地址:Readoor 项目的服务器环境内置这些字段, +# 打包时写入 STSConstantsMacro.h 中 TARGETTYPE == 2 段落的同名宏(字段名去掉 DICT_ 前缀即宏名)。 +READOOR_DICT_SERVER_FIELDS = [ + {"key": "DICT_SERVERURL", "label": "词典 SERVERURL", "required": False}, + {"key": "DICT_SERVERHTTPSURL", "label": "词典 SERVERHTTPSURL", "required": False}, + {"key": "DICT_UCSERVERURL", "label": "词典 UCSERVERURL", "required": False}, + {"key": "DICT_RECORDSERVERURL", "label": "词典 RECORDSERVERURL", "required": False}, + {"key": "DICT_LOGSERVERURL", "label": "词典 LOGSERVERURL", "required": False}, +] + # 当前请求操作的项目,由 main.py 的中间件按请求头 X-Project 设置; # load_config() 未显式指定项目时使用它,未设置则取第一个项目。 PROJECT_HEADER = "X-Project" @@ -109,6 +119,11 @@ def get_definition(project_id: str, project: dict) -> dict: definition["dingtalk_at"] = {**defaults["dingtalk_at"], **(definition.get("dingtalk_at") or {})} if definition["patcher"] not in PATCHERS: definition["patcher"] = PATCHER_GENERIC + if definition["patcher"] == PATCHER_READOOR: + keys = {field.get("key") for field in definition["server_fields"]} + definition["server_fields"] = list(definition["server_fields"]) + [ + dict(field) for field in READOOR_DICT_SERVER_FIELDS if field["key"] not in keys + ] return definition diff --git a/backend/services/project_patcher.py b/backend/services/project_patcher.py index b5561b7..60bb0a9 100644 --- a/backend/services/project_patcher.py +++ b/backend/services/project_patcher.py @@ -117,11 +117,78 @@ def _write_export_options(build_dir: Path, config: dict): plistlib.dump(data, f) +# 词典环境宏 ← 服务器环境字段(APPID 取 App 的 AppGuid) +DICT_SERVER_MACROS = { + "SERVERURL": "DICT_SERVERURL", + "SERVERHTTPSURL": "DICT_SERVERHTTPSURL", + "UCSERVERURL": "DICT_UCSERVERURL", + "RECORDSERVERURL": "DICT_RECORDSERVERURL", + "LOGSERVERURL": "DICT_LOGSERVERURL", +} +_DICT_BLOCK_START = re.compile(r"^\s*#\s*(?:el)?if\s+TARGETTYPE\s*==\s*2\s*$") +_PP_OPEN = re.compile(r"^\s*#\s*if") +_PP_BRANCH = re.compile(r"^\s*#\s*(?:elif|else)\b") +_PP_CLOSE = re.compile(r"^\s*#\s*endif\b") + + +def _replace_dict_env_macros(content: str, values: dict) -> str: + """只替换 TARGETTYPE == 2 段落中未注释的 #define,其它 TARGETTYPE 的同名宏不动。""" + lines = content.splitlines(keepends=True) + start = next((i for i, line in enumerate(lines) if _DICT_BLOCK_START.match(line)), None) + if start is None: + raise ProjectPatchError("STSConstantsMacro.h 中未找到 #elif TARGETTYPE == 2 词典配置段") + counts = {name: 0 for name in values} + depth = 0 + for i in range(start + 1, len(lines)): + line = lines[i] + if _PP_OPEN.match(line): + depth += 1 + continue + if _PP_CLOSE.match(line) or _PP_BRANCH.match(line): + if depth == 0: + break + if _PP_CLOSE.match(line): + depth -= 1 + continue + for name, value in values.items(): + if re.match(rf"^\s*#define\s+{name}\b", line): + ending = "\n" if line.endswith("\n") else "" + lines[i] = f'#define {name} @"{value}"{ending}' + counts[name] += 1 + missing = [name for name, count in counts.items() if count == 0] + if missing: + raise ProjectPatchError(f"词典配置段中未找到未注释的宏: {', '.join(missing)}") + return "".join(lines) + + +def _dict_env_values(config: dict) -> dict: + """服务器环境中的词典地址;全部未配置返回空(沿用源码),部分配置视为错误。""" + server_vars = config.get("SERVER_VARS") or {} + values = {macro: str(server_vars.get(key, "") or "").strip() for macro, key in DICT_SERVER_MACROS.items()} + if not any(values.values()): + return {} + missing = [DICT_SERVER_MACROS[macro] for macro, value in values.items() if not value] + if missing: + raise ProjectPatchError(f"服务器环境 {config.get('SERVER', '')} 的词典地址未配置完整: {', '.join(missing)}") + if not str(config.get("APPID", "") or "").strip(): + raise ProjectPatchError("词典 App 未配置 AppGuid,无法写入 APPID") + return {"APPID": str(config["APPID"]).strip(), **values} + + def _apply_dictionary_config(build_dir: Path, config: dict, messages: list[str]): macro = build_dir / "readoor" / "BookShelf" / "Classes" / "Macro" / "STSConstantsMacro.h" if not macro.exists(): raise ProjectPatchError(f"词典配置文件不存在: {macro}") content = macro.read_text(encoding="utf-8") + env_values = _dict_env_values(config) + if env_values: + content = _replace_dict_env_macros(content, env_values) + messages.append( + f"已替换词典环境配置({config.get('SERVER', '')}): APPID {env_values['APPID']}," + f"SERVERURL {env_values['SERVERURL']}" + ) + else: + messages.append(f"服务器环境 {config.get('SERVER', '')} 未配置词典地址,沿用源码中的词典环境配置") version = config.get("VERSION", "") content, count = re.subn( r'^(#define\s+SOURCE_VERSION\s+)@"[^"]*"', diff --git a/tests/test_project_patcher.py b/tests/test_project_patcher.py index d6d8e31..24c11fa 100644 --- a/tests/test_project_patcher.py +++ b/tests/test_project_patcher.py @@ -1,7 +1,9 @@ """服务端工程配置替换测试。""" import plistlib -from backend.services.project_patcher import apply_project_config +import pytest + +from backend.services.project_patcher import ProjectPatchError, apply_project_config def test_apply_project_config_without_branch_autopacking(tmp_path): @@ -111,3 +113,86 @@ def test_wxwork_schema_removed_when_not_configured(tmp_path): with plist_path.open("rb") as f: url_types = plistlib.load(f)["CFBundleURLTypes"] assert all(i.get("CFBundleURLName") != "wxwork" for i in url_types) + + +# ---- 英汉大词典(readoorDict)---- + +_DICT_MACRO = """#define SOURCE_VERSION @"1.0.0" +#if TARGETTYPE == 1 || TARGETTYPE == 3 +#define APPID @"other" +#define SERVERURL @"http://other/" +#elif TARGETTYPE == 2 +//#define SERVERURL @"http://commented/" + #define APPID @"old" //旧环境 + #define SERVERURL @"http://old/" + #define SERVERHTTPSURL @"https://old/" + #define UCSERVERURL @"https://uc-old/" + #define RECORDSERVERURL @"http://record-old/" + #define LOGSERVERURL @"http://log-old/" +#endif +""" + +_DICT_SERVER_VARS = { + "DICT_SERVERURL": "http://api-stage3/", + "DICT_SERVERHTTPSURL": "https://api-stage3/", + "DICT_UCSERVERURL": "https://uc-dev/", + "DICT_RECORDSERVERURL": "http://record-dev/", + "DICT_LOGSERVERURL": "http://log-dev/", +} + + +def _dict_build(tmp_path): + macro = tmp_path / "readoor" / "BookShelf" / "Classes" / "Macro" / "STSConstantsMacro.h" + macro.parent.mkdir(parents=True) + macro.write_text(_DICT_MACRO, encoding="utf-8") + return macro + + +def _dict_config(**extra): + return {"SCHEME": "readoorDict", "VERSION": "2.0.0", "SERVER": "词典测试", "APPID": "1593413622", + "NO_CERT": True, "BUILD_TYPE": "Ad_Hoc", **extra} + + +def test_dict_env_macros_replaced_only_in_targettype_2(tmp_path): + macro = _dict_build(tmp_path) + apply_project_config(tmp_path, _dict_config(SERVER_VARS=_DICT_SERVER_VARS), {"patcher": "readoor"}) + content = macro.read_text() + + assert '#define SOURCE_VERSION @"2.0.0"' in content + assert '#define APPID @"1593413622"' in content + assert '#define SERVERURL @"http://api-stage3/"' in content + assert '#define LOGSERVERURL @"http://log-dev/"' in content + # 其它 TARGETTYPE 与注释行不变 + assert '#define APPID @"other"' in content + assert '#define SERVERURL @"http://other/"' in content + assert '//#define SERVERURL @"http://commented/"' in content + assert "http://old/" not in content + + +def test_dict_env_not_configured_keeps_source(tmp_path): + macro = _dict_build(tmp_path) + messages = apply_project_config(tmp_path, _dict_config(SERVER_VARS={}), {"patcher": "readoor"}) + content = macro.read_text() + + assert '#define SERVERURL @"http://old/"' in content + assert '#define APPID @"old"' in content + assert any("沿用源码" in m for m in messages) + + +def test_dict_env_partially_configured_fails(tmp_path): + _dict_build(tmp_path) + with pytest.raises(ProjectPatchError, match="DICT_LOGSERVERURL"): + apply_project_config( + tmp_path, + _dict_config(SERVER_VARS={**_DICT_SERVER_VARS, "DICT_LOGSERVERURL": ""}), + {"patcher": "readoor"}, + ) + + +def test_readoor_definition_has_dict_server_fields(): + from backend.projects import LEGACY_PROJECT_ID, get_definition + + keys = [f["key"] for f in get_definition(LEGACY_PROJECT_ID, {"server_fields": []})["server_fields"]] + assert keys == ["DICT_SERVERURL", "DICT_SERVERHTTPSURL", "DICT_UCSERVERURL", + "DICT_RECORDSERVERURL", "DICT_LOGSERVERURL"] + assert get_definition("other", {"patcher": "generic"})["server_fields"] == []