dsh-qianchuan-toolkit 1.0.9 → 1.0.11
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 +15 -0
- package/assets/live-control/scripts/daily-supervisor.mjs +41 -0
- package/assets/live-control/scripts/hourly.mjs +98 -1
- package/assets/live-control/scripts/watchdog.mjs +156 -0
- package/assets/plan-copy/SKILL.md +15 -1
- package/assets/plan-copy/scripts/capture.mjs +156 -0
- package/assets/plan-copy/scripts/copy.mjs +86 -14
- package/assets/plan-copy/scripts/pick-all.mjs +22 -9
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## 1.0.11
|
|
4
|
+
|
|
5
|
+
- **看门狗(watchdog.mjs,新)**:独立进程,每 60 秒查三件事 —— ① 心跳文件 `heartbeat.json` 是否新鲜(超过 6 分钟没更新 / 超过 `nextAt` 判定卡死);② `supervisor.pid` / `watch.pid` 是否还活着;③ CDP 9222 是否连得上。发现问题立即推 **QQ + 企业微信**(同一故障 30 分钟内只推一次),能把守夜进程拉起来就自动拉起,恢复后再推一条「已恢复」。窗口外不检查、不打扰。
|
|
6
|
+
- **整点播报**:`hourly.mjs` 默认开启,每个整点(09:00、10:00…)推一条「X点播报」:本小时轮次数与时间点、最后一次的小时消耗/净成交/ROI/判定、本小时控量次数与结果、异常条数。**整点没收到播报 = 巡航掉线**,与看门狗互为兜底。`--no-digest` 可关闭。
|
|
7
|
+
- **开工 与 收工日报**:守夜进程每个窗口只推一次「已开工(窗口 07:00 ~ 次日 01:00)」;`--until` 到点收工前推「收工日报」(本次轮次数、控量成功/失败、异常条数、下一窗口时间)。
|
|
8
|
+
- 心跳由 `hourly.mjs` 每轮写入(含下一轮预计时间),看门狗据此判断是否卡死;`daily-supervisor.mjs` 负责拉起并每 2 分钟确认看门狗存活。
|
|
9
|
+
- 调试:`node hourly.mjs --digest-now --no-send` 只渲染上个小时播报;`node watchdog.mjs --once` 只检查一次并打印结果。
|
|
10
|
+
## 1.0.10
|
|
11
|
+
|
|
12
|
+
- **计划复制·批量跑通**:新增 `assets/plan-copy/scripts/capture.mjs`(按 ID 搜索 → 详情页抓抖音号/素材/ROI/预算/商品 → 生成 `qc/params-<原ID>.json`)。抖音号解析只取在投行(过滤「已删除」「无抖音号(仅含商城流量)」与计划行),aweme ID 支持 `_`/`.` 字符,修掉漏号与误取商品 ID。
|
|
13
|
+
- **发布后不再误判失败**:`copy.mjs` 的 `publish` 捕获 `Inspected target navigated or closed`(页面跳转导致 CDP target 失效),`all` 改为**重新导航列表并按首行计划名核验**新计划 ID,不再读旧标签页 DOM(旧页常残留搜索过滤后的空结果)。
|
|
14
|
+
- **素材弹层落位修复**:`addMaterialsViaDrawer` 先轮询 ≤18s 等「添加视频」弹层从右侧滑入落位,只有真在视口外才关标签重开(`reopen-tab`)重试一次,避免误重开与首次 0 选。
|
|
15
|
+
- `pick-all.mjs` 同步到最新版(同 itemid 多副本时只取 `elementFromPoint` 命中的坐标)。
|
|
16
|
+
- 文档:`assets/plan-copy/SKILL.md` 增加 capture/copy/notify-media 脚本说明与「抓参数→确认→删除→重建」四步命令、自动化要点。
|
|
17
|
+
|
|
3
18
|
## 1.0.9
|
|
4
19
|
|
|
5
20
|
- **巡航单实例锁(安全)**:`hourly.mjs --watch` 启动时写 `<QC_HOME>/watch.pid`,发现已有存活的巡航进程就直接退出(code 4)并提示,避免「开机自启的巡航」和「手动启动的巡航」同时提交造成重复控量。进程退出时自动清理锁文件;确认旧进程已死可手工删除该文件。
|
|
@@ -13,9 +13,11 @@ import { spawn } from 'node:child_process'
|
|
|
13
13
|
import path from 'node:path'
|
|
14
14
|
import fs from 'node:fs'
|
|
15
15
|
import { fileURLToPath } from 'node:url'
|
|
16
|
+
import { notify } from './notify.mjs'
|
|
16
17
|
|
|
17
18
|
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
18
19
|
const HOURLY = process.env.QC_HOURLY || path.join(here, 'hourly.mjs')
|
|
20
|
+
const WATCHDOG = process.env.QC_WATCHDOG || path.join(here, 'watchdog.mjs')
|
|
19
21
|
if (!fs.existsSync(HOURLY)) { console.error('找不到 hourly.mjs:' + HOURLY + '(可用 QC_HOURLY 指定)'); process.exit(2) }
|
|
20
22
|
const HOME = process.env.QC_HOME || path.join(here, '..', 'prod')
|
|
21
23
|
const argv = process.argv.slice(2)
|
|
@@ -60,6 +62,41 @@ function nextWindow(now = Date.now()) {
|
|
|
60
62
|
|
|
61
63
|
function fmt(ms) { return new Date(ms).toLocaleString('zh-CN') }
|
|
62
64
|
|
|
65
|
+
// ---- 看门狗:独立进程,自己盯着心跳/进程/CDP;本进程负责拉起它,并每 2 分钟确认它还活着 ----
|
|
66
|
+
function watchdogAlive() {
|
|
67
|
+
try {
|
|
68
|
+
const n = Number(String(fs.readFileSync(path.join(HOME, 'watchdog.pid'), 'utf8')).trim())
|
|
69
|
+
if (!n) return false
|
|
70
|
+
process.kill(n, 0)
|
|
71
|
+
return true
|
|
72
|
+
} catch (e) { return e.code === 'EPERM' }
|
|
73
|
+
}
|
|
74
|
+
function ensureWatchdog() {
|
|
75
|
+
if (!fs.existsSync(WATCHDOG)) return
|
|
76
|
+
if (watchdogAlive()) return
|
|
77
|
+
try {
|
|
78
|
+
const out = fs.openSync(path.join(HOME, 'watchdog.out.log'), 'a')
|
|
79
|
+
const c = spawn(process.execPath, [WATCHDOG, '--start', START, '--end', END], { stdio: ['ignore', out, out], env: { ...process.env, QC_HOME: HOME }, windowsHide: true })
|
|
80
|
+
log('看门狗已拉起 pid ' + c.pid)
|
|
81
|
+
c.on('exit', (code) => log('看门狗退出(退出码 ' + code + '),2 分钟后会重新拉起'))
|
|
82
|
+
} catch (e) { log('拉起看门狗失败:' + e.message) }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ---- 每个窗口只推一次「已开工」 ----
|
|
86
|
+
const WINDOW_STATE = path.join(HOME, '.window-notified.json')
|
|
87
|
+
async function notifyWindowStart(w) {
|
|
88
|
+
let last = 0
|
|
89
|
+
try { last = Number(JSON.parse(fs.readFileSync(WINDOW_STATE, 'utf8')).start) || 0 } catch (e) {}
|
|
90
|
+
if (last === w.start) return
|
|
91
|
+
try { fs.mkdirSync(HOME, { recursive: true }); fs.writeFileSync(WINDOW_STATE, JSON.stringify({ start: w.start })) } catch (e) {}
|
|
92
|
+
const text = [
|
|
93
|
+
'窗口:' + fmt(w.start) + ' ~ ' + fmt(w.end),
|
|
94
|
+
'从现在起正常轮次不再打扰你;每个整点推一条「X点播报」,01:00 推收工日报。',
|
|
95
|
+
'整点没有播报 = 巡航掉线,看门狗会同时告警。',
|
|
96
|
+
].join(String.fromCharCode(10))
|
|
97
|
+
await notify({ dir: HOME, title: '千川巡航:已开工', text, level: 'info', event: 'start', say: (s) => log(' notify: ' + s) }).catch(() => {})
|
|
98
|
+
}
|
|
99
|
+
|
|
63
100
|
async function runOnce() {
|
|
64
101
|
const args = ['--watch', '--max-rounds', '1000', '--until', END]
|
|
65
102
|
log('启动巡航:hourly.mjs ' + args.join(' '))
|
|
@@ -81,6 +118,8 @@ if (PLAN_ONLY) {
|
|
|
81
118
|
try { fs.writeFileSync(path.join(HOME, 'supervisor.pid'), String(process.pid)) } catch { /* 忽略 */ }
|
|
82
119
|
process.on('exit', () => { try { if (String(fs.readFileSync(path.join(HOME, 'supervisor.pid'), 'utf8')).trim() === String(process.pid)) fs.unlinkSync(path.join(HOME, 'supervisor.pid')) } catch { /* 忽略 */ } })
|
|
83
120
|
log('守夜进程启动:每天 ' + START + ' 开始,次日 ' + END + ' 收工(数据目录 ' + HOME + ')')
|
|
121
|
+
ensureWatchdog()
|
|
122
|
+
setInterval(() => { try { ensureWatchdog() } catch (e) { /* 忽略 */ } }, 120000)
|
|
84
123
|
for (;;) {
|
|
85
124
|
const w = nextWindow()
|
|
86
125
|
if (!w.inWindow) {
|
|
@@ -89,6 +128,8 @@ for (;;) {
|
|
|
89
128
|
continue
|
|
90
129
|
}
|
|
91
130
|
log('现在在窗口内(' + fmt(w.start) + ' ~ ' + fmt(w.end) + '),开始巡航')
|
|
131
|
+
ensureWatchdog()
|
|
132
|
+
await notifyWindowStart(w).catch(() => {})
|
|
92
133
|
const code = await runOnce()
|
|
93
134
|
const still = nextWindow()
|
|
94
135
|
if (!still.inWindow) continue // 已到收工点:回到循环顶部睡到下一个开始时间
|
|
@@ -31,6 +31,7 @@ const STAGE_MS = Number(arg('stage-timeout', '90')) * 1000
|
|
|
31
31
|
const ROUND_MS = Number(arg('round-timeout', '420')) * 1000
|
|
32
32
|
const SHOTS = arg('shots', paths().home)
|
|
33
33
|
const REPORT_ALL = has('report-all') // 每轮都把结果推给通知通道(默认只报异常)
|
|
34
|
+
const DIGEST = !has('no-digest') // 整点播报:每个整点推一次上一小时摘要(--no-digest 关闭)
|
|
34
35
|
const UNTIL = arg('until', '') // 例:--until 01:00 跑到次日 01:00 自动收工
|
|
35
36
|
function deadlineOf(hhmm) {
|
|
36
37
|
const m = String(hhmm).match(/^(\d{1,2}):(\d{2})$/)
|
|
@@ -546,6 +547,72 @@ async function executeAccount(group, rec) {
|
|
|
546
547
|
}
|
|
547
548
|
}
|
|
548
549
|
|
|
550
|
+
|
|
551
|
+
// ---------- 心跳 + 整点播报 ----------
|
|
552
|
+
// 心跳:每轮写入 heartbeat.json,看门狗据 nextAt 判断是否卡死
|
|
553
|
+
const HB_FILE = path.join(P.home, 'heartbeat.json')
|
|
554
|
+
function writeHeartbeat(o) {
|
|
555
|
+
try { fs.mkdirSync(P.home, { recursive: true }); fs.writeFileSync(HB_FILE, JSON.stringify({ ts: new Date().toISOString(), pid: process.pid, ...o })) } catch (e) { /* 心跳失败不影响巡航 */ }
|
|
556
|
+
}
|
|
557
|
+
function hourStartOf(t = Date.now()) { const d = new Date(t); d.setMinutes(0, 0, 0); return d.getTime() }
|
|
558
|
+
const DIGEST_STATE = path.join(P.home, '.digest-state.json')
|
|
559
|
+
function loadDigestLast() { try { const n = Number(JSON.parse(fs.readFileSync(DIGEST_STATE, 'utf8')).lastAt); if (n > 0) return n } catch (e) {} return 0 }
|
|
560
|
+
function saveDigestLast(n) { try { fs.mkdirSync(P.home, { recursive: true }); fs.writeFileSync(DIGEST_STATE, JSON.stringify({ lastAt: n })) } catch (e) {} }
|
|
561
|
+
let DIGEST_LAST = WATCH && DIGEST ? (loadDigestLast() || hourStartOf()) : 0
|
|
562
|
+
function readJsonlFile(f) {
|
|
563
|
+
try { return fs.readFileSync(f, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch (e) { return null } }).filter(Boolean) } catch (e) { return [] }
|
|
564
|
+
}
|
|
565
|
+
const tms = (s) => new Date(s).getTime()
|
|
566
|
+
const hm2 = (t) => new Date(t).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
|
|
567
|
+
|
|
568
|
+
// 整点播报:把上一个整点小时的巡航日志压成一条,用户看「整点有没有消息」就知道是否还在跑
|
|
569
|
+
function digestInfo(hs) {
|
|
570
|
+
const he = hs + 3600000
|
|
571
|
+
const rounds = readJsonlFile(P.rounds).filter((r) => { const t = tms(r.ts); return t >= hs && t < he })
|
|
572
|
+
const acts = readJsonlFile(P.actions).filter((a) => { const t = tms(a.ts); return t >= hs && t < he })
|
|
573
|
+
const hh = new Date(hs).getHours()
|
|
574
|
+
const head = '千川巡航 · ' + hh + '点播报'
|
|
575
|
+
if (!rounds.length) {
|
|
576
|
+
return { title: '⚠️' + head, level: 'warn', text: ['本小时 0 轮:没有收到任何巡航记录。', '如果不是你手动停的,请检查巡航是否还在跑。'].join('\n') }
|
|
577
|
+
}
|
|
578
|
+
const decisions = []
|
|
579
|
+
let anomalies = 0
|
|
580
|
+
for (const r of rounds) {
|
|
581
|
+
for (const a of r.accounts || []) {
|
|
582
|
+
anomalies += (a.anomalies || []).length
|
|
583
|
+
for (const d of a.decisions || []) decisions.push({ t: tms(r.ts), d })
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
const lines = ['轮次 ' + rounds.length + ' 次(' + rounds.map((r) => hm2(tms(r.ts))).join(' / ') + ')']
|
|
587
|
+
if (decisions.length) {
|
|
588
|
+
const lastOne = decisions[decisions.length - 1]
|
|
589
|
+
const d = lastOne.d
|
|
590
|
+
let tail = d.decision.action
|
|
591
|
+
if (d.decision.action === 'control') tail = 'control:应控 ' + (d.decision.budget || '?') + ' 元'
|
|
592
|
+
else if (d.decision.reason) tail += ':' + d.decision.reason
|
|
593
|
+
lines.push('最后 ' + hm2(lastOne.t) + ':消耗 ' + d.cost + ' / 净成交 ' + d.gmv + ' / ROI ' + d.roi + ' → ' + tail)
|
|
594
|
+
}
|
|
595
|
+
if (acts.length) {
|
|
596
|
+
const okN = acts.filter((a) => a.ok).length
|
|
597
|
+
lines.push('控量 ' + acts.length + ' 次(成功 ' + okN + ' / 失败 ' + (acts.length - okN) + '):' + acts.map((a) => hm2(tms(a.ts)) + (a.ok ? ' ✅' : ' ❌')).join('、'))
|
|
598
|
+
}
|
|
599
|
+
lines.push('异常 ' + anomalies + ' 条')
|
|
600
|
+
return { title: (anomalies ? '⚠️' : '') + head, text: lines.join('\n'), level: anomalies ? 'warn' : 'info' }
|
|
601
|
+
}
|
|
602
|
+
async function pushDigest(hs) {
|
|
603
|
+
const d = digestInfo(hs)
|
|
604
|
+
await notify({ dir: P.home, title: d.title, text: d.text, level: d.level, event: 'digest', say: (s) => log(' notify: ' + s) }).catch(() => {})
|
|
605
|
+
log('已推送 ' + d.title)
|
|
606
|
+
}
|
|
607
|
+
async function flushDueDigests() {
|
|
608
|
+
if (!(WATCH && DIGEST)) return
|
|
609
|
+
while (DIGEST_LAST + 3605000 <= Date.now()) {
|
|
610
|
+
await pushDigest(DIGEST_LAST)
|
|
611
|
+
DIGEST_LAST += 3600000
|
|
612
|
+
saveDigestLast(DIGEST_LAST)
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
549
616
|
// ---------- 每轮结果推送(--report-all 时,不论正常还是异常都发) ----------
|
|
550
617
|
async function reportRound(i, recs, nextAt) {
|
|
551
618
|
const lines = []
|
|
@@ -596,6 +663,13 @@ function nextSlot(nodes, extraAt = [], lastStart = 0) {
|
|
|
596
663
|
}
|
|
597
664
|
|
|
598
665
|
// ---- main ----
|
|
666
|
+
if (has('digest-now')) { // 调试用:只渲染上一个整点的播报内容;加 --no-send 不实际推送
|
|
667
|
+
const hs = hourStartOf(Date.now()) - 3600000
|
|
668
|
+
const d = digestInfo(hs)
|
|
669
|
+
console.log(d.title + String.fromCharCode(10) + d.text)
|
|
670
|
+
if (!has('no-send') && !DRY) await pushDigest(hs)
|
|
671
|
+
process.exit(0)
|
|
672
|
+
}
|
|
599
673
|
if (has('doctor')) {
|
|
600
674
|
console.log('数据目录 ' + P.home)
|
|
601
675
|
for (const g of groupByAccount(cfg)) for (const t of g.targets) {
|
|
@@ -628,6 +702,7 @@ if (START_AT_MS) {
|
|
|
628
702
|
log('定时启动:等到 ' + new Date(START_AT_MS).toLocaleString('zh-CN') + ' 才开始巡航(约 ' + Math.round(ms / 60000) + ' 分钟后)')
|
|
629
703
|
await sleep(ms)
|
|
630
704
|
}
|
|
705
|
+
writeHeartbeat({ round: 0, nextAt: Date.now() + 15 * 60000, phase: 'starting' })
|
|
631
706
|
log('本轮 ' + groups.length + ' 个账号 / ' + groups.reduce((s, g) => s + g.targets.length, 0) + ' 个目标' + (DRY ? ' [dry-run]' : '') + (REPORT_ALL ? ' [每轮推送]' : '') + (DEADLINE ? ' [跑到 ' + new Date(DEADLINE).toLocaleString('zh-CN') + ']' : ''))
|
|
632
707
|
if (REPORT_ALL && WATCH) {
|
|
633
708
|
const r0 = resolveRule(cfg, groups[0].targets[0])
|
|
@@ -663,12 +738,25 @@ try {
|
|
|
663
738
|
}
|
|
664
739
|
for (const rec of recs) { delete rec._group }
|
|
665
740
|
jl(P.rounds, { ts: new Date().toISOString(), round: i, ms: Date.now() - roundStart, accounts: recs })
|
|
741
|
+
writeHeartbeat({ round: i, ms: Date.now() - roundStart, nextAt: 0 })
|
|
666
742
|
log('本轮耗时 ' + ((Date.now() - roundStart) / 1000).toFixed(1) + 's')
|
|
667
743
|
const nodes = [...new Set(groups.flatMap((g) => g.targets.flatMap((t) => resolveRule(cfg, t).nodes)))].sort((a, b) => a - b)
|
|
668
744
|
const last = i === MAX_ROUNDS
|
|
669
745
|
const next = last ? 0 : nextSlot(nodes, extras, roundStart)
|
|
746
|
+
const digestDue = WATCH && DIGEST ? DIGEST_LAST + 3605000 : 0
|
|
747
|
+
const wakeAt = last ? digestDue : (digestDue && digestDue < next - 5000 ? digestDue : next)
|
|
748
|
+
writeHeartbeat({ round: i, ms: Date.now() - roundStart, nextAt: wakeAt || 0, nextRound: next || 0 })
|
|
670
749
|
// 有异常时即使没开 --report-all 也要推,异常必须让人看到
|
|
671
750
|
if (REPORT_ALL || recs.some((r) => (r.anomalies || []).length)) await reportRound(i, recs, next)
|
|
751
|
+
await flushDueDigests()
|
|
752
|
+
if (WATCH && DIGEST && !last) {
|
|
753
|
+
const due = DIGEST_LAST + 3605000
|
|
754
|
+
if (due < next - 5000) {
|
|
755
|
+
log('整点播报:等到 ' + new Date(due).toLocaleString('zh-CN'))
|
|
756
|
+
await sleep(Math.max(0, due - Date.now()))
|
|
757
|
+
await flushDueDigests()
|
|
758
|
+
}
|
|
759
|
+
}
|
|
672
760
|
if (last) break
|
|
673
761
|
if (DEADLINE && next > DEADLINE) {
|
|
674
762
|
const remain = DEADLINE - Date.now()
|
|
@@ -680,7 +768,16 @@ try {
|
|
|
680
768
|
continue
|
|
681
769
|
}
|
|
682
770
|
log('已到收工时间 ' + new Date(DEADLINE).toLocaleString('zh-CN') + ',巡航结束')
|
|
683
|
-
|
|
771
|
+
await flushDueDigests()
|
|
772
|
+
if (WATCH) {
|
|
773
|
+
const since = Date.now() - 20 * 3600000
|
|
774
|
+
const rs = readJsonlFile(P.rounds).filter((r) => tms(r.ts) >= since)
|
|
775
|
+
const acts = readJsonlFile(P.actions).filter((a) => tms(a.ts) >= since)
|
|
776
|
+
const okN = acts.filter((a) => a.ok).length
|
|
777
|
+
const errN = readJsonlFile(P.errors).filter((e) => tms(e.ts) >= since).length
|
|
778
|
+
const text = ['收工时间:' + new Date(DEADLINE).toLocaleString('zh-CN'), '本次共 ' + rs.length + ' 轮,控量 ' + acts.length + ' 次(成功 ' + okN + ' / 失败 ' + (acts.length - okN) + ')', '异常记录 ' + errN + ' 条', '下一窗口:明天 07:00 自动开始(看门狗全程盯着)'].join(String.fromCharCode(10))
|
|
779
|
+
await notify({ dir: P.home, title: '千川巡航:收工日报', text, level: 'info', event: 'stop', say: (s) => log(' notify: ' + s) }).catch(() => {})
|
|
780
|
+
}
|
|
684
781
|
break
|
|
685
782
|
}
|
|
686
783
|
const waitMs = Math.max(0, next - Date.now())
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* watchdog.mjs —— 巡航看门狗(独立进程,60 秒一轮)
|
|
4
|
+
*
|
|
5
|
+
* 为什么需要它:巡航进程自己死了就发不出消息,必须有一个「旁观者」。
|
|
6
|
+
* 它做三件事:
|
|
7
|
+
* 1) 心跳检查:读 <QC_HOME>/heartbeat.json,超过 stale-min 分钟没更新 → 判卡死
|
|
8
|
+
* 2) 进程检查:supervisor.pid / watch.pid 是否还活着
|
|
9
|
+
* 3) 环境检查:CDP 9222 是否还能连上(Chrome 是否被关掉)
|
|
10
|
+
* 发现问题 → 能自动重启的就重启(守夜进程死了直接拉起来),然后推送告警;
|
|
11
|
+
* 恢复后再推一条「已恢复」。同一故障 30 分钟内只推一次,避免刷屏。
|
|
12
|
+
*
|
|
13
|
+
* node watchdog.mjs 长时间运行(由守夜进程拉起)
|
|
14
|
+
* node watchdog.mjs --once 只检查一次,打印结果(调试用)
|
|
15
|
+
* node watchdog.mjs --start 07:00 --end 01:00
|
|
16
|
+
* node watchdog.mjs --stale-min 6 --interval 60
|
|
17
|
+
*/
|
|
18
|
+
import fs from 'node:fs'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { spawn } from 'node:child_process'
|
|
21
|
+
import { fileURLToPath } from 'node:url'
|
|
22
|
+
import { notify } from './notify.mjs'
|
|
23
|
+
|
|
24
|
+
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
25
|
+
const HOME = process.env.QC_HOME || path.join(here, '..', 'prod')
|
|
26
|
+
const SUPERVISOR = process.env.QC_SUPERVISOR || path.join(here, 'daily-supervisor.mjs')
|
|
27
|
+
const argv = process.argv.slice(2)
|
|
28
|
+
const arg = (k, d) => { const i = argv.indexOf('--' + k); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : d }
|
|
29
|
+
const has = (k) => argv.includes('--' + k)
|
|
30
|
+
|
|
31
|
+
const START = arg('start', '07:00')
|
|
32
|
+
const END = arg('end', '01:00')
|
|
33
|
+
const ONCE = has('once')
|
|
34
|
+
const INTERVAL = Math.max(20, Number(arg('interval', '60'))) * 1000
|
|
35
|
+
const STALE_MS = Math.max(2, Number(arg('stale-min', '6'))) * 60000
|
|
36
|
+
const ALERT_WIN = 30 * 60000
|
|
37
|
+
|
|
38
|
+
const log = (...a) => console.log(new Date().toLocaleString('zh-CN'), ...a)
|
|
39
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
40
|
+
const P = (f) => path.join(HOME, f)
|
|
41
|
+
|
|
42
|
+
const hm = (s) => { const m = String(s).match(/^(\d{1,2}):(\d{2})$/); if (!m) throw new Error('时间格式应为 HH:MM:' + s); return Number(m[1]) * 3600000 + Number(m[2]) * 60000 }
|
|
43
|
+
const START_OFF = hm(START)
|
|
44
|
+
const END_OFF = hm(END)
|
|
45
|
+
const midnight = (now = Date.now()) => { const d = new Date(now); d.setHours(0, 0, 0, 0); return d.getTime() }
|
|
46
|
+
function windowOfDay(dayStart) {
|
|
47
|
+
const start = dayStart + START_OFF
|
|
48
|
+
let end = dayStart + END_OFF
|
|
49
|
+
if (end <= start) end += 86400000
|
|
50
|
+
return { start, end }
|
|
51
|
+
}
|
|
52
|
+
function inWindow(now = Date.now()) {
|
|
53
|
+
const d0 = midnight(now)
|
|
54
|
+
for (let i = -1; i <= 1; i++) { const w = windowOfDay(d0 + i * 86400000); if (now >= w.start && now < w.end) return true }
|
|
55
|
+
return false
|
|
56
|
+
}
|
|
57
|
+
function nextStart(now = Date.now()) {
|
|
58
|
+
const d0 = midnight(now)
|
|
59
|
+
for (let i = 0; i <= 2; i++) { const w = windowOfDay(d0 + i * 86400000); if (w.start > now) return w.start }
|
|
60
|
+
return now + 86400000
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const readJson = (f) => { try { return JSON.parse(fs.readFileSync(P(f), 'utf8')) } catch (e) { return null } }
|
|
64
|
+
const readPid = (f) => { try { const n = Number(String(fs.readFileSync(P(f), 'utf8')).trim()); return n > 0 ? n : 0 } catch (e) { return 0 } }
|
|
65
|
+
function alive(pid) { if (!pid) return false; try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
|
|
66
|
+
|
|
67
|
+
// 告警去重:同一 kind 30 分钟一次
|
|
68
|
+
function readAlerts() { return readJson('.watchdog-alerts.json') || {} }
|
|
69
|
+
function saveAlerts(o) { const now = Date.now(); for (const k of Object.keys(o)) if (now - Number(o[k] || 0) > 7 * 86400000) delete o[k]; try { fs.mkdirSync(HOME, { recursive: true }); fs.writeFileSync(P('.watchdog-alerts.json'), JSON.stringify(o)) } catch (e) {} }
|
|
70
|
+
async function alertOnce(kind, title, text, level = 'error') {
|
|
71
|
+
const m = readAlerts()
|
|
72
|
+
if (Date.now() - Number(m[kind] || 0) < ALERT_WIN) { log('(' + kind + ' 30 分钟内已报过,不重复推送)'); return false }
|
|
73
|
+
m[kind] = Date.now(); saveAlerts(m)
|
|
74
|
+
await notify({ dir: HOME, title, text, level, event: kind, say: (s) => log(' notify: ' + s) }).catch(() => {})
|
|
75
|
+
return true
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function cdpOk() {
|
|
79
|
+
try {
|
|
80
|
+
const r = await fetch('http://127.0.0.1:9222/json/version', { signal: AbortSignal.timeout(5000) })
|
|
81
|
+
return r.ok
|
|
82
|
+
} catch (e) { return false }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function startSupervisor() {
|
|
86
|
+
try {
|
|
87
|
+
const out = fs.openSync(P('supervisor.out.log'), 'a')
|
|
88
|
+
const child = spawn(process.execPath, [SUPERVISOR, '--start', START, '--end', END], { stdio: ['ignore', out, out], env: { ...process.env, QC_HOME: HOME }, detached: true, windowsHide: true })
|
|
89
|
+
child.unref()
|
|
90
|
+
log('已重新拉起守夜进程 pid ' + child.pid)
|
|
91
|
+
return child.pid
|
|
92
|
+
} catch (e) { log('拉起守夜进程失败:' + e.message); return 0 }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function check() {
|
|
96
|
+
const now = Date.now()
|
|
97
|
+
const hb = readJson('heartbeat.json')
|
|
98
|
+
const supPid = readPid('supervisor.pid')
|
|
99
|
+
const watchPid = readPid('watch.pid')
|
|
100
|
+
const issues = []
|
|
101
|
+
|
|
102
|
+
if (!hb) issues.push({ kind: 'no-heartbeat', msg: '还没有心跳文件(巡航可能从未成功跑过一轮)' })
|
|
103
|
+
else {
|
|
104
|
+
const hbMs = new Date(hb.ts).getTime()
|
|
105
|
+
const age = now - hbMs
|
|
106
|
+
const overdue = hb.nextAt && now > Number(hb.nextAt) + STALE_MS
|
|
107
|
+
if (age > STALE_MS || overdue) issues.push({ kind: 'heartbeat-stale', msg: '心跳停止 ' + Math.round(age / 60000) + ' 分钟(最后 ' + new Date(hb.ts).toLocaleString('zh-CN') + ',第 ' + (hb.round || '?') + ' 轮' + (hb.nextAt ? ',应于 ' + new Date(hb.nextAt).toLocaleString('zh-CN') + ' 有新心跳' : '') + ')' })
|
|
108
|
+
}
|
|
109
|
+
if (!alive(supPid)) issues.push({ kind: 'supervisor-dead', msg: '守夜进程不存在(supervisor.pid=' + (supPid || '无') + ')' })
|
|
110
|
+
if (!alive(watchPid) && inWindow(now)) issues.push({ kind: 'watch-dead', msg: '巡航进程不存在(watch.pid=' + (watchPid || '无') + ')' })
|
|
111
|
+
const cdp = await cdpOk()
|
|
112
|
+
if (!cdp) issues.push({ kind: 'cdp-down', msg: 'CDP 9222 连不上(Chrome 被关掉或未启动)' })
|
|
113
|
+
|
|
114
|
+
if (!issues.length) return { ok: true }
|
|
115
|
+
log('发现问题:' + issues.map((x) => x.kind).join(', '))
|
|
116
|
+
const fixed = []
|
|
117
|
+
if (issues.some((x) => x.kind === 'supervisor-dead')) { const pid = startSupervisor(); if (pid) fixed.push('守夜进程已重启(pid ' + pid + ')') }
|
|
118
|
+
if (!cdp) fixed.push('请双击 start-qc.cmd 重新打开 Chrome 并登录千川')
|
|
119
|
+
if (issues.some((x) => x.kind === 'watch-dead') && alive(supPid)) fixed.push('守夜进程会自动重拉巡航(最多 5 分钟)')
|
|
120
|
+
|
|
121
|
+
const title = '🚨【巡航看门狗】' + (issues.some((x) => x.kind === 'cdp-down' || x.kind === 'supervisor-dead') ? '巡航已中断' : '巡航可能卡住')
|
|
122
|
+
const text = ['检查时间:' + new Date(now).toLocaleString('zh-CN'), ...issues.map((x) => '• ' + x.msg), ...(fixed.length ? ['', '已处理:', ...fixed.map((s) => '• ' + s)] : []), hb && hb.round ? '最后成功轮次:第 ' + hb.round + ' 轮(' + new Date(hb.ts).toLocaleString('zh-CN') + ')' : ''].filter(Boolean).join('\n')
|
|
123
|
+
await alertOnce('watchdog', title, text)
|
|
124
|
+
return { ok: false, issues }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function recovery() {
|
|
128
|
+
const m = readAlerts()
|
|
129
|
+
if (!m['watchdog']) return
|
|
130
|
+
delete m['watchdog']; saveAlerts(m)
|
|
131
|
+
await notify({ dir: HOME, title: '✅【巡航看门狗】已恢复', text: '之前报过的问题已消失,心跳与进程均正常。\n时间:' + new Date().toLocaleString('zh-CN'), level: 'info', event: 'watchdog-recover', say: (s) => log(' notify: ' + s) }).catch(() => {})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (ONCE) {
|
|
135
|
+
const r = await check()
|
|
136
|
+
console.log(JSON.stringify({ inWindow: inWindow(), ...r }))
|
|
137
|
+
process.exit(r.ok ? 0 : 1)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 单实例
|
|
141
|
+
const lock = P('watchdog.pid')
|
|
142
|
+
try {
|
|
143
|
+
const old = readPid('watchdog.pid')
|
|
144
|
+
if (old && old !== process.pid && alive(old)) { console.error('已有看门狗在跑(pid ' + old + '),本次不重复启动'); process.exit(4) }
|
|
145
|
+
} catch (e) {}
|
|
146
|
+
try { fs.mkdirSync(HOME, { recursive: true }); fs.writeFileSync(lock, String(process.pid)) } catch (e) {}
|
|
147
|
+
process.on('exit', () => { try { if (String(fs.readFileSync(lock, 'utf8')).trim() === String(process.pid)) fs.unlinkSync(lock) } catch (e) {} })
|
|
148
|
+
|
|
149
|
+
log('看门狗启动:窗口 ' + START + ' ~ 次日 ' + END + ',每 ' + Math.round(INTERVAL / 1000) + ' 秒检查一次(数据目录 ' + HOME + ')')
|
|
150
|
+
for (;;) {
|
|
151
|
+
if (!inWindow()) { await sleep(Math.min(Math.max(60000, nextStart() - Date.now()), 30 * 60000)); continue }
|
|
152
|
+
let r
|
|
153
|
+
try { r = await check() } catch (e) { log('检查异常:' + e.message); r = { ok: true } }
|
|
154
|
+
if (r.ok) await recovery().catch(() => {})
|
|
155
|
+
await sleep(INTERVAL)
|
|
156
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 千川乘方「复制计划」技能包
|
|
2
2
|
|
|
3
|
-
> **资源位置**:本技能的资源基目录下有 `scripts/`(cdp.mjs、gen-batch11.mjs、pick-all.mjs、start-qc.cmd)与 `references/`(完整手册、界面结构、弹窗处理、浏览器会话)。下文出现的 `scripts/xxx.mjs` 都相对这个基目录;截图与记录可以写到任意工作目录,建议统一放一个 `qc/` 目录。
|
|
3
|
+
> **资源位置**:本技能的资源基目录下有 `scripts/`(cdp.mjs、copy.mjs、capture.mjs、gen-batch11.mjs、pick-all.mjs、notify-media.mjs、start-qc.cmd)与 `references/`(完整手册、界面结构、弹窗处理、浏览器会话)。下文出现的 `scripts/xxx.mjs` 都相对这个基目录;截图与记录可以写到任意工作目录,建议统一放一个 `qc/` 目录。
|
|
4
4
|
>
|
|
5
5
|
> **运行环境**:Windows 或 macOS;Microsoft Edge / Google Chrome 任一(用 `--remote-debugging-port=9222` 开调试端口);Node 18+,脚本零第三方依赖。**不要假设用户用的是哪个浏览器、哪个 profile、哪个千川账户**——1.1 和 1.2 会先探测再动手。
|
|
6
6
|
|
|
@@ -362,6 +362,9 @@ node scripts/pick-all.mjs "抖音号名1,抖音号名2,...,抖音号名N"
|
|
|
362
362
|
| `scripts/cdp.mjs` | 通用 CDP 执行器(所有操作都用它) |
|
|
363
363
|
| `scripts/gen-batch11.mjs` | 抖音号抽屉批量按 ID 搜索 + 勾选(最稳版本) |
|
|
364
364
|
| `scripts/pick-all.mjs` | 添加视频弹窗按抖音号名称逐号全选并提交 |
|
|
365
|
+
| `scripts/capture.mjs` | 按计划 ID 抓参数(详情页抖音号/素材/ROI/预算/商品)→ 生成 `qc/params-<原ID>.json`,供 copy.mjs 直接使用 |
|
|
366
|
+
| `scripts/copy.mjs` | 一条龙:`confirm`(删除前确认单+截图推送)→ `delete <TOKEN>` → `all`(新建+发布+找新ID+加素材);另有 `create/publish/materials/search/click` 子命令 |
|
|
367
|
+
| `scripts/notify-media.mjs` | 确认图推送 QQ 官方机器人 + 企业微信(copy.mjs confirm 自动调用) |
|
|
365
368
|
| `scripts/start-qc.cmd` | 双击启动 Edge(9222 + 固定 profile) |
|
|
366
369
|
|
|
367
370
|
用法示例:
|
|
@@ -373,8 +376,19 @@ node scripts/cdp.mjs b1.json
|
|
|
373
376
|
|
|
374
377
|
# 素材全选(逗号名单,单号也要带尾逗号)
|
|
375
378
|
node scripts/pick-all.mjs "盖盖,蓝莓多米,在下猫猫雨哎"
|
|
379
|
+
|
|
380
|
+
# 抓参数 → 出确认单 → 删除 → 重建(新名后缀 1124)
|
|
381
|
+
node scripts/capture.mjs 1860422794525708 1880459534529783 qc/params-1880459534529783.json 1124
|
|
382
|
+
node scripts/copy.mjs confirm 1860422794525708 1880459534529783 # 打印 TOKEN + 截图
|
|
383
|
+
node scripts/copy.mjs delete 1860422794525708 1880459534529783 <TOKEN>
|
|
384
|
+
node scripts/copy.mjs all 1860422794525708 qc/params-1880459534529783.json
|
|
376
385
|
```
|
|
377
386
|
|
|
387
|
+
自动化要点(1.0.10 起已在代码里):
|
|
388
|
+
- 发布后 CDP 会报 `Inspected target navigated or closed`,这是页面跳转,发布通常已成功;`all` 会重导航列表并**按首行计划名核验**新计划 ID,不再依赖旧标签页 DOM。
|
|
389
|
+
- 「添加视频」弹层从右侧滑入会短暂停在视口外(x≈innerWidth):先**轮询等落位 ≤18s**,真异常才关标签重开(`reopen-tab`)重试。
|
|
390
|
+
- 详情页「抖音号」tab 解析只取在投行:过滤「已删除」「无抖音号(仅含商城流量)」与计划行;aweme ID 含 `_`、`.`(如 `Xxxxxx_789.`、`_0528ff`、`Yang33ei.`),字符集不能只写 `[A-Za-z0-9]`。
|
|
391
|
+
|
|
378
392
|
> 换账户时:把全文的 `aavid=1860000000000001` 换掉,profile 目录换成对应账户专用目录(不同账户建议分开 profile)。
|
|
379
393
|
|
|
380
394
|
## 7. 一句话流程
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 抓取乘方-推商品计划参数:列表搜 ID -> 唯一命中 -> 详情页 抖音号/素材 -> params.json
|
|
3
|
+
// 用法: node capture.mjs <aavid> <planId> <outJson> [newDateSuffix]
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import { connect, sleep, listPages } from '../../live-control/scripts/cdp-lib.mjs';
|
|
6
|
+
|
|
7
|
+
const aavid = process.argv[2], planId = process.argv[3], outFile = process.argv[4], suffix = process.argv[5] || '1124';
|
|
8
|
+
if (!aavid || !planId || !outFile) { console.log('usage: node capture.mjs <aavid> <planId> <outJson> [suffix]'); process.exit(2); }
|
|
9
|
+
const listUrl = 'https://qianchuan.jinritemai.com/overall-prom?aavid=' + aavid + '&campaignType=1&uniTab=ad&uniVideoTab=1&overallPromViewTab=plan';
|
|
10
|
+
const t0 = Date.now();
|
|
11
|
+
const mark = (l, e) => console.log('[' + ((Date.now() - t0) / 1000).toFixed(1) + 's] ' + l + (e ? ' ' + e : ''));
|
|
12
|
+
setTimeout(() => { console.log('[WATCHDOG] 超时退出'); process.exit(9) }, Number(process.env.QC_WATCHDOG || 240000));
|
|
13
|
+
|
|
14
|
+
async function prepFn() {
|
|
15
|
+
const pid = window.__qcArg;
|
|
16
|
+
const T = (s) => (s || '').replace(/[\s\u00a0]+/g, ' ').trim();
|
|
17
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
18
|
+
const tab = [...document.querySelectorAll('.aurora-qc-tabs-tab-btn')].find((x) => T(x.innerText) === '商品');
|
|
19
|
+
if (tab) { tab.click(); await sleep(5000) }
|
|
20
|
+
const ct = (w) => { const els = [...document.querySelectorAll('*')].filter((x) => x.children.length === 0 && T(x.innerText) === w && x.getBoundingClientRect().width > 0); if (!els.length) return 'miss'; els[els.length - 1].click(); return 'ok' };
|
|
21
|
+
ct('计划视图'); await sleep(1500); ct('商品自选'); await sleep(5000);
|
|
22
|
+
const inp = [...document.querySelectorAll('input')].find((x) => /回车搜索|计划名称|计划ID/.test(x.placeholder || ''));
|
|
23
|
+
if (!inp) return JSON.stringify({ err: 'noinput', ph: [...document.querySelectorAll('input')].map((i) => i.placeholder).slice(0, 10) });
|
|
24
|
+
const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
|
25
|
+
set.call(inp, pid); inp.dispatchEvent(new Event('input', { bubbles: true }));
|
|
26
|
+
inp.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, bubbles: true }));
|
|
27
|
+
await sleep(8000);
|
|
28
|
+
const rows = [...document.querySelectorAll('tbody tr')].map((r) => T(r.innerText)).filter((t) => t.indexOf('ID:') >= 0);
|
|
29
|
+
const row = [...document.querySelectorAll('tbody tr')].find((r) => T(r.innerText).includes(pid));
|
|
30
|
+
if (rows.length !== 1 || !row) return JSON.stringify({ err: 'notunique', n: rows.length });
|
|
31
|
+
const name = T(rows[0]).split(' ID')[0];
|
|
32
|
+
const nameEl = [...row.querySelectorAll('*')].find((e) => e.children.length === 0 && T(e.innerText) === name);
|
|
33
|
+
if (!nameEl) return JSON.stringify({ err: 'noname', name });
|
|
34
|
+
nameEl.click(); await sleep(4500);
|
|
35
|
+
return JSON.stringify({ row: rows[0], name });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function awemesFn() {
|
|
39
|
+
const pid = window.__qcArg;
|
|
40
|
+
const T = (s) => (s || '').replace(/[\s\u00a0]+/g, ' ').trim();
|
|
41
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
42
|
+
const ct = (w) => { const els = [...document.querySelectorAll('div,span,li,a,button')].filter((x) => T(x.innerText) === w && x.getBoundingClientRect().width > 0 && x.getBoundingClientRect().y < 210); if (!els.length) return 'miss'; els[els.length - 1].click(); return 'ok' };
|
|
43
|
+
const tabRes = ct('抖音号');
|
|
44
|
+
await sleep(4000);
|
|
45
|
+
const parse = () => {
|
|
46
|
+
const out = [];
|
|
47
|
+
const rows = [...document.querySelectorAll('tr')].filter((r) => {
|
|
48
|
+
const t = r.innerText || '';
|
|
49
|
+
if (!/编辑/.test(t) || !/删除/.test(t)) return false;
|
|
50
|
+
if (/已删除/.test(t)) return false;
|
|
51
|
+
if (t.indexOf('无抖音号') >= 0) return false;
|
|
52
|
+
if (t.indexOf(pid) >= 0) return false;
|
|
53
|
+
if (!/ID:/.test(t)) return false;
|
|
54
|
+
return true;
|
|
55
|
+
});
|
|
56
|
+
for (const r of rows) {
|
|
57
|
+
const t = T(r.innerText);
|
|
58
|
+
const m = t.match(/^(.{1,40}?)\s*ID:([A-Za-z0-9_.\-]+)/);
|
|
59
|
+
if (!m) continue;
|
|
60
|
+
const name = m[1].trim();
|
|
61
|
+
const id = m[2];
|
|
62
|
+
const allIds = [...t.matchAll(/ID:([A-Za-z0-9_.\-]+)/g)].map((x) => x[1]);
|
|
63
|
+
const prodId = allIds.find((x) => /^\d{15,}$/.test(x)) || '';
|
|
64
|
+
const seg = t.indexOf('渠道品') >= 0 ? t.slice(t.indexOf('渠道品') + 3, t.indexOf('ID:' + prodId)) : '';
|
|
65
|
+
out.push({ name, id, prodId, prodName: T(seg) });
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
};
|
|
69
|
+
let all = parse();
|
|
70
|
+
const pagerItems = () => [...document.querySelectorAll('li.main-vmok-plugin-page-turner__item')].filter((e) => /^\d+$/.test(T(e.innerText)) && e.getBoundingClientRect().x > 1000);
|
|
71
|
+
const pages = pagerItems().map((e) => T(e.innerText));
|
|
72
|
+
for (const p of pages) {
|
|
73
|
+
if (p === '1') continue;
|
|
74
|
+
const li = pagerItems().find((e) => T(e.innerText) === p);
|
|
75
|
+
if (!li) continue;
|
|
76
|
+
li.click(); await sleep(2800);
|
|
77
|
+
all = all.concat(parse());
|
|
78
|
+
}
|
|
79
|
+
const seen = new Map();
|
|
80
|
+
for (const a of all) { if (!seen.has(a.id)) seen.set(a.id, a) }
|
|
81
|
+
const list = [...seen.values()];
|
|
82
|
+
const prod = {};
|
|
83
|
+
for (const a of list) { if (a.prodId && !prod[a.prodId]) prod[a.prodId] = a.prodName }
|
|
84
|
+
return JSON.stringify({ tabRes, pages, count: list.length, list, products: prod });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function matFn() {
|
|
88
|
+
const T = (s) => (s || '').replace(/[\s\u00a0]+/g, ' ').trim();
|
|
89
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
90
|
+
const ct = (w) => { const els = [...document.querySelectorAll('div,span,li,a,button')].filter((x) => T(x.innerText) === w && x.getBoundingClientRect().width > 0 && x.getBoundingClientRect().y < 210); if (!els.length) return 'miss'; els[els.length - 1].click(); return 'ok' };
|
|
91
|
+
ct('素材'); await sleep(3500);
|
|
92
|
+
const t = T(document.body.innerText);
|
|
93
|
+
const m = (t.match(/共\s*\d+\s*个视频/) || [])[0] || null;
|
|
94
|
+
const i = t.indexOf('视频');
|
|
95
|
+
return JSON.stringify({ mat: m, snip: i >= 0 ? t.slice(Math.max(0, i - 60), i + 60) : t.slice(0, 160) });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function pageFor() {
|
|
99
|
+
try {
|
|
100
|
+
const pages = await listPages();
|
|
101
|
+
const hit = pages.find((t) => t.type === 'page' && (t.url || '').indexOf('overall-prom') >= 0 && (t.url || '').indexOf(aavid) >= 0);
|
|
102
|
+
if (hit) return await connect('overall-prom', { id: hit.id });
|
|
103
|
+
const any = pages.find((t) => t.type === 'page' && (t.url || '').indexOf('jinritemai') >= 0);
|
|
104
|
+
if (any) return await connect('jinritemai', { id: any.id });
|
|
105
|
+
} catch (e) { mark('pageFor', String(e.message).slice(0, 60)) }
|
|
106
|
+
throw new Error('没有可用的千川标签页');
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const page = await pageFor();
|
|
110
|
+
await page.send('Page.navigate', { url: listUrl }, 20000);
|
|
111
|
+
mark('nav-done');
|
|
112
|
+
await sleep(3000);
|
|
113
|
+
const run = (fn, arg, timeout) => page.eval('window.__qcArg=' + JSON.stringify(arg) + ';(' + fn.toString() + ')()', timeout);
|
|
114
|
+
|
|
115
|
+
let prep = null;
|
|
116
|
+
for (let attempt = 1; attempt <= 2 && !prep; attempt++) {
|
|
117
|
+
const r = JSON.parse(await run(prepFn, planId, 60000));
|
|
118
|
+
mark('prep-' + attempt, JSON.stringify(r).slice(0, 160));
|
|
119
|
+
if (r.err === 'notunique' && attempt === 1) { await sleep(3000); continue }
|
|
120
|
+
if (r.err) throw new Error('列表阶段失败: ' + JSON.stringify(r));
|
|
121
|
+
prep = r;
|
|
122
|
+
}
|
|
123
|
+
const row = prep.row;
|
|
124
|
+
const aw = JSON.parse(await run(awemesFn, planId, 120000));
|
|
125
|
+
mark('awemes', 'count=' + aw.count + ' pages=' + JSON.stringify(aw.pages) + ' products=' + JSON.stringify(aw.products).slice(0, 120));
|
|
126
|
+
const mat = JSON.parse(await run(matFn, 0, 60000));
|
|
127
|
+
mark('mat', JSON.stringify(mat));
|
|
128
|
+
|
|
129
|
+
const nums = (row.match(/综合营销ROI目标\s*([0-9.]+)/) || [])[1] || '';
|
|
130
|
+
const budget = (row.match(/每日预算\s*([0-9.]+)/) || [])[1] || '';
|
|
131
|
+
const stateM = row.match(/投放中|已暂停|已结束|审核中|未开始/);
|
|
132
|
+
const state = stateM ? stateM[0] : '';
|
|
133
|
+
const chip = (row.match(/(\d+)\s*抖音号/) || [])[1] || '';
|
|
134
|
+
const planName = prep.name || '';
|
|
135
|
+
let newName = planName;
|
|
136
|
+
if (/--\d{4}$/.test(planName)) newName = planName.replace(/--\d{4}$/, '--' + suffix);
|
|
137
|
+
else if (/--\d{4}/.test(planName)) newName = planName.replace(/--\d{4}(?!.*--\d{4})/, '--' + suffix);
|
|
138
|
+
else newName = planName + '--' + suffix;
|
|
139
|
+
|
|
140
|
+
const awemeNames = {};
|
|
141
|
+
const awemeIds = [];
|
|
142
|
+
for (const a of aw.list) { awemeIds.push(a.id); awemeNames[a.id] = a.name }
|
|
143
|
+
const prodIds = Object.keys(aw.products || {});
|
|
144
|
+
const params = {
|
|
145
|
+
planName: newName,
|
|
146
|
+
productId: prodIds.filter((x) => x.length >= 15)[0] || prodIds[0] || '',
|
|
147
|
+
productName: prodIds.length ? aw.products[prodIds[0]] : '',
|
|
148
|
+
awemeIds, awemeNames,
|
|
149
|
+
roi: nums, budget,
|
|
150
|
+
origin: { planId, planName, state, awemes: aw.count, chipAwemes: chip, materials: mat.mat },
|
|
151
|
+
note: 'capture.mjs ' + new Date().toISOString()
|
|
152
|
+
};
|
|
153
|
+
fs.writeFileSync(outFile, JSON.stringify(params, null, 1));
|
|
154
|
+
mark('written', outFile);
|
|
155
|
+
console.log('SUMMARY ' + JSON.stringify({ planName, newName, roi: nums, budget, state, awemes: aw.count, chip, productId: params.productId, productName: params.productName, mat: mat.mat }));
|
|
156
|
+
process.exit(0);
|
|
@@ -6,7 +6,7 @@ import crypto from 'node:crypto';
|
|
|
6
6
|
import os from 'node:os';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { pickAllOnTarget } from './pick-all.mjs';
|
|
9
|
-
import { connect, sleep, listPages } from '../../live-control/scripts/cdp-lib.mjs';
|
|
9
|
+
import { connect, sleep, listPages, browserSend } from '../../live-control/scripts/cdp-lib.mjs';
|
|
10
10
|
|
|
11
11
|
const W = 'C:/Users/admin/Documents/deepseek-harness/default-workspace';
|
|
12
12
|
|
|
@@ -24,6 +24,24 @@ const mark = (l, e) => { LAST = l; console.log('[' + ((Date.now() - t0) / 1000).
|
|
|
24
24
|
// 看门狗:任何一步卡住都会打印最后一步并退出,避免静默长跑(默认 150s,可用 QC_WATCHDOG 覆盖)
|
|
25
25
|
setTimeout(() => { console.log('[WATCHDOG] 卡在 ' + LAST + ',强制退出'); process.exit(9) }, Number(process.env.QC_WATCHDOG || 150000));
|
|
26
26
|
|
|
27
|
+
// ---------- 通用自愈:关掉标签页重开 ----------
|
|
28
|
+
// 用户 2026-11-21 确认:大多数异常(「添加视频」弹层跑到视口外、抽屉/搜索卡住)关闭标签页重开就能解决。
|
|
29
|
+
const listUrl = (aavid) => 'https://qianchuan.jinritemai.com/overall-prom?aavid=' + aavid + '&campaignType=1&uniTab=ad&uniVideoTab=1&overallPromViewTab=plan';
|
|
30
|
+
async function reopenTab(aavid) {
|
|
31
|
+
mark('reopen-tab', 'start');
|
|
32
|
+
try {
|
|
33
|
+
const pages = await listPages();
|
|
34
|
+
const old = pages.find((t) => t.type === 'page' && (t.url || '').indexOf('overall-prom') >= 0 && (t.url || '').indexOf(aavid) >= 0);
|
|
35
|
+
if (old) { await browserSend('Target.closeTarget', { targetId: old.id }); mark('reopen-tab', 'closed ' + old.id) }
|
|
36
|
+
} catch (e) { mark('reopen-tab', 'close-err ' + String(e.message).slice(0, 60)) }
|
|
37
|
+
await browserSend('Target.createTarget', { url: listUrl(aavid) });
|
|
38
|
+
await sleep(6000);
|
|
39
|
+
const page = await connect('overall-prom');
|
|
40
|
+
await page.eval(INJECT);
|
|
41
|
+
mark('reopen-tab', 'new ' + (page.id || ''));
|
|
42
|
+
return page
|
|
43
|
+
}
|
|
44
|
+
|
|
27
45
|
// ---------- 注入到页面里的工具函数(不依赖坐标) ----------
|
|
28
46
|
function qcHelpers() {
|
|
29
47
|
const T = (s) => (s || '').replace(/\s+/g, ' ').trim();
|
|
@@ -106,6 +124,16 @@ const ROI_INPUT = 'document.querySelectorAll(".aurora-qc-input-number-input")[0]
|
|
|
106
124
|
const BUDGET_INPUT = 'document.querySelectorAll(".aurora-qc-input-number-input")[1]';
|
|
107
125
|
const NAME_INPUT = '[...document.querySelectorAll("input")].find(x => (x.placeholder||"").includes("计划名称,1-50"))';
|
|
108
126
|
|
|
127
|
+
// 优先连「本账户的 overall-prom」标签:多开标签时 connect('jinritemai') 可能抓到别的账户的 uni-prom,导致搜错页
|
|
128
|
+
async function connectFor(aavid) {
|
|
129
|
+
try {
|
|
130
|
+
const pages = await listPages();
|
|
131
|
+
const hit = pages.find((t) => t.type === 'page' && (t.url || '').indexOf('overall-prom') >= 0 && (t.url || '').indexOf(aavid) >= 0);
|
|
132
|
+
if (hit) return await connect('overall-prom', { id: hit.id });
|
|
133
|
+
} catch (e) { mark('connectFor', 'fallback ' + String(e.message).slice(0, 40)) }
|
|
134
|
+
return await connect('jinritemai')
|
|
135
|
+
}
|
|
136
|
+
|
|
109
137
|
async function openList(page, aavid) {
|
|
110
138
|
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);
|
|
111
139
|
await sleep(2500);
|
|
@@ -145,7 +173,7 @@ async function ensurePlanList(page) {
|
|
|
145
173
|
|
|
146
174
|
async function cmdSearch() {
|
|
147
175
|
const aavid = process.argv[3], planId = process.argv[4];
|
|
148
|
-
const page = await
|
|
176
|
+
const page = await connectFor(aavid);
|
|
149
177
|
await openList(page, aavid);
|
|
150
178
|
const hitRes = await searchPlan(page, planId);
|
|
151
179
|
mark('search-hit', hitRes);
|
|
@@ -169,7 +197,7 @@ async function cmdDelete() {
|
|
|
169
197
|
if (!fs.existsSync(rc.shot)) throw new Error('拒绝删除:确认截图文件丢失 ' + rc.shot);
|
|
170
198
|
mark('receipt-ok', rc.shot + ' @ ' + new Date(rc.ts).toISOString());
|
|
171
199
|
} else { mark('WARN', '--force 跳过了确认单校验,仅限用户已口头明确授权'); }
|
|
172
|
-
const page = await
|
|
200
|
+
const page = await connectFor(aavid);
|
|
173
201
|
await openList(page, aavid);
|
|
174
202
|
const hit = (await searchPlan(page, planId)) !== 'miss';
|
|
175
203
|
if (!hit) throw new Error('未唯一命中,拒绝删除');
|
|
@@ -189,7 +217,7 @@ async function cmdDelete() {
|
|
|
189
217
|
async function cmdConfirm() {
|
|
190
218
|
const aavid = process.argv[3], planId = process.argv[4];
|
|
191
219
|
if (!planId) throw new Error('用法: copy.mjs confirm <aavid> <planId>');
|
|
192
|
-
const page = await
|
|
220
|
+
const page = await connectFor(aavid);
|
|
193
221
|
await openList(page, aavid);
|
|
194
222
|
const hit = (await searchPlan(page, planId)) !== 'miss';
|
|
195
223
|
if (!hit) throw new Error('拒绝出确认图:搜索结果里没有唯一该 ID 的行');
|
|
@@ -225,7 +253,7 @@ async function cmdConfirm() {
|
|
|
225
253
|
|
|
226
254
|
async function cmdCreate() {
|
|
227
255
|
const aavid = process.argv[3], p = JSON.parse(fs.readFileSync(process.argv[4], 'utf8'));
|
|
228
|
-
const page = await
|
|
256
|
+
const page = await connectFor(aavid);
|
|
229
257
|
await page.send('Page.navigate', { url: 'https://qianchuan.jinritemai.com/create-ad/overall-product?aavid=' + aavid }, 15000);
|
|
230
258
|
await page.eval(INJECT); // 必须先注入 __qc,否则 ready 判断里的 __qc.text() 直接抛错
|
|
231
259
|
const ready = await wait(page, '/选择投放对象/.test(__qc.text())', 20000);
|
|
@@ -351,6 +379,16 @@ async function addMaterialsViaDrawer(page, aavid, planId, names, opts = {}) {
|
|
|
351
379
|
const popup = await wait(page, '(__qc.text().indexOf("已选择") >= 0)', 15000);
|
|
352
380
|
if (!popup) throw new Error('「添加视频」弹窗未打开');
|
|
353
381
|
mark('popup');
|
|
382
|
+
// 弹层从右侧滑入,位置会短暂停在视口外:轮询等它落定(≤18s)再看几何
|
|
383
|
+
const geo = await page.eval('(async () => { const sl=(ms)=>new Promise(r=>setTimeout(r,ms)); for (let i=0;i<26;i++){ const e=document.querySelector(".main-vmok-plugin-create-material-list"); if(e){ const r=e.getBoundingClientRect(); if(r.width>400 && r.x < innerWidth-200) return [Math.round(r.x),Math.round(r.width),innerWidth] } await sl(700) } const e2=document.querySelector(".main-vmok-plugin-create-material-list"); if(!e2) return null; const r2=e2.getBoundingClientRect(); return [Math.round(r2.x),Math.round(r2.width),innerWidth] })()', 40000);
|
|
384
|
+
if (!Array.isArray(geo) || geo[0] >= geo[2] - 200) {
|
|
385
|
+
mark('popup-offscreen', JSON.stringify(geo));
|
|
386
|
+
if (!opts._reopened) {
|
|
387
|
+
const p2 = await reopenTab(aavid);
|
|
388
|
+
return await addMaterialsViaDrawer(p2, aavid, planId, names, Object.assign({}, opts, { _reopened: true }))
|
|
389
|
+
}
|
|
390
|
+
throw new Error('「添加视频」弹层在视口外(x=' + JSON.stringify(geo) + '),重开标签后仍失败');
|
|
391
|
+
}
|
|
354
392
|
const targets = (await listPages()).filter((t) => t.type === 'page' && (t.url || '').indexOf('qianchuan') >= 0);
|
|
355
393
|
if (!targets.length) throw new Error('找不到千川标签页');
|
|
356
394
|
// 绑定到当前驱动的那个标签页(有 id 就按 id,没有就按连接时的 URL 兜底)
|
|
@@ -377,7 +415,7 @@ async function cmdMaterials() {
|
|
|
377
415
|
const names = Object.values(p.awemeNames || {});
|
|
378
416
|
if (!names.length) throw new Error('params.json 里没有 awemeNames,拿不到抖音号名单');
|
|
379
417
|
if (dry) {
|
|
380
|
-
const page0 = await
|
|
418
|
+
const page0 = await connectFor(aavid);
|
|
381
419
|
mark('connected');
|
|
382
420
|
await openList(page0, aavid);
|
|
383
421
|
mark('list-ready');
|
|
@@ -391,9 +429,18 @@ async function cmdMaterials() {
|
|
|
391
429
|
mark('dry', JSON.stringify({ hit: hit, chip: chip, drawer: drawer, names: names.length }));
|
|
392
430
|
return
|
|
393
431
|
}
|
|
394
|
-
const page = await
|
|
432
|
+
const page = await connectFor(aavid);
|
|
395
433
|
await page.eval(INJECT);
|
|
396
|
-
const
|
|
434
|
+
const prePick = ['nav-done','injected','page-ready','tabs','search-box','list-ready','search-unique','material-tab','drawer-material','material-src','material-type','popup','popup-offscreen'];
|
|
435
|
+
let res;
|
|
436
|
+
try {
|
|
437
|
+
res = await addMaterialsViaDrawer(page, aavid, planId, names, { cancelAfterPick: process.argv.includes('--picktest') });
|
|
438
|
+
} catch (e) {
|
|
439
|
+
if (prePick.indexOf(LAST) < 0) throw e;
|
|
440
|
+
mark('materials-retry', String(e.message).slice(0, 90));
|
|
441
|
+
const p2 = await reopenTab(aavid);
|
|
442
|
+
res = await addMaterialsViaDrawer(p2, aavid, planId, names, { cancelAfterPick: process.argv.includes('--picktest'), _reopened: true });
|
|
443
|
+
}
|
|
397
444
|
mark('result', JSON.stringify({ totalVideos: res.totalVideos, submitted: res.submitted, picktest: process.argv.includes('--picktest') }));
|
|
398
445
|
}
|
|
399
446
|
|
|
@@ -405,24 +452,49 @@ async function cmdAll() {
|
|
|
405
452
|
await cmdCreate();
|
|
406
453
|
process.argv = argv0.concat(['publish']);
|
|
407
454
|
await cmdPublish();
|
|
408
|
-
const page = await
|
|
455
|
+
const page = await connectFor(aavid);
|
|
409
456
|
await page.eval(INJECT);
|
|
410
|
-
const
|
|
457
|
+
const wantName = JSON.parse(fs.readFileSync(paramsFile, 'utf8')).planName;
|
|
458
|
+
let newId = null, topRow = '';
|
|
459
|
+
for (let i = 0; i < 5; i++) {
|
|
460
|
+
try {
|
|
461
|
+
const p3 = await connectFor(aavid);
|
|
462
|
+
await p3.send('Page.navigate', { url: listUrl }, 20000);
|
|
463
|
+
} catch (e) { mark('list-nav-err', String(e.message).slice(0, 60)) }
|
|
464
|
+
await sleep(8000);
|
|
465
|
+
try {
|
|
466
|
+
const p4 = await connectFor(aavid);
|
|
467
|
+
newId = await newestPlanId(p4);
|
|
468
|
+
topRow = await p4.eval('(() => { const tr = document.querySelector("tbody tr"); return tr ? (tr.innerText || "").replace(/\\s+/g, " ").trim() : "" })()');
|
|
469
|
+
} catch (e) { newId = null; topRow = '' }
|
|
470
|
+
if (newId && String(topRow).indexOf(wantName) >= 0) break;
|
|
471
|
+
mark('new-plan-retry', i + ' ' + String(topRow).slice(0, 40));
|
|
472
|
+
}
|
|
411
473
|
if (!newId) throw new Error('发布后拿不到新计划 ID');
|
|
412
|
-
|
|
474
|
+
if (String(topRow).indexOf(wantName) < 0) throw new Error('列表首行不是刚建的计划(首行=' + String(topRow).slice(0, 60) + ' 期望=' + wantName + ')');
|
|
475
|
+
mark('new-plan', newId + ' ' + wantName);
|
|
413
476
|
process.argv = argv0.concat(['materials', aavid, newId, paramsFile]);
|
|
414
477
|
await cmdMaterials();
|
|
415
478
|
}
|
|
416
479
|
|
|
417
480
|
async function cmdPublish() {
|
|
418
|
-
const
|
|
481
|
+
const aavid = process.argv[3] || '';
|
|
482
|
+
let page;
|
|
483
|
+
try { page = await connect('create-ad') } catch (e) { page = await connectFor(aavid) }
|
|
419
484
|
await page.eval(INJECT);
|
|
420
485
|
await page.eval('__qc.clickText("发布计划")');
|
|
421
486
|
const dlg = await wait(page, '/确认发布/.test(__qc.text())', 8000);
|
|
422
487
|
if (!dlg) throw new Error('发布确认框未出现');
|
|
423
488
|
const c = await clickByText(page, '确认发布');
|
|
424
489
|
mark('confirm', JSON.stringify(c));
|
|
425
|
-
|
|
490
|
+
let done = false;
|
|
491
|
+
try {
|
|
492
|
+
done = await wait(page, 'location.href.includes("overall-prom") && location.href.includes("createSuccess")', 30000);
|
|
493
|
+
} catch (e) {
|
|
494
|
+
// 发布后页面导航会让 CDP 当前 target 失效:按「已提交」继续,靠列表首行核验
|
|
495
|
+
mark('publish-wait-err', String(e.message).slice(0, 70));
|
|
496
|
+
done = true;
|
|
497
|
+
}
|
|
426
498
|
mark('published', done ? 'ok' : 'timeout');
|
|
427
499
|
if (!done) throw new Error('发布后未跳到 createSuccess');
|
|
428
500
|
}
|
|
@@ -452,7 +524,7 @@ async function clickByText(page, text) {
|
|
|
452
524
|
return { text: text, layer: 'shadow', click: sh, ms: Date.now() - t };
|
|
453
525
|
}
|
|
454
526
|
async function cmdClick() {
|
|
455
|
-
const page = await
|
|
527
|
+
const page = await connectFor(aavid);
|
|
456
528
|
await page.eval(INJECT);
|
|
457
529
|
const text = process.argv[3] || '发布计划';
|
|
458
530
|
const dry = process.argv.includes('--dry');
|
|
@@ -45,8 +45,15 @@ async function click(c, x, y) {
|
|
|
45
45
|
}
|
|
46
46
|
const getSel = `(()=>{const t=document.body.innerText.replace(/[ \\t]+/g,' ');const m=t.match(/已选择\\s*(\\d+)\\/200/);return m?Number(m[1]):-1})()`
|
|
47
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'})()`
|
|
48
|
-
|
|
49
|
-
|
|
48
|
+
// 只取真能被点到的卡片:弹窗 DOM 里有隐藏同构副本,坐标取自副本会点击落空或点穿页面
|
|
49
|
+
// 返回全部去重卡片 id(网格多行、可横向滚动;滚动与命中判定交给 cardPos)
|
|
50
|
+
const listCards = `(()=>{const seen=new Set();const out=[];for(const c of document.querySelectorAll('${CARD}')){const w=c.querySelector('[itemid]')||c;const id=w.getAttribute('itemid');if(!id||seen.has(id))continue;const r=c.getBoundingClientRect();if(r.width<10||r.height<10)continue;seen.add(id);out.push({id,y:Math.round(r.y),x:Math.round(r.x)})}out.sort((a,b)=>a.y-b.y||a.x-b.x);return out.map(o=>o.id)})()`
|
|
51
|
+
const chainInfo = (id) => `(()=>{const c=[...document.querySelectorAll('${CARD}')].map(x=>x).filter(x=>(x.querySelector('[itemid]')||x).getAttribute('itemid')===${JSON.stringify(id)})[0];if(!c)return null;const out=[];let a=c;for(let i=0;i<8&&a&&a!==document.body;i++,a=a.parentElement){const s=getComputedStyle(a);const r=a.getBoundingClientRect();out.push({t:a.tagName,c:String(a.className).slice(0,60),ox:s.overflowX,oy:s.overflowY,sl:a.scrollLeft,sw:a.scrollWidth,cw:a.clientWidth,x:Math.round(r.x),w:Math.round(r.width),tr:s.transform.slice(0,30)})}return out})()`
|
|
52
|
+
// 面板被渲染到视口右侧外(左边界≥innerWidth)时,强制 fixed 定位到屏幕内,避免点不到卡片
|
|
53
|
+
const fixOffscreen = `(()=>{const el=document.querySelector('.main-vmok-plugin-create-material-list');if(!el)return 'nolist';let a=el.offsetParent,tf=null;while(a&&a!==document.documentElement){const s=getComputedStyle(a);if(s.transform&&s.transform!=='none'){tf=a;break}a=a.offsetParent}if(!tf){let p=el.parentElement;while(p&&p!==document.documentElement){const s=getComputedStyle(p);if(s.transform&&s.transform!=='none'){tf=p;break}p=p.parentElement}}if(tf){tf.style.transform='none'}let r=el.getBoundingClientRect();if(!(r.x>=0&&r.x+40<innerWidth)){el.style.position='fixed';el.style.left='320px';el.style.top='60px';el.style.zIndex='99999';el.style.background='#fff';el.style.maxHeight=(innerHeight-90)+'px';el.style.overflow='auto'}const r2=el.getBoundingClientRect();return 'tf='+(tf?String(tf.className).slice(0,42):'none')+' x='+Math.round(r.x)+' -> '+Math.round(r2.x)})()`
|
|
54
|
+
const cardPos = (id) => `(()=>{const cands=[...document.querySelectorAll('${CARD}')].filter(x=>(x.querySelector('[itemid]')||x).getAttribute('itemid')===${JSON.stringify(id)});if(!cands.length)return {err:'nocard'};const seen=[];for(const c of cands){const r=c.getBoundingClientRect();if(r.width<10||r.height<10){seen.push(['tiny',Math.round(r.x)]);continue}const cx=Math.round(r.x+r.width/2),cy=Math.round(r.y+r.height/2);if(cx<0||cy<0||cx>innerWidth||cy>innerHeight){seen.push(['off',Math.round(r.x),Math.round(r.y)]);continue}const e=document.elementFromPoint(cx,cy);if(!e||!c.contains(e)){seen.push(['hid',Math.round(r.x),Math.round(r.y)]);continue}return {x:cx,y:cy}}return {err:'noclick',n:cands.length,seen}})()`
|
|
55
|
+
const listPos = `(()=>[...document.querySelectorAll('${CARD}')].slice(0,6).map(c=>{const r=c.getBoundingClientRect();return [Math.round(r.x),Math.round(r.y),Math.round(r.width),Math.round(r.height)]}))()`
|
|
56
|
+
const resetScroll = `(()=>{let n=0;for(const el of document.querySelectorAll('*')){const s=getComputedStyle(el);if((s.overflowX==='auto'||s.overflowX==='scroll')&&el.scrollWidth>el.clientWidth+4){if(el.scrollLeft!==0){el.scrollLeft=0;n++}}}return n})()`
|
|
50
57
|
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
58
|
const filterToggle = `(()=>{const i=${filterFind};if(!i)return 'NOBOX';i.click();return 'OK'})()`
|
|
52
59
|
|
|
@@ -61,10 +68,10 @@ async function pollCards(c, maxMs) {
|
|
|
61
68
|
}
|
|
62
69
|
|
|
63
70
|
async function selectCards(c, ids) {
|
|
64
|
-
let clicked = 0, retried = 0
|
|
71
|
+
let clicked = 0, retried = 0, skipped = 0, why = null
|
|
65
72
|
for (const id of ids) {
|
|
66
73
|
const p = await ev(c, cardPos(id))
|
|
67
|
-
if (!p) continue
|
|
74
|
+
if (!p || p.err || typeof p.x !== 'number') { skipped++; if (!why && p && p.err === 'noclick') why = JSON.stringify(await ev(c, chainInfo(id))); else why = why || (p && (p.err || 'bad')) + ' ' + JSON.stringify(p); continue }
|
|
68
75
|
await sleep(120)
|
|
69
76
|
const before = await ev(c, getSel)
|
|
70
77
|
await click(c, p.x, p.y)
|
|
@@ -76,7 +83,7 @@ async function selectCards(c, ids) {
|
|
|
76
83
|
}
|
|
77
84
|
clicked++
|
|
78
85
|
}
|
|
79
|
-
return { clicked, retried }
|
|
86
|
+
return { clicked, retried, skipped, why }
|
|
80
87
|
}
|
|
81
88
|
|
|
82
89
|
|
|
@@ -85,29 +92,35 @@ export async function pickAllOnTarget(target, names) {
|
|
|
85
92
|
const c = await connect(target)
|
|
86
93
|
const modalOpen = await ev(c, `(()=>/已选择\\s*\\d+\\/200/.test(document.body.innerText))()`)
|
|
87
94
|
if (!modalOpen) return { error: '「添加视频」弹窗没开,先点「添加视频」' }
|
|
95
|
+
await ev(c, resetScroll)
|
|
88
96
|
|
|
89
97
|
const log = []
|
|
98
|
+
const fixRes = 'skip'
|
|
90
99
|
for (const name of names) {
|
|
91
|
-
|
|
100
|
+
let r = await ev(c, clickTab(name))
|
|
101
|
+
// 切号后 tab 列表偶尔还未渲染完,重试几次再判定失败
|
|
102
|
+
for (let i = 0; i < 4 && r !== 'OK'; i++) { await sleep(900); r = await ev(c, clickTab(name)) }
|
|
92
103
|
if (r !== 'OK') { log.push({ name, err: r }); continue }
|
|
104
|
+
await ev(c, resetScroll)
|
|
93
105
|
let ids = await pollCards(c, 8000)
|
|
106
|
+
if (ids.length) { await sleep(1500); ids = await ev(c, listCards) }
|
|
94
107
|
let refreshed = false
|
|
95
108
|
if (!ids.length) {
|
|
96
109
|
const t = await ev(c, filterToggle)
|
|
97
110
|
if (t === 'OK') { refreshed = true; await sleep(1200); ids = await pollCards(c, 12000) }
|
|
98
111
|
}
|
|
99
112
|
const before = await ev(c, getSel)
|
|
100
|
-
let sel = { clicked: 0, retried: 0 }
|
|
113
|
+
let sel = { clicked: 0, retried: 0, skipped: 0 }
|
|
101
114
|
if (ids.length) sel = await selectCards(c, ids)
|
|
102
115
|
const after = await ev(c, getSel)
|
|
103
116
|
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 : '该号主页无可投视频(取消过滤后仍为空)' })
|
|
117
|
+
log.push({ name, cards: ids.length, before, after, delta: after - before, retried: sel.retried, skipped: sel.skipped, why: sel.why, pos: await ev(c, listPos), note: ids.length ? undefined : '该号主页无可投视频(取消过滤后仍为空)' })
|
|
105
118
|
}
|
|
106
119
|
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
120
|
let submitted = false
|
|
108
121
|
if (Array.isArray(okb)) { await click(c, okb[0], okb[1]); await sleep(5000); submitted = true }
|
|
109
122
|
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 }
|
|
123
|
+
return { ok: true, fix: fixRes, submitted, totalVideos: total, log }
|
|
111
124
|
}
|
|
112
125
|
|
|
113
126
|
async function main() {
|