dsh-qianchuan-toolkit 1.0.5 → 1.0.6

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,5 +1,17 @@
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 长连接挂住不退出。
14
+
3
15
  ## 1.0.5
4
16
 
5
17
  - 修复**「控量中」误判根源**:定位「一键调速」组时原来会「退回第一个含图标的组」,而「素材/人群追投」组也有同款 `iconpark-icon`(含 ⏸ 样式),退到那一组就会把「素材追投」当成「控量中」,点开还弹不出控量弹窗(`DIALOG_NOT_FOUND`)。现在四个表达式(`row-state` / `pause-info` / `pick` / `open-plus`)**不再兜底**:必须命中「一键调速」文案或 `.interfere-tool-wrapper`,且组内不含素材/人群/搜索字样;定位不到一律判 `unknown`,绝不当成控量中。
@@ -134,11 +134,12 @@ export async function connect(match = 'jinritemai', { autoDialog = true, id = nu
134
134
  return {
135
135
  url: page.url,
136
136
  title: page.title,
137
+ id: page.id,
137
138
  dialogs,
138
139
  send: rawSend,
139
140
  async eval(expr, timeoutMs = EVAL_TIMEOUT) {
140
141
  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
+ if (r.exceptionDetails) throw new CdpError('eval 异常: ' + r.exceptionDetails.text + ' ' + ((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || '') + ' ||EXPR|| ' + String(expr).slice(0, 240))
142
143
  return r.result ? r.result.value : undefined
143
144
  },
144
145
  async evalJson(expr, timeoutMs = EVAL_TIMEOUT) {
@@ -0,0 +1,171 @@
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,12 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
  // 乘方-推商品「复制计划」v2:全部用 DOM 点击 + 页面内等待,不用坐标,不受窗口大小/缩放/滚动影响。
3
- // 用法:node copy.mjs <search|delete|create|materials|publish|verify> <aavid> [params.json]
3
+ // 用法:node copy.mjs <all|confirm|search|delete|create|materials|publish|verify> <aavid> [params.json|计划ID]
4
4
  import fs from 'node:fs';
5
- import { connect, sleep } from '../../live-control/scripts/cdp-lib.mjs';
5
+ import crypto from 'node:crypto';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { pickAllOnTarget } from './pick-all.mjs';
9
+ import { connect, sleep, listPages } from '../../live-control/scripts/cdp-lib.mjs';
6
10
 
7
11
  const W = 'C:/Users/admin/Documents/deepseek-harness/default-workspace';
12
+
13
+ // ---------- 删除前确认单(硬闸门)----------
14
+ // 规则(用户 2026-11-20 定):删除前必须把「搜索该计划 ID 后的单条计划截图」原文发给用户并等其确认;
15
+ // 只读图不算发图。confirm 子命令负责产出截图 + 确认单;delete 没有有效确认单一律拒绝。
16
+ // 确认单 30 分钟失效;换计划 ID 或换了截图都要重新 confirm。
17
+ const RECEIPT_TTL_MS = 30 * 60 * 1000;
18
+ const receiptPath = (planId) => path.join(W, 'qc', 'confirm', planId + '.json');
19
+ const tokenFor = (planId, ts, shot) => crypto.createHash('sha1').update(planId + '|' + ts + '|' + shot).digest('hex').slice(0, 16);
20
+ const nowIso = () => new Date().toISOString();
8
21
  const t0 = Date.now();
9
- const mark = (l, e) => console.log('[' + ((Date.now() - t0) / 1000).toFixed(1) + 's] ' + l + (e ? ' ' + e : ''));
22
+ let LAST = 'init';
23
+ const mark = (l, e) => { LAST = l; console.log('[' + ((Date.now() - t0) / 1000).toFixed(1) + 's] ' + l + (e ? ' ' + e : '')); };
24
+ // 看门狗:任何一步卡住都会打印最后一步并退出,避免静默长跑(默认 150s,可用 QC_WATCHDOG 覆盖)
25
+ setTimeout(() => { console.log('[WATCHDOG] 卡在 ' + LAST + ',强制退出'); process.exit(9) }, Number(process.env.QC_WATCHDOG || 150000));
10
26
 
11
27
  // ---------- 注入到页面里的工具函数(不依赖坐标) ----------
12
28
  function qcHelpers() {
@@ -61,13 +77,29 @@ const wait = async (page, cond, ms) => await page.eval(waitJs(cond, ms), ms + 80
61
77
  const txt = async (page) => await page.eval('__qc.text()');
62
78
 
63
79
  async function focusAndType(page, inputExpr, text) {
80
+ text = String(text);
64
81
  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
82
  if (!ok) throw new Error('input not found');
66
83
  await page.send('Input.insertText', { text }, 8000);
67
84
  return true;
68
85
  }
69
86
 
70
- const PLAN_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("计划名称"))';
87
+ const HIT_ONE = (pid) => '(() => { const rows=[...document.querySelectorAll("tbody tr")].filter(function(r){ return (r.innerText||"").indexOf("ID:")>=0 }); return rows.length === 1 && (rows[0].innerText||"").indexOf(' + JSON.stringify(pid) + ') >= 0 })()';
88
+ async function pressEnter(page, inputExpr) {
89
+ const expr = inputExpr || 'document.activeElement';
90
+ return await page.eval('(() => { const i = ' + expr + '; if (!i) return "noinput"; const k = { key: "Enter", code: "Enter", keyCode: 13, which: 13, bubbles: true }; i.dispatchEvent(new KeyboardEvent("keydown", k)); i.dispatchEvent(new KeyboardEvent("keyup", k)); return "sent" })()')
91
+ }
92
+ async function searchPlan(page, planId) {
93
+ for (let i = 1; i <= 2; i++) {
94
+ await focusAndType(page, PLAN_SEARCH, planId);
95
+ await sleep(700);
96
+ await pressEnter(page);
97
+ if (await wait(page, HIT_ONE(planId), i === 1 ? 9000 : 15000)) return 'hit-' + i;
98
+ await sleep(800);
99
+ }
100
+ return 'miss'
101
+ }
102
+ const PLAN_SEARCH = '[...document.querySelectorAll("input")].find(x => /回车搜索|计划名称|计划ID|计划 ID/.test(x.placeholder||""))';
71
103
  const PRODUCT_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("商品名称"))';
72
104
  const AWEME_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("抖音号名称"))';
73
105
  const ROI_INPUT = 'document.querySelectorAll(".aurora-qc-input-number-input")[0]';
@@ -76,32 +108,70 @@ const NAME_INPUT = '[...document.querySelectorAll("input")].find(x => (x.placeho
76
108
 
77
109
  async function openList(page, aavid) {
78
110
  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);
111
+ await sleep(2500);
112
+ mark('nav-done');
113
+ // 导航后 SPA 常把视图停在上次的「全店托管」,先注入再切视图,否则连搜索框都搜不到
114
+ let injected = false;
115
+ for (let i = 0; i < 6 && !injected; i++) {
116
+ try { await page.eval(INJECT); injected = true } catch (e) { await sleep(1000) }
117
+ }
118
+ mark('injected', injected ? 'ok' : 'fail');
119
+ const ready = await wait(page, '(__qc.text().indexOf("计划视图") >= 0 || __qc.text().indexOf("商品自选") >= 0 || __qc.text().indexOf("全店托管") >= 0)', 20000);
120
+ mark('page-ready', ready ? 'ok' : 'timeout');
121
+ if (!ready) throw new Error('列表页未就绪(没看到 计划视图/商品自选/全店托管 任一文字)');
122
+ await ensurePlanList(page);
123
+ }
124
+
125
+ // 列表页默认可能停在「全店托管」,必须先切到「商品自选」才有计划搜索框
126
+ async function ensurePlanList(page) {
127
+ const clickLeaf = async (w) => page.eval('(() => { const els=[...document.querySelectorAll("*")].filter(x=>x.children.length===0 && (x.innerText||"").trim()===' + JSON.stringify(w) + ' && x.getBoundingClientRect().width>0); if(!els.length) return "missing"; els[els.length-1].click(); return "clicked" })()');
128
+ // 1) 先切「计划视图」(页面上有 商品视图/计划视图 两级),2) 再切「商品自选」,3) 才出现计划搜索框
129
+ const r1 = await clickLeaf('计划视图');
130
+ await sleep(1200);
131
+ const r2 = await clickLeaf('商品自选');
132
+ mark('tabs', r1 + '/' + r2);
133
+ let ok = await wait(page, '!!(' + PLAN_SEARCH + ')', 12000);
134
+ mark('search-box', ok ? 'ok' : 'timeout');
135
+ if (!ok) {
136
+ const diag = await page.eval('JSON.stringify([...document.querySelectorAll("*")].filter(x=>x.children.length===0 && (x.innerText||"").trim().length>0 && (x.innerText||"").trim().length<8 && x.getBoundingClientRect().width>0).map(x=>(x.innerText||"").trim()).filter((v,i,a)=>a.indexOf(v)===i).slice(0,40))');
137
+ await clickLeaf('计划视图');
138
+ await sleep(1500);
139
+ await clickLeaf('商品自选');
140
+ ok = await wait(page, '!!(' + PLAN_SEARCH + ')', 12000);
141
+ if (!ok) throw new Error('计划列表搜索框未就绪(计划视图=' + r1 + ' 商品自选=' + r2 + ' 可见文字=' + String(diag).slice(0, 200) + ')');
142
+ }
143
+ return true;
82
144
  }
83
145
 
84
146
  async function cmdSearch() {
85
147
  const aavid = process.argv[3], planId = process.argv[4];
86
148
  const page = await connect('jinritemai');
87
149
  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)}) })()');
150
+ const hitRes = await searchPlan(page, planId);
151
+ mark('search-hit', hitRes);
152
+ await wait(page, '(() => { const t = document.body.innerText || ""; return t.indexOf("条计划") >= 0 })()', 12000);
153
+ const info = await page.eval('(() => { const rows = [...document.querySelectorAll("tbody tr")].map(r => r.innerText || "").filter(x => x.indexOf("ID:") >= 0); return JSON.stringify({ idRows: rows.length, rows: rows.slice(0, 5) }) })()');
93
154
  mark('search', info);
94
155
  // 不要 page.close():会关掉标签页
95
156
  }
96
157
 
97
158
  async function cmdDelete() {
98
- const aavid = process.argv[3], planId = process.argv[4];
159
+ const aavid = process.argv[3], planId = process.argv[4], token = process.argv[5];
160
+ if (!planId) throw new Error('用法: copy.mjs delete <aavid> <planId> <确认单TOKEN>');
161
+ // —— 硬闸门:没有 confirm 产出的确认单,直接拒绝删除(除非显式 --force,但仍会告警)
162
+ if (token !== '--force') {
163
+ const rp = receiptPath(planId);
164
+ if (!fs.existsSync(rp)) throw new Error('拒绝删除:没有确认单 ' + rp + ',先跑 confirm 并把截图原文发给用户');
165
+ const rc = JSON.parse(fs.readFileSync(rp, 'utf8'));
166
+ if (rc.planId !== planId) throw new Error('拒绝删除:确认单不属于计划 ' + planId);
167
+ if (Date.now() - rc.ts > RECEIPT_TTL_MS) throw new Error('拒绝删除:确认单已超过 30 分钟,重新 confirm');
168
+ if (rc.token !== token) throw new Error('拒绝删除:TOKEN 与确认单不一致(应为 ' + rc.token + ')');
169
+ if (!fs.existsSync(rc.shot)) throw new Error('拒绝删除:确认截图文件丢失 ' + rc.shot);
170
+ mark('receipt-ok', rc.shot + ' @ ' + new Date(rc.ts).toISOString());
171
+ } else { mark('WARN', '--force 跳过了确认单校验,仅限用户已口头明确授权'); }
99
172
  const page = await connect('jinritemai');
100
173
  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);
174
+ const hit = (await searchPlan(page, planId)) !== 'miss';
105
175
  if (!hit) throw new Error('未唯一命中,拒绝删除');
106
176
  mark('unique-hit');
107
177
  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" })()');
@@ -110,41 +180,82 @@ async function cmdDelete() {
110
180
  if (!dlg) throw new Error('删除弹窗未出现');
111
181
  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
182
  mark('confirm-clicked');
113
- const gone = await wait(page, '/删除成功/.test(__qc.text()) && /共\s*0\s*条计划|暂无数据/.test(__qc.text())', 75000);
183
+ const gone = await wait(page, '(() => { const t = document.body.innerText || ""; if (t.indexOf("删除成功") < 0) return false; const rows = [...document.querySelectorAll("tbody tr")].filter(r => (r.innerText || "").indexOf("ID:") >= 0); return rows.length === 0 })()', 75000);
114
184
  mark('deleted', gone ? 'ok' : 'timeout');
115
185
  // 不要 page.close():会关掉标签页
116
186
  process.exit(gone ? 0 : 4);
117
187
  }
118
188
 
189
+ async function cmdConfirm() {
190
+ const aavid = process.argv[3], planId = process.argv[4];
191
+ if (!planId) throw new Error('用法: copy.mjs confirm <aavid> <planId>');
192
+ const page = await connect('jinritemai');
193
+ await openList(page, aavid);
194
+ const hit = (await searchPlan(page, planId)) !== 'miss';
195
+ if (!hit) throw new Error('拒绝出确认图:搜索结果里没有唯一该 ID 的行');
196
+ const row = 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) + ')); return tr ? c(tr.innerText) : "norow" })()');
197
+ if (row === 'norow') throw new Error('拒绝出确认图:列表里没有该 ID 的行');
198
+ const outDir = path.join(W, 'qc');
199
+ fs.mkdirSync(outDir, { recursive: true });
200
+ const shot = path.join(outDir, 'confirm-' + planId + '.png');
201
+ await page.eval('window.scrollTo(0,0)');
202
+ await page.shot(shot);
203
+ const ts = Date.now(), token = tokenFor(planId, ts, shot);
204
+ fs.mkdirSync(path.dirname(receiptPath(planId)), { recursive: true });
205
+ fs.writeFileSync(receiptPath(planId), JSON.stringify({ planId, aavid, ts, shot, token, rowText: row }, null, 1));
206
+ mark('confirm-shot', shot);
207
+ console.log('ROW ' + row);
208
+ console.log('SHOT ' + shot);
209
+ console.log('TOKEN ' + token);
210
+ console.log('-- 硬规则:把下面这行原文发给用户,等用户回「确认删除」后,再用 TOKEN 执行 delete --');
211
+ console.log('![删除前确认](<' + shot.replace(/\\/g, '/') + '>)');
212
+ // 不要 page.close():会关掉标签页
213
+ process.exit(0);
214
+ }
215
+
119
216
  async function cmdCreate() {
120
217
  const aavid = process.argv[3], p = JSON.parse(fs.readFileSync(process.argv[4], 'utf8'));
121
218
  const page = await connect('jinritemai');
122
219
  await page.send('Page.navigate', { url: 'https://qianchuan.jinritemai.com/create-ad/overall-product?aavid=' + aavid }, 15000);
220
+ await page.eval(INJECT); // 必须先注入 __qc,否则 ready 判断里的 __qc.text() 直接抛错
123
221
  const ready = await wait(page, '/选择投放对象/.test(__qc.text())', 20000);
124
222
  if (!ready) throw new Error('新建页未就绪');
125
- await page.eval(INJECT);
126
223
  mark('create-page');
127
224
 
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('商品抽屉未出现');
225
+ await wait(page, '/添加商品/.test(__qc.text())', 20000);
226
+ let drawerOpened = false;
227
+ for (let i = 0; i < 3 && !drawerOpened; i++) {
228
+ await page.eval('__qc.clickText("添加商品")');
229
+ drawerOpened = await wait(page, '!!' + PRODUCT_SEARCH, 8000);
230
+ if (!drawerOpened) await page.eval('new Promise(r=>setTimeout(r,1500))');
231
+ }
232
+ if (!drawerOpened) throw new Error('商品抽屉未出现(搜索框没出来)');
132
233
  mark('product-drawer');
133
234
 
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('商品行未出现');
235
+ const filt = await page.eval('(() => { var ls = [].slice.call(document.querySelectorAll("label,span,div")).filter(function (e) { var t = e.innerText || ""; return t.indexOf("只看可投商品") >= 0 && t.length < 30 }); if (!ls.length) return "no-label"; ls.sort(function (a, b) { return (a.innerText || "").length - (b.innerText || "").length }); var lab = ls[0].closest ? ls[0].closest("label") : null; var inp = null; if (lab) inp = lab.querySelector("input[type=checkbox]"); if (!inp) inp = ls[0].querySelector("input[type=checkbox]"); if (!inp) return "no-input"; if (inp.checked) { inp.click(); return "unchecked" } return "already-off" })()');
236
+ mark('product-filter', filt);
237
+ await sleep(600);
238
+ let rowOk = false;
239
+ for (let i = 0; i < 3 && !rowOk; i++) {
240
+ await focusAndType(page, PRODUCT_SEARCH, p.productId);
241
+ await sleep(600);
242
+ rowOk = await wait(page, '__qc.rowByText(' + JSON.stringify(p.productId) + ')', 7000);
243
+ if (!rowOk) { await pressEnter(page); rowOk = await wait(page, '__qc.rowByText(' + JSON.stringify(p.productId) + ')', 8000); }
244
+ if (!rowOk) await sleep(1000);
245
+ }
246
+ if (!rowOk) throw new Error('商品行未出现(已尝试取消只看可投商品并回车搜索三次)');
137
247
  const clicked = await page.eval('__qc.clickRowLabel(' + JSON.stringify(p.productId) + ')');
138
248
  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);
249
+ const picked = await wait(page, '/已选[^0-9]{0,3}[1-9]\\d*\\s*\\/\\s*30/.test(__qc.text())', 4000);
140
250
  if (!picked) throw new Error('商品未选中');
141
251
  mark('product-picked');
142
252
 
143
253
  await page.eval('__qc.clickText("下一步")');
144
- const step2 = await wait(page, '/手动选择抖音号/.test(__qc.text())', 8000);
254
+ const step2 = await wait(page, '/手动选择抖音号|为商品添加抖音号|请输入抖音号名称/.test(__qc.text())', 15000);
145
255
  if (!step2) throw new Error('抖音号步骤未出现');
146
256
  await page.eval('__qc.clickText("手动选择抖音号")');
147
- await wait(page, '!!' + AWEME_SEARCH, 4000);
257
+ const awemeReady = await wait(page, '!!' + AWEME_SEARCH, 12000);
258
+ if (!awemeReady) throw new Error('抖音号搜索框未出现');
148
259
  mark('aweme-step');
149
260
 
150
261
  const ids = p.awemeIds || [], names = p.awemeNames || {};
@@ -176,45 +287,121 @@ async function cmdCreate() {
176
287
  // 不要 page.close():会关掉标签页
177
288
  }
178
289
 
290
+ // ---------- 规则(用户 2026-11-20 定,写进代码)----------
291
+ // 1) 页面上任何遮挡式引导/气泡(「建议您开启…」「我知道了」)必须先关掉,再做下一步;
292
+ // 2) 素材唯一合法路径:列表 → 搜计划ID → 该行「素材」入口(详情抽屉)→ 素材 → 素材类型「视频」→ 添加视频
293
+ // → 逐抖音号全选 → 一次确定。禁止走 create-ad?type=e 编辑页加素材。
294
+ const BUBBLE_TEXTS = ['我知道了', '知道了', '不再提示', '跳过'];
295
+
296
+ async function dismissBubbles(page, depth = 0) {
297
+ if (depth > 3) return 'deeper';
298
+ const r = await page.eval('(() => { const texts = ' + JSON.stringify(BUBBLE_TEXTS) + '; const els = [...document.querySelectorAll("span,div,button,a")].filter(e => e.children.length === 0 && texts.indexOf((e.innerText || "").trim()) >= 0 && e.getBoundingClientRect().width > 0); if (!els.length) return "none"; els[els.length - 1].click(); return "dismissed" })()');
299
+ if (r === 'dismissed') { await sleep(900); return dismissBubbles(page, depth + 1) }
300
+ return r
301
+ }
302
+
303
+ // 列表第一行 = 最新创建的计划(列表按创建时间倒序)
304
+ async function newestPlanId(page) {
305
+ const raw = await page.eval('(() => { const tr = document.querySelector("tbody tr"); return tr ? tr.innerText : "" })()');
306
+ const m = String(raw).match(/ID[::]\s*(\d{10,})/);
307
+ return m ? m[1] : null
308
+ }
309
+
310
+ // 素材:只在详情页抽屉里加(用户指定路径)
311
+ async function addMaterialsViaDrawer(page, aavid, planId, names, opts = {}) {
312
+ await openList(page, aavid);
313
+ await dismissBubbles(page);
314
+ mark('list-ready');
315
+ const hit = (await searchPlan(page, planId)) !== 'miss';
316
+ if (!hit) throw new Error('搜索该 ID 不是唯一 1 条(可见行数不唯一或窗口里没等到结果),拒绝继续');
317
+ mark('search-unique');
318
+ const chip = await page.eval('(() => { const rows = [...document.querySelectorAll("tbody tr")]; const tr = rows.find(r => (r.innerText || "").indexOf(' + JSON.stringify(planId) + ') >= 0); if (!tr) return "norow"; const leaves = [...tr.querySelectorAll("*")].filter(e => e.children.length === 0 && (e.innerText || "").trim().length > 0); const first = (tr.innerText || "").split(String.fromCharCode(10)).map(s => s.trim()).filter(Boolean)[0]; let el = leaves.find(e => e.innerText.trim() === first) || leaves.find(e => e.innerText.trim() === "素材"); if (!el) return "nochip"; el.click(); return "ok" })()');
319
+ if (chip !== 'ok') throw new Error('打不开素材入口: ' + chip);
320
+ const opened = await wait(page, '(__qc.text().indexOf("保障历史") >= 0)', 12000);
321
+ if (!opened) throw new Error('详情抽屉未打开');
322
+ const tabClick = await page.eval('(() => { const roots = [...document.querySelectorAll("*")].filter(e => { const t = e.innerText || ""; return t.indexOf("保障历史") >= 0 && t.indexOf("素材") >= 0 && t.length > 100 }); if (!roots.length) return "noroot"; roots.sort((a, b) => a.innerText.length - b.innerText.length); const r = roots[0]; const lv = [...r.querySelectorAll("*")].filter(e => e.children.length === 0 && (e.innerText || "").trim() === "素材"); if (!lv.length) return "notab"; lv[0].click(); return "ok" })()');
323
+ mark('material-tab', tabClick);
324
+ await sleep(1500);
325
+ const drawer = await wait(page, '(__qc.text().indexOf("素材来源") >= 0)', 15000);
326
+ if (!drawer) throw new Error('详情抽屉-素材 tab 未就绪');
327
+ await dismissBubbles(page);
328
+ mark('drawer-material');
329
+ const typeOk = await wait(page, '(__qc.text().indexOf("素材类型") >= 0)', 8000);
330
+ if (!typeOk) throw new Error('素材类型行未出现');
331
+ const srcPick = await clickByText(page, '自选素材');
332
+ mark('material-src', JSON.stringify(srcPick));
333
+ await sleep(900);
334
+ const typePick = await clickByText(page, '视频');
335
+ mark('material-type', JSON.stringify(typePick));
336
+ await sleep(1500);
337
+ const hasBtn = await wait(page, '(__qc.text().indexOf("添加视频") >= 0)', 10000);
338
+ if (!hasBtn) throw new Error('选中 自选素材/视频 后仍没有「添加视频」按钮');
339
+ const clicked = await clickByText(page, '添加视频');
340
+ if (clicked.click !== 'ok') throw new Error('点不到「添加视频」: ' + JSON.stringify(clicked));
341
+ const popup = await wait(page, '(__qc.text().indexOf("已选择") >= 0)', 15000);
342
+ if (!popup) throw new Error('「添加视频」弹窗未打开');
343
+ mark('popup');
344
+ const targets = (await listPages()).filter((t) => t.type === 'page' && (t.url || '').indexOf('qianchuan') >= 0);
345
+ if (!targets.length) throw new Error('找不到千川标签页');
346
+ // 绑定到当前驱动的那个标签页(有 id 就按 id,没有就按连接时的 URL 兜底)
347
+ const tgt = (page.id && targets.find((t) => t.id === page.id)) || targets.find((t) => t.url === page.url) || targets[0];
348
+ const res = await pickAllOnTarget(tgt, names);
349
+ if (res.error) throw new Error(res.error);
350
+ mark('pick', JSON.stringify(res.log));
351
+ if (opts.cancelAfterPick) {
352
+ // 验证用:勾完不提交,直接取消,计划数据不变
353
+ const cx = await clickByText(page, '取消');
354
+ mark('cancelled', JSON.stringify(cx));
355
+ return res
356
+ }
357
+ const applied = await wait(page, '(__qc.text().split(" ").join("").indexOf("个视频") >= 0)', 8000);
358
+ mark('materials-applied', applied ? 'ok' : 'timeout');
359
+ return res
360
+ }
361
+
179
362
  async function cmdMaterials() {
180
- const p = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
363
+ const aavid = process.argv[3], planId = process.argv[4], paramsFile = process.argv[5];
364
+ const dry = process.argv.includes('--dry');
365
+ if (!aavid || !planId) throw new Error('用法: node copy.mjs materials <aavid> <计划ID> [params.json] [--dry]');
366
+ const p = paramsFile ? JSON.parse(fs.readFileSync(paramsFile, 'utf8')) : {};
367
+ const names = Object.values(p.awemeNames || {});
368
+ if (!names.length) throw new Error('params.json 里没有 awemeNames,拿不到抖音号名单');
369
+ if (dry) {
370
+ const page0 = await connect('jinritemai');
371
+ mark('connected');
372
+ await openList(page0, aavid);
373
+ mark('list-ready');
374
+ await dismissBubbles(page0);
375
+ const hit = (await searchPlan(page0, planId)) !== 'miss';
376
+ mark('submitted', hit ? 'hit' : 'miss');
377
+ const rowsInfo = String(1);
378
+ mark('rows', rowsInfo);
379
+ const chip = await page0.eval('(() => { const rows = [...document.querySelectorAll("tbody tr")]; const tr = rows.find(r => (r.innerText || "").indexOf(' + JSON.stringify(planId) + ') >= 0); if (!tr) return "norow"; const chips = [...tr.querySelectorAll("*")].filter(e => e.children.length === 0 && (e.innerText || "").trim() === "素材" && e.getBoundingClientRect().width > 0); if (!chips.length) return "nochip"; chips[chips.length - 1].click(); return "ok" })()');
380
+ const drawer = await wait(page0, '(__qc.text().indexOf("素材来源") >= 0)', 15000);
381
+ mark('dry', JSON.stringify({ hit: hit, chip: chip, drawer: drawer, names: names.length }));
382
+ return
383
+ }
181
384
  const page = await connect('jinritemai');
182
385
  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(),那会关掉标签页(曾导致整窗退出)
386
+ const res = await addMaterialsViaDrawer(page, aavid, planId, names, { cancelAfterPick: process.argv.includes('--picktest') });
387
+ mark('result', JSON.stringify({ totalVideos: res.totalVideos, submitted: res.submitted, picktest: process.argv.includes('--picktest') }));
388
+ }
389
+
390
+ // 一条龙:新建 → 发布 → 找新计划ID → 详情抽屉加素材
391
+ async function cmdAll() {
392
+ const aavid = process.argv[3], paramsFile = process.argv[4];
393
+ const argv0 = process.argv.slice(0, 2);
394
+ process.argv = argv0.concat(['create', aavid, paramsFile]);
395
+ await cmdCreate();
396
+ process.argv = argv0.concat(['publish']);
397
+ await cmdPublish();
398
+ const page = await connect('jinritemai');
399
+ await page.eval(INJECT);
400
+ const newId = await newestPlanId(page);
401
+ if (!newId) throw new Error('发布后拿不到新计划 ID');
402
+ mark('new-plan', newId);
403
+ process.argv = argv0.concat(['materials', aavid, newId, paramsFile]);
404
+ await cmdMaterials();
218
405
  }
219
406
 
220
407
  async function cmdPublish() {
@@ -227,7 +414,7 @@ async function cmdPublish() {
227
414
  mark('confirm', JSON.stringify(c));
228
415
  const done = await wait(page, 'location.href.includes("overall-prom") && location.href.includes("createSuccess")', 30000);
229
416
  mark('published', done ? 'ok' : 'timeout');
230
- process.exit(done ? 0 : 4);
417
+ if (!done) throw new Error('发布后未跳到 createSuccess');
231
418
  }
232
419
 
233
420
 
@@ -265,7 +452,10 @@ async function cmdClick() {
265
452
  mark('locate', JSON.stringify({ text: text, domLeaves: domCount, shadowTextNodes: shadowHit }));
266
453
  if (!dry) mark('click', JSON.stringify(await clickByText(page, text)));
267
454
  }
268
- const table = { search: cmdSearch, verify: cmdSearch, delete: cmdDelete, create: cmdCreate, materials: cmdMaterials, publish: cmdPublish, click: cmdClick };
455
+ const table = { all: cmdAll, confirm: cmdConfirm, search: cmdSearch, verify: cmdSearch, delete: cmdDelete, create: cmdCreate, materials: cmdMaterials, publish: cmdPublish, click: cmdClick };
269
456
  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); }
457
+ if (!table[cmd]) { console.log('usage: node copy.mjs <all|confirm|search|delete|create|materials|publish|verify|click> ...')
458
+ console.log(' all <aavid> <params.json> 一条龙:新建+发布+素材')
459
+ console.log(' confirm <aavid> <计划ID> 出确认截图+确认单(删除前置)')
460
+ console.log(' materials <aavid> <计划ID> [params.json] [--dry] 详情抽屉加素材'); process.exit(2); }
461
+ try { await table[cmd](); mark('done'); process.exit(0) } catch (e) { console.log('ERR ' + e.message); process.exit(3) }
@@ -0,0 +1,271 @@
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,13 +1,19 @@
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'
1
+ // pick-all.mjs —— 「添加视频」弹窗里把每个抖音号的主页视频全勾上,一次跑完直接点确定(不二次补选)
7
2
  import path from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+ // 用法: node scripts/pick-all.mjs "抖音号名1,抖音号名2,...,抖音号名N"
5
+ // (单号也要带尾逗号:"号名,";不传参时从 out/*.json 读名单)
6
+ // 前提: 已进入某计划的 素材 tab,素材类型=视频,且「添加视频」弹窗已打开
7
+ // 改自技能资产 dsh-qianchuan-toolkit/assets/plan-copy/scripts/pick-all.mjs(用户 2026-11-20 要求的一次跑完规则)
8
+ // 逻辑:
9
+ // 1) 切号 JS click(横向列表坐标点不动,只能 JS click)
10
+ // 2) 切号后轮询等卡片渲染(最多 8s),不要固定 sleep 后立刻取
11
+ // 3) 每张卡片 CDP 真实点击;点完读「已选择 N/200」,没涨就补点一次(漏勾/点空)
12
+ // 4) 某号 0 卡片 → 取消勾选「过滤不良素材」刷新 → 仍为 0 判定该号确实无视频,继续下一个号
13
+ // 5) 全部号点完,一次性点「确定」提交;不再二次进弹窗、不再翻抽屉核对
14
+ import fs from 'node:fs'
8
15
 
9
16
  const PORT = 9222, BASE = 'http://127.0.0.1:' + PORT
10
- // 计划参数快照目录:默认 <数据目录>/out,可用 QC_OUT 覆盖
11
17
  const OUT_DIR = process.env.QC_OUT || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.qianchuan-cruise', 'out')
12
18
  const CARD = '.main-vmok-plugin-create-material-list-card-item'
13
19
  const NAV = '.main-vmok-plugin-tabs__nav-list'
@@ -15,6 +21,7 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
15
21
 
16
22
  function namesFor(adId) {
17
23
  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 || [] } }
24
+ if (!fs.existsSync(OUT_DIR)) return []
18
25
  const files = fs.readdirSync(OUT_DIR).filter((f) => f.endsWith('.json')).map((f) => path.join(OUT_DIR, f))
19
26
  if (!files.length) return []
20
27
  files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)
@@ -40,38 +47,78 @@ const getSel = `(()=>{const t=document.body.innerText.replace(/[ \\t]+/g,' ');co
40
47
  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
48
  const listCards = `(()=>[...document.querySelectorAll('${CARD}')].map(c=>{const w=c.querySelector('[itemid]')||c;return w.getAttribute('itemid')}).filter(Boolean))()`
42
49
  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)}})()`
50
+ 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})()`
51
+ const filterToggle = `(()=>{const i=${filterFind};if(!i)return 'NOBOX';i.click();return 'OK'})()`
43
52
 
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
+ async function pollCards(c, maxMs) {
54
+ const t0 = Date.now(); let ids = []
55
+ while (Date.now() - t0 < maxMs) {
56
+ ids = await ev(c, listCards)
57
+ if (ids.length) return ids
58
+ await sleep(400)
59
+ }
60
+ return ids
61
+ }
53
62
 
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)
63
+ async function selectCards(c, ids) {
64
+ let clicked = 0, retried = 0
61
65
  for (const id of ids) {
62
66
  const p = await ev(c, cardPos(id))
63
67
  if (!p) continue
64
- await sleep(140)
68
+ await sleep(120)
69
+ const before = await ev(c, getSel)
65
70
  await click(c, p.x, p.y)
66
- await sleep(300)
71
+ await sleep(260)
72
+ let after = await ev(c, getSel)
73
+ if (after === before) {
74
+ const p2 = await ev(c, cardPos(id))
75
+ if (p2) { await sleep(120); await click(c, p2.x, p2.y); await sleep(320); retried++ }
76
+ }
77
+ clicked++
67
78
  }
68
- const after = await ev(c, getSel)
69
- log.push({ name, cards: ids.length, before, after, delta: after - before })
79
+ return { clicked, retried }
80
+ }
81
+
82
+
83
+ // 供 copy.mjs 复用:在已打开的「添加视频」弹窗里按名单逐个抖音号全选,返回结构化日志
84
+ export async function pickAllOnTarget(target, names) {
85
+ const c = await connect(target)
86
+ const modalOpen = await ev(c, `(()=>/已选择\\s*\\d+\\/200/.test(document.body.innerText))()`)
87
+ if (!modalOpen) return { error: '「添加视频」弹窗没开,先点「添加视频」' }
88
+
89
+ const log = []
90
+ for (const name of names) {
91
+ const r = await ev(c, clickTab(name))
92
+ if (r !== 'OK') { log.push({ name, err: r }); continue }
93
+ let ids = await pollCards(c, 8000)
94
+ let refreshed = false
95
+ if (!ids.length) {
96
+ const t = await ev(c, filterToggle)
97
+ if (t === 'OK') { refreshed = true; await sleep(1200); ids = await pollCards(c, 12000) }
98
+ }
99
+ const before = await ev(c, getSel)
100
+ let sel = { clicked: 0, retried: 0 }
101
+ if (ids.length) sel = await selectCards(c, ids)
102
+ const after = await ev(c, getSel)
103
+ if (refreshed) { await ev(c, filterToggle); await sleep(600) }
104
+ log.push({ name, cards: ids.length, before, after, delta: after - before, retried: sel.retried, note: ids.length ? undefined : '该号主页无可投视频(取消过滤后仍为空)' })
105
+ }
106
+ 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)]})()`)
107
+ let submitted = false
108
+ if (Array.isArray(okb)) { await click(c, okb[0], okb[1]); await sleep(5000); submitted = true }
109
+ const total = await ev(c, `(()=>{const m=document.body.innerText.match(/共\\d+个视频/);return m?m[0]:null})()`)
110
+ return { ok: true, submitted, totalVideos: total, log }
111
+ }
112
+
113
+ async function main() {
114
+ const arg = process.argv[2]
115
+ const names = arg ? arg.split(/[,,\n]/).map((s) => s.trim()).filter(Boolean) : namesFor(null)
116
+ if (!names.length) { console.log(JSON.stringify({ error: '没有抖音号名单:把名字用逗号串起来传进来' })); process.exit(1) }
117
+ const pages = (await j('/json/list')).filter((t) => t.type === 'page')
118
+ const target = pages.find((p) => p.url.includes('qianchuan')) || pages[0]
119
+ const res = await pickAllOnTarget(target, names)
120
+ if (res.error) { console.log(JSON.stringify(res)); process.exit(1) }
121
+ console.log(JSON.stringify(res, null, 1))
122
+ process.exit(0)
70
123
  }
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)
124
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main()
@@ -0,0 +1,77 @@
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)
@@ -0,0 +1,112 @@
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)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qianchuan-toolkit",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
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
+ }