cp_agent/server/web/index.html
2026-10-22 17:21:00 +08:00

839 lines
47 KiB
HTML
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.

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CP Bridge · ATX 设备列表平台</title>
<style>
:root {
--sidebar-bg: #1d232c; --sidebar-hover: #2a3340; --sidebar-active: #00b96b;
--bg: #f4f6f8; --card: #fff; --border: #e4e8ec;
--text: #232a33; --muted: #8a94a0; --primary: #00b96b; --primary-dark: #009e5a;
--danger: #e5484d; --terminal-bg: #1b1f26; --radius: 10px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: "Segoe UI", "Microsoft YaHei", sans-serif; background: var(--bg); color: var(--text); }
.app { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; }
/* ---------- 侧边栏 ---------- */
.sidebar { background: var(--sidebar-bg); color: #cdd5de; display: flex; flex-direction: column; position: sticky; top: 0; height: 100vh; }
.brand { padding: 20px 18px 14px; border-bottom: 1px solid rgba(255,255,255,.07); }
.brand h1 { font-size: 17px; color: #fff; letter-spacing: .5px; }
.brand small { color: var(--muted); font-size: 11px; }
.nav { flex: 1; padding: 10px 10px; overflow-y: auto; }
.nav-item { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 8px; cursor: pointer; font-size: 14px; margin-bottom: 2px; transition: background .15s, color .15s; }
.nav-item:hover { background: var(--sidebar-hover); color: #fff; }
.nav-item.active { background: var(--sidebar-active); color: #fff; font-weight: 600; }
.nav-item .ico { width: 18px; text-align: center; font-size: 15px; }
.sidebar-foot { padding: 14px 18px; font-size: 11px; color: var(--muted); border-top: 1px solid rgba(255,255,255,.07); }
/* ---------- 顶栏 ---------- */
.topbar { display: flex; align-items: center; justify-content: space-between; padding: 16px 24px 0; }
.topbar h2 { font-size: 20px; }
.topbar-right { display: flex; align-items: center; gap: 10px; }
.badge { font-size: 12px; padding: 4px 12px; border-radius: 999px; background: #eef1f4; color: var(--muted); }
.badge.on { background: #e2f7ec; color: #0a8f56; }
.badge.off { background: #fdecec; color: var(--danger); }
.device-picker select { padding: 7px 10px; border: 1px solid var(--border); border-radius: 8px; font-size: 13px; background: #fff; min-width: 180px; }
main { padding: 16px 24px 24px; }
.page { display: none; }
.page.active { display: block; }
/* ---------- 卡片 ---------- */
.card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); padding: 18px; margin-bottom: 16px; }
.card h3 { font-size: 14px; margin-bottom: 12px; color: var(--text); display: flex; align-items: center; justify-content: space-between; }
.hint { font-size: 12px; color: var(--muted); margin-bottom: 10px; }
/* ---------- 控件 ---------- */
.btn { background: var(--primary); color: #fff; border: none; border-radius: 8px; padding: 8px 16px; cursor: pointer; font-size: 13px; transition: background .15s; }
.btn:hover { background: var(--primary-dark); }
.btn:disabled { background: #c6ccd3; cursor: not-allowed; }
.btn.secondary { background: #fff; color: var(--text); border: 1px solid var(--border); }
.btn.secondary:hover { background: #f2f4f6; }
.btn.danger { background: var(--danger); }
.btn.sm { padding: 4px 12px; font-size: 12px; border-radius: 6px; }
input[type=text], textarea { padding: 7px 10px; border: 1px solid var(--border); border-radius: 8px; font-size: 13px; background: #fff; outline: none; }
input[type=text]:focus, textarea:focus { border-color: var(--primary); }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
/* ---------- 表格 ---------- */
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th, td { text-align: left; padding: 9px 10px; }
thead th { color: var(--muted); font-weight: 600; font-size: 12px; background: #f7f9fa; }
tbody tr { border-top: 1px solid #f0f2f4; cursor: default; }
tbody tr.cloud { background: #f0faf5; }
.online { color: #0a8f56; font-weight: 600; }
.offline { color: var(--danger); font-weight: 600; }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }
.dot.on { background: var(--primary); } .dot.off { background: var(--danger); }
/* ---------- 设备管理 ---------- */
.two-col { display: grid; grid-template-columns: minmax(280px, 420px) minmax(340px, 560px); gap: 16px; align-items: stretch; justify-content: start; }
.two-col > div { display: flex; min-height: 0; min-width: 0; }
.two-col > div > .card { width: 100%; display: flex; flex-direction: column; min-height: 0; }
@media (max-width: 1100px) {
.two-col { grid-template-columns: 1fr; }
.two-col > div { display: block; }
}
.card-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; margin-bottom: 12px; }
.card-head h3 { margin-bottom: 0; }
.shot-wrap { background: var(--terminal-bg); border-radius: 8px; min-height: 280px; display: flex; align-items: center; justify-content: center; }
.shot-wrap img { max-width: 100%; max-height: 640px; display: block; border-radius: 4px; }
.shot-wrap .empty { color: var(--muted); font-size: 13px; }
/* ---------- 应用列表 ---------- */
.app-list { max-height: 640px; overflow-y: auto; }
.app-item { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 6px; border-bottom: 1px solid #f2f4f6; font-size: 13px; }
.app-item:nth-child(odd) { background: #f5f7fa; }
.app-item:nth-child(even) { background: #fff; }
.app-item .pkg { color: var(--muted); font-size: 11px; }
.app-item .ver { color: var(--muted); font-size: 11px; margin-left: 6px; }
.file-list { overflow-x: auto; }
.file-list tbody tr:nth-child(odd) { background: #f5f7fa; }
.file-list tbody tr:nth-child(even) { background: #fff; }
.file-list tbody tr:hover { background: #edf3fb; }
.file-list th:first-child, .file-list td:first-child { width: 34px; text-align: center; }
.file-list td:last-child { white-space: nowrap; text-align: right; }
.file-name { color: var(--text); font-weight: 500; cursor: pointer; }
.file-name:hover { color: var(--primary-dark); }
.progress { height: 6px; background: #edf0f2; border-radius: 4px; overflow: hidden; margin-top: 8px; }
.progress > span { display: block; height: 100%; background: var(--primary); width: 0; transition: width .1s; }
/* ---------- 终端 / 日志 ---------- */
#terminal, #log-box { background: var(--terminal-bg); color: #d4d9e0; font-family: Consolas, monospace; font-size: 12px; padding: 12px; border-radius: 8px; height: 420px; overflow-y: auto; white-space: pre-wrap; word-break: break-all; }
.log-line .t { color: #6b7683; }
.log-line .k { font-weight: 600; }
.log-line .k.debug { color: #8a94a0; }
.log-line .k.info { color: #4cc2ff; }
.log-line .k.warning { color: #f5c451; }
.log-line .k.error, .log-line .k.critical { color: var(--danger); }
.log-line .logger { color: #8a94a0; }
.log-line .err { color: var(--danger); }
/* ---------- 详情 ---------- */
.detail-grid { display: grid; grid-template-columns: 130px 1fr; font-size: 13px; row-gap: 6px; }
.detail-grid th { color: var(--muted); font-weight: 500; text-align: left; }
.detail-grid td code { background: #f2f4f6; padding: 1px 6px; border-radius: 4px; font-size: 12px; }
.toast { position: fixed; bottom: 24px; right: 24px; background: #232a33; color: #fff; padding: 10px 18px; border-radius: 8px; font-size: 13px; opacity: 0; transition: opacity .25s; pointer-events: none; z-index: 99; }
.toast.show { opacity: .95; }
</style>
</head>
<body>
<div class="app">
<aside class="sidebar">
<div class="brand">
<h1>CP Bridge</h1>
<small>ATX 设备自动化平台</small>
</div>
<nav class="nav" id="nav">
<div class="nav-item active" data-page="devices"><span class="ico">▢</span>设备列表</div>
<div class="nav-item" data-page="screen"><span class="ico">▣</span>设备管理</div>
<div class="nav-item" data-page="files"><span class="ico">▤</span>文件管理</div>
<div class="nav-item" data-page="apps"><span class="ico">▦</span>应用管理</div>
<div class="nav-item" data-page="terminal"><span class="ico">&gt;_</span>远程终端</div>
<div class="nav-item" data-page="atx"><span class="ico">⚙</span>ATX 接口</div>
<div class="nav-item" data-page="logs"><span class="ico">▤</span>运行日志</div>
</nav>
<div class="sidebar-foot">执行核心 · phase1+</div>
</aside>
<div>
<div class="topbar">
<h2 id="page-title">设备列表</h2>
<div class="topbar-right">
<span class="device-picker">
<select id="device-select"><option value="">无在线设备</option></select>
</span>
<span class="badge" id="conn-status">连接中</span>
</div>
</div>
<main>
<!-- ================= 设备列表 ================= -->
<section class="page active" id="page-devices">
<div class="card">
<h3>设备列表 <button class="btn secondary sm" id="btn-refresh">刷新</button></h3>
<p class="hint">通过 Bridge App 接入的设备实时状态;点击行查看详情。</p>
<table>
<thead><tr><th></th><th>设备名称</th><th>系统</th><th>电量</th><th>内存</th><th>状态</th></tr></thead>
<tbody id="device-tbody"><tr><td colspan="6" class="hint">加载中...</td></tr></tbody>
</table>
</div>
<div class="card">
<h3>设备详情</h3>
<div id="device-detail" class="hint">点击上方设备行查看详情</div>
</div>
</section>
<!-- ================= 文件管理 ================= -->
<section class="page" id="page-files">
<div class="card">
<div class="card-head">
<h3>文件管理</h3>
<span class="row">
<button class="btn secondary sm" id="file-up">返回上级</button>
<button class="btn secondary sm" id="file-refresh">刷新</button>
<button class="btn secondary sm" id="file-mkdir">新建文件夹</button>
<label class="btn sm" for="file-upload">上传文件</label>
<button class="btn danger sm" id="file-delete-selected" disabled>删除所选</button>
<input id="file-upload" type="file" hidden>
</span>
</div>
<p class="hint">仅允许访问 <code>/sdcard/Download</code> 及其子目录。上传和下载按块传输。</p>
<div class="hint">当前位置:<code id="file-breadcrumb">/sdcard/Download</code></div>
<div class="progress"><span id="file-progress"></span></div>
<div id="file-status" class="hint" style="margin-top:8px"></div>
<div id="file-list" class="file-list hint">选择在线设备后加载文件</div>
</div>
</section>
<!-- ================= 应用管理 ================= -->
<section class="page" id="page-apps">
<div class="card">
<div class="card-head">
<h3>应用管理</h3>
<span class="row">
<input type="text" id="app-manager-filter" placeholder="按名称 / 包名过滤" style="width:190px" disabled>
<button class="btn secondary sm" id="app-manager-refresh" disabled>刷新列表</button>
<label class="btn sm" for="apk-install">上传 APK 安装</label>
<input id="apk-install" type="file" accept=".apk,application/vnd.android.package-archive" hidden>
</span>
</div>
<p class="hint">支持启动和卸载应用。APK 会先上传到设备的 <code>/sdcard/Download</code>。</p>
<div class="progress"><span id="apk-progress"></span></div>
<div id="apk-status" class="hint" style="margin-top:8px"></div>
<div id="app-manager-list" class="app-list hint">选择在线设备后加载应用</div>
</div>
</section>
<!-- ================= 设备管理 ================= -->
<section class="page" id="page-screen">
<div class="two-col">
<div>
<div class="card">
<div class="card-head">
<h3>屏幕画面</h3>
<span class="row">
<span class="hint" id="shot-status"></span>
<button class="btn secondary sm" id="btn-shot-auto">自动刷新: 开</button>
<button class="btn sm" id="btn-shot">立即截图</button>
</span>
</div>
<p class="hint">每 5 秒自动刷新一次(atx-agent /screenshot,Base64 传输)。</p>
<div class="shot-wrap" id="shot-box"><span class="empty">选择在线设备后显示屏幕画面</span></div>
</div>
</div>
<div>
<div class="card">
<div class="card-head">
<h3>应用列表</h3>
<span class="row">
<input type="text" id="app-filter" placeholder="按名称 / 包名过滤" style="width:160px" disabled>
<button class="btn sm" id="btn-apps" disabled>加载应用列表</button>
</span>
</div>
<p class="hint">显示设备上可启动的应用,点击「启动」拉起(通过 am start,不受后台启动限制)。</p>
<div id="app-list" class="app-list hint">点击「加载应用列表」获取设备上可启动的应用</div>
</div>
</div>
</div>
</section>
<!-- ================= 远程终端 ================= -->
<section class="page" id="page-terminal">
<div class="card">
<h3>远程 Shell</h3>
<div class="row" style="margin-bottom:10px">
<input type="text" id="cmd-input" placeholder="输入 shell 命令,如 ls /sdcard" style="flex:1;min-width:300px" disabled>
<button class="btn" id="btn-exec" disabled>执行</button>
</div>
<div id="terminal">等待连接服务器...\n</div>
</div>
</section>
<!-- ================= ATX 接口 ================= -->
<section class="page" id="page-atx">
<div class="card">
<h3>ATX 接口调试</h3>
<p class="hint">直接调用设备端 atx-agent 能力(由 Bridge 映射)。常用:atx.version / atx.dumpHierarchy / atx.pidof / atx.procList / atx.rotation / atx.wlanIp / atx.packages / atx.service / atx.jsonrpc / atx.fileInfo 等,完整表见 server/README.md。</p>
<div class="row" style="margin-bottom:10px">
<input type="text" id="atx-action" placeholder="action,如 atx.version" style="width:220px">
<input type="text" id="atx-params" placeholder='JSON 参数,如 {"package":"com.android.settings"}' style="flex:1;min-width:280px">
<button class="btn" id="btn-atx">调用</button>
</div>
<div class="row" style="margin-bottom:10px">
<button class="btn secondary sm" data-quick='["atx.version",{}]'>version</button>
<button class="btn secondary sm" data-quick='["atx.rotation",{}]'>rotation</button>
<button class="btn secondary sm" data-quick='["atx.wlanIp",{}]'>wlanIp</button>
<button class="btn secondary sm" data-quick='["atx.procList",{}]'>procList</button>
<button class="btn secondary sm" data-quick='["atx.packages",{}]'>packages</button>
<button class="btn secondary sm" data-quick='["atx.service",{"name":"uiautomator","op":"status"}]'>uiautomator 状态</button>
<button class="btn secondary sm" data-quick='["atx.service",{"name":"uiautomator","op":"start"}]'>uiautomator 启动</button>
<button class="btn secondary sm" data-quick='["atx.dumpHierarchy",{}]'>dumpHierarchy</button>
</div>
<div id="terminal2" style="background:var(--terminal-bg);color:#d4d9e0;font-family:Consolas,monospace;font-size:12px;padding:12px;border-radius:8px;height:380px;overflow-y:auto;white-space:pre-wrap;word-break:break-all;">调用结果将显示在这里\n</div>
</div>
</section>
<!-- ================= 运行日志 ================= -->
<section class="page" id="page-logs">
<div class="card">
<h3>运行日志 <button class="btn secondary sm" id="btn-log-clear">清空显示</button></h3>
<p class="hint">服务器进程日志:启动、访问、警告与异常(服务端保留最近 500 条,页面实时推送追加)。</p>
<div id="log-box"><span class="hint">加载中...</span></div>
</div>
</section>
</main>
</div>
</div>
<div class="toast" id="toast"></div>
<script>
const state = { ws: null, devices: [], selected: null, reqSeq: 0, pending: {},
shotAuto: true, shotBusy: false, shotTimer: null, apps: null, launching: null,
logs: [], logsCleared: false, filePath: '', managerApps: null, managerLaunching: null, managerUninstalling: null,
selectionVersion: 0, selectedFilePaths: new Set(), deletingSelectedFiles: false };
const $ = id => document.getElementById(id);
function toast(msg) {
const t = $('toast'); t.textContent = msg; t.classList.add('show');
clearTimeout(t._h); t._h = setTimeout(() => t.classList.remove('show'), 2200);
}
function log(text, term) {
const t = $(term || 'terminal');
const line = typeof text === 'string' ? text : JSON.stringify(text, null, 2);
t.textContent += line + '\n';
t.scrollTop = t.scrollHeight;
}
function send(action, payload, deviceId, timeoutMs) {
return new Promise((resolve, reject) => {
if (!state.ws || state.ws.readyState !== 1) return reject(new Error('WebSocket 未连接'));
const id = 'ui-' + (++state.reqSeq);
state.pending[id] = { resolve, reject };
state.ws.send(JSON.stringify({ id, type: 'command', action, deviceId, payload }));
if (timeoutMs) setTimeout(() => {
if (state.pending[id]) { delete state.pending[id]; reject(new Error('请求超时')); }
}, timeoutMs);
});
}
// ---------------- 导航 ----------------
const PAGE_TITLES = { devices: '设备列表', screen: '设备管理', files: '文件管理', apps: '应用管理', terminal: '远程终端', atx: 'ATX 接口', logs: '运行日志' };
document.querySelectorAll('.nav-item').forEach(item => {
item.onclick = () => {
document.querySelectorAll('.nav-item').forEach(i => i.classList.remove('active'));
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
item.classList.add('active');
$('page-' + item.dataset.page).classList.add('active');
$('page-title').textContent = PAGE_TITLES[item.dataset.page];
if (item.dataset.page === 'screen' && state.shotAuto) captureShot();
if (item.dataset.page === 'files') loadFiles();
if (item.dataset.page === 'apps') loadManagerApps();
if (item.dataset.page === 'logs') loadLogs();
};
});
// ---------------- 设备列表 ----------------
function renderDevices() {
const tbody = $('device-tbody');
if (!state.devices.length) {
tbody.innerHTML = '<tr><td colspan="6" class="hint">暂无设备(等待手机接入)</td></tr>';
} else {
tbody.innerHTML = state.devices.map(d => {
const hb = d.heartbeat || {};
const cell = v => v != null ? v + '%' : '-';
return `<tr class="${d.online ? 'cloud' : ''}" onclick="selectDevice('${d.deviceId}')" style="cursor:pointer">
<td><span class="dot ${d.online ? 'on' : 'off'}"></span></td>
<td>${escapeHtml(d.deviceName || d.deviceId)}<br><span class="hint">${d.deviceId}</span></td>
<td>${d.osVersion || '-'}</td>
<td>${cell(hb.battery)}</td>
<td>${cell(hb.memory)}</td>
<td class="${d.online ? 'online' : 'offline'}">${d.online ? '在线' : '离线'}</td>
</tr>`;
}).join('');
}
const sel = $('device-select');
const previousDeviceId = sel.value || state.selected;
const online = state.devices.filter(d => d.online);
sel.innerHTML = online.length
? online.map(d => `<option value="${d.deviceId}">${escapeHtml(d.deviceName || d.deviceId)}</option>`).join('')
: '<option value="">无在线设备</option>';
const selectedDeviceId = online.some(d => d.deviceId === previousDeviceId)
? previousDeviceId
: (online[0]?.deviceId || '');
sel.value = selectedDeviceId;
const selectionChanged = state.selected !== selectedDeviceId;
updateControls();
if (selectionChanged) window.selectDevice(selectedDeviceId);
}
function updateControls() {
const has = state.devices.some(d => d.online);
['btn-exec', 'btn-apps', 'cmd-input', 'app-filter', 'file-up', 'file-refresh', 'file-mkdir', 'file-upload', 'file-delete-selected',
'app-manager-filter', 'app-manager-refresh', 'apk-install'].forEach(id => { if ($(id)) $(id).disabled = !has; });
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
window.selectDevice = async function(deviceId) {
const selectionVersion = ++state.selectionVersion;
state.selected = deviceId;
state.filePath = '';
state.apps = null;
state.managerApps = null;
renderApps();
renderManagerApps();
$('file-breadcrumb').textContent = '/sdcard/Download';
$('file-list').className = 'file-list hint';
$('file-list').textContent = deviceId ? '正在加载文件列表...' : '选择在线设备后加载文件';
$('file-status').textContent = '';
$('app-manager-list').textContent = deviceId ? '正在加载应用列表...' : '选择在线设备后加载应用';
$('apk-status').textContent = '';
$('shot-box').innerHTML = '<span class="empty">正在加载所选设备截图...</span>';
$('shot-status').textContent = '';
$('device-detail').textContent = deviceId ? '加载中...' : '选择在线设备后查看详情';
if (!deviceId) return;
if (Array.from($('device-select').options).some(option => option.value === deviceId)) {
$('device-select').value = deviceId;
}
try {
const res = await send('device.detail', {}, deviceId);
if (selectionVersion !== state.selectionVersion) return;
const d = res.device;
$('device-detail').innerHTML = `<div class="detail-grid">
<th>deviceId</th><td><code>${d.device_id}</code></td>
<th>名称</th><td>${escapeHtml(d.device_name || '-')}</td>
<th>系统</th><td>${d.os_version || '-'} (SDK ${d.sdk_version || '-'})</td>
<th>在线</th><td class="${d.online ? 'online' : 'offline'}">${d.online ? '在线' : '离线'}</td>
<th>最近心跳</th><td>${d.last_heartbeat ? new Date(d.last_heartbeat * 1000).toLocaleString() : '-'}</td>
<th>心跳数据</th><td><code>${escapeHtml(JSON.stringify(d.heartbeat || {}))}</code></td>
</div>`;
if ($('device-select').value !== deviceId) $('device-select').value = deviceId;
} catch (e) {
if (selectionVersion !== state.selectionVersion) return;
$('device-detail').textContent = '加载失败: ' + e.message;
}
// 切换设备后刷新所有设备相关页面;截图切换时立即更新,不受自动刷新开关影响。
loadApps(deviceId);
loadFiles(deviceId);
loadManagerApps(deviceId);
captureShot();
};
$('device-select').onchange = () => {
window.selectDevice($('device-select').value);
};
function refreshList() {
send('device.list', {}).then(res => { state.devices = res.devices || []; renderDevices(); })
.catch(e => toast('刷新设备列表失败: ' + e.message));
}
// ---------------- 屏幕监控 ----------------
function scheduleShot(intervalMs) {
clearTimeout(state.shotTimer);
state.shotTimer = setTimeout(captureShot, intervalMs);
}
async function captureShot() {
clearTimeout(state.shotTimer);
const deviceId = $('device-select').value;
if (!deviceId || !state.devices.some(d => d.deviceId === deviceId && d.online)) {
$('shot-status').textContent = '';
scheduleShot(5000);
return;
}
if (state.shotBusy) { scheduleShot(5000); return; }
state.shotBusy = true;
try {
const res = await send('screen.capture', {}, deviceId, 35000);
if ($('device-select').value !== deviceId) return;
$('shot-box').innerHTML = `<img src="data:image/${res.format || 'png'};base64,${res.image}" alt="screen">`;
$('shot-status').textContent = '更新于 ' + new Date().toLocaleTimeString();
} catch (e) {
if ($('device-select').value !== deviceId) return;
$('shot-status').textContent = '截图失败: ' + e.message;
} finally {
state.shotBusy = false;
if (state.shotAuto) scheduleShot(5000);
}
}
$('btn-shot').onclick = captureShot;
$('btn-shot-auto').onclick = () => {
state.shotAuto = !state.shotAuto;
$('btn-shot-auto').textContent = '自动刷新: ' + (state.shotAuto ? '开' : '关');
if (state.shotAuto) captureShot();
else { clearTimeout(state.shotTimer); state.shotTimer = null; }
};
// ---------------- 应用管理 ----------------
function renderApps() {
const box = $('app-list');
if (!state.apps) { box.className = 'app-list hint'; box.textContent = '点击「加载应用列表」获取设备上可启动的应用'; return; }
const kw = $('app-filter').value.trim().toLowerCase();
const items = state.apps.filter(a => !kw ||
a.name.toLowerCase().includes(kw) || a.package.toLowerCase().includes(kw) ||
(a.versionName || '').toLowerCase().includes(kw));
box.className = 'app-list';
if (!items.length) { box.innerHTML = '<span class="hint">无匹配应用</span>'; return; }
box.innerHTML = items.map(a => `
<div class="app-item">
<div>${escapeHtml(a.name)}${a.versionName ? `<span class="ver">v${escapeHtml(a.versionName)}${a.versionCode ? ' (' + a.versionCode + ')' : ''}</span>` : ''}<br><span class="pkg">${a.package}</span></div>
<button class="btn sm ${state.launching === a.package ? '' : 'secondary'}" ${state.launching === a.package ? 'disabled' : ''}
onclick="launchApp('${a.package}')">${state.launching === a.package ? '启动中...' : '启动'}</button>
</div>`).join('');
}
async function loadApps(deviceId = $('device-select').value) {
if (!deviceId) return;
const box = $('app-list');
box.className = 'app-list hint';
box.textContent = '加载中...';
try {
const res = await send('app.list', {}, deviceId, 35000);
if ($('device-select').value !== deviceId) return;
state.apps = Object.entries(res || {}).map(([package_, info]) => ({
package: package_,
name: info.name || package_,
versionName: info.versionName || '',
versionCode: info.versionCode || 0,
}));
renderApps();
} catch (e) {
if ($('device-select').value !== deviceId) return;
box.textContent = '加载失败: ' + e.message;
state.apps = null;
}
}
$('btn-apps').onclick = loadApps;
$('app-filter').addEventListener('input', renderApps);
window.launchApp = async function(pkg) {
const deviceId = $('device-select').value;
state.launching = pkg;
renderApps();
try {
await send('app.launch', { package: pkg }, deviceId, 20000);
toast('已启动 ' + pkg);
} catch (e) {
toast('启动失败: ' + e.message);
} finally {
state.launching = null;
renderApps();
}
};
// ---------------- 文件管理 ----------------
const FILE_CHUNK = 64 * 1024;
function transferId(prefix) { return prefix + '-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8); }
function fileLabel(path) { return path ? '/sdcard/Download/' + path : '/sdcard/Download'; }
function setProgress(id, value, status) { $(id).style.width = Math.max(0, Math.min(100, value)) + '%'; if (status != null) $(id.replace('file-progress', 'file-status').replace('apk-progress', 'apk-status')).textContent = status; }
function currentDevice() { const id = $('device-select').value; if (!id) throw new Error('无在线设备'); return id; }
function joinFilePath(name) { return state.filePath ? state.filePath + '/' + name : name; }
// Incremental SHA-256 keeps memory bounded while hashing large File objects.
class Sha256 {
constructor() {
this.h = new Uint32Array([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]);
this.k = new Uint32Array([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]);
this.buffer = new Uint8Array(64);
this.bufferLength = 0;
this.bytesHashed = 0;
this.finished = false;
}
update(input) {
if (this.finished) throw new Error('SHA-256 已结束');
const data = input instanceof Uint8Array ? input : new Uint8Array(input);
this.bytesHashed += data.length;
let pos = 0;
while (pos < data.length) {
const take = Math.min(64 - this.bufferLength, data.length - pos);
this.buffer.set(data.subarray(pos, pos + take), this.bufferLength);
this.bufferLength += take;
pos += take;
if (this.bufferLength === 64) { this.compress(this.buffer); this.bufferLength = 0; }
}
return this;
}
compress(block) {
const w = new Uint32Array(64), view = new DataView(block.buffer, block.byteOffset, 64);
for (let i = 0; i < 16; i++) w[i] = view.getUint32(i * 4);
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
for (let i = 16; i < 64; i++) {
const x = w[i - 15], y = w[i - 2];
const s0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3), s1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10);
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
}
let [a,b,c,d,e,f,g,h] = this.h;
for (let i = 0; i < 64; i++) {
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25), ch = (e & f) ^ (~e & g);
const t1 = (h + s1 + ch + this.k[i] + w[i]) >>> 0;
const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22), maj = (a & b) ^ (a & c) ^ (b & c);
const t2 = (s0 + maj) >>> 0;
h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
}
const v = [a,b,c,d,e,f,g,h];
for (let i = 0; i < 8; i++) this.h[i] = (this.h[i] + v[i]) >>> 0;
}
digest() {
if (this.finished) throw new Error('SHA-256 已结束');
this.finished = true;
const bitLength = this.bytesHashed * 8;
const paddedLength = this.bufferLength < 56 ? 64 : 128;
const tail = new Uint8Array(paddedLength);
tail.set(this.buffer.subarray(0, this.bufferLength));
tail[this.bufferLength] = 0x80;
const view = new DataView(tail.buffer);
view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000));
view.setUint32(paddedLength - 4, bitLength >>> 0);
for (let offset = 0; offset < paddedLength; offset += 64) this.compress(tail.subarray(offset, offset + 64));
return Array.from(this.h, n => n.toString(16).padStart(8, '0')).join('');
}
}
async function loadFiles(deviceId = $('device-select').value) {
const box = $('file-list');
const requestedPath = state.filePath;
state.selectedFilePaths.clear();
updateBulkDeleteButton();
try {
const result = await send('file.list', { path: requestedPath }, deviceId, 35000);
if ($('device-select').value !== deviceId || state.filePath !== requestedPath) return;
$('file-breadcrumb').textContent = fileLabel(result.path || state.filePath);
const entries = [...(result.entries || [])].sort((a, b) =>
(a.type === 'directory' ? 0 : 1) - (b.type === 'directory' ? 0 : 1));
box.className = 'file-list';
if (!entries.length) { box.innerHTML = '<span class="hint">目录为空</span>'; return; }
box.innerHTML = `<table><thead><tr><th><input type="checkbox" id="file-select-all" aria-label="选择当前目录所有条目"></th><th>名称</th><th>类型</th><th>大小</th><th>更新时间</th><th>操作</th></tr></thead><tbody>${entries.map(entry => {
const encoded = encodeURIComponent(entry.path);
const size = entry.type === 'directory' ? '-' : ((Number(entry.size || 0) / 1024).toFixed(1) + ' KiB');
return `<tr><td><input type="checkbox" class="file-entry-select" data-path="${escapeHtml(entry.path)}" aria-label="选择 ${escapeHtml(entry.name)}"></td><td><span class="file-name" onclick="fileOpen('${encoded}', '${entry.type}')">${entry.type === 'directory' ? '📁 ' : '📄 '}${escapeHtml(entry.name)}</span></td><td>${entry.type === 'directory' ? '目录' : '文件'}</td><td>${size}</td><td>${escapeHtml(entry.modifiedAt || '-')}</td><td>${entry.type === 'directory' ? '' : `<button class="btn secondary sm" onclick="fileDownload('${encoded}', '${encodeURIComponent(entry.name)}')">下载</button>`} <button class="btn secondary sm" onclick="fileRename('${encoded}', '${encodeURIComponent(entry.name)}')">重命名</button> <button class="btn danger sm" onclick="fileDelete('${encoded}')">删除</button></td></tr>`;
}).join('')}</tbody></table>`;
updateBulkDeleteButton();
} catch (e) {
if ($('device-select').value !== deviceId || state.filePath !== requestedPath) return;
box.className = 'file-list hint'; box.textContent = '加载失败: ' + e.message;
}
}
function updateBulkDeleteButton() {
const button = $('file-delete-selected');
const count = state.selectedFilePaths.size;
const selectedDeviceOnline = state.devices.some(device =>
device.deviceId === $('device-select').value && device.online);
button.textContent = count ? `删除所选 (${count})` : '删除所选';
button.disabled = !count || state.deletingSelectedFiles || !selectedDeviceOnline;
const selectAll = $('file-select-all');
if (selectAll) {
const checkboxes = Array.from($('file-list').querySelectorAll('.file-entry-select'));
const checked = checkboxes.filter(item => item.checked).length;
selectAll.checked = checkboxes.length > 0 && checked === checkboxes.length;
selectAll.indeterminate = checked > 0 && checked < checkboxes.length;
}
}
$('file-list').addEventListener('change', event => {
const target = event.target;
if (target.id === 'file-select-all') {
$('file-list').querySelectorAll('.file-entry-select').forEach(item => {
item.checked = target.checked;
if (target.checked) state.selectedFilePaths.add(item.dataset.path);
else state.selectedFilePaths.delete(item.dataset.path);
});
} else if (target.classList.contains('file-entry-select')) {
if (target.checked) state.selectedFilePaths.add(target.dataset.path);
else state.selectedFilePaths.delete(target.dataset.path);
} else return;
updateBulkDeleteButton();
});
$('file-delete-selected').onclick = async () => {
const paths = Array.from(state.selectedFilePaths);
if (!paths.length || !confirm(`确认删除所选 ${paths.length} 个文件或文件夹?此操作不可撤销。`)) return;
const deviceId = currentDevice();
state.deletingSelectedFiles = true;
updateBulkDeleteButton();
let deleted = 0, failed = 0;
for (const path of paths) {
try { await send('file.delete', { path }, deviceId, 30000); deleted++; }
catch (_) { failed++; }
}
state.deletingSelectedFiles = false;
await loadFiles(deviceId);
toast(failed ? `已删除 ${deleted} 项,${failed} 项失败` : `已删除 ${deleted} 项`);
};
window.fileOpen = (encoded, type) => { if (type === 'directory') { state.filePath = decodeURIComponent(encoded); loadFiles(); } };
$('file-up').onclick = () => { if (state.filePath) { state.filePath = state.filePath.split('/').slice(0, -1).join('/'); loadFiles(); } };
$('file-refresh').onclick = loadFiles;
$('file-mkdir').onclick = async () => { const name = prompt('请输入文件夹名称'); if (!name) return; try { await send('file.mkdir', { path: joinFilePath(name) }, currentDevice(), 30000); await loadFiles(); } catch (e) { toast('新建失败: ' + e.message); } };
window.fileRename = async (encoded, encodedName) => { const oldPath = decodeURIComponent(encoded); const name = prompt('请输入新名称', decodeURIComponent(encodedName)); if (!name) return; const target = state.filePath ? state.filePath + '/' + name : name; try { await send('file.rename', { path: oldPath, newPath: target }, currentDevice(), 30000); await loadFiles(); } catch (e) { toast('重命名失败: ' + e.message); } };
window.fileDelete = async encoded => { const path = decodeURIComponent(encoded); if (!confirm('确认删除 ' + fileLabel(path) + '?此操作不可撤销。')) return; try { await send('file.delete', { path }, currentDevice(), 30000); await loadFiles(); } catch (e) { toast('删除失败: ' + e.message); } };
function base64(buffer) { const bytes = new Uint8Array(buffer); let result = ''; for (let i = 0; i < bytes.length; i += 0x8000) result += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(result); }
async function uploadFile(file, targetPath, progressId, statusId) {
const deviceId = currentDevice(), id = transferId('upload'), hash = new Sha256();
await send('file.upload.start', { transferId: id, path: targetPath, size: file.size }, deviceId, 30000);
for (let offset = 0; offset < file.size; offset += FILE_CHUNK) {
const bytes = new Uint8Array(await file.slice(offset, Math.min(file.size, offset + FILE_CHUNK)).arrayBuffer());
hash.update(bytes);
const data = base64(bytes);
await send('file.upload.chunk', { transferId: id, offset, data }, deviceId, 60000);
setProgress(progressId, (Math.min(file.size, offset + FILE_CHUNK) / Math.max(file.size, 1)) * 100, '上传中 ' + Math.round((Math.min(file.size, offset + FILE_CHUNK) / Math.max(file.size, 1)) * 100) + '%');
}
await send('file.upload.finish', { transferId: id, sha256: hash.digest() }, deviceId, 120000);
$(progressId).style.width = '100%'; $(statusId).textContent = '上传完成';
}
$('file-upload').onchange = async e => { const file = e.target.files[0]; e.target.value = ''; if (!file) return; try { await uploadFile(file, joinFilePath(file.name), 'file-progress', 'file-status'); await loadFiles(); } catch (err) { $('file-status').textContent = '上传失败: ' + err.message; } };
window.fileDownload = async (encoded, encodedName) => { const path = decodeURIComponent(encoded), name = decodeURIComponent(encodedName), deviceId = currentDevice(), id = transferId('download'); let started = false; try { const start = await send('file.download.start', { transferId: id, path }, deviceId, 120000); started = true; const chunks = []; for (let offset = 0; offset < start.size; offset += (start.chunkSize || FILE_CHUNK)) { const result = await send('file.download.chunk', { transferId: id, offset, size: start.chunkSize || FILE_CHUNK }, deviceId, 60000); const raw = atob(result.data); chunks.push(Uint8Array.from(raw, c => c.charCodeAt(0))); setProgress('file-progress', ((offset + result.size) / Math.max(start.size, 1)) * 100, '下载中 ' + Math.round(((offset + result.size) / Math.max(start.size, 1)) * 100) + '%'); } const blob = new Blob(chunks); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = name; link.click(); URL.revokeObjectURL(link.href); $('file-status').textContent = '下载完成'; } catch (e) { $('file-status').textContent = '下载失败: ' + e.message; } finally { if (started) send('file.download.finish', { transferId: id }, deviceId, 30000).catch(() => {}); } };
// ---------------- 应用管理 ----------------
function renderManagerApps() { const box = $('app-manager-list'); if (!state.managerApps) { box.className = 'app-list hint'; box.textContent = '选择在线设备后加载应用'; return; } const kw = $('app-manager-filter').value.trim().toLowerCase(); const items = state.managerApps.filter(a => !kw || a.name.toLowerCase().includes(kw) || a.package.toLowerCase().includes(kw)); box.className = 'app-list'; box.innerHTML = items.length ? items.map(a => `<div class="app-item"><div>${escapeHtml(a.name)}<span class="ver">${escapeHtml(a.versionName || '')}</span><br><span class="pkg">${escapeHtml(a.package)}</span></div><span class="row"><button class="btn secondary sm" ${state.managerLaunching === a.package ? 'disabled' : ''} onclick="managerLaunch('${encodeURIComponent(a.package)}')">${state.managerLaunching === a.package ? '启动中...' : '启动'}</button><button class="btn danger sm" ${a.package === 'com.cpagent.bridge' || state.managerUninstalling === a.package ? 'disabled' : ''} onclick="managerUninstall('${encodeURIComponent(a.package)}')">卸载</button></span></div>`).join('') : '<span class="hint">无匹配应用</span>'; }
async function loadManagerApps(deviceId = $('device-select').value) { try { if (!deviceId) return; const res = await send('app.list', {}, deviceId, 35000); if ($('device-select').value !== deviceId) return; state.managerApps = Object.entries(res || {}).map(([pkg, info]) => ({ package: pkg, name: info.name || pkg, versionName: info.versionName || '', versionCode: info.versionCode || 0 })); renderManagerApps(); } catch (e) { if ($('device-select').value !== deviceId) return; $('app-manager-list').textContent = '加载失败: ' + e.message; } }
$('app-manager-refresh').onclick = loadManagerApps; $('app-manager-filter').oninput = renderManagerApps;
window.managerLaunch = async encoded => { const pkg = decodeURIComponent(encoded); state.managerLaunching = pkg; renderManagerApps(); try { await send('app.launch', { package: pkg }, currentDevice(), 20000); toast('已启动 ' + pkg); } catch (e) { toast('启动失败: ' + e.message); } finally { state.managerLaunching = null; renderManagerApps(); } };
window.managerUninstall = async encoded => { const pkg = decodeURIComponent(encoded); if (!confirm('确认卸载 ' + pkg + '?')) return; state.managerUninstalling = pkg; renderManagerApps(); try { const result = await send('app.uninstall', { package: pkg }, currentDevice(), 90000); if (!result.success) throw new Error(result.output || '卸载失败'); toast('已卸载 ' + pkg); await loadManagerApps(); } catch (e) { toast('卸载失败: ' + e.message); } finally { state.managerUninstalling = null; renderManagerApps(); } };
$('apk-install').onchange = async e => { const file = e.target.files[0]; e.target.value = ''; if (!file) return; if (!file.name.toLowerCase().endsWith('.apk')) return toast('请选择 APK 文件'); try { const target = file.name.replace(/[^A-Za-z0-9._-]/g, '_'); await uploadFile(file, target, 'apk-progress', 'apk-status'); const result = await send('app.install', { path: target }, currentDevice(), 210000); if (!result.success) throw new Error(result.output || '安装失败'); $('apk-status').textContent = '安装完成'; toast('APK 安装成功'); await loadManagerApps(); } catch (err) { $('apk-status').textContent = '安装失败: ' + err.message; } };
// ---------------- 远程终端 ----------------
$('btn-exec').onclick = async () => {
const cmd = $('cmd-input').value.trim();
if (!cmd) return;
const deviceId = $('device-select').value;
log('$ ' + cmd);
try {
const res = await send('shell.exec', { cmd, timeout: 15 }, deviceId, 35000);
log('[exit ' + res.exitCode + ']');
if (res.output) log(res.output);
} catch (e) {
log('执行失败: ' + e.message);
}
$('cmd-input').value = '';
};
$('cmd-input').addEventListener('keydown', e => { if (e.key === 'Enter') $('btn-exec').click(); });
// ---------------- ATX 接口 ----------------
async function callAtx(action, params) {
const deviceId = $('device-select').value;
if (!deviceId) { toast('无在线设备'); return; }
log('> ' + action + ' ' + JSON.stringify(params || {}), 'terminal2');
try {
const res = await send(action, params || {}, deviceId, 65000);
log(JSON.stringify(res, null, 2), 'terminal2');
} catch (e) {
log('失败: ' + e.message, 'terminal2');
}
}
$('btn-atx').onclick = () => {
const action = $('atx-action').value.trim();
if (!action) return toast('请输入 action');
let params = {};
const raw = $('atx-params').value.trim();
if (raw) {
try { params = JSON.parse(raw); }
catch { return toast('参数不是合法 JSON'); }
}
callAtx(action, params);
};
document.querySelectorAll('[data-quick]').forEach(btn => {
btn.onclick = () => { const [a, p] = JSON.parse(btn.dataset.quick); $('atx-action').value = a; $('atx-params').value = JSON.stringify(p); callAtx(a, p); };
});
$('btn-refresh').onclick = refreshList;
// ---------------- 运行日志 ----------------
function logLine(e) {
const t = new Date(e.ts * 1000).toLocaleTimeString('zh-CN', { hour12: false });
const level = String(e.level || 'INFO').toUpperCase();
const loggerName = e.logger ? ` <span class="logger">${escapeHtml(e.logger)}</span>` : '';
const isErr = level === 'ERROR' || level === 'CRITICAL';
return `<div class="log-line"><span class="t">[${t}]</span> <span class="k ${escapeHtml(level.toLowerCase())}">${escapeHtml(level)}</span>${loggerName} ${isErr ? '<span class="err">' : ''}${escapeHtml(e.message || '')}${isErr ? '</span>' : ''}</div>`;
}
function renderLogs() {
const box = $('log-box');
box.innerHTML = state.logs.length
? state.logs.map(logLine).join('')
: '<span class="hint">暂无日志</span>';
box.scrollTop = box.scrollHeight;
}
async function loadLogs() {
try {
const res = await send('log.list', {});
state.logs = res.logs || [];
state.logsCleared = false;
renderLogs();
} catch (e) {
$('log-box').innerHTML = '<span class="hint">加载失败: ' + escapeHtml(e.message) + '</span>';
}
}
function appendLog(entry) {
if (state.logsCleared) return;
state.logs.push(entry);
if (state.logs.length > 500) state.logs.splice(0, state.logs.length - 500);
renderLogs();
}
$('btn-log-clear').onclick = () => {
state.logs = [];
state.logsCleared = true;
renderLogs();
};
// ---------------- WS 连接 ----------------
function connect() {
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
const ws = new WebSocket(`${proto}://${location.host}/ws/ui`);
state.ws = ws;
ws.onopen = () => {
$('conn-status').textContent = '● 已连接';
$('conn-status').className = 'badge on';
log('已连接服务器');
loadLogs();
if (state.shotAuto) captureShot();
};
ws.onclose = () => {
$('conn-status').textContent = '○ 已断开,3 秒后重连';
$('conn-status').className = 'badge off';
log('与服务器断开,3 秒后重连');
setTimeout(connect, 3000);
};
ws.onmessage = ev => {
let msg;
try { msg = JSON.parse(ev.data); } catch { return; }
if (msg.type === 'response' && state.pending[msg.id]) {
const p = state.pending[msg.id]; delete state.pending[msg.id];
msg.status === 'success' ? p.resolve(msg.payload) : p.reject(new Error(msg.payload.message || 'error'));
return;
}
if (msg.type === 'event' && msg.action === 'device.list') {
state.devices = msg.payload || []; renderDevices(); return;
}
if (msg.type === 'event' && msg.action === 'event.heartbeat') {
const d = state.devices.find(d => d.deviceId === msg.deviceId);
if (d) { d.online = true; d.heartbeat = msg.payload; renderDevices(); }
return;
}
if (msg.type === 'event' && msg.action === 'event.log') {
appendLog(msg.payload); return;
}
if (msg.type === 'event' && (msg.action === 'device.online' || msg.action === 'device.offline')) {
refreshList();
}
};
}
connect();
</script>
</body>
</html>