"""CLI entry points for the System Admin HTTP API.""" import argparse import json from pathlib import Path import re import subprocess from .api import format_response from .shop_visual import render from .system_client import LOGIN_PATH, LOGOUT_PATH from .system_routes import GROUPS from .system_schema import REQUESTS from .transport import ClientError, MultipartBody, compact, private_output, reject_constant PRIVATE_INPUT_FIELDS = { "accessKey", "accessKeyId", "accessKeySecret", "apiKey", "clientSecret", "secretKey", "password", "oldPassword", "newPassword", "token", } def example_value(name, field): if "type" not in field: return {} if "const" in field: return field["const"] if "default" in field: return field["default"] if "examples" in field: return field["examples"][0] if "enum" in field: return field["enum"][0] if field["type"] == "array": return [example_value(name, field["items"])] if field["type"] == "object": return {key: example_value(key, spec) for key, spec in field.get("properties", {}).items()} if field["type"] == "integer": return 600 if name == "ttl" else field.get("minimum", 1) if field["type"] == "boolean": return True if field["type"] == "number": return field.get("minimum", 0.0) examples = {"uuid": "0198d956-1111-4444-8888-111111111111", "uri": "https://example.com/", "email": "admin@example.com", "binary": "example.png"} if field.get("format") in examples: return examples[field["format"]] return {"rr": "www", "value": "192.0.2.1", "domains": "example.com", "domainName": "example.com", "modules": "system", "tables": "system_admin_users"}.get(name, "示例") class ShowRequest(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): schema = namespace.request_schema result = schema if option_string == "--example": result = {name: example_value(name, field) for name, field in schema["properties"].items() if name in schema["required"] or "default" in field or "examples" in field} print(json.dumps(result, ensure_ascii=False, indent=2)) parser.exit() def request_body(args): flags = {name: getattr(args, name) for name in args.fields if getattr(args, name) is not None} if args.body_file is None: return {name: field["default"] for name, field in args.request_schema["properties"].items() if "default" in field and args.mode != "upload"} | flags if flags: raise ClientError("--body-file 与字段参数只能选择一种。") try: with args.body_file.open("rb") as stream: raw = stream.read((8 << 20) + 1) if len(raw) > 8 << 20: raise ClientError("请求文件不能超过 8 MiB。") body = json.loads(raw.decode("utf-8-sig"), parse_constant=reject_constant, object_pairs_hook=unique_fields) except ValueError: raise ClientError("请求正文必须是有效且无重复字段的 JSON 对象。") from None if not isinstance(body, dict): raise ClientError("请求正文必须是 JSON 对象。") return body def unique_fields(pairs): fields = {} for key, value in pairs: if key in fields: raise ValueError("duplicate JSON field") fields[key] = value return fields def save_private_json(args, data, details): target = args.output.absolute() try: with private_output(target) as stream: stream.write((compact(data) + "\n").encode("utf-8")) except (OSError, subprocess.SubprocessError, ClientError): raise ClientError("已收到服务端响应,但私有输出保存失败。", **details) from None return {"ok": True, **details, "outputFile": str(target)} def call(client, args): if args.output is not None and (args.output.exists() or args.output.is_symlink()): raise ClientError("目标文件已存在,拒绝覆盖。") body = request_body(args) if getattr(args, "dry_run", False): body["dryRun"] = True client.remember_secrets(body) if client.app == "shop" and args.endpoint in ( "/general/agentPublicFile/importFile", "/content/workspaceAgent/importAttachment", ) and isinstance(body.get("url"), str): client.secrets.append(body["url"]) if args.mode == "render": return render(client, args, body) if args.mode == "metadata-upload": payload = MultipartBody(args.file, {"metadata": compact(body)}, reject_symlink=True) elif args.mode == "upload": payload = MultipartBody(args.file, body, reject_symlink=client.app == "shop") else: payload = compact(body).encode("utf-8") try: response = client.exchange(args.endpoint, payload, output=args.output if args.mode in ("zip", "download") else None) except ClientError as error: if "结果未知" in str(error): meta = body.get("meta") request_id = body.get("requestId") or (meta.get("requestId") if isinstance(meta, dict) else None) if request_id: error.details["requestId"] = request_id if body.get("idempotencyKey"): error.details["idempotencyKey"] = body["idempotencyKey"] raise if response.get("downloaded"): return response details = {key: response[key] for key in ("httpStatus", "code", "traceId")} if args.mode in ("zip", "download", "private-output"): if not client.success(response): message = (response["json"] or {}).get("msg") if isinstance(response["json"], dict) else None raise ClientError(message or "请求失败。", **details) if args.mode in ("zip", "download"): raise ClientError("响应未包含可下载文件。", **details) data = response["json"].get("data") if not isinstance(data, dict) or not data: raise ClientError("响应未包含所需数据。", **details) return save_private_json(args, data, details) if args.endpoint == "/user/updatePassword" and client.success(response): data = response["json"].get("data") if not isinstance(data, dict) or data.get("success") is not True: message = (data or {}).get("message") if isinstance(data, dict) else None raise ClientError(message or "System 密码修改失败。", **details) return format_response(client, response, Path.cwd() / ".work" / "lightcore" / client.app, args.max_chars) def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=None, *, schema=None): command = actions.add_parser(name, help=summary, description=summary, allow_abbrev=False) if schema is None: request = REQUESTS[request_type] if request_type else {"properties": {}, "required": []} schema = {"type": "object", **request} private_input = bool(PRIVATE_INPUT_FIELDS.intersection(schema["properties"])) inputs = command.add_mutually_exclusive_group(required=private_input) inputs.add_argument("--schema", action=ShowRequest, nargs=0, help="离线查看请求字段、类型和约束") inputs.add_argument("--example", action=ShowRequest, nargs=0, help="离线生成示例请求") if mode in ("upload", "metadata-upload"): command.add_argument("--file", type=Path, required=True, help="上传的本机文件") if mode != "upload" or schema["properties"].keys() - {"file"}: label = "本机私有 JSON 输入文件" if private_input else "UTF-8 JSON 请求文件" inputs.add_argument("--body-file", type=Path, help=label) if mode in ("zip", "download", "private-output"): command.add_argument("--output", type=Path, required=True, help="私有输出路径,拒绝覆盖") if mode == "render": command.add_argument("--output-dir", dest="output", type=Path, required=True, help="私有视觉包输出目录") command.add_argument("--renderer", type=Path, help="本地 light 可执行文件路径") fields = [] if not private_input: for field, spec in schema["properties"].items(): value_type = spec.get("type") if isinstance(value_type, list): value_type = value_type[0] repeated = value_type == "array" if repeated: value_type = spec.get("items", {}).get("type") if field in ("file", "dryRun") or value_type not in ("string", "integer", "number", "boolean"): continue flag = "--" + re.sub(r"[A-Z]", lambda hit: "-" + hit[0].lower(), field) label = f"JSON 字段 {field}" if field in schema["required"] and "default" not in spec: label += ",必填" options = {"dest": field, "help": label} if repeated: options.update(action="append", help=f"{label},可重复指定") if value_type == "integer": options["type"] = int if value_type == "number": options["type"] = float if value_type == "boolean": options.update(type=parse_bool, metavar="true|false") if "enum" in spec: options["choices"] = spec["enum"] if "default" in spec: options["help"] += f",默认 {spec['default']}" command.add_argument(flag, **options) fields.append(field) command.set_defaults(handler=call, endpoint=f"{prefix}/{endpoint}" if prefix else endpoint, mode=mode, request_schema=schema, output=None, body_file=None, fields=fields) if "dryRun" in schema["properties"]: command.add_argument("--dry-run", action="store_true", help="只预检输入与状态") def parse_bool(value): if value not in ("true", "false"): raise argparse.ArgumentTypeError("需要 true 或 false") return value == "true" def add_commands(commands): login = commands.add_parser("login", help="交互登录 System 并保存本机会话") login.add_argument("--base-url", help="目标后端地址,首次登录必填") login.set_defaults(handler=lambda client, args: client.login(args.base_url), endpoint=LOGIN_PATH) logout = commands.add_parser("logout", help="在服务端退出并清理本机 Token") logout.set_defaults(handler=lambda client, _: client.logout(), endpoint=LOGOUT_PATH) for group, (summary, prefix, operations) in GROUPS.items(): section = commands.add_parser(group, help=summary, description=summary) actions = section.add_subparsers(required=True) for operation in operations: add_operation(actions, prefix, *operation)