dsh-fish-soul 0.19.15 → 0.19.16

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.15**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.19.16**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
@@ -80,7 +80,7 @@ export async function consumePushFrames(ctx) {
80
80
  const mineMsg = messages.find((m) => selfIds.includes(String(m?.senderId ?? '').trim()) && m?.secUid);
81
81
  if (mineMsg) {
82
82
  ctx.selfSecUid = mineMsg.secUid;
83
- try { setKv(ctx.db, 'douyin.selfSecUid', mineMsg.secUid); } catch {}
83
+ try { setKv(ctx.db, 'douyin.selfSecUid', mineMsg.secUid); } catch { /* 落盘失败不影响本轮:下次从消息里还能学到 */ }
84
84
  }
85
85
  }
86
86
  const tagged = ctx.selfSecUid
@@ -21,6 +21,7 @@ import {
21
21
  import { join } from 'node:path';
22
22
  import { getKv, setKv } from '../db.js';
23
23
  import { checkLogin, dmList, readDM, sendDM, sendEmoji, sendImage, drainPushFrames } from './vendor/douyin-bridge/douyin-dm.mjs';
24
+ import { ensurePanel } from './vendor/douyin-bridge/douyin-panel.mjs';
24
25
  import { knownEmojiNames } from './vendor/douyin-bridge/media.mjs';
25
26
  import { canary } from './vendor/douyin-bridge/selectors.mjs';
26
27
  import { shareVideoToFriend } from './vendor/douyin-bridge/douyin-share.mjs';
@@ -217,6 +218,9 @@ function pageDriver(host) {
217
218
  // 已知的表情名(给提示词用)。被动攒的:只有读完私信发现有不认识的表情才会去抓面板,
218
219
  // 所以刚起来时可能是空的 —— 调用方按空处理
219
220
  emojiNames: (limit) => knownEmojiNames(limit),
221
+ // 自检前先把私信面板打开 —— conversationItem 只在面板开着时才渲染,
222
+ // 页面停在推荐首页时它必然是 0(ensurePanel 幂等:已开着直接返回)。
223
+ ensurePanel: () => ensurePanel(b()),
220
224
  canary: () => canary(b())
221
225
  };
222
226
  }
@@ -1127,6 +1131,12 @@ export class DouyinChannel {
1127
1131
 
1128
1132
  /** 跑一次页面自检(不含自救)。 */
1129
1133
  async canaryOnce() {
1134
+ // 🔴 先开面板再自检。canary 把 conversationItem 当关键项(「无论在什么页面都该存在」),
1135
+ // 但它其实只在私信面板开着时才渲染 —— 页面停在推荐首页时必然是 0 个。
1136
+ // 手动自检(selfCheck)本来就走 driver.list() 先开面板,所以一直是过的;
1137
+ // 自动轮询这条路径没开 ⇒ 误报「改版」⇒ replyPaused=true 误停自动回复。
1138
+ // ensurePanel 幂等,面板已开着时直接返回,不多点。
1139
+ try { await this.driver.ensurePanel?.(); } catch { /* 开不开得了都继续自检,自检自己会报 broken */ }
1130
1140
  try { return await this.driver.canary(); } catch (error) { return { ok: false, broken: ['canary'], error: errText(error) }; }
1131
1141
  }
1132
1142
 
@@ -11,7 +11,7 @@ export class ChatArchive {
11
11
  open(create=false){if(this.db)return this.db;const path=join(fishSoulDir(),'chat-archive.db');if(!create&&!existsSync(path))return null;mkdirSync(fishSoulDir(),{recursive:true,mode:0o700});if(!existsSync(path)){try {closeSync(openSync(path,'wx',0o600));}catch(e){if(e.code!=='EEXIST')throw e;}}chmodSync(path,0o600);const db=new DatabaseSync(path);db.exec('PRAGMA journal_mode=WAL; PRAGMA secure_delete=ON; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS chat_text(id INTEGER PRIMARY KEY, channel_id TEXT NOT NULL, who TEXT NOT NULL, self INTEGER NOT NULL, content TEXT NOT NULL, at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS chat_text_channel_at ON chat_text(channel_id,at DESC); CREATE INDEX IF NOT EXISTS chat_text_at ON chat_text(at);');ensureFts(db);this.db=db;return db;}
12
12
  add(channel,line){const cfg=this.config();if(!cfg.enabled)return;
13
13
  // channels 留空 = 全记(默认);填了才按白名单过滤
14
- if(cfg.channels.length>0&&!cfg.channels.includes(channel))return;try {const text=String(line?.text??'').trim();if(!text)return;if(Buffer.byteLength(text,'utf8')>2*1024*1024)throw new Error('文本过长');const db=this.open(true);db.exec('BEGIN');try {const res=db.prepare('INSERT INTO chat_text(channel_id,who,self,content,at) VALUES(?,?,?,?,?)').run(channel,String(line.who??''),line.self===true?1:0,text,Date.now());indexRow(db,Number(res.lastInsertRowid),text);db.exec('COMMIT');}catch(e){try{db.exec('ROLLBACK');}catch{}throw e;}this.error='';}catch {this.failures++;this.error='聊天存档写入失败';this.log('warn','[fish-soul] 聊天存档写入失败,聊天继续');}}
14
+ if(cfg.channels.length>0&&!cfg.channels.includes(channel))return;try {const text=String(line?.text??'').trim();if(!text)return;if(Buffer.byteLength(text,'utf8')>2*1024*1024)throw new Error('文本过长');const db=this.open(true);db.exec('BEGIN');try {const res=db.prepare('INSERT INTO chat_text(channel_id,who,self,content,at) VALUES(?,?,?,?,?)').run(channel,String(line.who??''),line.self===true?1:0,text,Date.now());indexRow(db,Number(res.lastInsertRowid),text);db.exec('COMMIT');}catch(e){try{db.exec('ROLLBACK');}catch{/* 回滚失败也无所谓:原异常 e 会继续抛,调用方看得到真正的失败原因 */}throw e;}this.error='';}catch {this.failures++;this.error='聊天存档写入失败';this.log('warn','[fish-soul] 聊天存档写入失败,聊天继续');}}
15
15
  prune(){try{const db=this.open();if(!db)return;const res=db.prepare('DELETE FROM chat_text WHERE at < ?').run(Date.now()-this.config().days*DAY);if(Number(res?.changes??0)>0)db.exec('PRAGMA wal_checkpoint(TRUNCATE)');}catch{this.error='聊天存档清理失败';}}
16
16
  state(){let count=0, stored=[];try{const db=this.open();count=Number(db?.prepare('SELECT COUNT(*) n FROM chat_text').get()?.n??0);stored=db?db.prepare('SELECT channel_id AS channel, COUNT(*) AS count FROM chat_text GROUP BY channel_id ORDER BY max(at) DESC LIMIT 100').all():[];}catch{this.error='聊天存档读取失败';}return {ok:true,...this.config(),count,stored,error:this.error,failures:this.failures};}
17
17
  list(channel,before=Number.MAX_SAFE_INTEGER){try {const db=this.open();const items=db?db.prepare('SELECT id,channel_id AS channel,who,self,content,at FROM chat_text WHERE channel_id=? AND id<? ORDER BY id DESC LIMIT 50').all(channel,before):[];return {ok:true,items,next:items.length===50?items[items.length-1].id:null};}catch{return {ok:false,error:'读取聊天存档失败'};}}
@@ -71,5 +71,5 @@ export class ChatArchive {
71
71
  }
72
72
  remove(channel){try{const db=this.open();const changed=db?Number(db.prepare('DELETE FROM chat_text WHERE channel_id=?').run(channel).changes):0;db?.exec('PRAGMA wal_checkpoint(TRUNCATE)');return {ok:true,changed};}catch{return {ok:false,error:'清理聊天存档失败'};}}
73
73
  start(){this.prune();this.timer=setInterval(()=>this.prune(),3600000);this.timer.unref?.();}
74
- stop(){clearInterval(this.timer);try{this.db?.close();}catch{}this.db=null;}
74
+ stop(){clearInterval(this.timer);try{this.db?.close();}catch{/* 已经关了 / 句柄失效:stop 是收尾路径,抛出去只会掩盖调用方的真正意图 */}this.db=null;}
75
75
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * 抖音作品「标题 / 描述」的文本切分。
3
+ *
4
+ * 编辑页的标题和描述是两个独立的框(2026-11-30 真机核对:
5
+ * 标题 placeholder「添加作品标题」,标题计数 4/20;
6
+ * 描述 placeholder「添加作品描述...」,计数 0/1000)。
7
+ *
8
+ * 以前标题取正文第一句、描述又原样填全文 ⇒ 页面上「标题 + 描述」连读会把第一句念两遍。
9
+ * 真机作品标题就长这样:
10
+ * post_id 回填验证,发完就删。post_id 回填验证,发完就删
11
+ * 更早那条也是:
12
+ * 下班顺路买吃的,在冰柜里纠结了五分钟。下班顺路买吃的,在冰柜里纠结了五分钟。 *最后拎了瓶酸奶走。
13
+ *
14
+ * 所以描述只写「标题没占用的那部分」。
15
+ */
16
+
17
+ /** 标题:正文第一句,最多 20 字(抖音图文标题上限 20)。 */
18
+ export function noteTitle(text) {
19
+ const first = String(text ?? '').split(/[。!?!?\n]/).map((s) => s.trim()).find(Boolean) ?? '';
20
+ return first.slice(0, 20);
21
+ }
22
+
23
+ /**
24
+ * 描述:正文里去掉标题已经占用的那段,并削掉紧跟的标点。
25
+ *
26
+ * 只削「与标题逐字重合的前缀」,所以不会丢字 —— 标题可能被截到 20 字,
27
+ * 截断后剩下的半句仍然留在描述里。
28
+ * 正文恰好只有标题那一句时返回空串:真机验过「只填标题、描述空着」时
29
+ * 「发布」按钮 `disabled: false`,可以发(2026-11-30 上传页探针,未点发布)。
30
+ *
31
+ * @param {string} text 正文全文
32
+ * @param {string} title 实际填进标题框的文本(空 = 没填标题,此时原样返回全文)
33
+ */
34
+ export function noteBody(text, title) {
35
+ const full = String(text ?? '');
36
+ const head = String(title ?? '');
37
+ if (!head) return full;
38
+ const rest = full.replace(/^\s+/, '');
39
+ if (!rest.startsWith(head)) return full;
40
+ return rest.slice(head.length).replace(/^[。!?!?,,、;;::\s]+/, '').trim();
41
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * douyin-social-dom.js —— 抖音网页的**页面注入脚本**与选择器(纯常量,零业务依赖)。
3
+ *
4
+ * 为什么单独成文件(2026-11-30):
5
+ * `lib/douyin-social.js` 有 1760 行,超过 `test/file-size-budget.json` 的 1500 行预算
6
+ * (已登记为待拆的存量债)。这个文件里前半部分全是「注入到页面里跑的 JS 字符串」,
7
+ * 与业务逻辑零耦合 —— 抽出来是这次拆分里风险最小的一刀。
8
+ *
9
+ * 拆法照 `douyin-fastpath.js` 的先例:`douyin-social.js` 保留同名 re-export,
10
+ * 既有 import 方(含测试)一行都不用改。
11
+ *
12
+ * ⚠️ 改这些字符串里的转义要格外小心:它们是**两层**转义的(模板字符串 → 页面 JS),
13
+ * 比如 `\\d` 在页面里是 `\d`。改完必须真机跑一次,纯单测抓不到。
14
+ */
15
+
16
+ export const SEL = {
17
+ input: '.comment-input-inner-container',
18
+ item: '[data-e2e="comment-item"]',
19
+ stats: '.comment-item-stats-container',
20
+ right: '.commentInput-right-ct',
21
+ editor: '.public-DraftEditor-content[contenteditable="true"]',
22
+ commentBtn: '[data-e2e="feed-comment-icon"]'
23
+ };
24
+
25
+ export const VERIFY_JS = String.raw`(() => {
26
+ const t = document.body ? document.body.innerText : '';
27
+ const sms = /接收短信验证码|获取验证码|请输入验证码/.test(t);
28
+ const captcha = /滑块验证|安全验证|请完成验证|拖动滑块/.test(t);
29
+ // 滑块常挂在独立 iframe(rc-verifycenter)里,body 文本一个字都不露(2026-11-15 真机踩过)
30
+ const frame = [...document.querySelectorAll('iframe')].some((f) => /rc-verifycenter|verifycenter|captcha/i.test(String(f.src || '')));
31
+ return sms || captcha || frame ? (sms ? 'sms' : 'captcha') : '';
32
+ })()`;
33
+
34
+ /**
35
+ * 视频转码好没 —— 判据是 video 元素能播(有时长)且源在抖音自己的 CDN 上。
36
+ *
37
+ * ⚠️ 不能拿「上传中」文字消失当判据:实测那行字 180 秒都不消,可视频早转好了(2026-11-20 真机)。
38
+ */
39
+ export const VIDEO_READY_JS = `(() => {
40
+ const videos = [...document.querySelectorAll('video')];
41
+ if (!videos.length) return { ok: false, duration: 0, src: '' };
42
+ const cdnRe = /(?:video-cn\\.douyin\\.com|douyinvod\\.com|douyinpic\\.com|bytevcloudcdn\\.com|ixigua\\.com)/i;
43
+ for (const v of videos) {
44
+ const raw = Number(v.duration);
45
+ const duration = Number.isFinite(raw) ? raw : 0;
46
+ const src = String(v.currentSrc || v.src || '');
47
+ if (duration > 0 && cdnRe.test(src)) return { ok: true, duration, src };
48
+ }
49
+ const v0 = videos[0];
50
+ const raw = Number(v0.duration);
51
+ return { ok: false, duration: Number.isFinite(raw) ? raw : 0, src: String(v0.currentSrc || v0.src || '') };
52
+ })()`;
53
+
54
+ /** 「我的」页的作品列表(新的在前)。 */
55
+ export const WORKS_JS = String.raw`(() => {
56
+ const out = [];
57
+ const scope = document.querySelector('[data-e2e="user-post-list"]') || document;
58
+ for (const a of scope.querySelectorAll('a[href*="/video/"], a[href*="/note/"]')) {
59
+ const m = String(a.getAttribute('href')).match(/\/(video|note)\/(\d{8,})/);
60
+ if (!m || out.some((x) => x.id === m[2])) continue;
61
+ const li = a.closest('li') || a;
62
+ if (/置顶/.test(li.innerText || '') && out.length > 0) continue;
63
+ out.push({ id: m[2], kind: m[1], title: (a.innerText || li.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 60) });
64
+ }
65
+ return out;
66
+ })()`;
67
+
68
+ /** 评论区状态。box 必须是「可见」的(有布局尺寸)——note 页评论区默认折叠,
69
+ * 容器在 DOM 里但 display:none,只判存在会把折叠态误判成「已打开」,
70
+ * 于是 openWork 不点图标就返回 ok,后面 reply() 必然 NO_BOX(2026-11-06 实测)。 */
71
+ export const COMMENT_STATE_JS = `(() => {
72
+ const box = document.querySelector('${SEL.input}');
73
+ const r = box ? box.getBoundingClientRect() : null;
74
+ return {
75
+ box: Boolean(r && r.width > 0 && r.height > 0),
76
+ inDom: Boolean(box),
77
+ items: document.querySelectorAll('${SEL.item}').length,
78
+ btn: Boolean(document.querySelector('${SEL.commentBtn}')),
79
+ url: location.href
80
+ };
81
+ })()`;
82
+
83
+ /** 编辑页上的「选择音乐 / 添加音乐」入口(页面有多个同名节点,取最后一个——真正可点的那颗;优先取其按钮容器并避免在视口内时不必要的滚动)。 */
84
+ export const MUSIC_ENTRY_JS = String.raw`(() => {
85
+ const els = [...document.querySelectorAll('div, span, button')].filter((x) => x.children.length === 0 && /^(选择音乐|添加音乐)$/.test((x.innerText || '').trim()));
86
+ const el = els[els.length - 1];
87
+ if (!el) return null;
88
+ const target = el.closest('[class*="preview-button"], button') || el;
89
+ let r = target.getBoundingClientRect();
90
+ if (r.top < 0 || r.bottom > window.innerHeight || r.left < 0 || r.right > window.innerWidth) {
91
+ target.scrollIntoView({ block: 'center', behavior: 'instant' });
92
+ r = target.getBoundingClientRect();
93
+ }
94
+ return r.width && r.height ? { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) } : null;
95
+ })()`;
96
+
97
+ /** 只在可见音乐抽屉中读取歌卡;避免抓到预览区或其他面板里的文字。 */
98
+ export const MUSIC_DOM_JS = String.raw`
99
+ const visible = (el) => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; };
100
+ const panel = [...document.querySelectorAll('.semi-sidesheet-content, [class*="music-collection-container"]')].find(el => visible(el) && (el.matches('[class*="music-collection-container"]') || el.querySelector('input[placeholder*="搜索"], [class*="music-collection-container"]')));
101
+ // 一行 = 一个**外层歌卡**(不是内层左半,也不是右半的计数行)。
102
+ // 真机结构:外层卡 → {内层左半(歌名), 右半(N万人使用 + 使用按钮)}。
103
+ // 旧选择器把三层都当一行 ⇒ 20 首歌读成 60 行,两个后果:
104
+ // ① 同一首歌被读两次(外层卡 + 内层左半都有 song-name)⇒ counts 恒为 2;
105
+ // ② 右半没有 song-name ⇒ 回退读 innerText 首行 ⇒ 读出「N万人使用」,不是歌名。
106
+ // 60 行还会被 MUSIC_ROWS_JS 的 slice(0,20) 截断 ⇒ 模型只看到 7 首歌 + 1 个计数行
107
+ // (20 首里 13 首根本不可见)。
108
+ const cardOf = (el) => {
109
+ // 找**最外层**歌卡:真机结构是 外层卡 → {内层左半(歌名), 右半(计数 + 使用按钮)},
110
+ // 歌名和按钮分居两半,只有外层卡同时装着两者。
111
+ // (从 song-name 往上第一个命中的是内层左半 —— 那里没有按钮。)
112
+ // 只认「恰好含一个歌名」的层:抖音若在歌卡之上再加一层列表包裹层,
113
+ // 那一层也带 card-container 类名,会把所有歌塌成一行。
114
+ const songSel = '[class*="song-name"]';
115
+ let found = null;
116
+ for (let p = el; p && p !== panel; p = p.parentElement) {
117
+ if (p.matches('[class*="card-container"], [class*="music-item"], [class*="song-item"], [class*="MusicItem"]')
118
+ && p.querySelectorAll(songSel).length === 1) found = p;
119
+ }
120
+ return found || el;
121
+ };
122
+ const songNameEls = panel ? [...panel.querySelectorAll('[class*="song-name"]')].filter(visible) : [];
123
+ const rows = [...new Set(songNameEls.map(cardOf))].filter(visible);
124
+ const nameOf = (row) => ((row.querySelector('[class*="song-name"]')?.innerText || (row.innerText || '').split('\n')[0]) || '').trim();
125
+ `;
126
+ export const MUSIC_OPEN_JS = `(() => { ${MUSIC_DOM_JS} return Boolean(panel); })()`;
127
+ export const MUSIC_ROWS_JS = `(() => { ${MUSIC_DOM_JS}
128
+ return rows.map(nameOf).map(s => String(s || '').trim()).filter(Boolean).slice(0, 20);
129
+ })()`;
130
+ export const MUSIC_TAB_JS = `(() => { ${MUSIC_DOM_JS}
131
+ if (!panel) return false;
132
+ const tab = [...panel.querySelectorAll('div, span, button')].find(x => x.children.length === 0 && (x.innerText || '').trim() === '推荐' && visible(x));
133
+ if (tab) tab.click();
134
+ return Boolean(tab);
135
+ })()`;
136
+
137
+ /** 评论区里的一级评论:作者 / 内容 / 是不是作者本人 / 能不能回。
138
+ * 真实结构(2026-11-06 连真浏览器 dump 出来的):
139
+ * div[data-e2e=comment-item]
140
+ * a[href*="/user/"] ← 昵称
141
+ * .comment-item-info-wrap ← 作者信息块(里面有 [data-e2e=video-comment-more] 的「...」按钮)
142
+ * .comment-item-info-wrap + 1(兄弟节点) ← 评论正文
143
+ * .VAQA49VP ← 「3天前·浙江」
144
+ * .comment-item-stats-container ← 「0 分享 回复」
145
+ * 两条教训:① 整个 item 的 innerText 常常是**单行无换行**的,拆行取 rest[1] 取不到正文;
146
+ * ② [data-e2e=video-comment-more] 的文本就是「...」,换行布局时它会独占一行被当成正文 →
147
+ * 19/20 条评论被读成「...」。所以正文改取「作者信息块的下一个兄弟节点」,拆行只做兜底。 */
148
+ export const LIST_COMMENTS_JS = `(() => [...document.querySelectorAll('${SEL.item}')].map((el, i) => {
149
+ const lines = (el.innerText || '').split('\\n').map((s) => s.trim()).filter(Boolean);
150
+ const stats = el.querySelector('${SEL.stats}');
151
+ const canReply = Boolean(stats && [...stats.querySelectorAll('*')].some((x) => (x.innerText || '').trim() === '回复'));
152
+ const infoWrap = el.querySelector('.comment-item-info-wrap')
153
+ || (el.querySelector('[data-e2e="video-comment-more"]') || {}).parentElement
154
+ || null;
155
+ const nameLink = el.querySelector('a[href*="/user/"]');
156
+ let author = nameLink ? (nameLink.innerText || '').trim() : '';
157
+ // 正文 = 作者信息块的下一个兄弟节点(独立节点,不含「更多」按钮,也不含「展开」按钮)
158
+ let content = infoWrap && infoWrap.nextElementSibling ? (infoWrap.nextElementSibling.innerText || '').trim() : '';
159
+ const NOISE = (s) => s === '' || s === '...' || s === '···' || s === '…' || s === '作者' || s === '置顶' || s === '作者赞过';
160
+ if (NOISE(content)) content = '';
161
+ if (!content) {
162
+ // 兜底:叶子节点里挑一段既不是作者名、也不是时间 / 按钮 / 纯数字的文本
163
+ const cand = [...el.querySelectorAll('span, div, p')].filter((x) => x.children.length === 0)
164
+ .map((x) => (x.innerText || '').trim())
165
+ .filter((s) => !NOISE(s) && s !== author
166
+ && !/^展开/.test(s) && !/^收起/.test(s)
167
+ && !/^\\d+$/.test(s)
168
+ && !/^(分享|回复|点赞|收藏|举报|关注)$/.test(s)
169
+ && !/\\d+\\s*(天|小时|分钟|秒|周|月|年)前/.test(s)
170
+ && !/·\\S+$/.test(s));
171
+ content = cand[0] || '';
172
+ }
173
+ if (!author) author = (lines[0] || '').slice(0, 40);
174
+ // 「作者」标记是 0 层叶子节点里文本恰为「作者」的那颗(不靠行号、不靠位置)
175
+ const isAuthor = [...el.querySelectorAll('span, div, p')].some((x) => x.children.length === 0 && (x.innerText || '').trim() === '作者');
176
+ return { i, author: author.slice(0, 40), content: content.slice(0, 300), isAuthor, canReply };
177
+ }))()`;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * douyin-social-music.js —— 抖音「给作品配乐」的页面交互(从 douyin-social.js 抽出)。
3
+ *
4
+ * 为什么单独成文件(2026-11-30):
5
+ * `lib/douyin-social.js` 1760 行超过 1500 行预算(test/file-size-budget.json 里
6
+ * 登记为待拆的存量债)。上一刀抽走了页面注入脚本(douyin-social-dom.js),
7
+ * 这一刀抽走配乐交互 —— 它只跟「打开抽屉 / 读歌卡 / 点使用 / 关抽屉」有关。
8
+ *
9
+ * 拆法照 `douyin-fastpath.js` 的先例:**注入依赖**(工具函数由调用方传进来),
10
+ * `douyin-social.js` 保留同名薄转发 —— 既有的打桩点一个都不用改。
11
+ *
12
+ * ⚠️ 这些函数里的 JS 字符串是**两层转义**的(模板字符串 → 页面代码),
13
+ * 搬动时不要改动字符串内容;改完必须真机跑一次。
14
+ */
15
+
16
+ import { sleep } from './time-util.js';
17
+ import { MUSIC_ENTRY_JS, MUSIC_OPEN_JS, MUSIC_ROWS_JS, MUSIC_TAB_JS, MUSIC_DOM_JS } from './douyin-social-dom.js';
18
+
19
+ export async function clickMusicEntry(inject, br, timing) {
20
+
21
+ const { waitFor, realClick, findApplyButton, pointBelongsToCard, ensurePageAlive, PAGE_TIMING, VIDEO_LOCK_MARGIN_MS } = inject;
22
+ const sel = await br.eval(MUSIC_ENTRY_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => null);
23
+ if (!sel) return false;
24
+ await br.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: sel.x, y: sel.y }, br.sessionId).catch(() => {});
25
+ await sleep(150);
26
+ await realClick(br, sel.x, sel.y);
27
+ await sleep(1200);
28
+ return true;
29
+ }
30
+
31
+ /** 打开音乐面板,返回面板开了没。 */
32
+ export async function openMusicPanel(inject, br, timing) {
33
+
34
+ const { waitFor, realClick, findApplyButton, pointBelongsToCard, ensurePageAlive, PAGE_TIMING, VIDEO_LOCK_MARGIN_MS } = inject;
35
+ if (!await clickMusicEntry(inject, br, timing)) return false;
36
+ const opened = await waitFor(() => br.eval(MUSIC_OPEN_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => false), { tries: 6, gapMs: 800, budgetMs: timing.waitBudgetMs });
37
+ return opened === true;
38
+ }
39
+
40
+ /** 打开推荐列表并保持抽屉打开,模型选完后直接点击同一张卡片。 */
41
+ export async function grabRecommendedMusic(inject, br, timing) {
42
+
43
+ const { waitFor, realClick, findApplyButton, pointBelongsToCard, ensurePageAlive, PAGE_TIMING, VIDEO_LOCK_MARGIN_MS } = inject;
44
+ // 页面卡死时 eval 永远 pending,waitFor 会空等十几秒再报「没找到面板」(2026-11-15 真机)。
45
+ // 先探活,死了就 reload 一次;还死就直接报原因,不在死页面上盲点。
46
+ if (!await ensurePageAlive(br)) return { ok: false, error: '页面没响应(已尝试刷新一次),没找到或打开音乐面板' };
47
+ if (!await openMusicPanel(inject, br, timing)) return { ok: false, error: '没找到或打开音乐面板' };
48
+ await br.eval(MUSIC_TAB_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => false);
49
+ const songs = await waitFor(async () => {
50
+ const list = await br.eval(MUSIC_ROWS_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => []);
51
+ return Array.isArray(list) && list.length ? list : null;
52
+ }, { tries: 12, gapMs: 800, budgetMs: timing.waitBudgetMs });
53
+ if (!songs) return { ok: false, error: '音乐面板没有加载出推荐歌曲' };
54
+ const counts = {};
55
+ for (const name of songs) counts[name] = (counts[name] ?? 0) + 1;
56
+ return { ok: true, songs: [...new Set(songs)].slice(0, 10), counts };
57
+ }
58
+
59
+ /** 关掉音乐面板,避免失败后影响下一次操作。 */
60
+ export async function shutMusicPanel(inject, br, timing) {
61
+
62
+ const { waitFor, realClick, findApplyButton, pointBelongsToCard, ensurePageAlive, PAGE_TIMING, VIDEO_LOCK_MARGIN_MS } = inject;
63
+ if (!await br.eval(MUSIC_OPEN_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => false)) return;
64
+ for (const type of ['keyDown', 'keyUp']) {
65
+ await br.send('Input.dispatchKeyEvent', { type, key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27, nativeVirtualKeyCode: 27 }, br.sessionId).catch(() => {});
66
+ }
67
+ await sleep(400);
68
+ await br.eval(String.raw`(() => {
69
+ const panel = [...document.querySelectorAll('.semi-sidesheet-content, [class*="music-collection-container"]')].find(x => { const r = x.getBoundingClientRect(); return r.width && r.height; });
70
+ if (!panel) return true;
71
+ const close = panel.closest('.semi-sidesheet')?.querySelector('.semi-sidesheet-close, [aria-label="close"]');
72
+ if (close) close.click();
73
+ return true;
74
+ })()`, { timeoutMs: timing.evalTimeoutMs }).catch(() => false);
75
+ }
76
+
77
+ /** 仅点击匹配歌曲卡片内的「使用」,并在编辑区确认歌名后才允许发布。
78
+ * allowDuplicate:推荐里同名卡不止一张时点第一张。编辑页仍要确认歌名,确认不了就不发布。 */
79
+ export async function pickNoteMusic(inject, br, music, { allowDuplicate = false, timing = PAGE_TIMING } = {}) {
80
+
81
+ const { waitFor, realClick, findApplyButton, pointBelongsToCard, ensurePageAlive, PAGE_TIMING, VIDEO_LOCK_MARGIN_MS } = inject;
82
+ if (!music) return { ok: false, error: '模型没有选出推荐歌曲' };
83
+ try {
84
+ const card = await br.eval(`(() => { ${MUSIC_DOM_JS}
85
+ const matches = rows.filter(row => nameOf(row) === ${JSON.stringify(music)});
86
+ if (!matches.length) return { count: 0 };
87
+ const target = matches.length === 1 || ${allowDuplicate ? 'true' : 'false'} ? matches[0] : null;
88
+ if (!target) return { count: matches.length };
89
+ target.scrollIntoView({ block: 'center' });
90
+ const r = target.getBoundingClientRect();
91
+ return { count: matches.length, x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };
92
+ })()`, { timeoutMs: timing.evalTimeoutMs });
93
+ if (!card?.count) return { ok: false, error: '选中的歌曲已不在推荐列表' };
94
+ // 同名(剪辑版 / 合集版)不整单作废。点第一张,后面仍要编辑页确认歌名。
95
+ if (card.count !== 1 && !allowDuplicate) return { ok: false, error: '推荐列表里有同名歌曲,无法确定选哪首' };
96
+ await br.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: card.x, y: card.y }, br.sessionId);
97
+ // 「使用」按钮按**语义**定位(role=button + name=使用),不靠抖音的构建哈希类名。
98
+ // 按钮平时 visibility:hidden、不进无障碍树 —— 上面 hover 之后才出现,所以放在这里找。
99
+ // ⚠️ findApplyButton 找不到时**必须返回 null**:waitFor 用 `if (v) return v` 判,
100
+ // 返回 {ok:false} 是 truthy ⇒ 第一轮就返回、重试形同虚设 ⇒ hover 后按钮
101
+ // 异步出现的那个竞态完全没被吸收(2026-11-20 独立审查实测:700ms 才出现时必挂)。
102
+ const found = await waitFor(async () => {
103
+ const r = await findApplyButton(br, timing, card);
104
+ if (r.reason === 'read-failed') throw new Error(r.error); // 读失败要透出来,不能当「没找到」
105
+ return r.ok ? r : null;
106
+ }, { tries: 8, gapMs: 500, budgetMs: timing.waitBudgetMs });
107
+ let btn = null;
108
+ if (found?.ok) {
109
+ // 逐个候选做归属校验:AX 命中的是整棵树,页面别处也可能有可见的「使用」。
110
+ for (const c of found.candidates) {
111
+ if (await pointBelongsToCard(br, c, music, timing)) { btn = c; break; }
112
+ }
113
+ }
114
+ if (!btn) {
115
+ // 兜底:直接在该歌卡 DOM 子树里找文本为「使用」的按钮或行内节点(防 AX 树漏掉或虚拟列表重排)
116
+ const domBtn = await br.eval(`(() => { ${MUSIC_DOM_JS}
117
+ const matches = rows.filter(row => nameOf(row) === ${JSON.stringify(music)});
118
+ const target = matches.length === 1 || ${allowDuplicate ? 'true' : 'false'} ? matches[0] : null;
119
+ if (!target) return null;
120
+ const el = [...target.querySelectorAll('button, [role="button"], span, div')]
121
+ .find(x => (x.innerText || x.textContent || '').trim() === '使用' && x.children.length <= 1);
122
+ if (!el) return null;
123
+ const r = el.getBoundingClientRect();
124
+ return r.width > 0 && r.height > 0 ? { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) } : { x: card.x, y: card.y };
125
+ })()`, { timeoutMs: timing.evalTimeoutMs }).catch(() => null);
126
+ if (domBtn) btn = domBtn;
127
+ }
128
+ if (!btn) return { ok: false, error: found?.ok ? '找到的「使用」按钮不在选中的那首歌上(页面结构变了?)' : '歌曲卡片悬停后没有出现使用按钮' };
129
+ // 点击前再 hover 到按钮上:查询与点击之间可能已过几轮重试,按钮可能重新 hidden。
130
+ // ⚠️ hover 与按下之间必须隔一帧:按钮靠 CSS :hover 从 visibility:hidden 变可见,
131
+ // 紧接着按下会落在「刚变可见」的瞬间、事件不派发(实测:点了没反应且不报错)。
132
+ await br.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: btn.x, y: btn.y }, br.sessionId).catch(() => {});
133
+ await sleep(250);
134
+ await realClick(br, btn.x, btn.y);
135
+ if (btn.backendNodeId) {
136
+ // 真机容错:getBoxModel 偶尔返回的是内层 span 偏移坐标(甚至超出了 400px 卡片右边界),
137
+ // 或者窗口在后台时 mousePressed 没触发 React 合成 onClick —— 仅在抽屉仍开着时用该节点的 DOM click 补一道。
138
+ await sleep(250);
139
+ const stillOpen = await br.eval(MUSIC_OPEN_JS, { timeoutMs: timing.evalTimeoutMs }).catch(() => false);
140
+ if (stillOpen) {
141
+ const resolved = await br.send('DOM.resolveNode', { backendNodeId: btn.backendNodeId }, br.sessionId, timing.evalTimeoutMs).catch(() => null);
142
+ const objectId = resolved?.object?.objectId;
143
+ if (objectId) {
144
+ await br.send('Runtime.callFunctionOn', {
145
+ objectId,
146
+ functionDeclaration: `function () { if (typeof this.click === 'function') this.click(); }`,
147
+ returnByValue: true
148
+ }, br.sessionId, timing.evalTimeoutMs).catch(() => {});
149
+ await br.send('Runtime.releaseObject', { objectId }, br.sessionId, timing.evalTimeoutMs).catch(() => {});
150
+ }
151
+ }
152
+ }
153
+ const verified = await waitFor(() => br.eval(`(() => {
154
+ const want = ${JSON.stringify(music)}.replace(/\\s+/g, '');
155
+ const visible = el => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; };
156
+ const anchors = [...document.querySelectorAll('[class*="container-right"]')].filter(visible);
157
+ for (const anchor of anchors) {
158
+ if (anchor.closest('.semi-sidesheet, [class*="music-collection-container"]')) continue;
159
+ let row = anchor;
160
+ for (let i = 0; i < 4 && row; i++, row = row.parentElement) {
161
+ if (row === document.body) break;
162
+ // 这一层内部装着音乐面板 ⇒ 它的 innerText 含面板里的歌名,不能当证据,跳过。
163
+ if (row.querySelector('.semi-sidesheet, [class*="music-collection-container"]')) continue;
164
+ if (row.querySelector('[class*="preview"], [contenteditable="true"], input[placeholder*="标题"]')) break;
165
+ const text = (row.innerText || '').trim();
166
+ if (text.length <= 250 && text.replace(/\\s+/g, '').includes(want)) return true;
167
+ }
168
+ }
169
+ const binders = [...document.querySelectorAll('[class*="music-binder"], [class*="music-text"]')].filter(visible);
170
+ for (const b of binders) {
171
+ if (b.closest('.semi-sidesheet, [class*="music-collection-container"]')) continue;
172
+ const text = (b.innerText || '').trim();
173
+ if (text.length <= 250 && text.replace(/\\s+/g, '').includes(want)) return true;
174
+ }
175
+ return false;
176
+ })()`, { timeoutMs: timing.evalTimeoutMs }).catch(() => false), { tries: 10, gapMs: 500, budgetMs: timing.waitBudgetMs });
177
+ return verified ? { ok: true } : { ok: false, error: '已点击使用,但编辑页未确认显示歌名' };
178
+ } catch (error) {
179
+ return { ok: false, error: `配乐操作出错:${String(error?.message ?? error).slice(0, 80)}` };
180
+ }
181
+ }
182
+
183
+ /** 真正的页面驱动(测试里换成假的)。全部都得在 host.exclusive 里调。
184
+ * timing:页面操作的时间上限(eval 单次超时 / waitFor 总预算),测试可以调小。 */
@@ -0,0 +1,49 @@
1
+ /**
2
+ * douyin-social-works.js —— 发布之后「读回作品 id」。
3
+ *
4
+ * 为什么需要它(2026-11-30 真机发现):
5
+ * 创作者中心点完「发布」只回 `{ ok: true }`,**不带作品 id**。而 `social_post.post_id`
6
+ * 以前被写死成空串 ⇒ `commentPoll()` 那句「从 social_post 补回完整文案」的反查
7
+ * (`WHERE platform='douyin' AND post_id = ?`)永远查不到 ⇒ 那段保护是死代码 ⇒
8
+ * 作品标题只能用列表页的「标题 + 摘要」拼接,实际显示成**标题重复两遍**。
9
+ *
10
+ * 真机证据:发完一条 `note/7713924450059619618`,库里 `post_id` 是空的,
11
+ * 页面上标题是「测试一下新配置,发完就删。测试一下新配置,发完就删」。
12
+ *
13
+ * 两条路径:
14
+ * · `attachWorkId` —— 正常发布。**必须在那把浏览器锁里调**(见下)。
15
+ * · `readTopWorkId` —— 人工核实「已发布」那条路,它不在发布流程里,自己占锁。
16
+ */
17
+
18
+ /**
19
+ * 发布成功后读回刚发的作品 id,挂到结果上(`published.workId`)。
20
+ *
21
+ * 🔴 为什么必须在**发布那把锁里**调用:放锁外再读会多占一次 exclusive,
22
+ * 直接打挂 `test/douyin-video-post.mjs` 的「发布阶段才占锁」契约
23
+ * (那条断言守的是「生成视频不能占着浏览器锁」,是有价值的约束,不该放宽)。
24
+ * 而且发布完页面正好停在作品管理页,锁内读是顺路的。
25
+ *
26
+ * 读不到就是空串 —— 只是回到旧行为,**绝不能因此把发布判失败**(作品已经发出去了)。
27
+ *
28
+ * @param {{ listWorks: (n: number) => Promise<Array<{id: string}>> }} driver
29
+ * @param {{ ok?: boolean, workId?: string }} published
30
+ */
31
+ export async function attachWorkIdImpl(driver, published) {
32
+ if (!published?.ok) return published;
33
+ try {
34
+ const works = await driver.listWorks(3);
35
+ published.workId = Array.isArray(works) && works[0]?.id ? String(works[0].id) : '';
36
+ } catch { /* 读不到就当没有 */ }
37
+ return published;
38
+ }
39
+
40
+ /**
41
+ * 自己占锁读一次最新作品 id。
42
+ * 只给「人工核实已发布」那条路径用 —— 它不在发布流程里,占一次锁没有副作用。
43
+ */
44
+ export async function readTopWorkIdImpl(host, driver) {
45
+ try {
46
+ const works = await host.exclusive('读回作品 id', () => driver.listWorks(3), { maxMs: 90_000 });
47
+ return Array.isArray(works) && works[0]?.id ? String(works[0].id) : '';
48
+ } catch { return ''; }
49
+ }