dsh-qianchuan-toolkit 1.0.5 → 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,5 +1,11 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
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 逐字节一致,本次未改动。
|
|
8
|
+
|
|
3
9
|
## 1.0.5
|
|
4
10
|
|
|
5
11
|
- 修复**「控量中」误判根源**:定位「一键调速」组时原来会「退回第一个含图标的组」,而「素材/人群追投」组也有同款 `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) {
|
|
@@ -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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
|
89
|
-
|
|
90
|
-
await page
|
|
91
|
-
await
|
|
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
|
|
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,92 @@ 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, '
|
|
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
|
+
// 同步下发到 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)); }
|
|
216
|
+
mark('confirm-shot', shot);
|
|
217
|
+
console.log('ROW ' + row);
|
|
218
|
+
console.log('SHOT ' + shot);
|
|
219
|
+
console.log('TOKEN ' + token);
|
|
220
|
+
console.log('-- 硬规则:把下面这行原文发给用户,等用户回「确认删除」后,再用 TOKEN 执行 delete --');
|
|
221
|
+
console.log(' + '>)');
|
|
222
|
+
// 不要 page.close():会关掉标签页
|
|
223
|
+
process.exit(0);
|
|
224
|
+
}
|
|
225
|
+
|
|
119
226
|
async function cmdCreate() {
|
|
120
227
|
const aavid = process.argv[3], p = JSON.parse(fs.readFileSync(process.argv[4], 'utf8'));
|
|
121
228
|
const page = await connect('jinritemai');
|
|
122
229
|
await page.send('Page.navigate', { url: 'https://qianchuan.jinritemai.com/create-ad/overall-product?aavid=' + aavid }, 15000);
|
|
230
|
+
await page.eval(INJECT); // 必须先注入 __qc,否则 ready 判断里的 __qc.text() 直接抛错
|
|
123
231
|
const ready = await wait(page, '/选择投放对象/.test(__qc.text())', 20000);
|
|
124
232
|
if (!ready) throw new Error('新建页未就绪');
|
|
125
|
-
await page.eval(INJECT);
|
|
126
233
|
mark('create-page');
|
|
127
234
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
235
|
+
await wait(page, '/添加商品/.test(__qc.text())', 20000);
|
|
236
|
+
let drawerOpened = false;
|
|
237
|
+
for (let i = 0; i < 3 && !drawerOpened; i++) {
|
|
238
|
+
await page.eval('__qc.clickText("添加商品")');
|
|
239
|
+
drawerOpened = await wait(page, '!!' + PRODUCT_SEARCH, 8000);
|
|
240
|
+
if (!drawerOpened) await page.eval('new Promise(r=>setTimeout(r,1500))');
|
|
241
|
+
}
|
|
242
|
+
if (!drawerOpened) throw new Error('商品抽屉未出现(搜索框没出来)');
|
|
132
243
|
mark('product-drawer');
|
|
133
244
|
|
|
134
|
-
await
|
|
135
|
-
|
|
136
|
-
|
|
245
|
+
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" })()');
|
|
246
|
+
mark('product-filter', filt);
|
|
247
|
+
await sleep(600);
|
|
248
|
+
let rowOk = false;
|
|
249
|
+
for (let i = 0; i < 3 && !rowOk; i++) {
|
|
250
|
+
await focusAndType(page, PRODUCT_SEARCH, p.productId);
|
|
251
|
+
await sleep(600);
|
|
252
|
+
rowOk = await wait(page, '__qc.rowByText(' + JSON.stringify(p.productId) + ')', 7000);
|
|
253
|
+
if (!rowOk) { await pressEnter(page); rowOk = await wait(page, '__qc.rowByText(' + JSON.stringify(p.productId) + ')', 8000); }
|
|
254
|
+
if (!rowOk) await sleep(1000);
|
|
255
|
+
}
|
|
256
|
+
if (!rowOk) throw new Error('商品行未出现(已尝试取消只看可投商品并回车搜索三次)');
|
|
137
257
|
const clicked = await page.eval('__qc.clickRowLabel(' + JSON.stringify(p.productId) + ')');
|
|
138
258
|
if (clicked !== 'ok') throw new Error('商品勾选: ' + clicked);
|
|
139
|
-
const picked = await wait(page, '/已选[^0-9]{0,3}[1-9]
|
|
259
|
+
const picked = await wait(page, '/已选[^0-9]{0,3}[1-9]\\d*\\s*\\/\\s*30/.test(__qc.text())', 4000);
|
|
140
260
|
if (!picked) throw new Error('商品未选中');
|
|
141
261
|
mark('product-picked');
|
|
142
262
|
|
|
143
263
|
await page.eval('__qc.clickText("下一步")');
|
|
144
|
-
const step2 = await wait(page, '
|
|
264
|
+
const step2 = await wait(page, '/手动选择抖音号|为商品添加抖音号|请输入抖音号名称/.test(__qc.text())', 15000);
|
|
145
265
|
if (!step2) throw new Error('抖音号步骤未出现');
|
|
146
266
|
await page.eval('__qc.clickText("手动选择抖音号")');
|
|
147
|
-
await wait(page, '!!' + AWEME_SEARCH,
|
|
267
|
+
const awemeReady = await wait(page, '!!' + AWEME_SEARCH, 12000);
|
|
268
|
+
if (!awemeReady) throw new Error('抖音号搜索框未出现');
|
|
148
269
|
mark('aweme-step');
|
|
149
270
|
|
|
150
271
|
const ids = p.awemeIds || [], names = p.awemeNames || {};
|
|
@@ -176,45 +297,121 @@ async function cmdCreate() {
|
|
|
176
297
|
// 不要 page.close():会关掉标签页
|
|
177
298
|
}
|
|
178
299
|
|
|
300
|
+
// ---------- 规则(用户 2026-11-20 定,写进代码)----------
|
|
301
|
+
// 1) 页面上任何遮挡式引导/气泡(「建议您开启…」「我知道了」)必须先关掉,再做下一步;
|
|
302
|
+
// 2) 素材唯一合法路径:列表 → 搜计划ID → 该行「素材」入口(详情抽屉)→ 素材 → 素材类型「视频」→ 添加视频
|
|
303
|
+
// → 逐抖音号全选 → 一次确定。禁止走 create-ad?type=e 编辑页加素材。
|
|
304
|
+
const BUBBLE_TEXTS = ['我知道了', '知道了', '不再提示', '跳过'];
|
|
305
|
+
|
|
306
|
+
async function dismissBubbles(page, depth = 0) {
|
|
307
|
+
if (depth > 3) return 'deeper';
|
|
308
|
+
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" })()');
|
|
309
|
+
if (r === 'dismissed') { await sleep(900); return dismissBubbles(page, depth + 1) }
|
|
310
|
+
return r
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// 列表第一行 = 最新创建的计划(列表按创建时间倒序)
|
|
314
|
+
async function newestPlanId(page) {
|
|
315
|
+
const raw = await page.eval('(() => { const tr = document.querySelector("tbody tr"); return tr ? tr.innerText : "" })()');
|
|
316
|
+
const m = String(raw).match(/ID[::]\s*(\d{10,})/);
|
|
317
|
+
return m ? m[1] : null
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// 素材:只在详情页抽屉里加(用户指定路径)
|
|
321
|
+
async function addMaterialsViaDrawer(page, aavid, planId, names, opts = {}) {
|
|
322
|
+
await openList(page, aavid);
|
|
323
|
+
await dismissBubbles(page);
|
|
324
|
+
mark('list-ready');
|
|
325
|
+
const hit = (await searchPlan(page, planId)) !== 'miss';
|
|
326
|
+
if (!hit) throw new Error('搜索该 ID 不是唯一 1 条(可见行数不唯一或窗口里没等到结果),拒绝继续');
|
|
327
|
+
mark('search-unique');
|
|
328
|
+
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" })()');
|
|
329
|
+
if (chip !== 'ok') throw new Error('打不开素材入口: ' + chip);
|
|
330
|
+
const opened = await wait(page, '(__qc.text().indexOf("保障历史") >= 0)', 12000);
|
|
331
|
+
if (!opened) throw new Error('详情抽屉未打开');
|
|
332
|
+
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" })()');
|
|
333
|
+
mark('material-tab', tabClick);
|
|
334
|
+
await sleep(1500);
|
|
335
|
+
const drawer = await wait(page, '(__qc.text().indexOf("素材来源") >= 0)', 15000);
|
|
336
|
+
if (!drawer) throw new Error('详情抽屉-素材 tab 未就绪');
|
|
337
|
+
await dismissBubbles(page);
|
|
338
|
+
mark('drawer-material');
|
|
339
|
+
const typeOk = await wait(page, '(__qc.text().indexOf("素材类型") >= 0)', 8000);
|
|
340
|
+
if (!typeOk) throw new Error('素材类型行未出现');
|
|
341
|
+
const srcPick = await clickByText(page, '自选素材');
|
|
342
|
+
mark('material-src', JSON.stringify(srcPick));
|
|
343
|
+
await sleep(900);
|
|
344
|
+
const typePick = await clickByText(page, '视频');
|
|
345
|
+
mark('material-type', JSON.stringify(typePick));
|
|
346
|
+
await sleep(1500);
|
|
347
|
+
const hasBtn = await wait(page, '(__qc.text().indexOf("添加视频") >= 0)', 10000);
|
|
348
|
+
if (!hasBtn) throw new Error('选中 自选素材/视频 后仍没有「添加视频」按钮');
|
|
349
|
+
const clicked = await clickByText(page, '添加视频');
|
|
350
|
+
if (clicked.click !== 'ok') throw new Error('点不到「添加视频」: ' + JSON.stringify(clicked));
|
|
351
|
+
const popup = await wait(page, '(__qc.text().indexOf("已选择") >= 0)', 15000);
|
|
352
|
+
if (!popup) throw new Error('「添加视频」弹窗未打开');
|
|
353
|
+
mark('popup');
|
|
354
|
+
const targets = (await listPages()).filter((t) => t.type === 'page' && (t.url || '').indexOf('qianchuan') >= 0);
|
|
355
|
+
if (!targets.length) throw new Error('找不到千川标签页');
|
|
356
|
+
// 绑定到当前驱动的那个标签页(有 id 就按 id,没有就按连接时的 URL 兜底)
|
|
357
|
+
const tgt = (page.id && targets.find((t) => t.id === page.id)) || targets.find((t) => t.url === page.url) || targets[0];
|
|
358
|
+
const res = await pickAllOnTarget(tgt, names);
|
|
359
|
+
if (res.error) throw new Error(res.error);
|
|
360
|
+
mark('pick', JSON.stringify(res.log));
|
|
361
|
+
if (opts.cancelAfterPick) {
|
|
362
|
+
// 验证用:勾完不提交,直接取消,计划数据不变
|
|
363
|
+
const cx = await clickByText(page, '取消');
|
|
364
|
+
mark('cancelled', JSON.stringify(cx));
|
|
365
|
+
return res
|
|
366
|
+
}
|
|
367
|
+
const applied = await wait(page, '(__qc.text().split(" ").join("").indexOf("个视频") >= 0)', 8000);
|
|
368
|
+
mark('materials-applied', applied ? 'ok' : 'timeout');
|
|
369
|
+
return res
|
|
370
|
+
}
|
|
371
|
+
|
|
179
372
|
async function cmdMaterials() {
|
|
180
|
-
const
|
|
373
|
+
const aavid = process.argv[3], planId = process.argv[4], paramsFile = process.argv[5];
|
|
374
|
+
const dry = process.argv.includes('--dry');
|
|
375
|
+
if (!aavid || !planId) throw new Error('用法: node copy.mjs materials <aavid> <计划ID> [params.json] [--dry]');
|
|
376
|
+
const p = paramsFile ? JSON.parse(fs.readFileSync(paramsFile, 'utf8')) : {};
|
|
377
|
+
const names = Object.values(p.awemeNames || {});
|
|
378
|
+
if (!names.length) throw new Error('params.json 里没有 awemeNames,拿不到抖音号名单');
|
|
379
|
+
if (dry) {
|
|
380
|
+
const page0 = await connect('jinritemai');
|
|
381
|
+
mark('connected');
|
|
382
|
+
await openList(page0, aavid);
|
|
383
|
+
mark('list-ready');
|
|
384
|
+
await dismissBubbles(page0);
|
|
385
|
+
const hit = (await searchPlan(page0, planId)) !== 'miss';
|
|
386
|
+
mark('submitted', hit ? 'hit' : 'miss');
|
|
387
|
+
const rowsInfo = String(1);
|
|
388
|
+
mark('rows', rowsInfo);
|
|
389
|
+
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" })()');
|
|
390
|
+
const drawer = await wait(page0, '(__qc.text().indexOf("素材来源") >= 0)', 15000);
|
|
391
|
+
mark('dry', JSON.stringify({ hit: hit, chip: chip, drawer: drawer, names: names.length }));
|
|
392
|
+
return
|
|
393
|
+
}
|
|
181
394
|
const page = await connect('jinritemai');
|
|
182
395
|
await page.eval(INJECT);
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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(),那会关掉标签页(曾导致整窗退出)
|
|
396
|
+
const res = await addMaterialsViaDrawer(page, aavid, planId, names, { cancelAfterPick: process.argv.includes('--picktest') });
|
|
397
|
+
mark('result', JSON.stringify({ totalVideos: res.totalVideos, submitted: res.submitted, picktest: process.argv.includes('--picktest') }));
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// 一条龙:新建 → 发布 → 找新计划ID → 详情抽屉加素材
|
|
401
|
+
async function cmdAll() {
|
|
402
|
+
const aavid = process.argv[3], paramsFile = process.argv[4];
|
|
403
|
+
const argv0 = process.argv.slice(0, 2);
|
|
404
|
+
process.argv = argv0.concat(['create', aavid, paramsFile]);
|
|
405
|
+
await cmdCreate();
|
|
406
|
+
process.argv = argv0.concat(['publish']);
|
|
407
|
+
await cmdPublish();
|
|
408
|
+
const page = await connect('jinritemai');
|
|
409
|
+
await page.eval(INJECT);
|
|
410
|
+
const newId = await newestPlanId(page);
|
|
411
|
+
if (!newId) throw new Error('发布后拿不到新计划 ID');
|
|
412
|
+
mark('new-plan', newId);
|
|
413
|
+
process.argv = argv0.concat(['materials', aavid, newId, paramsFile]);
|
|
414
|
+
await cmdMaterials();
|
|
218
415
|
}
|
|
219
416
|
|
|
220
417
|
async function cmdPublish() {
|
|
@@ -227,7 +424,7 @@ async function cmdPublish() {
|
|
|
227
424
|
mark('confirm', JSON.stringify(c));
|
|
228
425
|
const done = await wait(page, 'location.href.includes("overall-prom") && location.href.includes("createSuccess")', 30000);
|
|
229
426
|
mark('published', done ? 'ok' : 'timeout');
|
|
230
|
-
|
|
427
|
+
if (!done) throw new Error('发布后未跳到 createSuccess');
|
|
231
428
|
}
|
|
232
429
|
|
|
233
430
|
|
|
@@ -265,7 +462,10 @@ async function cmdClick() {
|
|
|
265
462
|
mark('locate', JSON.stringify({ text: text, domLeaves: domCount, shadowTextNodes: shadowHit }));
|
|
266
463
|
if (!dry) mark('click', JSON.stringify(await clickByText(page, text)));
|
|
267
464
|
}
|
|
268
|
-
const table = { search: cmdSearch, verify: cmdSearch, delete: cmdDelete, create: cmdCreate, materials: cmdMaterials, publish: cmdPublish, click: cmdClick };
|
|
465
|
+
const table = { all: cmdAll, confirm: cmdConfirm, search: cmdSearch, verify: cmdSearch, delete: cmdDelete, create: cmdCreate, materials: cmdMaterials, publish: cmdPublish, click: cmdClick };
|
|
269
466
|
const cmd = process.argv[2];
|
|
270
|
-
if (!table[cmd]) { console.log('usage: node copy.mjs <search|delete|create|materials|publish|verify> ...')
|
|
271
|
-
|
|
467
|
+
if (!table[cmd]) { console.log('usage: node copy.mjs <all|confirm|search|delete|create|materials|publish|verify|click> ...')
|
|
468
|
+
console.log(' all <aavid> <params.json> 一条龙:新建+发布+素材')
|
|
469
|
+
console.log(' confirm <aavid> <计划ID> 出确认截图+确认单(删除前置)')
|
|
470
|
+
console.log(' materials <aavid> <计划ID> [params.json] [--dry] 详情抽屉加素材'); process.exit(2); }
|
|
471
|
+
try { await table[cmd](); mark('done'); process.exit(0) } catch (e) { console.log('ERR ' + e.message); process.exit(3) }
|
|
@@ -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
|
+
}
|
|
@@ -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
|
-
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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
|
-
|
|
55
|
-
|
|
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(
|
|
68
|
+
await sleep(120)
|
|
69
|
+
const before = await ev(c, getSel)
|
|
65
70
|
await click(c, p.x, p.y)
|
|
66
|
-
await sleep(
|
|
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
|
-
|
|
69
|
-
|
|
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()
|