dsh-qianchuan-toolkit 1.0.21 → 1.0.35
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 +62 -0
- package/assets/live-control/scripts/account-lib.mjs +26 -10
- package/assets/live-control/scripts/cdp-lib.mjs +11 -4
- package/assets/live-control/scripts/hourly.mjs +48 -13
- package/assets/plan-copy/SKILL.md +21 -4
- package/assets/plan-copy/references/01-/345/256/214/346/225/264/346/223/215/344/275/234/346/211/213/345/206/214.md +3 -3
- package/assets/plan-copy/references/04-/346/265/217/350/247/210/345/231/250/344/274/232/350/257/235.md +3 -3
- package/assets/plan-copy/references/05-/345/274/271/347/252/227/346/270/205/345/215/225.md +44 -0
- package/assets/plan-copy/scripts/capture.mjs +67 -1
- package/assets/plan-copy/scripts/cdp.mjs +3 -1
- package/assets/plan-copy/scripts/copy.mjs +63 -17
- package/assets/plan-copy/scripts/newmat.mjs +399 -0
- package/assets/plan-copy/scripts/pick-all.mjs +110 -4
- package/assets/plan-copy/scripts/readmat.mjs +2 -0
- package/assets/plan-copy/scripts/start-qc-copy.cmd +49 -0
- package/package.json +1 -1
|
@@ -7,6 +7,8 @@ import os from 'node:os';
|
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { pickAllOnTarget } from './pick-all.mjs';
|
|
9
9
|
import { connect, sleep, listPages, browserSend } from '../../live-control/scripts/cdp-lib.mjs';
|
|
10
|
+
// 复制技能固定连 9223 的独立浏览器实例(与 9222 的巡航实例物理隔离,互不抢标签)。
|
|
11
|
+
process.env.QC_CDP_PORT = process.env.QC_CDP_PORT || '9223';
|
|
10
12
|
|
|
11
13
|
// 确认单/截图落盘根目录:默认当前工作目录(可移植),需要固定位置时用 QC_WORKDIR 指定。
|
|
12
14
|
// confirm 与 delete 必须在同一个 QC_WORKDIR 下运行,否则找不到确认单。
|
|
@@ -203,8 +205,12 @@ async function cmdDelete() {
|
|
|
203
205
|
await openList(page, aavid);
|
|
204
206
|
const hit = (await searchPlan(page, planId)) !== 'miss';
|
|
205
207
|
if (!hit) throw new Error('未唯一命中,拒绝删除');
|
|
208
|
+
// 用户 2026-11-26:搜索到删除之间停 1.5s,等页面完全加载,规避加载中删错
|
|
209
|
+
await sleep(1500);
|
|
210
|
+
const guard = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const trs=[...document.querySelectorAll("tbody tr")].filter(r=>{const t=c(r.innerText); return t.includes("ID:") && t.includes("每日预算") && !t.includes("素材ID")}); if(trs.length!==1) return "rows="+trs.length; return c(trs[0].innerText).includes(' + JSON.stringify(planId) + ') ? "ok" : "other-row:"+c(trs[0].innerText).slice(0,60) })()');
|
|
211
|
+
if (guard !== 'ok') throw new Error('删除前校验失败:' + guard);
|
|
206
212
|
mark('unique-hit');
|
|
207
|
-
const clicked = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const tr=[...document.querySelectorAll("tbody tr")].
|
|
213
|
+
const clicked = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const tr=[...document.querySelectorAll("tbody tr")].filter(r=>{const t=c(r.innerText); return t.includes(' + JSON.stringify(planId) + ') && t.includes("每日预算") && !t.includes("素材ID")})[0]; 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" })()');
|
|
208
214
|
if (clicked !== 'ok') throw new Error('删除按钮: ' + clicked);
|
|
209
215
|
const dlg = await wait(page, '[...document.querySelectorAll("*")].some(e=>(e.innerText||"").trim()==="确定要删除计划吗?")', 6000);
|
|
210
216
|
if (!dlg) throw new Error('删除弹窗未出现');
|
|
@@ -221,10 +227,34 @@ async function cmdConfirm() {
|
|
|
221
227
|
if (!planId) throw new Error('用法: copy.mjs confirm <aavid> <planId>');
|
|
222
228
|
const page = await connectFor(aavid);
|
|
223
229
|
await openList(page, aavid);
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
230
|
+
// 用户 2026-11-26:进页面先关掉残留的抽屉/弹窗,避免影响操作
|
|
231
|
+
await page.eval('(() => { document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",keyCode:27,bubbles:true})); [...document.querySelectorAll(".aurora-qc-modal-close,.aurora-qc-drawer-close,.semi-icon-close,.semi-modal-close")].forEach(e=>{ try{ e.click() }catch(_){} }); return 1 })()');
|
|
232
|
+
await sleep(600);
|
|
233
|
+
// 若当前列表已经是「唯一命中该 ID」状态(capture 刚搜过),直接截图,不再重复搜索
|
|
234
|
+
const already = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const inp=[...document.querySelectorAll("input")].find(x=>/回车搜索|计划名称|计划ID|计划 ID/.test(x.placeholder||"")); const trs=[...document.querySelectorAll("tbody tr")].filter(r=>c(r.innerText).includes("ID:")); if(!inp || c(inp.value)!==(' + JSON.stringify(planId) + ')) return "no"; return (trs.length===1 && c(trs[0].innerText).includes(' + JSON.stringify(planId) + ')) ? "ok" : "no" })()');
|
|
235
|
+
if (already === 'ok') { mark('confirm-reuse', 'skip-extra-search'); }
|
|
236
|
+
else {
|
|
237
|
+
const hit = (await searchPlan(page, planId)) !== 'miss';
|
|
238
|
+
if (!hit) throw new Error('拒绝出确认图:搜索结果里没有唯一该 ID 的行');
|
|
239
|
+
}
|
|
240
|
+
const row = await page.eval('(() => { const c=(s)=>(s||"").replace(/\s+/g," ").trim(); const tr=[...document.querySelectorAll("tbody tr")].filter(r=>{const t=c(r.innerText); return t.includes(' + JSON.stringify(planId) + ') && t.includes("每日预算") && !t.includes("素材ID")})[0]; return tr ? c(tr.innerText) : "norow" })()');
|
|
227
241
|
if (row === 'norow') throw new Error('拒绝出确认图:列表里没有该 ID 的行');
|
|
242
|
+
// 用户 2026-11-26:截图前必须先按回车刷新计数,等「共N条计划」变成 1,避免残留旧计数(曾出现共45条)
|
|
243
|
+
const pressEnter = '(() => { const i=[...document.querySelectorAll("input")].find(x=>/回车搜索|计划名称|计划ID/.test(x.placeholder||"")); if(!i) return "noinput"; i.focus(); i.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true})); i.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true})); return "enter" })()';
|
|
244
|
+
const readCount = '(() => { const t=document.body.innerText||""; const m=t.match(/共\s*(\d+)\s*条(?:计划|记录)/); const r=[...document.querySelectorAll("tbody tr")].filter(x=>(x.innerText||"").includes("ID:")).length; return (m?m[1]:"-1")+"|"+r })()';
|
|
245
|
+
let cnt = "-1", rows = "0";
|
|
246
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
247
|
+
await page.eval(pressEnter);
|
|
248
|
+
for (let k = 0; k < 25; k++) {
|
|
249
|
+
await sleep(600);
|
|
250
|
+
const cv = String(await page.eval(readCount)).split("|");
|
|
251
|
+
cnt = cv[0]; rows = cv[1] || "0";
|
|
252
|
+
if (cnt === "1" || rows === "1") break;
|
|
253
|
+
}
|
|
254
|
+
if (cnt === "1" || rows === "1") break;
|
|
255
|
+
}
|
|
256
|
+
mark("confirm-count", "共" + cnt + "条计划 行=" + rows);
|
|
257
|
+
if (!(cnt === "1" || rows === "1")) console.log("WARN 截图前计数不是1:共" + cnt + "条计划 行=" + rows);
|
|
228
258
|
const outDir = path.join(W, 'qc');
|
|
229
259
|
fs.mkdirSync(outDir, { recursive: true });
|
|
230
260
|
const shot = path.join(outDir, 'confirm-' + planId + '.png');
|
|
@@ -395,7 +425,7 @@ async function addMaterialsViaDrawer(page, aavid, planId, names, opts = {}) {
|
|
|
395
425
|
if (!targets.length) throw new Error('找不到千川标签页');
|
|
396
426
|
// 绑定到当前驱动的那个标签页(有 id 就按 id,没有就按连接时的 URL 兜底)
|
|
397
427
|
const tgt = (page.id && targets.find((t) => t.id === page.id)) || targets.find((t) => t.url === page.url) || targets[0];
|
|
398
|
-
const res = await pickAllOnTarget(tgt, names);
|
|
428
|
+
const res = await pickAllOnTarget(tgt, names, opts.onlyIds, opts.onlyRows);
|
|
399
429
|
if (res.error) throw new Error(res.error);
|
|
400
430
|
mark('pick', JSON.stringify(res.log));
|
|
401
431
|
if (opts.cancelAfterPick) {
|
|
@@ -416,6 +446,15 @@ async function cmdMaterials() {
|
|
|
416
446
|
const p = paramsFile ? JSON.parse(fs.readFileSync(paramsFile, 'utf8')) : {};
|
|
417
447
|
const names = Object.values(p.awemeNames || {});
|
|
418
448
|
if (!names.length) throw new Error('params.json 里没有 awemeNames,拿不到抖音号名单');
|
|
449
|
+
const onlyMode = process.argv.includes('--only') || process.argv[6] === 'only';
|
|
450
|
+
let onlyIds = null;
|
|
451
|
+
let onlyRows = null;
|
|
452
|
+
if (onlyMode) {
|
|
453
|
+
const ml = Array.isArray(p.materialsList) ? p.materialsList : [];
|
|
454
|
+
onlyIds = ml.map((x) => String((x && x.id) || x)).filter(Boolean);
|
|
455
|
+
onlyRows = ml.map((x) => ({ img: String((x && x.img) || ''), row: String((x && x.row) || ''), aweme: String((x && x.aweme) || ''), awemeId: String((x && x.awemeId) || ''), date: String((x && x.date) || '') })).filter((x) => x.row || x.img);
|
|
456
|
+
if (!onlyIds.length) throw new Error('params.json 里没有 materialsList(先用带素材清单的 capture 抓一次)');
|
|
457
|
+
}
|
|
419
458
|
if (dry) {
|
|
420
459
|
const page0 = await connectFor(aavid);
|
|
421
460
|
mark('connected');
|
|
@@ -436,32 +475,40 @@ async function cmdMaterials() {
|
|
|
436
475
|
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'];
|
|
437
476
|
let res;
|
|
438
477
|
try {
|
|
439
|
-
res = await addMaterialsViaDrawer(page, aavid, planId, names, { cancelAfterPick: process.argv.includes('--picktest') });
|
|
478
|
+
res = await addMaterialsViaDrawer(page, aavid, planId, names, { cancelAfterPick: process.argv.includes('--picktest'), onlyIds, onlyRows });
|
|
440
479
|
} catch (e) {
|
|
480
|
+
if (String(e.message).indexOf('ONLY_MISSING') === 0) throw e;
|
|
441
481
|
if (prePick.indexOf(LAST) < 0) throw e;
|
|
442
482
|
mark('materials-retry', String(e.message).slice(0, 90));
|
|
443
483
|
const p2 = await reopenTab(aavid);
|
|
444
|
-
res = await addMaterialsViaDrawer(p2, aavid, planId, names, { cancelAfterPick: process.argv.includes('--picktest'), _reopened: true });
|
|
484
|
+
res = await addMaterialsViaDrawer(p2, aavid, planId, names, { cancelAfterPick: process.argv.includes('--picktest'), _reopened: true, onlyIds, onlyRows });
|
|
445
485
|
}
|
|
446
|
-
mark('result', JSON.stringify({ totalVideos: res.totalVideos, submitted: res.submitted, picktest: process.argv.includes('--picktest') }));
|
|
486
|
+
mark('result', JSON.stringify({ totalVideos: res.totalVideos, submitted: res.submitted, picktest: process.argv.includes('--picktest'), only: res.only || null }));
|
|
447
487
|
}
|
|
448
488
|
|
|
449
|
-
// 一条龙:新建 → 发布 →
|
|
489
|
+
// 一条龙:新建 → 发布 → 按计划名搜到新计划 → 详情抽屉加素材
|
|
450
490
|
async function searchByName(page, name) {
|
|
451
|
-
|
|
491
|
+
const okExpr = '(() => { const trs=[...document.querySelectorAll("tbody tr")].filter(r=>(r.innerText||"").indexOf("ID:")>=0); return trs.length===1 && (trs[0].innerText||"").indexOf(' + JSON.stringify(name) + ')>=0 })()'
|
|
492
|
+
const searchOnce = async () => {
|
|
452
493
|
await focusAndType(page, PLAN_SEARCH, name)
|
|
453
494
|
await sleep(700)
|
|
454
495
|
await pressEnter(page)
|
|
455
|
-
|
|
456
|
-
if (ok) return true
|
|
457
|
-
await sleep(800)
|
|
496
|
+
return await wait(page, okExpr, 8000)
|
|
458
497
|
}
|
|
459
|
-
return
|
|
498
|
+
if (await searchOnce()) return true
|
|
499
|
+
// 用户 2026-11-26:搜不到 → 刷新界面一次 → 再搜;仍搜不到就报异常,不做额外重试
|
|
500
|
+
mark('search-reload', 'once')
|
|
501
|
+
try { await page.eval('location.reload()') } catch (e) {}
|
|
502
|
+
await sleep(6000)
|
|
503
|
+
try { await page.eval(INJECT) } catch (e) {}
|
|
504
|
+
await sleep(1200)
|
|
505
|
+
return await searchOnce()
|
|
460
506
|
}
|
|
461
507
|
|
|
462
508
|
async function cmdAll() {
|
|
463
509
|
const aavid = process.argv[3], paramsFile = process.argv[4]
|
|
464
510
|
const argv0 = process.argv.slice(0, 2)
|
|
511
|
+
const onlyFlag = process.argv.includes('--only')
|
|
465
512
|
process.argv = argv0.concat(['create', aavid, paramsFile])
|
|
466
513
|
await cmdCreate()
|
|
467
514
|
process.argv = argv0.concat(['publish'])
|
|
@@ -475,18 +522,17 @@ async function cmdAll() {
|
|
|
475
522
|
await dismissBubbles(page)
|
|
476
523
|
mark('list-ready')
|
|
477
524
|
let newId = null, rowText = ''
|
|
478
|
-
for (let i = 0; i <
|
|
525
|
+
for (let i = 0; i < 1 && !newId; i++) {
|
|
479
526
|
const hit = await searchByName(page, wantName)
|
|
480
527
|
rowText = await page.eval('(() => { const trs=[...document.querySelectorAll("tbody tr")].filter(r=>(r.innerText||"").indexOf("ID:")>=0); return trs.length ? trs[0].innerText.replace(/\s+/g," ").trim() : "" })()')
|
|
481
528
|
const m = String(rowText).match(/ID[::]\s*(\d{10,})/)
|
|
482
529
|
if (hit && m) newId = m[1]
|
|
483
530
|
else { mark('new-plan-retry', i + ' ' + String(rowText).slice(0, 50)); await sleep(2000) }
|
|
484
531
|
}
|
|
485
|
-
if (!newId) { try { newId = await newestPlanId(page) } catch (e) {} }
|
|
486
532
|
if (!newId) throw new Error('发布后拿不到新计划 ID(按名字搜也没有)')
|
|
487
533
|
if (String(rowText).indexOf(wantName) < 0) throw new Error('搜到的不是刚建的计划(行=' + String(rowText).slice(0, 60) + ' 期望=' + wantName + ')')
|
|
488
534
|
mark('new-plan', newId + ' ' + wantName)
|
|
489
|
-
process.argv = argv0.concat(['materials', aavid, newId, paramsFile])
|
|
535
|
+
process.argv = argv0.concat(onlyFlag ? ['materials', aavid, newId, paramsFile, '--only'] : ['materials', aavid, newId, paramsFile])
|
|
490
536
|
await cmdMaterials()
|
|
491
537
|
}
|
|
492
538
|
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
// newmat.mjs —— 达人新发布素材补投
|
|
2
|
+
// 用法:
|
|
3
|
+
// node newmat.mjs scan <aavid> [--days=5] [--max=999] [--plan=<计划ID>]
|
|
4
|
+
// node newmat.mjs apply <aavid> [--days=5] [--max=999] [--plan=<计划ID>] [--force]
|
|
5
|
+
// 只勾「未勾选 且 发布时间在近 N 天」,超期未勾选不补(用户 2026-11-30 定)。
|
|
6
|
+
// 记录: QC_WORKDIR/newmat/records-<aavid>.csv 与 run-*.log
|
|
7
|
+
process.env.QC_CDP_PORT = process.env.QC_CDP_PORT || '9223'
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { connect, listPages } from '../../live-control/scripts/cdp-lib.mjs'
|
|
11
|
+
|
|
12
|
+
const argv = process.argv.slice(2)
|
|
13
|
+
const mode = argv[0]
|
|
14
|
+
const aavid = argv[1]
|
|
15
|
+
const argOf = (k, d) => { const x = argv.find((a) => a.startsWith('--' + k + '=')); return x ? x.split('=')[1] : d }
|
|
16
|
+
const DAYS = Number(argOf('days', '5'))
|
|
17
|
+
const MAX = Number(argOf('max', '999'))
|
|
18
|
+
const ONE = argOf('plan', '')
|
|
19
|
+
const FORCE = argv.includes('--force')
|
|
20
|
+
const W = process.env.QC_WORKDIR || process.cwd()
|
|
21
|
+
const OUT = path.join(W, 'newmat')
|
|
22
|
+
fs.mkdirSync(OUT, { recursive: true })
|
|
23
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
24
|
+
const T0 = Date.now()
|
|
25
|
+
const LOGF = path.join(OUT, 'run-' + new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19) + '.log')
|
|
26
|
+
function logLine(s) { const line = '[' + new Date().toISOString().slice(11, 19) + '] ' + s; console.log(line); try { fs.appendFileSync(LOGF, line + '\n') } catch (e) {} }
|
|
27
|
+
const CSVF = path.join(OUT, 'records-' + aavid + '.csv')
|
|
28
|
+
if (!fs.existsSync(CSVF)) fs.writeFileSync(CSVF, '\uFEFF' + 'time,planId,planName,aweme,title,publishTime,mode' + String.fromCharCode(13) + String.fromCharCode(10))
|
|
29
|
+
const csv = (o) => fs.appendFileSync(CSVF, [new Date().toISOString(), o.planId, o.planName, o.aweme, o.title, o.publishTime, mode].map((x) => '"' + String(x || '').split('"').join('""') + '"').join(',') + String.fromCharCode(13) + String.fromCharCode(10))
|
|
30
|
+
|
|
31
|
+
const LIST_URL = 'https://qianchuan.jinritemai.com/overall-prom?aavid=' + aavid + '&campaignType=1&uniTab=ad&marGoal=1&uniVideoTab=1&overallPromViewTab=plan'
|
|
32
|
+
const CARD = '.main-vmok-plugin-create-material-list-card-item'
|
|
33
|
+
const NAV = '.main-vmok-plugin-tabs__nav-list'
|
|
34
|
+
|
|
35
|
+
const pages = await listPages()
|
|
36
|
+
const cands = pages.filter((p) => p.type === 'page' && (p.url || '').indexOf('jinritemai') >= 0)
|
|
37
|
+
const tab = cands.find((p) => (p.url || '').indexOf(aavid) >= 0 && (p.url || '').indexOf('overall-prom') >= 0) || cands.find((p) => (p.url || '').indexOf('overall-prom') >= 0) || cands[0]
|
|
38
|
+
if (!tab) { logLine('ERR 没有千川标签页'); process.exit(2) }
|
|
39
|
+
const page = await connect('jinritemai', { id: tab.id })
|
|
40
|
+
logLine('TAB ' + String(tab.url).slice(0, 90))
|
|
41
|
+
|
|
42
|
+
async function waitJs(expr, ms) { const t0 = Date.now(); while (Date.now() - t0 < ms) { try { if (await page.eval(expr, 20000)) return true } catch (e) {} await sleep(400) } return false }
|
|
43
|
+
async function clickExact(txt) { return await page.eval("(() => { const t = " + JSON.stringify(txt) + "; const ls = [...document.querySelectorAll('span,div,button,a,li')].filter(e => e.children.length === 0 && (e.innerText||'').trim() === t && e.getBoundingClientRect().width > 0); if (!ls.length) return 'none'; ls[ls.length-1].click(); return 'ok' })()") }
|
|
44
|
+
async function mouse(x, y) {
|
|
45
|
+
await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
|
|
46
|
+
await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
|
|
47
|
+
await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
|
|
48
|
+
}
|
|
49
|
+
const key = async (k, vk) => { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code: k, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code: k, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }) }
|
|
50
|
+
|
|
51
|
+
async function openList() {
|
|
52
|
+
await page.send('Page.navigate', { url: LIST_URL }, 25000)
|
|
53
|
+
await sleep(1200)
|
|
54
|
+
await waitJs("document.body.innerText.indexOf('计划视图') >= 0 || document.body.innerText.indexOf('商品自选') >= 0 || document.body.innerText.indexOf('全店托管') >= 0", 20000)
|
|
55
|
+
await clickExact('计划视图'); await sleep(1200)
|
|
56
|
+
await clickExact('商品自选')
|
|
57
|
+
const ok = await waitJs("!![...document.querySelectorAll('input')].find(x => /回车搜索|计划名称|计划ID|计划 ID/.test(x.placeholder || ''))", 20000)
|
|
58
|
+
logLine('LIST-READY ' + ok)
|
|
59
|
+
await sleep(600)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const STATUSBOX = "(() => { const T = (s) => (s || '').replace(/[\\s]+/g, ' ').trim(); const ls = [...document.querySelectorAll('*')].filter((x) => { if (x.closest('tbody')) return false; const t = T(x.innerText); return t === '请筛选计划状态' || t === '投放中' }); if (!ls.length) return null; const leaf = ls[ls.length - 1]; const txt = T(leaf.innerText); let n = leaf; for (let i = 0; i < 5 && n; i++) { const r = n.getBoundingClientRect(); if (r.width > 120 && r.height > 18) return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), text: txt }; n = n.parentElement } const r2 = leaf.getBoundingClientRect(); return { x: Math.round(r2.x + r2.width / 2), y: Math.round(r2.y + r2.height / 2), text: txt } })()"
|
|
63
|
+
async function filterRunning() {
|
|
64
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
65
|
+
const box = await page.eval(STATUSBOX, 20000)
|
|
66
|
+
if (!box) throw new Error('找不到计划状态筛选框')
|
|
67
|
+
logLine('FILTER-CHIP attempt=' + attempt + ' chip=' + box.text)
|
|
68
|
+
if (box.text === '投放中') return
|
|
69
|
+
await mouse(box.x, box.y)
|
|
70
|
+
await sleep(1100)
|
|
71
|
+
await key('ArrowDown', 40); await sleep(300)
|
|
72
|
+
await key('Enter', 13)
|
|
73
|
+
let box2 = null
|
|
74
|
+
for (let i = 0; i < 10; i++) { await sleep(300); box2 = await page.eval(STATUSBOX, 20000); if (box2 && box2.text === '投放中') break }
|
|
75
|
+
logLine('FILTER-AFTER attempt=' + attempt + ' chip=' + (box2 ? box2.text : 'nochip'))
|
|
76
|
+
if (box2 && box2.text === '投放中') return
|
|
77
|
+
await key('Escape', 27); await sleep(700)
|
|
78
|
+
}
|
|
79
|
+
throw new Error('状态筛选没切到投放中(2 次尝试失败)')
|
|
80
|
+
}
|
|
81
|
+
const ROWS = "(() => { const T = (s) => (s || '').replace(/[\\s\\u00a0]+/g, ' ').trim(); const out = []; for (const tr of document.querySelectorAll('tbody tr')) { const t = T(tr.innerText); if (t.indexOf('ID') < 0) continue; const m = t.match(/ID[::]\\s*(\\d{10,})/); if (!m) continue; const raw = t.split(' ID')[0]; const name = raw.replace(/^[[【]\s*(?:扶持中|已暂停|投放中|已删除|审核中|删除中|待审核)\s*[\]】]\s*/, ''); out.push({ id: m[1], name: name.slice(0, 60), run: t.indexOf('投放中') >= 0 }) } return JSON.stringify(out) })()"
|
|
82
|
+
async function pageRows() { try { return JSON.parse(await page.eval(ROWS, 20000)) } catch (e) { return [] } }
|
|
83
|
+
async function enumerate() {
|
|
84
|
+
const all = []; const seen = new Set()
|
|
85
|
+
for (let w = 0; w < 25; w++) { const rr = await pageRows(); if (rr.length) break; await sleep(800) }
|
|
86
|
+
const first = await pageRows()
|
|
87
|
+
logLine('ROWS first=' + first.length + (first.length ? ' sample=' + first[0].id : ''))
|
|
88
|
+
for (let p = 0; p < 12; p++) {
|
|
89
|
+
for (const r of await pageRows()) if (!seen.has(r.id)) { seen.add(r.id); all.push(r) }
|
|
90
|
+
if (all.length >= MAX) break
|
|
91
|
+
const np = await page.eval("(() => { const b = document.querySelector('li.aurora-qc-pagination-next'); if (!b) return 'none'; if (/disabled/.test(String(b.className || ''))) return 'disabled'; b.scrollIntoView({ block: 'center' }); const r = b.getBoundingClientRect(); return JSON.stringify({ x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }) })()", 20000)
|
|
92
|
+
if (np === 'none' || np === 'disabled') break
|
|
93
|
+
const pp = JSON.parse(np)
|
|
94
|
+
await sleep(300)
|
|
95
|
+
const p2 = await page.eval("(() => { const b = document.querySelector('li.aurora-qc-pagination-next'); if (!b) return 'none'; const r = b.getBoundingClientRect(); return JSON.stringify({ x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }) })()")
|
|
96
|
+
const at = p2 === 'none' ? pp : JSON.parse(p2)
|
|
97
|
+
const sigBefore = JSON.stringify(await pageRows())
|
|
98
|
+
await mouse(at.x, at.y)
|
|
99
|
+
for (let k = 0; k < 24; k++) { await sleep(250); const rr = await pageRows(); if (rr.length && JSON.stringify(rr) !== sigBefore) break }
|
|
100
|
+
}
|
|
101
|
+
return all.slice(0, MAX)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const SEARCH_INPUT = "(() => { const i = [...document.querySelectorAll('input')].find(x => /回车搜索|计划名称|计划ID/.test(x.placeholder || '')); return i ? 'ok' : 'noinput' })()"
|
|
105
|
+
const searchFill = (v) => "(() => { const i = [...document.querySelectorAll('input')].find(x => /回车搜索|计划名称|计划ID/.test(x.placeholder || '')); if (!i) return 'noinput'; const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set; i.focus(); set.call(i, ''); i.dispatchEvent(new Event('input', { bubbles: true })); set.call(i, " + JSON.stringify(v) + "); i.dispatchEvent(new Event('input', { bubbles: true })); return 'ok' })()"
|
|
106
|
+
const uniqRow = (p) => "(() => { const P = " + JSON.stringify(p) + "; const rs = [...document.querySelectorAll('tbody tr')].filter(r => { const t = r.innerText || ''; return /ID[::]\\s*\\d{10,}/.test(t) && t.indexOf('每日预算') >= 0 && t.indexOf('素材ID') < 0 }); return rs.length === 1 && (rs[0].innerText || '').indexOf(P) >= 0 })()"
|
|
107
|
+
async function ensureList() {
|
|
108
|
+
if (await page.eval(SEARCH_INPUT, 15000) === 'ok') { logLine('LIST-OK reuse'); return true }
|
|
109
|
+
try { await openList(); return true } catch (e) { logLine('LIST-FAIL ' + String(e.message).slice(0, 80)); return false }
|
|
110
|
+
}
|
|
111
|
+
async function ensurePlanView() {
|
|
112
|
+
const ROWSD = "(() => { const rs = [...document.querySelectorAll('tbody tr')].filter(r => (r.innerText||'').indexOf('每日预算') >= 0); return rs.length > 0 })()"
|
|
113
|
+
for (let t = 0; t < 2; t++) {
|
|
114
|
+
if (await page.eval(ROWSD, 15000)) return true
|
|
115
|
+
try { await clickExact('计划视图') } catch (e) {}
|
|
116
|
+
await sleep(600)
|
|
117
|
+
try { await clickExact('商品自选') } catch (e) {}
|
|
118
|
+
for (let i = 0; i < 8; i++) { await sleep(400); if (await page.eval(ROWSD, 15000)) return true }
|
|
119
|
+
}
|
|
120
|
+
return false
|
|
121
|
+
}
|
|
122
|
+
async function reloadList() {
|
|
123
|
+
logLine('RELOAD list (reload)')
|
|
124
|
+
try { await page.send('Page.reload', { ignoreCache: false }) } catch (e) {}
|
|
125
|
+
await sleep(2500)
|
|
126
|
+
for (let i = 0; i < 10; i++) { if (await page.eval(SEARCH_INPUT, 15000) === 'ok') break; await sleep(500) }
|
|
127
|
+
if (await ensurePlanView()) { logLine('RELOAD planview-ok'); return }
|
|
128
|
+
logLine('RELOAD fallback-openList')
|
|
129
|
+
await openList()
|
|
130
|
+
}
|
|
131
|
+
const INPUT_VAL = "(() => { const i = [...document.querySelectorAll('input')].find(x => /输入计划名称|回车搜索/.test(x.placeholder || '')); return i ? i.value : 'noinput' })()"
|
|
132
|
+
const INPUT_FOCUS = "(() => { const i = [...document.querySelectorAll('input')].find(x => /输入计划名称|回车搜索/.test(x.placeholder || '')); if (!i) return 'noinput'; i.focus(); return document.activeElement === i ? 'focused' : 'lost' })()"
|
|
133
|
+
async function typeSearch(planId) {
|
|
134
|
+
for (let k = 0; k < 3; k++) {
|
|
135
|
+
const rect = await page.eval("(() => { const i = [...document.querySelectorAll('input')].find(x => /输入计划名称|回车搜索/.test(x.placeholder || '')); if (!i) return 'noinput'; const r = i.getBoundingClientRect(); return JSON.stringify({ x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }) })()", 15000)
|
|
136
|
+
if (rect === "noinput") return "noinput"
|
|
137
|
+
const p = JSON.parse(rect)
|
|
138
|
+
const fo = await page.eval(INPUT_FOCUS, 15000)
|
|
139
|
+
if (fo === "noinput") return "noinput"
|
|
140
|
+
await mouse(p.x, p.y)
|
|
141
|
+
await sleep(180)
|
|
142
|
+
await page.eval(searchFill(""), 15000)
|
|
143
|
+
const v0 = await page.eval(INPUT_VAL, 15000)
|
|
144
|
+
if (String(v0) !== "") {
|
|
145
|
+
await page.eval(INPUT_FOCUS, 15000)
|
|
146
|
+
await page.send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: "a", code: "KeyA", windowsVirtualKeyCode: 65, modifiers: 2, commands: ["selectAll"] })
|
|
147
|
+
await page.send("Input.dispatchKeyEvent", { type: "keyUp", key: "a", code: "KeyA", windowsVirtualKeyCode: 65, modifiers: 2 })
|
|
148
|
+
await key("Backspace", 8)
|
|
149
|
+
await sleep(180)
|
|
150
|
+
}
|
|
151
|
+
await page.send("Input.insertText", { text: String(planId) })
|
|
152
|
+
await sleep(320)
|
|
153
|
+
const v = await page.eval(INPUT_VAL, 15000)
|
|
154
|
+
if (String(v) === String(planId)) { await key("Enter", 13); return "ok" }
|
|
155
|
+
logLine("TYPE-RETRY k=" + k + " val=" + v + " want=" + planId)
|
|
156
|
+
}
|
|
157
|
+
return "badtype"
|
|
158
|
+
}
|
|
159
|
+
async function searchPlanId(planId) {
|
|
160
|
+
for (let att = 0; att < 2; att++) {
|
|
161
|
+
if (att > 0) await reloadList()
|
|
162
|
+
const r = await typeSearch(planId)
|
|
163
|
+
if (r === 'ok' && (await waitJs(uniqRow(planId), 3000))) return
|
|
164
|
+
logLine('SEARCH-MISS ' + planId + ' attempt=' + att + ' type=' + r)
|
|
165
|
+
}
|
|
166
|
+
throw new Error('搜索该 ID 没有出唯一 1 行: ' + planId)
|
|
167
|
+
}
|
|
168
|
+
async function openDrawer(planId) {
|
|
169
|
+
const chip = await page.eval("(() => { const P = " + JSON.stringify(planId) + "; const tr = [...document.querySelectorAll('tbody tr')].find(r => (r.innerText||'').indexOf(P) >= 0); if (!tr) return 'norow'; const leaves = [...tr.querySelectorAll('*')].filter(e => e.children.length === 0 && (e.innerText||'').trim().length > 0); const first = (tr.innerText||'').split(String.fromCharCode(10)).map(s => s.trim()).filter(Boolean)[0]; const el = leaves.find(e => e.innerText.trim() === first) || leaves.find(e => e.innerText.trim() === '素材'); if (!el) return 'nochip'; el.click(); return 'ok' })()")
|
|
170
|
+
if (chip !== 'ok') throw new Error('打不开素材入口: ' + chip)
|
|
171
|
+
if (!(await waitJs('document.body.innerText.indexOf("保障历史") >= 0', 15000))) throw new Error('详情抽屉未打开')
|
|
172
|
+
await sleep(1200)
|
|
173
|
+
const mt = await page.eval("(() => { const roots = [...document.querySelectorAll('*')].filter(e => { const t = e.innerText || ''; return t.indexOf('保障历史') >= 0 && t.indexOf('素材') >= 0 && t.length > 100 }); if (!roots.length) return 'noroot'; roots.sort((a,b) => a.innerText.length - b.innerText.length); const r = roots[0]; const lv = [...r.querySelectorAll('*')].filter(e => e.children.length === 0 && (e.innerText||'').trim() === '素材'); if (!lv.length) return 'notab'; lv[0].click(); return 'ok' })()")
|
|
174
|
+
if (mt !== 'ok') throw new Error('素材 tab: ' + mt)
|
|
175
|
+
if (!(await waitJs('document.body.innerText.indexOf("素材来源") >= 0', 15000))) throw new Error('素材 tab 未就绪')
|
|
176
|
+
await clickExact('自选素材')
|
|
177
|
+
await waitJs("!![...document.querySelectorAll('*')].find(e => e.children.length === 0 && (e.innerText||'').trim() === '视频')", 8000)
|
|
178
|
+
await clickExact('视频')
|
|
179
|
+
const addLeaf = "!![...document.querySelectorAll('span,div,button')].find(e => e.children.length === 0 && (e.innerText||'').trim() === '添加视频' && e.getBoundingClientRect().width > 0)"
|
|
180
|
+
if (!(await waitJs(addLeaf, 15000))) throw new Error('没有「添加视频」按钮')
|
|
181
|
+
await sleep(300)
|
|
182
|
+
const b = await clickExact('添加视频')
|
|
183
|
+
if (b !== 'ok') throw new Error('点不到「添加视频」')
|
|
184
|
+
if (!(await waitJs('/已选择\\s*\\d+\\/200/.test(document.body.innerText)', 20000))) throw new Error('「添加视频」弹窗未打开')
|
|
185
|
+
for (let i = 0; i < 25; i++) { const ts = await accountTabs(); if (ts.length) break; await sleep(200) }
|
|
186
|
+
}
|
|
187
|
+
const TABS_JS = "(() => { const out = []; for (const l of document.querySelectorAll('" + NAV + "')) { for (const c of l.children) { const t = (c.innerText||'').trim(); if (t) out.push(t) } } return JSON.stringify([...new Set(out)]) })()"
|
|
188
|
+
async function accountTabs() { const t = JSON.parse(await page.eval(TABS_JS)); return t.filter((x) => ['我的视频', '上传视频', '其他视频'].indexOf(x) < 0) }
|
|
189
|
+
const CARDS_SIG = "(() => { const CARD = '" + CARD + "'; const ids = []; for (const c of document.querySelectorAll(CARD)) { const w = c.querySelector('[itemid]') || c; ids.push(w.getAttribute('itemid') || '') } return ids.slice(0, 8).join(',') })()"
|
|
190
|
+
const CARDS_JS = "(() => { const CARD = '" + CARD + "'; const out = []; const seen = new Set(); 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); const cb = c.querySelector('input[type=checkbox]'); const cls = /selected|checked/i.test(String(c.className || '')) ? 1 : 0; out.push({ id, ct: Number(w.getAttribute('createtime') || 0), title: String(w.getAttribute('title') || ''), sel: cb ? (cb.checked ? 1 : 0) : cls }) } return JSON.stringify(out) })()"
|
|
191
|
+
async function readCards() { try { return JSON.parse(await page.eval(CARDS_JS, 25000)) } catch (e) { return [] } }
|
|
192
|
+
const sigOf = (arr) => arr.slice(0, 6).map((c) => c.id).join(',') + '|' + arr.length
|
|
193
|
+
async function readCardsStable(prev) { let sig = '', same = 0, last = []; for (let i = 0; i < 40; i++) { const c = await readCards(); const s = sigOf(c); if (c.length > 0) { if (s === sig) same++; else { same = 0; sig = s } last = c; if (same >= 1 && (s !== prev || i >= 10)) return last } await sleep(180) } for (let i = 0; i < 3; i++) { await sleep(600); const c = await readCards(); if (c.length) return c } return last }
|
|
194
|
+
const SCROLLINFO = "(() => { const CARD = '" + CARD + "'; const c0 = document.querySelector(CARD); if (!c0) return '0'; let a = c0.parentElement, best = null; for (let i = 0; i < 10 && a; i++, a = a.parentElement) { const s = getComputedStyle(a); if ((s.overflowY === 'auto' || s.overflowY === 'scroll') && a.scrollHeight > a.clientHeight + 20) { best = a; break } } if (!best) return '0'; best.setAttribute('data-qc-scroll', 'on'); return JSON.stringify({ h: best.scrollHeight, c: best.clientHeight }) })()"
|
|
195
|
+
const SCROLLTO = (v) => "(() => { const e = document.querySelector('[data-qc-scroll=on]'); if (!e) return 'no'; e.scrollTop = " + Number(v) + "; return 'ok' })()"
|
|
196
|
+
async function readAllCards(prev) {
|
|
197
|
+
const cards = await readCardsStable(prev)
|
|
198
|
+
const seen = new Set(cards.map((c) => c.id))
|
|
199
|
+
try {
|
|
200
|
+
const si = await page.eval(SCROLLINFO, 15000)
|
|
201
|
+
if (si !== '0') {
|
|
202
|
+
const info = JSON.parse(si)
|
|
203
|
+
if (info.h > info.c + 20) {
|
|
204
|
+
const steps = Math.min(12, Math.ceil(info.h / Math.max(200, info.c)) + 1)
|
|
205
|
+
let extra = 0
|
|
206
|
+
for (let i = 1; i <= steps; i++) {
|
|
207
|
+
await page.eval(SCROLLTO(Math.round((info.h - info.c) * i / steps)), 15000)
|
|
208
|
+
await sleep(240)
|
|
209
|
+
for (const c of await readCards()) if (!seen.has(c.id)) { seen.add(c.id); cards.push(c); extra++ }
|
|
210
|
+
}
|
|
211
|
+
await page.eval(SCROLLTO(0), 15000)
|
|
212
|
+
await sleep(180)
|
|
213
|
+
if (extra) logLine('DEEP extra=' + extra + ' total=' + cards.length)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
} catch (e) { logLine('DEEP-ERR ' + String(e.message).slice(0, 80)) }
|
|
217
|
+
return cards
|
|
218
|
+
}
|
|
219
|
+
const fmt = (ct) => new Date(ct * 1000 + 8 * 3600 * 1000).toISOString().slice(0, 16).replace('T', ' ')
|
|
220
|
+
const nowSecF = () => Math.floor(Date.now() / 1000)
|
|
221
|
+
const WIN = DAYS * 86400
|
|
222
|
+
|
|
223
|
+
const cardPosFn = (id) => "(() => { const CARD = '" + CARD + "'; const id = " + JSON.stringify(id) + "; const cands = [...document.querySelectorAll(CARD)].filter(x => (x.querySelector('[itemid]') || x).getAttribute('itemid') === id); if (!cands.length) return { err: 'nocard' }; for (const c of cands) { const r = c.getBoundingClientRect(); if (r.width < 10 || r.height < 10) continue; const x = Math.round(r.x + r.width / 2), y = Math.round(r.y + r.height / 2); if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) continue; const e = document.elementFromPoint(x, y); if (!e || !c.contains(e)) continue; return { x, y } } return { err: 'noclick' } })()"
|
|
224
|
+
const isSelFn = (id) => "(() => { const CARD = '" + CARD + "'; const id = " + JSON.stringify(id) + "; const c = [...document.querySelectorAll(CARD)].find(x => (x.querySelector('[itemid]') || x).getAttribute('itemid') === id); if (!c) return -1; if (/selected|checked/i.test(String(c.className || ''))) return 1; const cb = c.querySelector('input[type=checkbox]'); if (cb) return cb.checked ? 1 : 0; return -1 })()"
|
|
225
|
+
const SCROLL = "(() => { const roots = [...document.querySelectorAll('[class*=create-material]')]; const els = new Set(); for (const r of roots) { let a = r; for (let i = 0; i < 8 && a; i++, a = a.parentElement) els.add(a) } let n = 0; for (const el of els) { if (el === document.body || el === document.documentElement) continue; const rc = el.getBoundingClientRect(); if (!rc || rc.width < 10) continue; const s = getComputedStyle(el); if ((s.overflowX === 'auto' || s.overflowX === 'scroll') && el.scrollWidth > el.clientWidth + 4) { el.scrollLeft = Math.min(el.scrollLeft + Math.round(el.clientWidth * 0.8), el.scrollWidth - el.clientWidth); n++ } if ((s.overflowY === 'auto' || s.overflowY === 'scroll') && el.scrollHeight > el.clientHeight + 4 && el.clientHeight > 200) { el.scrollTop = Math.min(el.scrollTop + Math.round(el.clientHeight * 0.6), el.scrollHeight - el.clientHeight); n++ } } return n })()"
|
|
226
|
+
|
|
227
|
+
async function clickCards(ids) {
|
|
228
|
+
let clicked = 0, already = 0, failed = []
|
|
229
|
+
let pending = ids.slice()
|
|
230
|
+
for (let pass = 0; pass < 10 && pending.length; pass++) {
|
|
231
|
+
const next = []
|
|
232
|
+
for (const id of pending) {
|
|
233
|
+
if ((await page.eval(isSelFn(id))) === 1) { already++; continue }
|
|
234
|
+
const p = await page.eval(cardPosFn(id))
|
|
235
|
+
if (!p || p.err || typeof p.x !== 'number') { next.push(id); continue }
|
|
236
|
+
await sleep(120)
|
|
237
|
+
await mouse(p.x, p.y)
|
|
238
|
+
clicked++
|
|
239
|
+
let st = -1
|
|
240
|
+
for (let i = 0; i < 8; i++) { st = await page.eval(isSelFn(id)); if (st === 1) break; await sleep(150) }
|
|
241
|
+
if (st !== 1) failed.push(id)
|
|
242
|
+
}
|
|
243
|
+
if (!next.length) { pending = []; break }
|
|
244
|
+
for (let k = 0; k < 2; k++) { await page.eval(SCROLL, 20000); await sleep(450) }
|
|
245
|
+
pending = next
|
|
246
|
+
}
|
|
247
|
+
return { clicked, already, failed, skipped: pending.length }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const COUNTER = "(() => { const m = (document.body.innerText||'').match(/已选择\\s*(\\d+)\\/200/); return m ? Number(m[1]) : -1 })()"
|
|
251
|
+
async function clickCandidates(cands) {
|
|
252
|
+
let clicked = 0; const failed = []
|
|
253
|
+
let cnt = await page.eval(COUNTER, 15000)
|
|
254
|
+
if (!(cnt >= 0)) cnt = 0
|
|
255
|
+
for (const c of cands) {
|
|
256
|
+
let done = false
|
|
257
|
+
for (let a = 0; a < 3 && !done; a++) {
|
|
258
|
+
if ((await page.eval(isSelFn(c.id))) === 1) { done = true; break }
|
|
259
|
+
const p = await page.eval(cardPosFn(c.id))
|
|
260
|
+
if (!p || p.err || typeof p.x !== "number") { await page.eval(SCROLL, 20000); await sleep(500); continue }
|
|
261
|
+
await mouse(p.x, p.y)
|
|
262
|
+
clicked++
|
|
263
|
+
for (let i = 0; i < 12; i++) {
|
|
264
|
+
await sleep(150)
|
|
265
|
+
const now = await page.eval(COUNTER, 15000)
|
|
266
|
+
if (now > cnt) { cnt = now; done = true; break }
|
|
267
|
+
if ((await page.eval(isSelFn(c.id))) === 1) { if (now > cnt) cnt = now; done = true; break }
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (!done) failed.push(c.id)
|
|
271
|
+
}
|
|
272
|
+
return { clicked: clicked, failed: failed, counter: cnt }
|
|
273
|
+
}
|
|
274
|
+
async function closeDrawer() {
|
|
275
|
+
for (let i = 0; i < 3; i++) {
|
|
276
|
+
const ok = await page.eval("(() => { const els = [...document.querySelectorAll('[aria-label=关闭], [class*=close-icon], [class*=drawer] [class*=close]')].filter(e => e.getBoundingClientRect().width > 0); if (!els.length) return 'none'; els[0].click(); return 'ok' })()")
|
|
277
|
+
if (ok === 'ok') { await sleep(900); break }
|
|
278
|
+
await key('Escape', 27); await sleep(700)
|
|
279
|
+
}
|
|
280
|
+
await sleep(600)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const SUBMIT_CANDS = "(() => { const out = []; for (const b of document.querySelectorAll('button')) { const t = (b.innerText || '').replace(/\s+/g, ''); if (t !== '确定') continue; const r = b.getBoundingClientRect(); if (r.width < 5 || r.height < 5) continue; if (b.offsetParent === null) continue; const dis = !!b.disabled || b.getAttribute('aria-disabled') === 'true' || /disabled/i.test(String(b.className || '')); let inPopup = false; let n = b; for (let i = 0; i < 8 && n; i++, n = n.parentElement) { if ((n.innerText || '').indexOf('已选择') >= 0) { inPopup = true; break } } out.push({ x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), dis, inPopup }) } return JSON.stringify(out) })()"
|
|
284
|
+
const SUBMIT_STATE = "(() => { const ls = [...document.querySelectorAll('button,span,div')].filter(e => e.children.length === 0 && (e.innerText||'').trim() === '确定' && e.getBoundingClientRect().width > 0); if (!ls.length) return 'none'; const b = ls[ls.length - 1]; const btn = b.closest('button') || b; const dis = !!btn.disabled || btn.getAttribute('aria-disabled') === 'true' || /disabled/i.test(String(btn.className || '')); return dis ? 'disabled' : 'enabled' })()"
|
|
285
|
+
async function tabClick(n) {
|
|
286
|
+
return await page.eval("(() => { for (const l of document.querySelectorAll('" + NAV + "')) { for (const c of l.children) { if ((c.innerText||'').replace(/\\s+/g,' ').trim().includes(" + JSON.stringify(n) + ")) { c.click(); return 'ok' } } } return 'NOTAB' })()")
|
|
287
|
+
}
|
|
288
|
+
const PLAN_MS = Number(process.env.QC_PLAN_MS || 180000)
|
|
289
|
+
async function scanPlan(plan) {
|
|
290
|
+
const t0 = Date.now()
|
|
291
|
+
const nowS = nowSecF()
|
|
292
|
+
const over = (where) => { if (Date.now() - t0 > PLAN_MS) throw new Error('单条计划超时 ' + Math.round((Date.now() - t0) / 1000) + 's @' + where) }
|
|
293
|
+
await searchPlanId(plan.id)
|
|
294
|
+
await openDrawer(plan.id)
|
|
295
|
+
const names = await accountTabs()
|
|
296
|
+
const rec = { planId: plan.id, planName: plan.name, accounts: [], cand: [], stale: 0, clicked: 0, failed: 0 }
|
|
297
|
+
let selTab = null
|
|
298
|
+
let prevSig = ''
|
|
299
|
+
for (const n of names) {
|
|
300
|
+
const tk = await tabClick(n)
|
|
301
|
+
if (tk !== 'ok') { logLine('TAB-FAIL ' + n + ' ' + tk); rec.tabFail = (rec.tabFail || 0) + 1; continue }
|
|
302
|
+
const cards = await readAllCards(prevSig)
|
|
303
|
+
prevSig = sigOf(cards)
|
|
304
|
+
over('cards ' + n)
|
|
305
|
+
logLine('ACCT-READ ' + n + ' cards=' + cards.length + ' recent10=' + cards.filter((c) => c.ct > 0 && nowS - c.ct <= 10 * 86400).length)
|
|
306
|
+
const cand = cards.filter((c) => c.ct > 0 && nowS - c.ct <= WIN && c.sel !== 1)
|
|
307
|
+
const stale = cards.filter((c) => c.ct > 0 && nowS - c.ct > WIN && c.sel !== 1).length
|
|
308
|
+
rec.accounts.push({ name: n, cards: cards.length, sel: cards.filter((c) => c.sel === 1).length, cand: cand.length })
|
|
309
|
+
rec.stale += stale
|
|
310
|
+
if (cand.length) {
|
|
311
|
+
for (const c of cand) rec.cand.push({ aweme: n, id: c.id, title: c.title, ct: c.ct })
|
|
312
|
+
if (mode === 'apply') {
|
|
313
|
+
const r = await clickCandidates(cand)
|
|
314
|
+
rec.clicked += r.clicked
|
|
315
|
+
rec.failed += r.failed.length
|
|
316
|
+
rec.selAfter = r.counter
|
|
317
|
+
for (const c of cand) if (r.failed.indexOf(c.id) < 0) csv({ planId: plan.id, planName: plan.name, aweme: n, title: c.title, publishTime: fmt(c.ct) })
|
|
318
|
+
logLine('ACCT-SEL ' + n + ' clicked=' + r.clicked + ' counter=' + r.counter + ' failed=' + r.failed.length)
|
|
319
|
+
if (r.counter > 0 && !selTab) selTab = n
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
if (mode === 'apply' && rec.cand.length && !(rec.selAfter > 0)) {
|
|
324
|
+
logLine('NO-PENDING-SELECTION counter=0 skip submit')
|
|
325
|
+
await clickExact('取消'); await sleep(1200); await closeDrawer()
|
|
326
|
+
rec.ms = Date.now() - t0
|
|
327
|
+
return rec
|
|
328
|
+
}
|
|
329
|
+
if (mode === 'apply' && rec.cand.length) {
|
|
330
|
+
logLine('SELECTED-TOTAL ' + (rec.selAfter || 0) + ' selTab=' + selTab)
|
|
331
|
+
if (selTab) { await tabClick(selTab); await sleep(1500) }
|
|
332
|
+
let pick = null
|
|
333
|
+
for (let i = 0; i < 12; i++) {
|
|
334
|
+
let cands = []
|
|
335
|
+
try { cands = JSON.parse(await page.eval(SUBMIT_CANDS, 20000)) } catch (e) { cands = [] }
|
|
336
|
+
if (i === 0 || !pick) logLine('SUBMIT-CANDS ' + JSON.stringify(cands))
|
|
337
|
+
pick = cands.find((c) => c.inPopup && !c.dis) || cands.find((c) => !c.dis) || null
|
|
338
|
+
if (pick) break
|
|
339
|
+
await sleep(350)
|
|
340
|
+
}
|
|
341
|
+
if (!pick) throw new Error('确定按钮不可点(没有可用候选)')
|
|
342
|
+
await mouse(pick.x, pick.y)
|
|
343
|
+
logLine('SUBMIT ' + plan.id + ' at=' + pick.x + ',' + pick.y)
|
|
344
|
+
let closed = 0
|
|
345
|
+
for (let i = 0; i < 20; i++) { await sleep(200); closed = await page.eval("document.body.innerText.indexOf('已选择') >= 0 ? 0 : 1"); if (closed) break }
|
|
346
|
+
logLine('POPUP-CLOSED ' + closed)
|
|
347
|
+
if (!closed) throw new Error('提交后素材弹窗没关闭')
|
|
348
|
+
} else {
|
|
349
|
+
await clickExact('取消')
|
|
350
|
+
await sleep(1200)
|
|
351
|
+
}
|
|
352
|
+
rec.ms = Date.now() - t0
|
|
353
|
+
await closeDrawer()
|
|
354
|
+
return rec
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function main() {
|
|
358
|
+
if (mode !== 'scan' && mode !== 'apply') { logLine('用法: node newmat.mjs scan|apply <aavid> [--days=5] [--max=N] [--plan=ID]'); process.exit(2) }
|
|
359
|
+
if (!aavid) { logLine('缺 aavid'); process.exit(2) }
|
|
360
|
+
logLine('START mode=' + mode + ' aavid=' + aavid + ' days=' + DAYS + ' max=' + MAX + (ONE ? ' plan=' + ONE : ''))
|
|
361
|
+
const stateF = path.join(OUT, 'state-' + aavid + '.json')
|
|
362
|
+
const done = (fs.existsSync(stateF) && !FORCE) ? JSON.parse(fs.readFileSync(stateF, 'utf8')) : { done: [] }
|
|
363
|
+
if (!done.done) done.done = []
|
|
364
|
+
let plans = []
|
|
365
|
+
if (ONE) plans = [{ id: ONE, name: '(--plan 指定)' }]
|
|
366
|
+
else if (done.queue && done.queue.length && !FORCE) {
|
|
367
|
+
plans = done.queue.map((x) => (typeof x === 'string' ? { id: x, name: '(--queue)' } : x))
|
|
368
|
+
logLine('RESUME queue=' + plans.length + ' done=' + done.done.length)
|
|
369
|
+
} else {
|
|
370
|
+
await openList()
|
|
371
|
+
try { await filterRunning(); logLine('FILTER-ONCE ok') } catch (e) { logLine('FILTER-ONCE fail ' + String(e.message).slice(0, 60)) }
|
|
372
|
+
plans = await enumerate()
|
|
373
|
+
plans = plans.filter((p) => p.run !== false)
|
|
374
|
+
logLine('PLANS-RUNNING ' + plans.length)
|
|
375
|
+
done.queue = plans
|
|
376
|
+
try { fs.writeFileSync(stateF, JSON.stringify(done, null, 1)) } catch (e) {}
|
|
377
|
+
}
|
|
378
|
+
logLine('PLANS ' + plans.length)
|
|
379
|
+
if (plans.length && !(await ensureList())) throw new Error('列表页不可用')
|
|
380
|
+
let ok = 0; const errs = []
|
|
381
|
+
for (const p of plans) {
|
|
382
|
+
if (done.done.indexOf(p.id) >= 0) { logLine('SKIP ' + p.id); continue }
|
|
383
|
+
try {
|
|
384
|
+
const r = await scanPlan(p)
|
|
385
|
+
ok++
|
|
386
|
+
if (mode === 'apply') { done.done.push(p.id); fs.writeFileSync(stateF, JSON.stringify(done, null, 1)) }
|
|
387
|
+
logLine('PLAN ' + p.id + ' accounts=' + r.accounts.length + ' cand=' + r.cand.length + ' clicked=' + r.clicked + ' failed=' + r.failed + ' stale=' + r.stale + ' ' + (r.ms / 1000).toFixed(1) + 's ' + JSON.stringify(r.accounts.map((a) => a.name + ':' + a.cand)))
|
|
388
|
+
} catch (e) {
|
|
389
|
+
const msg = String(e.message).slice(0, 160)
|
|
390
|
+
errs.push({ id: p.id, err: msg })
|
|
391
|
+
logLine('PLAN-ERR ' + p.id + ' ' + msg)
|
|
392
|
+
try { await clickExact('取消'); await closeDrawer() } catch (e2) {}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
logLine('DONE ok=' + ok + ' err=' + errs.length + ' records=' + CSVF)
|
|
396
|
+
if (errs.length) logLine('ERRS ' + JSON.stringify(errs))
|
|
397
|
+
process.exit(0)
|
|
398
|
+
}
|
|
399
|
+
await main()
|