micloud-cli 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/README.en.md +118 -0
  3. package/README.md +117 -2
  4. package/dist/cli.js +59 -0
  5. package/dist/commands/account.js +76 -0
  6. package/dist/core/account.js +22 -0
  7. package/dist/core/auth.js +338 -0
  8. package/dist/core/config.js +75 -0
  9. package/dist/core/http.js +172 -0
  10. package/dist/core/lock.js +90 -0
  11. package/dist/core/output.js +137 -0
  12. package/dist/core/template.js +39 -0
  13. package/dist/core/utils.js +205 -0
  14. package/dist/note/client.js +298 -0
  15. package/dist/note/commands/create.js +44 -0
  16. package/dist/note/commands/delete.js +32 -0
  17. package/dist/note/commands/export.js +20 -0
  18. package/dist/note/commands/folder.js +101 -0
  19. package/dist/note/commands/get.js +35 -0
  20. package/dist/note/commands/list.js +57 -0
  21. package/dist/note/commands/move.js +37 -0
  22. package/dist/note/commands/pin.js +41 -0
  23. package/dist/note/commands/search.js +45 -0
  24. package/dist/note/commands/shared.js +37 -0
  25. package/dist/note/commands/sync.js +203 -0
  26. package/dist/note/commands/update.js +61 -0
  27. package/dist/note/commands/upload-image.js +27 -0
  28. package/dist/note/config.js +157 -0
  29. package/dist/note/converter.js +664 -0
  30. package/dist/note/extra-info.js +23 -0
  31. package/dist/note/images.js +100 -0
  32. package/dist/note/register.js +172 -0
  33. package/dist/note/sync-diff.js +143 -0
  34. package/dist/note/sync.js +744 -0
  35. package/dist/note/text-diff.js +71 -0
  36. package/dist/note/types.js +2 -0
  37. package/dist/recording/client.js +115 -0
  38. package/dist/recording/commands/config.js +73 -0
  39. package/dist/recording/commands/delete.js +171 -0
  40. package/dist/recording/commands/list.js +161 -0
  41. package/dist/recording/commands/shared.js +47 -0
  42. package/dist/recording/commands/transfer.js +192 -0
  43. package/dist/recording/commands/trash.js +140 -0
  44. package/dist/recording/config.js +104 -0
  45. package/dist/recording/dates.js +61 -0
  46. package/dist/recording/download.js +308 -0
  47. package/dist/recording/progress.js +77 -0
  48. package/dist/recording/pull.js +433 -0
  49. package/dist/recording/recording.js +294 -0
  50. package/dist/recording/register.js +202 -0
  51. package/dist/recording/template.js +44 -0
  52. package/dist/recording/types.js +2 -0
  53. package/package.json +53 -4
@@ -0,0 +1,71 @@
1
+ /** 行级 diff(LCS),用于同步冲突时对比两侧内容 */
2
+ /** 超过该规模(行数乘积)时不做 LCS,退化为整体替换,避免内存与耗时失控 */
3
+ const MAX_CELLS = 4_000_000;
4
+ export function diffLines(before, after) {
5
+ const a = before.split("\n");
6
+ const b = after.split("\n");
7
+ const n = a.length;
8
+ const m = b.length;
9
+ if (n * m > MAX_CELLS) {
10
+ return [
11
+ ...a.map((text) => ({ op: "-", text })),
12
+ ...b.map((text) => ({ op: "+", text })),
13
+ ];
14
+ }
15
+ // lcs[i][j] = a[i..] 与 b[j..] 的最长公共子序列长度
16
+ const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
17
+ for (let i = n - 1; i >= 0; i--) {
18
+ for (let j = m - 1; j >= 0; j--) {
19
+ lcs[i][j] =
20
+ a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
21
+ }
22
+ }
23
+ const out = [];
24
+ let i = 0;
25
+ let j = 0;
26
+ while (i < n && j < m) {
27
+ if (a[i] === b[j]) {
28
+ out.push({ op: " ", text: a[i] });
29
+ i++;
30
+ j++;
31
+ }
32
+ else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
33
+ out.push({ op: "-", text: a[i++] });
34
+ }
35
+ else {
36
+ out.push({ op: "+", text: b[j++] });
37
+ }
38
+ }
39
+ while (i < n)
40
+ out.push({ op: "-", text: a[i++] });
41
+ while (j < m)
42
+ out.push({ op: "+", text: b[j++] });
43
+ return out;
44
+ }
45
+ /** 渲染为带 -/+ 前缀的文本;未改动的长段只保留前后 context 行 */
46
+ export function formatDiff(lines, context = 3) {
47
+ const changed = lines.map((l) => l.op !== " ");
48
+ const keep = lines.map((_, idx) => {
49
+ for (let k = Math.max(0, idx - context); k <= Math.min(lines.length - 1, idx + context); k++) {
50
+ if (changed[k])
51
+ return true;
52
+ }
53
+ return false;
54
+ });
55
+ const out = [];
56
+ let skipped = 0;
57
+ lines.forEach((l, idx) => {
58
+ if (!keep[idx]) {
59
+ skipped++;
60
+ return;
61
+ }
62
+ if (skipped > 0) {
63
+ out.push(` … 省略 ${skipped} 行未改动内容`);
64
+ skipped = 0;
65
+ }
66
+ out.push(`${l.op} ${l.text}`);
67
+ });
68
+ if (skipped > 0)
69
+ out.push(` … 省略 ${skipped} 行未改动内容`);
70
+ return out.join("\n");
71
+ }
@@ -0,0 +1,2 @@
1
+ // ============ 小米云笔记 API 原始数据结构 ============
2
+ export {};
@@ -0,0 +1,115 @@
1
+ import { getQuota } from "../core/account.js";
2
+ import { MiCloudHttp, MiApiError, unwrapEnvelope } from "../core/http.js";
3
+ import { randomDelay } from "../core/utils.js";
4
+ const RECORDER = "/sfs/ns/recorder";
5
+ /** 与网页端一致的分页大小 */
6
+ const PAGE_SIZE = 500;
7
+ /** 分页上限,防止服务端异常时死循环 */
8
+ const MAX_PAGES = 1000;
9
+ /** 云空间已满(从回收站恢复时出现) */
10
+ export const CODE_SPACE_FULL = 50006;
11
+ const KNOWN_ERRORS = {
12
+ 50202: "录音不存在(可能已被删除,或 id 有误)",
13
+ [CODE_SPACE_FULL]: "云空间已满",
14
+ };
15
+ /**
16
+ * 小米云录音 API 客户端(端点来自 i.mi.com/record 网页端)。
17
+ *
18
+ * - 删除是两段式:`file/{id}/delete` 移入回收站(ver 会变)→ 回收站里用新 ver `recover` 恢复或 `purge` 永久删除
19
+ * - 登录态续期、超时与重试由 MiCloudHttp 负责
20
+ */
21
+ export class MiRecordingClient {
22
+ http;
23
+ constructor(auth, refresher) {
24
+ this.http = new MiCloudHttp(auth, refresher, "https://i.mi.com/record");
25
+ }
26
+ get userId() {
27
+ return this.http.userId;
28
+ }
29
+ // ============ 读 ============
30
+ /** 列出全部云端录音(offset 分页,单页不满即为最后一页) */
31
+ async listRecordings(onProgress) {
32
+ const all = [];
33
+ const seen = new Set();
34
+ let offset = 0;
35
+ for (let page = 0; page < MAX_PAGES; page++) {
36
+ const data = await this.get(`${RECORDER}/dir/0/list`, {
37
+ offset,
38
+ limit: PAGE_SIZE,
39
+ _dc: Date.now(),
40
+ });
41
+ const list = data.list ?? [];
42
+ for (const item of list) {
43
+ const id = String(item.id);
44
+ if (seen.has(id))
45
+ continue;
46
+ seen.add(id);
47
+ all.push({ ...item, id });
48
+ }
49
+ onProgress?.(all.length);
50
+ if (list.length < PAGE_SIZE)
51
+ break;
52
+ offset += list.length;
53
+ await randomDelay(200);
54
+ }
55
+ return all;
56
+ }
57
+ /** 列出回收站(最近删除)里的录音(syncToken 分页,响应不再带 syncToken 即为最后一页) */
58
+ async listTrash(onProgress) {
59
+ const all = [];
60
+ const seen = new Set();
61
+ let syncToken = "";
62
+ for (let page = 0; page < MAX_PAGES; page++) {
63
+ const data = await this.get(`${RECORDER}/deleted`, { syncToken, limit: PAGE_SIZE });
64
+ for (const item of data.list ?? []) {
65
+ const id = String(item.id);
66
+ if (seen.has(id))
67
+ continue;
68
+ seen.add(id);
69
+ all.push({ ...item, id });
70
+ }
71
+ onProgress?.(all.length);
72
+ const next = data.syncToken;
73
+ if (!next || next === syncToken)
74
+ break;
75
+ syncToken = next;
76
+ await randomDelay(200);
77
+ }
78
+ return all;
79
+ }
80
+ /** 获取录音的临时直链(预签名,无需 cookie,支持 Range;实测约 4 小时有效) */
81
+ async getDownloadUrl(id) {
82
+ const data = await this.get(`${RECORDER}/file/${encodeURIComponent(id)}/storage/geturl`);
83
+ if (!data.url)
84
+ throw new MiApiError(`未拿到录音 ${id} 的下载地址`);
85
+ return data.url;
86
+ }
87
+ /** 分块下载凭证;账号开启「高级数据保护」(端到端加密)时带 encryptInfo,用于诊断 */
88
+ async getBlockStorage(id) {
89
+ return await this.get(`${RECORDER}/file/${encodeURIComponent(id)}/block/storage`);
90
+ }
91
+ /** 云空间用量与会员等级(会员等级决定回收站保留天数) */
92
+ async getQuota() {
93
+ return await getQuota(this.http);
94
+ }
95
+ // ============ 写 ============
96
+ /** 删除录音:移入回收站(网页端同样只做软删除,永久删除需再对回收站条目 purge) */
97
+ async deleteRecording(id) {
98
+ await this.post(`${RECORDER}/file/${encodeURIComponent(id)}/delete`, { permanent: "false" });
99
+ }
100
+ /** 从回收站恢复;ver 必须取回收站条目当前的 ver */
101
+ async recoverRecording(id, ver) {
102
+ await this.post(`${RECORDER}/deleted/${encodeURIComponent(id)}/${encodeURIComponent(ver)}/recover`);
103
+ }
104
+ /** 从回收站永久删除(不可恢复);ver 必须取回收站条目当前的 ver */
105
+ async purgeRecording(id, ver) {
106
+ await this.post(`${RECORDER}/deleted/${encodeURIComponent(id)}/${encodeURIComponent(ver)}/purge`);
107
+ }
108
+ // ============ 底层 ============
109
+ async get(path, query = {}) {
110
+ return await this.http.getJson(path, query, (json) => unwrapEnvelope(json, KNOWN_ERRORS));
111
+ }
112
+ async post(path, params = {}) {
113
+ return unwrapEnvelope(await this.http.postForm(path, params), KNOWN_ERRORS);
114
+ }
115
+ }
@@ -0,0 +1,73 @@
1
+ import { getConfigPath } from "../../core/config.js";
2
+ import { success, logInfo, fail } from "../../core/output.js";
3
+ import { formatTime } from "../../core/utils.js";
4
+ import { resolveOutputDir, loadState, loadRecordingConfig, saveRecordingConfig, getStatePath, CONFIG_KEYS, DEFAULT_CONCURRENCY, parseConfigValue, } from "../config.js";
5
+ import { DEFAULT_FILE_NAME_TEMPLATE } from "../template.js";
6
+ /** recording config:查看生效配置与拉取状态 */
7
+ export async function configShowCommand(opts = {}) {
8
+ try {
9
+ const cfg = await loadRecordingConfig();
10
+ const outputDir = await resolveOutputDir(opts.output);
11
+ const state = await loadState(outputDir);
12
+ const pulled = Object.values(state.recordings);
13
+ const lastPulledAt = pulled.reduce((max, r) => Math.max(max, r.pulledAt), 0);
14
+ const data = {
15
+ configFile: getConfigPath(),
16
+ config: cfg,
17
+ effective: {
18
+ output: outputDir,
19
+ fileNameTemplate: cfg.fileNameTemplate ?? DEFAULT_FILE_NAME_TEMPLATE,
20
+ concurrency: cfg.concurrency ?? DEFAULT_CONCURRENCY,
21
+ },
22
+ state: {
23
+ file: getStatePath(outputDir),
24
+ pulledCount: pulled.length,
25
+ cloudDeletedCount: pulled.filter((r) => r.cloudDeletedAt).length,
26
+ lastPulledAt: lastPulledAt || null,
27
+ },
28
+ };
29
+ success(data, () => {
30
+ logInfo(`配置文件:${data.configFile}${Object.keys(cfg).length ? "" : "(未配置录音项,使用默认值)"}`);
31
+ logInfo(`拉取目录:${outputDir}${opts.output || cfg.output ? "" : "(默认)"}`);
32
+ logInfo(`文件名模板:${data.effective.fileNameTemplate}`);
33
+ logInfo(`并发下载数:${data.effective.concurrency}`);
34
+ logInfo(`已拉取:${pulled.length} 条${data.state.cloudDeletedCount ? `(其中 ${data.state.cloudDeletedCount} 条已删除云端副本)` : ""}` +
35
+ `${lastPulledAt ? `,最近一次 ${formatTime(lastPulledAt)}` : ""}`);
36
+ });
37
+ }
38
+ catch (err) {
39
+ fail(err);
40
+ }
41
+ }
42
+ /** recording config set <key> <value> */
43
+ export async function configSetCommand(key, value) {
44
+ try {
45
+ const k = parseKey(key);
46
+ const cfg = await loadRecordingConfig();
47
+ cfg[k] = parseConfigValue(k, value);
48
+ await saveRecordingConfig(cfg);
49
+ success({ configFile: getConfigPath(), config: cfg }, () => logInfo(`✅ 已设置 ${k} = ${cfg[k]}`));
50
+ }
51
+ catch (err) {
52
+ fail(err);
53
+ }
54
+ }
55
+ /** recording config unset <key> */
56
+ export async function configUnsetCommand(key) {
57
+ try {
58
+ const k = parseKey(key);
59
+ const cfg = await loadRecordingConfig();
60
+ delete cfg[k];
61
+ await saveRecordingConfig(cfg);
62
+ success({ configFile: getConfigPath(), config: cfg }, () => logInfo(`✅ 已移除 ${k},恢复默认值`));
63
+ }
64
+ catch (err) {
65
+ fail(err);
66
+ }
67
+ }
68
+ function parseKey(key) {
69
+ if (!CONFIG_KEYS.includes(key)) {
70
+ throw new Error(`未知配置项:${key}(可选:${CONFIG_KEYS.join(" / ")})`);
71
+ }
72
+ return key;
73
+ }
@@ -0,0 +1,171 @@
1
+ import { getClient, buildFilter, hasFilter, DEVICE_SYNC_WARNING } from "./shared.js";
2
+ import { printRecordingTable, summarize } from "./list.js";
3
+ import { isFatalError } from "../../core/http.js";
4
+ import { getStatePath, lockOutputDir, resolveOutputDir, saveState } from "../config.js";
5
+ import { checkCloudDeletable, errorMessage, listCloud, loadExistingState, resolveIds, selectPulled, skippedItem, } from "../pull.js";
6
+ import { matchesFilter, sortByRecordedAt } from "../recording.js";
7
+ import { success, logInfo, fail, isJsonMode, confirmDestructive, finishBatch } from "../../core/output.js";
8
+ import { formatBytes, formatDuration, randomDelay } from "../../core/utils.js";
9
+ /**
10
+ * delete:把云端录音移到回收站(可在 trash 中恢复)。
11
+ *
12
+ * 目标三选一:
13
+ * - 直接给 id;
14
+ * - --pulled:已拉取到本地的录音(规则见 checkCloudDeletable),可再叠加筛选条件;
15
+ * - 筛选条件(--type / --since / --until / --query),或 --all 表示全部。
16
+ */
17
+ export async function deleteCommand(ids, opts) {
18
+ let release = null;
19
+ try {
20
+ const filtered = hasFilter(opts);
21
+ const modes = [ids.length > 0, !!opts.pulled, !!opts.all].filter(Boolean).length;
22
+ if (modes > 1)
23
+ throw new Error("id、--pulled、--all 只能选一种方式指定要删除的录音");
24
+ if (ids.length > 0 && filtered)
25
+ throw new Error("指定 id 时不能再加筛选条件");
26
+ if (opts.all && filtered)
27
+ throw new Error("--all 表示删除全部录音,不能再加筛选条件");
28
+ if (opts.allowMoved && !opts.pulled)
29
+ throw new Error("--allow-moved 只能与 --pulled 一起使用");
30
+ if (modes === 0 && !filtered) {
31
+ throw new Error("请指定要删除的录音:id、--pulled、筛选条件(--type / --since / --until / --query),或 --all");
32
+ }
33
+ const filter = buildFilter(opts);
34
+ let outputDir;
35
+ let state = null;
36
+ if (opts.pulled) {
37
+ outputDir = await resolveOutputDir(opts.output);
38
+ state = await loadExistingState(outputDir);
39
+ if (!state)
40
+ throw new Error(`拉取目录里没有拉取记录:${getStatePath(outputDir)}(用 -o 指定 pull 时的目录)`);
41
+ if (!opts.dryRun) {
42
+ release = await lockOutputDir(outputDir);
43
+ state = (await loadExistingState(outputDir)) ?? state;
44
+ }
45
+ }
46
+ const client = await getClient();
47
+ const cloud = await listCloud(client, isJsonMode());
48
+ const failed = [];
49
+ let skipped = [];
50
+ let targets;
51
+ if (ids.length > 0) {
52
+ const resolved = await resolveIds(client, cloud, ids);
53
+ targets = resolved.found;
54
+ failed.push(...resolved.failures);
55
+ }
56
+ else if (state && outputDir) {
57
+ const selection = await selectPulled(cloud, state, outputDir, {
58
+ allowMoved: opts.allowMoved,
59
+ predicate: (r) => matchesFilter(r, filter),
60
+ });
61
+ targets = selection.targets;
62
+ skipped = selection.skipped;
63
+ }
64
+ else {
65
+ targets = cloud.filter((r) => matchesFilter(r, filter));
66
+ }
67
+ targets = sortByRecordedAt(targets, "desc");
68
+ const plan = { count: targets.length, ...summarize(targets) };
69
+ const printSkipped = () => {
70
+ if (skipped.length === 0)
71
+ return;
72
+ logInfo(`ℹ️ 另有 ${skipped.length} 条已拉取的录音未删除:`);
73
+ for (const s of skipped.slice(0, 20))
74
+ logInfo(` ${s.title}:${s.reason}`);
75
+ if (skipped.length > 20)
76
+ logInfo(` ……其余 ${skipped.length - 20} 条略(--json 查看全部)`);
77
+ };
78
+ if (opts.dryRun || targets.length === 0) {
79
+ const data = { dryRun: !!opts.dryRun, deleted: [], wouldDelete: targets, skipped, failed, ...plan };
80
+ finishBatch(data, { succeeded: targets.length, failed }, () => {
81
+ if (targets.length === 0)
82
+ logInfo("(没有要删除的录音)");
83
+ else {
84
+ logInfo(`🔍 预览:将把以下 ${targets.length} 条录音移到回收站(${formatDuration(plan.duration)},${formatBytes(plan.size)})`);
85
+ printRecordingTable(targets);
86
+ }
87
+ printSkipped();
88
+ for (const f of failed)
89
+ logInfo(`⚠️ ${f.title || f.id}:${f.error}`);
90
+ });
91
+ return;
92
+ }
93
+ if (!isJsonMode()) {
94
+ logInfo(`将把以下 ${targets.length} 条云端录音移到回收站(${formatDuration(plan.duration)},${formatBytes(plan.size)}):`);
95
+ printRecordingTable(targets.slice(0, 20));
96
+ if (targets.length > 20)
97
+ logInfo(`……其余 ${targets.length - 20} 条略`);
98
+ printSkipped();
99
+ logInfo(DEVICE_SYNC_WARNING);
100
+ }
101
+ if (!(await confirmDestructive(`确认删除这 ${targets.length} 条录音吗?`, opts.yes))) {
102
+ success({ cancelled: true }, () => logInfo("已取消"));
103
+ return;
104
+ }
105
+ const deleted = [];
106
+ const warnings = [];
107
+ let fatal = null;
108
+ for (const r of targets) {
109
+ if (fatal) {
110
+ failed.push({ id: r.id, title: r.title, error: fatal });
111
+ continue;
112
+ }
113
+ // --pulled:删除前再核对一次(确认后、逐条删除期间,本地文件可能已被转移或改动)
114
+ const record = state?.recordings[r.id];
115
+ if (record && outputDir) {
116
+ const code = await checkCloudDeletable(r, record, outputDir, !!opts.allowMoved);
117
+ if (code) {
118
+ skipped.push(skippedItem(r, code));
119
+ continue;
120
+ }
121
+ }
122
+ try {
123
+ await client.deleteRecording(r.id);
124
+ deleted.push(r);
125
+ if (!isJsonMode())
126
+ logInfo(`🗑️ ${r.title}`);
127
+ }
128
+ catch (err) {
129
+ const message = errorMessage(err);
130
+ failed.push({ id: r.id, title: r.title, error: message });
131
+ if (!isJsonMode())
132
+ logInfo(`❌ ${r.title}:${message}`);
133
+ if (isFatalError(err))
134
+ fatal = message;
135
+ }
136
+ if (targets.length > 1)
137
+ await randomDelay(150);
138
+ }
139
+ // 记下删除时间:之后若从回收站恢复,--pulled / --delete-cloud 不会再自动删除它
140
+ if (state && outputDir) {
141
+ let marked = false;
142
+ for (const r of deleted) {
143
+ const record = state.recordings[r.id];
144
+ if (record) {
145
+ record.cloudDeletedAt = Date.now();
146
+ marked = true;
147
+ }
148
+ }
149
+ if (marked) {
150
+ try {
151
+ await saveState(outputDir, state);
152
+ }
153
+ catch (err) {
154
+ warnings.push(`无法写入拉取状态:${errorMessage(err)}`);
155
+ }
156
+ }
157
+ }
158
+ const data = { deleted, skipped, failed, warnings, count: deleted.length, ...summarize(deleted) };
159
+ finishBatch(data, { succeeded: deleted.length, failed, warnings: warnings.length }, () => {
160
+ for (const w of warnings)
161
+ logInfo(`⚠️ ${w}`);
162
+ logInfo(`\n已将 ${deleted.length} 条录音移到回收站${failed.length ? `,${failed.length} 条失败` : ""}(可用 trash restore 恢复)`);
163
+ });
164
+ }
165
+ catch (err) {
166
+ fail(err);
167
+ }
168
+ finally {
169
+ await release?.();
170
+ }
171
+ }
@@ -0,0 +1,161 @@
1
+ import { getClient, buildFilter } from "./shared.js";
2
+ import { listCloud } from "../pull.js";
3
+ import { ALL_TYPES, TYPE_NAMES, matchesFilter, parseTrashedRecording, shortTypeName, sortByRecordedAt, } from "../recording.js";
4
+ import { success, logInfo, fail, isJsonMode } from "../../core/output.js";
5
+ import { displayWidth, formatBytes, formatDuration, formatTime, getDateTokens, padEndDisplay, padStartDisplay, parsePositiveInt, truncateDisplay, } from "../../core/utils.js";
6
+ const TITLE_MAX_WIDTH = 56;
7
+ const SORT_KEYS = ["time", "size", "duration"];
8
+ /** 列出云端录音 */
9
+ export async function listCommand(opts) {
10
+ try {
11
+ const filter = buildFilter(opts);
12
+ const limit = parsePositiveInt(opts.limit, Infinity, "--limit");
13
+ const sortKey = parseSortKey(opts.sort);
14
+ const client = await getClient();
15
+ const all = await listCloud(client, isJsonMode());
16
+ const matched = sortRecordings(all.filter((r) => matchesFilter(r, filter)), sortKey, !!opts.asc);
17
+ const items = matched.slice(0, limit);
18
+ success(items, () => {
19
+ if (items.length === 0) {
20
+ logInfo("(没有符合条件的录音)");
21
+ return;
22
+ }
23
+ printRecordingTable(items);
24
+ const total = summarize(matched);
25
+ const shown = items.length < matched.length ? `,显示前 ${items.length} 条` : "";
26
+ logInfo(`\n共 ${matched.length} 条,总时长 ${formatDuration(total.duration)},总大小 ${formatBytes(total.size)}${shown}`);
27
+ });
28
+ }
29
+ catch (err) {
30
+ fail(err);
31
+ }
32
+ }
33
+ /** 按关键词搜索(标题、联系人、号码、来源应用) */
34
+ export async function searchCommand(keywords, opts) {
35
+ await listCommand({ ...opts, query: keywords.join(" ") });
36
+ }
37
+ /** 查看单条录音的完整信息(也会查找回收站) */
38
+ export async function infoCommand(id) {
39
+ try {
40
+ const client = await getClient();
41
+ const all = await listCloud(client, true);
42
+ let recording = all.find((r) => r.id === id);
43
+ let inTrash = false;
44
+ if (!recording) {
45
+ const trashed = (await client.listTrash()).find((r) => String(r.id) === id);
46
+ if (trashed) {
47
+ recording = parseTrashedRecording(trashed);
48
+ inTrash = true;
49
+ }
50
+ }
51
+ if (!recording)
52
+ throw new Error(`找不到录音 ${id}(云端与回收站都没有)`);
53
+ const r = recording;
54
+ success({ ...r, inTrash }, () => {
55
+ const rows = [
56
+ ["标题", r.title],
57
+ ["ID", r.id],
58
+ ["类型", r.appName && r.type === "app" ? `${r.typeName}(${r.appName})` : r.typeName],
59
+ ["录音时间", formatTime(r.recordedAt, true)],
60
+ ["时长", `${formatDuration(r.duration)}${r.durationEstimated ? "(按大小估算)" : ""}`],
61
+ ["大小", `${formatBytes(r.size)}(${r.size} 字节)`],
62
+ ["格式", r.extension || "未知"],
63
+ ];
64
+ if (r.contactName)
65
+ rows.push(["对方", r.contactName]);
66
+ if (r.phoneNumber)
67
+ rows.push(["号码", r.phoneNumber]);
68
+ rows.push(["上传时间", formatTime(r.createTime, true)], ["SHA-1", r.sha1], ["云端文件名", r.rawName]);
69
+ if (inTrash && "deletedAt" in r)
70
+ rows.push(["状态", `在回收站中(${formatTime(r.deletedAt)} 删除)`]);
71
+ for (const [label, value] of rows) {
72
+ process.stdout.write(`${padEndDisplay(label, 10)} ${value}\n`);
73
+ }
74
+ });
75
+ }
76
+ catch (err) {
77
+ fail(err);
78
+ }
79
+ }
80
+ const GROUP_KEYS = ["type", "month", "year"];
81
+ /** 录音统计:按类型 / 月份 / 年份汇总条数、时长与大小 */
82
+ export async function statsCommand(opts) {
83
+ try {
84
+ const by = (opts.by ?? "type");
85
+ if (!GROUP_KEYS.includes(by)) {
86
+ throw new Error(`--by 只支持 ${GROUP_KEYS.join(" / ")},收到:${opts.by}`);
87
+ }
88
+ const filter = buildFilter(opts);
89
+ const client = await getClient();
90
+ const matched = (await listCloud(client, isJsonMode())).filter((r) => matchesFilter(r, filter));
91
+ const groups = new Map();
92
+ for (const r of matched) {
93
+ const key = groupKey(r, by);
94
+ const group = groups.get(key) ?? { key, label: groupLabel(key, by), count: 0, duration: 0, size: 0 };
95
+ group.count++;
96
+ group.duration += r.duration;
97
+ group.size += r.size;
98
+ groups.set(key, group);
99
+ }
100
+ const ordered = [...groups.values()].sort((a, b) => by === "type"
101
+ ? ALL_TYPES.indexOf(a.key) - ALL_TYPES.indexOf(b.key)
102
+ : b.key.localeCompare(a.key));
103
+ const total = { count: matched.length, ...summarize(matched) };
104
+ success({ by, total, groups: ordered }, () => {
105
+ if (matched.length === 0) {
106
+ logInfo("(没有符合条件的录音)");
107
+ return;
108
+ }
109
+ const labelWidth = Math.max(4, ...ordered.map((g) => displayWidth(g.label)));
110
+ for (const g of ordered) {
111
+ process.stdout.write(`${padEndDisplay(g.label, labelWidth)} ${padStartDisplay(String(g.count), 5)} 条 ` +
112
+ `${padStartDisplay(formatDuration(g.duration), 10)} ${padStartDisplay(formatBytes(g.size), 10)}\n`);
113
+ }
114
+ process.stdout.write(`${padEndDisplay("合计", labelWidth)} ${padStartDisplay(String(total.count), 5)} 条 ` +
115
+ `${padStartDisplay(formatDuration(total.duration), 10)} ${padStartDisplay(formatBytes(total.size), 10)}\n`);
116
+ });
117
+ }
118
+ catch (err) {
119
+ fail(err);
120
+ }
121
+ }
122
+ /** 录音表格:ID、录音时间、时长、大小、类型、标题 */
123
+ export function printRecordingTable(items) {
124
+ for (const r of items) {
125
+ const cells = [
126
+ r.id.padEnd(17),
127
+ formatTime(r.recordedAt),
128
+ padStartDisplay(formatDuration(r.duration), 8),
129
+ padStartDisplay(formatBytes(r.size), 9),
130
+ padEndDisplay(shortTypeName(r), 8),
131
+ truncateDisplay(r.title, TITLE_MAX_WIDTH),
132
+ ];
133
+ process.stdout.write(cells.join(" ") + "\n");
134
+ }
135
+ }
136
+ export function summarize(items) {
137
+ return items.reduce((acc, r) => ({ duration: acc.duration + r.duration, size: acc.size + r.size }), { duration: 0, size: 0 });
138
+ }
139
+ function parseSortKey(raw) {
140
+ if (raw === undefined)
141
+ return "time";
142
+ if (!SORT_KEYS.includes(raw)) {
143
+ throw new Error(`--sort 只支持 ${SORT_KEYS.join(" / ")},收到:${raw}`);
144
+ }
145
+ return raw;
146
+ }
147
+ function sortRecordings(items, key, asc) {
148
+ if (key === "time")
149
+ return sortByRecordedAt(items, asc ? "asc" : "desc");
150
+ const sign = asc ? 1 : -1;
151
+ return [...items].sort((a, b) => sign * (a[key] - b[key]) || b.recordedAt - a.recordedAt);
152
+ }
153
+ function groupKey(r, by) {
154
+ if (by === "type")
155
+ return r.type;
156
+ const t = getDateTokens(r.recordedAt);
157
+ return by === "month" ? `${t.YYYY}-${t.MM}` : t.YYYY;
158
+ }
159
+ function groupLabel(key, by) {
160
+ return by === "type" ? TYPE_NAMES[key] ?? key : key;
161
+ }
@@ -0,0 +1,47 @@
1
+ import { resolveAuth, refreshAuth } from "../../core/auth.js";
2
+ import { isJsonMode } from "../../core/output.js";
3
+ import { MiRecordingClient } from "../client.js";
4
+ import { DEFAULT_CONCURRENCY, loadRecordingConfig, parseConcurrency } from "../config.js";
5
+ import { parseTimeInput } from "../dates.js";
6
+ import { parseTypes } from "../recording.js";
7
+ import { DEFAULT_FILE_NAME_TEMPLATE } from "../template.js";
8
+ /** 已登录的录音客户端;请求遇 401 时自动静默续期并重试 */
9
+ export async function getClient() {
10
+ return new MiRecordingClient(await resolveAuth(), refreshAuth);
11
+ }
12
+ export function hasFilter(opts) {
13
+ return Boolean(opts.type || opts.since || opts.until || opts.query);
14
+ }
15
+ /** 由 --type / --since / --until / --query 构造过滤条件 */
16
+ export function buildFilter(opts) {
17
+ const filter = {};
18
+ if (opts.type)
19
+ filter.types = parseTypes(opts.type);
20
+ if (opts.since)
21
+ filter.since = parseTimeInput(opts.since);
22
+ if (opts.until)
23
+ filter.until = parseTimeInput(opts.until, { endOfDay: true });
24
+ if (opts.query?.trim())
25
+ filter.match = opts.query.trim();
26
+ if (filter.since !== undefined && filter.until !== undefined && filter.since > filter.until) {
27
+ throw new Error("--since 晚于 --until,没有录音能同时满足");
28
+ }
29
+ return filter;
30
+ }
31
+ /** 文件名模板与并发数:命令行参数 > 配置 > 默认 */
32
+ export async function resolveTransferSettings(opts) {
33
+ const cfg = await loadRecordingConfig();
34
+ const template = opts.template?.trim() ? opts.template : cfg.fileNameTemplate ?? DEFAULT_FILE_NAME_TEMPLATE;
35
+ const concurrency = opts.concurrency !== undefined
36
+ ? parseConcurrency(opts.concurrency)
37
+ : cfg.concurrency !== undefined
38
+ ? parseConcurrency(cfg.concurrency)
39
+ : DEFAULT_CONCURRENCY;
40
+ return { template, concurrency };
41
+ }
42
+ /** 是否显示动态进度行 */
43
+ export function showProgress() {
44
+ return !isJsonMode() && !!process.stderr.isTTY;
45
+ }
46
+ /** 删除类操作的统一提醒:云端删除会同步到已登录的设备 */
47
+ export const DEVICE_SYNC_WARNING = "注意:小米云会同步删除已登录该账号的设备(如手机)上的这些录音。";