Files
auto_control/static/admin/account_folder.js
T
butubb aba4583641 fix(评论): 表情保留(UTF-8 提示 + 剪贴板输入 + 严格回读)
- 导入报告新增 emoji_rows/含表情数量;页面提示 CSV 必须 UTF-8
- input_text 评论来源优先设备端剪贴板粘贴,send_keys 兜底
- 评论回读改为整段文字校验(原前缀校验会放过被丢掉的表情)
- 测试覆盖表情解析/入库/计数
2026-10-31 10:38:51 +08:00

3244 lines
188 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ================== 流水线(账号文件夹) ==================
// 四个标签:① 资产管理(账号+素材)② 动作 ③ 计划调度 ④ 运行监测
// 所有可变的参数都存 /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 = `
<div class="page-title">流水线 · 账号文件夹</div>
<div class="page-sub">
<b>① 资产管理</b>(账号 ↔ 所属手机 ↔ 素材库,支持模板批量导入)→ <b>② 动作</b> →
<b>③ 计划调度</b>(什么素材、什么时间、怎么发、发多少)→ <b>④ 运行监测</b>
(计划/账号/设备三维度;发布成功自动回写素材状态)。素材与日志都落在该账号文件夹的
<code>_日志/&lt;日期&gt;/</code>;所有设置在本页,改完即生效。
</div>
<div class="sub-tabs" style="display:flex;gap:4px;margin:6px 0 10px">
<button class="btn btn-xs" data-afsub="asset" onclick="afSub('asset')">① 资产管理</button>
<button class="btn btn-xs" data-afsub="act" onclick="afSub('act')">② 动作</button>
<button class="btn btn-xs" data-afsub="plan" onclick="afSub('plan')">③ 计划调度</button>
<button class="btn btn-xs" data-afsub="run" onclick="afSub('run')">④ 运行监测</button>
<button class="btn btn-xs" onclick="afRefreshAll(true)">刷新</button>
</div>
<div id="af-body"><div class="text-muted">加载中…</div></div>`;
}
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();
}
// 有效状态:人工标记优先,否则自动检测值(与后端 DeviceAccount.effective_status 一致)
function afEffStatus(a) {
return ((a && (a.effective_status || a.manual_status || a.account_status)) || '').trim();
}
// ---------- 单条素材上传:选一个文件 → 弹窗手填明细 → 入库 ----------
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 = '<div class="modal" style="max-width:680px">' +
'<div class="modal-header"><h3>上传素材 · ' + esc(account) + '</h3>' +
'<button class="close" onclick="document.getElementById(\'af-oneup-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="help" style="margin-bottom:8px">' +
'<b>' + esc(file.name) + '</b> · ' + kind + ' · ' +
(file.size ? (file.size / 1024 / 1024).toFixed(1) + ' MB' : '') +
' — 填好明细再入库(音频默认「仅素材·不发布」)。</div>' +
'<div class="form-row">' +
'<div class="form-group"><label>标题' +
(kind === 'audio' ? '(可空)' : '(不填 = 待文案,不会被发布)') + '</label>' +
'<input class="form-control" id="af-one-title" maxlength="100"></div>' +
'<div class="form-group"><label>时长(秒,自动读)</label>' +
'<input class="form-control" type="number" min="0" step="0.1" id="af-one-dur"></div>' +
'</div>' +
'<div class="form-group"><label>内容 / 正文</label>' +
'<textarea class="form-control" id="af-one-body" rows="3" maxlength="1000"></textarea></div>' +
'<div class="form-row">' +
'<div class="form-group"><label>话题</label>' +
'<input class="form-control" id="af-one-topics" placeholder="#苏州 #探店"></div>' +
'<div class="form-group"><label>分类</label>' +
'<input class="form-control" id="af-one-cat" placeholder="美食 / 生活 …"></div>' +
'</div>' +
'<div class="form-row">' +
'<div class="form-group"><label>展示方式</label>' +
'<input class="form-control" id="af-one-mode" list="af-one-modes" placeholder="口播 / 大字报 / 混剪 / 搬运">' +
'<datalist id="af-one-modes"><option value="口播"><option value="大字报">' +
'<option value="混剪"><option value="搬运"></datalist></div>' +
'<div class="form-group"><label>入库状态</label>' +
'<select class="form-control" id="af-one-status">' +
'<option value="">未发布(会被计划按序号取用)</option>' +
'<option value="asset">仅素材·不发布(音频/备用)</option>' +
'</select></div>' +
'</div>' +
'<div class="form-group"><label>备注</label>' +
'<input class="form-control" id="af-one-note"></div>' +
'<div id="af-one-log" class="text-muted" style="font-size:12px"></div>' +
'</div>' +
'<div class="modal-footer">' +
'<button class="btn" onclick="document.getElementById(\'af-oneup-overlay\').remove()">取消</button>' +
'<button class="btn btn-primary" id="af-one-btn" onclick="afDoSingleUpload()">上传入库</button>' +
'</div></div>';
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 = '<span style="color:#c0392b">❌ ' + esc((j && j.error) || '上传失败') + '</span>';
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 = '<span style="color:#c0392b">❌ 请求失败:' + esc(String(e)) + '</span>';
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 !afEffStatus(a); });
else if (F.status === '__abnormal') shown = shown.filter(function (a) { return afEffStatus(a).indexOf('异常') >= 0; });
else if (F.status) shown = shown.filter(function (a) { return afEffStatus(a) === 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 afEffStatus(a);
}).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 '<tr>' +
'<td><b>' + esc(a.name) + '</b>' +
(a.in_roster ? '' : ' <span class="label label-warning">账号库没有</span>') +
(a.has_dir ? '' : '<div class="text-muted" style="font-size:11px">还没有素材文件夹</div>') + '</td>' +
'<td>' + devSel + '</td>' +
'<td style="white-space:nowrap">' +
(a.account_status
? '<span class="label ' + ((a.account_status === '正常' || a.account_status === '账号正常') ? 'label-success' : 'label-warning') + '">' +
esc(a.account_status) + '</span> '
: '<span class="text-muted" style="font-size:11px">—</span> ') +
(a.in_roster
? '<button class="btn btn-xs" title="手动改账号状态" ' +
'onclick="afAssetEditStatus(\'' + esc(a.roster_id) + '\',\'' + esc(a.name) + '\',\'' +
esc(a.account_status || '') + '\')">改</button> ' +
'<button class="btn btn-xs" onclick="afAssetStatusLogs(\'' + esc(a.name) + '\')">记录</button>'
: '') +
(a.status_checked_at
? '<div class="text-muted" style="font-size:11px;margin-top:2px">检测 ' +
esc(a.status_checked_at) + '</div>' : '') +
'</td>' +
'<td>' + afManualStatusHtml(a) + '</td>' +
'<td><button class="btn btn-xs btn-primary" onclick="afAssetOpenAccount(\'' + esc(a.name) + '\')">' +
'入库 <b>' + (a.total || 0) + '</b> · 未发布 <b style="color:#b45309">' + (a.pending || 0) + '</b>' +
' · 已发布 <b style="color:#16a34a">' + (a.done || 0) + '</b>' +
((a.need_text || 0) ? ' · 缺文案 ' + a.need_text : '') +
((a.unscanned || 0) ? ' <span class="text-muted">(文件夹里还有 ' + a.unscanned + ' 个没入库)</span>' : '') +
' →</button></td>' +
'<td class="text-muted" style="font-size:12px">' + esc(a.last_published_at || '—') + '</td>' +
'<td style="white-space:nowrap">' +
'<button class="btn btn-xs" onclick="afAssetScan(\'' + esc(a.name) + '\')" title="重新扫描这个账号的文件夹">扫描</button>' +
(a.in_roster ? '<button class="btn btn-xs" onclick="afAssetEditAccount(\'' + esc(a.roster_id) + '\')">编辑</button>' : '') +
'<button class="btn btn-xs btn-primary" data-perm="devices" ' +
'onclick="afAssetPickFile(\'' + esc(a.name) + '\')" title="传一个文件,手填标题/话题等明细">上传素材</button>' +
'<button class="btn btn-xs btn-danger" data-perm="devices" ' +
'onclick="afAssetDeleteAccount(\'' + esc(a.name) + '\')" title="删除账号登记 / 归档素材文件夹">删除</button>' +
'</td></tr>';
}).join('');
return '' +
'<div class="toolbar" style="flex-wrap:wrap;align-items:center">' +
'<button class="btn btn-primary" onclick="afOpenAssetImport()" data-perm="devices">⬆ 批量上传素材(配模板)</button>' +
'<button class="btn" onclick="afOpenRoster()" data-perm="devices">导入/维护账号库</button>' +
'<button class="btn" onclick="afShowPoolApi()" data-perm="devices">🔑 账号池 API</button>' +
'<a class="btn" href="/api/af/accounts/export" data-perm="devices" title="导出账号列表 + 自动状态/人工标记/有效状态">⬇ 导出账号列表</a>' +
'<button class="btn" onclick="afRefreshAll(true)">刷新</button>' +
'<span class="text-muted" style="font-size:12px">账号表里点「入库 N」进素材库;' +
'「所属手机」改了就**重新登记**(下次按新设备激活)。' +
'「人工标记」优先于自动状态(筛选/通知/账号池 API 都按它)。</span>' +
'</div>' +
'<div class="toolbar" style="flex-wrap:wrap;align-items:center;gap:8px">' +
'<span style="font-size:12px">所属手机</span>' +
'<select class="form-control" style="width:160px" onchange="afAccFilterSet(\'device\', this.value)">' +
'<option value="">全部</option>' +
devNames.map(function (n) {
return '<option value="' + esc(n) + '"' + (F.device === n ? ' selected' : '') + '>' +
esc(n) + '</option>';
}).join('') +
'<option value="__none"' + (F.device === '__none' ? ' selected' : '') + '>未登记</option>' +
'</select>' +
'<span style="font-size:12px">账号状态</span>' +
'<select class="form-control" style="width:150px" onchange="afAccFilterSet(\'status\', this.value)">' +
'<option value="">全部</option>' +
'<option value="__abnormal"' + (F.status === '__abnormal' ? ' selected' : '') + '>只看异常</option>' +
statusNames.map(function (s) {
return '<option value="' + esc(s) + '"' + (F.status === s ? ' selected' : '') + '>' +
esc(s) + '</option>';
}).join('') +
'<option value="__none"' + (F.status === '__none' ? ' selected' : '') + '>未设置</option>' +
'</select>' +
'<input class="form-control" style="width:200px" value="' + esc(F.q) + '" ' +
'oninput="afAccFilterSet(\'q\', this.value, 1)" placeholder="搜账号昵称">' +
((F.device || F.q || F.status)
? '<button class="btn btn-xs" onclick="afAccFilterSet(\'__clear\')">清除筛选</button>' : '') +
'<span class="text-muted" style="font-size:12px">共 ' + all.length + ' 个' +
(((F.device || F.q || F.status) && shown.length !== all.length)
? ',筛出 ' + shown.length + ' 个' : '') + '</span>' +
'</div>' +
'<table class="table"><thead><tr>' +
'<th style="width:230px">账号</th><th style="width:210px">所属手机</th>' +
'<th style="width:190px">账号状态(自动)</th><th style="width:140px">人工标记</th>' +
'<th style="width:360px">素材库</th><th style="width:140px">最近发布</th><th style="width:190px">操作</th>' +
'</tr></thead><tbody>' +
(rows || '<tr><td colspan="7" class="empty">' +
((F.device || F.q || F.status) ? '没有符合筛选条件的账号 —— 点「清除筛选」看全部'
: '还没有账号 —— 先「导入/维护账号库」,再「批量上传素材」') +
'</td></tr>') +
'</tbody></table>';
}
function afDevSelectHtml(a) {
const devs = (_af.devices || []).map(function (d) { return d.name || d.serial; });
const cur = a.device_name || '';
const opts = ['<option value="">(未登记设备)</option>'].concat(
devs.map(function (n) {
return '<option value="' + esc(n) + '"' + (n === cur ? ' selected' : '') + '>' + esc(n) + '</option>';
}));
// 当前的所属设备可能不在池里(老数据)→ 也列出来,别让它显示成空白
if (cur && devs.indexOf(cur) < 0) {
opts.push('<option value="' + esc(cur) + '" selected>' + esc(cur) + '(不在设备池)</option>');
}
const state = !a.in_roster ? '<span class="text-muted" style="font-size:11px">未登记</span>'
: (a.pooled ? (a.online ? '<span style="color:#16a34a;font-size:11px">在线</span>'
: '<span style="color:#b45309;font-size:11px">离线</span>')
: '<span style="color:#dc2626;font-size:11px">设备未入池</span>');
return '<div style="display:flex;gap:6px;align-items:center">' +
'<select class="form-control" style="width:120px" ' +
(a.roster_id ? 'onchange="afAssetSetDevice(\'' + esc(a.roster_id) + '\', this.value)"'
: 'disabled title="账号库里没有这个号,先在账号库里加它"') + '>' +
opts.join('') + '</select>' + state + '</div>';
}
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;自动检测只改自动列。
var AF_MANUAL_OPTS = [
['', '未标记'],
['账号异常', '账号异常'],
['作品异常', '作品异常'],
['账号限流', '账号限流'],
['账号正常', '账号正常']
];
function afManualStatusHtml(a) {
if (!a.in_roster) return '<span class="text-muted">—</span>';
var cur = a.manual_status || '';
var opts = AF_MANUAL_OPTS.slice();
if (cur && !opts.some(function (o) { return o[0] === cur; })) opts.unshift([cur, cur]);
var bad = cur.indexOf('异常') >= 0;
var style = 'width:120px' + (bad ? ';border-color:#c0392b;color:#c0392b;font-weight:600' : '');
return '<select class="form-control" style="' + style + '" title="人工标记优先于自动状态" ' +
'onchange="afSaveManualStatus(\'' + esc(a.roster_id) + '\', this.value)">' +
opts.map(function (o) {
return '<option value="' + esc(o[0]) + '"' + (o[0] === cur ? ' selected' : '') + '>' +
esc(o[1]) + '</option>';
}).join('') + '</select>';
}
async function afSaveManualStatus(rosterId, status) {
const r = await apiPut('/api/af/roster/' + encodeURIComponent(rosterId),
{manual_status: status});
if (!r || !r.ok) {
showToast((r && r.error) || '保存人工标记失败', 'error');
await afRefreshAll();
return;
}
showToast(status ? ('人工标记:' + status) : '已清除人工标记', '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
? '<span class="label ' + (good ? 'label-success' : 'label-warning') + '">' +
esc(x.status) + '</span>'
: '<span class="text-muted">(空)</span>';
return '<tr><td style="white-space:nowrap">' + esc(x.detected_at || '') + '</td>' +
'<td>' + st + '</td><td>' + esc(x.device_name || '') + '</td>' +
'<td>' + esc(x.source || '') + '</td></tr>';
}).join('');
document.getElementById('modal-title').textContent = '账号状态记录 · ' + name;
document.getElementById('modal-body').innerHTML =
'<table class="table"><thead><tr><th>时间</th><th>状态</th><th>设备</th>' +
'<th>来源</th></tr></thead><tbody>' +
(rows || '<tr><td colspan="4" class="empty">还没有检测记录</td></tr>') +
'</tbody></table>';
document.getElementById('modal-footer').innerHTML =
'<button class="btn" onclick="closeModal()">关闭</button>';
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 '<div class="form-check" style="margin-bottom:8px">' +
'<input type="checkbox" id="' + id + '"' + (checked ? ' checked' : '') +
(disabled ? ' disabled' : '') + '> ' +
'<label for="' + id + '" style="font-weight:400">' + title + '</label>' +
(help ? '<div class="help" style="margin-left:22px">' + help + '</div>' : '') +
'</div>';
};
ov.innerHTML = '<div class="modal" style="max-width:620px">' +
'<div class="modal-header"><h3>删除账号 · ' + esc(name) + '</h3>' +
'<button class="close" onclick="document.getElementById(\'af-del-acc-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="help" style="margin-bottom:8px">' +
'平台入库 <b>' + (a.total || 0) + '</b> 条(未发布 ' + (a.pending || 0) +
' / 已发布 ' + (a.done || 0) + ');素材文件夹:<b>' + (a.has_dir ? '有' : '没有') + '</b>;' +
'所属手机:<b>' + esc(a.device_name || '未登记') + '</b><br>' +
'删除**不会动手机上已登录的账号**,只是平台不再管理它。不要在所有设备都空闲前操作。</div>' +
row('af-del-roster', '删除账号库登记(名字 ↔ 手机)', !!a.in_roster, !a.in_roster,
a.in_roster ? '' : '这个账号不在账号库里(只有素材文件夹),没有登记可删。') +
row('af-del-archive', '把素材文件夹移到 <code>_已删除/</code>', !!a.has_dir, !a.has_dir,
a.has_dir ? '**不会永久删除文件**:移动到 <code>&lt;根&gt;/_已删除/&lt;时间&gt;-&lt;账号&gt;/</code>,以后可以手动找回。' +
'不勾的话,账号仍会以“账号库没有”出现在列表里。'
: '没有素材文件夹。') +
row('af-del-records', '删除平台素材记录(' + (a.total || 0) + ' 条)', false, !(a.total > 0),
(a.total > 0) ? '只删平台库里的素材/发布记录;账号文件夹里的原始文件不受影响(如勾了上一项,会一起移到回收目录)。'
: '没有平台素材记录。') +
'</div>' +
'<div class="modal-footer">' +
'<button class="btn" onclick="document.getElementById(\'af-del-acc-overlay\').remove()">取消</button>' +
'<button class="btn btn-danger" onclick="afDoDeleteAccount(\'' + esc(name) + '\')">删除</button>' +
'</div></div>';
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 = '<div class="modal" style="max-width:520px">' +
'<div class="modal-header"><h3>编辑账号</h3>' +
'<button class="close" onclick="document.getElementById(\'af-acc-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="form-group"><label>昵称(= 素材文件夹名,也是计划里选的"账号")</label>' +
'<input class="form-control" id="af-acc-nick" value="' + esc(row.nickname || '') + '"></div>' +
'<div class="form-group"><label>抖音号(可选)</label>' +
'<input class="form-control" id="af-acc-did" value="' + esc(row.douyin_id || '') + '"></div>' +
'<div class="form-group"><label>所属手机</label>' +
'<select class="form-control" id="af-acc-dev"><option value="">(未登记)</option>' +
devs.map(function (n) {
return '<option value="' + esc(n) + '"' + (n === (row.device_name || '') ? ' selected' : '') +
'>' + esc(n) + '</option>';
}).join('') + '</select>' +
'<div class="help">改昵称不会自动改素材文件夹名;换号请先在账号库里改好再搬文件夹。</div></div>' +
'</div>' +
'<div class="modal-footer"><button class="btn" onclick="document.getElementById(\'af-acc-overlay\').remove()">取消</button>' +
'<button class="btn btn-primary" onclick="afAssetSaveAccount(\'' + esc(rosterId) + '\')">保存</button></div></div>';
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 '<tr>' +
'<td style="width:52px" class="text-muted">#' + (x.seq || '') + '</td>' +
'<td style="width:220px"><div style="max-width:210px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" ' +
'title="' + esc(x.src_path || x.video_name || '') + '">' + esc(x.video_name || '') + '</div>' +
'<span class="text-muted" style="font-size:11px">' + esc(x.device_name || '—') + ' · ' + t +
(x.duration_s ? ' · ' + x.duration_s + 's' : '') + '</span></td>' +
'<td style="width:200px"><div style="max-width:190px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" ' +
'title="' + esc(x.title || '') + '">' + esc(x.title || '(无标题)') + '</div>' +
(x.body ? '<div class="text-muted" style="font-size:11px;max-width:190px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' +
esc(x.body) + '</div>' : '') + '</td>' +
'<td style="width:120px;font-size:12px">' + esc(x.topics || '') + '</td>' +
'<td style="width:90px;font-size:12px">' + esc(x.category || '') + '</td>' +
'<td style="width:80px;font-size:12px">' + esc(x.display_mode || '') + '</td>' +
'<td style="width:80px">' + esc(st[x.status] || x.status) + '</td>' +
'<td style="width:110px;font-size:11px">' + esc(x.published_at || '—') + '</td>' +
'<td style="width:300px;white-space:nowrap;text-align:right">' +
'<button class="btn btn-xs" onclick="afAssetEditItem(\'' + esc(x.id) + '\')">编辑</button> ' +
(canPub ? '' : '<button class="btn btn-xs" onclick="afAssetUnpublish(\'' + esc(x.id) + '\')" ' +
'title="状态放回未发布,下次计划就能再取到它">标为未发布</button> ') +
'<button class="btn btn-xs" onclick="afAssetLogs(\'' + esc(x.id) + '\')">发布记录</button> ' +
'<button class="btn btn-xs btn-danger" onclick="afAssetDel(\'' + esc(x.id) + '\')">删除</button>' +
'</td></tr>';
}).join('');
return '' +
'<div class="toolbar" style="flex-wrap:wrap;align-items:center">' +
'<button class="btn" onclick="afAssetBack()">← 返回账号表</button>' +
'<b style="margin-left:8px">' + esc(acc) + '</b>' +
'<span class="text-muted" style="font-size:12px">素材库(按编号排序;未发布的会被计划按序号取走)</span>' +
'<button class="btn" onclick="afAssetScan(\'' + esc(acc) + '\')">重新扫描这个文件夹</button>' +
'<button class="btn btn-primary" onclick="afOpenAssetImport(\'' + esc(acc) + '\')" data-perm="devices">⬆ 批量上传(配模板)</button>' +
'</div>' +
'<div class="toolbar" style="flex-wrap:wrap;gap:6px">' +
'状态 <select class="form-control" style="width:120px" onchange="afAssetFilterSet(\'status\', this.value)">' +
'<option value="">全部</option>' +
['ready', 'pending', 'pushing', 'publishing', 'done', 'failed', 'unknown', 'asset'].map(function (s) {
return '<option value="' + s + '"' + (f.status === s ? ' selected' : '') + '>' + esc(st[s] || s) + '</option>';
}).join('') + '</select>' +
' 分类 <input class="form-control" style="width:110px" value="' + esc(f.category || '') +
'" onchange="afAssetFilterSet(\'category\', this.value)" placeholder="如 美食">' +
' 展示方式 <select class="form-control" style="width:110px" onchange="afAssetFilterSet(\'display_mode\', this.value)">' +
modeOpts.map(function (m) {
return '<option value="' + esc(m) + '"' + (f.display_mode === m ? ' selected' : '') + '>' +
(m || '全部') + '</option>';
}).join('') + '</select>' +
' 搜索 <input class="form-control" style="width:160px" value="' + esc(f.q || '') +
'" oninput="afAssetFilterSet(\'q\', this.value, 1)" placeholder="标题/文件名">' +
'</div>' +
'<table class="table"><thead><tr>' +
'<th>#</th><th>文件名 / 设备 / 类型</th><th>标题 / 内容</th><th>话题</th><th>分类</th>' +
'<th>展示方式</th><th>状态</th><th>上次发布</th><th style="text-align:right">操作</th>' +
'</tr></thead><tbody>' + (rows || '<tr><td colspan="9" class="empty">这个账号还没有素材 —— 点「批量上传(配模板)」</td></tr>') +
'</tbody></table>' +
'<div id="af-asset-log"></div>';
}
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 = '<div class="modal" style="max-width:680px">' +
'<div class="modal-header"><h3>编辑素材:' + esc(x.video_name || '') + '</h3>' +
'<button class="close" onclick="document.getElementById(\'af-item-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="form-group"><label>标题(≤100 字,发布页的标题框)</label>' +
'<input class="form-control" id="afe-title" value="' + esc(x.title || '') + '"></div>' +
'<div class="form-group"><label>内容 / 正文(≤1000 字)</label>' +
'<textarea class="form-control" id="afe-body" rows="3">' + esc(x.body || '') + '</textarea></div>' +
'<div class="form-row">' +
'<div class="form-group"><label>话题</label>' +
'<input class="form-control" id="afe-topics" value="' + esc(x.topics || '') + '" placeholder="#苏州 #探店"></div>' +
'<div class="form-group"><label>分类</label>' +
'<input class="form-control" id="afe-cat" value="' + esc(x.category || '') + '" placeholder="美食 / 生活…"></div>' +
'</div>' +
'<div class="form-row">' +
'<div class="form-group"><label>展示方式</label>' +
'<select class="form-control" id="afe-mode"><option value="">(未设)</option>' +
['口播', '大字报', '混剪', '搬运'].map(function (m) {
return '<option value="' + m + '"' + (x.display_mode === m ? ' selected' : '') + '>' + m + '</option>';
}).join('') + '</select></div>' +
'<div class="form-group"><label>时长(秒)</label>' +
'<input class="form-control" type="number" min="0" id="afe-dur" value="' + (x.duration_s || 0) + '"></div>' +
'</div>' +
'<div class="form-group"><label>备注</label>' +
'<input class="form-control" id="afe-note" value="' + esc(x.note || '') + '"></div>' +
'</div>' +
'<div class="modal-footer"><button class="btn" onclick="document.getElementById(\'af-item-overlay\').remove()">取消</button>' +
'<button class="btn btn-primary" onclick="afAssetSaveItem(\'' + esc(id) + '\')">保存</button></div></div>';
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 = '<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-top:8px">' +
'<b>发布记录</b> <button class="btn btn-xs" onclick="document.getElementById(\'af-asset-log\').innerHTML=\'\'">收起</button>' +
'<table class="table" style="margin-top:4px"><thead><tr><th style="width:150px">时间</th>' +
'<th style="width:90px">结果</th><th style="width:150px">设备</th><th>链接 / 原因</th></tr></thead><tbody>' +
(logs.length ? logs.map(function (l) {
return '<tr><td class="text-muted" style="font-size:12px">' + esc(l.at) + '</td>' +
'<td>' + ({published: '✅ 发布成功', failed: '❌ 失败', unknown: '❔ 未知'}[l.result] || esc(l.result)) + '</td>' +
'<td>' + esc(l.device_name || '') + '</td>' +
'<td style="font-size:12px">' + (l.share_url
? '<a href="' + esc(l.share_url) + '" target="_blank">' + esc(l.share_url) + '</a>'
: esc(l.error || '')) + '</td></tr>';
}).join('') : '<tr><td colspan="4" class="empty">还没发过</td></tr>') +
'</tbody></table></div>';
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 = '<div class="modal" style="max-width:760px">' +
'<div class="modal-header"><h3>批量上传素材(配模板)</h3>' +
'<button class="close" onclick="document.getElementById(\'af-asset-up-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="help" style="margin-bottom:8px">' +
'① 先下载模板(Excel 填好 → 另存为 <b>CSV UTF-8</b>) ' +
'② 选**素材文件**和**填好的表**一起传 ③ 系统校验<b>数量一致 + 文件名一一对应</b>,' +
'不过就整批不导入<br>表里的<b>账号</b>决定这条素材放进谁的文件夹;' +
'<b>标题必填</b>;话题/分类/展示方式/备注可选;类型和时长不用填(自动识别/读取)。</div>' +
'<div class="toolbar" style="margin-bottom:6px">' +
'<a class="btn btn-xs" href="/api/af/assets/template' + (acc ? ('?account=' + encodeURIComponent(acc)) : '') +
'" target="_blank">⬇ 下载模板(CSV)</a>' +
'<span class="text-muted" style="font-size:12px">模板里的示例账号已填成 ' + esc(acc || '(当前账号)') + '</span></div>' +
'<div class="form-row">' +
'<div class="form-group"><label>素材文件(可多选:视频/图片/音频)</label>' +
'<input type="file" class="form-control" id="af-au-files" multiple accept="video/*,image/*,audio/*">' +
'<div class="help" id="af-au-count">没选文件</div></div>' +
'<div class="form-group"><label>填好的表(CSV)</label>' +
'<input type="file" class="form-control" id="af-au-table" accept=".csv,text/csv">' +
'<div class="help">只收 CSV(Excel 另存为「CSV UTF-8」)</div></div>' +
'</div>' +
'<div id="af-au-log" class="text-muted" style="font-size:12px;max-height:240px;overflow:auto"></div>' +
'</div>' +
'<div class="modal-footer">' +
'<button class="btn" onclick="document.getElementById(\'af-asset-up-overlay\').remove()">关闭</button>' +
'<button class="btn" onclick="afDoAssetImport(1)">试导(只校验)</button>' +
'<button class="btn btn-primary" onclick="afDoAssetImport(0)">导入</button>' +
'</div></div>';
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 = '<div style="color:#c0392b"><b>❌ 校验没过,整批没有导入</b></div>' +
(errs.length ? '<ul style="margin:4px 0 0 16px">' + errs.map(function (x) {
return '<li>' + (x.line ? ('第 ' + x.line + ' 行 ') : '') +
(x.file ? ('<code>' + esc(x.file) + '</code> ') : '') + esc(x.error) + '</li>';
}).join('') + '</ul>' : '<div>' + esc(j.error || '') + '</div>');
return;
}
const rows = j.rows || [];
log.innerHTML = '<div style="color:#16a34a"><b>✅ ' + esc(j.msg || '') + '</b></div>' +
'<table class="table" style="margin-top:4px;font-size:12px"><thead><tr>' +
'<th style="width:50px">行</th><th>文件</th><th style="width:110px">账号</th>' +
'<th style="width:80px">结果</th><th>说明</th></tr></thead><tbody>' +
rows.map(function (x) {
return '<tr><td>' + (x.line || '') + '</td><td>' + esc(x.file) + '</td>' +
'<td>' + esc(x.account || '') + '</td>' +
'<td>' + esc(x.action || '') + '</td>' +
'<td style="' + (x.error ? 'color:#c0392b' : '') + '">' + esc(x.error || x.msg || '') + '</td></tr>';
}).join('') + '</tbody></table>';
if (!dry) {
showToast(j.msg || '已导入', 'success');
await afRefreshAll();
if (_af.curAccount) await afLoadItems(_af.curAccount);
afRender();
}
} catch (e) {
log.innerHTML = '<span style="color:#c0392b">❌ 请求失败:' + esc(String(e)) + '</span>';
}
}
// ① 素材
function afHtmlSrc() {
const P = _af.profile.params.source;
const rows = _af.accounts.map(a => `
<tr style="cursor:pointer" onclick="afPickAccount('${esc(a.name)}')"
class="${a.name === _af.curAccount ? 'row-active' : ''}">
<td><b>${esc(a.name)}</b>${a.valid ? '' : ' <span style="color:#dc2626">(目录名不合法)</span>'}</td>
<td>${a.media}</td><td>${a.pending}</td><td>${a.done}</td>
<td class="text-muted">${a.last_run ? esc(a.last_run.started_at) + ' · ' + esc(_AF_STATUS[a.last_run.status] || a.last_run.status) : '—'}</td>
</tr>`).join('');
const items = _af.items.filter(x => !_af.curAccount || x.nickname === _af.curAccount);
const itemRows = items.map(x => `
<tr>
<td>${x.seq}</td>
<td style="max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(x.video_name || x.src_path || '')}</td>
<td style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(x.title || '(无标题)')}</td>
<td>${esc(_AF_STATUS[x.status] || x.status)}</td>
<td class="text-muted">${esc(x.last_error || '')}</td>
</tr>`).join('');
return `
<div class="toolbar" style="flex-wrap:wrap;align-items:center">
<button class="btn btn-primary" onclick="afOpenUpload()" data-perm="devices">⬆ 上传素材到账号文件夹</button>
<button class="btn" onclick="afScan('')" data-perm="devices"
title="把根目录下所有账号文件夹里的素材扫进条目(已入库的跳过)">扫描全部账号</button>
${_af.curAccount ? `<button class="btn" onclick="afScan('${esc(_af.curAccount)}')" data-perm="devices"
title="只扫当前选中的那个账号">只扫「${esc(_af.curAccount)}」</button>` : ''}
<button class="btn" onclick="afScan('', true)" data-perm="devices"
title="试扫一遍:只告诉你会入库哪些、缺不缺文案,**不写库**">试扫(不写库)</button>
<button class="btn" onclick="afToggleSet()">命名/文案规则</button>
<span class="text-muted">根目录:<code>${esc(_af.root || '')}</code>(也可以直接把文件拷进去,效果一样)</span>
</div>
<div id="af-set" style="display:none;border:1px solid var(--border);border-radius:6px;padding:10px;margin:8px 0">
<div class="form-row" style="display:flex;gap:10px;flex-wrap:wrap">
<div><label class="text-muted" style="font-size:12px">根目录</label>
<input class="form-control" style="width:260px" value="${esc(P.root || '')}"
onchange="afSet('source.root', this.value)"></div>
<div><label class="text-muted" style="font-size:12px">目录结构</label>
<select class="form-control" onchange="afSet('source.layout', this.value)">
<option value="account"${P.layout === 'account' ? ' selected' : ''}>根/&lt;账号&gt;/</option>
<option value="account_date"${P.layout === 'account_date' ? ' selected' : ''}>根/&lt;账号&gt;/&lt;日期&gt;/</option>
</select></div>
<div><label class="text-muted" style="font-size:12px">文件名</label>
<select class="form-control" onchange="afSet('source.filename_rule', this.value)">
<option value="opaque"${P.filename_rule === 'opaque' ? ' selected' : ''}>不管(只看扩展名)</option>
<option value="name_date_seq"${P.filename_rule === 'name_date_seq' ? ' selected' : ''}>沿用 名字_日期_编号</option>
</select></div>
<div><label class="text-muted" style="font-size:12px">文案文件</label>
<input class="form-control" style="width:200px" value="${esc((P.caption_files || []).join(','))}"
onchange="afSet('source.caption_files', this.value.split(',').map(s=>s.trim()).filter(Boolean))"></div>
<div><label class="text-muted" style="font-size:12px">没文案时</label>
<select class="form-control" onchange="afSet('source.title_fallback', this.value)">
<option value="none"${P.title_fallback === 'none' ? ' selected' : ''}>明说"缺文案"(不发)</option>
<option value="filename"${P.title_fallback === 'filename' ? ' selected' : ''}>拿文件名当标题</option>
</select></div>
</div>
<div style="margin-top:8px"><button class="btn btn-primary btn-xs" onclick="afSaveProfile()">保存</button>
<span class="text-muted" style="font-size:12px;margin-left:8px">保存后<b>下次扫描生效</b>(已入库的条目不动)</span></div>
</div>
<div style="display:flex;gap:12px;align-items:flex-start">
<div style="flex:0 0 320px">
<div class="section-title" style="font-size:13px;margin:6px 0">账号(目录)</div>
<table class="table"><thead><tr><th>账号</th><th>素材</th><th>待发</th><th>已发</th><th>上次运行</th></tr></thead>
<tbody>${rows || '<tr><td colspan="5" class="text-muted">根目录下还没有账号文件夹</td></tr>'}</tbody></table>
</div>
<div style="flex:1;min-width:0">
<div class="section-title" style="font-size:13px;margin:6px 0">
条目${_af.curAccount ? '(' + esc(_af.curAccount) + ')' : ''}</div>
<table class="table"><thead><tr><th>编号</th><th>素材</th><th>标题</th><th>状态</th><th>说明</th></tr></thead>
<tbody>${itemRows || '<tr><td colspan="5" class="text-muted">还没有条目 —— 点「扫描全部账号」</td></tr>'}</tbody></table>
</div>
</div>`;
}
// 上传素材:等价于"把文件拷进账号文件夹",传完自动扫描入库
function afOpenUpload() {
const opts = _af.accounts.map(a => `<option value="${esc(a.name)}">`).join('');
const ov = document.createElement('div');
ov.id = 'af-up-overlay';
ov.className = 'modal-overlay show';
ov.onclick = e => { if (e.target === ov) ov.remove(); };
ov.innerHTML = `
<div class="modal" style="max-width:620px">
<div class="modal-header"><h3>上传素材到账号文件夹</h3>
<button class="close" onclick="document.getElementById('af-up-overlay').remove()">&times;</button></div>
<div class="modal-body">
<div class="form-row">
<div class="form-group"><label>账号(= 文件夹名)</label>
<input class="form-control" id="af-up-account" list="af-up-accounts" value="${esc(_af.curAccount || '')}"
placeholder="如 锋哥苏州寻宝藏小店">
<datalist id="af-up-accounts">${opts}</datalist>
<div class="help">没有就自动新建目录;名字不许含下划线、不许纯数字</div></div>
</div>
<div class="form-row"><div class="form-group" style="grid-column:span 3">
<label>选文件(可多选,视频/图片)</label>
<input type="file" class="form-control" id="af-up-files" multiple accept="video/*,image/*">
</div></div>
<div class="form-row"><div class="form-group" style="grid-column:span 3">
<label>文案(可选,一行一条,按顺序配素材;写成 <code>标题 || 正文</code> 可带正文)</label>
<textarea class="form-control" id="af-up-caps" rows="4"
placeholder="第一条标题 || 正文&#10;第二条标题"></textarea>
<div class="help">会**追加**到该账号目录的 <code>标题.txt</code>(先传素材再传文案,顺序就对得上)</div>
</div></div>
<div id="af-up-log" class="text-muted" style="font-size:12px"></div>
</div>
<div class="modal-footer">
<button class="btn" onclick="document.getElementById('af-up-overlay').remove()">取消</button>
<button class="btn btn-primary" id="af-up-btn" onclick="afDoUpload()">上传</button>
</div>
</div>`;
document.body.appendChild(ov);
}
async function afDoUpload() {
const account = (document.getElementById('af-up-account').value || '').trim();
const files = document.getElementById('af-up-files').files;
const caps = document.getElementById('af-up-caps').value || '';
const log = document.getElementById('af-up-log');
if (!account) { showToast('先填账号(= 文件夹名)', 'error'); return; }
if (!files || !files.length) { showToast('先选文件', 'error'); return; }
const fd = new FormData();
fd.append('account', account);
fd.append('captions', caps);
for (let i = 0; i < files.length; i++) fd.append('files', files[i]);
const btn = document.getElementById('af-up-btn');
btn.disabled = true;
log.textContent = '上传中…(' + files.length + ' 个文件)';
try {
const r = await fetch('/api/af/upload', {method: 'POST',
headers: {'X-CSRF-Token': (typeof _csrfToken !== 'undefined' ? _csrfToken : '')}, body: fd});
const j = await r.json();
if (!j.ok) { log.textContent = '❌ ' + (j.error || '上传失败'); showToast(j.error || '上传失败', 'error'); }
else {
const bad = (j.rejected || []);
log.textContent = '✅ ' + (j.msg || '') + (bad.length ? ('\n⚠ ' + bad.map(x => x.file + ':' + x.error).join(';')) : '');
showToast(j.msg || '已上传', 'success');
_af.curAccount = account;
await afRefreshAll();
await afLoadItems(account);
}
} catch (e) { log.textContent = '❌ 请求失败:' + e; }
btn.disabled = false;
}
function afToggleSet() {
const el = document.getElementById('af-set');
if (el) el.style.display = (el.style.display === 'none' ? 'block' : 'none');
}
function afPickAccount(name) {
_af.curAccount = name;
afLoadItems(name);
}
async function afLoadItems(name) {
const r = await apiGet('/api/af/items?account=' + encodeURIComponent(name || ''));
if (r && r.ok) _af.items = r.items || [];
afRender();
}
async function afScan(account, dry) {
if (_af.busy) return;
_af.busy = true;
showToast(dry ? '预览中…' : '扫描中…');
const r = await apiPost('/api/af/scan', {account: account || '', dry_run: !!dry});
_af.busy = false;
if (!r) return;
if (!r.ok) { showToast(r.error || '扫描失败', 'error'); return; }
if (r.accounts) { // 扫全部:给一条汇总
showToast((r.msg || ('新增 %d、跳过 %d、拒收 %d' % (r.added, r.skipped, r.rejected))), 'success');
const bad = (r.accounts || []).filter(a => !a.ok);
if (bad.length) showToast('有 ' + bad.length + ' 个账号目录没扫成:' + (bad[0].error || ''), 'error');
} else {
showToast(r.msg || '扫描完成', r.rejected ? 'error' : 'success');
if (r.items && r.items.length) {
const bad = r.items.filter(x => x.action === 'reject');
if (bad.length) showToast(bad[0].error || '有文件被拒收', 'error');
}
if (r.account) _af.curAccount = r.account;
}
await afRefreshAll();
if (_af.curAccount) await afLoadItems(_af.curAccount);
}
// ② 设备与账号:执行单位(按设备 / 按账号)+ 范围选择 + 切号参数 + 用哪个动作组
function afHtmlFleet() {
const P = _af.profile.params, F = P.fleet;
const mode = F.run_mode || 'by_account';
const devs = _af.devices.map(function (d) {
const checked = mode === 'by_device' ? !!_af.selDevices[d.serial] : false;
const acc = _af.devAccount[d.serial] || d.cur_account || '';
return '<div style="border:1px solid ' + (checked ? 'var(--primary)' : 'var(--border)') +
';border-radius:8px;padding:8px 10px;min-width:235px;background:' +
(checked ? 'rgba(37,99,235,.06)' : 'transparent') + '">' +
'<div style="cursor:pointer" onclick="afToggleDev(\'' + esc(d.serial) + '\')">' +
'<input type="checkbox" ' + (checked ? 'checked' : '') + '>' +
' <b>' + esc(d.name || d.serial) + '</b> ' +
(d.online ? '<span style="color:#16a34a">在线</span>' : '<span class="text-muted">离线</span>') +
(d.busy ? ' <span style="color:#dc2626">忙</span>' : '') +
' <span class="text-muted" style="font-size:12px">' + esc(d.model || '') + '</span></div>' +
'<div style="display:flex;gap:4px;align-items:center;margin-top:4px">' +
'<span class="text-muted" style="font-size:12px">要跑的号</span>' +
'<input class="form-control" style="width:210px" value="' + esc(acc) + '"' +
' placeholder="可多个,逗号分隔" title="这台机器要跑的账号;一个号跑完自动切下一个(切不过来就跳过这个号)"' +
' onchange="afSetDevAccount(\'\' + esc(d.serial) + \'\', this.value)"></div></div>';
}).join('');
const accs = _af.accounts.map(function (a) {
const on = _af.selAccounts[a.name] !== false;
return '<label style="display:inline-flex;gap:6px;align-items:center;margin:3px 12px 3px 0">' +
'<input type="checkbox" ' + (on ? 'checked' : '') + ' onchange="afToggleAcc(\'' + esc(a.name) + '\', this.checked)">' +
esc(a.name) + ' <span class="text-muted">待发 ' + a.pending + '</span></label>';
}).join('');
const taskActions = _af.actions.filter(function (a) {
const k = a.kind || ''; return k !== 'opening' && k !== 'builtin'; });
const actOpts = taskActions.map(function (a) {
const app = _af.apps.find(function (x) { return x.id === a.app_id; }) || {};
return '<option value="' + esc(a.id) + '"' + (P.action.action_id === a.id ? ' selected' : '') + '>' +
esc(a.name) + (a.app_id ? '(' + esc(app.name || 'App') + ')' : '(未归属 App)') + '</option>';
}).join('');
const S = F.switch;
return '' +
'<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-bottom:10px">' +
'<b>执行单位</b> ' +
'<label style="margin-left:10px"><input type="radio" name="af-mode" ' + (mode === 'by_device' ? 'checked' : '') +
' onchange="afSetMode(\'by_device\')"> <b>按设备</b>' +
' <span class="text-muted" style="font-size:12px">勾几台机器 → 同时跑(每台先跑开场动作把状态统一)</span></label>' +
'<label style="margin-left:14px"><input type="radio" name="af-mode" ' + (mode !== 'by_device' ? 'checked' : '') +
' onchange="afSetMode(\'by_account\')"> <b>按账号</b>' +
' <span class="text-muted" style="font-size:12px">勾几个账号 → 谁登着这个号谁跑</span></label>' +
'</div>' +
(mode === 'by_device'
? '<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-bottom:10px">' +
'<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px">' +
'<div><b>① 设备</b> <span class="text-muted" style="font-size:12px">勾选要同时跑的机器;「用号」= 这台要切到哪个账号</span></div>' +
'<div><button class="btn btn-xs" onclick="afProbe()">探测当前登录账号(自动填「用号」)</button>' +
'<button class="btn btn-xs" onclick="afRefreshAll(true)">刷新状态</button></div></div>' +
'<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:8px">' +
(devs || '<span class="text-muted">设备池为空</span>') + '</div></div>'
: '<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-bottom:10px">' +
'<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px">' +
'<div><b>① 账号</b> <span class="text-muted" style="font-size:12px">默认全选;取消勾选就不跑它</span></div>' +
'<div><button class="btn btn-xs" onclick="afPickAll(true)">全选</button>' +
'<button class="btn btn-xs" onclick="afPickAll(false)">全不选</button>' +
'<select class="form-control" style="width:190px;display:inline-block" onchange="afSet(\'fleet.assign\', this.value);afSaveProfile(true)">' +
'<option value="auto_by_account"' + (F.assign === 'auto_by_account' ? ' selected' : '') + '>按账号自动找设备</option>' +
'<option value="manual"' + (F.assign === 'manual' ? ' selected' : '') + '>手工指定(映射表)</option></select></div></div>' +
'<div style="margin-top:6px">' + (accs || '<span class="text-muted">还没有账号 —— 先去「① 素材」扫描或上传</span>') + '</div></div>') +
'<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-bottom:10px">' +
'<b>② 切号与校验</b> <span class="text-muted" style="font-size:12px">(开场动作里那步「切账号」用这些参数)</span>' +
'<div class="form-row" style="display:flex;gap:10px;flex-wrap:wrap;margin-top:6px">' +
'<div><label class="text-muted" style="font-size:12px">切完等(秒)</label>' +
'<input type="number" class="form-control" style="width:90px" value="' + S.wait_after + '" onchange="afSet(\'fleet.switch.wait_after\', this.value, \'num\')"></div>' +
'<div><label class="text-muted" style="font-size:12px">回读校验</label>' +
'<select class="form-control" onchange="afSet(\'fleet.switch.verify\', this.value)">' +
'<option value="contains"' + (S.verify === 'contains' ? ' selected' : '') + '>包含</option>' +
'<option value="equals"' + (S.verify === 'equals' ? ' selected' : '') + '>精确相等</option>' +
'<option value="none"' + (S.verify === 'none' ? ' selected' : '') + '>不校验</option></select></div>' +
'<div><label class="text-muted" style="font-size:12px">重试次数</label>' +
'<input type="number" class="form-control" style="width:80px" value="' + S.retries + '" onchange="afSet(\'fleet.switch.retries\', this.value, \'num\')"></div>' +
'<div><label class="text-muted" style="font-size:12px">停在登录页</label>' +
'<select class="form-control" onchange="afSet(\'fleet.switch.on_login\', this.value)">' +
'<option value="stop"' + (S.on_login === 'stop' ? ' selected' : '') + '>停本设备</option>' +
'<option value="skip"' + (S.on_login === 'skip' ? ' selected' : '') + '>跳过继续</option></select></div>' +
'<div><label class="text-muted" style="font-size:12px">发布后删手机素材</label>' +
'<input type="checkbox" ' + (P.fleet.after.delete_phone ? 'checked' : '') + ' onchange="afSet(\'fleet.after.delete_phone\', this.checked, \'bool\')"></div>' +
'</div></div>' +
'<div style="border:1px solid var(--border);border-radius:6px;padding:10px">' +
'<b>③ 用哪个动作组</b>' +
'<div style="margin-top:6px;display:flex;gap:8px;align-items:center;flex-wrap:wrap">' +
'<select class="form-control" style="max-width:340px" onchange="afSet(\'action.action_id\', this.value);afSaveProfile(true)">' +
'<option value="">(请选择)</option>' + actOpts + '</select>' +
'<span class="text-muted" style="font-size:12px">开场动作(把设备置初始状态)在「③ 动作」里按 App 配;' +
'没配就用内置默认:打开App → 等首页 → 切到目标号</span></div>' +
'<div style="margin-top:10px;display:flex;align-items:center;gap:10px;flex-wrap:wrap">' +
'<button class="btn btn-primary" onclick="afRun()" data-perm="devices">▶ 跑一轮</button>' +
'<button class="btn" onclick="afSaveProfile()">保存设置</button>' +
'<span class="text-muted" id="af-run-hint"></span></div>' +
'<div class="text-muted" style="font-size:12px;margin-top:6px">' +
'⚠ 每台设备同一时刻只能跑一个任务;流水线会跳过正在跑任务的设备(不会打断它)。</div>' +
'</div>' +
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 === '(未指定设备)' ? '<span class="text-muted">没写设备号</span>'
: one.pooled ? (one.online ? '<span style="color:#16a34a">在线</span>'
: '<span class="text-muted">离线</span>')
: '<span style="color:#dc2626">未入设备池</span>';
return '<div style="display:flex;gap:8px;padding:4px 0;border-bottom:1px dashed var(--border)">' +
'<div style="width:74px"><b>' + esc(dev) + '</b><div style="font-size:11px">' + state + '</div></div>' +
'<div style="flex:1;display:flex;flex-wrap:wrap;gap:4px">' +
rows.map(r => '<span class="label label-default" style="font-size:12px">' + esc(r.nickname) +
' <span class="text-muted">' + esc(r.douyin_id || '') + '</span>' +
'<a href="javascript:;" onclick="afDelRoster(\'' + esc(r.id) + '\',\'' + esc(r.nickname) + '\')" ' +
'title="从账号库删掉这一行(只影响这张表)" style="color:#dc2626">×</a></span>').join('') +
'</div></div>';
}).join('');
return '<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-top:10px">' +
'<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px">' +
'<div><b>📇 账号库</b> <span class="text-muted" style="font-size:12px">' +
devCount + ' 台设备 · ' + _af.roster.length + ' 个号|<b>名字 ↔ 哪台手机</b> 就靠它 —— ' +
'以后"输入几个名字,只有对应的手机才激活任务"查的就是这张表</span></div>' +
'<div><button class="btn btn-xs" onclick="afOpenRoster()" data-perm="devices">粘贴导入 / 查看</button>' +
'<button class="btn btn-xs" onclick="afRefreshAll(true)">刷新</button></div></div>' +
'<div style="margin-top:6px;max-height:230px;overflow:auto">' +
(body || '<div class="text-muted">账号库是空的 —— 点「粘贴导入」把表格里的行贴进来</div>') +
'</div></div>';
}
// 账号池对外只读 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 = '<div class="modal" style="max-width:720px">' +
'<div class="modal-header"><h3>🔑 账号池 API(只读)</h3>' +
'<button class="close" onclick="document.getElementById(\'af-pool-api\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<p class="text-muted" style="font-size:12px">其他应用直接 GET 这个地址,不需要登录;' +
'请求头带 <code>X-Account-Token</code>(或 <code>Authorization: Bearer …</code>)。</p>' +
'<div class="form-group"><label>地址</label>' +
'<input class="form-control" readonly value="' + esc(url) + '"></div>' +
'<div class="form-group"><label>令牌 ' + esc(r.token_created_at || '') + '</label>' +
'<div style="display:flex;gap:6px">' +
'<input class="form-control" readonly id="af-pool-token" value="' + esc(token) + '">' +
'<button class="btn" onclick="afCopyPoolToken()">复制</button></div></div>' +
'<div class="form-group"><label>示例</label>' +
'<pre style="white-space:pre-wrap;font-size:12px;margin:0">' + esc(curl) + '</pre></div>' +
'<p class="text-muted" style="font-size:12px">可选过滤:<code>?device=A11</code>、' +
'<code>?q=锋哥</code>、<code>?status=正常</code>、<code>?online=1</code></p>' +
'</div>' +
'<div class="modal-footer">' +
'<button class="btn btn-danger" onclick="afResetPoolToken()">重置令牌</button>' +
'<button class="btn" onclick="document.getElementById(\'af-pool-api\').remove()">关闭</button>' +
'</div></div>';
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 =
'<div class="modal" style="max-width:760px">' +
'<div class="modal-header"><h3>账号库:粘贴导入</h3>' +
'<button class="close" onclick="document.getElementById(\'af-roster-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="help">每行三段:<b>设备号 账号名 抖音号</b>(制表符或空格分隔,不用表头)。' +
'例如:<code>A01 周周逛苏州 49057596509</code><br>' +
'导入<b>按抖音号认同一行</b> —— <b>改名字不会变成两条</b>;' +
'库里多出来的(这次没提到的)<b>一条都不删</b>,只在下面列出来提醒你。</div>' +
'<textarea class="form-control" id="af-roster-text" rows="9" ' +
'placeholder="从表格里复制几行,直接粘在这里"></textarea>' +
'<div id="af-roster-res" class="text-muted" style="font-size:12px;margin-top:8px"></div>' +
'</div>' +
'<div class="modal-footer">' +
'<button class="btn" onclick="afDoRoster(true)">先试算(不写库)</button>' +
'<button class="btn btn-primary" onclick="afDoRoster(false)">导入</button>' +
'<button class="btn" onclick="document.getElementById(\'af-roster-overlay\').remove()">关闭</button>' +
'</div></div>';
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 = '<span style="color:#dc2626">❌ ' + esc((r && r.error) || '失败') + '</span>'; return; }
const x = r.result || {};
let html = (dry ? '<b>试算结果</b>(没写库):' : '<b>已导入</b>:') +
'新增 <b>' + x.added + '</b> 行、改名 <b>' + x.updated + '</b> 行、没变 ' + x.unchanged + ' 行';
if ((x.bad || []).length) {
html += '<br><span style="color:#dc2626">认不出来的 ' + x.bad.length + ' 行:</span> ' +
x.bad.map(b => esc(b.nickname || '(空)')).join('、');
}
if ((x.stale || []).length) {
html += '<br><span style="color:#d97706">库里多出来 ' + x.stale.length + ' 行(没删,自己看一眼要不要删):</span><br>' +
x.stale.map(s => esc(s.device_name + ' ' + s.nickname + ' ' + (s.douyin_id || '')) +
' <a href="javascript:;" onclick="afDelRoster(\'' + esc(s.id) + '\',\'' + esc(s.nickname) +
'\')" style="color:#dc2626">删除</a>').join('<br>');
}
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 '' +
'<div style="border:1px solid var(--border);border-radius:6px;padding:8px 10px;margin-bottom:8px">' +
'<div style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap;align-items:center">' +
'<div><b>' + esc(app.name) + '</b> <span class="text-muted">' + esc(app.package) + '</span>' +
(op ? ' <span class="label label-default">开场动作已配</span>'
: ' <span class="label label-warning">还没开场动作</span>') + '</div>' +
'<div style="display:flex;gap:4px;align-items:center">' +
'<input class="form-control" style="width:230px" id="app-home-' + esc(app.id) + '"' +
' value="' + esc(app.home_selector_value || '') + '" placeholder="首页定位(如 //*[@text=首页])">' +
'<button class="btn btn-xs btn-pick" onclick="_stepEditor.openPicker(this)">抓取元素</button>' +
'<button class="btn btn-xs" onclick="afTestSel(\'app-home-' + esc(app.id) + '\')">测一下</button>' +
'<button class="btn btn-xs btn-primary" onclick="afSaveApp(\'' + esc(app.id) + '\')">保存</button>' +
(op ? '' : '<button class="btn btn-xs" onclick="afNewOpening(\'' + esc(app.id) + '\')">一键建开场动作</button>') +
'</div></div></div>';
}).join('');
// ---- 动作表:**一行一个动作,"动作内容"自成一列,操作放在这一行下面** ----
const typeLabel = function (a) {
const k = a.kind || '';
if (k === 'builtin') return '<span class="label label-info">内置</span>';
if (k === 'opening') return '<span class="label label-default">开场</span>';
return a.app_id ? '<span class="label label-success">业务</span>'
: '<span class="label label-warning">未归属 App</span>';
};
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 = [
'<button class="btn btn-xs" onclick="afTryAction(\'' + esc(a.id) + '\')" data-perm="devices" ' +
'title="在一台设备上单独试跑这个动作(手填要切到的账号)">▶ 试跑</button>',
'<button class="btn btn-xs btn-primary" onclick="openActionModal(\'' + esc(a.id) + '\')" ' +
'title="用同一个动作编辑器改:归属App / 起点 / 内容 / 终点">✎ 编辑</button>',
'<button class="btn btn-xs" onclick="afCopyAction(\'' + esc(a.id) + '\')" title="复制一份再改">复制</button>',
'<button class="btn btn-xs" onclick="afStarAction(\'' + esc(a.id) + '\',' + (!a.starred) + ')" ' +
'title="标准件:置顶显示;要删得先取消标记">' + (a.starred ? '★ 已标标准' : '☆ 标为标准') + '</button>',
'<button class="btn btn-xs" onclick="afShowUsage(\'' + esc(a.id) + '\')" title="谁在用这个组合">' +
(used ? '被引用 ' + used + ' 处' : '引用:无') + '</button>'
];
if ((a.kind || '') !== 'builtin' && (a.kind || '') !== 'opening') {
ops.push('<button class="btn btn-xs btn-danger" onclick="afDelAction(\'' + esc(a.id) + '\')">删除</button>');
}
if ((a.kind || '') === 'builtin') {
ops.push('<button class="btn btn-xs" onclick="afCopyAction(\'' + esc(a.id) + '\')" ' +
'title="内置动作由代码播种、不能删;复制一份就能改">内置·只能复制</button>');
}
return '<tr>' +
'<td style="font-size:12px">' + esc(app.name || '(未归属)') + '</td>' +
'<td>' + typeLabel(a) + '</td>' +
'<td><b>' + esc(a.name) + '</b>' +
(a.starred ? ' <span class="label label-warning" title="标准件">★</span>' : '') +
(used ? ' <span class="text-muted" style="font-size:11px">被引用 ' + used + ' 处</span>' : '') + '</td>' +
'<td style="font-size:12px;max-width:460px"><div style="max-height:52px;overflow:hidden">' +
esc(afStepsSummary(a.steps)) + '</div>' +
'<span class="text-muted" style="font-size:11px">共 ' + n + ' 步</span></td>' +
'<td style="font-size:11px">起点:' + (sp.selector_value ? '<code>' + esc(sp.selector_value) + '</code>' : 'App 首页') +
'<div class="text-muted">终点:' + (ep.selector_value ? esc(ep.selector_value) : '(未设)') + '</div></td>' +
'<td style="white-space:nowrap;text-align:right">' + ops.join(' ') + '</td>' +
'</tr>';
}).join('');
const table = '<table class="table" style="margin-top:6px"><thead><tr>' +
'<th style="width:110px">App</th><th style="width:80px">类型</th><th style="width:230px">动作名</th>' +
'<th>动作内容(一眼看它都干了什么)</th><th style="width:180px">起点 / 终点</th>' +
'<th style="width:340px;text-align:right">操作</th></tr></thead><tbody>' +
(rows || '<tr><td colspan="6" class="empty">还没有动作 —— 点「+ 新建业务动作组」,' +
'或先建 App 再「一键建开场动作」</td></tr>') + '</tbody></table>';
return '' +
'<div class="toolbar" style="flex-wrap:wrap">' +
'<button class="btn btn-primary" onclick="openActionModal(\'\')" data-perm="devices">+ 新建业务动作组</button>' +
'<button class="btn" onclick="afNewApp()" data-perm="devices">+ 新建 App</button>' +
'<button class="btn" onclick="afRefreshAll(true)">刷新</button>' +
'<span class="text-muted" style="font-size:12px">' +
'动作组 = <b>起点</b>(App + 从哪一页开始)+ <b>内容</b>(一串步骤)+ <b>终点</b>(跑完得看到的那一页);' +
'编辑器是<b>任务页同一个</b>,建的动作任务/计划里都能直接引用。' +
'<b>内置动作</b>由代码播种(不可删、可复制);<b>★标准件</b>是你自己标的常用件(置顶、删前要取消标记)</span>' +
'</div>' +
'<div id="af-newapp" style="display:none;border:1px solid var(--border);border-radius:6px;padding:10px;margin:8px 0">' +
'<div class="form-row" style="display:flex;gap:8px;flex-wrap:wrap">' +
'<input class="form-control" id="na-name" placeholder="App 名称(抖音)" style="width:160px">' +
'<input class="form-control" id="na-pkg" placeholder="包名 com.ss.android.ugc.aweme" style="width:280px">' +
'<input class="form-control" id="na-wh" placeholder="首页说明(抖音首页)" style="width:160px">' +
'<button class="btn btn-primary btn-xs" onclick="afCreateApp()">创建</button>' +
'<button class="btn btn-xs" onclick="document.getElementById(\'af-newapp\').style.display=\'none\'">取消</button>' +
'</div></div>' +
(appBlocks || '<div class="text-muted" style="margin-bottom:8px">先「+ 新建 App」(例如抖音),再建开场动作与业务动作组</div>') +
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 '<li>' + esc(x.name || x.id) + (x.path ? ' <span class="text-muted">(' + esc(x.path) + ')</span>' : '') +
(x.field ? ' <span class="text-muted">(' + esc(x.field) + ')</span>' : '') + '</li>';
}).join('');
};
const html = '<div style="font-size:13px">' +
'<div><b>' + esc((r.action || {}).name || '') + '</b>:' + esc(r.summary || '') + '</div>' +
((e.tasks || []).length ? '<div style="margin-top:6px">任务:<ul>' + li(e.tasks) + '</ul></div>' : '') +
((e.actions || []).length ? '<div style="margin-top:6px">其它组合:<ul>' + li(e.actions) + '</ul></div>' : '') +
((e.plans || []).length ? '<div style="margin-top:6px">计划:<ul>' + li(e.plans) + '</ul></div>' : '') +
((g.tasks || []).length ? '<div style="margin-top:6px;color:#b45309">可能是它(老任务里的展开副本,按名字猜的,' +
'仅供参考 —— 那些任务里存的是步骤副本,改/删这个组合**不影响**它们):<ul>' + li(g.tasks) + '</ul></div>' : '') +
'<div class="help" style="margin-top:8px">' + (r.can_delete ? '现在**可以删**。' :
('**不能直接删**:' + esc(r.error || ''))) + '</div></div>';
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 = '<div class="modal" style="max-width:620px">' +
'<div class="modal-header"><h3>这个组合被谁用了</h3>' +
'<button class="close" onclick="document.getElementById(\'af-usage-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' + html + '</div>' +
'<div class="modal-footer"><button class="btn" onclick="document.getElementById(\'af-usage-overlay\').remove()">知道了</button></div>' +
'</div>';
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 '<option value="' + esc(d.serial) + '"' + (d.online ? '' : ' disabled') + '>' +
esc(d.name || d.serial) + (d.online ? '(在线)' : '(离线)') +
(d.cur_account ? ' 当前登着:' + esc(d.cur_account) : '') + '</option>';
}).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 =
'<div class="modal" style="max-width:560px">' +
'<div class="modal-header"><h3>试跑动作:' + esc(a.name || '') + '</h3>' +
'<button class="close" onclick="document.getElementById(\'af-try-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="help" style="margin-bottom:8px">动作步骤:' + ((a.steps || []).length) +
' 步|这个入口**不取内容、不推素材**,只把动作本身跑一遍(测"切账号"最合适)</div>' +
'<div class="form-group"><label>在哪台设备上跑</label>' +
'<select class="form-control" id="af-try-dev">' + (devs || '<option value="">(没有设备)</option>') + '</select></div>' +
'<div class="form-group" style="margin-top:8px"><label>本次要切的名字(手填)</label>' +
'<input class="form-control" id="af-try-name" placeholder="如 锋哥苏州寻宝藏小店">' +
'<div class="help">这个名字会作为运行期变量 <code>{本次要发的名字}</code> 注入 —— ' +
'动作里"点列表那一行""条件判断的候选值来源"都用它。留空就只跑动作里写死的部分。</div></div>' +
'<div id="af-try-log" class="text-muted" style="font-size:12px;margin-top:8px"></div>' +
'</div>' +
'<div class="modal-footer">' +
'<button class="btn" onclick="document.getElementById(\'af-try-overlay\').remove()">取消</button>' +
'<button class="btn btn-primary" id="af-try-btn" onclick="afDoTry(\'' + esc(actionId) + '\')">开始试跑</button>' +
'</div></div>';
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 '<div style="border:1px solid var(--border);border-radius:6px;padding:8px 10px;margin-bottom:10px">' +
'<b>切号 / 发布前准备参数</b> <span class="text-muted" style="font-size:12px">' +
'(所有计划共用;选择器点「编辑切号选择器」,改一次全部生效)</span>' +
'<div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:6px;align-items:center;font-size:12px">' +
'<span>切完等 <input class="form-control" style="width:60px;display:inline-block" type="number" min="5" id="af-sw-wait" value="' +
(s.wait_after === undefined ? 15 : s.wait_after) + '"> 秒</span>' +
'<span>重试 <input class="form-control" style="width:55px;display:inline-block" type="number" min="1" id="af-sw-retry" value="' +
(s.retries || 2) + '"> 次</span>' +
'<span>停在登录页 <select class="form-control" style="width:130px;display:inline-block" id="af-sw-login">' +
'<option value="stop"' + ((s.on_login || 'stop') === 'stop' ? ' selected' : '') + '>停本设备</option>' +
'<option value="continue"' + (s.on_login === 'continue' ? ' selected' : '') + '>继续(只记一句)</option>' +
'</select></span>' +
'<button class="btn btn-xs btn-primary" onclick="afSaveSwitchParams()">保存</button>' +
'<button class="btn btn-xs" onclick="afOpenReadyEditor(\'global\')">编辑切号选择器</button>' +
'<button class="btn btn-xs" onclick="afOpenQuickRun()" data-perm="devices">⚡ 临时跑一轮(不建计划)</button>' +
'</div></div>';
}
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');
await afReloadReadyDefaults();
}
// 临时跑一轮:选账号 + 动作组 → 立刻跑(不走计划、不建记录之外的任何东西)
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 = '<div class="modal" style="max-width:620px">' +
'<div class="modal-header"><h3>临时跑一轮(不建计划)</h3>' +
'<button class="close" onclick="document.getElementById(\'af-quick-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="form-group"><label>业务动作组</label>' +
'<select class="form-control" id="af-q-act"><option value="">(选一个)</option>' +
acts.map(function (a) {
return '<option value="' + esc(a.id) + '">' + esc(a.name) + '</option>';
}).join('') + '</select></div>' +
'<div class="form-group"><label>账号(勾要跑的;它们在哪台手机上由资产管理里的"所属手机"决定)</label>' +
'<div style="max-height:200px;overflow:auto;border:1px solid var(--border);border-radius:6px;padding:8px">' +
(accs.length ? accs.map(function (a) {
return '<label style="display:inline-flex;gap:4px;align-items:center;margin:2px 12px 2px 0;font-weight:400">' +
'<input type="checkbox" class="af-q-acc" value="' + esc(a.nickname) + '"> ' + esc(a.nickname) +
' <span class="text-muted" style="font-size:11px">' + esc(a.device_name || '未登记') + '</span></label>';
}).join('') : '<span class="text-muted">账号库是空的</span>') + '</div></div>' +
'<div class="help">跑一轮 = 每个账号:切到它(需要才切)→ 取**未发布**素材按序号发 N 条 → 标记;' +
'正在跑别的任务的设备会跳过。</div>' +
'<div id="af-q-log" class="text-muted" style="font-size:12px"></div>' +
'</div>' +
'<div class="modal-footer"><button class="btn" onclick="document.getElementById(\'af-quick-overlay\').remove()">取消</button>' +
'<button class="btn btn-primary" id="af-q-btn" onclick="afDoQuickRun()">开始</button></div></div>';
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('、') || '<span class="text-muted">(没填时间:只能手动跑)</span>';
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 isComment = !!p.comment_mode;
const commentByName = {};
(_af.accounts || []).forEach(function (a) { commentByName[a.name] = a.comment_pending || 0; });
const commentTotal = (p.accounts || []).reduce(function (s, n) {
return s + (commentByName[n] || 0);
}, 0);
const n = isComment
? ('评论 · 待评论 ' + commentTotal + ' 条')
: (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 '<tr>' +
'<td><b>' + esc(p.name) + '</b>' +
(isComment ? ' <span class="label label-info">评论</span>' : '') +
(p.enabled ? ' <span class="label label-success">启用</span>'
: ' <span class="label label-default">停用</span>') +
(p.note ? '<div class="text-muted" style="font-size:11px">' + esc(p.note) + '</div>' : '') + '</td>' +
'<td>' + esc(app.name || '(没选 App)') +
'<div class="text-muted" style="font-size:11px;white-space:normal;max-width:220px">' +
esc(flow) + (segs.length ? (' <span style="opacity:.7">(' + segs.length + ' 段)</span>') : '') +
'</div></td>' +
'<td>' + accs.length + ' 个号<div class="text-muted" style="font-size:11px;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="' +
esc(accs.join('、')) + '">' + esc(accs.slice(0, 3).join('、')) + (accs.length > 3 ? '…' : '') + '</div></td>' +
'<td style="font-size:12px">' + n + '</td>' +
'<td style="font-size:12px">' + pts + jit +
(p.next_run ? '<div class="text-muted" style="font-size:11px">下次 ' + esc(p.next_run) + '</div>' : '') + '</td>' +
'<td style="font-size:11px">' + (p.prep_check ? '发布前准备 ✓' : '发布前准备 ✗') +
'<div class="text-muted">重试 ' + ((p.retry || {}).max_attempts || 1) + ' 次后跳过' +
(p.max_parallel ? (' 并发 ' + p.max_parallel) : '') + '</div></td>' +
'<td style="font-size:11px">' + (last
? (esc((last.started_at || '').slice(5, 16)) + ' ' + _afPlanStatus(last.status) +
'<div class="text-muted">' + last.ok_accounts + '✓ ' + last.failed_accounts + '✗ ' +
last.skipped_accounts + '跳过</div>')
: '<span class="text-muted">还没跑过</span>') + '</td>' +
'<td style="white-space:nowrap">' +
'<button class="btn btn-xs btn-primary" onclick="afPlanRun(\'' + esc(p.id) + '\')" data-perm="devices" title="立刻跑一批(只激活这些号所在的手机)">▶ 立即跑</button> ' +
'<button class="btn btn-xs" onclick="afPlanTry(\'' + esc(p.id) + '\')" data-perm="devices" title="只挑一个号试跑,验证整条链">试跑</button> ' +
'<button class="btn btn-xs" onclick="afPlanPreview(\'' + esc(p.id) + '\')" title="只算不跑:现在会激活哪几台手机、哪些号跑不了">预览</button> ' +
'<button class="btn btn-xs" onclick="afOpenPlan(\'' + esc(p.id) + '\')">编辑</button> ' +
'<button class="btn btn-xs" onclick="afPlanToggle(\'' + esc(p.id) + '\',' + (!p.enabled) + ')">' + (p.enabled ? '停用' : '启用') + '</button> ' +
'<button class="btn btn-xs btn-danger" onclick="afPlanDelete(\'' + esc(p.id) + '\',\'' + esc(p.name) + '\')">删除</button>' +
'</td></tr>';
}).join('');
const runs = (_af.planRuns || []).map(function (r) {
const t = (r.trigger === 'cron' ? '到点' : r.trigger === 'try' ? '试跑' : '手动');
return '<tr><td class="text-muted" style="font-size:12px">' + esc((r.started_at || '').slice(5, 16)) + '</td>' +
'<td>' + esc(r.plan_name) + ' <span class="text-muted">' + t + '</span></td>' +
'<td>' + _afPlanStatus(r.status) + '</td>' +
'<td>' + r.ok_accounts + ' ✓ / ' + r.failed_accounts + ' ✗ / ' + r.skipped_accounts + ' 跳过</td>' +
'<td>' + esc((r.devices || []).length) + ' 台</td>' +
'<td><button class="btn btn-xs" onclick="afShowPlanRun(\'' + esc(r.id) + '\')">明细</button></td></tr>';
}).join('');
return afPlanSwitchBar() + '' +
'<div class="toolbar" style="flex-wrap:wrap;align-items:center">' +
'<button class="btn btn-primary" onclick="afOpenPlan(\'\')" data-perm="devices">+ 新建计划</button>' +
'<button class="btn" onclick="afOpenCommentImport()" data-perm="devices">📥 导入评论</button>' +
'<button class="btn" onclick="afShowComments()" data-perm="devices">评论数据</button>' +
'<button class="btn" onclick="afRefreshAll(true)">刷新</button>' +
'<span class="text-muted">一条计划 = <b>干什么</b>(App + 动作组)· <b>给谁干</b>(账号库里勾号)· ' +
'<b>发什么</b>(每人几条)· <b>什么时候</b>(固定点 + 抖动)· <b>怎么跑</b>(并发/重试/失败处置);' +
'到点或点一下就跑,<b>只激活这些号所在的手机</b>。</span>' +
'</div>' +
'<div id="af-plan-preview" style="display:none;border:1px solid var(--border);border-radius:6px;padding:10px;margin:8px 0"></div>' +
'<table class="table"><thead><tr>' +
'<th style="width:190px">计划</th><th style="width:180px">干什么</th><th style="width:150px">给谁干</th>' +
'<th style="width:110px">发什么</th><th style="width:170px">什么时候</th><th style="width:130px">怎么跑</th>' +
'<th style="width:120px">上次</th><th>操作</th></tr></thead>' +
'<tbody>' + (rows || '<tr><td colspan="8" class="empty">还没有计划 —— 点「+ 新建计划」:' +
'选个动作组、勾几个号、定个时间,到点它自己跑</td></tr>') + '</tbody></table>' +
'<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-top:12px">' +
'<b>最近的计划运行</b> <span class="text-muted" style="font-size:12px">每次触发的成功/失败/跳过 —— 点「明细」看每个号跑了什么</span>' +
'<table class="table" style="margin-top:6px"><thead><tr>' +
'<th style="width:100px">时间</th><th>计划</th><th style="width:90px">结果</th>' +
'<th style="width:190px">账号</th><th style="width:70px">设备</th><th style="width:70px"></th>' +
'</tr></thead><tbody>' + (runs || '<tr><td colspan="6" class="empty">还没有运行记录</td></tr>') +
'</tbody></table>' +
'<div id="af-plan-run-detail"></div>' +
'</div>';
}
// ================== 评论数据:导入 / 列表 ==================
function afOpenCommentImport() {
if (document.getElementById('af-cm-imp')) return;
const ov = document.createElement('div');
ov.id = 'af-cm-imp';
ov.className = 'modal-overlay show';
ov.onclick = function (e) { if (e.target === ov) ov.remove(); };
ov.innerHTML = '<div class="modal" style="max-width:860px">' +
'<div class="modal-header"><h3>导入评论数据</h3>' +
'<button class="close" onclick="document.getElementById(\'af-cm-imp\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="help" style="margin-bottom:8px">每行一条:<b>视频链接 &nbsp;账号 &nbsp;评论内容</b>(制表符/逗号都行)。' +
'账号写账号库里的昵称或抖音号;同一个账号可以对多条视频各有一行。' +
'重复导入按「视频链接 + 账号」去重:未执行的更新,已评论/结果未知的跳过。<br>' +
'CSV 里评论内容带逗号/换行时要用引号包起来。<b>CSV 必须存成「CSV UTF-8」</b>' +
'(Excel 默认的普通 CSV/GBK 会把表情变成 ? 或直接丢掉);直接粘贴不受影响。' +
'导入报告会显示「含表情 N 条」,可用来核对表情有没有保留。</div>' +
'<div class="toolbar" style="margin-bottom:6px">' +
'<a class="btn btn-xs" href="/api/af/comments/template" target="_blank">⬇ 下载模板(CSV)</a>' +
'<span class="text-muted" style="font-size:12px">可以从 Excel 直接复制三列粘贴到下面</span></div>' +
'<div class="form-group"><label>粘贴表格(优先使用;有文件时以文件为准)</label>' +
'<textarea id="af-cm-text" class="form-control" rows="8" style="font-family:monospace" ' +
'placeholder="视频链接\t账号\t评论内容&#10;https://v.douyin.com/xxxxxx/\t周周苏州寻宝藏小店\t这家店我去过"></textarea></div>' +
'<div class="form-group"><label>或上传 CSV</label>' +
'<input type="file" class="form-control" id="af-cm-file" accept=".csv,text/csv"></div>' +
'<div id="af-cm-log" class="text-muted" style="font-size:12px;max-height:260px;overflow:auto"></div>' +
'</div>' +
'<div class="modal-footer">' +
'<button class="btn" onclick="document.getElementById(\'af-cm-imp\').remove()">关闭</button>' +
'<button class="btn" onclick="afDoCommentImport(1)">试导(只校验)</button>' +
'<button class="btn btn-primary" onclick="afDoCommentImport(0)">导入</button>' +
'</div></div>';
document.body.appendChild(ov);
}
async function afDoCommentImport(dry) {
const textEl = document.getElementById('af-cm-text');
const fileEl = document.getElementById('af-cm-file');
const log = document.getElementById('af-cm-log');
if (!textEl || !log) return;
const text = (textEl.value || '').trim();
const file = fileEl && fileEl.files ? fileEl.files[0] : null;
if (!text && !file) { showToast('先粘贴表格或选一个 CSV', 'error'); return; }
log.innerHTML = '⏳ ' + (dry ? '正在校验(不写库)…' : '正在导入…');
let res = null;
try {
if (file) {
const fd = new FormData();
fd.append('file', file);
if (dry) fd.append('dry_run', '1');
const r = await fetch('/api/af/comments/import', {
method: 'POST',
headers: {'X-CSRF-Token': (typeof _csrfToken !== 'undefined' ? _csrfToken : '')},
body: fd
});
res = await r.json();
} else {
res = await apiPost('/api/af/comments/import', {text: text, dry_run: !!dry});
}
} catch (e) {
log.innerHTML = '<span style="color:#c0392b">❌ 请求失败:' + esc(String(e)) + '</span>';
return;
}
if (!res || !res.ok) {
log.innerHTML = '<span style="color:#c0392b">❌ ' + esc((res && (res.error || res.msg)) || '导入失败') + '</span>';
return;
}
const rows = res.rows || [];
const head = (dry ? '试导' : '导入') + '完成:新增 ' + (res.added || 0) +
' / 更新 ' + (res.updated || 0) + ' / 跳过 ' + (res.skipped || 0) +
' / 错误 ' + (res.errors || 0) + ' / 含表情 ' + (res.emoji_rows || 0) + ' 条' +
(dry ? '(没有写库)' : '');
log.innerHTML = '<div style="color:' + ((res.errors || 0) ? '#b45309' : '#16a34a') +
';margin-bottom:4px"><b>' + esc(head) + '</b></div>' +
'<table class="table" style="font-size:12px"><thead><tr>' +
'<th style="width:45px">行</th><th style="width:110px">账号</th><th>视频链接</th>' +
'<th style="width:75px">结果</th><th>说明</th></tr></thead><tbody>' +
rows.map(function (x) {
const bad = x.action === 'error';
return '<tr><td>' + (x.line || '') + '</td><td>' + esc(x.account || '') + '</td>' +
'<td style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' +
esc(x.url || x.video_url || '') + '</td>' +
'<td style="' + (bad ? 'color:#c0392b' : '') + '">' + esc(x.action || '') + '</td>' +
'<td style="' + (bad ? 'color:#c0392b' : '') + '">' + esc(x.msg || x.error || '') + '</td></tr>';
}).join('') + '</tbody></table>';
if (!dry) showToast('评论数据已导入', 'success');
}
function _afCommentStatusLabel(st) {
const m = {pending: ['待评论', 'label-default'], running: ['执行中', 'label-warning'],
done: ['已评论', 'label-success'], failed: ['失败可重试', 'label-danger'],
unknown: ['结果未知', 'label-warning']};
const x = m[st] || [st || '—', 'label-default'];
return '<span class="label ' + x[1] + '">' + esc(x[0]) + '</span>';
}
async function afShowComments(account, status) {
account = account || '';
status = status || '';
const qs = '/api/af/comments?limit=500' +
(account ? ('&account=' + encodeURIComponent(account)) : '') +
(status ? ('&status=' + encodeURIComponent(status)) : '');
const r = await apiGet(qs);
if (!r || !r.ok) { showToast((r && r.error) || '读取评论数据失败', 'error'); return; }
const rows = r.rows || [];
const st = r.stats || {};
const counts = st.counts || {};
const old = document.getElementById('af-cm-list');
if (old) old.remove();
const ov = document.createElement('div');
ov.id = 'af-cm-list';
ov.className = 'modal-overlay show';
ov.onclick = function (e) { if (e.target === ov) ov.remove(); };
const opts = [['', '全部账号']].concat((r.accounts || []).map(function (a) {
return [a.account_name, a.account_name + '(' + a.pending + ' 条待评论)'];
}));
ov.innerHTML = '<div class="modal" style="max-width:1050px">' +
'<div class="modal-header"><h3>评论数据</h3>' +
'<button class="close" onclick="document.getElementById(\'af-cm-list\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="toolbar" style="flex-wrap:wrap;align-items:center;gap:8px">' +
'<span class="text-muted" style="font-size:12px">待评论 <b>' + (st.pending || 0) + '</b> 条 · ' +
'涉及 <b>' + (st.accounts || 0) + '</b> 个账号 · 已评论 ' + (counts.done || 0) +
' · 结果未知 ' + (counts.unknown || 0) + ' · 失败 ' + (counts.failed || 0) + '</span>' +
'<select class="form-control" style="width:210px" data-status="' + esc(status) + '" onchange="afShowComments(this.value, this.dataset.status||\'\')">' +
opts.map(function (o) {
return '<option value="' + esc(o[0]) + '"' + (o[0] === account ? ' selected' : '') + '>' + esc(o[1]) + '</option>';
}).join('') + '</select>' +
'<select class="form-control" style="width:130px" data-account="' + esc(account) + '" onchange="afShowComments(this.dataset.account||\'\', this.value)">' +
[['', '全部状态'], ['pending', '待评论'], ['failed', '失败可重试'],
['unknown', '结果未知'], ['done', '已评论'], ['running', '执行中']].map(function (o) {
return '<option value="' + o[0] + '"' + (o[0] === status ? ' selected' : '') + '>' + o[1] + '</option>';
}).join('') + '</select>' +
'<button class="btn btn-xs" onclick="afOpenCommentImport()">📥 导入评论</button>' +
'</div>' +
'<table class="table" style="font-size:12px;margin-top:8px"><thead><tr>' +
'<th style="width:120px">账号</th><th style="width:150px">视频链接</th><th>评论内容</th>' +
'<th style="width:90px">状态</th><th style="width:70px">尝试</th><th style="width:190px">操作</th>' +
'</tr></thead><tbody>' +
(rows.map(function (x) {
const url = x.video_url || '';
return '<tr><td>' + esc(x.account_name || '') + '</td>' +
'<td style="max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="' + esc(url) + '">' +
(url ? '<a href="' + esc(url) + '" target="_blank" rel="noopener">' + esc(url) + '</a>' : '—') + '</td>' +
'<td title="' + esc(x.comment_text || '') + '">' + esc((x.comment_text || '').slice(0, 80)) +
((x.comment_text || '').length > 80 ? '…' : '') + '</td>' +
'<td>' + _afCommentStatusLabel(x.status) + '</td>' +
'<td>' + (x.attempts || 0) + '</td>' +
'<td style="white-space:nowrap">' +
(x.status !== 'pending' ? '<button class="btn btn-xs" onclick="afCommentAction(\'' + esc(x.id) + '\',\'reset\')">重置</button>' : '') +
(x.status !== 'done' ? '<button class="btn btn-xs" onclick="afCommentAction(\'' + esc(x.id) + '\',\'done\')">标已发</button>' : '') +
'<button class="btn btn-xs" onclick="afCommentAction(\'' + esc(x.id) + '\',\'unknown\')">标未知</button>' +
'<button class="btn btn-xs btn-danger" onclick="afCommentDelete(\'' + esc(x.id) + '\')">删除</button>' +
'</td></tr>';
}).join('') || '<tr><td colspan="6" class="empty">还没有评论数据 —— 点「导入评论」粘贴表格</td></tr>') +
'</tbody></table></div>' +
'<div class="modal-footer"><button class="btn" onclick="document.getElementById(\'af-cm-list\').remove()">关闭</button></div></div>';
document.body.appendChild(ov);
}
async function afCommentAction(id, action) {
let r = null;
if (action === 'reset') r = await apiPost('/api/af/comments/' + encodeURIComponent(id) + '/reset', {});
else r = await apiPost('/api/af/comments/' + encodeURIComponent(id) + '/resolve', {result: action});
if (!r || !r.ok) { showToast((r && r.error) || '操作失败', 'error'); return; }
showToast(r.msg || '已更新', 'success');
afShowComments();
}
async function afCommentDelete(id) {
if (!confirm('删除这条评论数据?')) return;
const r = await apiDelete('/api/af/comments/' + encodeURIComponent(id));
if (!r || !r.ok) { showToast((r && r.error) || '删除失败', 'error'); return; }
showToast('已删除', 'success');
afShowComments();
}
function _afPlanStatus(s) {
const m = {done: '<span class="label label-success">全部完成</span>',
partial: '<span class="label label-warning">部分完成</span>',
failed: '<span class="label label-danger">失败</span>',
running: '<span class="label label-info">运行中</span>',
skipped: '<span class="label label-default">跳过</span>',
unknown: '<span class="label label-default">未知</span>'};
return m[s] || ('<span class="label label-default">' + esc(s || '') + '</span>');
}
// ---- 新建/编辑计划(一页向导)----
// 用户 2026-10-17 重定:**上面是时间和状态**;账号勾选里标「未发 N 条」;
// 动作不再是一个动作组,而是**账号下面的编排列表**(多段按顺序跑,可循环/条件/回主页)。
let _afPlanSegs = [];
let _afPlanCommentMode = false;
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 s = saved || {};
// 2026-10-31:默认用**全局切号参数**。老计划没有 use_global 字段也按全局走
// (否则元素一变就要一个个计划改)。要单独覆盖才显式存 use_global=false。
const useGlobal = s.use_global !== false;
_afPlanReady = {enabled: s.enabled === undefined ? true : !!s.enabled,
use_global: useGlobal};
if (!useGlobal) Object.assign(_afPlanReady, s, {use_global: false});
}
function afPlanReadySet(k, v) {
if (!_afPlanReady) _afPlanReady = {enabled: true, use_global: true};
if (k === 'use_global') {
if (v) {
_afPlanReady = {enabled: _afPlanReady.enabled !== false, use_global: true};
} else {
const d = _af.readyDefaults || {};
_afPlanReady = Object.assign({}, d, {enabled: _afPlanReady.enabled !== false,
use_global: false});
}
} else {
_afPlanReady[k] = v;
}
afPlanReadyRender();
}
function afPlanReadyRender() {
const box = document.getElementById('afp-ready');
if (!box) return;
const r = _afPlanReady || {};
const en = r.enabled !== false;
const useGlobal = r.use_global !== false;
const d = _af.readyDefaults || {};
const v = useGlobal ? Object.assign({}, d, {enabled: en}) : r;
const short = function (val) {
val = val || '';
return val.length > 44 ? (val.slice(0, 44) + '…') : (val || '(默认)');
};
box.innerHTML = '<div style="border:1px solid var(--border);border-radius:6px;padding:8px;margin-bottom:8px;background:#fafafa">' +
'<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">' +
'<b>🔒 内置 · 账号就绪(切号)</b>' +
'<label style="font-weight:400;font-size:12px"><input type="checkbox" ' + (en ? 'checked' : '') +
' onchange="afPlanReadySet(\'enabled\', this.checked)"> 启用</label>' +
'<label style="font-weight:400;font-size:12px"><input type="checkbox" ' + (useGlobal ? 'checked' : '') +
' onchange="afPlanReadySet(\'use_global\', this.checked)"> 使用全局切号参数</label>' +
(useGlobal
? '<button class="btn btn-xs" onclick="afOpenReadyEditor(\'global\')">编辑全局参数</button>'
: '<button class="btn btn-xs" onclick="afOpenReadyEditor(\'plan\')">编辑本计划参数</button>') +
'<span class="text-muted" style="font-size:11px">' +
(useGlobal ? '全局改了所有计划一起生效' : '本计划单独覆盖,不受全局改动影响') + '</span>' +
'</div>' +
(en
? ('<div class="text-muted" style="font-size:11px;margin-top:4px">' +
'点「我」(' + esc(v.me_selector_type || 'xpath') + ': ' + esc(short(v.me_selector_value)) + ')' +
' → 读名字 → 一样跳过 / 不一样才切;切后等 ' +
(v.wait_after === undefined ? 15 : v.wait_after) + ' 秒,重试 ' +
(v.max_attempts || 2) + ' 次;切不过去:' +
(v.on_fail === 'stop' ? '停本设备' : '跳过这个号') +
'</div>')
: '<div style="color:#c0392b;font-size:11px;margin-top:4px">' +
'已关闭内置切号 —— 请在下面的编排里放一个切号动作组,否则可能发到错误的号</div>') +
'</div>';
}
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 '<option value="' + esc(t[0]) + '"' + (String(cur || '') === t[0] ? ' selected' : '') + '>' +
esc(t[1]) + '</option>';
}).join('');
}
var _afReadyEditMode = 'plan';
async function afReloadReadyDefaults() {
const rd = await apiGet('/api/af/ready_defaults');
if (rd && rd.ok) _af.readyDefaults = rd.params || {};
if (document.getElementById('afp-ready')) afPlanReadyRender();
afRender();
}
function afOpenReadyEditor(mode) {
_afReadyEditMode = mode || 'plan';
const globalMode = _afReadyEditMode === 'global';
const gsw = ((((_af.profile || {}).params || {}).fleet || {}).switch) || {};
const d = _af.readyDefaults || {};
const r = globalMode ? {
switch_selector_type: gsw.entry_selector_type || gsw.switch_selector_type || d.switch_selector_type || '',
switch_selector_value: gsw.entry_selector_value || gsw.switch_selector_value || d.switch_selector_value || '',
name_selector_type: gsw.name_selector_type || d.name_selector_type || '',
name_selector_value: gsw.name_selector_value || d.name_selector_value || '',
me_selector_type: gsw.me_selector_type || d.me_selector_type || '',
me_selector_value: gsw.me_selector_value || d.me_selector_value || '',
timeout: gsw.timeout === undefined ? (d.timeout === undefined ? 8 : d.timeout) : gsw.timeout,
wait_after: gsw.wait_after === undefined ? (d.wait_after === undefined ? 15 : d.wait_after) : gsw.wait_after,
max_attempts: gsw.retries || d.max_attempts || 2,
on_login_page: gsw.on_login || d.on_login_page || 'stop',
on_fail: gsw.on_fail || d.on_fail || 'skip_account'
} : Object.assign({}, d, _afPlanReady || {}, {use_global: false});
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 = '<div class="modal" style="max-width:760px">' +
'<div class="modal-header"><h3>' +
(globalMode ? '全局切号参数(所有计划共用)' : '内置步骤参数 · 账号就绪(切号)') + '</h3>' +
'<button class="close" onclick="document.getElementById(\'af-ready-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="help" style="margin-bottom:8px">' +
(globalMode
? '这里是<b>全局</b>切号选择器:所有「使用全局切号参数」的计划都读这一份,元素变了只改这里一次。'
: '这里是<b>本计划</b>的切号覆盖:只影响这个计划。一般保持「使用全局切号参数」,除非本计划确实要不同选择器。') +
'</div>' +
(globalMode ? '' :
'<div class="form-check" style="margin-bottom:8px"><input type="checkbox" id="afr-enabled" ' +
(r.enabled !== false ? 'checked' : '') + '><label for="afr-enabled">启用内置切号</label></div>') +
'<div class="form-group"><label>进「切换账号」列表的入口</label>' +
'<div style="display:flex;gap:6px">' +
'<select class="form-control" id="afr-sw-type" style="width:170px">' + _afReadySelOpts(r.switch_selector_type) + '</select>' +
'<input class="form-control" id="afr-sw-val" value="' + esc(r.switch_selector_value || '') + '" placeholder="如 切换账号">' +
'</div></div>' +
'<div class="form-group"><label>底部「我」页签(⚠ 用精确 xpath,不要 descriptionContains=我)</label>' +
'<div style="display:flex;gap:6px">' +
'<select class="form-control" id="afr-me-type" style="width:170px">' + _afReadySelOpts(r.me_selector_type) + '</select>' +
'<input class="form-control" id="afr-me-val" value="' + esc(r.me_selector_value || '') + '">' +
'</div></div>' +
'<div class="form-group"><label>昵称控件(读到当前登录名)</label>' +
'<div style="display:flex;gap:6px">' +
'<select class="form-control" id="afr-name-type" style="width:170px">' + _afReadySelOpts(r.name_selector_type) + '</select>' +
'<input class="form-control" id="afr-name-val" value="' + esc(r.name_selector_value || '') + '">' +
'</div></div>' +
'<div class="form-row">' +
'<div class="form-group"><label>单个元素超时(秒)</label>' +
'<input class="form-control" type="number" min="1" max="120" id="afr-timeout" value="' + (r.timeout === undefined ? 8 : r.timeout) + '"></div>' +
'<div class="form-group"><label>切号后等待(秒)</label>' +
'<input class="form-control" type="number" min="0" max="120" id="afr-wait" value="' + (r.wait_after === undefined ? 15 : r.wait_after) + '"></div>' +
'<div class="form-group"><label>最多尝试</label>' +
'<input class="form-control" type="number" min="1" max="10" id="afr-attempts" value="' + (r.max_attempts || 2) + '"></div>' +
'</div>' +
'<div class="form-row">' +
'<div class="form-group"><label>停在登录页</label>' +
'<select class="form-control" id="afr-login">' +
'<option value="stop"' + ((r.on_login_page || 'stop') === 'stop' ? ' selected' : '') + '>停本设备</option>' +
'<option value="continue"' + (r.on_login_page === 'continue' ? ' selected' : '') + '>继续(只记一句)</option>' +
'</select></div>' +
'<div class="form-group"><label>切不过去</label>' +
'<select class="form-control" id="afr-fail">' +
'<option value="skip_account"' + ((r.on_fail || 'skip_account') === 'skip_account' ? ' selected' : '') + '>跳过这个号(推荐)</option>' +
'<option value="stop"' + (r.on_fail === 'stop' ? ' selected' : '') + '>停本设备</option>' +
'</select></div>' +
'</div>' +
'</div>' +
'<div class="modal-footer">' +
'<button class="btn" onclick="document.getElementById(\'af-ready-overlay\').remove()">取消</button>' +
'<button class="btn btn-primary" onclick="afSaveReadyEditor()">保存</button>' +
'</div></div>';
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); };
const r = {
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'
};
if (_afReadyEditMode === 'global') {
const p = _af.profile && _af.profile.params;
if (!p) { showToast('配置还没加载', 'error'); return; }
p.fleet = p.fleet || {};
p.fleet.switch = Object.assign({}, p.fleet.switch || {}, {
entry_selector_type: r.switch_selector_type,
entry_selector_value: r.switch_selector_value,
name_selector_type: r.name_selector_type,
name_selector_value: r.name_selector_value,
me_selector_type: r.me_selector_type,
me_selector_value: r.me_selector_value,
timeout: r.timeout, wait_after: r.wait_after, retries: r.max_attempts,
on_login: r.on_login_page, on_fail: r.on_fail
});
apiPost('/api/af/profile', {name: _af.profile.name, params: p}).then(async function (res) {
const ov = document.getElementById('af-ready-overlay');
if (ov) ov.remove();
if (!res || !res.ok) { showToast((res && res.error) || '保存失败', 'error'); return; }
showToast('全局切号参数已保存(所有使用全局的计划生效)', 'success');
await afReloadReadyDefaults();
});
return;
}
_afPlanReady = Object.assign({}, r, {enabled: c('afr-enabled'), use_global: false});
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 '<option value="' + esc(value) + '"' +
(String(current || '') === String(value) ? ' selected' : '') + '>' + esc(label) + '</option>';
}
function afPlanCommentToggle(on) {
_afPlanCommentMode = !!on;
if (on) {
_afPlanSegs.forEach(function (s) { s.publish = false; });
}
document.querySelectorAll('.afp-acc-video').forEach(function (el) {
el.style.display = on ? 'none' : 'inline';
});
document.querySelectorAll('.afp-acc-comment').forEach(function (el) {
el.style.display = on ? 'inline' : 'none';
});
const g = document.getElementById('afp-mat-group');
if (g) g.style.display = on ? 'none' : 'block';
afPlanSegsRender();
}
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 '<option value="' + esc(v) + '"' + (v === curVal ? ' selected' : '') + '>' +
esc(a.name) + ' · ' + esc(an) + '</option>';
}).join('');
const taskOpts = (_af.jobs || []).map(function (t) {
const an = _afPlanTaskAppName(t);
const v = 't:' + t.id;
return '<option value="' + esc(v) + '"' + (v === curVal ? ' selected' : '') + '>' +
esc(t.name) + (an ? ' · ' + esc(an) : '') + '</option>';
}).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 '<div class="afp-seg" data-i="' + i + '" style="border:1px solid var(--border);border-radius:6px;padding:8px;margin-bottom:6px">' +
'<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">' +
'<b style="min-width:24px">#' + (i + 1) + '</b>' +
'<select class="form-control" style="width:320px" onchange="afPlanSegPick(' + i + ',this.value)">' +
'<option value="">(选动作组 / 任务)</option>' +
'<optgroup label="动作组">' + actOpts + '</optgroup>' +
(taskOpts ? '<optgroup label="任务(只取步骤)">' + taskOpts + '</optgroup>' : '') +
'</select>' +
'<label style="font-weight:400;font-size:12px"><input type="checkbox" ' + (s.publish ? 'checked' : '') +
(_afPlanCommentMode ? ' disabled' : '') +
' onchange="afPlanSegSet(' + i + ',\'publish\',this.checked)"> 发布素材</label>' +
(s.publish ? ('<span style="font-size:12px">每号 <input class="form-control" style="width:60px;display:inline-block" ' +
'type="number" min="0" value="' + (s.per_account === undefined ? 1 : s.per_account) +
'" onchange="afPlanSegSet(' + i + ',\'per_account\',this.value)"> 条(0=全部)</span>') : '') +
(s.source === 'task'
? (function () {
const tj = (_af.jobs || []).find(function (x) { return x.id === s.task_id; }) || {};
const isComment = (tj.name || '').indexOf('评论') >= 0;
return isComment
? '<span style="color:#b45309;font-size:11px">评论任务:<b>不要勾「发布素材」</b>,评论数据由任务里的「循环评论」取</span>'
: '<span class="text-muted" style="font-size:11px">任务只做发布动作;推送/标记由计划补(任务里已有就不重复)</span>';
})()
: '') +
'<label style="font-weight:400;font-size:12px">循环 ' +
'<select class="form-control" style="width:86px;display:inline-block" onchange="afPlanSegSet(' + i + ',\'loop.mode\',this.value)">' +
_afPlanSel('none', '不循环', lm) + _afPlanSel('rounds', '按轮次', lm) + _afPlanSel('time', '按时长', lm) +
'</select>' +
(lm === 'none' ? '' :
' <input class="form-control" style="width:64px;display:inline-block" type="number" min="1" value="' + loopNum +
'" onchange="afPlanSegSet(' + i + ',\'' + (lm === 'time' ? 'loop.seconds' : 'loop.rounds') + '\',this.value)">' +
(lm === 'time' ? ' 秒' : ' 轮')) +
'</label>' +
'<label style="font-weight:400;font-size:12px">条件 ' +
'<select class="form-control" style="width:140px;display:inline-block" onchange="afPlanSegSet(' + i + ',\'when.mode\',this.value)">' +
_afPlanSel('none', '无', wm) + _afPlanSel('exists', '元素存在才执行', wm) + _afPlanSel('missing', '元素不存在才执行', wm) +
'</select></label>' +
'<label style="font-weight:400;font-size:12px">前 <select class="form-control" style="width:92px;display:inline-block" ' +
'onchange="afPlanSegSet(' + i + ',\'home_before\',this.value)">' + homeOpts(s.home_before) + '</select></label>' +
'<label style="font-weight:400;font-size:12px">后 <select class="form-control" style="width:92px;display:inline-block" ' +
'onchange="afPlanSegSet(' + i + ',\'home_after\',this.value)">' + homeOpts(s.home_after) + '</select></label>' +
'<span style="margin-left:auto;white-space:nowrap">' +
'<button class="btn btn-xs" onclick="afPlanSegMove(' + i + ',-1)"' + (i === 0 ? ' disabled' : '') + '>↑</button> ' +
'<button class="btn btn-xs" onclick="afPlanSegMove(' + i + ',1)"' + (i === _afPlanSegs.length - 1 ? ' disabled' : '') + '>↓</button> ' +
'<button class="btn btn-xs btn-danger" onclick="afPlanSegDel(' + i + ')">✕</button>' +
'</span>' +
'</div>' +
(wm === 'none' ? '' :
'<div style="display:flex;gap:6px;align-items:center;margin-top:6px;font-size:12px">' +
'元素 <select class="form-control" style="width:150px" onchange="afPlanSegSet(' + i + ',\'when.selector_type\',this.value)">' +
_afPlanSel('xpath', 'xpath', s.when.selector_type) +
_afPlanSel('text', 'text(等于)', s.when.selector_type) +
_afPlanSel('textContains', 'textContains(包含)', s.when.selector_type) +
_afPlanSel('description', 'description', s.when.selector_type) +
_afPlanSel('descriptionContains', 'descriptionContains', s.when.selector_type) +
_afPlanSel('resourceId', 'resourceId', s.when.selector_type) +
'</select>' +
'<input class="form-control" style="flex:1" placeholder="选择器 / 文本" value="' + esc(s.when.selector_value || '') + '" ' +
'oninput="afPlanSegSet(' + i + ',\'when.selector_value\',this.value)">' +
'<input class="form-control" style="width:170px" placeholder="说明(写日志用)" value="' + esc(s.when.what || '') + '" ' +
'oninput="afPlanSegSet(' + i + ',\'when.what\',this.value)">' +
'</div>') +
'</div>';
}
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 = _afPlanCommentMode ? false : !!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 commentMode = !!p.comment_mode;
_afPlanCommentMode = commentMode;
const pendingByName = {};
const commentByName = {};
(_af.accounts || []).forEach(function (a) {
pendingByName[a.name] = a.pending || 0;
commentByName[a.name] = a.comment_pending || 0;
});
// 账号勾选:按设备分组;视频计划标「未发 N 条」,评论计划标「待评论 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 ? '<span style="color:#16a34a">在线</span>'
: '<span class="text-muted">离线</span>')
: '<span style="color:#dc2626">未入池</span>';
const rows = (groups[dev] || []).slice().sort(function (a, b) {
const av = commentMode ? (commentByName[a.nickname] || 0) : (pendingByName[a.nickname] || 0);
const bv = commentMode ? (commentByName[b.nickname] || 0) : (pendingByName[b.nickname] || 0);
return bv - av;
});
return '<div style="margin-bottom:4px"><b>' + esc(dev) + '</b> ' + state + ' ' +
rows.map(function (r) {
const n = pendingByName[r.nickname] || 0;
const c = commentByName[r.nickname] || 0;
return '<label style="display:inline-flex;gap:4px;align-items:center;margin:2px 10px 2px 0;font-weight:400">' +
'<input type="checkbox" class="af-plan-acc" value="' + esc(r.id) + '" data-name="' + esc(r.nickname) + '"' +
(chosen[r.id] ? ' checked' : '') + '> ' + esc(r.nickname) +
' <span class="text-muted afp-acc-video" style="font-size:11px;display:' + (commentMode ? 'none' : 'inline') + '">未发 <b style="color:' +
(n ? '#b45309' : 'inherit') + '">' + n + '</b></span>' +
' <span class="text-muted afp-acc-comment" style="font-size:11px;display:' + (commentMode ? 'inline' : 'none') + '">待评论 <b style="color:' +
(c ? '#b45309' : 'inherit') + '">' + c + '</b></span></label>';
}).join('') + '</div>';
}).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 =
'<div class="modal" style="max-width:1040px">' +
'<div class="modal-header"><h3>' + (planId ? '编辑计划' : '新建计划') + '</h3>' +
'<button class="close" onclick="document.getElementById(\'af-plan-overlay\').remove()">&times;</button></div>' +
'<div class="modal-body">' +
'<div class="form-row">' +
'<div class="form-group"><label>计划名</label>' +
'<input class="form-control" id="afp-name" value="' + esc(p.name || '') + '" placeholder="如:每晚三批发布"></div>' +
'<div class="form-group form-check" style="align-self:center;margin-top:18px">' +
'<input type="checkbox" id="afp-on" ' + (p.enabled ? 'checked' : '') + '>' +
'<label for="afp-on">启用(到点自动跑;不勾就只能手动/试跑)</label></div>' +
'</div>' +
'<div class="form-group form-check">' +
'<input type="checkbox" id="afp-comment" ' + (commentMode ? 'checked' : '') +
' onchange="afPlanCommentToggle(this.checked)">' +
'<label for="afp-comment">评论计划(按「评论数据」显示待评论;不取视频素材)</label></div>' +
'<div class="form-group"><label>什么时候跑(固定点,可多个)</label>' +
'<input class="form-control" id="afp-points" value="' + esc((S.points || []).join(', ')) + '"' +
' placeholder="21:00, 14:30(留空 = 只手动跑)">' +
'<div class="help" style="margin:6px 0 0">抖动 <input id="afp-jitter" style="width:60px" type="number" min="0" step="1" value="' +
Math.round((S.jitter_sec || 0) / 60) + '"> 分钟' +
' 起止日期 <input id="afp-dfrom" type="date" value="' + esc(S.date_from || '') + '"> ~ ' +
'<input id="afp-dto" type="date" value="' + esc(S.date_to || '') + '"></div></div>' +
'<div class="form-group"><label>给谁干:勾要跑的账号(后面是当前未发 / 待评论条数)</label>' +
'<div style="max-height:180px;overflow:auto;border:1px solid var(--border);border-radius:6px;padding:8px">' +
(accBox || '<span class="text-muted">账号库是空的 —— 去「① 资产管理」导入/登记</span>') + '</div>' +
'<div class="help" style="margin:6px 0 0">勾几个号就只跑那几个;它们在哪台手机上由账号库决定(换机/换 IP 跟得上)。' +
'<button class="btn btn-xs" onclick="afPlanAllAcc(true)">全选</button>' +
'<button class="btn btn-xs" onclick="afPlanAllAcc(false)">全不选</button></div></div>' +
'<div class="form-group"><label>动作编排:这个号的**顺序流程**(可以好几个动作组)</label>' +
'<div class="help" style="margin:0 0 6px">每一行 = 一个动作组或任务;按 #1 → #2 → … 顺序跑。' +
'勾「发布素材」的段才从素材池取(每号几条写在行里);任务段也可以勾 —— 计划负责推送/标记,' +
'任务里已经带了的不会重复加。不勾的段只是跑动作(浏览/评论/进视频…)。' +
'「循环」只对这一行生效;「条件」= 元素存在/不存在才执行;「前/后 回主页」= 这段前后怎么回到首页。</div>' +
'<div id="afp-ready"></div>' +
'<div id="afp-segs"></div>' +
'<div><button class="btn btn-xs btn-primary" onclick="afPlanSegAdd()">+ 添加动作组</button></div></div>' +
'<div class="form-row">' +
'<div class="form-group" id="afp-mat-group" style="display:' + (commentMode ? 'none' : 'block') + '"><label>发什么(只作用于勾了「发布素材」的段;任务里已有推送/标记时计划不重复补)</label>' +
'<div style="font-size:12px;margin-bottom:4px">' +
'<label style="font-weight:400;margin-right:10px"><input type="radio" name="afp-matmode" value="pool"' +
((M.ids || []).length ? '' : ' checked') + ' onchange="afPlanMatMode()"> 未发布按序号取</label>' +
'<label style="font-weight:400;margin-left:14px"><input type="radio" name="afp-matmode" value="pick"' +
((M.ids || []).length ? ' checked' : '') + ' onchange="afPlanMatMode()"> 勾具体几条</label>' +
'</div>' +
'<div id="afp-pick" style="display:' + ((M.ids || []).length ? 'block' : 'none') +
';max-height:170px;overflow:auto;border:1px solid var(--border);border-radius:6px;padding:8px;font-size:12px"></div>' +
'<div class="help" style="margin:4px 0 0">条数在动作编排的「发布素材」里填;0 = 全部未发布;' +
'勾具体几条只发选中的(取不到会自动跳过)</div></div>' +
'<div class="form-group"><label>怎么跑</label>' +
'<div style="display:flex;gap:6px;flex-wrap:wrap">' +
'同时最多 <input class="form-control" style="width:60px" type="number" min="0" id="afp-par" value="' + (p.max_parallel || 0) + '"> 台' +
' 失败重试 <input class="form-control" style="width:60px" type="number" min="0" id="afp-retry" value="' + (R.max_attempts === undefined ? 2 : R.max_attempts) + '"> 次' +
' 间隔 <input class="form-control" style="width:70px" type="number" min="0" id="afp-delay" value="' + (R.delay === undefined ? 300 : R.delay) + '"> 秒' +
'</div>' +
'<div class="help" style="margin:4px 0 0">重试后仍不行 → <b>跳过这个号</b>,继续下一个(不拖累整批)</div></div>' +
'</div>' +
'<div class="form-group form-check">' +
'<input type="checkbox" id="afp-prep" ' + (p.prep_check === false ? '' : 'checked') + '>' +
'<label for="afp-prep">发布前准备(推荐):跑之前先查设备在线 → 打开 App 等到首页 → 读一眼现在登的是谁 → ' +
'<b>不一样才切号</b> → 回读确认;任一步不过就跳过这个号</label></div>' +
'<div class="form-group"><label>备注</label>' +
'<input class="form-control" id="afp-note" value="' + esc(p.note || '') + '"></div>' +
'<div id="afp-warn" class="help" style="color:#b45309"></div>' +
'</div>' +
'<div class="modal-footer">' +
(planId ? '<button class="btn" onclick="afPlanPreview(\'' + esc(planId) + '\')">只算不跑:看看会激活哪几台</button>' : '') +
'<button class="btn" onclick="document.getElementById(\'af-plan-overlay\').remove()">取消</button>' +
'<button class="btn btn-primary" onclick="afSavePlan(\'' + esc(planId || '') + '\')">保存</button>' +
'</div></div>';
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 = '<span class="text-muted">这些账号没有未发布的素材(先去资产管理上传/标未发布)</span>';
return;
}
box.innerHTML = items.map(function (x) {
const on = keep.indexOf(x.id) >= 0 ? ' checked' : '';
return '<label style="display:block;font-weight:400;margin:1px 0">' +
'<input type="checkbox" class="afp-item" value="' + esc(x.id) + '"' + on + '> ' +
esc(x.nickname) + ' #' + (x.seq || '') + ' ' + esc(x.title || x.video_name || '') + '</label>';
}).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 commentMode = !!(document.getElementById('afp-comment') &&
document.getElementById('afp-comment').checked);
if (commentMode) segs.forEach(function (s) { s.publish = false; });
const body = {
name: document.getElementById('afp-name').value.trim(),
app_id: first.app_id || '',
action_id: first.action_id,
comment_mode: commentMode,
segments: segs,
ready: (function () {
const r = _afPlanReady || {};
if (r.use_global !== false) {
return {enabled: r.enabled !== false, use_global: true};
}
return Object.assign({}, r, {use_global: false});
})(),
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 = '<b>现在跑的话会激活 ' + devs.length + ' 台手机 / ' +
devs.reduce(function (a, d) { return a + d.accounts.length; }, 0) + ' 个号</b>' +
(r.warning ? (' <span style="color:#b45309">(配置提醒:' + esc(r.warning) + ')</span>') : '') + '<br>' +
devs.map(function (d) {
return ' ✓ <b>' + esc(d.device_name || d.serial) + '</b> ' + esc(d.serial) + ' → ' +
esc(d.accounts.join('、'));
}).join('<br>') +
(skip.length ? ('<br><span style="color:#b45309">跑不了的 ' + skip.length + ' 个:</span><br>' +
skip.map(function (s) { return ' ✗ ' + esc(s.account) + ':' + esc(s.reason); }).join('<br>')) : '');
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 '<option value="' + esc(n) + '">' + esc(n) + '</option>';
}).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 = '<div style="border-top:1px dashed var(--border);margin-top:8px;padding-top:8px">' +
'<b>' + esc(d.plan_name || '') + '</b> · ' + esc(d.started_at || '') + ' → ' + esc(d.finished_at || '(跑着)') +
' · ' + _afPlanStatus(d.status) + '<table class="table" style="margin-top:4px">' +
'<thead><tr><th style="width:190px">账号</th><th style="width:150px">设备</th>' +
'<th style="width:90px">结果</th><th>说明 / 明细</th></tr></thead><tbody>' +
(d.detail || []).map(function (x) {
return '<tr><td>' + esc(x.account) + '</td>' +
'<td>' + esc(x.device_name || '') + '<div class="text-muted" style="font-size:11px">' + esc(x.serial || '') + '</div></td>' +
'<td>' + _afPlanStatus(x.status === 'done' ? 'done' : x.status) + '</td>' +
'<td style="font-size:12px">' + esc(x.reason || '') +
(x.ae_run_id ? (' <button class="btn btn-xs" onclick="afShowRun(\'' + esc(x.ae_run_id) + '\')">看步骤</button>') : '') +
'</td></tr>';
}).join('') + '</tbody></table></div>';
}
// ================== ④ 运行监测(计划 / 账号 / 设备 三个维度)==================
// 用户 2026-10-17:"所有计划任务,实际执行的情况汇报;发布成功以后,前面的素材要重新标记更新"。
// 素材状态由引擎自己回写(mark_release),这里只负责**把结果摆出来**。
// 设备画面**点开才取**(adb screencap,不抢 uiautomator),不做自动轮询。
function afRunBadge(s) {
const m = {done: '<span class="label label-success">完成</span>',
failed: '<span class="label label-danger">失败</span>',
running: '<span class="label label-info">运行中</span>',
skipped: '<span class="label label-default">跳过</span>',
unknown: '<span class="label label-warning">未知</span>'};
return m[s] || ('<span class="label label-default">' + esc(s || '') + '</span>');
}
// 一次 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 '<tr><td><b>' + esc(a) + '</b></td>' +
'<td>' + esc(r.device_name || r.serial || '') + '</td>' +
'<td>' + afRunBadge(r.status) + '</td>' +
'<td class="text-muted" style="font-size:12px">' + esc(r.started_at || '') + '</td>' +
'<td style="font-size:12px">发 ' + (t.published || 0) + ' / 共 ' + (t.items_total || 0) +
((t.failed ? ' / 失败 ' + t.failed : '') + (t.unknown ? ' / 未知 ' + t.unknown : '')) + '</td>' +
'<td><button class="btn btn-xs" onclick="afShowRun(\'' + esc(r.id) + '\')">明细</button></td></tr>';
}).join('');
// 计划维度:每次计划触发
const planRows = (_af.planRuns || []).slice(0, 20).map(function (r) {
return '<tr><td class="text-muted" style="font-size:12px">' + esc((r.started_at || '').slice(5, 16)) + '</td>' +
'<td>' + esc(r.plan_name) + '</td>' +
'<td style="font-size:12px">' + (r.trigger === 'cron' ? '到点' : r.trigger === 'try' ? '试跑' : '手动') + '</td>' +
'<td>' + _afPlanStatus(r.status) + '</td>' +
'<td style="font-size:12px">' + (r.ok_accounts || 0) + ' ✓ / ' + (r.failed_accounts || 0) + ' ✗ / ' +
(r.skipped_accounts || 0) + ' 跳过</td>' +
'<td>' + ((r.devices || []).length) + ' 台</td>' +
'<td><button class="btn btn-xs" onclick="afShowPlanRun(\'' + esc(r.id) + '\',\'af-mon-plan-detail\')">明细</button></td></tr>';
}).join('');
// 全部运行记录:一次 ae_run 拆成"每账号一行"(同一设备的一轮 → 多行,共用同一份步骤明细)
const runRows = [];
(_af.runs || []).forEach(function (r) {
const accs = _afRunAccountList(r);
(accs.length ? accs : ['']).forEach(function (a) {
runRows.push('<tr>' +
'<td class="text-muted">' + esc(r.started_at) + '</td>' +
'<td><b>' + esc(a) + '</b></td>' +
'<td>' + esc(r.device_name || r.serial || '') + '</td>' +
'<td>' + esc(_AF_STATUS[r.status] || r.status) + '</td>' +
'<td title="这是该设备这一轮的合计,不是单个号">' +
((r.totals && r.totals.published) || 0) + '/' + ((r.totals && r.totals.items_total) || 0) + '</td>' +
'<td class="text-muted" style="max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' +
esc((r.summary && r.summary[0] && r.summary[0].share_url) || '') + '</td>' +
'<td><button class="btn btn-xs" onclick="afShowRun(\'' + esc(r.id) + '\')">明细</button>' +
'<button class="btn btn-xs" onclick="afListLogs(\'' + esc(a) + '\',\'' + esc(r.date) + '\')">日志文件</button></td>' +
'</tr>');
});
});
const runRowsHtml = runRows.join('');
setTimeout(afMonLoadDevices, 0);
return '' +
'<div class="toolbar" style="flex-wrap:wrap">' +
'<button class="btn" onclick="afRefreshAll(true)">刷新</button>' +
'<span class="text-muted" style="font-size:12px">计划维度=每次触发;账号维度=每个号最近一轮;' +
'设备维度=每台现在在干什么(「看画面」点了才取,运行中也安全)</span></div>' +
'<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-bottom:10px">' +
'<b>📋 计划维度</b>' +
'<table class="table" style="margin-top:4px"><thead><tr>' +
'<th style="width:100px">时间</th><th>计划</th><th style="width:60px">触发</th>' +
'<th style="width:90px">结果</th><th style="width:150px">账号</th>' +
'<th style="width:55px">设备</th><th style="width:60px"></th></tr></thead><tbody>' +
(planRows || '<tr><td colspan="7" class="text-muted">还没有计划运行记录</td></tr>') +
'</tbody></table><div id="af-mon-plan-detail"></div></div>' +
'<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-bottom:10px">' +
'<b>👤 账号维度</b> <span class="text-muted" style="font-size:12px">每个账号最近一轮;' +
'同一台设备串行跑多个号时按账号拆开显示(素材数是该设备这一轮的合计)</span>' +
'<table class="table" style="margin-top:4px"><thead><tr>' +
'<th style="width:200px">账号</th><th style="width:160px">设备</th><th style="width:90px">结果</th>' +
'<th style="width:150px">时间</th><th style="width:180px">素材</th><th style="width:60px"></th></tr></thead><tbody>' +
(acctRows || '<tr><td colspan="6" class="text-muted">还没有账号运行记录</td></tr>') +
'</tbody></table></div>' +
'<div style="border:1px solid var(--border);border-radius:6px;padding:10px;margin-bottom:10px">' +
'<b>📱 设备维度</b> <span class="text-muted" style="font-size:12px">' +
'当前在跑什么;画面用 adb 截图,按需取</span>' +
'<div id="af-mon-dev"><div class="text-muted">加载设备状态…</div></div>' +
'<div id="af-mon-shot" style="margin-top:8px"></div></div>' +
'<div style="border:1px solid var(--border);border-radius:6px;padding:10px">' +
'<b>📜 全部运行记录</b> <span class="text-muted" style="font-size:12px">' +
'同一台设备跑多个号会按账号拆成多行(「明细」是同一份设备步骤);' +
'日志写到各自的账号文件夹 <code>_日志/&lt;日期&gt;/</code></span>' +
'<table class="table" style="margin-top:4px"><thead><tr><th>时间</th><th>账号</th><th>设备</th><th>结果</th>' +
'<th>已发/条目</th><th>分享链接</th><th></th></tr></thead>' +
'<tbody>' + (runRowsHtml || '<tr><td colspan="7" class="text-muted">还没有运行记录</td></tr>') + '</tbody></table>' +
'<div id="af-run-detail" style="margin-top:10px"></div>' +
'<div id="af-log-files" style="margin-top:10px"></div></div>';
}
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 = '<div class="text-muted">设备状态加载失败:' + esc((st && st.error) || '') + '</div>';
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 '<tr>' +
'<td><b>' + esc(d.device_name || d.serial) + '</b>' +
'<div class="text-muted" style="font-size:11px">' + esc(d.serial) + '</div></td>' +
'<td>' + (d.present
? (d.worker_status === 'running' ? '<span style="color:#2563eb">运行中</span>'
: d.worker_status === 'connecting' ? '<span style="color:#2563eb">连接中</span>'
: '<span style="color:#16a34a">空闲</span>')
: '<span class="text-muted">不在线</span>') + '</td>' +
'<td style="font-size:12px">' + esc(d.account || '—') + '</td>' +
'<td style="font-size:12px">' + esc(d.running_job || d.task_job || '—') +
(d.attempt ? (' <span class="text-muted">(' + d.attempt + ')</span>') : '') + '</td>' +
'<td style="font-size:12px">' + esc(d.current_action || '—') + pgTxt + '</td>' +
'<td class="text-muted" style="font-size:11px">' + esc((d.last_error || '').slice(0, 60)) + '</td>' +
'<td style="white-space:nowrap">' +
'<button class="btn btn-xs" onclick="afMonShot(\'' + esc(d.serial) + '\')">看画面</button>' +
(busy ? '<button class="btn btn-xs" onclick="afMonStop(\'' + esc(d.serial) + '\')">停止</button>' : '') +
'</td></tr>';
}).join('');
box.innerHTML = '<table class="table" style="margin-top:4px"><thead><tr>' +
'<th style="width:170px">设备</th><th style="width:70px">状态</th><th style="width:150px">当前账号</th>' +
'<th style="width:190px">任务</th><th style="width:210px">当前动作</th><th>最近错误</th><th style="width:120px"></th>' +
'</tr></thead><tbody>' + (rows || '<tr><td colspan="7" class="text-muted">没有设备</td></tr>') +
'</tbody></table>';
}
function afMonShot(serial) {
const box = document.getElementById('af-mon-shot');
if (!box) return;
box.innerHTML = '<div class="text-muted">⏳ 正在取 ' + esc(serial) + ' 的画面…</div>';
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 = '<span style="color:#c0392b">取画面失败(设备可能不在线)</span>';
};
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 = '<div class="text-muted">加载明细…</div>';
const r = await apiGet('/api/af/run/' + runId);
if (!r || !r.ok) { box.innerHTML = '<div class="text-muted">' + esc((r && r.error) || '加载失败') + '</div>'; return; }
const steps = (r.steps || []).map(s => `<tr>
<td class="text-muted">${esc(s.time)}</td><td>${esc(s.step_path)}</td><td>${esc(s.label)}</td>
<td>${esc(s.type)}</td><td>${esc(s.result)}</td><td>${esc(s.ms)}</td>
<td class="text-muted" style="max-width:280px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(s.detail)}</td>
</tr>`).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 = `<div class="section-title" style="font-size:13px">${_accTxt} · ${esc(r.run.started_at)}
· ${esc(_AF_STATUS[r.run.status] || r.run.status)} · ${(r.steps || []).length} 步</div>
<table class="table"><thead><tr><th>时间</th><th>路径</th><th>步骤</th><th>类型</th><th>结果</th><th>ms</th><th>详情</th></tr></thead>
<tbody>${steps || '<tr><td colspan="7" class="text-muted">这一步没记录(可能没跑到)</td></tr>'}</tbody></table>`;
}
async function afListLogs(account, date) {
const box = document.getElementById('af-log-files');
box.innerHTML = '<div class="text-muted">查日志文件…</div>';
const r = await apiGet('/api/af/logs?account=' + encodeURIComponent(account) +
'&date=' + encodeURIComponent(date || ''));
if (!r || !r.ok) { box.innerHTML = '<div class="text-muted">' + esc((r && r.error) || '加载失败') + '</div>'; return; }
const items = (r.files || []).map(f => `<div style="margin:2px 0">
<a href="/api/af/log?account=${encodeURIComponent(account)}&date=${encodeURIComponent(f.date)}&name=${encodeURIComponent(f.name)}"
target="_blank" style="color:var(--primary)">${esc(f.name)}</a>
<span class="text-muted" style="font-size:12px">${(f.size / 1024).toFixed(1)} KB · ${esc(f.mtime)}</span></div>`).join('');
box.innerHTML = `<div class="section-title" style="font-size:13px">${esc(account)} 的日志文件</div>
${items || '<div class="text-muted">还没有日志(跑一轮后就有了)</div>'}`;
}