dsh-qianchuan-toolkit 1.0.6 → 1.0.7

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/CHANGELOG.md CHANGED
@@ -1,16 +1,10 @@
1
1
  # 更新日志
2
2
 
3
- ## 1.0.6
4
-
5
- - `copy.mjs` 新增「没截图=不让删」硬闸门:`confirm` 先按计划 ID 搜到唯一一条、截列表图 `qc/confirm-<ID>.png` 并写确认单(TOKEN,30 分钟有效);`delete` 没有有效确认单 / TOKEN 不符 / 截图丢失一律拒绝,只有 `--force` 可跳过。
6
- - 列表搜索改合成回车(`KeyboardEvent`,`keyCode 13`):CDP `Input.dispatchKeyEvent` 在千川列表里不触发搜索,会一直停在「共 N 条计划」;新增 `HIT_ONE` 行判定(含 `ID:` 的行恰好 1 行且包含该 ID)替代正则,避开多层字符串吃反斜杠。
7
- - 导航后 SPA 默认停在「全店托管」,新增 `ensurePlanList()`:先点「计划视图」再点「商品自选」,才等到搜索框;搜索失败会 dump 可见文字后重试一次。
8
- - 创建链路修三处:①`focusAndType` 里 `Input.insertText` 的 `text` 必须是字符串(ROI/预算传数字报 `Failed to deserialize params.text`);②商品抽屉默认勾着「只看可投商品」,搜 ID 得 0 行,改为自动取消勾选并最多搜三次(含回车);③抖音号步骤先等「手动选择抖音号」再点,行内勾选正则转义修正。
9
- - 素材链路改走**列表页详情抽屉**(用户指定路径):点行内计划名叶子打开抽屉 → 抽屉内「素材」tab → 「自选素材」→ 素材类型「视频」→「添加视频」→ 逐抖音号全选 → 一次确定。素材 tab 默认停在 AIGC,不先点「视频」就没有「添加视频」按钮。
10
- - `pick-all.mjs` 模块化导出 `pickAllOnTarget`:切号后轮询最多 8s 取卡片;点完读「已选择 N/200」,没涨就补点一次;某号 0 卡片先取消「过滤不良素材」再等 12s,仍为空才跳过并记录;最后统一提交,逐号输出 `{cards,before,after,delta,retried,note}`。单号模式修掉 `~/.qianchuan-cruise/out` 不存在导致的 `ENOENT`。
11
- - `cdp-lib.mjs`:`connect()` 返回值补 `id`(素材步骤需绑定当前驱动的标签页);`eval` 抛错附带表达式前 240 字符。
12
- - 新增 `node copy.mjs all <aavid> <params.json>`:confirm → 人工确认 → delete → create → materials → publish 一条龙,确认单为硬闸门。
13
- - 看门狗 `QC_WATCHDOG`(默认 150s)与秒级打点:进程不再因 CDP 长连接挂住不退出。
3
+ ## 1.0.7
4
+
5
+ - **计划复制**:`copy.mjs` 增加**删除前确认单**(`confirm` 子命令 + 令牌校验),没有确认单 `delete` 拒绝执行;新增 `notify-media.mjs`,删除前截图自动推 **QQ 官方机器人 + 企业微信**(三行格式:`【删除前确认】` + 名称 + ID);`pick-all.mjs` 改为按抖音号轮询、取消失败重试,修掉「卡片已渲染但已选为 0」的漏选。
6
+ - **CDP 层**:`cdp-lib.mjs` 的 `page` 带 `id`,报错时附带页面标题/URL 上下文,多标签页排查不再靠猜。
7
+ - 巡航部分(`live-control`)与 1.0.5 逐字节一致,本次未改动。
14
8
 
15
9
  ## 1.0.5
16
10
 
@@ -203,6 +203,16 @@ async function cmdConfirm() {
203
203
  const ts = Date.now(), token = tokenFor(planId, ts, shot);
204
204
  fs.mkdirSync(path.dirname(receiptPath(planId)), { recursive: true });
205
205
  fs.writeFileSync(receiptPath(planId), JSON.stringify({ planId, aavid, ts, shot, token, rowText: row }, null, 1));
206
+ // 同步下发到 QQ / 企业微信(失败不影响出图与确认单)
207
+ try {
208
+ const { pushImage } = await import('./notify-media.mjs');
209
+ const text = '【删除前确认】' + String.fromCharCode(10)
210
+ + '名称:' + String(row).split('ID:')[0].trim().slice(0, 40) + String.fromCharCode(10)
211
+ + 'ID:' + planId;
212
+ console.log('PUSH-TEXT ' + text.split(String.fromCharCode(10)).join(' / '));
213
+ const pushed = await pushImage({ file: shot, text, say: (s) => console.log(s) });
214
+ console.log('PUSH ' + JSON.stringify(pushed.map((x) => ({ ch: x.ch, part: x.part, ok: x.ok }))));
215
+ } catch (e) { console.log('PUSH-ERR ' + String(e.message).slice(0, 140)); }
206
216
  mark('confirm-shot', shot);
207
217
  console.log('ROW ' + row);
208
218
  console.log('SHOT ' + shot);
@@ -0,0 +1,83 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import os from 'node:os';
5
+
6
+ const CFG = path.join(os.homedir(), '.qianchuan-cruise', 'notify.json');
7
+
8
+ export function loadChannels() {
9
+ try { return JSON.parse(fs.readFileSync(CFG, 'utf8')).channels || [] } catch { return [] }
10
+ }
11
+
12
+ let tok = null;
13
+ async function qqToken(ch) {
14
+ if (tok && tok.exp > Date.now() + 60000) return tok.v;
15
+ const r = await fetch('https://bots.qq.com/app/getAppAccessToken', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ appId: ch.appId, clientSecret: ch.clientSecret }) });
16
+ const j = await r.json();
17
+ if (!j.access_token) throw new Error('QQ token 失败 ' + JSON.stringify(j).slice(0, 160));
18
+ tok = { v: j.access_token, exp: Date.now() + (Number(j.expires_in || 7200) - 120) * 1000 };
19
+ return tok.v;
20
+ }
21
+
22
+ async function qqPost(ch, p, body, auth) {
23
+ const r = await fetch('https://api.sgroup.qq.com' + p, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'QQBot ' + auth }, body: JSON.stringify(body) });
24
+ const t = await r.text();
25
+ let j = null;
26
+ try { j = JSON.parse(t) } catch {}
27
+ return { status: r.status, j, body: t.slice(0, 200) };
28
+ }
29
+
30
+ async function sendQQText(ch, text) {
31
+ const a = await qqToken(ch);
32
+ return qqPost(ch, '/v2/users/' + ch.openid + '/messages', { content: text, msg_type: 0 }, a);
33
+ }
34
+
35
+ async function sendQQImage(ch, file) {
36
+ const a = await qqToken(ch);
37
+ const b64 = fs.readFileSync(file).toString('base64');
38
+ const up = await qqPost(ch, '/v2/users/' + ch.openid + '/files', { file_type: 1, file_data: b64, srv_send_msg: false }, a);
39
+ const info = up.j && up.j.file_info;
40
+ if (!info) return { ok: false, step: 'upload', status: up.status, body: up.body };
41
+ const sent = await qqPost(ch, '/v2/users/' + ch.openid + '/messages', { content: '', msg_type: 7, media: { file_info: info } }, a);
42
+ return { ok: sent.status === 200 || sent.status === 201, step: 'send', status: sent.status, body: sent.body };
43
+ }
44
+
45
+ async function sendWecomImage(ch, file) {
46
+ const buf = fs.readFileSync(file);
47
+ const body = { msgtype: 'image', image: { base64: buf.toString('base64'), md5: crypto.createHash('md5').update(buf).digest('hex') } };
48
+ const r = await fetch(ch.url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
49
+ const t = await r.text();
50
+ return { ok: /"errcode":0/.test(t), status: r.status, body: t.slice(0, 200) };
51
+ }
52
+
53
+ async function sendWecomText(ch, text) {
54
+ const r = await fetch(ch.url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ msgtype: 'text', text: { content: text } }) });
55
+ const t = await r.text();
56
+ return { ok: /"errcode":0/.test(t), status: r.status, body: t.slice(0, 200) };
57
+ }
58
+
59
+ /** 把一张图 + 一段文字同时推到所有启用的渠道 */
60
+ export async function pushImage({ file, text, say = () => {} }) {
61
+ const out = [];
62
+ for (const ch of loadChannels()) {
63
+ if (!ch.enabled) continue;
64
+ try {
65
+ if (ch.type === 'qq') {
66
+ if (text) out.push({ ch: ch.name, part: 'text', ...(await sendQQText(ch, text)) });
67
+ out.push({ ch: ch.name, part: 'image', ...(await sendQQImage(ch, file)) });
68
+ } else if (ch.type === 'wecom') {
69
+ if (text) out.push({ ch: ch.name, part: 'text', ...(await sendWecomText(ch, text)) });
70
+ out.push({ ch: ch.name, part: 'image', ...(await sendWecomImage(ch, file)) });
71
+ }
72
+ } catch (e) { out.push({ ch: ch.name, ok: false, err: String(e.message).slice(0, 120) }) }
73
+ }
74
+ out.forEach(r => say('[notify] ' + JSON.stringify(r).slice(0, 150)));
75
+ return out;
76
+ }
77
+
78
+ if (process.argv[1] && process.argv[1].endsWith('notify-media.mjs')) {
79
+ const file = process.argv[2];
80
+ const text = process.argv[3] || '';
81
+ const r = await pushImage({ file, text, say: (s) => console.log(s) });
82
+ console.log('RESULT ' + JSON.stringify(r.map(x => ({ ch: x.ch, part: x.part, ok: x.ok, status: x.status, step: x.step }))));
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qianchuan-toolkit",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "type": "module",
5
5
  "description": "DSH skill bundle for 巨量千川: 直播盯盘自动控量 (qianchuan-live-control) + 乘方计划复制 (qianchuan-plan-copy).",
6
6
  "license": "MIT",
@@ -46,4 +46,4 @@
46
46
  "CHANGELOG.md",
47
47
  "docs"
48
48
  ]
49
- }
49
+ }
@@ -1,171 +0,0 @@
1
- /**
2
- * 进程内 CDP 客户端:巡航/控量脚本直接 import 本文件,不再 spawn 子进程
3
- * (沙箱里 Node 再 spawn Node 会 EPERM,所以必须走这条路)。
4
- *
5
- * v9 加固:
6
- * - 自动接管原生弹窗(alert/confirm/beforeunload)——它们会卡住渲染线程,导致 eval 永不返回
7
- * - 所有 CDP 调用带超时(默认 20s),eval 默认 15s,绝不无限等待
8
- * - 暴露 page.dialogs,便于排查「页面为什么卡住」
9
- */
10
- import fs from 'node:fs'
11
- import path from 'node:path'
12
-
13
- const PORT = process.env.CDP_PORT || 9222
14
- const BASE = 'http://127.0.0.1:' + PORT
15
- const SEND_TIMEOUT = Number(process.env.CDP_SEND_TIMEOUT_MS || 20000)
16
- const EVAL_TIMEOUT = Number(process.env.CDP_EVAL_TIMEOUT_MS || 15000)
17
-
18
- export class CdpError extends Error {}
19
-
20
- async function getJson(p) {
21
- const r = await fetch(BASE + p)
22
- if (!r.ok) throw new CdpError('http ' + r.status + ' ' + p)
23
- return r.json()
24
- }
25
-
26
- export async function listPages() {
27
- try {
28
- return await getJson('/json/list')
29
- } catch (err) {
30
- throw new CdpError('连不上调试端口 ' + PORT + '(' + ((err && err.message) || err) + ')—— 请先手动启动浏览器:双击 assets/scripts/start-qc.cmd,登录千川并停在「全域投放 · 推直播间」列表页')
31
- }
32
- }
33
-
34
- /** 浏览器级 CDP(用于新建标签页):/json/version 的 webSocketDebuggerUrl */
35
- async function browserWs() {
36
- const v = await getJson('/json/version')
37
- return v.webSocketDebuggerUrl
38
- }
39
-
40
- /** 浏览器级调用(Target.createTarget 等) */
41
- export async function browserSend(method, params = {}, timeoutMs = 15000) {
42
- const wsUrl = await browserWs()
43
- const ws = new WebSocket(wsUrl)
44
- await new Promise((res, rej) => {
45
- const timer = setTimeout(() => rej(new CdpError('浏览器 WS 连接超时')), 8000)
46
- ws.onopen = () => { clearTimeout(timer); res() }
47
- ws.onerror = () => { clearTimeout(timer); rej(new CdpError('浏览器 WS 连接失败')) }
48
- })
49
- try {
50
- return await new Promise((res, rej) => {
51
- const id = 1
52
- const timer = setTimeout(() => rej(new CdpError('浏览器 CDP 超时:' + method)), timeoutMs)
53
- ws.onmessage = (ev) => {
54
- let m
55
- try { m = JSON.parse(ev.data) } catch { return }
56
- if (m.id !== id) return
57
- clearTimeout(timer)
58
- if (m.error) rej(new CdpError(JSON.stringify(m.error))); else res(m.result)
59
- }
60
- ws.send(JSON.stringify({ id, method, params }))
61
- })
62
- } finally { try { ws.close() } catch {} }
63
- }
64
-
65
- /** 新建一个标签页,返回 targetId(不抢焦点:background=true) */
66
- export async function createTab(url, { background = true } = {}) {
67
- const r = await browserSend('Target.createTarget', { url, background })
68
- return r.targetId
69
- }
70
-
71
- /** 关掉指定标签页 */
72
- export async function closeTab(targetId) {
73
- try { return await browserSend('Target.closeTarget', { targetId }) } catch (e) { return null }
74
- }
75
-
76
- /** 连上匹配 match 的标签页(默认千川页面);给 id 则精确连某个标签页 */
77
- export async function connect(match = 'jinritemai', { autoDialog = true, id = null } = {}) {
78
- const pages = await listPages()
79
- const page = id
80
- ? pages.find((p) => p.type === 'page' && p.id === id)
81
- : pages.find((p) => p.type === 'page' && ((p.url || '').includes(match) || (p.title || '').includes(match)))
82
- if (!page) {
83
- throw new CdpError('没找到标题/URL 含「' + match + '」的标签页。当前标签页:' + pages.filter((p) => p.type === 'page').map((p) => (p.title || p.url).slice(0, 40)).join(' / '))
84
- }
85
- const ws = new WebSocket(page.webSocketDebuggerUrl)
86
- await new Promise((res, rej) => {
87
- const timer = setTimeout(() => rej(new CdpError('WebSocket 连接超时(' + (page.url || '').slice(0, 60) + ')')), 10000)
88
- ws.onopen = () => { clearTimeout(timer); res() }
89
- ws.onerror = () => { clearTimeout(timer); rej(new CdpError('WebSocket 连接失败(' + (page.url || '').slice(0, 60) + ')')) }
90
- })
91
-
92
- const pending = new Map()
93
- const dialogs = []
94
- let seq = 0
95
- let alive = true
96
-
97
- ws.onmessage = (ev) => {
98
- let m
99
- try { m = JSON.parse(ev.data) } catch { return }
100
- if (m.id && pending.has(m.id)) {
101
- const p = pending.get(m.id)
102
- pending.delete(m.id)
103
- clearTimeout(p.timer)
104
- if (m.error) p.rej(new CdpError(JSON.stringify(m.error)))
105
- else p.res(m.result)
106
- return
107
- }
108
- if (m.method === 'Page.javascriptDialogOpening') {
109
- const info = m.params || {}
110
- dialogs.push({ type: info.type, message: (info.message || '').slice(0, 120), at: Date.now() })
111
- if (dialogs.length > 20) dialogs.shift()
112
- if (autoDialog) {
113
- const accept = info.type === 'beforeunload'
114
- rawSend('Page.handleJavaScriptDialog', { accept }).catch(() => {})
115
- }
116
- }
117
- }
118
- ws.onclose = () => {
119
- alive = false
120
- for (const p of pending.values()) { clearTimeout(p.timer); p.rej(new CdpError('ws closed')) }
121
- pending.clear()
122
- }
123
-
124
- const rawSend = (method, params = {}, timeoutMs = SEND_TIMEOUT) => new Promise((res, rej) => {
125
- if (!alive) return rej(new CdpError('ws closed'))
126
- const id = ++seq
127
- const timer = setTimeout(() => { pending.delete(id); rej(new CdpError('cdp 超时 ' + Math.round(timeoutMs / 1000) + 's:' + method)) }, timeoutMs)
128
- pending.set(id, { res, rej, timer })
129
- try { ws.send(JSON.stringify({ id, method, params })) } catch (e) { clearTimeout(timer); pending.delete(id); rej(new CdpError('ws send 失败: ' + e.message)) }
130
- })
131
-
132
- await rawSend('Page.enable', {}).catch(() => {})
133
-
134
- return {
135
- url: page.url,
136
- title: page.title,
137
- dialogs,
138
- send: rawSend,
139
- async eval(expr, timeoutMs = EVAL_TIMEOUT) {
140
- const r = await rawSend('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true }, timeoutMs)
141
- if (r.exceptionDetails) throw new CdpError('eval 异常: ' + r.exceptionDetails.text + ' ' + ((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || ''))
142
- return r.result ? r.result.value : undefined
143
- },
144
- async evalJson(expr, timeoutMs = EVAL_TIMEOUT) {
145
- const v = await this.eval(expr, timeoutMs)
146
- return typeof v === 'string' ? JSON.parse(v) : v
147
- },
148
- async shot(file) {
149
- const r = await rawSend('Page.captureScreenshot', { format: 'png' }, 30000)
150
- fs.mkdirSync(path.dirname(file), { recursive: true })
151
- fs.writeFileSync(file, Buffer.from(r.data, 'base64'))
152
- return file
153
- },
154
- async clickAt(x, y) {
155
- for (const e of [
156
- { type: 'mouseMoved', x, y },
157
- { type: 'mousePressed', x, y, button: 'left', clickCount: 1 },
158
- { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 },
159
- ]) await rawSend('Input.dispatchMouseEvent', e)
160
- return [Math.round(x), Math.round(y)]
161
- },
162
- async ping() { // 渲染线程是否还能跑 JS
163
- const t0 = Date.now()
164
- try { const v = await this.eval('1+1', 5000); return { ok: v === 2, ms: Date.now() - t0 } }
165
- catch (e) { return { ok: false, ms: Date.now() - t0, err: e.message } }
166
- },
167
- close() { try { ws.close() } catch {} },
168
- }
169
- }
170
-
171
- export const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
@@ -1,271 +0,0 @@
1
- #!/usr/bin/env node
2
- // 乘方-推商品「复制计划」v2:全部用 DOM 点击 + 页面内等待,不用坐标,不受窗口大小/缩放/滚动影响。
3
- // 用法:node copy.mjs <search|delete|create|materials|publish|verify> <aavid> [params.json]
4
- import fs from 'node:fs';
5
- import { connect, sleep } from '../../live-control/scripts/cdp-lib.mjs';
6
-
7
- const W = 'C:/Users/admin/Documents/deepseek-harness/default-workspace';
8
- const t0 = Date.now();
9
- const mark = (l, e) => console.log('[' + ((Date.now() - t0) / 1000).toFixed(1) + 's] ' + l + (e ? ' ' + e : ''));
10
-
11
- // ---------- 注入到页面里的工具函数(不依赖坐标) ----------
12
- function qcHelpers() {
13
- const T = (s) => (s || '').replace(/\s+/g, ' ').trim();
14
- window.__qc = {
15
- text: () => T(document.body ? document.body.innerText : ''),
16
- leaves(t, root) {
17
- return [...(root || document).querySelectorAll('button,span,div,a,li,label')]
18
- .filter((e) => e.children.length === 0 && T(e.innerText) === t && e.getBoundingClientRect().width > 0);
19
- },
20
- clickText(t, root) {
21
- const hits = this.leaves(t, root);
22
- const el = hits[hits.length - 1];
23
- if (!el) return false;
24
- el.click();
25
- return true;
26
- },
27
- rowByText(t) {
28
- const cands = [...document.querySelectorAll('*')]
29
- .filter((e) => e.children.length === 0 && T(e.innerText).includes(t) && e.getBoundingClientRect().width > 0);
30
- for (const l of cands) { const tr = l.closest('tr'); if (tr) return tr; }
31
- for (const l of cands) { const c = l.closest('.card-product-item,.oc-card,.ovui-card,.create-material-list-card-item'); if (c) return c; }
32
- return null;
33
- },
34
- clickRowLabel(t) {
35
- const row = this.rowByText(t);
36
- if (!row) return 'norow';
37
- const lab = row.querySelector('label.ovui-checkbox') || row.querySelector('label') || row.querySelector('input[type=checkbox]');
38
- if (!lab) return 'nolabel';
39
- lab.click();
40
- return 'ok';
41
- },
42
- clickCardLabel(i) {
43
- const cards = [...document.querySelectorAll('.create-material-list-card-item')].filter((c) => c.getBoundingClientRect().height > 0);
44
- const card = cards[i];
45
- if (!card) return 'nocard';
46
- const lab = card.querySelector('label') || card.querySelector('[class*=checkbox]') || card;
47
- lab.click();
48
- return 'ok';
49
- },
50
- cardsInfo() {
51
- const cards = [...document.querySelectorAll('.create-material-list-card-item')].filter((c) => c.getBoundingClientRect().height > 0);
52
- const sel = cards.filter((c) => c.querySelector('.oc-create-material-card-selected')).length;
53
- return { n: cards.length, sel: sel };
54
- }
55
- };
56
- return true;
57
- }
58
- const INJECT = '(' + qcHelpers.toString() + ')()';
59
- const waitJs = (cond, ms) => '(async () => { const t0 = performance.now(); while (performance.now() - t0 < ' + ms + ') { try { if (' + cond + ') return true } catch (e) {} await new Promise(r => setTimeout(r, 40)) } return false })()';
60
- const wait = async (page, cond, ms) => await page.eval(waitJs(cond, ms), ms + 8000);
61
- const txt = async (page) => await page.eval('__qc.text()');
62
-
63
- async function focusAndType(page, inputExpr, text) {
64
- const ok = await page.eval('(() => { const i = ' + inputExpr + '; if (!i) return false; const s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set; s.call(i, ""); i.dispatchEvent(new Event("input", { bubbles: true })); i.focus(); i.select(); return true })()');
65
- if (!ok) throw new Error('input not found');
66
- await page.send('Input.insertText', { text }, 8000);
67
- return true;
68
- }
69
-
70
- const PLAN_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("计划名称"))';
71
- const PRODUCT_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("商品名称"))';
72
- const AWEME_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("抖音号名称"))';
73
- const ROI_INPUT = 'document.querySelectorAll(".aurora-qc-input-number-input")[0]';
74
- const BUDGET_INPUT = 'document.querySelectorAll(".aurora-qc-input-number-input")[1]';
75
- const NAME_INPUT = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("计划名称,1-50"))';
76
-
77
- async function openList(page, aavid) {
78
- await page.send('Page.navigate', { url: 'https://qianchuan.jinritemai.com/overall-prom?aavid=' + aavid + '&campaignType=1&uniTab=ad&marGoal=1&uniVideoTab=1&overallPromViewTab=plan' }, 15000);
79
- const ok = await wait(page, '!!' + PLAN_SEARCH, 15000);
80
- if (!ok) throw new Error('列表页未就绪');
81
- await page.eval(INJECT);
82
- }
83
-
84
- async function cmdSearch() {
85
- const aavid = process.argv[3], planId = process.argv[4];
86
- const page = await connect('jinritemai');
87
- await openList(page, aavid);
88
- await focusAndType(page, PLAN_SEARCH, planId);
89
- await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', windowsVirtualKeyCode: 13, key: 'Enter', code: 'Enter' }, 8000);
90
- await page.send('Input.dispatchKeyEvent', { type: 'keyUp', windowsVirtualKeyCode: 13, key: 'Enter', code: 'Enter' }, 8000);
91
- await wait(page, '/共\s*\d+\s*条计划/.test(__qc.text())', 8000);
92
- const info = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const m=c(document.body.innerText).match(/共\s*(\d+)\s*条计划/); const rows=[...document.querySelectorAll("tbody tr")].map(r=>c(r.innerText)).filter(x=>x.length>40); return JSON.stringify({count: m?m[1]:null, rows: rows.slice(0,3)}) })()');
93
- mark('search', info);
94
- // 不要 page.close():会关掉标签页
95
- }
96
-
97
- async function cmdDelete() {
98
- const aavid = process.argv[3], planId = process.argv[4];
99
- const page = await connect('jinritemai');
100
- await openList(page, aavid);
101
- await focusAndType(page, PLAN_SEARCH, planId);
102
- await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', windowsVirtualKeyCode: 13, key: 'Enter', code: 'Enter' }, 8000);
103
- await page.send('Input.dispatchKeyEvent', { type: 'keyUp', windowsVirtualKeyCode: 13, key: 'Enter', code: 'Enter' }, 8000);
104
- const hit = await wait(page, '/共\s*1\s*条计划/.test(__qc.text())', 8000);
105
- if (!hit) throw new Error('未唯一命中,拒绝删除');
106
- mark('unique-hit');
107
- const clicked = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const tr=[...document.querySelectorAll("tbody tr")].find(r=>c(r.innerText).includes(' + JSON.stringify(planId) + ')); if(!tr) return "norow"; const b=[...tr.querySelectorAll("*")].filter(e=>e.children.length===0 && c(e.innerText)==="删除").pop(); if(!b) return "nobtn"; b.click(); return "ok" })()');
108
- if (clicked !== 'ok') throw new Error('删除按钮: ' + clicked);
109
- const dlg = await wait(page, '[...document.querySelectorAll("*")].some(e=>(e.innerText||"").trim()==="确定要删除计划吗?")', 6000);
110
- if (!dlg) throw new Error('删除弹窗未出现');
111
- await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const t=[...document.querySelectorAll("*")].find(e=>(e.innerText||"").trim()==="确定要删除计划吗?"); const w=t.closest(".aurora-qc-modal-wrap"); const b=[...w.querySelectorAll("button")].find(x=>c(x.innerText)==="确定"); if(b) b.click(); return 1 })()');
112
- mark('confirm-clicked');
113
- const gone = await wait(page, '/删除成功/.test(__qc.text()) && /共\s*0\s*条计划|暂无数据/.test(__qc.text())', 75000);
114
- mark('deleted', gone ? 'ok' : 'timeout');
115
- // 不要 page.close():会关掉标签页
116
- process.exit(gone ? 0 : 4);
117
- }
118
-
119
- async function cmdCreate() {
120
- const aavid = process.argv[3], p = JSON.parse(fs.readFileSync(process.argv[4], 'utf8'));
121
- const page = await connect('jinritemai');
122
- await page.send('Page.navigate', { url: 'https://qianchuan.jinritemai.com/create-ad/overall-product?aavid=' + aavid }, 15000);
123
- const ready = await wait(page, '/选择投放对象/.test(__qc.text())', 20000);
124
- if (!ready) throw new Error('新建页未就绪');
125
- await page.eval(INJECT);
126
- mark('create-page');
127
-
128
- const opened = await page.eval('__qc.clickText("添加商品")');
129
- if (!opened) throw new Error('找不到「添加商品」');
130
- const drawer = await wait(page, '!!document.querySelector(".card-product-item")', 8000);
131
- if (!drawer) throw new Error('商品抽屉未出现');
132
- mark('product-drawer');
133
-
134
- await focusAndType(page, PRODUCT_SEARCH, p.productId);
135
- const rowOk = await wait(page, '__qc.rowByText(' + JSON.stringify(p.productId) + ')', 10000);
136
- if (!rowOk) throw new Error('商品行未出现');
137
- const clicked = await page.eval('__qc.clickRowLabel(' + JSON.stringify(p.productId) + ')');
138
- if (clicked !== 'ok') throw new Error('商品勾选: ' + clicked);
139
- const picked = await wait(page, '/已选[^0-9]{0,3}[1-9]\d*\s*\/\s*30/.test(__qc.text())', 4000);
140
- if (!picked) throw new Error('商品未选中');
141
- mark('product-picked');
142
-
143
- await page.eval('__qc.clickText("下一步")');
144
- const step2 = await wait(page, '/手动选择抖音号/.test(__qc.text())', 8000);
145
- if (!step2) throw new Error('抖音号步骤未出现');
146
- await page.eval('__qc.clickText("手动选择抖音号")');
147
- await wait(page, '!!' + AWEME_SEARCH, 4000);
148
- mark('aweme-step');
149
-
150
- const ids = p.awemeIds || [], names = p.awemeNames || {};
151
- const tA = Date.now();
152
- let done = 0;
153
- for (const id of ids) {
154
- await focusAndType(page, AWEME_SEARCH, id);
155
- let ok = await wait(page, '__qc.rowByText(' + JSON.stringify(id) + ')', 4000);
156
- if (!ok) {
157
- const nm = names[id];
158
- if (nm) { await focusAndType(page, AWEME_SEARCH, nm); ok = await wait(page, '__qc.rowByText(' + JSON.stringify(id) + ')', 4000); }
159
- }
160
- if (!ok) { console.log('MISS ' + id); continue; }
161
- const r = await page.eval('__qc.clickRowLabel(' + JSON.stringify(id) + ')');
162
- if (r !== 'ok') { console.log('MISS2 ' + id + ' ' + r); continue; }
163
- done++;
164
- }
165
- const pickedAw = await page.eval('(() => { const m = __qc.text().match(/当前商品已选:\s*(\d+)/); return m ? m[1] : "?" })()');
166
- mark('awemes', 'clicked=' + done + ' picked=' + pickedAw + ' in ' + ((Date.now() - tA) / 1000).toFixed(1) + 's');
167
- await page.eval('__qc.clickText("确定")');
168
- const applied = await wait(page, '/\d+个抖音号/.test(__qc.text())', 8000);
169
- mark('aweme-applied', applied ? 'ok' : 'timeout');
170
-
171
- await focusAndType(page, ROI_INPUT, p.roi);
172
- await focusAndType(page, BUDGET_INPUT, p.budget);
173
- await focusAndType(page, NAME_INPUT, p.planName);
174
- const vals = await page.eval('JSON.stringify({ nums: [...document.querySelectorAll(".aurora-qc-input-number-input")].map(x => x.value), name: (' + NAME_INPUT + ' || {}).value })');
175
- mark('form', vals);
176
- // 不要 page.close():会关掉标签页
177
- }
178
-
179
- async function cmdMaterials() {
180
- const p = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
181
- const page = await connect('jinritemai');
182
- await page.eval(INJECT);
183
- const ok = await page.eval('__qc.clickText("添加自选素材")');
184
- if (!ok) throw new Error('找不到「添加自选素材」');
185
- const dOpen = await wait(page, '[...document.querySelectorAll(".ovui-tabs__tab-btn")].length > 1', 10000);
186
- if (!dOpen) throw new Error('素材抽屉未打开');
187
- mark('material-drawer');
188
- const cnt = await page.eval('[...document.querySelectorAll(".ovui-tabs__tab-btn")].length');
189
- let total = 0;
190
- for (let i = 1; i < cnt; i++) {
191
- const tA = Date.now();
192
- const tabName = await page.eval('(() => { const t=[...document.querySelectorAll(".ovui-tabs__tab-btn")][' + i + ']; return t ? (t.innerText||"").trim() : "" })()');
193
- await page.eval('(() => { const t=[...document.querySelectorAll(".ovui-tabs__tab-btn")][' + i + ']; if(t) t.click(); return 1 })()');
194
- await wait(page, '__qc.text().includes("添加视频")', 5000);
195
- await page.eval('__qc.clickText("添加视频")');
196
- let info = null;
197
- for (let a = 0; a < 3; a++) {
198
- const hasCards = await wait(page, '__qc.cardsInfo().n > 0', 8000);
199
- if (!hasCards) { await page.eval('__qc.clickText("添加视频")'); continue; }
200
- info = await page.eval('__qc.cardsInfo()');
201
- if (info.n > 0) break;
202
- }
203
- if (!info || info.n === 0) { console.log('NOCARD ' + tabName); continue; }
204
- let n = info.n;
205
- for (let k = 0; k < n; k++) await page.eval('__qc.clickCardLabel(' + k + ')');
206
- const after = await wait(page, '__qc.cardsInfo().sel >= ' + n, 3000);
207
- const st = await page.eval('__qc.cardsInfo()');
208
- total += st.sel;
209
- await page.eval('__qc.clickText("确定")');
210
- await wait(page, '/已添加:\d+/.test(__qc.text())', 5000);
211
- console.log('VID ' + tabName + ' n=' + n + ' sel=' + st.sel + ' ' + ((Date.now() - tA) / 1000).toFixed(1) + 's');
212
- }
213
- await page.eval('__qc.clickText("确定")');
214
- await sleep(600);
215
- const summary = await page.eval('(() => { const m = __qc.text().match(/共\s*(\d+)\s*条自选素材/); return m ? m[1] : "?" })()');
216
- mark('all-materials', 'total=' + total + ' applied=' + summary);
217
- // 注意:绝不能 page.close(),那会关掉标签页(曾导致整窗退出)
218
- }
219
-
220
- async function cmdPublish() {
221
- const page = await connect('jinritemai');
222
- await page.eval(INJECT);
223
- await page.eval('__qc.clickText("发布计划")');
224
- const dlg = await wait(page, '/确认发布/.test(__qc.text())', 8000);
225
- if (!dlg) throw new Error('发布确认框未出现');
226
- const c = await clickByText(page, '确认发布');
227
- mark('confirm', JSON.stringify(c));
228
- const done = await wait(page, 'location.href.includes("overall-prom") && location.href.includes("createSuccess")', 30000);
229
- mark('published', done ? 'ok' : 'timeout');
230
- process.exit(done ? 0 : 4);
231
- }
232
-
233
-
234
- // ---------- 统一「按文字点击」:普通 DOM → 穿透 shadow DOM 兜底 ----------
235
- async function findInShadow(page, text) {
236
- if (!page.__domEnabled) { await page.send('DOM.enable', {}, 8000); page.__domEnabled = true }
237
- const flat = await page.send('DOM.getFlattenedDocument', { depth: -1, pierce: true }, 20000);
238
- return (flat.nodes || []).filter((n) => n.nodeType === 3 && (n.nodeValue || "").indexOf(text) >= 0);
239
- }
240
- async function clickInShadow(page, text) {
241
- const hits = await findInShadow(page, text);
242
- if (!hits.length) return 'noshadow';
243
- const pid = hits[hits.length - 1].parentId;
244
- const obj = await page.send('DOM.resolveNode', { nodeId: pid }, 10000);
245
- const fn = 'function(){var p=this;for(var d=0;d<6&&p;d++){var c=(p.className||"").toString();if(p.tagName==="BUTTON"||c.indexOf("btn")>=0||c.indexOf("button")>=0){p.click();return "clicked:"+p.tagName}p=p.parentElement}this.click();return "clicked-self"}';
246
- const r = await page.send('Runtime.callFunctionOn', { objectId: obj.object.objectId, functionDeclaration: fn, returnByValue: true }, 10000);
247
- return r.result ? r.result.value : 'unknown';
248
- }
249
- // 先普通 DOM(__qc.clickText),没有就立刻穿透 shadow DOM;返回走了哪一层、耗多少毫秒
250
- async function clickByText(page, text) {
251
- const t = Date.now();
252
- const dom = await page.eval('__qc.clickText(' + JSON.stringify(text) + ')');
253
- if (dom) return { text: text, layer: 'dom', click: 'ok', ms: Date.now() - t };
254
- const sh = await clickInShadow(page, text);
255
- return { text: text, layer: 'shadow', click: sh, ms: Date.now() - t };
256
- }
257
- async function cmdClick() {
258
- const page = await connect('jinritemai');
259
- await page.eval(INJECT);
260
- const text = process.argv[3] || '发布计划';
261
- const dry = process.argv.includes('--dry');
262
- const domCount = await page.eval('__qc.leaves(' + JSON.stringify(text) + ').length');
263
- let shadowHit = 0;
264
- try { shadowHit = (await findInShadow(page, text)).length } catch (e) { shadowHit = -1 }
265
- mark('locate', JSON.stringify({ text: text, domLeaves: domCount, shadowTextNodes: shadowHit }));
266
- if (!dry) mark('click', JSON.stringify(await clickByText(page, text)));
267
- }
268
- const table = { search: cmdSearch, verify: cmdSearch, delete: cmdDelete, create: cmdCreate, materials: cmdMaterials, publish: cmdPublish, click: cmdClick };
269
- const cmd = process.argv[2];
270
- if (!table[cmd]) { console.log('usage: node copy.mjs <search|delete|create|materials|publish|verify> ...'); process.exit(2); }
271
- try { await table[cmd](); } catch (e) { console.log('ERR ' + e.message); process.exit(3); }
@@ -1,77 +0,0 @@
1
- // pick-all.mjs —— 「添加视频」弹窗里把每个抖音号的主页视频全勾上,然后点确定
2
- // 用法: node pick-all.mjs [adId]
3
- // adId 省略时从最近一个 out/*.json 读抖音号名称
4
- // 前提: 已进入某计划的 素材 tab,且「添加视频」弹窗已打开
5
- // 逻辑: 切号用 JS click(按名称,坐标点不动);素材卡片必须 CDP 真实点击;已添加的卡片点了没反应,所以每张都点一遍
6
- import fs from 'node:fs'
7
- import path from 'node:path'
8
-
9
- const PORT = 9222, BASE = 'http://127.0.0.1:' + PORT
10
- // 计划参数快照目录:默认 <数据目录>/out,可用 QC_OUT 覆盖
11
- const OUT_DIR = process.env.QC_OUT || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.qianchuan-cruise', 'out')
12
- const CARD = '.main-vmok-plugin-create-material-list-card-item'
13
- const NAV = '.main-vmok-plugin-tabs__nav-list'
14
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
15
-
16
- function namesFor(adId) {
17
- if (adId) { const f = path.join(OUT_DIR, adId + '.json'); if (fs.existsSync(f)) { const d = JSON.parse(fs.readFileSync(f, 'utf8')); return d.douyinNames || [] } }
18
- const files = fs.readdirSync(OUT_DIR).filter((f) => f.endsWith('.json')).map((f) => path.join(OUT_DIR, f))
19
- if (!files.length) return []
20
- files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)
21
- return JSON.parse(fs.readFileSync(files[0], 'utf8')).douyinNames || []
22
- }
23
-
24
- async function j(p) { const r = await fetch(BASE + p); if (!r.ok) throw new Error('http ' + r.status); return r.json() }
25
- async function connect(t) {
26
- const ws = new WebSocket(t.webSocketDebuggerUrl)
27
- await new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error('ws error')) })
28
- const c = { ws, seq: 0, p: new Map() }
29
- ws.onmessage = (e) => { let m; try { m = JSON.parse(e.data) } catch { return } if (m.id && c.p.has(m.id)) { const q = c.p.get(m.id); c.p.delete(m.id); m.error ? q.rej(new Error(JSON.stringify(m.error))) : q.res(m.result) } }
30
- return c
31
- }
32
- function send(c, method, params = {}) { const id = ++c.seq; return new Promise((res, rej) => { c.p.set(id, { res, rej }); c.ws.send(JSON.stringify({ id, method, params })) }) }
33
- async function ev(c, expr) { const r = await send(c, 'Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.text); return r.result?.value }
34
- async function click(c, x, y) {
35
- await send(c, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
36
- await send(c, 'Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
37
- await send(c, 'Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
38
- }
39
- const getSel = `(()=>{const t=document.body.innerText.replace(/[ \\t]+/g,' ');const m=t.match(/已选择\\s*(\\d+)\\/200/);return m?Number(m[1]):-1})()`
40
- const clickTab = (name) => `(()=>{const ls=[...document.querySelectorAll('${NAV}')];for(const list of ls){const t=[...list.children].find(c=>c.innerText&&c.innerText.replace(/\\s+/g,' ').trim().includes(${JSON.stringify(name)}));if(t){t.click();return 'OK'}}return 'NOTAB'})()`
41
- const listCards = `(()=>[...document.querySelectorAll('${CARD}')].map(c=>{const w=c.querySelector('[itemid]')||c;return w.getAttribute('itemid')}).filter(Boolean))()`
42
- const cardPos = (id) => `(()=>{const c=[...document.querySelectorAll('${CARD}')].find(x=>{const w=x.querySelector('[itemid]')||x;return w.getAttribute('itemid')===${JSON.stringify(id)}});if(!c)return null;c.scrollIntoView({block:'center',inline:'nearest'});const r=c.getBoundingClientRect();if(r.width<10)return null;return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`
43
-
44
- const arg = process.argv[2]
45
- const names = arg && arg.includes(',') ? arg.split(',').map((s) => s.trim()).filter(Boolean) : namesFor(arg)
46
- if (!names.length) { console.log(JSON.stringify({ error: '没有抖音号名单:先跑 dump-plan.mjs,或直接 socket 里看' })); process.exit(1) }
47
- const pages = (await j('/json/list')).filter((t) => t.type === 'page')
48
- const page = pages.find((p) => p.url.includes('qianchuan')) || pages[0]
49
- const c = await connect(page)
50
-
51
- const modalOpen = await ev(c, `(()=>/已选择\\s*\\d+\\/200/.test(document.body.innerText))()`)
52
- if (!modalOpen) { console.log(JSON.stringify({ error: '「添加视频」弹窗没开,先手动打开或点「添加视频」' })); process.exit(1) }
53
-
54
- const log = []
55
- for (const name of names) {
56
- const r = await ev(c, clickTab(name))
57
- if (r !== 'OK') { log.push({ name, err: r }); continue }
58
- await sleep(2600) // 卡片异步渲染,等不够会读到 0 张
59
- const ids = await ev(c, listCards)
60
- const before = await ev(c, getSel)
61
- for (const id of ids) {
62
- const p = await ev(c, cardPos(id))
63
- if (!p) continue
64
- await sleep(140)
65
- await click(c, p.x, p.y)
66
- await sleep(300)
67
- }
68
- const after = await ev(c, getSel)
69
- log.push({ name, cards: ids.length, before, after, delta: after - before })
70
- }
71
- // 点确定
72
- const okb = await ev(c, `(()=>{const bs=[...document.querySelectorAll('button')].filter(b=>b.innerText.trim()==='确定'&&b.getBoundingClientRect().width>0);if(!bs.length)return 'NOOK';const r=bs[bs.length-1].getBoundingClientRect();return [Math.round(r.x+r.width/2),Math.round(r.y+r.height/2)]})()`)
73
- let submitted = false
74
- if (Array.isArray(okb)) { await click(c, okb[0], okb[1]); await sleep(5000); submitted = true }
75
- const total = await ev(c, `(()=>{const m=document.body.innerText.match(/共\\d+个视频/);return m?m[0]:null})()`)
76
- console.log(JSON.stringify({ ok: true, submitted, totalVideos: total, log }, null, 1))
77
- process.exit(0)
@@ -1,112 +0,0 @@
1
- // pick-all.mjs —— 「添加视频」弹窗里把每个抖音号的主页视频全勾上,一次跑完直接点确定(不二次补选)
2
- // 用法: node scripts/pick-all.mjs "抖音号名1,抖音号名2,...,抖音号名N"
3
- // (单号也要带尾逗号:"号名,";不传参时从 out/*.json 读名单)
4
- // 前提: 已进入某计划的 素材 tab,素材类型=视频,且「添加视频」弹窗已打开
5
- // 改自技能资产 dsh-qianchuan-toolkit/assets/plan-copy/scripts/pick-all.mjs(用户 2026-11-20 要求的一次跑完规则)
6
- // 逻辑:
7
- // 1) 切号 JS click(横向列表坐标点不动,只能 JS click)
8
- // 2) 切号后轮询等卡片渲染(最多 8s),不要固定 sleep 后立刻取
9
- // 3) 每张卡片 CDP 真实点击;点完读「已选择 N/200」,没涨就补点一次(漏勾/点空)
10
- // 4) 某号 0 卡片 → 取消勾选「过滤不良素材」刷新 → 仍为 0 判定该号确实无视频,继续下一个号
11
- // 5) 全部号点完,一次性点「确定」提交;不再二次进弹窗、不再翻抽屉核对
12
- import fs from 'node:fs'
13
- import path from 'node:path'
14
-
15
- const PORT = 9222, BASE = 'http://127.0.0.1:' + PORT
16
- const OUT_DIR = process.env.QC_OUT || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.qianchuan-cruise', 'out')
17
- const CARD = '.main-vmok-plugin-create-material-list-card-item'
18
- const NAV = '.main-vmok-plugin-tabs__nav-list'
19
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
20
-
21
- function namesFor(adId) {
22
- if (adId) { const f = path.join(OUT_DIR, adId + '.json'); if (fs.existsSync(f)) { const d = JSON.parse(fs.readFileSync(f, 'utf8')); return d.douyinNames || [] } }
23
- const files = fs.readdirSync(OUT_DIR).filter((f) => f.endsWith('.json')).map((f) => path.join(OUT_DIR, f))
24
- if (!files.length) return []
25
- files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)
26
- return JSON.parse(fs.readFileSync(files[0], 'utf8')).douyinNames || []
27
- }
28
-
29
- async function j(p) { const r = await fetch(BASE + p); if (!r.ok) throw new Error('http ' + r.status); return r.json() }
30
- async function connect(t) {
31
- const ws = new WebSocket(t.webSocketDebuggerUrl)
32
- await new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error('ws error')) })
33
- const c = { ws, seq: 0, p: new Map() }
34
- ws.onmessage = (e) => { let m; try { m = JSON.parse(e.data) } catch { return } if (m.id && c.p.has(m.id)) { const q = c.p.get(m.id); c.p.delete(m.id); m.error ? q.rej(new Error(JSON.stringify(m.error))) : q.res(m.result) } }
35
- return c
36
- }
37
- function send(c, method, params = {}) { const id = ++c.seq; return new Promise((res, rej) => { c.p.set(id, { res, rej }); c.ws.send(JSON.stringify({ id, method, params })) }) }
38
- async function ev(c, expr) { const r = await send(c, 'Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.text); return r.result?.value }
39
- async function click(c, x, y) {
40
- await send(c, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
41
- await send(c, 'Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
42
- await send(c, 'Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
43
- }
44
- const getSel = `(()=>{const t=document.body.innerText.replace(/[ \\t]+/g,' ');const m=t.match(/已选择\\s*(\\d+)\\/200/);return m?Number(m[1]):-1})()`
45
- const clickTab = (name) => `(()=>{const ls=[...document.querySelectorAll('${NAV}')];for(const list of ls){const t=[...list.children].find(c=>c.innerText&&c.innerText.replace(/\\s+/g,' ').trim().includes(${JSON.stringify(name)}));if(t){t.click();return 'OK'}}return 'NOTAB'})()`
46
- const listCards = `(()=>[...document.querySelectorAll('${CARD}')].map(c=>{const w=c.querySelector('[itemid]')||c;return w.getAttribute('itemid')}).filter(Boolean))()`
47
- const cardPos = (id) => `(()=>{const c=[...document.querySelectorAll('${CARD}')].find(x=>{const w=x.querySelector('[itemid]')||x;return w.getAttribute('itemid')===${JSON.stringify(id)}});if(!c)return null;c.scrollIntoView({block:'center',inline:'nearest'});const r=c.getBoundingClientRect();if(r.width<10)return null;return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`
48
- const filterFind = `(()=>{const ins=[...document.querySelectorAll('input[type=checkbox]')];for(const i of ins){const lab=((i.closest('label')||i.parentElement||{}).innerText||'');if(lab.includes('过滤不良素材'))return i}return null})()`
49
- const filterToggle = `(()=>{const i=${filterFind};if(!i)return 'NOBOX';i.click();return 'OK'})()`
50
-
51
- async function pollCards(c, maxMs) {
52
- const t0 = Date.now(); let ids = []
53
- while (Date.now() - t0 < maxMs) {
54
- ids = await ev(c, listCards)
55
- if (ids.length) return ids
56
- await sleep(400)
57
- }
58
- return ids
59
- }
60
-
61
- async function selectCards(c, ids) {
62
- let clicked = 0, retried = 0
63
- for (const id of ids) {
64
- const p = await ev(c, cardPos(id))
65
- if (!p) continue
66
- await sleep(120)
67
- const before = await ev(c, getSel)
68
- await click(c, p.x, p.y)
69
- await sleep(260)
70
- let after = await ev(c, getSel)
71
- if (after === before) {
72
- const p2 = await ev(c, cardPos(id))
73
- if (p2) { await sleep(120); await click(c, p2.x, p2.y); await sleep(320); retried++ }
74
- }
75
- clicked++
76
- }
77
- return { clicked, retried }
78
- }
79
-
80
- const arg = process.argv[2]
81
- const names = arg && arg.includes(',') ? arg.split(',').map((s) => s.trim()).filter(Boolean) : namesFor(arg)
82
- if (!names.length) { console.log(JSON.stringify({ error: '没有抖音号名单:把名字用逗号串起来传进来' })); process.exit(1) }
83
- const pages = (await j('/json/list')).filter((t) => t.type === 'page')
84
- const page = pages.find((p) => p.url.includes('qianchuan')) || pages[0]
85
- const c = await connect(page)
86
-
87
- const modalOpen = await ev(c, `(()=>/已选择\\s*\\d+\\/200/.test(document.body.innerText))()`)
88
- if (!modalOpen) { console.log(JSON.stringify({ error: '「添加视频」弹窗没开,先点「添加视频」' })); process.exit(1) }
89
-
90
- const log = []
91
- for (const name of names) {
92
- const r = await ev(c, clickTab(name))
93
- if (r !== 'OK') { log.push({ name, err: r }); continue }
94
- let ids = await pollCards(c, 8000)
95
- let refreshed = false
96
- if (!ids.length) {
97
- const t = await ev(c, filterToggle)
98
- if (t === 'OK') { refreshed = true; await sleep(1200); ids = await pollCards(c, 12000) }
99
- }
100
- const before = await ev(c, getSel)
101
- let sel = { clicked: 0, retried: 0 }
102
- if (ids.length) sel = await selectCards(c, ids)
103
- const after = await ev(c, getSel)
104
- if (refreshed) { await ev(c, filterToggle); await sleep(600) }
105
- log.push({ name, cards: ids.length, before, after, delta: after - before, retried: sel.retried, note: ids.length ? undefined : '该号主页无可投视频(取消过滤后仍为空)' })
106
- }
107
- const okb = await ev(c, `(()=>{const bs=[...document.querySelectorAll('button')].filter(b=>b.innerText.trim()==='确定'&&b.getBoundingClientRect().width>0);if(!bs.length)return 'NOOK';const r=bs[bs.length-1].getBoundingClientRect();return [Math.round(r.x+r.width/2),Math.round(r.y+r.height/2)]})()`)
108
- let submitted = false
109
- if (Array.isArray(okb)) { await click(c, okb[0], okb[1]); await sleep(5000); submitted = true }
110
- const total = await ev(c, `(()=>{const m=document.body.innerText.match(/共\\d+个视频/);return m?m[0]:null})()`)
111
- console.log(JSON.stringify({ ok: true, submitted, totalVideos: total, log }, null, 1))
112
- process.exit(0)