dsh-fish-soul 0.18.8 → 0.18.9
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 +1 -1
- package/lib/channels/douyin.js +9 -0
- package/lib/douyin-adapter.js +535 -0
- package/lib/gateway-media.js +20 -163
- package/lib/gateway.js +44 -210
- package/lib/index.js +5 -0
- package/lib/life.js +59 -4
- package/lib/routes.js +30 -2
- package/package.json +5 -3
package/README.md
CHANGED
package/lib/channels/douyin.js
CHANGED
|
@@ -981,6 +981,15 @@ export class DouyinChannel {
|
|
|
981
981
|
status() {
|
|
982
982
|
return {
|
|
983
983
|
running: this.running,
|
|
984
|
+
// 「真的能用」= 轮询循环活着 && 浏览器在跑 && 登录态正常。
|
|
985
|
+
// 🔴 单看 `running` 会误判:`pollOnce` 在 `!this.host.running` 时**直接 return
|
|
986
|
+
// 且不记错误**,所以浏览器崩了/被暂停,轮询循环照样活着、`running` 仍是 true。
|
|
987
|
+
// `connected` 是那个 getter 的结果,和 QQ 的 `connected`、B站的 `loggedIn`
|
|
988
|
+
// 语义对齐 —— 诊断页判这个才看得出「真的不能用」。
|
|
989
|
+
connected: this.connected,
|
|
990
|
+
// ⚠️ 暂停时 `host.running` 仍是 true(只是停了轮询),所以 `connected` 看不出来 ——
|
|
991
|
+
// 单独给出来,让诊断页能说清「是被暂停了」而不是「没跑」。
|
|
992
|
+
paused: this.host?.paused === true,
|
|
984
993
|
lastPollAt: this.lastPollAt,
|
|
985
994
|
lastError: this.lastError,
|
|
986
995
|
replyPaused: this.replyPaused,
|
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 抖音适配器(PR2:接口与身份解析)。
|
|
3
|
+
*
|
|
4
|
+
* 只做两件事:
|
|
5
|
+
* ① 给出「已核实的身份键」(`douyin:<数字uid>`)—— 拿不到就返回 '',不猜、不退回昵称。
|
|
6
|
+
* ② 抖音会话相关的纯查询:配置归一、身份反查、候选 / 绑定表、主人身份、会话 ID、认人、会话标题。
|
|
7
|
+
*
|
|
8
|
+
* 不做授权:master / allowList / replyAll 的判定留在网关(onDouyinMessage),
|
|
9
|
+
* 适配器只回答「这条消息的身份键是什么、这个身份键对应谁」。
|
|
10
|
+
*
|
|
11
|
+
* 依赖方向:只 import db.js / douyin-conversation.js / gateway-util.js / channels/onebot.js,
|
|
12
|
+
* 不 import gateway*.js。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
16
|
+
import { getKv, setKv, resolveOrCreatePlatformPerson, cleanupMergedDouyinNames } from './db.js';
|
|
17
|
+
import { isIdentityKey } from './douyin-conversation.js';
|
|
18
|
+
import { findDouyinRefs } from './douyin-browse.js';
|
|
19
|
+
import { douyinVideoIds, deliverDouyinCards } from './douyin-delivery.js';
|
|
20
|
+
import { splitChannelId, clampReplyWindow } from './gateway-util.js';
|
|
21
|
+
import { sanitizeName } from './channels/onebot.js';
|
|
22
|
+
|
|
23
|
+
/** 抖音 uid 绑定表的 kv key(`douyin.uin.<纯数字uid>`);uid 不合法返回 ''。 */
|
|
24
|
+
function normUidKey(uid) {
|
|
25
|
+
const s = String(uid ?? '').trim().replace(/^uid:/, '').replace(/^douyin:/, '');
|
|
26
|
+
return /^\d+$/.test(s) ? `douyin.uin.${s}` : '';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class DouyinAdapter {
|
|
30
|
+
/**
|
|
31
|
+
* @param {object} deps
|
|
32
|
+
* @param {import('node:sqlite').DatabaseSync | (() => import('node:sqlite').DatabaseSync)} deps.db
|
|
33
|
+
* 库句柄,或返回句柄的函数。**推荐传函数**:网关允许 `gw.db = 新库` 换库(老测试就这么用),
|
|
34
|
+
* 快照下来的句柄会指向已关闭的旧库。
|
|
35
|
+
* @param {() => object} deps.getConfig 整个插件配置(读 douyin.* 与 masterQqUin)
|
|
36
|
+
* @param {(kind: string, info: object) => void} [deps.note] 记动态(候选提示用)
|
|
37
|
+
* @param {(level: string, msg: string) => void} [deps.log]
|
|
38
|
+
* @param {Function} [deps.diag]
|
|
39
|
+
* @param {() => object | null} [deps.inbox] 抖音收件箱(结算用);传函数以便换通道实例
|
|
40
|
+
* @param {() => object | null} [deps.channel] 抖音通道(发送 / 分享卡片用);传函数以便换通道实例
|
|
41
|
+
* @param {(row: object, text: string, images: any[], convId: string) => Promise<object>} [deps.sendText] 发文字(卡片分享的说明文字走它)
|
|
42
|
+
*/
|
|
43
|
+
constructor({ db, getConfig, note = () => {}, log = () => {}, diag = () => {}, inbox = null, channel = null, sendText = null }) {
|
|
44
|
+
this.platform = 'douyin';
|
|
45
|
+
// 库里可能被整体替换(`gw.db = fresh`),所以每次用的时候再取
|
|
46
|
+
const dbOf = typeof db === 'function' ? db : () => db;
|
|
47
|
+
Object.defineProperty(this, 'db', { get: dbOf, configurable: true });
|
|
48
|
+
this.getConfig = getConfig;
|
|
49
|
+
/** 抖音收件箱(PR3:结算走这里)。用函数以便通道实例被替换时跟着换。 */
|
|
50
|
+
this.inbox = typeof inbox === 'function' ? inbox : () => inbox;
|
|
51
|
+
/** 抖音通道(PR4:发送 / 分享卡片用)。用函数以便通道实例被替换时跟着换。 */
|
|
52
|
+
this.channel = typeof channel === 'function' ? channel : () => channel;
|
|
53
|
+
/** 发文字(卡片分享的说明文字走它)。可能是网关的 sendDouyin,也可能被替换。 */
|
|
54
|
+
this.sendText = typeof sendText === 'function' ? sendText : async () => ({ ok: false, delivered: false, parts: [], error: '没接上发送通道' });
|
|
55
|
+
this.note = note;
|
|
56
|
+
this.log = log;
|
|
57
|
+
this.diag = diag;
|
|
58
|
+
/** 仅声明能力;读取并做判定的仍是网关。 */
|
|
59
|
+
this.capabilities = { proactive: 'share-only', crossPlatformReply: false, hostTools: false };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 抖音通道配置(与 ChatGateway.douyinConfig 同形)。 */
|
|
63
|
+
douyinConfig() {
|
|
64
|
+
const d = this.getConfig().douyin ?? {};
|
|
65
|
+
const num = (v, def) => (Number.isFinite(Number(v)) ? Number(v) : def);
|
|
66
|
+
return {
|
|
67
|
+
enabled: d.enabled === true,
|
|
68
|
+
autoReply: d.autoReply === true,
|
|
69
|
+
masterName: String(d.masterName ?? '').trim(),
|
|
70
|
+
// 主人身份:只认会话身份(`douyin:<uid>`)。昵称 `masterName` 只用于显示,
|
|
71
|
+
// 不再授予任何权限 —— 同名可冒充,改名又会对不上。
|
|
72
|
+
masterUid: String(d.masterUid ?? '').trim(),
|
|
73
|
+
// 原生视频卡片分享(默认关)
|
|
74
|
+
shareCard: d.shareCard === true,
|
|
75
|
+
allowList: Array.isArray(d.allowList) ? d.allowList.map((x) => String(x).trim()).filter(Boolean) : [],
|
|
76
|
+
replyAll: d.replyAll === true,
|
|
77
|
+
groups: Array.isArray(d.groups) ? d.groups.map((x) => String(x).trim()).filter(Boolean) : [],
|
|
78
|
+
groupReply: d.groupReply === true,
|
|
79
|
+
callNames: Array.isArray(d.callNames) ? d.callNames.map((x) => String(x).trim()).filter(Boolean) : [],
|
|
80
|
+
batchMs: num(d.batchMs, 3000),
|
|
81
|
+
replyWindowMinutes: clampReplyWindow(d.replyWindowMinutes)
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 入站消息的「身份核验」:挡掉自身回声和不合法的身份键。只给结论,不做授权。
|
|
87
|
+
*
|
|
88
|
+
* @param {{userId?: string, senderId?: string}} m
|
|
89
|
+
* @param {string[]} selfUids 通道自己已知的 uid 列表(回声判定用)
|
|
90
|
+
* @returns {{ok: true, identity: string} | {ok: false, done: boolean, review: string}}
|
|
91
|
+
*/
|
|
92
|
+
verifyInbound(m, selfUids = []) {
|
|
93
|
+
if (selfUids.includes(String(m?.senderId ?? '').trim())) {
|
|
94
|
+
return { ok: false, done: true, review: '自身消息,不回复' };
|
|
95
|
+
}
|
|
96
|
+
if (!isIdentityKey(m?.userId)) {
|
|
97
|
+
return { ok: false, done: false, review: '抖音会话身份未确认(缺会话 ID),消息已保留,暂不处理' };
|
|
98
|
+
}
|
|
99
|
+
return { ok: true, identity: String(m.userId) };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 这个聊天对应的 QQ 号。算不出返回 ''(不共享会话)。昵称绝不当身份。
|
|
104
|
+
*
|
|
105
|
+
* 两级:① 数字 uid 对应表直接认;② 昵称对应表只定位候选,
|
|
106
|
+
* 必须拿到真实 uid 且已被主人确认过绑定(`douyin.uin.<uid>`)才并。
|
|
107
|
+
* 冒充者改名只能挂出候选,候选不点确认就不生效。
|
|
108
|
+
*/
|
|
109
|
+
douyinUinOf(chat) {
|
|
110
|
+
const [kind] = splitChannelId(chat?.channelId);
|
|
111
|
+
if (kind !== 'douyin') return '';
|
|
112
|
+
const cfg = this.douyinConfig();
|
|
113
|
+
const raw = this.getConfig().douyin ?? {};
|
|
114
|
+
const links = Array.isArray(raw.links) ? raw.links : [];
|
|
115
|
+
const norm = (v) => String(v ?? '').trim().replace(/^uid:/, '').replace(/^douyin:/, '');
|
|
116
|
+
// 真实 uid:优先 chat.userId;没有就从会话游标反查(游标里的 identity 是会话 ID 推出来的,不是昵称)
|
|
117
|
+
let uid = norm(chat?.userId);
|
|
118
|
+
if (!/^\d+$/.test(uid)) uid = norm(this.douyinIdentityOfChannel(chat?.channelId));
|
|
119
|
+
const hasUid = /^\d+$/.test(uid);
|
|
120
|
+
|
|
121
|
+
// ① 主人身份(数字 uid)—— 最硬的一条
|
|
122
|
+
const master = norm(cfg.masterUid);
|
|
123
|
+
if (hasUid && /^\d+$/.test(master) && uid === master) return String(this.getConfig().masterQqUin ?? '');
|
|
124
|
+
|
|
125
|
+
// ② 数字 uid 对应表
|
|
126
|
+
if (hasUid) {
|
|
127
|
+
for (const line of links) {
|
|
128
|
+
const m = String(line).match(/^\s*(?:douyin:|uid:)?(\d+)\s*[=::]\s*(\d{5,12})\s*$/);
|
|
129
|
+
if (m && uid === m[1]) return m[2];
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (!hasUid) return ''; // 只有昵称、拿不到真实 uid ⇒ 不敢并(宁可少并,不可串号)
|
|
134
|
+
|
|
135
|
+
// 🔴 绑定表优先,跟昵称无关:主人确认过一次之后,这个人改了昵称也照样认。
|
|
136
|
+
const boundQq = this.douyinUinBinding(uid);
|
|
137
|
+
if (boundQq !== '') return boundQq;
|
|
138
|
+
|
|
139
|
+
const name = String(splitChannelId(chat?.channelId)[1] ?? '').trim();
|
|
140
|
+
if (name === '') return '';
|
|
141
|
+
for (const line of links) {
|
|
142
|
+
const m = String(line).match(/^\s*([^\d=::\s][^=::]*?)\s*[=::]\s*(\d{5,12})\s*$/);
|
|
143
|
+
if (!m || m[1] !== name) continue;
|
|
144
|
+
// 走到这里 = 还没被主人确认过:挂一条候选,**不自动绑**
|
|
145
|
+
this.noteDouyinUinCandidate({ name, uid, qq: m[2] });
|
|
146
|
+
return '';
|
|
147
|
+
}
|
|
148
|
+
return '';
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 待确认的候选:「这个 uid 是不是你这个昵称对应的人」。不自动绑定,给主人看一眼。 */
|
|
152
|
+
noteDouyinUinCandidate({ name, uid, qq }) {
|
|
153
|
+
const key = `douyin.uinCandidate.${name}`;
|
|
154
|
+
try {
|
|
155
|
+
const old = getKv(this.db, key, null);
|
|
156
|
+
if (old?.uid === uid && old?.qq === qq) return; // 重复的同一条,不再弹
|
|
157
|
+
setKv(this.db, key, { uid, qq, at: Date.now() });
|
|
158
|
+
this.note?.('douyin-uin-candidate', { name, uid, qq });
|
|
159
|
+
this.log?.('info', `[fish-soul] 有一条待确认的抖音身份:「${name}」→ uid ${uid}(配了 QQ ${qq}),等主人确认`);
|
|
160
|
+
} catch { /* 记不下来不影响这一轮 */ }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** `person` 表里这个抖音 uid 挂着的 QQ 号(认人阶段写的,是已确认的事实);没有返回 ''。 */
|
|
164
|
+
douyinPersonQq(uid) {
|
|
165
|
+
const u = String(uid ?? '').trim().replace(/^uid:/, '').replace(/^douyin:/, '');
|
|
166
|
+
if (!/^\d+$/.test(u)) return '';
|
|
167
|
+
try {
|
|
168
|
+
const row = this.db.prepare('SELECT qq_uin FROM person WHERE douyin_uid = ? OR douyin_uid = ? LIMIT 1')
|
|
169
|
+
.get(`douyin:${u}`, `uid:${u}`);
|
|
170
|
+
const qq = String(row?.qq_uin ?? '').trim();
|
|
171
|
+
return /^\d{5,12}$/.test(qq) ? qq : '';
|
|
172
|
+
} catch { return ''; }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** 主人确认之后:把「真实 uid → QQ 号」写进绑定表,并清掉那条候选。 */
|
|
176
|
+
confirmDouyinUin(name) {
|
|
177
|
+
const key = `douyin.uinCandidate.${String(name ?? '').trim()}`;
|
|
178
|
+
const c = getKv(this.db, key, null);
|
|
179
|
+
if (!c?.uid || !/^\d+$/.test(String(c.uid)) || !/^\d{5,12}$/.test(String(c.qq))) return { ok: false, error: '没有这条候选(或已被确认过)' };
|
|
180
|
+
this.bindDouyinUin(String(c.uid), String(c.qq));
|
|
181
|
+
// 绑定已写进绑定表,这条候选没用了(留着会误导主人以为还没确认)
|
|
182
|
+
try { setKv(this.db, key, null); } catch { /* 清不掉也不影响 */ }
|
|
183
|
+
this.log?.('info', `[fish-soul] 已确认:「${name}」的抖音 uid ${c.uid} = QQ ${c.qq}`);
|
|
184
|
+
return { ok: true, uid: String(c.uid), qq: String(c.qq) };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 主人要清空某条候选(错认了,或想重配)。 */
|
|
188
|
+
dismissDouyinUinCandidate(name) {
|
|
189
|
+
const key = `douyin.uinCandidate.${String(name ?? '').trim()}`;
|
|
190
|
+
try { setKv(this.db, key, null); return { ok: true }; } catch { return { ok: false }; }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 面板读:有哪些待确认的候选。 */
|
|
194
|
+
douyinUinCandidates() {
|
|
195
|
+
try {
|
|
196
|
+
return this.db.prepare("SELECT key, value FROM kv WHERE key LIKE 'douyin.uinCandidate.%' AND value IS NOT NULL AND value != 'null'")
|
|
197
|
+
.all()
|
|
198
|
+
.map((r) => ({ name: String(r.key).slice('douyin.uinCandidate.'.length), ...(JSON.parse(r.value) ?? {}) }))
|
|
199
|
+
.filter((x) => x.uid && x.qq);
|
|
200
|
+
} catch { return []; }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** 抖音真实 uid 绑定的 QQ 号(`douyin.uin.<uid>`);没绑过返回 ''。 */
|
|
204
|
+
douyinUinBinding(uid) {
|
|
205
|
+
const key = normUidKey(uid);
|
|
206
|
+
if (key === '') return '';
|
|
207
|
+
try {
|
|
208
|
+
const v = String(this.db.prepare('SELECT value FROM kv WHERE key = ?').get(key)?.value ?? '').replace(/"/g, '').trim();
|
|
209
|
+
return /^\d{5,12}$/.test(v) ? v : '';
|
|
210
|
+
} catch { return ''; }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 把「真实 uid → QQ 号」记进绑定表。
|
|
215
|
+
* 之后一切判断只看这张表:昵称改了不影响,冒充者 uid 不同也进不来。
|
|
216
|
+
*/
|
|
217
|
+
bindDouyinUin(uid, qq) {
|
|
218
|
+
const key = normUidKey(uid);
|
|
219
|
+
if (key === '' || !/^\d{5,12}$/.test(String(qq))) return;
|
|
220
|
+
try {
|
|
221
|
+
this.db.prepare('INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)').run(key, JSON.stringify(String(qq)));
|
|
222
|
+
} catch { /* 记不下来就这轮不并,下一轮再试 */ }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* 抖音通道 id(`douyin:<昵称>`)→ 这个会话**真实的对端 uid**(`douyin:<uid>`)。
|
|
227
|
+
* 来源是轮询路学出来的游标(`douyin.conv.<sha1(昵称)前16>` 的 identity)。
|
|
228
|
+
* **不能退回昵称** —— 那正是 PR #96 的冒充洞。
|
|
229
|
+
*/
|
|
230
|
+
douyinIdentityOfChannel(channelId) {
|
|
231
|
+
const [kind, name] = splitChannelId(channelId);
|
|
232
|
+
if (kind !== 'douyin' || !name) return '';
|
|
233
|
+
try {
|
|
234
|
+
const key = `douyin.conv.${createHash('sha1').update(String(name)).digest('hex').slice(0, 16)}`;
|
|
235
|
+
const row = this.db.prepare('SELECT value FROM kv WHERE key = ?').get(key);
|
|
236
|
+
if (!row?.value) return '';
|
|
237
|
+
const cur = JSON.parse(row.value);
|
|
238
|
+
// 只认 `douyin:<数字uid>`;游标里的 name 是昵称,不能用
|
|
239
|
+
return /^douyin:\d+$/.test(String(cur?.identity ?? '')) ? String(cur.identity) : '';
|
|
240
|
+
} catch { return ''; }
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* 主人的抖音身份键(`douyin:<uid>`)。
|
|
245
|
+
* 优先设置页填的 `masterUid`;没填就退回 person.master 学到的(平台数据比手填更可信)。
|
|
246
|
+
*/
|
|
247
|
+
masterDouyinIdentity() {
|
|
248
|
+
const cfg = this.douyinConfig();
|
|
249
|
+
const configured = String(cfg.masterUid ?? '').trim();
|
|
250
|
+
if (/^douyin:\d+$/.test(configured)) return configured;
|
|
251
|
+
try {
|
|
252
|
+
const row = this.db.prepare("SELECT douyin_uid FROM person WHERE canonical_id = 'master'").get();
|
|
253
|
+
const learned = String(row?.douyin_uid ?? '').trim();
|
|
254
|
+
if (/^douyin:\d+$/.test(learned)) return learned;
|
|
255
|
+
} catch { /* 读不到就当没填,走下面那句提示 */ }
|
|
256
|
+
return '';
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** 主人那个抖音会话的 ID(转达 / 主动私信要用)。没读过就是空,宁可发不出去也不按昵称猜。 */
|
|
260
|
+
async masterDouyinConvId() {
|
|
261
|
+
const id = this.masterDouyinIdentity();
|
|
262
|
+
if (id === '') return '';
|
|
263
|
+
try {
|
|
264
|
+
return String(getKv(this.db, `douyin.convId.${id}`, '') ?? '').trim();
|
|
265
|
+
} catch { return ''; }
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 按会话身份建/找人。`masterUid` 对上就是主人,否则是陌生人(不按昵称合并)。 */
|
|
269
|
+
resolveDouyinPerson(m, cfg) {
|
|
270
|
+
try {
|
|
271
|
+
// 顺手清一次「把几个名字拼一起」的脏身份:好几个人的往来会记在一个人头上。清掉并留痕。
|
|
272
|
+
for (const c of cleanupMergedDouyinNames(this.db)) {
|
|
273
|
+
this.log('info', `[fish-soul] 抖音:清掉一个「把几个名字拼一起」的脏身份「${c.douyinUid}」(连带 ${c.memories} 条小结)`);
|
|
274
|
+
}
|
|
275
|
+
return resolveOrCreatePlatformPerson(this.db, {
|
|
276
|
+
platform: 'douyin',
|
|
277
|
+
platformId: String(m.userId),
|
|
278
|
+
nickname: String(m.nickname ?? ''),
|
|
279
|
+
nowMs: Date.now(),
|
|
280
|
+
masterId: cfg.masterUid || ''
|
|
281
|
+
});
|
|
282
|
+
} catch (error) {
|
|
283
|
+
this.log('warn', `[fish-soul] 抖音认人失败(按陌生人处理):${String(error instanceof Error ? error.message : error)}`);
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 抖音会话标题(chatTitle 的抖音分支)。 */
|
|
289
|
+
title(chat) {
|
|
290
|
+
const name = chat.targetId;
|
|
291
|
+
if (chat.chatType === 'group') return `抖音群·${sanitizeName(name, '抖音群')}`;
|
|
292
|
+
return `抖音·${sanitizeName(name, '抖音用户')}`;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// ───────────── 平台机制(PR5) ─────────────
|
|
296
|
+
|
|
297
|
+
/** 文本里的抖音视频引用(作品 ID / 短链)。 */
|
|
298
|
+
refs(text) {
|
|
299
|
+
return findDouyinRefs(text);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ───────────── 发送与卡片分享(PR4) ─────────────
|
|
303
|
+
//
|
|
304
|
+
// 🔴 「ok」和「delivered」必须分开记:抖音风控会静默吞消息(Enter 按了、UI 没报错、
|
|
305
|
+
// 消息没进会话)。只报 ok 等于撒谎 —— 上层要能说清「动作做了」和「对方真能看见」。
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* 抖音分享卡片的目标会话。
|
|
309
|
+
*
|
|
310
|
+
* 三道闸,少一道都不给:
|
|
311
|
+
* ① `douyin.shareCard` 开关打开(默认关)
|
|
312
|
+
* ② 认得出主人的抖音身份(`douyin:<数字uid>`)
|
|
313
|
+
* ③ 这个身份确认过会话 ID(kv `douyin.convId.<身份>`)——
|
|
314
|
+
* 没有会话 ID 就不知道对面是谁,按昵称点名分享 = 可能发错人
|
|
315
|
+
*
|
|
316
|
+
* @returns {string|{channelId: string, uid: string, convId: string, name: string}}
|
|
317
|
+
* 空串 = 不能走抖音(退回 QQ 文字分享)
|
|
318
|
+
*/
|
|
319
|
+
shareTarget() {
|
|
320
|
+
const cfg = this.douyinConfig();
|
|
321
|
+
if (cfg.enabled !== true || cfg.shareCard !== true) return '';
|
|
322
|
+
const identity = this.masterDouyinIdentity();
|
|
323
|
+
if (identity === '') return '';
|
|
324
|
+
const uid = identity.replace(/^douyin:/, '');
|
|
325
|
+
let convId = '';
|
|
326
|
+
try {
|
|
327
|
+
convId = String(getKv(this.db, `douyin.convId.${identity}`, '') ?? '').trim();
|
|
328
|
+
} catch { return ''; }
|
|
329
|
+
if (!/^0:1:\d+:\d+$/.test(convId)) return '';
|
|
330
|
+
const name = String(cfg.masterName ?? '').trim();
|
|
331
|
+
if (name === '') return '';
|
|
332
|
+
return { channelId: `douyin:${name}`, uid, convId, name };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* 把一条「抖音视频分享」真正投出去:**原生卡片 + 一句说明**,两段各自落盘。
|
|
337
|
+
*
|
|
338
|
+
* 🔴 与普通主动开口的根本区别:这里**不经过模型**。
|
|
339
|
+
* 作品 ID 和感受在入队时就落盘了(`share.intent.<pendingId>`),
|
|
340
|
+
* 模型只负责「说什么」;它漏抄链接、或者回个「[不回]」,卡片该发还是要发。
|
|
341
|
+
*
|
|
342
|
+
* @param {string} channelId `douyin:<名字>`
|
|
343
|
+
* @param {string} reason 待办里的理由(人话描述,给人看的)
|
|
344
|
+
* @param {{pendingId?: number|string}} meta
|
|
345
|
+
* @returns {Promise<boolean>} 卡片和说明都确认了才算 true
|
|
346
|
+
*/
|
|
347
|
+
async deliverShare(channelId, reason, meta = {}) {
|
|
348
|
+
const target = this.shareTarget();
|
|
349
|
+
if (!target) {
|
|
350
|
+
this.note('failed', { channelId, reason: '抖音卡片分享没开或认不出主人会话,未分享' });
|
|
351
|
+
return false;
|
|
352
|
+
}
|
|
353
|
+
const intent = getKv(this.db, `share.intent.${meta.pendingId}`, null);
|
|
354
|
+
const videoId = String(intent?.videoId ?? '').trim();
|
|
355
|
+
if (!/^\d{8,20}$/.test(videoId)) {
|
|
356
|
+
this.note('failed', { channelId, reason: '这条分享没有可用的作品 ID,未分享' });
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
const caption = String(intent?.caption ?? '').trim();
|
|
360
|
+
const result = await deliverDouyinCards({
|
|
361
|
+
db: this.db,
|
|
362
|
+
// 交付标识要稳定:同一条待办重试时是同一个 ⇒ 状态认得出「上次发过没有」
|
|
363
|
+
deliveryId: `pending:${meta.pendingId}:${channelId}`,
|
|
364
|
+
videoIds: [videoId],
|
|
365
|
+
caption,
|
|
366
|
+
sendCard: (id, onSubmitted) => this.channel().shareCard({
|
|
367
|
+
videoId: id, peerUid: target.uid, convId: target.convId, friendName: target.name,
|
|
368
|
+
}, onSubmitted),
|
|
369
|
+
// 说明文字走**注入的发送函数**(网关的 sendDouyin):它可能被替换/打桩,
|
|
370
|
+
// 卡片交付这条路要跟着走同一条,不能自己另接一条。
|
|
371
|
+
sendText: (text) => this.sendText({ channel_id: channelId }, text, [], target.convId),
|
|
372
|
+
log: (stage, info) => this.log('info', `[fish-soul] ${stage} ${JSON.stringify(info)}`),
|
|
373
|
+
});
|
|
374
|
+
this.note(result.ok ? 'sent' : result.unknown ? 'unconfirmed' : 'failed', {
|
|
375
|
+
channelId, text: caption, reason: result.ok ? `视频卡片已回读确认:${videoId}` : (result.error ?? '未交付'),
|
|
376
|
+
});
|
|
377
|
+
// 提交了但没确认 ⇒ 可能已经发出去了。告诉待办层「别再自动重试」
|
|
378
|
+
//(和 meta.timedOut 一个套路):宁可留一条待人工核实,也不重复分享。
|
|
379
|
+
if (result.unknown === true) meta.deliveryUnknown = true;
|
|
380
|
+
return result.ok === true;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* 发不出去时给一句「照着做就能修好」的话。
|
|
385
|
+
*
|
|
386
|
+
* 三种原因必须分开说,否则用户会照着错的提示白折腾:
|
|
387
|
+
* ① 根本不知道主人是哪个抖音号 → 去设置页填身份(发消息没用)
|
|
388
|
+
* ② 知道身份但没聊过 → 让他先在抖音发一条(这时那句提示才是对的)
|
|
389
|
+
* @returns {Promise<string>} 空串 = 能发
|
|
390
|
+
*/
|
|
391
|
+
async sendBlocker() {
|
|
392
|
+
const id = this.masterDouyinIdentity();
|
|
393
|
+
if (id === '') {
|
|
394
|
+
return '还没认出你的抖音身份:去设置页「平台 → 抖音」把「主人身份」填成 douyin:<你的抖音数字uid>(只发消息不会自动认出来)';
|
|
395
|
+
}
|
|
396
|
+
const convId = String(await this.masterDouyinConvId() ?? '').trim();
|
|
397
|
+
if (convId === '') {
|
|
398
|
+
return '还认不出你抖音那个会话:先在抖音里给我发一条消息,我就能把会话身份记下来';
|
|
399
|
+
}
|
|
400
|
+
return '';
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* 抖音私信:文字按空行拆条;单独一段 [名字] 发成抖音自带表情;图片(≤2 张)跟在最后。
|
|
405
|
+
*
|
|
406
|
+
* @returns {Promise<{ok: boolean, delivered: boolean, parts: Array<object>}>}
|
|
407
|
+
* `ok` = 动作都做了;`delivered` = 至少一条回读到证据。
|
|
408
|
+
* 🔴 两者要分开报:抖音风控静默吞消息时 `ok` 仍然是 true,
|
|
409
|
+
* 但对方根本收不到 —— 只报 ok 等于撒谎。
|
|
410
|
+
*/
|
|
411
|
+
async send(row, text, images = [], convId = '') {
|
|
412
|
+
const channel = this.channel();
|
|
413
|
+
if (channel === null || channel === undefined || typeof channel.send !== 'function') {
|
|
414
|
+
return { ok: false, delivered: false, parts: [], error: '抖音通道没接上' };
|
|
415
|
+
}
|
|
416
|
+
// 🔴 没有目标会话 ID 就不发:昵称只能用来「找到会话」,证明不了「打开的就是这个人」。
|
|
417
|
+
// 通道层还会再挡一道(DouyinChannel.send),这里是给上层一个明确原因。
|
|
418
|
+
const target = String(convId ?? '').trim();
|
|
419
|
+
if (!/^0:1:\d+:\d+$/.test(target)) {
|
|
420
|
+
return { ok: false, delivered: false, parts: [], error: '没有确认过这个抖音会话的身份(缺会话 ID),不发,以免发错人' };
|
|
421
|
+
}
|
|
422
|
+
// 会话名只用来找会话:channel_id 是 `douyin:<名字>`,名字从 row 上取。
|
|
423
|
+
const name = String(row?.channel_id ?? '').replace(/^douyin:/, '');
|
|
424
|
+
if (name === '') return { ok: false, delivered: false, parts: [], error: '不知道要发给哪个会话' };
|
|
425
|
+
|
|
426
|
+
const parts = [];
|
|
427
|
+
for (const para of String(text ?? '').split(/\n{2,}/).map((x) => x.trim()).filter((x) => x !== '')) {
|
|
428
|
+
// 单独一段 [名字] → 抖音自带表情
|
|
429
|
+
const m = /^\[([^\]\n]{1,12})\]$/.exec(para);
|
|
430
|
+
if (m !== null) { parts.push({ type: 'emoji', name: m[1] }); continue; }
|
|
431
|
+
parts.push({ type: 'text', text: para });
|
|
432
|
+
}
|
|
433
|
+
for (const img of images.slice(0, 2)) {
|
|
434
|
+
const file = String(img?.data?.file ?? img?.path ?? '');
|
|
435
|
+
if (file !== '') parts.push({ type: 'image', path: file });
|
|
436
|
+
}
|
|
437
|
+
if (parts.length === 0) return { ok: false, delivered: false, parts: [], error: '没有可发的内容' };
|
|
438
|
+
const r = await channel.send(name, parts, target);
|
|
439
|
+
return { ok: r?.ok === true, delivered: r?.delivered === true, parts: r?.parts ?? [], error: r?.ok === true ? '' : (r?.error ?? '发送失败') };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// ───────────── 路由信息(PR3) ─────────────
|
|
443
|
+
//
|
|
444
|
+
// 🔴 字段名与位置**不能动**:`convId` / `inboxIds` 写在宿主保存的消息 `source` 顶层,
|
|
445
|
+
// 插件重启后宿主会重放旧格式的消息。适配器读写同样的字段。
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* 这一批消息要带哪些路由信息(写进 followup 的 source)。
|
|
449
|
+
*
|
|
450
|
+
* @param {Array<{m: object}>} items 这一轮收到的消息
|
|
451
|
+
* @param {string} platform 这一轮来自哪个平台(`douyin` 之外的平台不写 convId)
|
|
452
|
+
* **没有默认值**:漏传 platform 时宁可不写 convId,也不能给 QQ 批写上抖音会话 ID。
|
|
453
|
+
* @returns {{convId?: string, inboxIds?: string[]}} 字段名与现在 source 里一致
|
|
454
|
+
*/
|
|
455
|
+
routeOf(items, platform) {
|
|
456
|
+
const inboxIds = (items ?? []).map((x) => x?.m?.inboxId).filter(Boolean);
|
|
457
|
+
const last = (items ?? [])[(items ?? []).length - 1]?.m;
|
|
458
|
+
const convId = platform === 'douyin' && last?.convId ? String(last.convId) : '';
|
|
459
|
+
return {
|
|
460
|
+
...(inboxIds.length ? { inboxIds } : {}),
|
|
461
|
+
...(convId !== '' ? { convId } : {})
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* 把 source 里的路由信息吸收进这一轮的 state。
|
|
467
|
+
*
|
|
468
|
+
* @param {object} st 这一轮的 turn state
|
|
469
|
+
* @param {object} source 宿主重放的消息 source
|
|
470
|
+
*/
|
|
471
|
+
absorbRoute(st, source) {
|
|
472
|
+
if (Array.isArray(source?.inboxIds)) {
|
|
473
|
+
st.inboxIds = [...new Set([...(st.inboxIds ?? []), ...source.inboxIds])];
|
|
474
|
+
}
|
|
475
|
+
if (source?.convId) st.convId = String(source.convId);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* 结算这轮处理过的私信(成功 / 不确定)。
|
|
480
|
+
*
|
|
481
|
+
* @param {string[]} ids 收件箱记录 id
|
|
482
|
+
* @param {boolean} ok 这一轮是否正常完成
|
|
483
|
+
* @param {string} why 不确定时的原因
|
|
484
|
+
*/
|
|
485
|
+
settle(ids, ok, why = '') {
|
|
486
|
+
const inbox = typeof this.inbox === 'function' ? this.inbox() : this.inbox;
|
|
487
|
+
if (inbox === null || inbox === undefined || typeof inbox.settle !== 'function') return;
|
|
488
|
+
inbox.settle(ids, ok, why);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* 文本里的抖音作品 ID 列表(分享原生卡片要知道作品 ID)。
|
|
494
|
+
*
|
|
495
|
+
* 导出成独立函数:life.js 的 LifeEngine 在网关之前构造,
|
|
496
|
+
* 让它经适配器实例拿作品 ID 会把「能不能分享」绑在实例时序上。
|
|
497
|
+
*/
|
|
498
|
+
export function douyinVideoIdsOf(text) {
|
|
499
|
+
return douyinVideoIds(text);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* 拿 this 上的抖音适配器;没有就临时造一个挂上去。
|
|
504
|
+
*
|
|
505
|
+
* 为什么:老测试(douyin-master-uid.mjs 等)用 `Object.create(mediaMethods)` 手搓 this,
|
|
506
|
+
* 没有 douyinAdapter 属性。mediaMethods 上的同名转发函数通过这里拿适配器,
|
|
507
|
+
* 老测试就一行都不用改。
|
|
508
|
+
*/
|
|
509
|
+
export function adapterOf(self) {
|
|
510
|
+
if (self.douyinAdapter instanceof DouyinAdapter) return self.douyinAdapter;
|
|
511
|
+
// 手搓 this(老测试)经常**自己塞一个 douyinConfig**(有的是 own property),
|
|
512
|
+
// 而不是完整的 getConfig —— 那种情况下它才是这段测试的配置源,
|
|
513
|
+
// 用 getConfig 反而会读到空配置。判据:douyinConfig 是不是 own property。
|
|
514
|
+
const hasOwnConfig = Object.hasOwn(self, 'douyinConfig');
|
|
515
|
+
const getConfig = hasOwnConfig
|
|
516
|
+
? () => ({ douyin: self.douyinConfig(), masterQqUin: self.masterQqUin ?? self.getConfig?.()?.masterQqUin ?? '' })
|
|
517
|
+
: (typeof self.getConfig === 'function' ? self.getConfig : () => ({}));
|
|
518
|
+
self.douyinAdapter = new DouyinAdapter({
|
|
519
|
+
// 传函数而不是快照:`gw.db = 新库` 的用法要跟着换
|
|
520
|
+
db: () => self.db,
|
|
521
|
+
getConfig,
|
|
522
|
+
// 抖音收件箱:结算私信用。手搓 this 上没有 douyin 时就是 null。
|
|
523
|
+
inbox: () => self.douyin?.inbox ?? null,
|
|
524
|
+
// 抖音通道:发送 / 分享卡片用。
|
|
525
|
+
channel: () => self.douyin ?? null,
|
|
526
|
+
// 说明文字走 this 上的 sendDouyin(可能被替换 / 打桩)
|
|
527
|
+
sendText: (row, text, images, convId) => (typeof self.sendDouyin === 'function'
|
|
528
|
+
? self.sendDouyin(row, text, images, convId)
|
|
529
|
+
: Promise.resolve({ ok: false, delivered: false, parts: [], error: '没接上发送通道' })),
|
|
530
|
+
note: self.note ? (...a) => self.note(...a) : () => {},
|
|
531
|
+
log: self.log ? (...a) => self.log(...a) : () => {},
|
|
532
|
+
diag: self.diag ? (...a) => self.diag(...a) : () => {}
|
|
533
|
+
});
|
|
534
|
+
return self.douyinAdapter;
|
|
535
|
+
}
|