// ================== 流水线(账号文件夹) ================== // 四个标签:① 资产管理(账号+素材)② 动作 ③ 计划调度 ④ 运行监测 // 所有可变的参数都存 /api/af/profile —— **改完保存即生效**,不用改代码、不用重启。 // 动作本身用的是**现有自定义动作**(/api/custom_actions,任务编辑器拖拽的同一份)。 let _af = {profile: null, accounts: [], devices: [], apps: [], actions: [], jobs: [], runs: [], items: [], roster: [], rosterGroups: {}, plans: [], planRuns: [], assetView: 'accounts', assetFilter: {}, accFilter: {device: '', q: ''}, readyDefaults: {}, curAccount: '', selAccounts: {}, selDevices: {}, devAccount: {}, sub: 'asset', probed: false, busy: false}; const _AF_STATUS = {pending: '待文案', ready: '待发布', pushing: '推送中', publishing: '发布中', done: '已发布', failed: '失败(可重试)', unknown: '未知(需人工)', skipped: '已跳过', asset: '仅素材·不发布'}; function afLoad() { const box = document.getElementById('tab-af'); if (!box) return; if (!box.dataset.built) { box.dataset.built = '1'; box.innerHTML = `
流水线 · 账号文件夹
① 资产管理(账号 ↔ 所属手机 ↔ 素材库,支持模板批量导入)→ ② 动作 → ③ 计划调度(什么素材、什么时间、怎么发、发多少)→ ④ 运行监测 (计划/账号/设备三维度;发布成功自动回写素材状态)。素材与日志都落在该账号文件夹的 _日志/<日期>/;所有设置在本页,改完即生效。
加载中…
`; } afSub(_af.sub); afRefreshAll(); } function afSub(name) { _af.sub = name || 'asset'; document.querySelectorAll('#tab-af [data-afsub]').forEach(b => { const on = b.dataset.afsub === _af.sub; b.classList.toggle('btn-primary', on); }); afRender(); } async function afRefreshAll(show) { const p = await apiGet('/api/af/profile'); if (p && p.ok) _af.profile = p.profile; const a = await apiGet('/api/af/accounts'); if (a && a.ok) { _af.accounts = a.accounts || []; _af.root = a.root || ''; } const d = await apiGet('/api/af/devices'); if (d && d.ok) _af.devices = d.devices || []; const ap = await apiGet('/api/af/apps'); if (ap && ap.ok) _af.apps = ap.apps || []; const ca = await apiGet('/api/custom_actions'); if (ca && ca.ok) _af.actions = ca.actions || []; // 计划编排里也可以直接选「任务」(只取任务步骤,见 core/plan.inline_task_steps) const jb = await apiGet('/api/jobs'); if (jb && (jb.ok || jb.jobs)) _af.jobs = jb.jobs || []; const r = await apiGet('/api/af/runs?limit=100'); if (r && r.ok) _af.runs = r.runs || []; const ro = await apiGet('/api/af/roster'); if (ro && ro.ok) { _af.roster = ro.rows || []; _af.rosterGroups = ro.groups || {}; } const rd = await apiGet('/api/af/ready_defaults'); if (rd && rd.ok) _af.readyDefaults = rd.params || {}; const pl = await apiGet('/api/af/plans'); if (pl && pl.ok) _af.plans = pl.plans || []; const pr = await apiGet('/api/af/plan_runs?limit=30'); if (pr && pr.ok) _af.planRuns = pr.runs || []; if (!_af.curAccount && _af.accounts.length) _af.curAccount = _af.accounts[0].name; const _da = ((_af.profile.params.fleet || {}).device_accounts) || {}; Object.keys(_da).forEach(k => { if (!_af.devAccount[k]) _af.devAccount[k] = _da[k]; }); afRender(); if (show) showToast('已刷新', 'success'); } function afSaveProfile(silent) { if (!_af.profile) return; return apiPost('/api/af/profile', {name: _af.profile.name, params: _af.profile.params}) .then(r => { if (r && r.ok) { if (!silent) showToast(r.msg || '已保存', 'success'); } return r; }); } // 表单里改值 → 直接写进 _af.profile.params(保存时整体提交) function afSet(path, val, type) { const parts = path.split('.'); let o = _af.profile.params; for (let i = 0; i < parts.length - 1; i++) { o = o[parts[i]] = o[parts[i]] || {}; } o[parts[parts.length - 1]] = type === 'num' ? (parseFloat(val) || 0) : type === 'bool' ? !!val : val; } // ---------- 渲染 ---------- function afRender() { const box = document.getElementById('af-body'); if (!box || !_af.profile) return; box.innerHTML = _af.sub === 'asset' ? afHtmlAsset() : _af.sub === 'act' ? afHtmlAct() : _af.sub === 'plan' ? afHtmlPlan() : afHtmlRun(); } // ================== ① 资产管理(账号 + 素材)================== // 用户 2026-10-17 定的结构:**以账号为主键** —— 一张账号表(所属手机 + 素材库), // 点素材库进二级页;支持"模板 + 批量上传素材"匹配导入。 // 素材语义:**未发布/已发布** 是开关(标回未发布 → 按序号继续被计划调用)。 function afAssetOpenAccount(name) { _af.curAccount = name || ''; _af.assetView = name ? 'items' : 'accounts'; _af.assetFilter = {status: '', category: '', display_mode: '', q: ''}; afRender(); if (name) afLoadItems(name); } function afAssetBack() { _af.assetView = 'accounts'; afRender(); } // 账号总表筛选(所属手机 / 昵称)—— 用户 2026-10-17:"方便我快速找出来我要管的账号" function afAccFilterSet(k, v, debounce) { const F = _af.accFilter = _af.accFilter || {device: '', q: '', status: ''}; if (k === '__clear') { F.device = ''; F.q = ''; F.status = ''; } else F[k] = v; const redraw = function () { afRender(); if (k === 'q') { // 重绘会换掉输入框 → 把光标放回去 const el = document.querySelector('#af-body input[placeholder="搜账号昵称"]'); if (el) { el.focus(); try { el.setSelectionRange(el.value.length, el.value.length); } catch (e) {} } } }; if (debounce) { clearTimeout(_af._accT); _af._accT = setTimeout(redraw, 250); } else redraw(); } // ---------- 单条素材上传:选一个文件 → 弹窗手填明细 → 入库 ---------- function afAssetPickFile(account) { const inp = document.createElement('input'); inp.type = 'file'; inp.accept = 'video/*,image/*,audio/*,.mp4,.mov,.mkv,.avi,.m4v,.webm,.3gp,' + '.jpg,.jpeg,.png,.webp,.bmp,.mp3,.m4a,.wav,.aac,.flac,.ogg'; inp.style.display = 'none'; document.body.appendChild(inp); inp.onchange = function () { const f = inp.files && inp.files[0]; try { document.body.removeChild(inp); } catch (e) {} if (f) afOpenSingleUpload(account, f); }; inp.click(); } function _afMediaKind(name) { if (/\.(mp3|m4a|wav|aac|flac|ogg)$/i.test(name || '')) return 'audio'; if (/\.(mp4|mov|mkv|avi|m4v|webm|3gp)$/i.test(name || '')) return 'video'; return 'image'; } let _afSingleFile = null, _afSingleAccount = ''; function afOpenSingleUpload(account, file) { const kind = _afMediaKind(file.name); const old = document.getElementById('af-oneup-overlay'); if (old) old.remove(); const ov = document.createElement('div'); ov.id = 'af-oneup-overlay'; ov.className = 'modal-overlay show'; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); if (kind === 'audio') document.getElementById('af-one-status').value = 'asset'; if (kind !== 'image') { const el = document.createElement(kind === 'audio' ? 'audio' : 'video'); const url = URL.createObjectURL(file); const done = function () { const d = el.duration; if (isFinite(d) && d > 0) document.getElementById('af-one-dur').value = Math.round(d * 10) / 10; URL.revokeObjectURL(url); }; el.preload = 'metadata'; el.onloadedmetadata = done; el.onerror = done; el.src = url; } setTimeout(function () { const t = document.getElementById('af-one-title'); if (t) t.focus(); }, 50); _afSingleFile = file; _afSingleAccount = account; } async function afDoSingleUpload() { const file = _afSingleFile; const account = _afSingleAccount; const ov = document.getElementById('af-oneup-overlay'); if (!file || !account || !ov) return; const val = function (id) { const e = document.getElementById(id); return e ? e.value : ''; }; const fd = new FormData(); fd.append('file', file); fd.append('account', account); fd.append('title', val('af-one-title')); fd.append('body', val('af-one-body')); fd.append('topics', val('af-one-topics')); fd.append('category', val('af-one-cat')); fd.append('display_mode', val('af-one-mode')); fd.append('note', val('af-one-note')); fd.append('duration_s', val('af-one-dur')); fd.append('status', val('af-one-status')); const log = document.getElementById('af-one-log'); const btn = document.getElementById('af-one-btn'); btn.disabled = true; log.textContent = '⏳ 正在上传入库…'; try { const r = await fetch('/api/af/item/upload', { method: 'POST', headers: {'X-CSRF-Token': (typeof _csrfToken !== 'undefined' ? _csrfToken : '')}, body: fd }); const j = await r.json(); if (!j || !j.ok) { log.innerHTML = '❌ ' + esc((j && j.error) || '上传失败') + ''; btn.disabled = false; return; } showToast(j.msg || '已入库', 'success'); ov.remove(); _afSingleFile = null; _afSingleAccount = ''; await afRefreshAll(); if (_af.curAccount) await afLoadItems(_af.curAccount); } catch (e) { log.innerHTML = '❌ 请求失败:' + esc(String(e)) + ''; btn.disabled = false; } } // ---------- 一级:账号总表 ---------- function afHtmlAsset() { if (_af.assetView === 'items' && _af.curAccount) return afHtmlAssetItems(); // 账号总表的筛选:**所属手机** + **账号状态** + 昵称搜索 // (用户 2026-10-17:"方便我快速找出来我要管的账号";2026-10-21 加状态筛选) const F = _af.accFilter || (_af.accFilter = {device: '', q: '', status: ''}); const all = _af.accounts || []; let shown = all; if (F.device === '__none') shown = shown.filter(function (a) { return !a.device_name; }); else if (F.device) shown = shown.filter(function (a) { return a.device_name === F.device; }); if (F.status === '__none') shown = shown.filter(function (a) { return !(a.account_status || '').trim(); }); else if (F.status === '__abnormal') shown = shown.filter(function (a) { return (a.account_status || '').indexOf('异常') >= 0; }); else if (F.status) shown = shown.filter(function (a) { return (a.account_status || '') === F.status; }); if (F.q) { const kw = F.q.toLowerCase(); shown = shown.filter(function (a) { return (a.name || '').toLowerCase().includes(kw); }); } const devNames = Array.from(new Set(all.map(function (a) { return a.device_name; }) .filter(Boolean))).sort(); const statusNames = Array.from(new Set(all.map(function (a) { return (a.account_status || '').trim(); }).filter(Boolean))); // 排序:正常 → 带「异常」的 → 其它(中文排序) statusNames.sort(function (a, b) { if (a === '正常') return -1; if (b === '正常') return 1; const ea = a.indexOf('异常') >= 0, eb = b.indexOf('异常') >= 0; if (ea && !eb) return -1; if (eb && !ea) return 1; return a.localeCompare(b, 'zh'); }); const rows = shown.map(function (a) { const devSel = afDevSelectHtml(a); return '' + '' + esc(a.name) + '' + (a.in_roster ? '' : ' 账号库没有') + (a.has_dir ? '' : '
还没有素材文件夹
') + '' + '' + devSel + '' + '' + (a.account_status ? '' + esc(a.account_status) + ' ' : '— ') + (a.in_roster ? ' ' + '' : '') + (a.status_checked_at ? '
检测 ' + esc(a.status_checked_at) + '
' : '') + '' + '' + '' + esc(a.last_published_at || '—') + '' + '' + '' + (a.in_roster ? '' : '') + '' + '' + ''; }).join(''); return '' + '
' + '' + '' + '' + '' + '账号表里点「入库 N」进素材库;' + '「所属手机」改了就**重新登记**(下次按新设备激活)。素材放进去 = 归这个账号。' + '
' + '
' + '所属手机' + '' + '账号状态' + '' + '' + ((F.device || F.q || F.status) ? '' : '') + '共 ' + all.length + ' 个' + (((F.device || F.q || F.status) && shown.length !== all.length) ? ',筛出 ' + shown.length + ' 个' : '') + '' + '
' + '' + '' + '' + '' + '' + (rows || '') + '
账号所属手机账号状态素材库最近发布操作
' + ((F.device || F.q || F.status) ? '没有符合筛选条件的账号 —— 点「清除筛选」看全部' : '还没有账号 —— 先「导入/维护账号库」,再「批量上传素材」') + '
'; } function afDevSelectHtml(a) { const devs = (_af.devices || []).map(function (d) { return d.name || d.serial; }); const cur = a.device_name || ''; const opts = [''].concat( devs.map(function (n) { return ''; })); // 当前的所属设备可能不在池里(老数据)→ 也列出来,别让它显示成空白 if (cur && devs.indexOf(cur) < 0) { opts.push(''); } const state = !a.in_roster ? '未登记' : (a.pooled ? (a.online ? '在线' : '离线') : '设备未入池'); return '
' + '' + state + '
'; } async function afAssetSetDevice(rosterId, deviceName) { const r = await apiPut('/api/af/roster/' + encodeURIComponent(rosterId), {device_name: deviceName}); if (!r || !r.ok) { showToast((r && r.error) || '改设备失败', 'error'); return; } showToast('已重新登记:' + (deviceName || '未登记设备'), 'success'); await afRefreshAll(); } // 账号状态:手动编辑(任务里「读取文字」写变量 account_status 时也会自动回写这列) function afAssetEditStatus(rosterId, name, cur) { const v = prompt('『' + name + '』的账号状态(正常 / 账号异常 / 限流…;留空=清空)', cur || ''); if (v === null) return; afSaveRosterStatus(rosterId, v); } async function afSaveRosterStatus(rosterId, status) { const r = await apiPut('/api/af/roster/' + encodeURIComponent(rosterId), {account_status: status}); if (!r || !r.ok) { showToast((r && r.error) || '改账号状态失败', 'error'); return; } showToast('账号状态已更新', 'success'); await afRefreshAll(); } async function afAssetStatusLogs(name) { const r = await apiGet('/api/af/account_status_logs?name=' + encodeURIComponent(name) + '&limit=100'); if (!r || !r.ok) { showToast((r && r.error) || '读取状态记录失败', 'error'); return; } const rows = (r.rows || []).map(function (x) { const good = (x.status === '正常' || x.status === '账号正常'); const st = x.status ? '' + esc(x.status) + '' : '(空)'; return '' + esc(x.detected_at || '') + '' + '' + st + '' + esc(x.device_name || '') + '' + '' + esc(x.source || '') + ''; }).join(''); document.getElementById('modal-title').textContent = '账号状态记录 · ' + name; document.getElementById('modal-body').innerHTML = '' + '' + (rows || '') + '
时间状态设备来源
还没有检测记录
'; document.getElementById('modal-footer').innerHTML = ''; showModal(); } function afAssetScan(name) { afScan(name); } // ---------- 删除账号(资产管理行内「删除」)---------- // 账号表 = 账号库 ∪ 素材目录,所以删除要分别处理: // ① 账号库登记 ② 素材文件夹(**移到 _已删除/,不永久删原件**) ③ 平台素材记录 function afAssetDeleteAccount(name) { const a = (_af.accounts || []).find(function (x) { return x.name === name; }) || {name: name}; const old = document.getElementById('af-del-acc-overlay'); if (old) old.remove(); const ov = document.createElement('div'); ov.id = 'af-del-acc-overlay'; ov.className = 'modal-overlay show'; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; const row = function (id, title, checked, disabled, help) { return '
' + ' ' + '' + (help ? '
' + help + '
' : '') + '
'; }; ov.innerHTML = ''; document.body.appendChild(ov); } async function afDoDeleteAccount(name) { const c = function (id) { const e = document.getElementById(id); return !!(e && e.checked && !e.disabled); }; const body = {delete_roster: c('af-del-roster'), archive_dir: c('af-del-archive'), delete_records: c('af-del-records')}; if (!body.delete_roster && !body.archive_dir && !body.delete_records) { showToast('至少勾选一项', 'error'); return; } const txt = []; if (body.delete_roster) txt.push('删除账号库登记'); if (body.archive_dir) txt.push('把素材文件夹移到 _已删除/'); if (body.delete_records) txt.push('删除平台素材记录'); if (!confirm('确定删除账号「' + name + '」?\n\n' + txt.join('\n') + '\n\n手机上的账号不会被退出。')) return; try { const r = await fetch('/api/af/account/' + encodeURIComponent(name), { method: 'DELETE', headers: {'Content-Type': 'application/json', ...(typeof _csrfHeaders === 'function' ? _csrfHeaders() : {})}, body: JSON.stringify(body) }).then(function (x) { return x.json(); }); if (!r || !r.ok) { showToast((r && r.error) || '删除失败', 'error'); return; } const ov = document.getElementById('af-del-acc-overlay'); if (ov) ov.remove(); if (_af.curAccount === name) { _af.curAccount = ''; _af.assetView = 'accounts'; } showToast(r.msg || '已删除', 'success'); await afRefreshAll(); } catch (e) { showToast('请求失败:' + String(e), 'error'); } } function afAssetEditAccount(rosterId) { const row = (_af.roster || []).find(function (x) { return x.id === rosterId; }) || {}; const devs = (_af.devices || []).map(function (d) { return d.name || d.serial; }); const ov = document.createElement('div'); ov.id = 'af-acc-overlay'; ov.className = 'modal-overlay show'; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); } async function afAssetSaveAccount(rosterId) { const body = { nickname: document.getElementById('af-acc-nick').value.trim(), douyin_id: document.getElementById('af-acc-did').value.trim(), device_name: document.getElementById('af-acc-dev').value }; const r = await apiPut('/api/af/roster/' + encodeURIComponent(rosterId), body); if (!r || !r.ok) { showToast((r && r.error) || '保存失败', 'error'); return; } const ov = document.getElementById('af-acc-overlay'); if (ov) ov.remove(); showToast('已保存', 'success'); await afRefreshAll(); } // ---------- 二级:某个账号的素材库 ---------- function afHtmlAssetItems() { const acc = _af.curAccount; const f = _af.assetFilter || {}; const st = _AF_STATUS; const modeOpts = ['', '口播', '大字报', '混剪', '搬运']; const items = (_af.items || []).filter(function (x) { if (f.status && x.status !== f.status) return false; if (f.category && x.category !== f.category) return false; if (f.display_mode && x.display_mode !== f.display_mode) return false; if (f.q) { const kw = f.q.toLowerCase(); if (!((x.title || '').toLowerCase().includes(kw) || (x.video_name || '').toLowerCase().includes(kw))) return false; } return true; }); const rows = items.map(function (x) { const t = {video: '视频', image: '图片', audio: '音频'}[x.media_type] || '?'; const canPub = x.status === 'ready' || x.status === 'failed'; return '' + '#' + (x.seq || '') + '' + '
' + esc(x.video_name || '') + '
' + '' + esc(x.device_name || '—') + ' · ' + t + (x.duration_s ? ' · ' + x.duration_s + 's' : '') + '' + '
' + esc(x.title || '(无标题)') + '
' + (x.body ? '
' + esc(x.body) + '
' : '') + '' + '' + esc(x.topics || '') + '' + '' + esc(x.category || '') + '' + '' + esc(x.display_mode || '') + '' + '' + esc(st[x.status] || x.status) + '' + '' + esc(x.published_at || '—') + '' + '' + ' ' + (canPub ? '' : ' ') + ' ' + '' + ''; }).join(''); return '' + '
' + '' + '' + esc(acc) + '' + '素材库(按编号排序;未发布的会被计划按序号取走)' + '' + '' + '
' + '
' + '状态 ' + ' 分类 ' + ' 展示方式 ' + ' 搜索 ' + '
' + '' + '' + '' + '' + (rows || '') + '
#文件名 / 设备 / 类型标题 / 内容话题分类展示方式状态上次发布操作
这个账号还没有素材 —— 点「批量上传(配模板)」
' + '
'; } function afAssetFilterSet(k, v, debounce) { _af.assetFilter = _af.assetFilter || {}; _af.assetFilter[k] = v; if (debounce) { clearTimeout(_af._assetT); _af._assetT = setTimeout(function () { afRender(); }, 300); } else afRender(); } // 编辑素材元数据(只改填入的字段;不走老 PUT,避免标题被清空) function afAssetEditItem(id) { const x = (_af.items || []).find(function (i) { return i.id === id; }) || {}; const ov = document.createElement('div'); ov.id = 'af-item-overlay'; ov.className = 'modal-overlay show'; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); } async function afAssetSaveItem(id) { const body = { title: document.getElementById('afe-title').value, body: document.getElementById('afe-body').value, topics: document.getElementById('afe-topics').value, category: document.getElementById('afe-cat').value, display_mode: document.getElementById('afe-mode').value, duration_s: parseInt(document.getElementById('afe-dur').value || '0', 10), note: document.getElementById('afe-note').value }; const r = await apiPost('/api/af/item/' + encodeURIComponent(id) + '/meta', body); if (!r || !r.ok) { showToast((r && r.error) || '保存失败', 'error'); return; } const ov = document.getElementById('af-item-overlay'); if (ov) ov.remove(); showToast('素材已更新', 'success'); await afLoadItems(_af.curAccount); afRender(); } async function afAssetUnpublish(id) { if (!confirm('标为「未发布」?\n\n它会被下一次计划按序号重新取走发布(历史链接/发布时间保留)。')) return; const r = await apiPost('/api/video_plan/' + encodeURIComponent(id) + '/retry', {}); if (!r || !r.ok) { showToast((r && r.error) || '操作失败', 'error'); return; } showToast('已放回未发布', 'success'); await afLoadItems(_af.curAccount); await afRefreshAll(); } async function afAssetDel(id) { if (!confirm('删除这条素材?\n(平台上的副本会删;账号文件夹里的原文件不动)')) return; const r = await apiDelete('/api/video_plan/' + encodeURIComponent(id)); if (!r || !r.ok) { showToast((r && r.error) || '删除失败', 'error'); return; } showToast('已删除', 'success'); await afLoadItems(_af.curAccount); await afRefreshAll(); } async function afAssetLogs(id) { const box = document.getElementById('af-asset-log'); const r = await apiGet('/api/af/item/' + encodeURIComponent(id) + '/publish_logs'); if (!r || !r.ok) { showToast('读发布记录失败', 'error'); return; } const logs = r.logs || []; if (box) { box.innerHTML = '
' + '发布记录 ' + '' + '' + (logs.length ? logs.map(function (l) { return '' + '' + '' + ''; }).join('') : '') + '
时间结果设备链接 / 原因
' + esc(l.at) + '' + ({published: '✅ 发布成功', failed: '❌ 失败', unknown: '❔ 未知'}[l.result] || esc(l.result)) + '' + esc(l.device_name || '') + '' + (l.share_url ? '' + esc(l.share_url) + '' : esc(l.error || '')) + '
还没发过
'; box.scrollIntoView({block: 'nearest'}); } } // ---------- 批量上传 + 模板匹配 ---------- function afOpenAssetImport(account) { const acc = account || _af.curAccount || ''; const ov = document.createElement('div'); ov.id = 'af-asset-up-overlay'; ov.className = 'modal-overlay show'; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); document.getElementById('af-au-files').onchange = afAssetFilesChanged; } // 选完文件先用浏览器把**时长**读出来(服务器没装 ffprobe) let _afDurations = {}; function afAssetFilesChanged() { const inp = document.getElementById('af-au-files'); const files = Array.from(inp.files || []); const cnt = document.getElementById('af-au-count'); _afDurations = {}; if (cnt) cnt.textContent = '已选 ' + files.length + ' 个文件,正在读取时长…'; let left = 0; files.forEach(function (f) { const isMedia = /^(video|audio)\//.test(f.type) || /\.(mp4|mov|mkv|avi|m4v|webm|mp3|m4a|wav|aac|flac|ogg)$/i.test(f.name); if (!isMedia) return; left += 1; const el = document.createElement(f.type && f.type.indexOf('audio') === 0 ? 'audio' : 'video'); const url = URL.createObjectURL(f); const done = function () { const d = el.duration; if (isFinite(d) && d > 0) _afDurations[f.name] = Math.round(d * 10) / 10; URL.revokeObjectURL(url); left -= 1; if (left <= 0 && cnt) { const got = Object.keys(_afDurations).length; cnt.textContent = '已选 ' + files.length + ' 个文件(读到 ' + got + ' 个时长)'; } }; el.preload = 'metadata'; el.onloadedmetadata = done; el.onerror = done; el.src = url; }); if (!left && cnt) cnt.textContent = '已选 ' + files.length + ' 个文件'; } async function afDoAssetImport(dry) { const files = document.getElementById('af-au-files').files; const table = document.getElementById('af-au-table').files[0]; const log = document.getElementById('af-au-log'); if (!files || !files.length) { showToast('先选素材文件', 'error'); return; } if (!table) { showToast('先选填好的表(CSV)', 'error'); return; } const fd = new FormData(); for (let i = 0; i < files.length; i++) fd.append('files', files[i]); fd.append('table', table); fd.append('durations', JSON.stringify(_afDurations || {})); if (dry) fd.append('dry_run', '1'); log.innerHTML = '⏳ ' + (dry ? '正在校验(不写盘)…' : '正在导入…'); try { const r = await fetch('/api/af/assets/import', { method: 'POST', headers: {'X-CSRF-Token': (typeof _csrfToken !== 'undefined' ? _csrfToken : '')}, body: fd }); const j = await r.json(); if (!j.ok) { const errs = (j.errors || []); log.innerHTML = '
❌ 校验没过,整批没有导入
' + (errs.length ? '' : '
' + esc(j.error || '') + '
'); return; } const rows = j.rows || []; log.innerHTML = '
✅ ' + esc(j.msg || '') + '
' + '' + '' + '' + rows.map(function (x) { return '' + '' + '' + ''; }).join('') + '
行文件账号结果说明
' + (x.line || '') + '' + esc(x.file) + '' + esc(x.account || '') + '' + esc(x.action || '') + '' + esc(x.error || x.msg || '') + '
'; if (!dry) { showToast(j.msg || '已导入', 'success'); await afRefreshAll(); if (_af.curAccount) await afLoadItems(_af.curAccount); afRender(); } } catch (e) { log.innerHTML = '❌ 请求失败:' + esc(String(e)) + ''; } } // ① 素材 function afHtmlSrc() { const P = _af.profile.params.source; const rows = _af.accounts.map(a => ` ${esc(a.name)}${a.valid ? '' : ' (目录名不合法)'} ${a.media}${a.pending}${a.done} ${a.last_run ? esc(a.last_run.started_at) + ' · ' + esc(_AF_STATUS[a.last_run.status] || a.last_run.status) : '—'} `).join(''); const items = _af.items.filter(x => !_af.curAccount || x.nickname === _af.curAccount); const itemRows = items.map(x => ` ${x.seq} ${esc(x.video_name || x.src_path || '')} ${esc(x.title || '(无标题)')} ${esc(_AF_STATUS[x.status] || x.status)} ${esc(x.last_error || '')} `).join(''); return `
${_af.curAccount ? `` : ''} 根目录:${esc(_af.root || '')}(也可以直接把文件拷进去,效果一样)
账号(目录)
${rows || ''}
账号素材待发已发上次运行
根目录下还没有账号文件夹
条目${_af.curAccount ? '(' + esc(_af.curAccount) + ')' : ''}
${itemRows || ''}
编号素材标题状态说明
还没有条目 —— 点「扫描全部账号」
`; } // 上传素材:等价于"把文件拷进账号文件夹",传完自动扫描入库 function afOpenUpload() { const opts = _af.accounts.map(a => `'; }).join(''); const S = F.switch; return '' + '
' + '执行单位 ' + '' + '' + '
' + (mode === 'by_device' ? '
' + '
' + '
① 设备 勾选要同时跑的机器;「用号」= 这台要切到哪个账号
' + '
' + '
' + '
' + (devs || '设备池为空') + '
' : '
' + '
' + '
① 账号 默认全选;取消勾选就不跑它
' + '
' + '' + '
' + '
' + (accs || '还没有账号 —— 先去「① 素材」扫描或上传') + '
') + '
' + '② 切号与校验 (开场动作里那步「切账号」用这些参数)' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '③ 用哪个动作组' + '
' + '' + '开场动作(把设备置初始状态)在「③ 动作」里按 App 配;' + '没配就用内置默认:打开App → 等首页 → 切到目标号
' + '
' + '' + '' + '
' + '
' + '⚠ 每台设备同一时刻只能跑一个任务;流水线会跳过正在跑任务的设备(不会打断它)。
' + '
' + afHtmlRoster(); } // ===== 账号库:哪台手机登着哪些号("名字 → 哪台手机"的唯一台账)===== // 用途:以后"输入几个视频/几个名字,**只有名字对应的那台手机才激活任务**"就查它, // 不用每次去每台手机上探测。数据表见 core/models.DeviceAccount(原先的账号台账,重新启用)。 function afHtmlRoster() { const groups = _af.rosterGroups || {}; const names = Object.keys(groups).sort(); const devCount = names.filter(n => n !== '(未指定设备)').length; const body = names.map(function (dev) { const rows = groups[dev] || []; const one = rows[0] || {}; const state = dev === '(未指定设备)' ? '没写设备号' : one.pooled ? (one.online ? '在线' : '离线') : '未入设备池'; return '
' + '
' + esc(dev) + '
' + state + '
' + '
' + rows.map(r => '' + esc(r.nickname) + ' ' + esc(r.douyin_id || '') + '' + '×').join('') + '
'; }).join(''); return '
' + '
' + '
📇 账号库 ' + devCount + ' 台设备 · ' + _af.roster.length + ' 个号|名字 ↔ 哪台手机 就靠它 —— ' + '以后"输入几个名字,只有对应的手机才激活任务"查的就是这张表
' + '
' + '
' + '
' + (body || '
账号库是空的 —— 点「粘贴导入」把表格里的行贴进来
') + '
'; } // 账号池对外只读 API:给其他应用看"池子里有哪些号、在哪台手机" async function afShowPoolApi() { const r = await apiGet('/api/account_pool/token'); if (!r || !r.ok) { showToast((r && r.error) || '需要管理员权限', 'error'); return; } const old = document.getElementById('af-pool-api'); if (old) old.remove(); const url = r.url || (location.origin + '/api/account_pool/accounts'); const token = r.token || ''; const curl = 'curl -H "X-Account-Token: ' + token + '" "' + url + '"'; const d = document.createElement('div'); d.id = 'af-pool-api'; d.className = 'modal-overlay show'; d.innerHTML = ''; document.body.appendChild(d); } function afCopyPoolToken() { const el = document.getElementById('af-pool-token'); if (!el) return; el.select(); if (navigator.clipboard) { navigator.clipboard.writeText(el.value).then(function () { showToast('已复制', 'success'); }); } else { document.execCommand('copy'); showToast('已复制', 'success'); } } async function afResetPoolToken() { if (!confirm('重置后旧令牌立即失效,其他应用需要更新。继续?')) return; const r = await apiPost('/api/account_pool/token/reset', {}); if (!r || !r.ok) { showToast((r && r.error) || '重置失败', 'error'); return; } showToast('令牌已重置', 'success'); afShowPoolApi(); } function afOpenRoster() { const ov = document.getElementById('af-roster-overlay'); if (ov) ov.remove(); const d = document.createElement('div'); d.id = 'af-roster-overlay'; d.className = 'modal-overlay show'; d.onclick = function (e) { if (e.target === d) d.remove(); }; d.innerHTML = ''; document.body.appendChild(d); } async function afDoRoster(dry) { const box = document.getElementById('af-roster-text'); const out = document.getElementById('af-roster-res'); const text = (box && box.value || '').trim(); if (!text) { showToast('先粘贴几行', 'error'); return; } out.innerHTML = '⏳ ' + (dry ? '试算中…' : '导入中…'); const r = await apiPost('/api/af/roster/import', {text: text, dry_run: !!dry}); if (!r || !r.ok) { out.innerHTML = '❌ ' + esc((r && r.error) || '失败') + ''; return; } const x = r.result || {}; let html = (dry ? '试算结果(没写库):' : '已导入:') + '新增 ' + x.added + ' 行、改名 ' + x.updated + ' 行、没变 ' + x.unchanged + ' 行'; if ((x.bad || []).length) { html += '
认不出来的 ' + x.bad.length + ' 行: ' + x.bad.map(b => esc(b.nickname || '(空)')).join('、'); } if ((x.stale || []).length) { html += '
库里多出来 ' + x.stale.length + ' 行(没删,自己看一眼要不要删):
' + x.stale.map(s => esc(s.device_name + ' ' + s.nickname + ' ' + (s.douyin_id || '')) + ' 删除').join('
'); } out.innerHTML = html; if (!dry) { if (r.rows) { _af.roster = r.rows; const g = {}; r.rows.forEach(function (x2) { g[(x2.device_name || '').trim() || '(未指定设备)'] = (g[(x2.device_name || '').trim() || '(未指定设备)'] || []).concat([x2]); }); _af.rosterGroups = g; } afRender(); showToast('账号库已更新', 'success'); } } async function afDelRoster(id, name) { if (!confirm('把「' + name + '」从账号库删掉?\n(只删这张表里的记录,不动手机上的账号)')) return; const r = await apiDelete('/api/af/roster/' + encodeURIComponent(id)); if (!r || !r.ok) { showToast((r && r.error) || '删除失败', 'error'); return; } _af.roster = r.rows || []; const g = {}; _af.roster.forEach(function (x) { const k = (x.device_name || '').trim() || '(未指定设备)'; g[k] = (g[k] || []).concat([x]); }); _af.rosterGroups = g; afRender(); showToast('已删一行', 'success'); } function afSetMode(m) { _af.profile.params.fleet.run_mode = m; afSaveProfile(true).then(function () { afRender(); }); } // "账号1, 账号2" → ["账号1","账号2"](中英文逗号、分号都认) function afSplitAccounts(v) { return String(v || '').replace(/[,;;]/g, ',').split(',') .map(function (x) { return x.trim(); }).filter(Boolean); } function afSetDevAccount(serial, account) { _af.devAccount[serial] = (account || '').trim(); const F = _af.profile.params.fleet; F.device_accounts = F.device_accounts || {}; F.device_accounts[serial] = _af.devAccount[serial]; afSaveProfile(true); } function afToggleDev(serial) { _af.selDevices[serial] = !_af.selDevices[serial]; afRender(); afSyncSel(); } function afToggleAcc(name, on) { _af.selAccounts[name] = !!on; afSyncSel(); } function afPickAll(on) { _af.accounts.forEach(a => _af.selAccounts[a.name] = !!on); afRender(); afSyncSel(); } function afSyncSel() { const d = Object.keys(_af.selDevices).filter(k => _af.selDevices[k]); const a = _af.accounts.filter(x => _af.selAccounts[x.name] !== false); const hint = document.getElementById('af-run-hint'); if (hint) hint.textContent = '将跑 ' + a.length + ' 个账号 / 用到 ' + (d.length ? d.length + ' 台指定设备' : '按账号自动找设备'); } async function afProbe() { showToast('探测中(每台要连一下,稍等)…'); const r = await apiPost('/api/af/probe', {}); if (!r || !r.ok) { showToast((r && r.error) || '探测失败', 'error'); return; } const got = (r.devices || []).filter(d => d.account); (r.devices || []).forEach(d => { if (d.account && !_af.devAccount[d.serial]) _af.devAccount[d.serial] = d.account; }); const F = _af.profile.params.fleet; F.device_accounts = Object.assign(F.device_accounts || {}, _af.devAccount); showToast(got.length ? ('探测到 ' + got.length + ' 台有账号:' + got.map(d => (d.device_name || d.serial) + '→' + d.account).join('、')) : '没探测到账号(设备上可能没开对应 App)', got.length ? 'success' : 'error'); await afSaveProfile(true); await afRefreshAll(true); } async function afRun() { const P = _af.profile.params; const action_id = P.action.action_id; if (!action_id) { showToast('先选一个动作组', 'error'); return; } const mode = P.fleet.run_mode || 'by_account'; await afSaveProfile(true); let body; if (mode === 'by_device') { const devices = _af.devices.filter(function (d) { return _af.selDevices[d.serial]; }) .map(function (d) { return {serial: d.serial, accounts: afSplitAccounts(_af.devAccount[d.serial] || d.cur_account || '')}; }); if (!devices.length) { showToast('先勾要跑的设备', 'error'); return; } const noAcc = devices.filter(function (d) { return !d.accounts.length; }); if (noAcc.length) { showToast('有 ' + noAcc.length + ' 台没填「要跑的号」(点「探测当前登录账号」或手工填,可多个)', 'error'); return; } body = {mode: 'by_device', devices: devices, action_id: action_id}; } else { const accounts = _af.accounts.filter(function (a) { return _af.selAccounts[a.name] !== false; }) .map(function (a) { return a.name; }); if (!accounts.length) { showToast('没选账号', 'error'); return; } body = {mode: 'by_account', accounts: accounts, action_id: action_id}; } const r = await apiPost('/api/af/run', body); if (!r || !r.ok) { showToast((r && r.error) || '触发失败', 'error'); return; } showToast(r.msg || '已触发', 'success'); afSub('run'); setTimeout(afRefreshAll, 1500); } // ③ 动作:① 开场动作(按 App)② 业务动作组 ③ 内置动作 function afHtmlAct() { // App 卡片(只放 App 本身的信息:名称/包名/首页定位 —— 动作都在下面的表里) const appBlocks = _af.apps.map(function (app) { const op = (_af.actions || []).find(function (a) { return (a.kind || '') === 'opening' && a.app_id === app.id; }); return '' + '
' + '
' + '
' + esc(app.name) + ' ' + esc(app.package) + '' + (op ? ' 开场动作已配' : ' 还没开场动作') + '
' + '
' + '' + '' + '' + '' + (op ? '' : '') + '
'; }).join(''); // ---- 动作表:**一行一个动作,"动作内容"自成一列,操作放在这一行下面** ---- const typeLabel = function (a) { const k = a.kind || ''; if (k === 'builtin') return '内置'; if (k === 'opening') return '开场'; return a.app_id ? '业务' : '未归属 App'; }; const actName = function (id) { const a = (_af.actions || []).find(function (x) { return x.id === id; }); return a ? a.name : '(已删?)'; }; // 排序:★标准件 → 内置 → 开场 → 业务;组内按 App 名、动作名 const rank = function (a) { if (a.starred) return 0; const k = a.kind || ''; if (k === 'builtin') return 1; if (k === 'opening') return 2; return 3; }; const rows = (_af.actions || []).slice().sort(function (x, y) { const r = rank(x) - rank(y); if (r) return r; const ax = (_af.apps.find(function (p) { return p.id === x.app_id; }) || {}).name || ''; const ay = (_af.apps.find(function (p) { return p.id === y.app_id; }) || {}).name || ''; return (ax + (x.name || '')).localeCompare(ay + (y.name || '')); }).map(function (a) { const app = _af.apps.find(function (p) { return p.id === a.app_id; }) || {}; const sp = a.start_page || {}, ep = a.end_page || {}; const used = a.used_by || 0; const n = (a.steps || []).length; const ops = [ '', '', '', '', '' ]; if ((a.kind || '') !== 'builtin' && (a.kind || '') !== 'opening') { ops.push(''); } if ((a.kind || '') === 'builtin') { ops.push(''); } return '' + '' + esc(app.name || '(未归属)') + '' + '' + typeLabel(a) + '' + '' + esc(a.name) + '' + (a.starred ? ' ★' : '') + (used ? ' 被引用 ' + used + ' 处' : '') + '' + '
' + esc(afStepsSummary(a.steps)) + '
' + '共 ' + n + ' 步' + '起点:' + (sp.selector_value ? '' + esc(sp.selector_value) + '' : 'App 首页') + '
终点:' + (ep.selector_value ? esc(ep.selector_value) : '(未设)') + '
' + '' + ops.join(' ') + '' + ''; }).join(''); const table = '' + '' + '' + '' + (rows || '') + '
App类型动作名动作内容(一眼看它都干了什么)起点 / 终点操作
还没有动作 —— 点「+ 新建业务动作组」,' + '或先建 App 再「一键建开场动作」
'; return '' + '
' + '' + '' + '' + '' + '动作组 = 起点(App + 从哪一页开始)+ 内容(一串步骤)+ 终点(跑完得看到的那一页);' + '编辑器是任务页同一个,建的动作任务/计划里都能直接引用。' + '内置动作由代码播种(不可删、可复制);★标准件是你自己标的常用件(置顶、删前要取消标记)' + '
' + '' + (appBlocks || '
先「+ 新建 App」(例如抖音),再建开场动作与业务动作组
') + table; } // 「动作内容」一列的摘要:把这一步串的头几步用人话连起来(容器显示它里面是什么) // 目的:一眼看出"这组动作到底干了什么",不用点开编辑。 function afStepsSummary(steps, maxItems) { maxItems = maxItems || 6; const one = function (s) { const t = (s && s.type) || ''; const p = (s && s.params) || {}; if (t === 'loop') return '循环×' + (p.max_iterations || '?') + '[ ' + afStepsSummary(p.children, 3) + ' ]'; if (t === 'foreach_account') return '循环账号[ ' + afStepsSummary(p.children, 3) + ' ]'; if (t === 'foreach_item') return '循环内容[ ' + afStepsSummary(p.children, 3) + ' ]'; if (t === 'if_el') return '条件判断[' + afStepsSummary(p.then, 2) + ' / ' + afStepsSummary(p.else, 2) + ']'; if (t === 'group') return '📦' + (s.label || '动作组') + '[ ' + afStepsSummary(p.children, 3) + ' ]'; if (t === 'action_ref') return '🔗' + (s.label || p.action_name || '组合') + '(引用)'; const lb = (s && s.label) || t; // 只在"人看得懂"的选择器上带出目标(文字/描述类、短);xpath 这种一串混淆 id 只会把列撑爆 const st = String(p.selector_type || ''); const sv = p.selector_value ? String(p.selector_value) : ''; const human = /text|description/i.test(st) && sv && sv.length <= 14 && sv.indexOf('//') !== 0; return lb + (human ? ('(' + sv + ')') : ''); }; const arr = (steps || []).filter(function (s) { return s && s.type; }); if (!arr.length) return '(空)'; const head = arr.slice(0, maxItems).map(one).join(' → '); return head + (arr.length > maxItems ? (' → …(共 ' + arr.length + ' 步)') : ''); } // ★ 标准件标记 async function afStarAction(id, on) { const r = await apiPut('/api/custom_actions/' + encodeURIComponent(id), {starred: !!on}); if (!r || !r.ok) { showToast((r && r.error) || '操作失败', 'error'); return; } showToast(on ? '已标为标准件(置顶显示)' : '已取消标准件', 'success'); await afRefreshAll(); } // 「谁在用这个组合」—— 删之前的影响面(弹窗) async function afShowUsage(id) { const r = await apiGet('/api/custom_actions/' + encodeURIComponent(id) + '/usage'); if (!r || !r.ok) { showToast((r && r.error) || '查询失败', 'error'); return; } const e = r.exact || {}, g = r.legacy_guess || {}; const li = function (arr, f) { return (arr || []).map(function (x) { return '
  • ' + esc(x.name || x.id) + (x.path ? ' (' + esc(x.path) + ')' : '') + (x.field ? ' (' + esc(x.field) + ')' : '') + '
  • '; }).join(''); }; const html = '
    ' + '
    ' + esc((r.action || {}).name || '') + ':' + esc(r.summary || '') + '
    ' + ((e.tasks || []).length ? '
    任务:
    ' : '') + ((e.actions || []).length ? '
    其它组合:
    ' : '') + ((e.plans || []).length ? '
    计划:
    ' : '') + ((g.tasks || []).length ? '
    可能是它(老任务里的展开副本,按名字猜的,' + '仅供参考 —— 那些任务里存的是步骤副本,改/删这个组合**不影响**它们):
    ' : '') + '
    ' + (r.can_delete ? '现在**可以删**。' : ('**不能直接删**:' + esc(r.error || ''))) + '
    '; const ov = document.createElement('div'); ov.className = 'modal-overlay show'; ov.id = 'af-usage-overlay'; ov.onclick = function (ev) { if (ev.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); } // 「试跑」:选设备 + 手填要切到的账号 → 单独跑这个动作(不套内容循环) function afTryAction(actionId) { const a = _af.actions.find(function (x) { return x.id === actionId; }) || {}; const devs = _af.devices.map(function (d) { return ''; }).join(''); const ov = document.createElement('div'); ov.id = 'af-try-overlay'; ov.className = 'modal-overlay show'; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); } async function afDoTry(actionId) { const serial = document.getElementById('af-try-dev').value; const target = (document.getElementById('af-try-name').value || '').trim(); const log = document.getElementById('af-try-log'); if (!serial) { log.textContent = '❌ 先选设备'; return; } const btn = document.getElementById('af-try-btn'); btn.disabled = true; log.textContent = '⏳ 已下发到 ' + serial + ',正在跑…(跑完自动跳到运行明细)'; const r = await apiPost('/api/af/try', {serial: serial, action_id: actionId, target_name: target}); if (!r || !r.ok) { log.textContent = '❌ ' + ((r && r.error) || '触发失败'); btn.disabled = false; return; } var ov = document.getElementById('af-try-overlay'); if (ov) ov.remove(); showToast('已开始试跑(' + (target || '未填名字') + ')', 'success'); afSub('run'); await afRefreshAll(); afShowRun(r.run_id); // 跑完再自动刷一次明细(切号含 15 秒等待,给它几次机会) var n = 0; var timer = setInterval(function () { n += 1; afShowRun(r.run_id); if (n >= 6) clearInterval(timer); }, 8000); } async function afNewOpening(appId) { showToast('正在新建开场动作…'); const r = await apiPost('/api/af/apps/' + appId + '/opening', {}); if (!r || !r.ok) { showToast((r && r.error) || '新建失败', 'error'); return; } showToast(r.msg || '已新建', 'success'); await afRefreshAll(); } async function afDelAction(id) { // **删之前必须先告诉操作者会影响谁**(用户 2026-10-17 的要求): // 先查引用 → 把任务/组合/计划列出来 → 有精确引用时默认不让删(要强删得再确认一次)。 const u = await apiGet('/api/custom_actions/' + encodeURIComponent(id) + '/usage'); if (!u || !u.ok) { showToast((u && u.error) || '查询引用失败', 'error'); return; } const e = u.exact || {}, g = u.legacy_guess || {}; const lines = []; const add = function (label, arr) { (arr || []).forEach(function (x) { lines.push(' · ' + label + ':' + (x.name || x.id)); }); }; add('任务', e.tasks); add('其它组合', e.actions); add('计划', e.plans); const name = (u.action || {}).name || ''; if (!u.can_delete) { if (!lines.length) { showToast(u.error || '不能删', 'error'); return; } if (!confirm('『' + name + '』' + (u.summary || '') + ':\n' + lines.join('\n') + '\n\n删掉后这些任务/计划运行时**会直接报错**。\n仍要强删吗?(不确定就点取消)')) return; const r = await apiDelete('/api/custom_actions/' + encodeURIComponent(id) + '?force=1'); if (!r || !r.ok) { showToast((r && r.error) || '删除失败', 'error'); return; } showToast('已强删(受影响的任务/计划要自己去改)', 'error'); await afRefreshAll(); return; } let msg = '确认删除『' + name + '』?'; if (lines.length) msg += '\n\n可能用过它的老任务(展开副本,仅供参考,不受影响):\n' + lines.join('\n'); if ((g.tasks || []).length) { msg += '\n\n注意:老任务里存的是**步骤副本**,删这个组合不影响它们运行,' + '但以后想改就找不到源头了。'; } if (!confirm(msg)) return; const r = await apiDelete('/api/custom_actions/' + encodeURIComponent(id)); if (!r || !r.ok) { showToast((r && r.error) || '删除失败', 'error'); return; } showToast('已删除', 'success'); await afRefreshAll(); } async function afCopyAction(id) { const a = _af.actions.find(function (x) { return x.id === id; }); if (!a) return; const r = await apiPost('/api/custom_actions', { name: (a.name || '动作') + '(副本)', icon: a.icon || '📦', steps: a.steps || [], app_id: a.app_id || '', kind: '', start_page: a.start_page || {}, end_page: a.end_page || {}}); if (!r || !r.ok) { showToast((r && r.error) || '复制失败', 'error'); return; } showToast('已复制,点「编辑动作组」改它', 'success'); await afRefreshAll(); } function afNewApp() { const e = document.getElementById('af-newapp'); e.style.display = 'block'; } async function afCreateApp() { const name = document.getElementById('na-name').value.trim(); const pkg = document.getElementById('na-pkg').value.trim(); const wh = document.getElementById('na-wh').value.trim(); if (!name || !pkg) { showToast('App 名称和包名都要填', 'error'); return; } const r = await apiPost('/api/af/apps', {name: name, package: pkg, home_what: wh, home_selector_type: 'xpath'}); if (!r || !r.ok) { showToast((r && r.error) || '创建失败', 'error'); return; } showToast('已创建 App', 'success'); document.getElementById('af-newapp').style.display = 'none'; await afRefreshAll(); } async function afSaveApp(id) { const el = document.getElementById('app-home-' + id); const r = await apiPost('/api/af/apps/' + id, {home_selector_value: el ? el.value.trim() : '', home_selector_type: 'xpath'}); showToast((r && r.ok) ? '首页定位已保存' : ((r && r.error) || '保存失败'), (r && r.ok) ? 'success' : 'error'); await afRefreshAll(); } async function afSetActionApp(actionId, appId) { const el = document.getElementById('act-start-' + actionId); const sp = {selector_type: 'xpath', selector_value: el ? el.value.trim() : '', what: ''}; const r = await apiPost('/api/custom_actions/' + actionId, {app_id: appId, start_page: sp}); showToast((r && r.ok) ? '已归属' : ((r && r.error) || '保存失败'), (r && r.ok) ? 'success' : 'error'); await afRefreshAll(); } async function afSaveAction(actionId) { const el = document.getElementById('act-start-' + actionId); const cur = _af.actions.find(a => a.id === actionId) || {}; const sp = {selector_type: 'xpath', selector_value: el ? el.value.trim() : '', what: ''}; const r = await apiPost('/api/custom_actions/' + actionId, {app_id: cur.app_id || '', start_page: sp}); showToast((r && r.ok) ? '初始页面已保存' : ((r && r.error) || '保存失败'), (r && r.ok) ? 'success' : 'error'); await afRefreshAll(); } // 测一下这个定位对不对(复用现有 /api/steps/test,用选中的第一台在线设备) async function afTestSel(inputId) { const el = document.getElementById(inputId); const sel = el ? el.value.trim() : ''; if (!sel) { showToast('先填选择器', 'error'); return; } const picked = Object.keys(_af.selDevices).filter(k => _af.selDevices[k]); const dev = picked[0] || (_af.devices.filter(d => d.online && !d.busy)[0] || {}).serial; if (!dev) { showToast('没有可用设备(先在「设备」页确认有一台在线的)', 'error'); return; } showToast('在 ' + dev + ' 上试…'); const r = await apiPost('/api/steps/test', {serial: dev, step: {type: 'wait_el', params: {selector_type: 'xpath', selector_value: sel, timeout: 6}}}); if (!r || !r.ok) { showToast((r && r.error) || '测试失败', 'error'); return; } showToast('选择器:' + (r.result || '') + (r.msg ? ' — ' + r.msg : ''), r.result === '命中' ? 'success' : 'error'); } // ④ 运行与日志 // ========== ③ 计划调度:切号参数 + 临时跑一轮(2026-10-17 收口) ========== // 这两块以前在「设备与账号」栏里,现在按用户的结构并进计划调度(跑的时候怎么切号、临时跑)。 function afPlanSwitchBar() { const sw = ((_af.profile || {}).params || {}).fleet || {}; const s = sw.switch || {}; return '
    ' + '切号 / 发布前准备参数 ' + '(所有计划共用;切号本身用的是「发布前准备」里的内置「切账号」)' + '
    ' + '切完等 秒' + '重试 次' + '停在登录页 ' + '' + '' + '
    '; } async function afSaveSwitchParams() { const p = _af.profile && _af.profile.params; if (!p) return; p.fleet = p.fleet || {}; p.fleet.switch = p.fleet.switch || {}; p.fleet.switch.wait_after = parseFloat(document.getElementById('af-sw-wait').value || '15'); p.fleet.switch.retries = parseInt(document.getElementById('af-sw-retry').value || '2', 10); p.fleet.switch.on_login = document.getElementById('af-sw-login').value; const r = await apiPost('/api/af/profile', {name: _af.profile.name, params: p}); if (!r || !r.ok) { showToast((r && r.error) || '保存失败', 'error'); return; } showToast('已保存(下次跑生效)', 'success'); } // 临时跑一轮:选账号 + 动作组 → 立刻跑(不走计划、不建记录之外的任何东西) function afOpenQuickRun() { const acts = (_af.actions || []).filter(function (a) { return (a.kind || '') === '' && a.app_id; }); const accs = (_af.roster || []).slice(); const ov = document.createElement('div'); ov.id = 'af-quick-overlay'; ov.className = 'modal-overlay show'; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); } async function afDoQuickRun() { const act = document.getElementById('af-q-act').value; const accs = Array.from(document.querySelectorAll('.af-q-acc')).filter(function (c) { return c.checked; }) .map(function (c) { return c.value; }); const log = document.getElementById('af-q-log'); if (!act) { showToast('先选动作组', 'error'); return; } if (!accs.length) { showToast('至少勾一个账号', 'error'); return; } const btn = document.getElementById('af-q-btn'); btn.disabled = true; log.textContent = '⏳ 正在下发到 ' + accs.length + ' 个账号…'; const r = await apiPost('/api/af/run', {accounts: accs, action_id: act}); btn.disabled = false; if (!r || !r.ok) { log.textContent = '❌ ' + ((r && r.error) || '触发失败'); return; } log.textContent = '✅ ' + (r.msg || '已触发') + '(去「④ 运行监测」看结果)'; showToast('已触发', 'success'); await afRefreshAll(); } // ================== ④ 计划调度 ================== // 一条计划 = "接下来这段时间,让电脑完成我这一批次的任务": // 干什么(App + 动作组)· 给谁干(账号库手选)· 发什么(每人 N 条)· // 什么时候(固定点 + 抖动)· 怎么跑(并发/重试/跳过)+ 发布前准备(自动检测 + 需要才切号) // 触发时**现算**"这些号在哪台手机上"(账号换机/换 IP 也跟得上),只激活对应的那几台。 function afHtmlPlan() { const plans = _af.plans || []; const rows = plans.map(function (p) { const segs = Array.isArray(p.segments) ? p.segments : []; const firstSeg = segs[0] || {}; const act = (_af.actions || []).find(function (a) { return a.id === p.action_id; }) || {}; let appId = firstSeg.app_id || p.app_id; if (!appId && firstSeg.source === 'task') { const tj = (_af.jobs || []).find(function (x) { return x.id === firstSeg.task_id; }); appId = _afPlanTaskAppId(tj); } const app = (_af.apps || []).find(function (a) { return a.id === appId; }) || {}; const sched = p.schedule || {}; const pts = (sched.points || []).join('、') || '(没填时间:只能手动跑)'; const jit = sched.jitter_sec ? (' ±' + Math.round(sched.jitter_sec / 60) + ' 分钟') : ''; const accs = p.accounts || []; const mat = p.material || {}; const readyOn = !(p.ready && p.ready.enabled === false); const flow = (readyOn ? '内置切号 → ' : '⚠无切号 → ') + (segs.length ? segs.map(function (s, i) { return (i + 1) + '. ' + (s.source === 'task' ? '任务·' : '') + (s.name || '?'); }).join(' → ') : (act.name || '(没选动作组)')); const pubs = segs.filter(function (s) { return s.publish; }); const n = pubs.length ? ('发布段 ' + pubs.length + ' · 每号 ' + (pubs[0].per_account || 0) + ' 条') : (segs.length ? '只跑动作' : ((mat.mode === 'pick' && (mat.ids || []).length) ? ('指定 ' + mat.ids.length + ' 条') : ((mat.per_account === 0 || mat.per_account === undefined) ? '当天待发全发' : ('每人 ' + mat.per_account + ' 条')))); const last = p.last_run; return '' + '' + esc(p.name) + '' + (p.enabled ? ' 启用' : ' 停用') + (p.note ? '
    ' + esc(p.note) + '
    ' : '') + '' + '' + esc(app.name || '(没选 App)') + '
    ' + esc(flow) + (segs.length ? (' (' + segs.length + ' 段)') : '') + '
    ' + '' + accs.length + ' 个号
    ' + esc(accs.slice(0, 3).join('、')) + (accs.length > 3 ? '…' : '') + '
    ' + '' + n + '' + '' + pts + jit + (p.next_run ? '
    下次 ' + esc(p.next_run) + '
    ' : '') + '' + '' + (p.prep_check ? '发布前准备 ✓' : '发布前准备 ✗') + '
    重试 ' + ((p.retry || {}).max_attempts || 1) + ' 次后跳过' + (p.max_parallel ? (' 并发 ' + p.max_parallel) : '') + '
    ' + '' + (last ? (esc((last.started_at || '').slice(5, 16)) + ' ' + _afPlanStatus(last.status) + '
    ' + last.ok_accounts + '✓ ' + last.failed_accounts + '✗ ' + last.skipped_accounts + '跳过
    ') : '还没跑过') + '' + '' + ' ' + ' ' + ' ' + ' ' + ' ' + '' + ''; }).join(''); const runs = (_af.planRuns || []).map(function (r) { const t = (r.trigger === 'cron' ? '到点' : r.trigger === 'try' ? '试跑' : '手动'); return '' + esc((r.started_at || '').slice(5, 16)) + '' + '' + esc(r.plan_name) + ' ' + t + '' + '' + _afPlanStatus(r.status) + '' + '' + r.ok_accounts + ' ✓ / ' + r.failed_accounts + ' ✗ / ' + r.skipped_accounts + ' 跳过' + '' + esc((r.devices || []).length) + ' 台' + ''; }).join(''); return afPlanSwitchBar() + '' + '
    ' + '' + '' + '一条计划 = 干什么(App + 动作组)· 给谁干(账号库里勾号)· ' + '发什么(每人几条)· 什么时候(固定点 + 抖动)· 怎么跑(并发/重试/失败处置);' + '到点或点一下就跑,只激活这些号所在的手机。' + '
    ' + '' + '' + '' + '' + '' + '' + (rows || '') + '
    计划干什么给谁干发什么什么时候怎么跑上次操作
    还没有计划 —— 点「+ 新建计划」:' + '选个动作组、勾几个号、定个时间,到点它自己跑
    ' + '
    ' + '最近的计划运行 每次触发的成功/失败/跳过 —— 点「明细」看每个号跑了什么' + '' + '' + '' + '' + (runs || '') + '
    时间计划结果账号设备
    还没有运行记录
    ' + '
    ' + '
    '; } function _afPlanStatus(s) { const m = {done: '全部完成', partial: '部分完成', failed: '失败', running: '运行中', skipped: '跳过', unknown: '未知'}; return m[s] || ('' + esc(s || '') + ''); } // ---- 新建/编辑计划(一页向导)---- // 用户 2026-10-17 重定:**上面是时间和状态**;账号勾选里标「未发 N 条」; // 动作不再是一个动作组,而是**账号下面的编排列表**(多段按顺序跑,可循环/条件/回主页)。 let _afPlanSegs = []; let _afPlanReady = {}; function _afPlanSegDefault() { return {source: 'action', action_id: '', task_id: '', name: '', app_id: '', publish: false, per_account: 1, loop: {mode: 'none', rounds: 3, seconds: 60}, home_before: 'none', home_after: 'none', when: {mode: 'none', selector_type: 'xpath', selector_value: '', what: ''}}; } // ========== 内置「账号就绪(切号)」:可见 + 可编辑 ========== // 它不是动作库里的条目,而是计划执行每个账号前的内置步骤;页面把它显示在编排列表上方, // 参数存在 plan.ready(空 = 用 /api/af/ready_defaults 的全局默认)。 function afPlanReadyInit(saved) { const d = _af.readyDefaults || {}; const s = saved || {}; _afPlanReady = Object.assign({}, d, s); _afPlanReady.enabled = (s.enabled === undefined) ? true : !!s.enabled; // 只保留可编辑字段,避免把 probability/target 等内部字段带进保存体 ['switch_selector_type', 'switch_selector_value', 'me_selector_type', 'me_selector_value', 'name_selector_type', 'name_selector_value', 'timeout', 'wait_after', 'max_attempts', 'on_login_page', 'on_fail'].forEach(function (k) { if (_afPlanReady[k] === undefined && d[k] !== undefined) _afPlanReady[k] = d[k]; }); } function afPlanReadySet(k, v) { if (!_afPlanReady) _afPlanReady = {}; _afPlanReady[k] = v; afPlanReadyRender(); } function afPlanReadyRender() { const box = document.getElementById('afp-ready'); if (!box) return; const r = _afPlanReady || {}; const en = r.enabled !== false; const short = function (v) { v = v || ''; return v.length > 44 ? (v.slice(0, 44) + '…') : (v || '(默认)'); }; box.innerHTML = '
    ' + '
    ' + '🔒 内置 · 账号就绪(切号)' + '' + '' + '每个账号在编排之前自动执行;切不过来默认跳过这个号' + '
    ' + (en ? ('
    ' + '点「我」(' + esc(r.me_selector_type || 'xpath') + ': ' + esc(short(r.me_selector_value)) + ')' + ' → 读名字 → 一样跳过 / 不一样才切;切后等 ' + (r.wait_after === undefined ? 15 : r.wait_after) + ' 秒,重试 ' + (r.max_attempts || 2) + ' 次;切不过去:' + (r.on_fail === 'stop' ? '停本设备' : '跳过这个号') + '
    ') : '
    ' + '已关闭内置切号 —— 请在下面的编排里放一个切号动作组,否则可能发到错误的号
    ') + '
    '; } function _afReadySelOpts(cur, withAll) { const types = withAll ? [['', '(不填)'], ['xpath', 'xpath'], ['text', 'text'], ['textContains', 'textContains'], ['description', 'description'], ['descriptionContains', 'descriptionContains'], ['resourceId', 'resourceId']] : [['xpath', 'xpath'], ['text', 'text'], ['textContains', 'textContains'], ['description', 'description'], ['descriptionContains', 'descriptionContains'], ['resourceId', 'resourceId']]; return types.map(function (t) { return ''; }).join(''); } function afOpenReadyEditor() { const r = _afPlanReady || {}; const old = document.getElementById('af-ready-overlay'); if (old) old.remove(); const ov = document.createElement('div'); ov.id = 'af-ready-overlay'; ov.className = 'modal-overlay show'; ov.style.zIndex = 1200; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); } function afSaveReadyEditor() { const g = function (id) { const e = document.getElementById(id); return e ? e.value : ''; }; const c = function (id) { const e = document.getElementById(id); return !!(e && e.checked); }; _afPlanReady = { enabled: c('afr-enabled'), switch_selector_type: g('afr-sw-type'), switch_selector_value: g('afr-sw-val'), me_selector_type: g('afr-me-type'), me_selector_value: g('afr-me-val'), name_selector_type: g('afr-name-type'), name_selector_value: g('afr-name-val'), timeout: parseInt(g('afr-timeout') || '8', 10) || 8, wait_after: parseInt(g('afr-wait') || '15', 10) || 0, max_attempts: parseInt(g('afr-attempts') || '2', 10) || 2, on_login_page: g('afr-login') || 'stop', on_fail: g('afr-fail') || 'skip_account' }; const ov = document.getElementById('af-ready-overlay'); if (ov) ov.remove(); afPlanReadyRender(); } function _afPlanAppName(appId) { const a = (_af.apps || []).find(function (x) { return x.id === appId; }); return a ? a.name : ''; } // 任务段:从任务步骤里的 open_app/stop_app 包名反查 App(用于列表显示与主 App) function _afPlanTaskPkg(t) { let pkg = ''; const walk = function (arr) { if (pkg || !Array.isArray(arr)) return; for (let k = 0; k < arr.length; k++) { const p = (arr[k] || {}).params || {}; if (p.package) { pkg = p.package; return; } ['children', 'then', 'else'].forEach(function (key) { if (Array.isArray(p[key])) walk(p[key]); }); if (pkg) return; } }; walk((((t || {}).params) || {}).steps || []); return pkg; } function _afPlanTaskAppId(t) { const pkg = _afPlanTaskPkg(t); const a = (_af.apps || []).find(function (x) { return x.package === pkg; }); if (a) return a.id; // 通用任务没有 open_app(如「抖音创作者中心」直接在「我」页操作)→ 反查不到包名; // 只登记了一个 App 时直接用它(开场要冷启动 App),多个 App 时不猜。 return ((_af.apps || []).length === 1) ? _af.apps[0].id : ''; } function _afPlanTaskAppName(t) { return _afPlanAppName(_afPlanTaskAppId(t)); } function _afPlanSel(value, label, current) { return ''; } function afPlanSegsRender() { const box = document.getElementById('afp-segs'); if (!box) return; if (!_afPlanSegs.length) _afPlanSegs.push(_afPlanSegDefault()); box.innerHTML = _afPlanSegs.map(function (s, i) { return afPlanSegRow(s, i); }).join(''); } function afPlanSegRow(s, i) { const acts = (_af.actions || []).filter(function (a) { const k = a.kind || ''; return k !== 'opening' && k !== 'builtin'; }); const curVal = s.source === 'task' ? ('t:' + (s.task_id || '')) : ('a:' + (s.action_id || '')); const actOpts = acts.map(function (a) { const an = _afPlanAppName(a.app_id) || '未归属App'; const v = 'a:' + a.id; return ''; }).join(''); const taskOpts = (_af.jobs || []).map(function (t) { const an = _afPlanTaskAppName(t); const v = 't:' + t.id; return ''; }).join(''); const lm = (s.loop || {}).mode || 'none'; const loopNum = lm === 'time' ? (s.loop.seconds || 60) : (s.loop.rounds || 3); const wm = (s.when || {}).mode || 'none'; const homeOpts = function (cur) { return _afPlanSel('none', '不处理', cur) + _afPlanSel('click', '点「首页」', cur) + _afPlanSel('cold', '冷启动', cur); }; return '
    ' + '
    ' + '#' + (i + 1) + '' + '' + '' + (s.publish ? ('每号 条(0=全部)') : '') + (s.source === 'task' ? '任务只做发布动作;推送/标记由计划补(任务里已有就不重复)' : '') + '' + '' + '' + '' + '' + ' ' + ' ' + '' + '' + '
    ' + (wm === 'none' ? '' : '
    ' + '元素 ' + '' + '' + '
    ') + '
    '; } function afPlanSegSet(i, path, value) { const s = _afPlanSegs[i]; if (!s) return; const parts = path.split('.'); let o = s; for (let k = 0; k < parts.length - 1; k++) { o = o[parts[k]] = o[parts[k]] || {}; } let v = value; if (path === 'publish') v = !!value; else if (path === 'per_account' || path === 'loop.rounds' || path === 'loop.seconds') { v = parseInt(value || '0', 10) || 0; } o[parts[parts.length - 1]] = v; if (path === 'publish' || path === 'loop.mode' || path === 'when.mode' || path === 'action_id') { afPlanSegsRender(); } } // 下拉:`a:<动作id>` = 引用动作组;`t:<任务id>` = 只取任务步骤 function afPlanSegPick(i, val) { const s = _afPlanSegs[i]; if (!s) return; if (!val) { s.source = 'action'; s.action_id = ''; s.task_id = ''; s.name = ''; s.app_id = ''; afPlanSegsRender(); return; } const kind = val.slice(0, 1), id = val.slice(2); if (kind === 't') { const t = (_af.jobs || []).find(function (x) { return x.id === id; }) || {}; s.source = 'task'; s.task_id = id; s.action_id = ''; s.name = t.name || ''; s.app_id = _afPlanTaskAppId(t); // 保留原来的「发布素材」勾选(用户可在行内自己勾;任务里已有推送/标记时计划不会重复补) } else { const a = (_af.actions || []).find(function (x) { return x.id === id; }) || {}; s.source = 'action'; s.action_id = id; s.task_id = ''; s.name = a.name || ''; s.app_id = a.app_id || ''; } afPlanSegsRender(); } function afPlanSegAction(i, aid) { const s = _afPlanSegs[i]; if (!s) return; const a = (_af.actions || []).find(function (x) { return x.id === aid; }) || {}; s.action_id = aid || ''; s.name = a.name || ''; s.app_id = a.app_id || ''; afPlanSegsRender(); } function afPlanSegAdd() { _afPlanSegs.push(_afPlanSegDefault()); afPlanSegsRender(); } function afPlanSegDel(i) { if (_afPlanSegs.length <= 1) { showToast('至少留一段动作组', 'error'); return; } _afPlanSegs.splice(i, 1); afPlanSegsRender(); } function afPlanSegMove(i, delta) { const j = i + delta; if (j < 0 || j >= _afPlanSegs.length) return; const t = _afPlanSegs[i]; _afPlanSegs[i] = _afPlanSegs[j]; _afPlanSegs[j] = t; afPlanSegsRender(); } function afOpenPlan(planId) { const p = planId ? ((_af.plans || []).find(function (x) { return x.id === planId; }) || {}) : {}; const S = p.schedule || {}, M = p.material || {}, R = p.retry || {}; const acts = (_af.actions || []).filter(function (a) { const k = a.kind || ''; return k !== 'opening' && k !== 'builtin'; }); // 动作编排:老计划(只有 action_id)自动合成一段,编辑保存后迁成新结构 const raw = Array.isArray(p.segments) ? p.segments : []; if (raw.length) { _afPlanSegs = raw.map(function (s) { const base = _afPlanSegDefault(); const one = Object.assign({}, base, s || {}); one.source = (s && s.source) || ((s && s.task_id) ? 'task' : 'action'); one.loop = Object.assign({}, base.loop, (s && s.loop) || {}); one.when = Object.assign({}, base.when, (s && s.when) || {}); return one; }); } else if (p.action_id) { const a = acts.find(function (x) { return x.id === p.action_id; }) || {}; const one = _afPlanSegDefault(); one.source = 'action'; one.action_id = p.action_id; one.name = a.name || ''; one.app_id = a.app_id || p.app_id || ''; one.publish = true; one.per_account = (M.per_account === undefined ? 1 : M.per_account); _afPlanSegs = [one]; } else { _afPlanSegs = [_afPlanSegDefault()]; } afPlanReadyInit(p.ready || {}); const chosen = {}; (p.account_ids || []).forEach(function (i) { chosen[i] = true; }); const pendingByName = {}; (_af.accounts || []).forEach(function (a) { pendingByName[a.name] = a.pending || 0; }); // 账号勾选:按设备分组,每个号后面标「未发 N 条」,有货的排前面 const groups = _af.rosterGroups || {}; const accBox = Object.keys(groups).sort().map(function (dev) { const one = (groups[dev] || [])[0] || {}; const state = one.pooled ? (one.online ? '在线' : '离线') : '未入池'; const rows = (groups[dev] || []).slice().sort(function (a, b) { return (pendingByName[b.nickname] || 0) - (pendingByName[a.nickname] || 0); }); return '
    ' + esc(dev) + ' ' + state + ' ' + rows.map(function (r) { const n = pendingByName[r.nickname] || 0; return ''; }).join('') + '
    '; }).join(''); const ov = document.createElement('div'); ov.id = 'af-plan-overlay'; ov.className = 'modal-overlay show'; ov.onclick = function (e) { if (e.target === ov) ov.remove(); }; ov.innerHTML = ''; document.body.appendChild(ov); afPlanReadyRender(); afPlanSegsRender(); if (((p.material || {}).ids || []).length) afPlanPickLoad(); } // 计划的"勾具体几条":列出**已勾账号**的未发布素材(勾选后只发这些) function afPlanMatMode() { const mode = (document.querySelector('input[name="afp-matmode"]:checked') || {}).value || 'pool'; const box = document.getElementById('afp-pick'); if (!box) return; box.style.display = (mode === 'pick') ? 'block' : 'none'; if (mode === 'pick') afPlanPickLoad(); } async function afPlanPickLoad() { const box = document.getElementById('afp-pick'); if (!box) return; const names = Array.from(document.querySelectorAll('#af-plan-overlay .af-plan-acc')) .filter(function (c) { return c.checked; }).map(function (c) { return c.dataset.name; }); const keep = Array.from(box.querySelectorAll('.afp-item')).filter(function (c) { return c.checked; }) .map(function (c) { return c.value; }); box.innerHTML = '⏳ 读取素材…'; if (!_af.allItems || !_af.allItems.length) { const r = await apiGet('/api/af/items?limit=2000'); if (r && r.ok) _af.allItems = r.items || []; } const items = (_af.allItems || []).filter(function (x) { return names.indexOf(x.nickname) >= 0 && (x.status === 'ready' || x.status === 'failed'); }); if (!items.length) { box.innerHTML = '这些账号没有未发布的素材(先去资产管理上传/标未发布)'; return; } box.innerHTML = items.map(function (x) { const on = keep.indexOf(x.id) >= 0 ? ' checked' : ''; return ''; }).join(''); } function afPlanAllAcc(on) { document.querySelectorAll('#af-plan-overlay .af-plan-acc').forEach(function (c) { c.checked = !!on; }); const pick = document.getElementById('afp-pick'); if (pick && pick.style.display !== 'none') afPlanPickLoad(); } async function afSavePlan(planId) { const box = document.getElementById('af-plan-overlay'); const ids = [], names = []; document.querySelectorAll('#af-plan-overlay .af-plan-acc').forEach(function (c) { if (c.checked) { ids.push(c.value); names.push(c.dataset.name); } }); const pts = (document.getElementById('afp-points').value || '') .split(/[,,\s]+/).map(function (s) { return s.trim(); }).filter(Boolean); // 动作编排:按顺序存,后端白名单化 const segs = (_afPlanSegs || []).filter(function (s) { return s.source === 'task' ? !!s.task_id : !!s.action_id; }) .map(function (s) { return {source: s.source === 'task' ? 'task' : 'action', action_id: s.source === 'task' ? '' : s.action_id, task_id: s.source === 'task' ? s.task_id : '', app_id: s.app_id || '', name: s.name || '', publish: !!s.publish, per_account: parseInt(s.per_account || '0', 10) || 0, loop: {mode: (s.loop || {}).mode || 'none', rounds: parseInt((s.loop || {}).rounds || '1', 10) || 1, seconds: parseInt((s.loop || {}).seconds || '60', 10) || 60}, home_before: s.home_before || 'none', home_after: s.home_after || 'none', when: {mode: (s.when || {}).mode || 'none', selector_type: (s.when || {}).selector_type || 'xpath', selector_value: (s.when || {}).selector_value || '', what: (s.when || {}).what || ''}}; }); if (!segs.length) { showToast('动作编排里至少选一个动作组', 'error'); return; } const hasPublish = segs.some(function (s) { return s.publish || s.source === 'task'; }); if (!hasPublish && !confirm('没有任何一段标了「发布素材」——这条计划只跑动作,不发素材。继续保存?')) { return; } const first = segs[0]; const body = { name: document.getElementById('afp-name').value.trim(), app_id: first.app_id || '', action_id: first.action_id, segments: segs, ready: _afPlanReady || {}, account_ids: ids, accounts: names, material: (function () { const mode = (document.querySelector('input[name="afp-matmode"]:checked') || {}).value || 'pool'; const ids = (mode === 'pick') ? Array.from(document.querySelectorAll('#afp-pick .afp-item')).filter(function (c) { return c.checked; }) .map(function (c) { return c.value; }) : []; const pub = segs.filter(function (s) { return s.publish; })[0] || {}; return {per_account: parseInt(pub.per_account || '0', 10) || 0, mode: mode, ids: ids}; })(), schedule: {points: pts, jitter_sec: (parseInt(document.getElementById('afp-jitter').value || '0', 10) || 0) * 60, date_from: document.getElementById('afp-dfrom').value, date_to: document.getElementById('afp-dto').value}, retry: {max_attempts: parseInt(document.getElementById('afp-retry').value || '1', 10), delay: parseInt(document.getElementById('afp-delay').value || '60', 10)}, max_parallel: parseInt(document.getElementById('afp-par').value || '0', 10), prep_check: document.getElementById('afp-prep').checked, enabled: document.getElementById('afp-on').checked, note: document.getElementById('afp-note').value }; if (!body.name) { showToast('计划名不能为空', 'error'); return; } if (!ids.length) { showToast('至少勾一个账号', 'error'); return; } const r = planId ? await apiPut('/api/af/plan/' + encodeURIComponent(planId), body) : await apiPost('/api/af/plans', body); if (!r || !r.ok) { showToast((r && r.error) || '保存失败', 'error'); return; } if (r.warning) showToast('已保存,但:' + r.warning, 'error'); else showToast('计划已保存' + (body.enabled ? '(已启用)' : ''), 'success'); if (box) box.remove(); await afRefreshAll(); } async function afPlanToggle(id, enabled) { const r = await apiPost('/api/af/plan/' + encodeURIComponent(id) + '/toggle', {enabled: !!enabled}); if (!r || !r.ok) { showToast((r && r.error) || '操作失败', 'error'); return; } showToast(r.msg || '已更新', 'success'); await afRefreshAll(); } async function afPlanDelete(id, name) { if (!confirm('删掉计划「' + name + '」?\n(只删这条计划;已经跑过的运行记录会留着)')) return; const r = await apiDelete('/api/af/plan/' + encodeURIComponent(id)); if (!r || !r.ok) { showToast((r && r.error) || '删除失败', 'error'); return; } showToast('计划已删除', 'success'); await afRefreshAll(); } // 只算不跑:会激活哪几台手机、哪些号跑不了(走的是**触发时同一段逻辑**) async function afPlanPreview(id) { const el = document.getElementById('af-plan-preview') || document.getElementById('afp-warn'); const r = await apiPost('/api/af/plan/' + encodeURIComponent(id) + '/preview', {}); if (!r || !r.ok) { showToast((r && r.error) || '预览失败', 'error'); return; } const devs = r.devices || [], skip = r.skipped || []; let html = '现在跑的话会激活 ' + devs.length + ' 台手机 / ' + devs.reduce(function (a, d) { return a + d.accounts.length; }, 0) + ' 个号' + (r.warning ? (' (配置提醒:' + esc(r.warning) + ')') : '') + '
    ' + devs.map(function (d) { return ' ✓ ' + esc(d.device_name || d.serial) + ' ' + esc(d.serial) + ' → ' + esc(d.accounts.join('、')); }).join('
    ') + (skip.length ? ('
    跑不了的 ' + skip.length + ' 个:
    ' + skip.map(function (s) { return ' ✗ ' + esc(s.account) + ':' + esc(s.reason); }).join('
    ')) : ''); if (el) { el.innerHTML = html; el.style.display = ''; el.style.color = ''; if (el.id === 'af-plan-preview') { afSub('plan'); el.scrollIntoView({block: 'nearest'}); } } else { showToast('预览见页面顶部', 'success'); } } // 立即跑(整批)/ 试跑(只挑一个号) async function afPlanRun(id) { const p = (_af.plans || []).find(function (x) { return x.id === id; }) || {}; if (!confirm('现在就跑「' + (p.name || '') + '」?\n只激活这些号所在的手机;正在跑别的任务的设备会自动跳过。')) return; const r = await apiPost('/api/af/plan/' + encodeURIComponent(id) + '/run', {}); if (!r || !r.ok) { showToast((r && r.error) || '触发失败', 'error'); return; } showToast(r.msg || '已触发', 'success'); afSub('plan'); await afRefreshAll(); _afPlanPoll(r.plan_run_id); } async function afPlanTry(id) { const p = (_af.plans || []).find(function (x) { return x.id === id; }) || {}; const opts = (p.accounts || []).map(function (n) { return ''; }).join(''); const acc = prompt('试跑哪个号?(只跑这一个号,验证整条链)\n可选:' + (p.accounts || []).join('、'), (p.accounts || [])[0] || ''); if (!acc) return; const r = await apiPost('/api/af/plan/' + encodeURIComponent(id) + '/run', {accounts: [acc]}); if (!r || !r.ok) { showToast((r && r.error) || '试跑失败', 'error'); return; } showToast('已在 ' + ((r.devices || []).map(function (d) { return d.device_name; }).join('、') || '?') + ' 上试跑「' + acc + '」', 'success'); afSub('plan'); await afRefreshAll(); _afPlanPoll(r.plan_run_id); } // 跑完自动刷几次(每一步都有等待,给它几次机会) function _afPlanPoll(runId) { let n = 0; const t = setInterval(function () { n += 1; afRefreshAll(); if (runId) afShowPlanRun(runId); if (n >= 8) clearInterval(t); }, 15000); } async function afShowPlanRun(runId, boxId) { const box = document.getElementById(boxId || 'af-plan-run-detail'); if (!box) return; const r = await apiGet('/api/af/plan_run/' + encodeURIComponent(runId)); if (!r || !r.ok) return; const d = r.run || {}; box.innerHTML = '
    ' + '' + esc(d.plan_name || '') + ' · ' + esc(d.started_at || '') + ' → ' + esc(d.finished_at || '(跑着)') + ' · ' + _afPlanStatus(d.status) + '' + '' + '' + (d.detail || []).map(function (x) { return '' + '' + '' + ''; }).join('') + '
    账号设备结果说明 / 明细
    ' + esc(x.account) + '' + esc(x.device_name || '') + '
    ' + esc(x.serial || '') + '
    ' + _afPlanStatus(x.status === 'done' ? 'done' : x.status) + '' + esc(x.reason || '') + (x.ae_run_id ? (' ') : '') + '
    '; } // ================== ④ 运行监测(计划 / 账号 / 设备 三个维度)================== // 用户 2026-10-17:"所有计划任务,实际执行的情况汇报;发布成功以后,前面的素材要重新标记更新"。 // 素材状态由引擎自己回写(mark_release),这里只负责**把结果摆出来**。 // 设备画面**点开才取**(adb screencap,不抢 uiautomator),不做自动轮询。 function afRunBadge(s) { const m = {done: '完成', failed: '失败', running: '运行中', skipped: '跳过', unknown: '未知'}; return m[s] || ('' + esc(s || '') + ''); } // 一次 ae_run = **一台设备**的一轮运行;同一台设备串行跑多个号时,`account` 是 // "号A、号B" 拼起来的。展示时必须拆开,否则会误以为"两个号被合并成一条记录"。 function _afRunAccountList(r) { return String((r && r.account) || '').split(/[、,,]/) .map(function (s) { return s.trim(); }).filter(Boolean); } function afHtmlRun() { // 账号维度:每个账号只显示最近一轮(_af.runs 已按时间倒序); // 同一台设备的一轮里有多个号 → 拆成多行(明细仍是同一份设备步骤) const latest = {}, acctOrder = []; (_af.runs || []).forEach(function (r) { _afRunAccountList(r).forEach(function (a) { if (latest[a]) return; latest[a] = Object.assign({}, r, {account: a}); acctOrder.push(a); }); }); const acctRows = acctOrder.map(function (a) { const r = latest[a], t = r.totals || {}; return '' + esc(a) + '' + '' + esc(r.device_name || r.serial || '') + '' + '' + afRunBadge(r.status) + '' + '' + esc(r.started_at || '') + '' + '发 ' + (t.published || 0) + ' / 共 ' + (t.items_total || 0) + ((t.failed ? ' / 失败 ' + t.failed : '') + (t.unknown ? ' / 未知 ' + t.unknown : '')) + '' + ''; }).join(''); // 计划维度:每次计划触发 const planRows = (_af.planRuns || []).slice(0, 20).map(function (r) { return '' + esc((r.started_at || '').slice(5, 16)) + '' + '' + esc(r.plan_name) + '' + '' + (r.trigger === 'cron' ? '到点' : r.trigger === 'try' ? '试跑' : '手动') + '' + '' + _afPlanStatus(r.status) + '' + '' + (r.ok_accounts || 0) + ' ✓ / ' + (r.failed_accounts || 0) + ' ✗ / ' + (r.skipped_accounts || 0) + ' 跳过' + '' + ((r.devices || []).length) + ' 台' + ''; }).join(''); // 全部运行记录:一次 ae_run 拆成"每账号一行"(同一设备的一轮 → 多行,共用同一份步骤明细) const runRows = []; (_af.runs || []).forEach(function (r) { const accs = _afRunAccountList(r); (accs.length ? accs : ['']).forEach(function (a) { runRows.push('' + '' + esc(r.started_at) + '' + '' + esc(a) + '' + '' + esc(r.device_name || r.serial || '') + '' + '' + esc(_AF_STATUS[r.status] || r.status) + '' + '' + ((r.totals && r.totals.published) || 0) + '/' + ((r.totals && r.totals.items_total) || 0) + '' + '' + esc((r.summary && r.summary[0] && r.summary[0].share_url) || '') + '' + '' + '' + ''); }); }); const runRowsHtml = runRows.join(''); setTimeout(afMonLoadDevices, 0); return '' + '
    ' + '' + '计划维度=每次触发;账号维度=每个号最近一轮;' + '设备维度=每台现在在干什么(「看画面」点了才取,运行中也安全)
    ' + '
    ' + '📋 计划维度' + '' + '' + '' + '' + (planRows || '') + '
    时间计划触发结果账号设备
    还没有计划运行记录
    ' + '
    ' + '👤 账号维度 每个账号最近一轮;' + '同一台设备串行跑多个号时按账号拆开显示(素材数是该设备这一轮的合计)' + '' + '' + '' + (acctRows || '') + '
    账号设备结果时间素材
    还没有账号运行记录
    ' + '
    ' + '📱 设备维度 ' + '当前在跑什么;画面用 adb 截图,按需取' + '
    加载设备状态…
    ' + '
    ' + '
    ' + '📜 全部运行记录 ' + '同一台设备跑多个号会按账号拆成多行(「明细」是同一份设备步骤);' + '日志写到各自的账号文件夹 _日志/<日期>/' + '' + '' + '' + (runRowsHtml || '') + '
    时间账号设备结果已发/条目分享链接
    还没有运行记录
    ' + '
    ' + '
    '; } async function afMonLoadDevices() { const box = document.getElementById('af-mon-dev'); if (!box) return; const st = await apiGet('/api/status'); if (!st || !st.ok) { box.innerHTML = '
    设备状态加载失败:' + esc((st && st.error) || '') + '
    '; return; } const rows = (st.devices || []).map(function (d) { const busy = d.worker_status === 'running' || d.worker_status === 'connecting'; const pg = d.progress || {}; const pgTxt = pg.total ? (' · ' + (pg.done || 0) + '/' + pg.total + ' ' + (pg.unit || '')) : ''; return '' + '' + esc(d.device_name || d.serial) + '' + '
    ' + esc(d.serial) + '
    ' + '' + (d.present ? (d.worker_status === 'running' ? '运行中' : d.worker_status === 'connecting' ? '连接中' : '空闲') : '不在线') + '' + '' + esc(d.account || '—') + '' + '' + esc(d.running_job || d.task_job || '—') + (d.attempt ? (' (' + d.attempt + ')') : '') + '' + '' + esc(d.current_action || '—') + pgTxt + '' + '' + esc((d.last_error || '').slice(0, 60)) + '' + '' + '' + (busy ? '' : '') + ''; }).join(''); box.innerHTML = '' + '' + '' + '' + (rows || '') + '
    设备状态当前账号任务当前动作最近错误
    没有设备
    '; } function afMonShot(serial) { const box = document.getElementById('af-mon-shot'); if (!box) return; box.innerHTML = '
    ⏳ 正在取 ' + esc(serial) + ' 的画面…
    '; const img = new Image(); img.style.maxWidth = '100%'; img.style.borderRadius = '6px'; img.onload = function () { box.innerHTML = ''; box.appendChild(img); const cap = document.createElement('div'); cap.className = 'text-muted'; cap.style.fontSize = '12px'; cap.textContent = serial + ' · ' + new Date().toLocaleTimeString(); box.appendChild(cap); }; img.onerror = function () { box.innerHTML = '取画面失败(设备可能不在线)'; }; img.src = '/api/device/screenshot?serial=' + encodeURIComponent(serial) + '&t=' + Date.now(); } async function afMonStop(serial) { if (!confirm('停止 ' + serial + ' 上正在跑的任务?')) return; const r = await apiPost('/api/stop_device', {serial: serial}); showToast((r && (r.msg || r.error)) || '已下发停止', (r && r.ok) ? 'success' : 'error'); setTimeout(afRefreshAll, 1500); } async function afShowRun(runId) { const box = document.getElementById('af-run-detail'); box.innerHTML = '
    加载明细…
    '; const r = await apiGet('/api/af/run/' + runId); if (!r || !r.ok) { box.innerHTML = '
    ' + esc((r && r.error) || '加载失败') + '
    '; return; } const steps = (r.steps || []).map(s => ` ${esc(s.time)}${esc(s.step_path)}${esc(s.label)} ${esc(s.type)}${esc(s.result)}${esc(s.ms)} ${esc(s.detail)} `).join(''); const _accs = _afRunAccountList(r.run); const _accTxt = _accs.length > 1 ? (esc(r.run.device_name || '') + ' · ' + _accs.length + ' 个号:' + esc(_accs.join('、'))) : esc(r.run.account); box.innerHTML = `
    ${_accTxt} · ${esc(r.run.started_at)} · ${esc(_AF_STATUS[r.run.status] || r.run.status)} · ${(r.steps || []).length} 步
    ${steps || ''}
    时间路径步骤类型结果ms详情
    这一步没记录(可能没跑到)
    `; } async function afListLogs(account, date) { const box = document.getElementById('af-log-files'); box.innerHTML = '
    查日志文件…
    '; const r = await apiGet('/api/af/logs?account=' + encodeURIComponent(account) + '&date=' + encodeURIComponent(date || '')); if (!r || !r.ok) { box.innerHTML = '
    ' + esc((r && r.error) || '加载失败') + '
    '; return; } const items = (r.files || []).map(f => `
    ${esc(f.name)} ${(f.size / 1024).toFixed(1)} KB · ${esc(f.mtime)}
    `).join(''); box.innerHTML = `
    ${esc(account)} 的日志文件
    ${items || '
    还没有日志(跑一轮后就有了)
    '}`; }