From 2d4659291dec8a7ad0930afe32a1f99cf041dd42 Mon Sep 17 00:00:00 2001 From: Xlxinxi Date: Sun, 22 Nov 2026 17:06:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=90=8C=E6=AD=A5=20Media=20CLI=20?= =?UTF-8?q?=E5=AF=B9=E6=A0=87=E7=B4=A0=E6=9D=90=E4=B8=8E=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 同步 LightCore d14de92a4 中的 CLI 变更。 --- README.md | 2 +- lightcore_cli/media.py | 10 +++ lightcore_cli/media_commands.py | 52 ++++++++++---- lightcore_cli/media_schema.py | 124 ++++++++++++++++++++++++++------ tests/test_media.py | 59 ++++++++++++++- 5 files changed, 208 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 9eecaad..ae1b389 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ lightcore media files get --document-id 58 --file-id 123 --file-id 124 上传响应超时后,核对原操作再使用错误输出中的 `requestId` 发起重试。临时下载、应用会话和本机配置留在使用设备。不同用户用自己的 Media 账号登录。 -Media 的子命令覆盖后台登录、刷新和退出、个人资料、管理员、社媒账号、稿件、参考内容、发布登记、文档、短剧、文件和存储绑定。 +Media 的子命令覆盖后台登录、刷新和退出、个人资料、管理员、社媒账号、稿件、对标素材、发布登记、文档、短剧、文件和存储绑定。 从 `lightcore media --help` 找命令组,在具体命令末尾加 `--help` 查参数。例如 `contents list --help` 显示 `--page-size` 范围 1–100、默认 20,以及 `--content-type` 的可选值。 diff --git a/lightcore_cli/media.py b/lightcore_cli/media.py index babc7ad..a172af7 100644 --- a/lightcore_cli/media.py +++ b/lightcore_cli/media.py @@ -15,6 +15,13 @@ def positive_int(value): return parsed +def folder_id(value): + parsed = int(value) + if parsed < 0: + raise argparse.ArgumentTypeError("文件夹编号须大于或等于 0") + return parsed + + def checked_result(client, response): if response.get("downloaded"): return response @@ -62,6 +69,8 @@ def upload(client, args): fields = {"requestId": request_id} if args.category: fields["category"] = args.category + if args.folder_id is not None: + fields["folderId"] = str(args.folder_id) try: payload = MultipartBody(args.file, fields) response = client.exchange("/content/social/uploadAsset", payload) @@ -124,6 +133,7 @@ def add_file_commands(commands): description='示例 lightcore media files upload "推窗器说明书.pdf"。返回 fileId。') sending.add_argument("file", type=Path, help="文件路径") sending.add_argument("--category", help="可选的 Media 文件分类") + sending.add_argument("--folder-id", type=folder_id, help="指定文件夹,0 表示根目录") sending.add_argument("--request-id", type=UUID, help="核对结果后重试时复用的上传 UUID") sending.set_defaults(handler=upload, endpoint="/content/social/uploadAsset") diff --git a/lightcore_cli/media_commands.py b/lightcore_cli/media_commands.py index a0edaad..8013295 100644 --- a/lightcore_cli/media_commands.py +++ b/lightcore_cli/media_commands.py @@ -4,7 +4,7 @@ from pathlib import Path import re from .api import format_response -from .media import positive_int +from .media import folder_id, positive_int from .media_schema import CASES, DESCRIPTIONS, enum_for, example_body, request_schema from .transport import ClientError, compact, reject_constant @@ -46,14 +46,20 @@ GROUPS = { "contentId requestId expectedUpdatedAt fileId text prompt referenceFileIds notes", "json"), ("download", "downloadAsset", "下载与稿件关联的文件", "contentId* fileId*", "download"), ]), - "references": ("参考内容", SOCIAL, [ - ("list", "getReferenceList", "查询参考内容", f"{PAGINATION} keyword platform contentType"), - ("get", "getReferenceDetail", "查看参考内容详情", "referenceId*"), - ("save", "saveReference", "新建或更新参考内容", - "requestId referenceId platform contentType creatorName creatorHandle creatorProfileUrl " - "sourceContentUrl title bodyMarkdown coverFileIds mediaFileIds expectedUpdatedAt", "json"), - ("delete", "deleteReference", "删除参考内容记录", "referenceId requestId expectedUpdatedAt", "json"), - ("download", "downloadReferenceAsset", "下载与参考内容关联的文件", "referenceId* fileId*", "download"), + "references": ("对标素材", SOCIAL, [ + ("list", "getReferenceList", "查询作品与评估。Agent 选题使用 --for-topic-selection true", + f"{PAGINATION} keyword platform contentType creatorId publishedFrom publishedTo transcriptStatus assessment forTopicSelection sort"), + ("get", "getReferenceDetail", "读取作品详情和转写全文", "referenceId*"), + ("save", "saveReference", "按平台作品 ID 写入采集数据", + "requestId platform platformContentId sourceUrl videoFileUrl audioFileUrl contentType title description publishedAt durationSeconds " + "coverFileId viewCount likeCount favoriteCount commentCount shareCount collectedAt creator", "json"), + ("save-transcript", "saveReferenceTranscript", "保存作品转写", + "requestId referenceId expectedUpdatedAt transcriptStatus transcriptText transcriptSegments " + "transcriptLanguage transcriptModel transcribedAt", "json"), + ("save-assessment", "saveReferenceAssessment", "保存人工选题评估、参考点和备注", + "requestId referenceId expectedUpdatedAt assessment referencePoints topicNotes", "json"), + ("delete", "deleteReference", "删除作品记录及其评论", "referenceId requestId expectedUpdatedAt", "json"), + ("download", "downloadReferenceAsset", "下载与作品关联的封面", "referenceId* fileId*", "download"), ]), "publications": ("人工发布记录", SOCIAL, [ ("list", "getPublicationList", "查询已登记的发布记录", f"{PAGINATION} contentId accountKey"), @@ -61,10 +67,12 @@ GROUPS = { "requestId contentId accountKey publishedAt publicUrl", "json"), ]), "documents": ("通用文档和产品资料", DOCUMENT, [ - ("list", "getDocumentList", "查询文档", f"{PAGINATION} keyword excludeKeyword searchScope matchMode projectId"), + ("list", "getDocumentList", "查询文档,省略文件夹编号时搜索全库", f"{PAGINATION} keyword excludeKeyword searchScope matchMode projectId folderId"), ("get", "getDocumentDetail", "读取文档正文和附件", "documentId*"), - ("save", "saveDocument", "新建或更新文档以及附件关联", - "requestId documentId expectedUpdatedAt title bodyMarkdown fileIds", "json"), + ("save", "saveDocument", "新建、编辑或移动文档以及更新附件关联", + "requestId documentId expectedUpdatedAt title bodyMarkdown fileIds folderId", "json"), + ("folders", "getFolderTree", "列出文档文件夹及其父目录", ""), + ("save-folder", "saveFolder", "新建、重命名或移动文档文件夹", "requestId folderId parentId expectedUpdatedAt name", "json"), ("delete", "deleteDocument", "删除文档记录", "documentId requestId expectedUpdatedAt", "json"), ]), "projects": ("短剧项目", SCRIPT, [ @@ -99,6 +107,12 @@ GROUPS = { ("image-prompt", "getReferenceImagePrompt", "读取指定参考图的生成提示词", "videoId* key*"), ("download", "downloadReferenceImage", "下载与视频关联的图片", "videoId* fileId*", "download"), ]), + "memos": ("Media 备忘录", "/memo", [ + ("check", "checkMemos", "检查已到提醒时间及已逾期的备忘", PAGINATION), + ("list", "getMemoList", "按状态或标题查找备忘", f"{PAGINATION} status keyword excludeMemoId"), + ("get", "getMemo", "查看备忘详情和备注", "memoId*"), + ("save", "saveMemo", "新建、编辑或完成备忘", "requestId memoId expectedUpdatedAt title notes status priority dueAt remindAt remindDaysBefore relatedMemoIds fileIds", "json"), + ]), "storage": ("Media 存储绑定", "/storage", [ ("get", "getConfig", "查看 Media 存储配置", ""), ("save", "saveConfig", "保存 Media 存储配置", "bucket clientSecret", "private"), @@ -132,8 +146,10 @@ def add_field(parser, endpoint, spec): options["type"] = positive_int if field == "pageNo" else page_size options["default"] = 1 if field == "pageNo" else 20 options["help"] += f",默认 {options['default']}" - elif field == "isValid": + elif field in ("isValid", "forTopicSelection"): options.update(type=parse_bool, metavar="true|false") + elif field == "folderId": + options["type"] = folder_id elif field == "id" or field.endswith("Id"): options["type"] = positive_int parser.add_argument(flag, **options) @@ -209,4 +225,12 @@ def add_commands(commands, file_actions): ) for operation in operations: add_operation(actions, prefix, *operation) - add_operation(file_actions, SOCIAL, "search", "getFileList", "按文件名查找素材台账", f"{PAGINATION} keyword type") + library = "/content/file" + add_operation(file_actions, library, "search", "searchFiles", "按文件名查找素材,省略文件夹编号时搜索全库", f"{PAGINATION} keyword type folderId") + add_operation(file_actions, library, "folders", "getFolderTree", "列出文件夹及其父目录", "") + add_operation(file_actions, library, "info", "getFile", "按文件编号查看描述和文本内容", "fileId*") + add_operation(file_actions, library, "preview", "previewFile", "获取临时预览地址", "fileId*") + add_operation(file_actions, library, "download", "downloadFile", "按文件编号下载原件", "fileId*", "download") + add_operation(file_actions, library, "update", "saveFile", "编辑文件名、描述或文本内容", "requestId fileId expectedUpdatedAt fileName description textContent", "json") + add_operation(file_actions, library, "save-folder", "saveFolder", "新建、重命名或移动文件夹", "requestId folderId parentId expectedUpdatedAt name", "json") + add_operation(file_actions, library, "move", "moveFiles", "移动一个或多个文件", "requestId folderId files", "json") diff --git a/lightcore_cli/media_schema.py b/lightcore_cli/media_schema.py index 5ce84ff..71e0370 100644 --- a/lightcore_cli/media_schema.py +++ b/lightcore_cli/media_schema.py @@ -11,6 +11,7 @@ ENUMS = { "matchMode": ("all", "any"), "role": ("owner", "admin"), "status": ("enabled", "disabled"), + "priority": ("hard_deadline", "blocks_followup", "scheduled", "when_available"), "mode": ("omni_reference", "first_last_frame"), "frameRole": ("reference", "first", "last"), } @@ -24,10 +25,18 @@ DESCRIPTIONS = { "pageNo": "页码,从 1 开始", "pageSize": "每页条数,范围 1–100", "keyword": "搜索关键词", + "videoFileUrl": "采集得到的视频文件地址,省略时保留现有地址。", + "audioFileUrl": "采集得到的音频文件地址,省略时保留现有地址。", "excludeKeyword": "排除关键词,多个词用空格分隔", "searchScope": "搜索范围,all 为标题和正文,默认 all", "matchMode": "多词匹配方式,all 为全部命中,默认 all", "isValid": "社媒账号是否有效", + "priority": "备忘优先级。hard_deadline 需要截止时间。", + "assessment": "人工选题评估。high / medium / low 对应 A / B / C。", + "referencePoints": "本次保存的全部参考点。空数组清空。", + "topicNotes": "人工填写的选题备注。空字符串清空。", + "forTopicSelection": "只返回 A、B 和评估完整的 C 档,按评估等级排序。", + "relatedMemoIds": "关联的 Media 备忘 ID。更新时省略保留,空数组清空。", "bodyMarkdown": "Markdown 正文。", "durationSeconds": "生成时长,1–3600 秒,新建默认 10 秒。", "referenceImages": "参考图数组。修改时提交希望保留的完整数组。", @@ -40,9 +49,16 @@ DESCRIPTIONS = { "sourceKeys": "对应当前稿件 researchSources 内的 key。", "documents": "项目文档关联数组。required 指定是否为本项目必读。", "clientSecret": "Media 存储客户端密钥,使用私有输入文件。", + "folderId": "文件夹 ID,0 表示根目录。", + "dueAt": "截止时刻,使用带时区的 RFC3339。空字符串清除。", + "remindAt": "具体提醒时刻,使用带时区的 RFC3339。空字符串清除提醒及按天设置。", + "remindDaysBefore": "按北京时间在截止前 N 天提醒,和 remindAt 二选一。", + "textContent": "文件的纯文本内容,例如 OCR 结果。空字符串清除。", } ARRAY_OBJECTS = { + "transcriptSegments": ("start_ms end_ms text", "start_ms end_ms text"), + "files": ("fileId expectedUpdatedAt", "fileId expectedUpdatedAt"), "referenceImages": ("key name purpose prompt resourceIds referenceFileIds fileId frameRole", "name"), "documents": ("documentId required", "documentId"), "imageDetails": ("fileId text prompt referenceFileIds notes", "fileId"), @@ -58,11 +74,9 @@ CASES = { "update": "requestId accountKey platform accountName isValid expectedUpdatedAt", }, "saveContent": {"create": "requestId contentType title", "update": "requestId contentId expectedUpdatedAt"}, - "saveReference": { - "create": "requestId platform contentType creatorName title", - "update": "requestId referenceId platform contentType creatorName title expectedUpdatedAt", - }, "saveDocument": {"create": "requestId title", "update": "requestId documentId expectedUpdatedAt"}, + "saveMemo": {"create": "requestId title", "update": "requestId memoId expectedUpdatedAt"}, + "saveFolder": {"create": "requestId name", "update": "requestId folderId expectedUpdatedAt"}, "saveProject": {"create": "requestId name", "update": "requestId projectId expectedUpdatedAt"}, "saveEpisode": {"create": "requestId projectId name", "update": "requestId episodeId expectedUpdatedAt"}, "saveResource": {"create": "requestId projectId name type", "update": "requestId resourceId expectedUpdatedAt"}, @@ -76,6 +90,9 @@ REQUIRED = { "setAccountValidity": "accountKey requestId isValid expectedUpdatedAt", "saveImageDetail": "contentId requestId expectedUpdatedAt fileId", "deleteReference": "referenceId requestId expectedUpdatedAt", + "saveReferenceAssessment": "requestId referenceId expectedUpdatedAt assessment", + "saveReference": "requestId platform platformContentId sourceUrl contentType collectedAt creator", + "saveReferenceTranscript": "requestId referenceId expectedUpdatedAt transcriptStatus", "markPublication": "requestId contentId accountKey publishedAt", "deleteDocument": "documentId requestId expectedUpdatedAt", "deleteProject": "requestId id expectedUpdatedAt", @@ -83,32 +100,53 @@ REQUIRED = { "deleteResource": "requestId id expectedUpdatedAt", "deleteVideo": "requestId id expectedUpdatedAt", "saveConfig": "bucket clientSecret", + "saveFile": "requestId fileId expectedUpdatedAt", + "moveFiles": "requestId folderId files", } EXAMPLE_FIELDS = { "saveAccount": "brandName", "saveContent": "title body contentFormat mediaFileIds researchSources researchFacts imageDetails", - "saveReference": "title bodyMarkdown", - "saveDocument": "title bodyMarkdown fileIds", + "saveReference": "description viewCount", + "saveReferenceTranscript": "transcriptText transcriptSegments transcriptModel transcribedAt", + "saveReferenceAssessment": "referencePoints topicNotes", + "saveDocument": "title bodyMarkdown fileIds folderId", "saveProject": "name description documents", "saveEpisode": "name sortOrder", "saveResource": "name imageFileIds", "saveVideo": "name mode durationSeconds body referenceImages", "saveImageDetail": "text prompt referenceFileIds", + "saveMemo": "dueAt remindDaysBefore priority", + "saveFile": "description textContent", + "saveFolder": "parentId", } UPDATE_EXAMPLE_FIELDS = { "saveAccount": "validityNote", "saveContent": "title", - "saveReference": "bodyMarkdown", - "saveDocument": "bodyMarkdown", + "saveDocument": "bodyMarkdown folderId", "saveProject": "description", "saveEpisode": "sortOrder", "saveResource": "prompt", "saveVideo": "body", + "saveMemo": "status relatedMemoIds fileIds", + "saveFolder": "name", } SAMPLE_VALUES = { + "profileUrl": "https://www.tiktok.com/@example", + "platformContentId": "7710240323204631829", + "platformCreatorId": "7556875931332969479", + "referenceId": 1, + "topicNotes": "适合护理选题,可参考开头的提问。", + "sourceUrl": "https://www.tiktok.com/@example/video/7710240323204631829", + "collectedAt": "2026-11-21T00:37:00+08:00", + "transcribedAt": "2026-11-21T01:00:00+08:00", + "transcriptStatus": "ready", + "transcriptText": "示例转写内容。", + "transcriptModel": "provider/model", + "start_ms": 0, + "end_ms": 1000, "accountKey": "example-media-account", "username": "example-admin", "bodyMarkdown": "示例正文", @@ -117,6 +155,8 @@ SAMPLE_VALUES = { "documentId": 7, "episodeId": 3, "expectedUpdatedAt": "2026-01-01T00:00:00Z", + "dueAt": "2026-12-23T00:00:00+08:00", + "remindDaysBefore": 7, "fileId": 123, "frameRole": "reference", "key": "example-source", @@ -135,11 +175,22 @@ SAMPLE_VALUES = { def enum_for(endpoint, field): + if field == "platform" and endpoint in ("getReferenceList", "saveReference"): + return ("tiktok", "douyin", "xiaohongshu") + if field == "transcriptStatus": + states = ("pending", "ready", "no_audio", "no_speech", "failed") + return states if endpoint == "saveReferenceTranscript" else (*states, "not_applicable") + if field == "assessment": + return ("high", "medium", "low", "excluded", "unrated") + if field == "sort" and endpoint == "getReferenceList": + return ("updated", "views", "favorites", "published", "assessment") if field == "type": if endpoint in ("getResourceList", "saveResource"): return RESOURCE_TYPES - if endpoint == "getFileList": + if endpoint in ("getFileList", "searchFiles"): return FILE_TYPES + if field == "status" and endpoint in ("getMemoList", "saveMemo"): + return ("open", "done") return ENUMS.get(field) @@ -147,6 +198,18 @@ def field_schema(endpoint, field): values = enum_for(endpoint, field) if values: result = {"type": "string", "enum": list(values)} + elif field == "creator" and endpoint == "saveReference": + result = object_schema( + endpoint, + "platformCreatorId handle displayName profileUrl bio followerCount totalLikesCount collectedAt".split(), + ["platformCreatorId", "collectedAt"], + ) + elif field in ("platformCreatorId", "platformContentId"): + result = {"type": "string", "minLength": 1} + elif field.endswith("Count") or field in ("start_ms", "end_ms"): + result = {"type": "integer", "minimum": 0} + elif field == "durationSeconds" and endpoint == "saveReference": + result = {"type": "integer", "minimum": 0, "maximum": 2147483647} elif field in ARRAY_OBJECTS: fields, required = ARRAY_OBJECTS[field] items = object_schema(endpoint, fields.split(), required.split()) @@ -156,11 +219,17 @@ def field_schema(endpoint, field): result = {"type": "array", "items": items} elif field.endswith("Ids"): result = {"type": "array", "items": {"type": "integer", "minimum": 1}} + elif field == "referencePoints": + result = { + "type": "array", + "items": {"type": "string", "enum": ["topic_angle", "opening", "structure", "presentation"]}, + "uniqueItems": True, + } elif field == "sourceKeys": result = {"type": "array", "items": {"type": "string"}} - elif field in ("required", "isValid"): + elif field in ("required", "isValid", "forTopicSelection"): result = {"type": "boolean"} - elif field in ("id", "pageNo", "pageSize", "sortOrder", "durationSeconds") or field.endswith("Id") and field != "requestId": + elif field in ("id", "pageNo", "pageSize", "sortOrder", "durationSeconds", "remindDaysBefore") or field.endswith("Id") and field != "requestId": result = {"type": "integer"} if field == "pageSize": result.update(minimum=1, maximum=100, default=20) @@ -169,10 +238,10 @@ def field_schema(endpoint, field): elif field == "durationSeconds": result.update(minimum=1, maximum=3600, default=10) else: - result["minimum"] = 0 if field == "sortOrder" else 1 + result["minimum"] = 0 if field in ("sortOrder", "folderId", "parentId", "remindDaysBefore") else 1 else: result = {"type": "string"} - if field in ("expectedUpdatedAt", "publishedAt"): + if field in ("expectedUpdatedAt", "publishedAt", "publishedFrom", "publishedTo", "collectedAt", "transcribedAt"): result["format"] = "date-time" elif field == "verifiedAt": result["format"] = "date" @@ -182,11 +251,13 @@ def field_schema(endpoint, field): result["writeOnly"] = True if field in DESCRIPTIONS: result["description"] = DESCRIPTIONS[field] - if field == "name" or field == "title": - result.update(minLength=1, maxLength=240) + if endpoint == "saveReference" and field in ("publishedAt", "durationSeconds"): + result.pop("description", None) + if field in ("name", "title", "fileName") and endpoint != "saveReference": + result.update(minLength=1, maxLength=255 if endpoint in ("saveFolder", "saveFile") else 240) if field in ("accountKey", "accountName", "creatorName"): result.update(minLength=1, maxLength=160) - if field in ("username", "displayName"): + if field in ("username", "displayName") and endpoint != "saveReference": result.update(minLength=3 if field == "username" else 1, maxLength=50) if field in ("newPassword", "password"): result["minLength"] = 8 @@ -207,6 +278,15 @@ def request_schema(endpoint, fields): result = object_schema(endpoint, names, required.split() if required else [ field[:-1] for field in fields if field.endswith("*") ]) + if endpoint == "saveReferenceTranscript": + result["if"] = {"properties": {"transcriptStatus": {"const": "ready"}}} + result["then"] = {"required": ["transcriptText", "transcribedAt"]} + if endpoint == "saveReferenceAssessment": + result["if"] = {"properties": {"assessment": {"const": "low"}}} + result["then"] = { + "required": ["referencePoints", "topicNotes"], + "properties": {"referencePoints": {"minItems": 1}, "topicNotes": {"pattern": r"\S"}}, + } if endpoint in CASES: case_fields = {mode: values.split() for mode, values in CASES[endpoint].items()} create, update = case_fields["create"], case_fields["update"] @@ -219,10 +299,7 @@ def request_schema(endpoint, fields): result["if"] = {"required": [selector], "properties": {selector: {"minimum": 1}}} result["then"] = {"required": update} result["else"] = {"required": create} - if endpoint == "saveReference": - result["description"] = "更新时提交希望保留的完整参考内容和附件字段。" - else: - result["description"] = "更新时省略不打算修改的字段。传入的数组按整组保存。" + result["description"] = "更新时省略不打算修改的字段。传入的数组按整组保存。" result["x-required-by-operation"] = case_fields return result @@ -259,4 +336,9 @@ def example_body(endpoint, schema, mode): required = schema.get("x-required-by-operation", {}).get(mode, schema["required"]) example_fields = UPDATE_EXAMPLE_FIELDS if mode == "update" else EXAMPLE_FIELDS fields = dict.fromkeys((*required, *example_fields.get(endpoint, "").split())) - return {field: example_value(field, schema["properties"][field]) for field in fields} + result = {field: example_value(field, schema["properties"][field]) for field in fields} + if endpoint == "saveReference": + result["contentType"] = "video" + if endpoint == "saveMemo" and mode == "update": + result["status"] = "done" + return result diff --git a/tests/test_media.py b/tests/test_media.py index 2cebb8a..7c055fa 100644 --- a/tests/test_media.py +++ b/tests/test_media.py @@ -60,9 +60,19 @@ class MediaHandler(BaseHTTPRequestHandler): elif path == "/content/document/getDocumentDetail": self.reply({"files": [{"id": 123, "fileName": "../说明书.pdf", "mimeType": "application/pdf", "fileSize": 3, "previewUrl": "https://example.test/?signature=synthetic"}]}) + elif path == "/content/document/getFolderTree": + self.reply({"folders": [{"id": 7, "parentId": 0, "name": "智能家居"}]}) + elif path in ("/content/document/saveFolder", "/content/document/saveDocument"): + self.reply({"id": 7, "updatedAt": "2026-11-20T12:00:00Z"}) elif path == "/content/social/uploadAsset": self.reply({"id": 123, "fileName": "ignored"}) - elif path == "/content/document/downloadAsset": + elif path == "/content/file/searchFiles": + self.reply({"total": 1, "list": [{"id": 123, "path": "/产品/说明书.pdf"}]}) + elif path == "/content/file/saveFile": + self.reply({"id": 123, "updatedAt": "2026-11-20T12:00:01Z"}) + elif path == "/memo/checkMemos": + self.reply({"total": 21, "overdueTotal": 3, "hasMore": True, "list": []}) + elif path in ("/content/document/downloadAsset", "/content/file/downloadFile"): self.send_response(200) self.send_header("Content-Type", "application/pdf") self.send_header("Content-Disposition", "attachment; filename=manual.pdf") @@ -111,6 +121,26 @@ class MediaCliTests(unittest.TestCase): def invoke(self, *args, expected=0): return self.invoke_media("files", *args, expected=expected) + def test_document_folder_paths_and_partial_move(self): + result = self.invoke_media("documents", "folders") + self.assertEqual(result["body"]["data"]["folders"][0]["id"], 7) + self.assertEqual(MediaHandler.requests[-1][0], "/content/document/getFolderTree") + self.invoke_media("documents", "list", "--folder-id", "0", "--keyword", "推窗器") + self.assertEqual(json.loads(MediaHandler.requests[-1][2]), + {"pageNo": 1, "pageSize": 20, "folderId": 0, "keyword": "推窗器"}) + self.invoke_media("documents", "list") + self.assertNotIn("folderId", json.loads(MediaHandler.requests[-1][2])) + request_id = "ee8818d5-3ed9-4230-8870-b86ca559e061" + create = {"requestId": request_id, "name": "推窗器", "parentId": 7} + self.invoke_media("documents", "save-folder", "--body", json.dumps(create)) + self.assertEqual(MediaHandler.requests[-1][0], "/content/document/saveFolder") + self.assertEqual(json.loads(MediaHandler.requests[-1][2]), create) + move = {"requestId": request_id, "documentId": 58, "folderId": 0, + "expectedUpdatedAt": "2026-11-20T12:00:00.123456Z"} + self.invoke_media("documents", "save", "--body", json.dumps(move)) + self.assertEqual(MediaHandler.requests[-1][0], "/content/document/saveDocument") + self.assertEqual(json.loads(MediaHandler.requests[-1][2]), move) + def test_login_prompts_again_after_rejected_credentials(self): stderr = io.StringIO() with patch("builtins.input", side_effect=["wrong-user", "synthetic-user"]), \ @@ -174,6 +204,28 @@ class MediaCliTests(unittest.TestCase): self.assertEqual(path.read_bytes(), b"PDF") self.assertEqual(sum(req[0].endswith("/downloadAsset") for req in MediaHandler.requests), 1) + def test_direct_file_queries_and_memo_check(self): + result = self.invoke_media("memos", "check")["body"]["data"] + self.assertEqual(result["overdueTotal"], 3) + self.assertTrue(result["hasMore"]) + self.assertEqual(json.loads(MediaHandler.requests[-1][2]), {"pageNo": 1, "pageSize": 20}) + + result = self.invoke("search", "--keyword", "说明书", "--folder-id", "0")["body"]["data"] + self.assertEqual(result["list"][0]["path"], "/产品/说明书.pdf") + self.assertEqual(json.loads(MediaHandler.requests[-1][2])["folderId"], 0) + patch = {"requestId": "814138da-aa09-4936-b76f-e4e18e007872", "fileId": 123, + "expectedUpdatedAt": "2026-11-20T12:00:00Z", "textContent": "OCR 正文"} + body = self.root / "metadata.json" + body.write_text(json.dumps(patch, ensure_ascii=False), encoding="utf-8") + self.assertTrue(self.invoke("update", "--body-file", str(body))["ok"]) + self.assertEqual(json.loads(MediaHandler.requests[-1][2]), patch) + + destination = self.root / "原件.pdf" + self.assertTrue(self.invoke("download", "--file-id", "123", "--output", str(destination))["downloaded"]) + self.assertEqual(MediaHandler.requests[-1][0], "/content/file/downloadFile") + self.assertEqual(json.loads(MediaHandler.requests[-1][2]), {"fileId": 123}) + self.assertEqual(destination.read_bytes(), b"PDF") + def test_default_session_for_checkout_and_standalone_install(self): lightcore = self.root / "LightCore" (lightcore / "scripts").mkdir(parents=True) @@ -286,7 +338,7 @@ class MediaCliTests(unittest.TestCase): routes = set() for source in controllers.glob("*.go"): text = source.read_text(encoding="utf-8") - group = re.search(r'\.Group\("(/content/[^"]+)"', text) + group = re.search(r'\.Group\("(/(?:content/[^"]+|memo))"', text) base = re.search(r'base := "(/content/[^"]+/)"', text) for direct, suffix in re.findall(r'\br\.Handle\("POST",\s*(?:"([^"]+)"|base\s*\+\s*"([^"]+)")', text): routes.add((group[1] if group else "") + direct if direct else base[1] + suffix) @@ -304,7 +356,8 @@ class MediaCliTests(unittest.TestCase): media_command = next(action.choices["media"] for action in parser()._actions if isinstance(action, argparse._SubParsersAction)) - self.assertSetEqual(endpoints(media_command), routes) + # The existing attachment picker still calls this route. CLI search uses the library route. + self.assertSetEqual(endpoints(media_command), routes - {"/content/social/getFileList"}) if __name__ == "__main__":