新增完整的 lightcore-cli 命令行工具代码,包含: - CLI 入口与参数解析 - System 和 Media 应用的客户端实现 - 丰富的子命令与操作接口 - 测试用例与项目配置 - .gitignore 与 README 文档
137 lines
6.2 KiB
Python
137 lines
6.2 KiB
Python
import argparse
|
||
from pathlib import Path
|
||
import re
|
||
from uuid import UUID, uuid4
|
||
|
||
from .transport import ClientError, MultipartBody, compact
|
||
|
||
DOCUMENT = "/content/document/"
|
||
|
||
|
||
def positive_int(value):
|
||
parsed = int(value)
|
||
if parsed <= 0:
|
||
raise argparse.ArgumentTypeError("需要正整数")
|
||
return parsed
|
||
|
||
|
||
def checked_result(client, response):
|
||
if response.get("downloaded"):
|
||
return response
|
||
payload = response["json"]
|
||
if client.success(response) and isinstance(payload.get("data"), dict):
|
||
return payload["data"]
|
||
message = ""
|
||
if isinstance(payload, dict):
|
||
message = payload.get("msg") or payload.get("message") or ""
|
||
raise ClientError(
|
||
message[:240] if isinstance(message, str) and message else "Media 未返回预期结果。",
|
||
**{key: response[key] for key in ("httpStatus", "code", "traceId") if response[key] is not None},
|
||
)
|
||
|
||
|
||
def request(client, path, fields):
|
||
return checked_result(client, client.exchange(path, compact(fields).encode("utf-8")))
|
||
|
||
|
||
def find(client, args):
|
||
data = request(client, DOCUMENT + "getDocumentList", {
|
||
"keyword": args.keyword, "pageNo": args.page, "pageSize": args.limit,
|
||
})
|
||
return {"ok": True, "total": data["total"], "page": args.page, "items": [
|
||
{"documentId": item["id"], "title": item["title"]} for item in data.get("list") or []
|
||
]}
|
||
|
||
|
||
def document_files(client, document_id):
|
||
data = request(client, DOCUMENT + "getDocumentDetail", {"documentId": document_id})
|
||
return [
|
||
{"fileId": item["id"], "fileName": item["fileName"],
|
||
"mimeType": item["mimeType"], "bytes": item["fileSize"]}
|
||
for item in data.get("files") or []
|
||
]
|
||
|
||
|
||
def list_files(client, args):
|
||
return {"ok": True, "documentId": args.document_id,
|
||
"items": document_files(client, args.document_id)}
|
||
|
||
|
||
def upload(client, args):
|
||
request_id = str(args.request_id or uuid4())
|
||
fields = {"requestId": request_id}
|
||
if args.category:
|
||
fields["category"] = args.category
|
||
try:
|
||
payload = MultipartBody(args.file, fields)
|
||
response = client.exchange("/content/social/uploadAsset", payload)
|
||
file = checked_result(client, response)
|
||
if type(file.get("id")) is not int or file["id"] <= 0:
|
||
raise ClientError("Media 上传回执缺少有效文件 ID。")
|
||
except ClientError as error:
|
||
raise ClientError(str(error), **error.details, requestId=request_id) from None
|
||
return {"ok": True, "fileId": file["id"]}
|
||
|
||
|
||
def local_name(file):
|
||
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", file["fileName"]).strip(" .")
|
||
return f'{file["fileId"]}-{name or "attachment"}'
|
||
|
||
|
||
def get_files(client, args):
|
||
files = {file["fileId"]: file for file in document_files(client, args.document_id)}
|
||
directory = args.output_dir or Path(".work", "media", str(args.document_id))
|
||
items = []
|
||
for file_id in dict.fromkeys(args.file_id):
|
||
file = files.get(file_id)
|
||
if file is None:
|
||
items.append({"ok": False, "fileId": file_id, "message": "文件不属于当前文档。"})
|
||
continue
|
||
try:
|
||
fields = {"documentId": args.document_id, "fileId": file_id}
|
||
result = client.exchange(
|
||
DOCUMENT + "downloadAsset", compact(fields).encode("utf-8"),
|
||
output=directory / local_name(file),
|
||
)
|
||
if not result.get("downloaded"):
|
||
checked_result(client, result)
|
||
raise ClientError("Media 响应未包含可下载的文件。")
|
||
except ClientError as error:
|
||
items.append({"ok": False, "fileId": file_id, "message": str(error), **error.details})
|
||
else:
|
||
items.append({"ok": True, "fileId": file_id,
|
||
"outputFile": result["outputFile"], "bytes": result["bytes"]})
|
||
return {"ok": all(item["ok"] for item in items), "items": items}
|
||
|
||
|
||
def add_file_commands(commands):
|
||
files = commands.add_parser("files", help="查找资料、列出附件、上传或下载文件")
|
||
actions = files.add_subparsers(required=True)
|
||
search = actions.add_parser("find", help="按关键词查找 Media 资料文档",
|
||
description='示例 lightcore media files find --keyword "推窗器"。返回文档 ID 和标题。')
|
||
search.add_argument("--keyword", required=True, help="文档标题或正文关键词")
|
||
search.add_argument("--page", type=positive_int, default=1, help="页码,默认 1")
|
||
search.add_argument("--limit", type=int, choices=range(1, 101), metavar="条数",
|
||
default=10, help="每页 1–100 条,默认 10")
|
||
search.set_defaults(handler=find, endpoint=DOCUMENT + "getDocumentList")
|
||
|
||
listing = actions.add_parser("list", help="查看文档的附件清单",
|
||
description="示例 lightcore media files list --document-id 58。返回文件 ID、名称、类型和大小。")
|
||
listing.add_argument("--document-id", type=positive_int, required=True)
|
||
listing.set_defaults(handler=list_files, endpoint=DOCUMENT + "getDocumentDetail")
|
||
|
||
sending = actions.add_parser("upload", help="上传一个本地文件到 Media",
|
||
description='示例 lightcore media files upload "推窗器说明书.pdf"。返回 fileId。')
|
||
sending.add_argument("file", type=Path, help="文件路径")
|
||
sending.add_argument("--category", help="可选的 Media 文件分类")
|
||
sending.add_argument("--request-id", type=UUID, help="核对结果后重试时复用的上传 UUID")
|
||
sending.set_defaults(handler=upload, endpoint="/content/social/uploadAsset")
|
||
|
||
download = actions.add_parser("get", help="从文档下载指定附件",
|
||
description="示例 lightcore media files get --document-id 58 --file-id 123。返回本地路径和字节数。")
|
||
download.add_argument("--document-id", type=positive_int, required=True)
|
||
download.add_argument("--file-id", type=positive_int, action="append", required=True, help="附件 ID,可重复指定")
|
||
download.add_argument("--output-dir", type=Path, help="保存目录,默认 .work/media/<文档 ID>")
|
||
download.set_defaults(handler=get_files, endpoint=DOCUMENT + "downloadAsset")
|
||
return actions
|