dsh-fish-soul 0.19.29 → 0.19.31

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  让一个 QQ 小号背后有"同一个人":固定人格、按人记记忆、有自己的生活节奏、会主动开口;同一个"她"同时出现在 QQ、B站、抖音。
4
4
 
5
- DSH 插件(单角色 `feiyu`)。版本 **0.19.29**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.19.31**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
@@ -484,6 +484,12 @@ window.__ModuleLoader__.load({
484
484
  if (r?.ok) load();
485
485
  else notify(r?.error ?? "保存失败");
486
486
  }
487
+ const [petToken, setPetToken] = react.useState(null); // generate 当次返回的明文,只留到用户复制走
488
+ async function petTokenAction(action) { // 桌面宠物互通令牌:generate / revoke
489
+ const r = await api("POST", "/desktop/pet-token", { action });
490
+ if (r?.ok) { setPetToken(action === "generate" ? (r.token ?? null) : null); load(); }
491
+ else notify(r?.error ?? "操作失败");
492
+ }
487
493
  async function test() {
488
494
  setBusy(true); setResult(null);
489
495
  const r = await api("POST", "/web/test", { query: "今天有什么新闻" });
@@ -515,7 +521,11 @@ window.__ModuleLoader__.load({
515
521
  { value: "memory", label: "只记忆+上网" }, { value: "master", label: "只对主人放开" }, { value: "all", label: "全放开" }
516
522
  ] })),
517
523
  Row({ title: "桌面会话继承主人身份", desc: "开着时任何 DSH 桌面会话都被当成主人,recall 能读到全部私聊记忆。同一台机器既跑工作会话又跑 QQ 人格时建议关掉" },
518
- h(Switch, { label: "桌面会话继承主人身份", checked: w.desktopAsMaster !== false, onChange: (v) => saveDesktopAsMaster(v) }))));
524
+ h(Switch, { label: "桌面会话继承主人身份", checked: w.desktopAsMaster !== false, onChange: (v) => saveDesktopAsMaster(v) })),
525
+ Row({ title: "桌面宠物互通令牌", desc: (data.desktopPet?.hasToken ? `桌宠端调用 /life/* 需带这个令牌(Authorization: Bearer …)。${petToken ? "请复制到桌宠端配置 —— 它只显示这一次" : "已配置"}` : "未启用鉴权(同机进程可调用)") },
526
+ data.desktopPet?.hasToken ? State("done", petToken ?? data.desktopPet?.tokenMasked ?? "") : null,
527
+ Button({ onClick: () => petTokenAction("generate") }, data.desktopPet?.hasToken ? "重新生成" : "生成令牌"),
528
+ data.desktopPet?.hasToken ? Button({ onClick: () => petTokenAction("revoke") }, "撤销") : null)));
519
529
  }
520
530
 
521
531
  /** 语音:听 QQ 语音 + 发语音 */
@@ -130,6 +130,12 @@ export function douyinConfigSchema(z) {
130
130
  perHour: z.number().default(4),
131
131
  replyChars: z.number().min(10).max(300).default(40),
132
132
  emoji: z.boolean().default(false)
133
+ }).default({}),
134
+ cli: z.object({ // 抖音开放 CLI(douyin-open-cli)混合驱动配置
135
+ socialBackend: z.string().default('browser'), // browser | hybrid
136
+ binaryPath: z.string().default('douyin-open-cli'),
137
+ authDir: z.string().default(''),
138
+ browseText: z.boolean().default(false)
133
139
  }).default({})
134
140
  }).default({});
135
141
  }
@@ -132,7 +132,10 @@ export function fishSoulConfigSchema(z) {
132
132
  sessionAllow: z.string().default('memory'),
133
133
  // #255:桌面会话(channel=dsh)是否继承主人身份(默认 true 保持现行为)。
134
134
  // 关掉后 dsh 会话 ownerId 保持 UNKNOWN,recall 不返回私聊记忆。
135
- desktopAsMaster: z.boolean().default(true)
135
+ desktopAsMaster: z.boolean().default(true),
136
+ // 桌面宠物互通令牌(/life/context、/life/interaction 的 Bearer 校验)。
137
+ // 空 = 不启用鉴权(向后兼容,同机任意进程可调用);非空 = 必须带 Authorization: Bearer <token>。
138
+ desktopPetToken: z.string().default('')
136
139
  }).default({}),
137
140
  onboarding: z.object({ dismissed: z.boolean().default(false) }).default({}),
138
141
  storage: z.object({ auto: z.boolean().default(true), keep: z.number().default(10), warnMB: z.number().default(1024), freeMB: z.number().default(512) }).default({}),
@@ -144,7 +144,7 @@ export class DouyinBrowser {
144
144
  * @param {import('./douyin-http.js').DouyinHttp} [deps.http] 纯 HTTP 客户端(http 模式用)
145
145
  * @param {object} [deps.timing] 页面操作的时间上限(eval / send / next 的总预算)
146
146
  */
147
- constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, shareFallback, note, http, frames, timing = {} }) {
147
+ constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, shareFallback, note, http, cli = null, frames, timing = {} }) {
148
148
  this.share = share ?? null;
149
149
  // #133:同上 —— 漏了这个参数兜底就是死代码。
150
150
  this.shareFallback = shareFallback ?? null;
@@ -163,6 +163,7 @@ export class DouyinBrowser {
163
163
  this.settleMs = settleMs;
164
164
  this.fetch = fetchImpl ?? ((...a) => fetch(...a));
165
165
  this.http = http ?? null; // 纯 HTTP 客户端(http 模式用;没有就退回浏览器)
166
+ this.cli = cli ?? null; // 可选:用 douyin-open-cli video text 补强视频口播/高质量文本
166
167
  this.running = false;
167
168
  this.httpBroken = false; // 这轮试过纯 HTTP 不行 → 退回浏览器
168
169
  this.described = new Map();
@@ -464,6 +465,8 @@ export class DouyinBrowser {
464
465
  imageCount: sum.imageCount,
465
466
  comments: (cm.ok ? cm.list : []).map((c) => ({ text: String(c.text ?? ''), author: String(c.user?.nickname ?? '') }))
466
467
  };
468
+ const cliText = await this.cliTextFor(v.id);
469
+ if (cliText !== '') v.ocr = v.ocr ? `${v.ocr};${cliText}` : cliText;
467
470
  // 抽帧看画面(默认关):九宫格 → 再让模型读成一句话,塞进这段感受里。
468
471
  // 和 B站 那条一个套路:拿不到就照旧只看文字,不影响她看完这条。
469
472
  const shot = await this.frameForWatch(d, v.id);
@@ -764,12 +767,25 @@ export class DouyinBrowser {
764
767
  const sum = extractWorkSummary(d, cm.ok ? cm.list : []);
765
768
  // 抽帧看画面(默认关,共用"自己刷视频"那个开关与每日配额):
766
769
  // 私信里分享的视频也该看得见画面,不能只给文案 + 热评(用户反馈 2026-11-25)。
770
+ const cliText = await this.cliTextFor(id);
767
771
  const shot = sum.imageCount > 0 ? '' : await this.frameForWatch(d, id);
768
772
  return `【抖音${sum.imageCount > 0 ? '图文' : '视频'}:${oneLine(sum.title, 120) || '(没有文案)'};作者 ${oneLine(sum.author, 20) || '未知'}`
769
773
  + (sum.imageCount > 0 ? `;共 ${sum.imageCount} 张图` : '')
770
774
  + (sum.music ? `;BGM:${oneLine(sum.music, 40)}` : '')
771
775
  + (sum.ocr ? `;画面文字:${oneLine(sum.ocr, 80)}` : '')
776
+ + (cliText ? `;视频文本:${oneLine(cliText, 120)}` : '')
772
777
  + (shot ? `;画面:${shot}` : '')
773
778
  + (sum.topComments.length ? `;热评:${sum.topComments.join(' / ')}` : '') + '】';
774
779
  }
780
+
781
+ /** 开了 douyin.cli.browseText 时调 CLI 拿官方高质量文本;失败静默退回空串,不阻断看视频。 */
782
+ async cliTextFor(id) {
783
+ if (!this.cli || this.getConfig()?.cli?.browseText !== true) return '';
784
+ try {
785
+ const r = await this.cli.videoText(id);
786
+ return r?.ok ? oneLine(r.text, 200) : '';
787
+ } catch {
788
+ return '';
789
+ }
790
+ }
775
791
  }
@@ -0,0 +1,474 @@
1
+ /**
2
+ * douyin-cli.js —— 抖音开放 CLI(douyin-open-cli)底层执行与协议适配层。
3
+ *
4
+ * 设计要点:
5
+ * 1. 只用 execFile(绝不走 shell),防止文案/标题里的特殊字符引发命令注入或 Windows 转义错乱;
6
+ * 2. 复杂 JSON 写无 BOM 的临时 UTF-8 文件,通过 `--data @<file>` 传入并在 finally 清理;
7
+ * 3. 用 Node 22 原生 `JSON.parse(raw, reviver)` 的 `context.source` 保留超过 Number.MAX_SAFE_INTEGER 的
8
+ * 64 位整数(抖音 19 位 item_id / comment_id / uid),避免精度截断;
9
+ * 4. 严格分离 stdout(业务 JSON)与 stderr(自动升级提醒 / 诊断日志),不把升级告警当成业务失败;
10
+ * 5. 统一区分「未发出去」(NOT_ATTEMPTED)与「结果不明」(ATTEMPTED_UNKNOWN),对齐 DouyinPostJobs 与防重发护栏。
11
+ */
12
+ import { execFile as execFileCb } from 'node:child_process';
13
+ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { promisify } from 'node:util';
17
+ import { WRITE_NOT_ATTEMPTED, WRITE_ATTEMPTED_UNKNOWN } from './channels/vendor/douyin-bridge/douyin-comment.js';
18
+
19
+ const execFileAsync = promisify(execFileCb);
20
+
21
+ const DEFAULT_TIMEOUT_MS = 30_000;
22
+ const UPLOAD_TIMEOUT_MS = 180_000;
23
+ const MAX_BUFFER_BYTES = 16 * 1024 * 1024;
24
+ const SAFE_INT_RE = /^-?\d+$/;
25
+
26
+ const AUTH_ERROR_CODES = new Set([
27
+ 'AUTH_REQUIRED',
28
+ 'AUTH_REFRESH_FAILED',
29
+ 'SCOPE_INSUFFICIENT',
30
+ 'TOKEN_MISSING',
31
+ 'CREDENTIALS_MISSING',
32
+ 'REAUTHORIZATION_REQUIRED'
33
+ ]);
34
+
35
+ const UNKNOWN_WRITE_CODES = new Set([
36
+ 'WRITE_OUTCOME_UNKNOWN',
37
+ 'REQUEST_TIMEOUT',
38
+ 'REQUEST_CANCELED'
39
+ ]);
40
+
41
+ /** 保留超过安全整数范围的 64 位整数(抖音 19 位作品/评论/用户 ID)为原始字符串。 */
42
+ export function parseCliJson(raw) {
43
+ const text = String(raw ?? '').trim();
44
+ if (text === '') return null;
45
+ return JSON.parse(text, (_key, value, context) => {
46
+ if (typeof value === 'number' && context && typeof context.source === 'string') {
47
+ const src = context.source.trim();
48
+ if (SAFE_INT_RE.test(src) && !Number.isSafeInteger(value)) return src;
49
+ }
50
+ return value;
51
+ });
52
+ }
53
+
54
+ /** 提取 CLI 返回体里的业务数据(兼容直出对象与 { err_no, data } 网关包装)。 */
55
+ function unwrapData(parsed) {
56
+ if (!parsed || typeof parsed !== 'object') return null;
57
+ const d = parsed.data;
58
+ if (d && typeof d === 'object' && d.data && typeof d.data === 'object' && ('err_no' in d || 'error_code' in d)) {
59
+ return d.data;
60
+ }
61
+ return d ?? parsed;
62
+ }
63
+
64
+ /** 从 CLI 失败对象或异常中提取标准化错误码与原因。 */
65
+ function extractCliError(parsed, err) {
66
+ const eObj = parsed?.error && typeof parsed.error === 'object' ? parsed.error : null;
67
+ const rawCode = String(eObj?.code ?? parsed?.code ?? parsed?.error_code ?? err?.code ?? '').trim();
68
+ const msg = String(
69
+ eObj?.message ?? eObj?.description ?? parsed?.message ?? parsed?.err_msg ?? err?.message ?? 'CLI 执行失败'
70
+ ).trim();
71
+ return { rawCode, msg };
72
+ }
73
+
74
+ /** 把字符串或数字安全转为非空 ID 字符串(兼容 19 位大整数)。 */
75
+ function idStr(v) {
76
+ if (v === null || v === undefined) return '';
77
+ const s = String(v).trim();
78
+ return s === '0' ? '' : s;
79
+ }
80
+
81
+ /** 构造仅包含正整数文本的 JSON(供 `--data @FILE` 传 64 位整数,避免 JS Number 精度丢失)。 */
82
+ export function buildCommentReplyJson({ itemId, replyId, replyToReplyId, text }) {
83
+ const parts = [`"ItemId":${String(itemId).trim()}`];
84
+ if (replyId) parts.push(`"ReplyId":${String(replyId).trim()}`);
85
+ if (replyToReplyId) parts.push(`"ReplyToReplyId":${String(replyToReplyId).trim()}`);
86
+ parts.push(`"Text":${JSON.stringify(String(text ?? ''))}`);
87
+ return `{${parts.join(',')}}`;
88
+ }
89
+
90
+ /** 构造评论对象(对齐 DouyinSocial 的 listCommentsApi 形状)。 */
91
+ function normalizeCommentItem(raw) {
92
+ if (!raw || typeof raw !== 'object') return null;
93
+ const cid = idStr(raw.cid ?? raw.comment_id ?? raw.CommentId ?? raw.id);
94
+ const user = raw.user && typeof raw.user === 'object' ? raw.user : {};
95
+ const uid = idStr(raw.uid ?? raw.user_id ?? user.uid ?? user.user_id);
96
+ const author = String(raw.author ?? raw.nickname ?? user.nickname ?? user.name ?? '').trim();
97
+ const content = String(raw.text ?? raw.content ?? raw.Text ?? '').trim();
98
+ const createTime = Number(raw.create_time ?? raw.createTime ?? raw.CreateTime ?? 0) || 0;
99
+ const replyTotal = Number(raw.reply_comment_total ?? raw.replyTotal ?? raw.ReplyCount ?? 0) || 0;
100
+ const labelType = Number(raw.label_type ?? raw.labelType ?? 0) || 0;
101
+ const hasImage = Boolean(raw.image_list?.length || raw.sticker || raw.has_image || raw.hasImage);
102
+ const replyComment = Array.isArray(raw.reply_comment ?? raw.replyComment)
103
+ ? (raw.reply_comment ?? raw.replyComment).map(normalizeCommentItem).filter(Boolean)
104
+ : [];
105
+ return {
106
+ cid,
107
+ uid,
108
+ author,
109
+ content,
110
+ createTime,
111
+ replyTotal,
112
+ labelType,
113
+ hasImage,
114
+ isAuthor: labelType === 1 || raw.is_author === true || raw.isAuthor === true,
115
+ canReply: cid !== '',
116
+ replyComment
117
+ };
118
+ }
119
+
120
+ /** 构造作品列表项(对齐 DouyinSocial 的 listWorks 形状)。 */
121
+ function normalizeWorkItem(raw) {
122
+ if (!raw || typeof raw !== 'object') return null;
123
+ const id = idStr(raw.item_id ?? raw.aweme_id ?? raw.video_id ?? raw.ItemId ?? raw.id);
124
+ if (!id) return null;
125
+ const title = String(raw.title ?? raw.desc ?? raw.Desc ?? '').trim();
126
+ const mediaType = Number(raw.aweme_type ?? raw.media_type ?? 0);
127
+ const kind = mediaType === 68 || raw.kind === 'note' ? 'note' : 'video';
128
+ return { id, kind, title, href: `https://www.douyin.com/video/${id}` };
129
+ }
130
+
131
+ export class DouyinCli {
132
+ /**
133
+ * @param {object} [opts]
134
+ * @param {() => object} [opts.getConfig] 返回 config.douyin.cli
135
+ * @param {(level: string, msg: string) => void} [opts.log]
136
+ * @param {(file: string, args: string[], options: object) => Promise<{stdout: string, stderr: string}>} [opts.execFileImpl]
137
+ */
138
+ constructor({ getConfig, log, execFileImpl } = {}) {
139
+ this.getConfig = typeof getConfig === 'function' ? getConfig : () => ({});
140
+ this.log = typeof log === 'function' ? log : () => {};
141
+ this.execFileImpl = execFileImpl ?? execFileAsync;
142
+ }
143
+
144
+ cfg() {
145
+ const raw = this.getConfig() ?? {};
146
+ return {
147
+ socialBackend: raw.socialBackend === 'hybrid' ? 'hybrid' : 'browser',
148
+ binaryPath: String(raw.binaryPath ?? '').trim() || 'douyin-open-cli',
149
+ authDir: String(raw.authDir ?? '').trim(),
150
+ browseText: raw.browseText === true
151
+ };
152
+ }
153
+
154
+ /**
155
+ * 执行一条 douyin-open-cli 子命令。
156
+ * @param {string[]} args
157
+ * @param {object} [opts]
158
+ * @param {number} [opts.timeoutMs]
159
+ * @param {boolean} [opts.isWrite]
160
+ * @param {string|object|null} [opts.dataPayload] 传给 `--data @FILE` 的无 BOM UTF-8 内容
161
+ */
162
+ async exec(args, { timeoutMs = DEFAULT_TIMEOUT_MS, isWrite = false, dataPayload = null } = {}) {
163
+ const { binaryPath, authDir } = this.cfg();
164
+ const finalArgs = [...args];
165
+ let tempDir = '';
166
+ if (dataPayload !== null && dataPayload !== undefined) {
167
+ tempDir = mkdtempSync(join(tmpdir(), 'fish-soul-dycli-'));
168
+ const reqPath = join(tempDir, 'request.json');
169
+ const body = typeof dataPayload === 'string' ? dataPayload : JSON.stringify(dataPayload);
170
+ writeFileSync(reqPath, body, { encoding: 'utf8' });
171
+ finalArgs.push('--data', `@${reqPath}`);
172
+ }
173
+ if (!finalArgs.includes('--output')) finalArgs.push('--output', 'json');
174
+
175
+ const env = { ...process.env };
176
+ if (authDir !== '') env.DOUYIN_OPEN_CLI_AUTH_DIR = authDir;
177
+
178
+ try {
179
+ const { stdout, stderr } = await this.execFileImpl(binaryPath, finalArgs, {
180
+ timeout: timeoutMs,
181
+ maxBuffer: MAX_BUFFER_BYTES,
182
+ windowsHide: true,
183
+ env
184
+ });
185
+ const errLine = String(stderr ?? '').trim();
186
+ if (errLine !== '') this.log('info', `[fish-soul] douyin-open-cli stderr: ${errLine.slice(0, 200)}`);
187
+
188
+ let parsed;
189
+ try {
190
+ parsed = parseCliJson(stdout);
191
+ } catch (parseErr) {
192
+ const msg = `CLI 返回非 JSON:${parseErr instanceof Error ? parseErr.message : String(parseErr)}`;
193
+ return {
194
+ ok: false,
195
+ code: isWrite ? 'WRITE_UNKNOWN' : 'INVALID_RESPONSE',
196
+ writeState: isWrite ? WRITE_ATTEMPTED_UNKNOWN : WRITE_NOT_ATTEMPTED,
197
+ error: msg
198
+ };
199
+ }
200
+
201
+ if (!parsed || typeof parsed !== 'object') {
202
+ return {
203
+ ok: false,
204
+ code: isWrite ? 'WRITE_UNKNOWN' : 'INVALID_RESPONSE',
205
+ writeState: isWrite ? WRITE_ATTEMPTED_UNKNOWN : WRITE_NOT_ATTEMPTED,
206
+ error: 'CLI 返回空内容'
207
+ };
208
+ }
209
+
210
+ if (parsed.ok === false) {
211
+ const { rawCode, msg } = extractCliError(parsed, null);
212
+ if (AUTH_ERROR_CODES.has(rawCode)) {
213
+ return { ok: false, code: 'AUTH_REQUIRED', rawCode, writeState: WRITE_NOT_ATTEMPTED, error: msg, parsed };
214
+ }
215
+ if (isWrite && UNKNOWN_WRITE_CODES.has(rawCode)) {
216
+ return { ok: false, code: 'WRITE_UNKNOWN', rawCode, writeState: WRITE_ATTEMPTED_UNKNOWN, error: msg, parsed };
217
+ }
218
+ return {
219
+ ok: false,
220
+ code: rawCode || 'CLI_ERROR',
221
+ rawCode,
222
+ writeState: WRITE_NOT_ATTEMPTED,
223
+ error: msg,
224
+ parsed
225
+ };
226
+ }
227
+
228
+ return { ok: true, parsed, data: unwrapData(parsed) };
229
+ } catch (err) {
230
+ if (err?.code === 'ENOENT') {
231
+ return {
232
+ ok: false,
233
+ code: 'CLI_NOT_FOUND',
234
+ writeState: WRITE_NOT_ATTEMPTED,
235
+ error: `找不到 ${binaryPath},请先安装 douyin-open-cli`
236
+ };
237
+ }
238
+ let parsed = null;
239
+ if (err?.stdout) {
240
+ try { parsed = parseCliJson(err.stdout); } catch { /* stdout 不是有效 JSON,按进程错误分类 */ }
241
+ }
242
+ const { rawCode, msg } = extractCliError(parsed, err);
243
+ if (AUTH_ERROR_CODES.has(rawCode)) {
244
+ return { ok: false, code: 'AUTH_REQUIRED', rawCode, writeState: WRITE_NOT_ATTEMPTED, error: msg, parsed };
245
+ }
246
+ const isTimeoutOrKilled = Boolean(err?.killed || err?.signal === 'SIGTERM' || err?.code === 'ETIMEDOUT' || UNKNOWN_WRITE_CODES.has(rawCode));
247
+ if (isWrite && isTimeoutOrKilled) {
248
+ return {
249
+ ok: false,
250
+ code: 'WRITE_UNKNOWN',
251
+ rawCode: rawCode || 'REQUEST_TIMEOUT',
252
+ writeState: WRITE_ATTEMPTED_UNKNOWN,
253
+ error: `写操作超时或结果不明:${msg}`,
254
+ parsed
255
+ };
256
+ }
257
+ return {
258
+ ok: false,
259
+ code: rawCode || (isTimeoutOrKilled ? 'TIMEOUT' : 'CLI_ERROR'),
260
+ rawCode,
261
+ writeState: WRITE_NOT_ATTEMPTED,
262
+ error: msg,
263
+ parsed
264
+ };
265
+ } finally {
266
+ if (tempDir !== '') {
267
+ try { rmSync(tempDir, { recursive: true, force: true }); } catch { /* 临时目录清理失败不影响主结果 */ }
268
+ }
269
+ }
270
+ }
271
+
272
+ /** 检查本地登录态与 scope 覆盖情况(不触发网络续期或扫码)。 */
273
+ async authStatus() {
274
+ const res = await this.exec(['auth', 'status']);
275
+ if (!res.ok) return { ok: false, loggedIn: false, code: res.code, error: res.error };
276
+ const d = res.data ?? {};
277
+ const loggedIn = d.logged_in === true || d.credential_status === 'valid';
278
+ const missingScopes = Array.isArray(d.missing_scopes) ? d.missing_scopes.map(String) : [];
279
+ return {
280
+ ok: true,
281
+ loggedIn,
282
+ credentialStatus: String(d.credential_status ?? ''),
283
+ openId: String(d.open_id ?? ''),
284
+ expiresAt: d.expires_at ?? null,
285
+ tokenExpired: d.token_expired === true,
286
+ missingScopes,
287
+ reauthRequired: d.reauthorization_required === true
288
+ };
289
+ }
290
+
291
+ /** 判断给定 authStatus 是否覆盖目标 scope。 */
292
+ static hasScope(status, scope) {
293
+ if (!status?.ok || !status.loggedIn) return false;
294
+ if (!scope) return true;
295
+ return !Array.isArray(status.missingScopes) || !status.missingScopes.includes(scope);
296
+ }
297
+
298
+ /** 发起非阻塞扫码登录,返回二维码图片 DataURL(如存在)与轮询建议。 */
299
+ async authLoginBegin({ force = false } = {}) {
300
+ const args = ['auth', 'login', '--begin'];
301
+ if (force) args.push('--force');
302
+ const res = await this.exec(args, { timeoutMs: 45_000 });
303
+ if (!res.ok) return { ok: false, code: res.code, error: res.error };
304
+ const d = res.data ?? {};
305
+ const qrImagePath = String(d.qr_image_path ?? '').trim();
306
+ let qrDataUrl = '';
307
+ if (qrImagePath !== '' && /\.png$/i.test(qrImagePath)) {
308
+ try {
309
+ const st = statSync(qrImagePath);
310
+ if (st.isFile() && st.size > 0 && st.size <= 2 * 1024 * 1024) {
311
+ const buf = readFileSync(qrImagePath);
312
+ qrDataUrl = `data:image/png;base64,${buf.toString('base64')}`;
313
+ }
314
+ } catch { /* 读取二维码文件失败时回退 verification_url */ }
315
+ }
316
+ return {
317
+ ok: true,
318
+ alreadyLoggedIn: d.logged_in === true || d.status === 'logged_in',
319
+ status: String(d.status ?? (qrImagePath ? 'pending' : 'logged_in')),
320
+ qrImagePath,
321
+ qrDataUrl,
322
+ verificationUrl: String(d.verification_url ?? ''),
323
+ retryAfterSeconds: Number(d.retry_after_seconds ?? 3) || 3,
324
+ expiresAt: d.expires_at ?? null
325
+ };
326
+ }
327
+
328
+ /** 轮询一次待确认的扫码登录状态。 */
329
+ async authLoginComplete() {
330
+ const res = await this.exec(['auth', 'login', '--complete'], { timeoutMs: 30_000 });
331
+ if (!res.ok) return { ok: false, status: 'failed', code: res.code, error: res.error };
332
+ const d = res.data ?? {};
333
+ const status = d.logged_in === true || d.status === 'logged_in' || d.status === 'completed'
334
+ ? 'logged_in'
335
+ : (d.status === 'pending' ? 'pending' : 'failed');
336
+ return {
337
+ ok: true,
338
+ status,
339
+ loggedIn: status === 'logged_in',
340
+ retryAfterSeconds: Number(d.retry_after_seconds ?? 3) || 3,
341
+ openId: String(d.open_id ?? '')
342
+ };
343
+ }
344
+
345
+ /** 查询自己的作品列表。 */
346
+ async videoList({ count = 3 } = {}) {
347
+ const n = Math.min(30, Math.max(1, Math.floor(Number(count) || 3)));
348
+ const res = await this.exec(['video', 'list', '--count', String(n)]);
349
+ if (!res.ok) return { ok: false, works: [], code: res.code, error: res.error };
350
+ const d = res.data ?? {};
351
+ const rawList = Array.isArray(d.list) ? d.list
352
+ : Array.isArray(d.videos) ? d.videos
353
+ : Array.isArray(d.item_list) ? d.item_list
354
+ : Array.isArray(d.aweme_list) ? d.aweme_list
355
+ : [];
356
+ return { ok: true, works: rawList.map(normalizeWorkItem).filter(Boolean) };
357
+ }
358
+
359
+ /** 获取作品高质量文本(口播 / 字幕 / 摘要),用于补强刷视频内容理解。 */
360
+ async videoText(videoId) {
361
+ const id = idStr(videoId);
362
+ if (!id) return { ok: false, text: '', code: 'INVALID_ID', error: '缺少作品 ID' };
363
+ const res = await this.exec(['video', 'text', '--video-id', id], { timeoutMs: 15_000 });
364
+ if (!res.ok) return { ok: false, text: '', code: res.code, error: res.error };
365
+ const d = res.data ?? {};
366
+ const text = String(d.high_quality_text ?? d.text ?? '').trim();
367
+ return { ok: text !== '', text };
368
+ }
369
+
370
+ /** 上传本地视频,返回加密 video_id(非作品 ID)。 */
371
+ async videoUpload(filePath) {
372
+ const res = await this.exec(['video', 'upload', '--file', String(filePath), '--yes'], {
373
+ timeoutMs: UPLOAD_TIMEOUT_MS,
374
+ isWrite: false
375
+ });
376
+ if (!res.ok) return { ok: false, code: res.code, error: res.error };
377
+ const d = res.data ?? {};
378
+ const videoId = String(d.video?.video_id ?? d.video_id ?? '').trim();
379
+ if (!videoId) return { ok: false, code: 'UPLOAD_NO_ID', error: '上传返回缺少 video_id' };
380
+ return { ok: true, videoId };
381
+ }
382
+
383
+ /** 用已上传的加密 video_id 正式投稿发布视频。 */
384
+ async videoPublish({ videoId, title, privateStatus = 0 }) {
385
+ const payload = {
386
+ video_id: String(videoId),
387
+ text: String(title ?? '').slice(0, 1000),
388
+ private_status: Number(privateStatus) || 0,
389
+ publish_way: 0
390
+ };
391
+ const res = await this.exec(['video', 'publish', '--yes'], {
392
+ timeoutMs: 60_000,
393
+ isWrite: true,
394
+ dataPayload: payload
395
+ });
396
+ if (!res.ok) {
397
+ return { ok: false, code: res.code, writeState: res.writeState, error: res.error };
398
+ }
399
+ const d = res.data ?? {};
400
+ const workId = idStr(d.item_id ?? d.video_id ?? d.aweme_id);
401
+ return { ok: true, workId };
402
+ }
403
+
404
+ /** 查询作品一级评论列表。 */
405
+ async commentList(videoId, { pageSize = 20, pageToken = '0' } = {}) {
406
+ const id = idStr(videoId);
407
+ if (!id) return { ok: false, comments: [], code: 'INVALID_ID', error: '缺少作品 ID' };
408
+ const size = Math.min(50, Math.max(1, Math.floor(Number(pageSize) || 20)));
409
+ const res = await this.exec([
410
+ 'comment', 'list',
411
+ '--video-id', id,
412
+ '--page-size', String(size),
413
+ '--page-token', String(pageToken ?? '0')
414
+ ]);
415
+ if (!res.ok) return { ok: false, comments: [], code: res.code, error: res.error };
416
+ const d = res.data ?? {};
417
+ const rawList = Array.isArray(d.comments) ? d.comments
418
+ : Array.isArray(d.list) ? d.list
419
+ : Array.isArray(d.comment_list) ? d.comment_list
420
+ : [];
421
+ return { ok: true, comments: rawList.map(normalizeCommentItem).filter(Boolean) };
422
+ }
423
+
424
+ /** 查询某条评论的回复列表。 */
425
+ async commentReplyList(videoId, commentId, { pageSize = 20, pageToken = '0' } = {}) {
426
+ const vid = idStr(videoId);
427
+ const cid = idStr(commentId);
428
+ if (!vid || !cid) return { ok: false, comments: [], code: 'INVALID_ID', error: '缺少作品或评论 ID' };
429
+ const size = Math.min(50, Math.max(1, Math.floor(Number(pageSize) || 20)));
430
+ const res = await this.exec([
431
+ 'comment', 'reply-list',
432
+ '--video-id', vid,
433
+ '--comment-id', cid,
434
+ '--page-size', String(size),
435
+ '--page-token', String(pageToken ?? '0')
436
+ ]);
437
+ if (!res.ok) return { ok: false, comments: [], code: res.code, error: res.error };
438
+ const d = res.data ?? {};
439
+ const rawList = Array.isArray(d.comments) ? d.comments
440
+ : Array.isArray(d.list) ? d.list
441
+ : Array.isArray(d.reply_list) ? d.reply_list
442
+ : [];
443
+ return { ok: true, comments: rawList.map(normalizeCommentItem).filter(Boolean) };
444
+ }
445
+
446
+ /** 回复评论(支持一级评论和二级楼中楼)。 */
447
+ async commentReply({ itemId, replyId, replyToReplyId, text }) {
448
+ const iid = idStr(itemId);
449
+ const rid = idStr(replyId);
450
+ const rtrid = idStr(replyToReplyId);
451
+ if (!iid || !rid || !/^\d+$/.test(iid) || !/^\d+$/.test(rid)) {
452
+ return { ok: false, code: 'INVALID_ID', writeState: WRITE_NOT_ATTEMPTED, error: '无效的作品或评论 ID' };
453
+ }
454
+ if (rtrid && !/^\d+$/.test(rtrid)) {
455
+ return { ok: false, code: 'INVALID_ID', writeState: WRITE_NOT_ATTEMPTED, error: '无效的二级评论 ID' };
456
+ }
457
+ const cleanText = String(text ?? '').trim();
458
+ if (!cleanText) {
459
+ return { ok: false, code: 'EMPTY_TEXT', writeState: WRITE_NOT_ATTEMPTED, error: '评论正文为空' };
460
+ }
461
+ const jsonBody = buildCommentReplyJson({ itemId: iid, replyId: rid, replyToReplyId: rtrid, text: cleanText });
462
+ const res = await this.exec(['comment', 'reply', '--yes'], {
463
+ timeoutMs: 30_000,
464
+ isWrite: true,
465
+ dataPayload: jsonBody
466
+ });
467
+ if (!res.ok) {
468
+ return { ok: false, code: res.code, writeState: res.writeState, error: res.error };
469
+ }
470
+ const d = res.data ?? {};
471
+ const cid = idStr(d.comment_id ?? d.cid ?? d.CommentId);
472
+ return { ok: true, cid };
473
+ }
474
+ }
@@ -41,8 +41,9 @@ export class DouyinPostJobs {
41
41
  const r=this.db.prepare("UPDATE douyin_post_job SET status='confirmed',error='',updated_at=? WHERE id=? AND status='submitting'").run(Date.now(),id);
42
42
  if (Number(r.changes)!==1) throw Error('发布任务状态异常,需核实');
43
43
  }
44
- fail(id, error) {
45
- this.db.prepare("UPDATE douyin_post_job SET status=CASE status WHEN 'submitting' THEN 'unknown' ELSE 'failed' END, error=?,updated_at=? WHERE id=? AND status IN ('preparing','submitting')").run(String(error).slice(0,300),Date.now(),id);
44
+ fail(id, error, { notAttempted = false } = {}) {
45
+ const nextStatus = notAttempted ? "'failed'" : "CASE status WHEN 'submitting' THEN 'unknown' ELSE 'failed' END";
46
+ this.db.prepare(`UPDATE douyin_post_job SET status=${nextStatus}, error=?,updated_at=? WHERE id=? AND status IN ('preparing','submitting')`).run(String(error).slice(0,300),Date.now(),id);
46
47
  }
47
48
  resolvePublished(id) {
48
49
  return Number(this.db.prepare("UPDATE douyin_post_job SET status='confirmed_manual',error='用户核实已发布',updated_at=? WHERE id=? AND status='unknown'").run(Date.now(),id).changes) === 1;