dsh-qianchuan-toolkit 1.0.6 → 1.0.8
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 +12 -11
- package/assets/live-control/scripts/cdp-lib.mjs +5 -1
- package/assets/live-control/scripts/hourly.mjs +125 -55
- package/assets/plan-copy/scripts/copy.mjs +10 -0
- package/assets/plan-copy/scripts/notify-media.mjs +83 -0
- package/package.json +2 -2
- package/assets/live-control/scripts/cdp-lib.mjs.bak-20261120 +0 -171
- package/assets/plan-copy/scripts/copy.mjs.bak-20261120 +0 -271
- package/assets/plan-copy/scripts/pick-all.mjs.bak +0 -77
- package/assets/plan-copy/scripts/pick-all.mjs.bak-20261120 +0 -112
package/CHANGELOG.md
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
-
## 1.0.
|
|
4
|
-
|
|
5
|
-
-
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
3
|
+
## 1.0.8
|
|
4
|
+
|
|
5
|
+
- **判定顺序修正(重要)**:原来看到行上不是「+」(⏸ 或找不到一键调速组)就先去点弹窗、查日志、报异常,**没有先算这小时该不该控**。现在固定为「刷新 → 读数据 → 先算要不要动」:未在投 / 没花钱 / 小时消耗未超过 `minCost` / ROI 达标一律就此结束,绝不为「看看是不是在控量」去点弹窗查日志。修掉 2026-11-20 16:15 那轮「消耗仅 83.17 元(门槛 200)却排查后报异常轮空」。
|
|
6
|
+
- **修复「刷新后没找到该行」根因**:`cdp-lib.mjs` 的 `page.url` 是**连接时的快照**,导航后仍返回旧值,而 watch 整轮复用同一连接。读完日志导航回列表时它仍写着列表页,`refreshList` 误判「已在列表」直接 reload,结果 reload 的其实是详情页 → 15s 等不到行 → 误报异常。现在新增 `page.href()`(实时 `location.href`);`refreshList` 用实时 `location.pathname` 判定并等待真正回到列表;`readRecentControl` 读完日志必须等回到列表才返回;`readRowOf` 改为最多重试 10s,读不到时打印当前页面路径与列表里的行,便于自证。
|
|
7
|
+
- **排查规则写进代码(最高优先级)**:新增 `resolveState()` —— 遇到「列表不是 +」按顺序执行:① 截图留证(`<QC_HOME>/shots/`)→ ② 日志逻辑自查 → ③ 刷新重读 → ④ 循环最多 170s 尽量解决 → ⑤ 仍查不清才报异常。异常文案带截图路径,并在 `errors.jsonl` 记录 `kind / msg / shot / evidence`,不再「一看不对就报异常轮空」。
|
|
8
|
+
- **控量中调度**:读到控量结束时间后按「结束 + 1 分钟」加跑一轮;若某个节点(:15/:30/:45/:55)落在「结束前 150s ~ 结束后 20s」,一律挪到「结束 + 60s」,不再卡在结束那一秒巡航。
|
|
9
|
+
|
|
10
|
+
## 1.0.7
|
|
11
|
+
|
|
12
|
+
- **计划复制**:`copy.mjs` 增加**删除前确认单**(`confirm` 子命令 + 令牌校验),没有确认单 `delete` 拒绝执行;新增 `notify-media.mjs`,删除前截图自动推 **QQ 官方机器人 + 企业微信**(三行格式:`【删除前确认】` + 名称 + ID);`pick-all.mjs` 改为按抖音号轮询、取消失败重试,修掉「卡片已渲染但已选为 0」的漏选。
|
|
13
|
+
- **CDP 层**:`cdp-lib.mjs` 的 `page` 带 `id`,报错时附带页面标题/URL 上下文,多标签页排查不再靠猜。
|
|
14
|
+
- 巡航部分(`live-control`)与 1.0.5 逐字节一致,本次未改动。
|
|
14
15
|
|
|
15
16
|
## 1.0.5
|
|
16
17
|
|
|
@@ -132,11 +132,15 @@ export async function connect(match = 'jinritemai', { autoDialog = true, id = nu
|
|
|
132
132
|
await rawSend('Page.enable', {}).catch(() => {})
|
|
133
133
|
|
|
134
134
|
return {
|
|
135
|
-
url: page.url,
|
|
135
|
+
url: page.url, // 连接时的快照,导航后不会更新 —— 判断「现在在哪一页」必须用 href()
|
|
136
136
|
title: page.title,
|
|
137
137
|
id: page.id,
|
|
138
138
|
dialogs,
|
|
139
139
|
send: rawSend,
|
|
140
|
+
async href(fallback) {
|
|
141
|
+
// 实时 URL。page.url 是连接时快照,导航后仍是旧值(2026-11-20 16:15 误判「刷新后没找到该行」的根因)
|
|
142
|
+
try { const v = await this.eval('location.href', 8000); return v ? String(v) : (fallback || this.url) } catch (e) { return fallback || this.url }
|
|
143
|
+
},
|
|
140
144
|
async eval(expr, timeoutMs = EVAL_TIMEOUT) {
|
|
141
145
|
const r = await rawSend('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true }, timeoutMs)
|
|
142
146
|
if (r.exceptionDetails) throw new CdpError('eval 异常: ' + r.exceptionDetails.text + ' ' + ((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || '') + ' ||EXPR|| ' + String(expr).slice(0, 240))
|
|
@@ -210,45 +210,44 @@ async function gatherAccount(group) {
|
|
|
210
210
|
if (!hr.rows.length) return { action: 'skip', reason: 'no-spend:本小时还没有消耗数据(刚开播或还没花钱)' }
|
|
211
211
|
return judgeHourly(target, hr, rule)
|
|
212
212
|
}
|
|
213
|
+
// 执行顺序(用户定的,别再改):
|
|
214
|
+
// 刷新 → 读数据 → 先把「这小时要不要动」算出来;
|
|
215
|
+
// 不需要动(消耗没过 minCost / 未在投 / ROI 达标 / 没花钱)→ 到此为止,
|
|
216
|
+
// 绝不为「看看是不是在控量」去点弹窗、查日志、报异常(2026-11-20 16:15 误报就是这样来的)。
|
|
217
|
+
// 需要动、但行上不是「+」→ 才走排查流程(截图 → 日志 → 刷新 → 3 分钟)。
|
|
213
218
|
let d
|
|
214
219
|
if (target.delivery === 'standby') d = { action: 'skip', reason: 'standby:该抖音号实际由 ' + (other ? other.key + '(' + entryLabel(other.entry) + ')' : '其他账号') + ' 投放,此账号仅备用,不控' }
|
|
215
220
|
else if (!row) d = { action: 'skip', reason: 'row-not-found:列表里没找到这个抖音号(是否已解绑/改名?)' }
|
|
216
|
-
else
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
log('
|
|
223
|
-
await
|
|
224
|
-
const r2 = await readRowOf(page, target)
|
|
225
|
-
mode = r2 ? r2.mode : 'norow'
|
|
226
|
-
log(' 刷新后 mode=' + mode)
|
|
227
|
-
}
|
|
228
|
-
if (mode === 'pause') {
|
|
229
|
-
const pr = await resolvePause(page, acct, target, (target.ads || [])[0] || null)
|
|
221
|
+
else {
|
|
222
|
+
const want = normalDecision()
|
|
223
|
+
if (want.action !== 'control') d = want
|
|
224
|
+
else if (row.mode === 'plus' || row.mode === 'none') d = want
|
|
225
|
+
else {
|
|
226
|
+
// 该控量,但行上是 ⏸ 或组找不到:按排查规则查清楚再决定
|
|
227
|
+
log(' 判定要控量,但当前 mode=' + row.mode + ',先排查能不能创建…')
|
|
228
|
+
const pr = await resolveState(page, acct, target, (hr.ads[0] || (target.ads || [])[0] || null))
|
|
230
229
|
if (pr.state === 'controlling') {
|
|
231
|
-
const stale = pr.endAt < Date.now() -
|
|
230
|
+
const stale = pr.endAt < Date.now() - 120000
|
|
232
231
|
d = {
|
|
233
232
|
action: 'skip',
|
|
234
|
-
reason: 'controlling:正在控量 ' + (pr.startText || '') + ' ~ ' + (pr.endText || '') + (pr.budget ? '(预算 ' + pr.budget + ' 元)' : '') + (stale ? ' ——
|
|
233
|
+
reason: 'controlling:正在控量 ' + (pr.startText || '') + ' ~ ' + (pr.endText || '') + (pr.budget ? '(预算 ' + pr.budget + ' 元)' : '') + (stale ? ' —— 异常:结束时间已过 2 分钟,⏸ 图标仍在(疑似残留)' : ',结束后 +1 分钟加跑一轮') + '[依据:' + pr.source + ']',
|
|
235
234
|
endAt: pr.endAt,
|
|
236
235
|
pauseInfo: { startText: pr.startText, endText: pr.endText, budget: pr.budget },
|
|
237
236
|
anomaly: stale ? 'pause-stale' : undefined,
|
|
237
|
+
evidence: pr.evidence, shot: pr.shot,
|
|
238
238
|
}
|
|
239
239
|
} else if (pr.state === 'free') {
|
|
240
|
-
log('
|
|
241
|
-
d =
|
|
240
|
+
log(' 排查确认没有控量任务(mode=' + pr.mode + '),按正常规则继续 → 控量')
|
|
241
|
+
d = want
|
|
242
242
|
} else {
|
|
243
|
-
d = {
|
|
243
|
+
d = {
|
|
244
|
+
action: 'skip', anomaly: 'pause-unresolved',
|
|
245
|
+
reason: '异常:列表不是「+」(mode=' + row.mode + '),截图/日志/刷新排查 3 分钟仍未查清(' + pr.reason + '),本轮轮空',
|
|
246
|
+
evidence: pr.evidence, shot: pr.shot,
|
|
247
|
+
}
|
|
244
248
|
}
|
|
245
|
-
} else if (mode === 'unknown' || mode === 'norow') {
|
|
246
|
-
d = { action: 'skip', anomaly: 'no-speed-group', reason: '异常:刷新后仍找不到「一键调速」组(可能改版),无法判断能否控量,本轮轮空' }
|
|
247
|
-
} else {
|
|
248
|
-
d = normalDecision()
|
|
249
249
|
}
|
|
250
250
|
}
|
|
251
|
-
else d = normalDecision()
|
|
252
251
|
|
|
253
252
|
const rec = {
|
|
254
253
|
target: target.id, aweme: target.awemeName, uid: target.awemeUniqueId || target.awemeName,
|
|
@@ -259,7 +258,11 @@ async function gatherAccount(group) {
|
|
|
259
258
|
rule: { roiFloor: rule.roiFloor, budget: rule.budget }, decision: d,
|
|
260
259
|
}
|
|
261
260
|
out.decisions.push(rec)
|
|
262
|
-
if (d.anomaly)
|
|
261
|
+
if (d.anomaly) {
|
|
262
|
+
out.anomalies.push({ aweme: rec.aweme, kind: d.anomaly, msg: d.reason, hour: hr.hour, shot: d.shot || null, evidence: d.evidence || [] })
|
|
263
|
+
// 异常必须有可回溯材料:截图路径 + 证据链写进 errors.jsonl
|
|
264
|
+
jl(P.errors, { ts: new Date().toISOString(), account: acct.key, aweme: rec.aweme, kind: d.anomaly, msg: d.reason, shot: d.shot || null, evidence: d.evidence || [] })
|
|
265
|
+
}
|
|
263
266
|
log(' ' + '[' + rec.entryLabel + '] ' + rec.aweme + ' [' + (row ? row.status : '未找到') + '] ' + hr.hour + '时 消耗 ' + rec.cost + ' 净成交 ' + rec.gmv + ' ROI ' + rec.roi + ' → ' + d.action + ' ' + (d.reason || ''))
|
|
264
267
|
}
|
|
265
268
|
// 逻辑自查:判定与现场证据不自洽就是异常(不只是「轮空」)
|
|
@@ -331,12 +334,25 @@ async function verifyLog(page, acct, o) {
|
|
|
331
334
|
return { ms: Date.now() - t0, verified: checks.budget && checks.hours && checks.time, checks, row, rows: rows.slice(0, 3), detail: JSON.parse(head) }
|
|
332
335
|
}
|
|
333
336
|
|
|
337
|
+
// ---------- 当前页面判定 ----------
|
|
338
|
+
// 绝不能用 page.url:那是连接时的快照,导航之后仍返回旧值。
|
|
339
|
+
// 2026-11-20 16:15 事故就是它:读完日志导航回列表时 page.url 还写着列表页,
|
|
340
|
+
// refreshList 以为「已在列表」直接 reload,结果 reload 的是详情页 → 15s 读不到行 → 误报异常。
|
|
341
|
+
async function hrefOf(page) { return page.href ? page.href() : page.url }
|
|
342
|
+
function pathOf(u) { try { return new URL(u).pathname } catch (e) { return '' } }
|
|
343
|
+
|
|
334
344
|
// ---------- 刷新列表(唯一入口:强制忽略缓存 + 等新文档 + 等图标就绪) ----------
|
|
335
|
-
async function refreshList(page, acct) {
|
|
336
|
-
const wantPath =
|
|
337
|
-
|
|
345
|
+
async function refreshList(page, acct, why = '') {
|
|
346
|
+
const wantPath = pathOf(listUrl(acct))
|
|
347
|
+
let href = await hrefOf(page)
|
|
348
|
+
if (pathOf(href) !== wantPath) {
|
|
349
|
+
log(' [' + acct.key + '] 当前不在列表页(' + (pathOf(href) || '未知') + ')→ 先回到列表' + (why ? ';原因:' + why : ''))
|
|
338
350
|
await page.send('Page.navigate', { url: listUrl(acct) }).catch(() => {})
|
|
351
|
+
// 等确实落到列表页;判据用实时 location.pathname,不用 page.url
|
|
352
|
+
await pollEval(page, 'location.pathname', (v) => String(v) === wantPath, 12000, 250)
|
|
339
353
|
await sleep(600)
|
|
354
|
+
href = await hrefOf(page)
|
|
355
|
+
if (pathOf(href) !== wantPath) { log(' [' + acct.key + '] 回列表页失败,仍在 ' + (pathOf(href) || '未知')); return false }
|
|
340
356
|
}
|
|
341
357
|
let origin0 = null
|
|
342
358
|
try { origin0 = String(await page.eval('performance.timeOrigin')) } catch (e) {}
|
|
@@ -345,23 +361,46 @@ async function refreshList(page, acct) {
|
|
|
345
361
|
await pollEval(page, 'performance.timeOrigin', (v) => v && String(v) !== origin0, 12000, 200)
|
|
346
362
|
await sleep(300)
|
|
347
363
|
const wantLayout = acct.entry === 'square' ? 'square' : 'uni-prom'
|
|
348
|
-
|
|
364
|
+
const ready = !!(await pollEval(page, expr('row-state.js'), (s) => {
|
|
349
365
|
try {
|
|
350
366
|
const v = JSON.parse(s)
|
|
351
367
|
if (!v || !v.hasAwemeCol || !v.iconsReady) return false
|
|
352
368
|
if (v.layout !== wantLayout) return false
|
|
353
|
-
if (new URL(page.url).pathname !== wantPath) return false
|
|
354
369
|
return (v.rows || []).some((r) => r.aweme && String(r.aweme).trim().length > 1)
|
|
355
370
|
} catch (e) { return false }
|
|
356
371
|
}, 15000, 350))
|
|
372
|
+
const nowPath = pathOf(await hrefOf(page))
|
|
373
|
+
if (!ready || nowPath !== wantPath) {
|
|
374
|
+
log(' [' + acct.key + '] 刷新后未就绪(页面 ' + (nowPath || '未知') + ',row-state ' + (ready ? 'ok' : '未就绪') + ')')
|
|
375
|
+
return false
|
|
376
|
+
}
|
|
377
|
+
return true
|
|
357
378
|
}
|
|
358
379
|
|
|
359
380
|
function rowMatch(rows, target) {
|
|
360
381
|
return (rows || []).find((r) => (target.awemeUniqueId && r.aweme === target.awemeUniqueId) || r.aweme === target.awemeName || (target.awemeName && r.aweme.includes(target.awemeName.slice(0, 4)))) || null
|
|
361
382
|
}
|
|
362
383
|
|
|
363
|
-
|
|
364
|
-
|
|
384
|
+
// 重读行:单次读太脆(SPA 正在重渲染时会读到空表),改为最多重试 timeoutMs;
|
|
385
|
+
// 读不到时把「当前页面路径 / 列表里有哪几行」打进日志,出问题能自证,不再只写「没找到该行」。
|
|
386
|
+
async function readRowOf(page, target, timeoutMs = 10000) {
|
|
387
|
+
const t0 = Date.now()
|
|
388
|
+
let lastRows = []
|
|
389
|
+
let sawTable = false
|
|
390
|
+
while (Date.now() - t0 < timeoutMs) {
|
|
391
|
+
try {
|
|
392
|
+
const v = JSON.parse(await page.eval(expr('row-state.js')))
|
|
393
|
+
lastRows = v.rows || []
|
|
394
|
+
if (v.hasAwemeCol) sawTable = true
|
|
395
|
+
const hit = rowMatch(lastRows, target)
|
|
396
|
+
if (hit) return hit
|
|
397
|
+
if (sawTable) return null // 表格已就绪且确实没有这一行
|
|
398
|
+
} catch (e) {}
|
|
399
|
+
await sleep(400)
|
|
400
|
+
}
|
|
401
|
+
if (lastRows.length) log(' 重读 ' + Math.round(timeoutMs / 1000) + 's 没有该行;列表 ' + lastRows.length + ' 行:' + lastRows.map((r) => r.aweme).slice(0, 8).join(' / '))
|
|
402
|
+
else log(' 重读 ' + Math.round(timeoutMs / 1000) + 's 仍读不到列表;当前页面 ' + (pathOf(await hrefOf(page)) || '未知'))
|
|
403
|
+
return null
|
|
365
404
|
}
|
|
366
405
|
|
|
367
406
|
// 日志闭环:读详情页「日志」里最近一条「一键控量」,用它反推这次控量是否还在有效期内。
|
|
@@ -371,7 +410,11 @@ async function readRecentControl(page, acct, adId) {
|
|
|
371
410
|
try {
|
|
372
411
|
await page.send('Page.navigate', { url: detailUrl(acct.aavid, adId) })
|
|
373
412
|
const raw = await pollEval(page, expr('plan-log.js'), (v) => { try { return (JSON.parse(v).rows || []).length > 0 } catch (e) { return false } }, 12000)
|
|
413
|
+
// 必须等真的回到列表页再往下走(原来是不等就返回,调用方以为还在列表)
|
|
414
|
+
const wantPath = pathOf(listUrl(acct))
|
|
374
415
|
await page.send('Page.navigate', { url: listUrl(acct) }).catch(() => {})
|
|
416
|
+
await pollEval(page, 'location.pathname', (v) => String(v) === wantPath, 12000, 250)
|
|
417
|
+
await sleep(400)
|
|
375
418
|
if (!raw) return { ok: false, err: 'no-log-rows' }
|
|
376
419
|
const rows = JSON.parse(raw).rows || []
|
|
377
420
|
const row = rows.find((r) => /新建/.test(r.type) && /一键控量/.test(r.content))
|
|
@@ -384,39 +427,57 @@ async function readRecentControl(page, acct, adId) {
|
|
|
384
427
|
} catch (e) { return { ok: false, err: e.message } }
|
|
385
428
|
}
|
|
386
429
|
|
|
387
|
-
//
|
|
388
|
-
//
|
|
389
|
-
//
|
|
390
|
-
//
|
|
391
|
-
//
|
|
392
|
-
|
|
430
|
+
// ---------- 出了问题时的排查(用户规则,写死在代码里,优先级最高) ----------
|
|
431
|
+
// 遇到问题 → ① 截图留证 → ② 日志逻辑自查 → ③ 刷新界面复核 → ④ 尽量解决
|
|
432
|
+
// → ⑤ 3 分钟还没解决,才报异常。
|
|
433
|
+
// 「列表显示控量中但读不到结束时间」「找不到一键调速组」都走这里,
|
|
434
|
+
// 绝不允许一看不对就报异常、直接轮空。
|
|
435
|
+
const INVESTIGATE_MS = 170000 // 约 3 分钟
|
|
436
|
+
async function resolveState(page, acct, target, adId) {
|
|
393
437
|
const t0 = Date.now()
|
|
394
|
-
const
|
|
438
|
+
const ev = [] // 证据链(进日志、异常文案、errors.jsonl)
|
|
439
|
+
let shot = null
|
|
395
440
|
const fmt = (ms) => new Date(ms).toLocaleString('zh-CN')
|
|
396
|
-
|
|
441
|
+
|
|
442
|
+
// ① 截图留证(只在「出问题」时拍,不是每轮都拍,避免频繁操作)
|
|
443
|
+
try {
|
|
444
|
+
const dir = path.join(SHOTS, 'shots')
|
|
445
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
446
|
+
const f = path.join(dir, new Date().toISOString().replace(/[:.]/g, '-') + '-' + (target.awemeUniqueId || target.id || 'aweme') + '.png')
|
|
447
|
+
shot = await page.shot(f)
|
|
448
|
+
ev.push('截图 ' + f)
|
|
449
|
+
log(' 已截图留证:' + f)
|
|
450
|
+
} catch (e) { ev.push('截图失败 ' + e.message) }
|
|
451
|
+
|
|
452
|
+
// ②③ 读弹窗 → 查日志 → 刷新后重读行;每一步都记进证据链
|
|
453
|
+
const step = async (tag) => {
|
|
397
454
|
const pi = await readPauseInfo(page, target.awemeName)
|
|
398
|
-
if (pi && pi.ok && pi.endAt) return { state: 'controlling', startText: pi.startText, endText: pi.endText, endAt: pi.endAt, budget: pi.budget, source: '弹窗/' + tag }
|
|
399
|
-
|
|
455
|
+
if (pi && pi.ok && pi.endAt) return { state: 'controlling', startText: pi.startText, endText: pi.endText, endAt: pi.endAt, budget: pi.budget, source: '弹窗/' + tag, evidence: ev, shot }
|
|
456
|
+
ev.push('弹窗(' + tag + '):' + ((pi && pi.reason) || 'unknown'))
|
|
400
457
|
const lg = await readRecentControl(page, acct, adId)
|
|
401
458
|
if (lg && lg.ok && lg.endAt > Date.now()) {
|
|
402
|
-
return { state: 'controlling', startAt: lg.startAt, endAt: lg.endAt, startText: fmt(lg.startAt), endText: fmt(lg.endAt), budget: lg.budget, source: '日志/' + tag }
|
|
459
|
+
return { state: 'controlling', startAt: lg.startAt, endAt: lg.endAt, startText: fmt(lg.startAt), endText: fmt(lg.endAt), budget: lg.budget, source: '日志/' + tag, evidence: ev, shot }
|
|
403
460
|
}
|
|
404
|
-
|
|
461
|
+
ev.push('日志(' + tag + '):' + (lg && lg.ok ? '最近一条已结束 ' + fmt(lg.endAt) : ((lg && lg.err) || 'none')))
|
|
462
|
+
const row = await readRowOf(page, target)
|
|
463
|
+
if (!row) { ev.push('刷新(' + tag + '):没读到该行(页面 ' + (pathOf(await hrefOf(page)) || '未知') + ')'); return null }
|
|
464
|
+
ev.push('刷新(' + tag + '):mode=' + row.mode)
|
|
465
|
+
// 「+」回来了 / 组里既无 ⏸ 也禁用 → 没有控量任务,按正常规则继续(该控就控)
|
|
466
|
+
if (row.mode === 'plus') return { state: 'free', mode: 'plus', evidence: ev, shot }
|
|
467
|
+
if (row.mode === 'none') return { state: 'free', mode: 'none', evidence: ev, shot }
|
|
405
468
|
return null
|
|
406
469
|
}
|
|
407
|
-
|
|
470
|
+
|
|
471
|
+
let r = await step('首次')
|
|
408
472
|
if (r) return r
|
|
409
|
-
while (Date.now() - t0 <
|
|
410
|
-
log(' 排查中:刷新列表后重读(已用 ' + Math.round((Date.now() - t0) / 1000) + 's
|
|
411
|
-
await refreshList(page, acct)
|
|
412
|
-
|
|
413
|
-
if (!row) { tried.push('刷新:没找到该行'); break }
|
|
414
|
-
if (row.mode !== 'pause') return { state: 'free', mode: row.mode, via: 'refresh' }
|
|
415
|
-
r = await grab('刷新后')
|
|
473
|
+
while (Date.now() - t0 < INVESTIGATE_MS) {
|
|
474
|
+
log(' 排查中:刷新列表后重读(已用 ' + Math.round((Date.now() - t0) / 1000) + 's,上限 3 分钟)…')
|
|
475
|
+
await refreshList(page, acct, '排查「控量中/找不到组」')
|
|
476
|
+
r = await step('刷新后')
|
|
416
477
|
if (r) return r
|
|
417
478
|
await sleep(2500)
|
|
418
479
|
}
|
|
419
|
-
return { state: 'unknown', reason:
|
|
480
|
+
return { state: 'unknown', evidence: ev, shot, reason: ev.join(' / ') }
|
|
420
481
|
}
|
|
421
482
|
|
|
422
483
|
// ---------- 执行阶段 ----------
|
|
@@ -501,7 +562,7 @@ async function reportRound(i, recs, nextAt) {
|
|
|
501
562
|
const anomalies = []
|
|
502
563
|
for (const rec of recs) {
|
|
503
564
|
if (rec.err) anomalies.push({ aweme: rec.name || rec.key, msg: '读取失败 ' + rec.err })
|
|
504
|
-
for (const a of rec.anomalies || []) anomalies.push({ aweme: (rec.name ? rec.name + ' / ' : '') + a.aweme, msg: a.msg })
|
|
565
|
+
for (const a of rec.anomalies || []) anomalies.push({ aweme: (rec.name ? rec.name + ' / ' : '') + a.aweme, msg: a.msg + (a.shot ? '(截图:' + a.shot + ')' : '') })
|
|
505
566
|
}
|
|
506
567
|
const head = anomalies.length ? ['⚠️ 本轮有 ' + anomalies.length + ' 处异常,请人工确认:', ...anomalies.map((a) => ' ⚠️ ' + a.aweme + ' — ' + a.msg)] : []
|
|
507
568
|
const text = [...(anomalies.length ? head : []), '第 ' + i + ' 轮 · ' + new Date().toLocaleString('zh-CN'), ...lines, '下一轮 ' + (nextAt ? new Date(nextAt).toLocaleString('zh-CN') : '(收工)')].join('\n')
|
|
@@ -520,7 +581,16 @@ function nextSlot(nodes, extraAt = [], lastStart = 0) {
|
|
|
520
581
|
}
|
|
521
582
|
}
|
|
522
583
|
for (const e of extraAt) if (e > floor) cands.push(e)
|
|
523
|
-
|
|
584
|
+
if (!cands.length) return now + 900000
|
|
585
|
+
let best = Math.min(...cands)
|
|
586
|
+
// 用户规则:控量结束那一刻不要卡秒去巡航。若某个节点落在「控量结束前 150s ~ 结束后 20s」,
|
|
587
|
+
// 一律挪到「结束 + 1 分钟」,避免结束瞬间 ⏸ 图标还没回退、读不到结束时间而误判。
|
|
588
|
+
for (const e of extraAt) {
|
|
589
|
+
if (e <= floor) continue
|
|
590
|
+
const end = e - 60000
|
|
591
|
+
if (best >= end - 150000 && best <= end + 20000) best = e
|
|
592
|
+
}
|
|
593
|
+
return best
|
|
524
594
|
}
|
|
525
595
|
|
|
526
596
|
// ---- main ----
|
|
@@ -203,6 +203,16 @@ async function cmdConfirm() {
|
|
|
203
203
|
const ts = Date.now(), token = tokenFor(planId, ts, shot);
|
|
204
204
|
fs.mkdirSync(path.dirname(receiptPath(planId)), { recursive: true });
|
|
205
205
|
fs.writeFileSync(receiptPath(planId), JSON.stringify({ planId, aavid, ts, shot, token, rowText: row }, null, 1));
|
|
206
|
+
// 同步下发到 QQ / 企业微信(失败不影响出图与确认单)
|
|
207
|
+
try {
|
|
208
|
+
const { pushImage } = await import('./notify-media.mjs');
|
|
209
|
+
const text = '【删除前确认】' + String.fromCharCode(10)
|
|
210
|
+
+ '名称:' + String(row).split('ID:')[0].trim().slice(0, 40) + String.fromCharCode(10)
|
|
211
|
+
+ 'ID:' + planId;
|
|
212
|
+
console.log('PUSH-TEXT ' + text.split(String.fromCharCode(10)).join(' / '));
|
|
213
|
+
const pushed = await pushImage({ file: shot, text, say: (s) => console.log(s) });
|
|
214
|
+
console.log('PUSH ' + JSON.stringify(pushed.map((x) => ({ ch: x.ch, part: x.part, ok: x.ok }))));
|
|
215
|
+
} catch (e) { console.log('PUSH-ERR ' + String(e.message).slice(0, 140)); }
|
|
206
216
|
mark('confirm-shot', shot);
|
|
207
217
|
console.log('ROW ' + row);
|
|
208
218
|
console.log('SHOT ' + shot);
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
|
|
6
|
+
const CFG = path.join(os.homedir(), '.qianchuan-cruise', 'notify.json');
|
|
7
|
+
|
|
8
|
+
export function loadChannels() {
|
|
9
|
+
try { return JSON.parse(fs.readFileSync(CFG, 'utf8')).channels || [] } catch { return [] }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
let tok = null;
|
|
13
|
+
async function qqToken(ch) {
|
|
14
|
+
if (tok && tok.exp > Date.now() + 60000) return tok.v;
|
|
15
|
+
const r = await fetch('https://bots.qq.com/app/getAppAccessToken', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ appId: ch.appId, clientSecret: ch.clientSecret }) });
|
|
16
|
+
const j = await r.json();
|
|
17
|
+
if (!j.access_token) throw new Error('QQ token 失败 ' + JSON.stringify(j).slice(0, 160));
|
|
18
|
+
tok = { v: j.access_token, exp: Date.now() + (Number(j.expires_in || 7200) - 120) * 1000 };
|
|
19
|
+
return tok.v;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function qqPost(ch, p, body, auth) {
|
|
23
|
+
const r = await fetch('https://api.sgroup.qq.com' + p, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'QQBot ' + auth }, body: JSON.stringify(body) });
|
|
24
|
+
const t = await r.text();
|
|
25
|
+
let j = null;
|
|
26
|
+
try { j = JSON.parse(t) } catch {}
|
|
27
|
+
return { status: r.status, j, body: t.slice(0, 200) };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function sendQQText(ch, text) {
|
|
31
|
+
const a = await qqToken(ch);
|
|
32
|
+
return qqPost(ch, '/v2/users/' + ch.openid + '/messages', { content: text, msg_type: 0 }, a);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function sendQQImage(ch, file) {
|
|
36
|
+
const a = await qqToken(ch);
|
|
37
|
+
const b64 = fs.readFileSync(file).toString('base64');
|
|
38
|
+
const up = await qqPost(ch, '/v2/users/' + ch.openid + '/files', { file_type: 1, file_data: b64, srv_send_msg: false }, a);
|
|
39
|
+
const info = up.j && up.j.file_info;
|
|
40
|
+
if (!info) return { ok: false, step: 'upload', status: up.status, body: up.body };
|
|
41
|
+
const sent = await qqPost(ch, '/v2/users/' + ch.openid + '/messages', { content: '', msg_type: 7, media: { file_info: info } }, a);
|
|
42
|
+
return { ok: sent.status === 200 || sent.status === 201, step: 'send', status: sent.status, body: sent.body };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function sendWecomImage(ch, file) {
|
|
46
|
+
const buf = fs.readFileSync(file);
|
|
47
|
+
const body = { msgtype: 'image', image: { base64: buf.toString('base64'), md5: crypto.createHash('md5').update(buf).digest('hex') } };
|
|
48
|
+
const r = await fetch(ch.url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
49
|
+
const t = await r.text();
|
|
50
|
+
return { ok: /"errcode":0/.test(t), status: r.status, body: t.slice(0, 200) };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function sendWecomText(ch, text) {
|
|
54
|
+
const r = await fetch(ch.url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ msgtype: 'text', text: { content: text } }) });
|
|
55
|
+
const t = await r.text();
|
|
56
|
+
return { ok: /"errcode":0/.test(t), status: r.status, body: t.slice(0, 200) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 把一张图 + 一段文字同时推到所有启用的渠道 */
|
|
60
|
+
export async function pushImage({ file, text, say = () => {} }) {
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const ch of loadChannels()) {
|
|
63
|
+
if (!ch.enabled) continue;
|
|
64
|
+
try {
|
|
65
|
+
if (ch.type === 'qq') {
|
|
66
|
+
if (text) out.push({ ch: ch.name, part: 'text', ...(await sendQQText(ch, text)) });
|
|
67
|
+
out.push({ ch: ch.name, part: 'image', ...(await sendQQImage(ch, file)) });
|
|
68
|
+
} else if (ch.type === 'wecom') {
|
|
69
|
+
if (text) out.push({ ch: ch.name, part: 'text', ...(await sendWecomText(ch, text)) });
|
|
70
|
+
out.push({ ch: ch.name, part: 'image', ...(await sendWecomImage(ch, file)) });
|
|
71
|
+
}
|
|
72
|
+
} catch (e) { out.push({ ch: ch.name, ok: false, err: String(e.message).slice(0, 120) }) }
|
|
73
|
+
}
|
|
74
|
+
out.forEach(r => say('[notify] ' + JSON.stringify(r).slice(0, 150)));
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (process.argv[1] && process.argv[1].endsWith('notify-media.mjs')) {
|
|
79
|
+
const file = process.argv[2];
|
|
80
|
+
const text = process.argv[3] || '';
|
|
81
|
+
const r = await pushImage({ file, text, say: (s) => console.log(s) });
|
|
82
|
+
console.log('RESULT ' + JSON.stringify(r.map(x => ({ ch: x.ch, part: x.part, ok: x.ok, status: x.status, step: x.step }))));
|
|
83
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-qianchuan-toolkit",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "DSH skill bundle for 巨量千川: 直播盯盘自动控量 (qianchuan-live-control) + 乘方计划复制 (qianchuan-plan-copy).",
|
|
6
6
|
"license": "MIT",
|
|
@@ -46,4 +46,4 @@
|
|
|
46
46
|
"CHANGELOG.md",
|
|
47
47
|
"docs"
|
|
48
48
|
]
|
|
49
|
-
}
|
|
49
|
+
}
|
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 进程内 CDP 客户端:巡航/控量脚本直接 import 本文件,不再 spawn 子进程
|
|
3
|
-
* (沙箱里 Node 再 spawn Node 会 EPERM,所以必须走这条路)。
|
|
4
|
-
*
|
|
5
|
-
* v9 加固:
|
|
6
|
-
* - 自动接管原生弹窗(alert/confirm/beforeunload)——它们会卡住渲染线程,导致 eval 永不返回
|
|
7
|
-
* - 所有 CDP 调用带超时(默认 20s),eval 默认 15s,绝不无限等待
|
|
8
|
-
* - 暴露 page.dialogs,便于排查「页面为什么卡住」
|
|
9
|
-
*/
|
|
10
|
-
import fs from 'node:fs'
|
|
11
|
-
import path from 'node:path'
|
|
12
|
-
|
|
13
|
-
const PORT = process.env.CDP_PORT || 9222
|
|
14
|
-
const BASE = 'http://127.0.0.1:' + PORT
|
|
15
|
-
const SEND_TIMEOUT = Number(process.env.CDP_SEND_TIMEOUT_MS || 20000)
|
|
16
|
-
const EVAL_TIMEOUT = Number(process.env.CDP_EVAL_TIMEOUT_MS || 15000)
|
|
17
|
-
|
|
18
|
-
export class CdpError extends Error {}
|
|
19
|
-
|
|
20
|
-
async function getJson(p) {
|
|
21
|
-
const r = await fetch(BASE + p)
|
|
22
|
-
if (!r.ok) throw new CdpError('http ' + r.status + ' ' + p)
|
|
23
|
-
return r.json()
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export async function listPages() {
|
|
27
|
-
try {
|
|
28
|
-
return await getJson('/json/list')
|
|
29
|
-
} catch (err) {
|
|
30
|
-
throw new CdpError('连不上调试端口 ' + PORT + '(' + ((err && err.message) || err) + ')—— 请先手动启动浏览器:双击 assets/scripts/start-qc.cmd,登录千川并停在「全域投放 · 推直播间」列表页')
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** 浏览器级 CDP(用于新建标签页):/json/version 的 webSocketDebuggerUrl */
|
|
35
|
-
async function browserWs() {
|
|
36
|
-
const v = await getJson('/json/version')
|
|
37
|
-
return v.webSocketDebuggerUrl
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** 浏览器级调用(Target.createTarget 等) */
|
|
41
|
-
export async function browserSend(method, params = {}, timeoutMs = 15000) {
|
|
42
|
-
const wsUrl = await browserWs()
|
|
43
|
-
const ws = new WebSocket(wsUrl)
|
|
44
|
-
await new Promise((res, rej) => {
|
|
45
|
-
const timer = setTimeout(() => rej(new CdpError('浏览器 WS 连接超时')), 8000)
|
|
46
|
-
ws.onopen = () => { clearTimeout(timer); res() }
|
|
47
|
-
ws.onerror = () => { clearTimeout(timer); rej(new CdpError('浏览器 WS 连接失败')) }
|
|
48
|
-
})
|
|
49
|
-
try {
|
|
50
|
-
return await new Promise((res, rej) => {
|
|
51
|
-
const id = 1
|
|
52
|
-
const timer = setTimeout(() => rej(new CdpError('浏览器 CDP 超时:' + method)), timeoutMs)
|
|
53
|
-
ws.onmessage = (ev) => {
|
|
54
|
-
let m
|
|
55
|
-
try { m = JSON.parse(ev.data) } catch { return }
|
|
56
|
-
if (m.id !== id) return
|
|
57
|
-
clearTimeout(timer)
|
|
58
|
-
if (m.error) rej(new CdpError(JSON.stringify(m.error))); else res(m.result)
|
|
59
|
-
}
|
|
60
|
-
ws.send(JSON.stringify({ id, method, params }))
|
|
61
|
-
})
|
|
62
|
-
} finally { try { ws.close() } catch {} }
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** 新建一个标签页,返回 targetId(不抢焦点:background=true) */
|
|
66
|
-
export async function createTab(url, { background = true } = {}) {
|
|
67
|
-
const r = await browserSend('Target.createTarget', { url, background })
|
|
68
|
-
return r.targetId
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** 关掉指定标签页 */
|
|
72
|
-
export async function closeTab(targetId) {
|
|
73
|
-
try { return await browserSend('Target.closeTarget', { targetId }) } catch (e) { return null }
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/** 连上匹配 match 的标签页(默认千川页面);给 id 则精确连某个标签页 */
|
|
77
|
-
export async function connect(match = 'jinritemai', { autoDialog = true, id = null } = {}) {
|
|
78
|
-
const pages = await listPages()
|
|
79
|
-
const page = id
|
|
80
|
-
? pages.find((p) => p.type === 'page' && p.id === id)
|
|
81
|
-
: pages.find((p) => p.type === 'page' && ((p.url || '').includes(match) || (p.title || '').includes(match)))
|
|
82
|
-
if (!page) {
|
|
83
|
-
throw new CdpError('没找到标题/URL 含「' + match + '」的标签页。当前标签页:' + pages.filter((p) => p.type === 'page').map((p) => (p.title || p.url).slice(0, 40)).join(' / '))
|
|
84
|
-
}
|
|
85
|
-
const ws = new WebSocket(page.webSocketDebuggerUrl)
|
|
86
|
-
await new Promise((res, rej) => {
|
|
87
|
-
const timer = setTimeout(() => rej(new CdpError('WebSocket 连接超时(' + (page.url || '').slice(0, 60) + ')')), 10000)
|
|
88
|
-
ws.onopen = () => { clearTimeout(timer); res() }
|
|
89
|
-
ws.onerror = () => { clearTimeout(timer); rej(new CdpError('WebSocket 连接失败(' + (page.url || '').slice(0, 60) + ')')) }
|
|
90
|
-
})
|
|
91
|
-
|
|
92
|
-
const pending = new Map()
|
|
93
|
-
const dialogs = []
|
|
94
|
-
let seq = 0
|
|
95
|
-
let alive = true
|
|
96
|
-
|
|
97
|
-
ws.onmessage = (ev) => {
|
|
98
|
-
let m
|
|
99
|
-
try { m = JSON.parse(ev.data) } catch { return }
|
|
100
|
-
if (m.id && pending.has(m.id)) {
|
|
101
|
-
const p = pending.get(m.id)
|
|
102
|
-
pending.delete(m.id)
|
|
103
|
-
clearTimeout(p.timer)
|
|
104
|
-
if (m.error) p.rej(new CdpError(JSON.stringify(m.error)))
|
|
105
|
-
else p.res(m.result)
|
|
106
|
-
return
|
|
107
|
-
}
|
|
108
|
-
if (m.method === 'Page.javascriptDialogOpening') {
|
|
109
|
-
const info = m.params || {}
|
|
110
|
-
dialogs.push({ type: info.type, message: (info.message || '').slice(0, 120), at: Date.now() })
|
|
111
|
-
if (dialogs.length > 20) dialogs.shift()
|
|
112
|
-
if (autoDialog) {
|
|
113
|
-
const accept = info.type === 'beforeunload'
|
|
114
|
-
rawSend('Page.handleJavaScriptDialog', { accept }).catch(() => {})
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
ws.onclose = () => {
|
|
119
|
-
alive = false
|
|
120
|
-
for (const p of pending.values()) { clearTimeout(p.timer); p.rej(new CdpError('ws closed')) }
|
|
121
|
-
pending.clear()
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const rawSend = (method, params = {}, timeoutMs = SEND_TIMEOUT) => new Promise((res, rej) => {
|
|
125
|
-
if (!alive) return rej(new CdpError('ws closed'))
|
|
126
|
-
const id = ++seq
|
|
127
|
-
const timer = setTimeout(() => { pending.delete(id); rej(new CdpError('cdp 超时 ' + Math.round(timeoutMs / 1000) + 's:' + method)) }, timeoutMs)
|
|
128
|
-
pending.set(id, { res, rej, timer })
|
|
129
|
-
try { ws.send(JSON.stringify({ id, method, params })) } catch (e) { clearTimeout(timer); pending.delete(id); rej(new CdpError('ws send 失败: ' + e.message)) }
|
|
130
|
-
})
|
|
131
|
-
|
|
132
|
-
await rawSend('Page.enable', {}).catch(() => {})
|
|
133
|
-
|
|
134
|
-
return {
|
|
135
|
-
url: page.url,
|
|
136
|
-
title: page.title,
|
|
137
|
-
dialogs,
|
|
138
|
-
send: rawSend,
|
|
139
|
-
async eval(expr, timeoutMs = EVAL_TIMEOUT) {
|
|
140
|
-
const r = await rawSend('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true }, timeoutMs)
|
|
141
|
-
if (r.exceptionDetails) throw new CdpError('eval 异常: ' + r.exceptionDetails.text + ' ' + ((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || ''))
|
|
142
|
-
return r.result ? r.result.value : undefined
|
|
143
|
-
},
|
|
144
|
-
async evalJson(expr, timeoutMs = EVAL_TIMEOUT) {
|
|
145
|
-
const v = await this.eval(expr, timeoutMs)
|
|
146
|
-
return typeof v === 'string' ? JSON.parse(v) : v
|
|
147
|
-
},
|
|
148
|
-
async shot(file) {
|
|
149
|
-
const r = await rawSend('Page.captureScreenshot', { format: 'png' }, 30000)
|
|
150
|
-
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
151
|
-
fs.writeFileSync(file, Buffer.from(r.data, 'base64'))
|
|
152
|
-
return file
|
|
153
|
-
},
|
|
154
|
-
async clickAt(x, y) {
|
|
155
|
-
for (const e of [
|
|
156
|
-
{ type: 'mouseMoved', x, y },
|
|
157
|
-
{ type: 'mousePressed', x, y, button: 'left', clickCount: 1 },
|
|
158
|
-
{ type: 'mouseReleased', x, y, button: 'left', clickCount: 1 },
|
|
159
|
-
]) await rawSend('Input.dispatchMouseEvent', e)
|
|
160
|
-
return [Math.round(x), Math.round(y)]
|
|
161
|
-
},
|
|
162
|
-
async ping() { // 渲染线程是否还能跑 JS
|
|
163
|
-
const t0 = Date.now()
|
|
164
|
-
try { const v = await this.eval('1+1', 5000); return { ok: v === 2, ms: Date.now() - t0 } }
|
|
165
|
-
catch (e) { return { ok: false, ms: Date.now() - t0, err: e.message } }
|
|
166
|
-
},
|
|
167
|
-
close() { try { ws.close() } catch {} },
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
@@ -1,271 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// 乘方-推商品「复制计划」v2:全部用 DOM 点击 + 页面内等待,不用坐标,不受窗口大小/缩放/滚动影响。
|
|
3
|
-
// 用法:node copy.mjs <search|delete|create|materials|publish|verify> <aavid> [params.json]
|
|
4
|
-
import fs from 'node:fs';
|
|
5
|
-
import { connect, sleep } from '../../live-control/scripts/cdp-lib.mjs';
|
|
6
|
-
|
|
7
|
-
const W = 'C:/Users/admin/Documents/deepseek-harness/default-workspace';
|
|
8
|
-
const t0 = Date.now();
|
|
9
|
-
const mark = (l, e) => console.log('[' + ((Date.now() - t0) / 1000).toFixed(1) + 's] ' + l + (e ? ' ' + e : ''));
|
|
10
|
-
|
|
11
|
-
// ---------- 注入到页面里的工具函数(不依赖坐标) ----------
|
|
12
|
-
function qcHelpers() {
|
|
13
|
-
const T = (s) => (s || '').replace(/\s+/g, ' ').trim();
|
|
14
|
-
window.__qc = {
|
|
15
|
-
text: () => T(document.body ? document.body.innerText : ''),
|
|
16
|
-
leaves(t, root) {
|
|
17
|
-
return [...(root || document).querySelectorAll('button,span,div,a,li,label')]
|
|
18
|
-
.filter((e) => e.children.length === 0 && T(e.innerText) === t && e.getBoundingClientRect().width > 0);
|
|
19
|
-
},
|
|
20
|
-
clickText(t, root) {
|
|
21
|
-
const hits = this.leaves(t, root);
|
|
22
|
-
const el = hits[hits.length - 1];
|
|
23
|
-
if (!el) return false;
|
|
24
|
-
el.click();
|
|
25
|
-
return true;
|
|
26
|
-
},
|
|
27
|
-
rowByText(t) {
|
|
28
|
-
const cands = [...document.querySelectorAll('*')]
|
|
29
|
-
.filter((e) => e.children.length === 0 && T(e.innerText).includes(t) && e.getBoundingClientRect().width > 0);
|
|
30
|
-
for (const l of cands) { const tr = l.closest('tr'); if (tr) return tr; }
|
|
31
|
-
for (const l of cands) { const c = l.closest('.card-product-item,.oc-card,.ovui-card,.create-material-list-card-item'); if (c) return c; }
|
|
32
|
-
return null;
|
|
33
|
-
},
|
|
34
|
-
clickRowLabel(t) {
|
|
35
|
-
const row = this.rowByText(t);
|
|
36
|
-
if (!row) return 'norow';
|
|
37
|
-
const lab = row.querySelector('label.ovui-checkbox') || row.querySelector('label') || row.querySelector('input[type=checkbox]');
|
|
38
|
-
if (!lab) return 'nolabel';
|
|
39
|
-
lab.click();
|
|
40
|
-
return 'ok';
|
|
41
|
-
},
|
|
42
|
-
clickCardLabel(i) {
|
|
43
|
-
const cards = [...document.querySelectorAll('.create-material-list-card-item')].filter((c) => c.getBoundingClientRect().height > 0);
|
|
44
|
-
const card = cards[i];
|
|
45
|
-
if (!card) return 'nocard';
|
|
46
|
-
const lab = card.querySelector('label') || card.querySelector('[class*=checkbox]') || card;
|
|
47
|
-
lab.click();
|
|
48
|
-
return 'ok';
|
|
49
|
-
},
|
|
50
|
-
cardsInfo() {
|
|
51
|
-
const cards = [...document.querySelectorAll('.create-material-list-card-item')].filter((c) => c.getBoundingClientRect().height > 0);
|
|
52
|
-
const sel = cards.filter((c) => c.querySelector('.oc-create-material-card-selected')).length;
|
|
53
|
-
return { n: cards.length, sel: sel };
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
return true;
|
|
57
|
-
}
|
|
58
|
-
const INJECT = '(' + qcHelpers.toString() + ')()';
|
|
59
|
-
const waitJs = (cond, ms) => '(async () => { const t0 = performance.now(); while (performance.now() - t0 < ' + ms + ') { try { if (' + cond + ') return true } catch (e) {} await new Promise(r => setTimeout(r, 40)) } return false })()';
|
|
60
|
-
const wait = async (page, cond, ms) => await page.eval(waitJs(cond, ms), ms + 8000);
|
|
61
|
-
const txt = async (page) => await page.eval('__qc.text()');
|
|
62
|
-
|
|
63
|
-
async function focusAndType(page, inputExpr, text) {
|
|
64
|
-
const ok = await page.eval('(() => { const i = ' + inputExpr + '; if (!i) return false; const s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set; s.call(i, ""); i.dispatchEvent(new Event("input", { bubbles: true })); i.focus(); i.select(); return true })()');
|
|
65
|
-
if (!ok) throw new Error('input not found');
|
|
66
|
-
await page.send('Input.insertText', { text }, 8000);
|
|
67
|
-
return true;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const PLAN_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("计划名称"))';
|
|
71
|
-
const PRODUCT_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("商品名称"))';
|
|
72
|
-
const AWEME_SEARCH = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("抖音号名称"))';
|
|
73
|
-
const ROI_INPUT = 'document.querySelectorAll(".aurora-qc-input-number-input")[0]';
|
|
74
|
-
const BUDGET_INPUT = 'document.querySelectorAll(".aurora-qc-input-number-input")[1]';
|
|
75
|
-
const NAME_INPUT = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("计划名称,1-50"))';
|
|
76
|
-
|
|
77
|
-
async function openList(page, aavid) {
|
|
78
|
-
await page.send('Page.navigate', { url: 'https://qianchuan.jinritemai.com/overall-prom?aavid=' + aavid + '&campaignType=1&uniTab=ad&marGoal=1&uniVideoTab=1&overallPromViewTab=plan' }, 15000);
|
|
79
|
-
const ok = await wait(page, '!!' + PLAN_SEARCH, 15000);
|
|
80
|
-
if (!ok) throw new Error('列表页未就绪');
|
|
81
|
-
await page.eval(INJECT);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
async function cmdSearch() {
|
|
85
|
-
const aavid = process.argv[3], planId = process.argv[4];
|
|
86
|
-
const page = await connect('jinritemai');
|
|
87
|
-
await openList(page, aavid);
|
|
88
|
-
await focusAndType(page, PLAN_SEARCH, planId);
|
|
89
|
-
await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', windowsVirtualKeyCode: 13, key: 'Enter', code: 'Enter' }, 8000);
|
|
90
|
-
await page.send('Input.dispatchKeyEvent', { type: 'keyUp', windowsVirtualKeyCode: 13, key: 'Enter', code: 'Enter' }, 8000);
|
|
91
|
-
await wait(page, '/共\s*\d+\s*条计划/.test(__qc.text())', 8000);
|
|
92
|
-
const info = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const m=c(document.body.innerText).match(/共\s*(\d+)\s*条计划/); const rows=[...document.querySelectorAll("tbody tr")].map(r=>c(r.innerText)).filter(x=>x.length>40); return JSON.stringify({count: m?m[1]:null, rows: rows.slice(0,3)}) })()');
|
|
93
|
-
mark('search', info);
|
|
94
|
-
// 不要 page.close():会关掉标签页
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
async function cmdDelete() {
|
|
98
|
-
const aavid = process.argv[3], planId = process.argv[4];
|
|
99
|
-
const page = await connect('jinritemai');
|
|
100
|
-
await openList(page, aavid);
|
|
101
|
-
await focusAndType(page, PLAN_SEARCH, planId);
|
|
102
|
-
await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', windowsVirtualKeyCode: 13, key: 'Enter', code: 'Enter' }, 8000);
|
|
103
|
-
await page.send('Input.dispatchKeyEvent', { type: 'keyUp', windowsVirtualKeyCode: 13, key: 'Enter', code: 'Enter' }, 8000);
|
|
104
|
-
const hit = await wait(page, '/共\s*1\s*条计划/.test(__qc.text())', 8000);
|
|
105
|
-
if (!hit) throw new Error('未唯一命中,拒绝删除');
|
|
106
|
-
mark('unique-hit');
|
|
107
|
-
const clicked = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const tr=[...document.querySelectorAll("tbody tr")].find(r=>c(r.innerText).includes(' + JSON.stringify(planId) + ')); if(!tr) return "norow"; const b=[...tr.querySelectorAll("*")].filter(e=>e.children.length===0 && c(e.innerText)==="删除").pop(); if(!b) return "nobtn"; b.click(); return "ok" })()');
|
|
108
|
-
if (clicked !== 'ok') throw new Error('删除按钮: ' + clicked);
|
|
109
|
-
const dlg = await wait(page, '[...document.querySelectorAll("*")].some(e=>(e.innerText||"").trim()==="确定要删除计划吗?")', 6000);
|
|
110
|
-
if (!dlg) throw new Error('删除弹窗未出现');
|
|
111
|
-
await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const t=[...document.querySelectorAll("*")].find(e=>(e.innerText||"").trim()==="确定要删除计划吗?"); const w=t.closest(".aurora-qc-modal-wrap"); const b=[...w.querySelectorAll("button")].find(x=>c(x.innerText)==="确定"); if(b) b.click(); return 1 })()');
|
|
112
|
-
mark('confirm-clicked');
|
|
113
|
-
const gone = await wait(page, '/删除成功/.test(__qc.text()) && /共\s*0\s*条计划|暂无数据/.test(__qc.text())', 75000);
|
|
114
|
-
mark('deleted', gone ? 'ok' : 'timeout');
|
|
115
|
-
// 不要 page.close():会关掉标签页
|
|
116
|
-
process.exit(gone ? 0 : 4);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
async function cmdCreate() {
|
|
120
|
-
const aavid = process.argv[3], p = JSON.parse(fs.readFileSync(process.argv[4], 'utf8'));
|
|
121
|
-
const page = await connect('jinritemai');
|
|
122
|
-
await page.send('Page.navigate', { url: 'https://qianchuan.jinritemai.com/create-ad/overall-product?aavid=' + aavid }, 15000);
|
|
123
|
-
const ready = await wait(page, '/选择投放对象/.test(__qc.text())', 20000);
|
|
124
|
-
if (!ready) throw new Error('新建页未就绪');
|
|
125
|
-
await page.eval(INJECT);
|
|
126
|
-
mark('create-page');
|
|
127
|
-
|
|
128
|
-
const opened = await page.eval('__qc.clickText("添加商品")');
|
|
129
|
-
if (!opened) throw new Error('找不到「添加商品」');
|
|
130
|
-
const drawer = await wait(page, '!!document.querySelector(".card-product-item")', 8000);
|
|
131
|
-
if (!drawer) throw new Error('商品抽屉未出现');
|
|
132
|
-
mark('product-drawer');
|
|
133
|
-
|
|
134
|
-
await focusAndType(page, PRODUCT_SEARCH, p.productId);
|
|
135
|
-
const rowOk = await wait(page, '__qc.rowByText(' + JSON.stringify(p.productId) + ')', 10000);
|
|
136
|
-
if (!rowOk) throw new Error('商品行未出现');
|
|
137
|
-
const clicked = await page.eval('__qc.clickRowLabel(' + JSON.stringify(p.productId) + ')');
|
|
138
|
-
if (clicked !== 'ok') throw new Error('商品勾选: ' + clicked);
|
|
139
|
-
const picked = await wait(page, '/已选[^0-9]{0,3}[1-9]\d*\s*\/\s*30/.test(__qc.text())', 4000);
|
|
140
|
-
if (!picked) throw new Error('商品未选中');
|
|
141
|
-
mark('product-picked');
|
|
142
|
-
|
|
143
|
-
await page.eval('__qc.clickText("下一步")');
|
|
144
|
-
const step2 = await wait(page, '/手动选择抖音号/.test(__qc.text())', 8000);
|
|
145
|
-
if (!step2) throw new Error('抖音号步骤未出现');
|
|
146
|
-
await page.eval('__qc.clickText("手动选择抖音号")');
|
|
147
|
-
await wait(page, '!!' + AWEME_SEARCH, 4000);
|
|
148
|
-
mark('aweme-step');
|
|
149
|
-
|
|
150
|
-
const ids = p.awemeIds || [], names = p.awemeNames || {};
|
|
151
|
-
const tA = Date.now();
|
|
152
|
-
let done = 0;
|
|
153
|
-
for (const id of ids) {
|
|
154
|
-
await focusAndType(page, AWEME_SEARCH, id);
|
|
155
|
-
let ok = await wait(page, '__qc.rowByText(' + JSON.stringify(id) + ')', 4000);
|
|
156
|
-
if (!ok) {
|
|
157
|
-
const nm = names[id];
|
|
158
|
-
if (nm) { await focusAndType(page, AWEME_SEARCH, nm); ok = await wait(page, '__qc.rowByText(' + JSON.stringify(id) + ')', 4000); }
|
|
159
|
-
}
|
|
160
|
-
if (!ok) { console.log('MISS ' + id); continue; }
|
|
161
|
-
const r = await page.eval('__qc.clickRowLabel(' + JSON.stringify(id) + ')');
|
|
162
|
-
if (r !== 'ok') { console.log('MISS2 ' + id + ' ' + r); continue; }
|
|
163
|
-
done++;
|
|
164
|
-
}
|
|
165
|
-
const pickedAw = await page.eval('(() => { const m = __qc.text().match(/当前商品已选:\s*(\d+)/); return m ? m[1] : "?" })()');
|
|
166
|
-
mark('awemes', 'clicked=' + done + ' picked=' + pickedAw + ' in ' + ((Date.now() - tA) / 1000).toFixed(1) + 's');
|
|
167
|
-
await page.eval('__qc.clickText("确定")');
|
|
168
|
-
const applied = await wait(page, '/\d+个抖音号/.test(__qc.text())', 8000);
|
|
169
|
-
mark('aweme-applied', applied ? 'ok' : 'timeout');
|
|
170
|
-
|
|
171
|
-
await focusAndType(page, ROI_INPUT, p.roi);
|
|
172
|
-
await focusAndType(page, BUDGET_INPUT, p.budget);
|
|
173
|
-
await focusAndType(page, NAME_INPUT, p.planName);
|
|
174
|
-
const vals = await page.eval('JSON.stringify({ nums: [...document.querySelectorAll(".aurora-qc-input-number-input")].map(x => x.value), name: (' + NAME_INPUT + ' || {}).value })');
|
|
175
|
-
mark('form', vals);
|
|
176
|
-
// 不要 page.close():会关掉标签页
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
async function cmdMaterials() {
|
|
180
|
-
const p = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
|
|
181
|
-
const page = await connect('jinritemai');
|
|
182
|
-
await page.eval(INJECT);
|
|
183
|
-
const ok = await page.eval('__qc.clickText("添加自选素材")');
|
|
184
|
-
if (!ok) throw new Error('找不到「添加自选素材」');
|
|
185
|
-
const dOpen = await wait(page, '[...document.querySelectorAll(".ovui-tabs__tab-btn")].length > 1', 10000);
|
|
186
|
-
if (!dOpen) throw new Error('素材抽屉未打开');
|
|
187
|
-
mark('material-drawer');
|
|
188
|
-
const cnt = await page.eval('[...document.querySelectorAll(".ovui-tabs__tab-btn")].length');
|
|
189
|
-
let total = 0;
|
|
190
|
-
for (let i = 1; i < cnt; i++) {
|
|
191
|
-
const tA = Date.now();
|
|
192
|
-
const tabName = await page.eval('(() => { const t=[...document.querySelectorAll(".ovui-tabs__tab-btn")][' + i + ']; return t ? (t.innerText||"").trim() : "" })()');
|
|
193
|
-
await page.eval('(() => { const t=[...document.querySelectorAll(".ovui-tabs__tab-btn")][' + i + ']; if(t) t.click(); return 1 })()');
|
|
194
|
-
await wait(page, '__qc.text().includes("添加视频")', 5000);
|
|
195
|
-
await page.eval('__qc.clickText("添加视频")');
|
|
196
|
-
let info = null;
|
|
197
|
-
for (let a = 0; a < 3; a++) {
|
|
198
|
-
const hasCards = await wait(page, '__qc.cardsInfo().n > 0', 8000);
|
|
199
|
-
if (!hasCards) { await page.eval('__qc.clickText("添加视频")'); continue; }
|
|
200
|
-
info = await page.eval('__qc.cardsInfo()');
|
|
201
|
-
if (info.n > 0) break;
|
|
202
|
-
}
|
|
203
|
-
if (!info || info.n === 0) { console.log('NOCARD ' + tabName); continue; }
|
|
204
|
-
let n = info.n;
|
|
205
|
-
for (let k = 0; k < n; k++) await page.eval('__qc.clickCardLabel(' + k + ')');
|
|
206
|
-
const after = await wait(page, '__qc.cardsInfo().sel >= ' + n, 3000);
|
|
207
|
-
const st = await page.eval('__qc.cardsInfo()');
|
|
208
|
-
total += st.sel;
|
|
209
|
-
await page.eval('__qc.clickText("确定")');
|
|
210
|
-
await wait(page, '/已添加:\d+/.test(__qc.text())', 5000);
|
|
211
|
-
console.log('VID ' + tabName + ' n=' + n + ' sel=' + st.sel + ' ' + ((Date.now() - tA) / 1000).toFixed(1) + 's');
|
|
212
|
-
}
|
|
213
|
-
await page.eval('__qc.clickText("确定")');
|
|
214
|
-
await sleep(600);
|
|
215
|
-
const summary = await page.eval('(() => { const m = __qc.text().match(/共\s*(\d+)\s*条自选素材/); return m ? m[1] : "?" })()');
|
|
216
|
-
mark('all-materials', 'total=' + total + ' applied=' + summary);
|
|
217
|
-
// 注意:绝不能 page.close(),那会关掉标签页(曾导致整窗退出)
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
async function cmdPublish() {
|
|
221
|
-
const page = await connect('jinritemai');
|
|
222
|
-
await page.eval(INJECT);
|
|
223
|
-
await page.eval('__qc.clickText("发布计划")');
|
|
224
|
-
const dlg = await wait(page, '/确认发布/.test(__qc.text())', 8000);
|
|
225
|
-
if (!dlg) throw new Error('发布确认框未出现');
|
|
226
|
-
const c = await clickByText(page, '确认发布');
|
|
227
|
-
mark('confirm', JSON.stringify(c));
|
|
228
|
-
const done = await wait(page, 'location.href.includes("overall-prom") && location.href.includes("createSuccess")', 30000);
|
|
229
|
-
mark('published', done ? 'ok' : 'timeout');
|
|
230
|
-
process.exit(done ? 0 : 4);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
// ---------- 统一「按文字点击」:普通 DOM → 穿透 shadow DOM 兜底 ----------
|
|
235
|
-
async function findInShadow(page, text) {
|
|
236
|
-
if (!page.__domEnabled) { await page.send('DOM.enable', {}, 8000); page.__domEnabled = true }
|
|
237
|
-
const flat = await page.send('DOM.getFlattenedDocument', { depth: -1, pierce: true }, 20000);
|
|
238
|
-
return (flat.nodes || []).filter((n) => n.nodeType === 3 && (n.nodeValue || "").indexOf(text) >= 0);
|
|
239
|
-
}
|
|
240
|
-
async function clickInShadow(page, text) {
|
|
241
|
-
const hits = await findInShadow(page, text);
|
|
242
|
-
if (!hits.length) return 'noshadow';
|
|
243
|
-
const pid = hits[hits.length - 1].parentId;
|
|
244
|
-
const obj = await page.send('DOM.resolveNode', { nodeId: pid }, 10000);
|
|
245
|
-
const fn = 'function(){var p=this;for(var d=0;d<6&&p;d++){var c=(p.className||"").toString();if(p.tagName==="BUTTON"||c.indexOf("btn")>=0||c.indexOf("button")>=0){p.click();return "clicked:"+p.tagName}p=p.parentElement}this.click();return "clicked-self"}';
|
|
246
|
-
const r = await page.send('Runtime.callFunctionOn', { objectId: obj.object.objectId, functionDeclaration: fn, returnByValue: true }, 10000);
|
|
247
|
-
return r.result ? r.result.value : 'unknown';
|
|
248
|
-
}
|
|
249
|
-
// 先普通 DOM(__qc.clickText),没有就立刻穿透 shadow DOM;返回走了哪一层、耗多少毫秒
|
|
250
|
-
async function clickByText(page, text) {
|
|
251
|
-
const t = Date.now();
|
|
252
|
-
const dom = await page.eval('__qc.clickText(' + JSON.stringify(text) + ')');
|
|
253
|
-
if (dom) return { text: text, layer: 'dom', click: 'ok', ms: Date.now() - t };
|
|
254
|
-
const sh = await clickInShadow(page, text);
|
|
255
|
-
return { text: text, layer: 'shadow', click: sh, ms: Date.now() - t };
|
|
256
|
-
}
|
|
257
|
-
async function cmdClick() {
|
|
258
|
-
const page = await connect('jinritemai');
|
|
259
|
-
await page.eval(INJECT);
|
|
260
|
-
const text = process.argv[3] || '发布计划';
|
|
261
|
-
const dry = process.argv.includes('--dry');
|
|
262
|
-
const domCount = await page.eval('__qc.leaves(' + JSON.stringify(text) + ').length');
|
|
263
|
-
let shadowHit = 0;
|
|
264
|
-
try { shadowHit = (await findInShadow(page, text)).length } catch (e) { shadowHit = -1 }
|
|
265
|
-
mark('locate', JSON.stringify({ text: text, domLeaves: domCount, shadowTextNodes: shadowHit }));
|
|
266
|
-
if (!dry) mark('click', JSON.stringify(await clickByText(page, text)));
|
|
267
|
-
}
|
|
268
|
-
const table = { search: cmdSearch, verify: cmdSearch, delete: cmdDelete, create: cmdCreate, materials: cmdMaterials, publish: cmdPublish, click: cmdClick };
|
|
269
|
-
const cmd = process.argv[2];
|
|
270
|
-
if (!table[cmd]) { console.log('usage: node copy.mjs <search|delete|create|materials|publish|verify> ...'); process.exit(2); }
|
|
271
|
-
try { await table[cmd](); } catch (e) { console.log('ERR ' + e.message); process.exit(3); }
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
// pick-all.mjs —— 「添加视频」弹窗里把每个抖音号的主页视频全勾上,然后点确定
|
|
2
|
-
// 用法: node pick-all.mjs [adId]
|
|
3
|
-
// adId 省略时从最近一个 out/*.json 读抖音号名称
|
|
4
|
-
// 前提: 已进入某计划的 素材 tab,且「添加视频」弹窗已打开
|
|
5
|
-
// 逻辑: 切号用 JS click(按名称,坐标点不动);素材卡片必须 CDP 真实点击;已添加的卡片点了没反应,所以每张都点一遍
|
|
6
|
-
import fs from 'node:fs'
|
|
7
|
-
import path from 'node:path'
|
|
8
|
-
|
|
9
|
-
const PORT = 9222, BASE = 'http://127.0.0.1:' + PORT
|
|
10
|
-
// 计划参数快照目录:默认 <数据目录>/out,可用 QC_OUT 覆盖
|
|
11
|
-
const OUT_DIR = process.env.QC_OUT || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.qianchuan-cruise', 'out')
|
|
12
|
-
const CARD = '.main-vmok-plugin-create-material-list-card-item'
|
|
13
|
-
const NAV = '.main-vmok-plugin-tabs__nav-list'
|
|
14
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
15
|
-
|
|
16
|
-
function namesFor(adId) {
|
|
17
|
-
if (adId) { const f = path.join(OUT_DIR, adId + '.json'); if (fs.existsSync(f)) { const d = JSON.parse(fs.readFileSync(f, 'utf8')); return d.douyinNames || [] } }
|
|
18
|
-
const files = fs.readdirSync(OUT_DIR).filter((f) => f.endsWith('.json')).map((f) => path.join(OUT_DIR, f))
|
|
19
|
-
if (!files.length) return []
|
|
20
|
-
files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)
|
|
21
|
-
return JSON.parse(fs.readFileSync(files[0], 'utf8')).douyinNames || []
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
async function j(p) { const r = await fetch(BASE + p); if (!r.ok) throw new Error('http ' + r.status); return r.json() }
|
|
25
|
-
async function connect(t) {
|
|
26
|
-
const ws = new WebSocket(t.webSocketDebuggerUrl)
|
|
27
|
-
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error('ws error')) })
|
|
28
|
-
const c = { ws, seq: 0, p: new Map() }
|
|
29
|
-
ws.onmessage = (e) => { let m; try { m = JSON.parse(e.data) } catch { return } if (m.id && c.p.has(m.id)) { const q = c.p.get(m.id); c.p.delete(m.id); m.error ? q.rej(new Error(JSON.stringify(m.error))) : q.res(m.result) } }
|
|
30
|
-
return c
|
|
31
|
-
}
|
|
32
|
-
function send(c, method, params = {}) { const id = ++c.seq; return new Promise((res, rej) => { c.p.set(id, { res, rej }); c.ws.send(JSON.stringify({ id, method, params })) }) }
|
|
33
|
-
async function ev(c, expr) { const r = await send(c, 'Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.text); return r.result?.value }
|
|
34
|
-
async function click(c, x, y) {
|
|
35
|
-
await send(c, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
|
|
36
|
-
await send(c, 'Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
|
|
37
|
-
await send(c, 'Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
|
|
38
|
-
}
|
|
39
|
-
const getSel = `(()=>{const t=document.body.innerText.replace(/[ \\t]+/g,' ');const m=t.match(/已选择\\s*(\\d+)\\/200/);return m?Number(m[1]):-1})()`
|
|
40
|
-
const clickTab = (name) => `(()=>{const ls=[...document.querySelectorAll('${NAV}')];for(const list of ls){const t=[...list.children].find(c=>c.innerText&&c.innerText.replace(/\\s+/g,' ').trim().includes(${JSON.stringify(name)}));if(t){t.click();return 'OK'}}return 'NOTAB'})()`
|
|
41
|
-
const listCards = `(()=>[...document.querySelectorAll('${CARD}')].map(c=>{const w=c.querySelector('[itemid]')||c;return w.getAttribute('itemid')}).filter(Boolean))()`
|
|
42
|
-
const cardPos = (id) => `(()=>{const c=[...document.querySelectorAll('${CARD}')].find(x=>{const w=x.querySelector('[itemid]')||x;return w.getAttribute('itemid')===${JSON.stringify(id)}});if(!c)return null;c.scrollIntoView({block:'center',inline:'nearest'});const r=c.getBoundingClientRect();if(r.width<10)return null;return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`
|
|
43
|
-
|
|
44
|
-
const arg = process.argv[2]
|
|
45
|
-
const names = arg && arg.includes(',') ? arg.split(',').map((s) => s.trim()).filter(Boolean) : namesFor(arg)
|
|
46
|
-
if (!names.length) { console.log(JSON.stringify({ error: '没有抖音号名单:先跑 dump-plan.mjs,或直接 socket 里看' })); process.exit(1) }
|
|
47
|
-
const pages = (await j('/json/list')).filter((t) => t.type === 'page')
|
|
48
|
-
const page = pages.find((p) => p.url.includes('qianchuan')) || pages[0]
|
|
49
|
-
const c = await connect(page)
|
|
50
|
-
|
|
51
|
-
const modalOpen = await ev(c, `(()=>/已选择\\s*\\d+\\/200/.test(document.body.innerText))()`)
|
|
52
|
-
if (!modalOpen) { console.log(JSON.stringify({ error: '「添加视频」弹窗没开,先手动打开或点「添加视频」' })); process.exit(1) }
|
|
53
|
-
|
|
54
|
-
const log = []
|
|
55
|
-
for (const name of names) {
|
|
56
|
-
const r = await ev(c, clickTab(name))
|
|
57
|
-
if (r !== 'OK') { log.push({ name, err: r }); continue }
|
|
58
|
-
await sleep(2600) // 卡片异步渲染,等不够会读到 0 张
|
|
59
|
-
const ids = await ev(c, listCards)
|
|
60
|
-
const before = await ev(c, getSel)
|
|
61
|
-
for (const id of ids) {
|
|
62
|
-
const p = await ev(c, cardPos(id))
|
|
63
|
-
if (!p) continue
|
|
64
|
-
await sleep(140)
|
|
65
|
-
await click(c, p.x, p.y)
|
|
66
|
-
await sleep(300)
|
|
67
|
-
}
|
|
68
|
-
const after = await ev(c, getSel)
|
|
69
|
-
log.push({ name, cards: ids.length, before, after, delta: after - before })
|
|
70
|
-
}
|
|
71
|
-
// 点确定
|
|
72
|
-
const okb = await ev(c, `(()=>{const bs=[...document.querySelectorAll('button')].filter(b=>b.innerText.trim()==='确定'&&b.getBoundingClientRect().width>0);if(!bs.length)return 'NOOK';const r=bs[bs.length-1].getBoundingClientRect();return [Math.round(r.x+r.width/2),Math.round(r.y+r.height/2)]})()`)
|
|
73
|
-
let submitted = false
|
|
74
|
-
if (Array.isArray(okb)) { await click(c, okb[0], okb[1]); await sleep(5000); submitted = true }
|
|
75
|
-
const total = await ev(c, `(()=>{const m=document.body.innerText.match(/共\\d+个视频/);return m?m[0]:null})()`)
|
|
76
|
-
console.log(JSON.stringify({ ok: true, submitted, totalVideos: total, log }, null, 1))
|
|
77
|
-
process.exit(0)
|
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
// pick-all.mjs —— 「添加视频」弹窗里把每个抖音号的主页视频全勾上,一次跑完直接点确定(不二次补选)
|
|
2
|
-
// 用法: node scripts/pick-all.mjs "抖音号名1,抖音号名2,...,抖音号名N"
|
|
3
|
-
// (单号也要带尾逗号:"号名,";不传参时从 out/*.json 读名单)
|
|
4
|
-
// 前提: 已进入某计划的 素材 tab,素材类型=视频,且「添加视频」弹窗已打开
|
|
5
|
-
// 改自技能资产 dsh-qianchuan-toolkit/assets/plan-copy/scripts/pick-all.mjs(用户 2026-11-20 要求的一次跑完规则)
|
|
6
|
-
// 逻辑:
|
|
7
|
-
// 1) 切号 JS click(横向列表坐标点不动,只能 JS click)
|
|
8
|
-
// 2) 切号后轮询等卡片渲染(最多 8s),不要固定 sleep 后立刻取
|
|
9
|
-
// 3) 每张卡片 CDP 真实点击;点完读「已选择 N/200」,没涨就补点一次(漏勾/点空)
|
|
10
|
-
// 4) 某号 0 卡片 → 取消勾选「过滤不良素材」刷新 → 仍为 0 判定该号确实无视频,继续下一个号
|
|
11
|
-
// 5) 全部号点完,一次性点「确定」提交;不再二次进弹窗、不再翻抽屉核对
|
|
12
|
-
import fs from 'node:fs'
|
|
13
|
-
import path from 'node:path'
|
|
14
|
-
|
|
15
|
-
const PORT = 9222, BASE = 'http://127.0.0.1:' + PORT
|
|
16
|
-
const OUT_DIR = process.env.QC_OUT || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.qianchuan-cruise', 'out')
|
|
17
|
-
const CARD = '.main-vmok-plugin-create-material-list-card-item'
|
|
18
|
-
const NAV = '.main-vmok-plugin-tabs__nav-list'
|
|
19
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
20
|
-
|
|
21
|
-
function namesFor(adId) {
|
|
22
|
-
if (adId) { const f = path.join(OUT_DIR, adId + '.json'); if (fs.existsSync(f)) { const d = JSON.parse(fs.readFileSync(f, 'utf8')); return d.douyinNames || [] } }
|
|
23
|
-
const files = fs.readdirSync(OUT_DIR).filter((f) => f.endsWith('.json')).map((f) => path.join(OUT_DIR, f))
|
|
24
|
-
if (!files.length) return []
|
|
25
|
-
files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)
|
|
26
|
-
return JSON.parse(fs.readFileSync(files[0], 'utf8')).douyinNames || []
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
async function j(p) { const r = await fetch(BASE + p); if (!r.ok) throw new Error('http ' + r.status); return r.json() }
|
|
30
|
-
async function connect(t) {
|
|
31
|
-
const ws = new WebSocket(t.webSocketDebuggerUrl)
|
|
32
|
-
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error('ws error')) })
|
|
33
|
-
const c = { ws, seq: 0, p: new Map() }
|
|
34
|
-
ws.onmessage = (e) => { let m; try { m = JSON.parse(e.data) } catch { return } if (m.id && c.p.has(m.id)) { const q = c.p.get(m.id); c.p.delete(m.id); m.error ? q.rej(new Error(JSON.stringify(m.error))) : q.res(m.result) } }
|
|
35
|
-
return c
|
|
36
|
-
}
|
|
37
|
-
function send(c, method, params = {}) { const id = ++c.seq; return new Promise((res, rej) => { c.p.set(id, { res, rej }); c.ws.send(JSON.stringify({ id, method, params })) }) }
|
|
38
|
-
async function ev(c, expr) { const r = await send(c, 'Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.text); return r.result?.value }
|
|
39
|
-
async function click(c, x, y) {
|
|
40
|
-
await send(c, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
|
|
41
|
-
await send(c, 'Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
|
|
42
|
-
await send(c, 'Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
|
|
43
|
-
}
|
|
44
|
-
const getSel = `(()=>{const t=document.body.innerText.replace(/[ \\t]+/g,' ');const m=t.match(/已选择\\s*(\\d+)\\/200/);return m?Number(m[1]):-1})()`
|
|
45
|
-
const clickTab = (name) => `(()=>{const ls=[...document.querySelectorAll('${NAV}')];for(const list of ls){const t=[...list.children].find(c=>c.innerText&&c.innerText.replace(/\\s+/g,' ').trim().includes(${JSON.stringify(name)}));if(t){t.click();return 'OK'}}return 'NOTAB'})()`
|
|
46
|
-
const listCards = `(()=>[...document.querySelectorAll('${CARD}')].map(c=>{const w=c.querySelector('[itemid]')||c;return w.getAttribute('itemid')}).filter(Boolean))()`
|
|
47
|
-
const cardPos = (id) => `(()=>{const c=[...document.querySelectorAll('${CARD}')].find(x=>{const w=x.querySelector('[itemid]')||x;return w.getAttribute('itemid')===${JSON.stringify(id)}});if(!c)return null;c.scrollIntoView({block:'center',inline:'nearest'});const r=c.getBoundingClientRect();if(r.width<10)return null;return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}})()`
|
|
48
|
-
const filterFind = `(()=>{const ins=[...document.querySelectorAll('input[type=checkbox]')];for(const i of ins){const lab=((i.closest('label')||i.parentElement||{}).innerText||'');if(lab.includes('过滤不良素材'))return i}return null})()`
|
|
49
|
-
const filterToggle = `(()=>{const i=${filterFind};if(!i)return 'NOBOX';i.click();return 'OK'})()`
|
|
50
|
-
|
|
51
|
-
async function pollCards(c, maxMs) {
|
|
52
|
-
const t0 = Date.now(); let ids = []
|
|
53
|
-
while (Date.now() - t0 < maxMs) {
|
|
54
|
-
ids = await ev(c, listCards)
|
|
55
|
-
if (ids.length) return ids
|
|
56
|
-
await sleep(400)
|
|
57
|
-
}
|
|
58
|
-
return ids
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
async function selectCards(c, ids) {
|
|
62
|
-
let clicked = 0, retried = 0
|
|
63
|
-
for (const id of ids) {
|
|
64
|
-
const p = await ev(c, cardPos(id))
|
|
65
|
-
if (!p) continue
|
|
66
|
-
await sleep(120)
|
|
67
|
-
const before = await ev(c, getSel)
|
|
68
|
-
await click(c, p.x, p.y)
|
|
69
|
-
await sleep(260)
|
|
70
|
-
let after = await ev(c, getSel)
|
|
71
|
-
if (after === before) {
|
|
72
|
-
const p2 = await ev(c, cardPos(id))
|
|
73
|
-
if (p2) { await sleep(120); await click(c, p2.x, p2.y); await sleep(320); retried++ }
|
|
74
|
-
}
|
|
75
|
-
clicked++
|
|
76
|
-
}
|
|
77
|
-
return { clicked, retried }
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const arg = process.argv[2]
|
|
81
|
-
const names = arg && arg.includes(',') ? arg.split(',').map((s) => s.trim()).filter(Boolean) : namesFor(arg)
|
|
82
|
-
if (!names.length) { console.log(JSON.stringify({ error: '没有抖音号名单:把名字用逗号串起来传进来' })); process.exit(1) }
|
|
83
|
-
const pages = (await j('/json/list')).filter((t) => t.type === 'page')
|
|
84
|
-
const page = pages.find((p) => p.url.includes('qianchuan')) || pages[0]
|
|
85
|
-
const c = await connect(page)
|
|
86
|
-
|
|
87
|
-
const modalOpen = await ev(c, `(()=>/已选择\\s*\\d+\\/200/.test(document.body.innerText))()`)
|
|
88
|
-
if (!modalOpen) { console.log(JSON.stringify({ error: '「添加视频」弹窗没开,先点「添加视频」' })); process.exit(1) }
|
|
89
|
-
|
|
90
|
-
const log = []
|
|
91
|
-
for (const name of names) {
|
|
92
|
-
const r = await ev(c, clickTab(name))
|
|
93
|
-
if (r !== 'OK') { log.push({ name, err: r }); continue }
|
|
94
|
-
let ids = await pollCards(c, 8000)
|
|
95
|
-
let refreshed = false
|
|
96
|
-
if (!ids.length) {
|
|
97
|
-
const t = await ev(c, filterToggle)
|
|
98
|
-
if (t === 'OK') { refreshed = true; await sleep(1200); ids = await pollCards(c, 12000) }
|
|
99
|
-
}
|
|
100
|
-
const before = await ev(c, getSel)
|
|
101
|
-
let sel = { clicked: 0, retried: 0 }
|
|
102
|
-
if (ids.length) sel = await selectCards(c, ids)
|
|
103
|
-
const after = await ev(c, getSel)
|
|
104
|
-
if (refreshed) { await ev(c, filterToggle); await sleep(600) }
|
|
105
|
-
log.push({ name, cards: ids.length, before, after, delta: after - before, retried: sel.retried, note: ids.length ? undefined : '该号主页无可投视频(取消过滤后仍为空)' })
|
|
106
|
-
}
|
|
107
|
-
const okb = await ev(c, `(()=>{const bs=[...document.querySelectorAll('button')].filter(b=>b.innerText.trim()==='确定'&&b.getBoundingClientRect().width>0);if(!bs.length)return 'NOOK';const r=bs[bs.length-1].getBoundingClientRect();return [Math.round(r.x+r.width/2),Math.round(r.y+r.height/2)]})()`)
|
|
108
|
-
let submitted = false
|
|
109
|
-
if (Array.isArray(okb)) { await click(c, okb[0], okb[1]); await sleep(5000); submitted = true }
|
|
110
|
-
const total = await ev(c, `(()=>{const m=document.body.innerText.match(/共\\d+个视频/);return m?m[0]:null})()`)
|
|
111
|
-
console.log(JSON.stringify({ ok: true, submitted, totalVideos: total, log }, null, 1))
|
|
112
|
-
process.exit(0)
|