🚀 Sync 2026-11-14 15:02:09

This commit is contained in:
github-actions[bot] committed 2026-11-14 15:02:09 +08:00
1 parent 90f27ab347
commit 9f5777add1
44 files changed
+3970 -5

No files matched your search

@@ -0,0 +1,695 @@
'use strict';
'require baseclass';
'require rpc';
'require fs';
'require ui';
/*
* Shared helpers for the 7Dollar theme: menu grouping, settings storage,
* formatting and the device list used by the home and devices pages.
*/
const ZH = /^zh/i.test(document.documentElement.getAttribute('lang') || '');
const T = (zh, en) => ZH ? zh : en;
const SPRITE = '/luci-static/7dollar/icons.svg';
const ACTIVE = /\/7dollar$/.test(L.env.media || '');
const callUciGet = rpc.declare({ object: 'uci', method: 'get', params: [ 'config', 'section' ], expect: { values: {} } });
const callUciGetType = rpc.declare({ object: 'uci', method: 'get', params: [ 'config', 'type' ], expect: { values: {} } });
const callUciSet = rpc.declare({ object: 'uci', method: 'set', params: [ 'config', 'section', 'values' ] });
const callUciAdd = rpc.declare({ object: 'uci', method: 'add', params: [ 'config', 'type', 'name', 'values' ] });
const callUciDelete = rpc.declare({ object: 'uci', method: 'delete', params: [ 'config', 'section', 'options' ] });
const callUciCommit = rpc.declare({ object: 'uci', method: 'commit', params: [ 'config' ] });
const callFileRead64 = rpc.declare({ object: 'file', method: 'read', params: [ 'path', 'base64' ], expect: { data: '' } });
const callLeases = rpc.declare({ object: 'luci-rpc', method: 'getDHCPLeases', expect: { '': {} } });
const callHints = rpc.declare({ object: 'luci-rpc', method: 'getHostHints', expect: { '': {} } });
const callWireless = rpc.declare({ object: 'luci-rpc', method: 'getWirelessDevices', expect: { '': {} } });
const callAssoc = rpc.declare({ object: 'iwinfo', method: 'assoclist', params: [ 'device' ], expect: { results: [] } });
const callDevices = rpc.declare({ object: 'luci-rpc', method: 'getNetworkDevices', expect: { '': {} } });
const callIfDump = rpc.declare({ object: 'network.interface', method: 'dump', expect: { interface: [] } });
const callBoard = rpc.declare({ object: 'system', method: 'board' });
const callInfo = rpc.declare({ object: 'system', method: 'info' });
const callServices = rpc.declare({ object: 'service', method: 'list', expect: { '': {} } });
const callMounts = rpc.declare({ object: 'luci', method: 'getMountPoints', expect: { result: [] } });
const DEFAULTS = { palette: 'clay', mode: 'auto', hidden_cards: '', shown_cards: '' };
const OPT_IN = [ 'apps' ]; // cards that are off until switched on (they show plugin information)
const words = s => String(s || '').split(/[\s,]+/).filter(Boolean);
/* Whether a home card is on: normal cards unless hidden, opt-in cards only when shown. */
function cardOn(conf, key) {
return OPT_IN.indexOf(key) > -1 ? words(conf.shown_cards).indexOf(key) > -1 : words(conf.hidden_cards).indexOf(key) < 0;
}
const PALETTES = [
[ 'clay', T('陶土', 'Clay') ],
[ 'celadon', T('青瓷', 'Celadon') ],
[ 'mist', T('雾蓝', 'Mist') ],
[ 'dusk', T('暮紫', 'Dusk') ],
[ 'graphite', T('石墨', 'Graphite') ]
];
/* Menu regrouping: native LuCI pages -> seven plain-language sections. `pages` are the everyday
* ones, shown as pills; `more` and anything matched by `prefix` sit behind the group's "More" pill.
* Plugins also put themselves under System or Status (other themes' settings, file transfer, disk
* tools ...); those are apps. So System's prefixes only take LuCI's own pages, told apart by the
* view they open (`own`), which also covers native pages added in newer LuCI versions. */
const GROUPS = [
{ id: 'home', icon: 'home', label: T('总览', 'Overview'), pages: [ 'admin/home' ] },
{ id: 'devices', icon: 'devices', label: T('设备', 'Devices'), pages: [ 'admin/clients' ] },
{ id: 'wifi', icon: 'wifi', label: 'Wi‑Fi', pages: [ 'admin/network/wireless', 'admin/status/channel_analysis' ] },
{ id: 'internet', icon: 'globe', label: T('上网', 'Internet'),
pages: [ 'admin/network/network', 'admin/network/dhcp', 'admin/network/dns', 'admin/network/diagnostics' ],
more: [ 'admin/network/routes', 'admin/status/routes', 'admin/status/routesj', 'admin/network/switch' ],
prefix: [ 'admin/network' ] },
{ id: 'security', icon: 'shield', label: T('安全', 'Security'), mob: false,
pages: [ 'admin/network/firewall', 'admin/status/nftables', 'admin/status/iptables', 'admin/system/admin' ] },
{ id: 'apps', icon: 'grid', label: T('应用', 'Apps'), mob: false, pages: [ 'admin/apps' ],
prefix: [ 'admin/services', 'admin/vpn', 'admin/nas', 'admin/docker', 'admin/statistics' ] },
{ id: 'system', icon: 'gear', label: T('系统', 'System'), short: T('更多', 'More'),
pages: [ 'admin/system/system', 'admin/system/appearance', 'admin/status/overview', 'admin/status/logs',
'admin/system/package-manager', 'admin/system/opkg', 'admin/system/flash', 'admin/system/reboot' ],
more: [ 'admin/dashboard', 'admin/status/realtime', 'admin/system/crontab', 'admin/system/startup', 'admin/status/processes', 'admin/system/mounts',
'admin/system/leds', 'admin/status/syslog', 'admin/status/dmesg', 'admin/status/dashboard' ],
prefix: [ 'admin/system', 'admin/status' ], own: true }
];
/* A page LuCI itself ships: it opens one of LuCI's status/system views, or points into them.
* (The patterns sit in constants: the buildroot's jsmin misreads a regex that follows `return`.) */
const OWN_VIEW = /^(status|system|admin_status)\//, OWN_ALIAS = /^admin\/(status|system)\//;
function own(node) {
const a = (node && node.action) || {}, path = a.path || '';
return OWN_VIEW.test(path) || (a.type == 'alias' && OWN_ALIAS.test(path));
}
const LABELS = {
'admin/home': T('总览', 'Overview'),
'admin/dashboard': T('仪表盘', 'Dashboard'),
'admin/clients': T('设备', 'Devices'),
'admin/apps': T('全部应用', 'All apps'),
'admin/network/wireless': T('无线网络', 'Wireless'),
'admin/status/channel_analysis': T('信道分析', 'Channel analysis'),
'admin/network/network': T('网络接口', 'Interfaces'),
'admin/network/diagnostics': T('网络诊断', 'Diagnostics'),
'admin/network/routes': T('静态路由', 'Static routes'),
'admin/status/routes': T('路由表', 'Routing table'),
'admin/status/routesj': T('路由表', 'Routing table'),
'admin/network/switch': T('交换机', 'Switch'),
'admin/network/firewall': T('防火墙', 'Firewall'),
'admin/status/nftables': T('防火墙规则', 'Firewall status'),
'admin/status/iptables': T('防火墙规则', 'Firewall status'),
'admin/system/admin': T('管理员', 'Administration'),
'admin/system/system': T('通用', 'General'),
'admin/system/appearance': T('外观与首页', 'Appearance'),
'admin/status/overview': T('运行状态', 'Status'),
'admin/status/realtime': T('实时监控', 'Realtime'),
'admin/status/logs': T('日志', 'Logs'),
'admin/status/processes': T('进程', 'Processes'),
'admin/system/package-manager': T('软件包', 'Software'),
'admin/system/opkg': T('软件包', 'Software'),
'admin/system/flash': T('备份与升级', 'Backup & upgrade'),
'admin/system/startup': T('启动项', 'Startup'),
'admin/system/crontab': T('计划任务', 'Scheduled tasks'),
'admin/system/mounts': T('挂载点', 'Mount points'),
'admin/system/leds': T('指示灯', 'LEDs'),
'admin/system/reboot': T('重启', 'Reboot'),
'admin/services/openclash': 'OpenClash',
'admin/services/ksmbd': T('文件共享', 'File sharing')
};
const APP_ICONS = [
[ /clash|passwall|homeproxy|ssr|v2ray|xray|sing|mihomo|proxy|nikki|daed/i, 'route' ],
[ /smb|samba|ksmbd|nfs|ftp|disk|share|alist|aria|transmission|qbit|minidlna/i, 'folder' ],
[ /vpn|wireguard|openvpn|zerotier|tailscale|frp|ipsec/i, 'vpn' ],
[ /ddns|dns|adguard|mosdns|smartdns/i, 'globe' ],
[ /docker|dockerman/i, 'box' ],
[ /stat|nlbw|bandwidth|netdata/i, 'pulse' ],
[ /upnp|qos|sqm|eqos/i, 'sliders' ],
[ /wol|wake/i, 'power' ],
[ /cron|sched|time/i, 'clock' ]
];
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
function icon(id, cls) {
return `<svg class="i${cls ? ' ' + cls : ''}" aria-hidden="true"><use href="${SPRITE}#${id}"></use></svg>`;
}
function html(s) {
const t = document.createElement('template');
t.innerHTML = s.trim();
return t.content.childNodes.length == 1 ? t.content.firstChild : t.content;
}
function title(path, node) {
if (LABELS[path])
return LABELS[path];
return node && node.title ? _(node.title) : path.split('/').pop();
}
/* ui.menu.getChildren() replaces alias nodes (e.g. Firewall → Zones) with a copy of
* their target, which drops the alias's own sub-pages. Always keep the real node. */
function realNode(parent, child) {
return (parent.children && parent.children[child.name]) || child;
}
/* True if the menu has this page. LuCI only lists pages whose dependencies are met, so this
* doubles as a free feature check (e.g. Wireless needs a wifi-device, OpenClash needs the app). */
function menuHas(tree, path) {
let n = tree;
for (const k of ('admin/' + path).split('/')) n = n && n.children && n.children[k];
return !!n;
}
/* The software page: package-manager since 24.10, opkg on 23.05; null when neither app is installed. */
function software(tree) {
return [ 'system/package-manager', 'system/opkg' ].find(p => menuHas(tree, p)) || null;
}
let menuPromise;
/* A menu cached before switching themes can omit our home page. Refresh it once and share the
* result between navigation and views; never invent entries that the server did not authorize. */
function loadMenu() {
if (!menuPromise)
menuPromise = ui.menu.load().then(tree => {
const home = tree && tree.children && tree.children.admin && tree.children.admin.children && tree.children.admin.children.home;
if (!ACTIVE || (home && home.satisfied && home.action && home.action.path == '7dollar/home'))
return tree;
ui.menu.flushCache();
ui.menu.menu = null;
return ui.menu.load();
});
return menuPromise;
}
function flatten(tree) {
/* Returns [{ path, node, title, group }] for every navigable page. */
const admin = tree && tree.children && tree.children.admin;
const out = [];
if (!admin)
return out;
ui.menu.getChildren(admin).forEach(t => {
const top = realNode(admin, t);
if (top.name == 'logout')
return;
const tpath = 'admin/' + top.name;
const kids = ui.menu.getChildren(top);
if (!kids.length)
out.push({ path: tpath, node: top });
else
kids.forEach(k => out.push({ path: tpath + '/' + k.name, node: realNode(top, k) }));
});
out.forEach(p => {
p.title = title(p.path, p.node);
p.group = groupOf(p.path, p.node);
});
return out;
}
function groupOf(path, node) {
for (const g of GROUPS)
if (g.pages.concat(g.more || []).indexOf(path) > -1)
return g.id;
for (const g of GROUPS)
for (const pre of (g.prefix || []))
if ((path == pre || path.indexOf(pre + '/') == 0) && (!g.own || own(node)))
return g.id;
return 'apps';
}
function grouped(pages) {
return GROUPS.map(g => {
const order = g.pages.concat(g.more || []), list = pages.filter(p => p.group == g.id);
list.sort((a, b) => {
const ia = order.indexOf(a.path), ib = order.indexOf(b.path);
return (ia < 0 ? 999 : ia) - (ib < 0 ? 999 : ib);
});
return Object.assign({}, g, { list: list });
}).filter(g => g.list.length);
}
function appIcon(path) {
for (const [ re, id ] of APP_ICONS)
if (re.test(path))
return id;
return 'grid';
}
/* The procd service behind an app page, matched by name (services/openclash ↔ openclash,
* nas/ksmbd ↔ ksmbd, services/upnp ↔ miniupnpd): { name, running }, or null if none fits. */
function service(services, path) {
const leaf = path.split('/').pop().toLowerCase().replace(/[^a-z0-9]/g, '');
const name = Object.keys(services || {}).find(k => {
const s = k.toLowerCase().replace(/[^a-z0-9]/g, '');
return s == leaf || (leaf.length > 3 && s.indexOf(leaf) > -1) || (s.length > 3 && leaf.indexOf(s) > -1);
});
if (!name) return null;
const inst = services[name].instances || {};
return { name: name, running: Object.keys(inst).some(k => inst[k].running) };
}
/* ---------------- settings (stored in /etc/config/7dollar) ---------------- */
function loadSettings() {
return L.resolveDefault(callUciGet('7dollar', 'main'), {}).then(v => Object.assign({}, DEFAULTS, v || {}));
}
function saveSettings(values) {
const set = {}, del = [];
for (const k in values) {
if (values[k] === '' || values[k] == null)
del.push(k);
else
set[k] = String(values[k]);
}
return L.resolveDefault(callUciGet('7dollar', 'main'), null).then(exists => {
const steps = [];
if (exists == null || !Object.keys(exists).length)
steps.push(() => callUciAdd('7dollar', 'theme', 'main', set));
else if (Object.keys(set).length)
steps.push(() => callUciSet('7dollar', 'main', set));
if (del.length)
steps.push(() => L.resolveDefault(callUciDelete('7dollar', 'main', del), null));
steps.push(() => callUciCommit('7dollar'));
return steps.reduce((p, fn) => p.then(fn), Promise.resolve());
});
}
/* ---------------- motion ---------------- */
/* Durations live in cascade.css (--fast / --base / --slow); scripts read them so CSS and JS move alike. */
const calm = matchMedia('(prefers-reduced-motion: reduce)');
function motion(name) {
return calm.matches ? 0 : parseFloat(getComputedStyle(document.documentElement).getPropertyValue(`--${name}`)) * 1000 || 0;
}
/* Exits mirror entrances: fade (and sink) out, then go. */
function leave(el) {
if (el.classList.contains('td-out')) return;
el.classList.add('td-out');
setTimeout(() => el.remove(), motion('fast'));
}
function applyLook(s) {
const r = document.documentElement;
const dark = s.mode == 'auto' ? matchMedia('(prefers-color-scheme: dark)').matches : s.mode == 'dark';
const paint = () => {
r.setAttribute('data-palette', s.palette);
r.setAttribute('data-mode', s.mode);
r.setAttribute('data-theme', dark ? 'dark' : 'light');
r.setAttribute('data-darkmode', dark ? 'true' : 'false');
document.dispatchEvent(new CustomEvent('td-look', { detail: s }));
};
/* one cross-fade of the whole page instead of every colour easing on its own */
if (document.startViewTransition && motion('base')) document.startViewTransition(paint);
else paint();
}
let toastTimer;
function toast(msg) {
let t = document.querySelector('.td-toast:not(.td-out)');
if (!t) document.body.appendChild(t = E('div', { 'class': 'td-toast', 'role': 'status' }));
t.textContent = msg;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => leave(t), 1800);
}
/* ---------------- formatting ---------------- */
function rate(bytesPerSec) {
const bits = Math.max(0, bytesPerSec * 8);
if (bits >= 1e9) return [ (bits / 1e9).toFixed(2), 'Gbps' ];
if (bits >= 1e6) return [ (bits / 1e6).toFixed(bits >= 1e8 ? 0 : 1), 'Mbps' ];
if (bits >= 1e3) return [ (bits / 1e3).toFixed(0), 'Kbps' ];
return [ bits.toFixed(0), 'bps' ];
}
function bytes(n) {
n = +n || 0;
if (n >= 1099511627776) return (n / 1099511627776).toFixed(1) + ' TB';
if (n >= 1073741824) return (n / 1073741824).toFixed(1) + ' GB';
if (n >= 1048576) return (n / 1048576).toFixed(0) + ' MB';
if (n >= 1024) return (n / 1024).toFixed(0) + ' KB';
return n + ' B';
}
function duration(sec) {
sec = Math.max(0, Math.floor(sec || 0));
const d = Math.floor(sec / 86400), h = Math.floor(sec % 86400 / 3600), m = Math.floor(sec % 3600 / 60);
if (ZH) {
if (d) return `${d} 天 ${h} 小时`;
if (h) return `${h} 小时 ${m} 分钟`;
return `${Math.max(m, 1)} 分钟`;
}
if (d) return `${d}d ${h}h`;
if (h) return `${h}h ${m}m`;
return `${Math.max(m, 1)}m`;
}
function signal(dbm) {
if (dbm == null || dbm == 0) return [ T('未知', 'Unknown'), 0 ];
if (dbm >= -55) return [ T('信号很好', 'Excellent'), 4 ];
if (dbm >= -65) return [ T('信号良好', 'Good'), 3 ];
if (dbm >= -75) return [ T('信号一般', 'Fair'), 2 ];
return [ T('信号较弱', 'Weak'), 1 ];
}
function quality(dbm) {
if (!dbm) return 0;
return Math.max(4, Math.min(100, Math.round((dbm + 92) / 50 * 100)));
}
function bandName(b) {
return ({ '2g': '2.4 GHz', '5g': '5 GHz', '6g': '6 GHz', '60g': '60 GHz' })[b] || b || 'Wi‑Fi';
}
function kind(name) {
name = name || '';
if (/watch/i.test(name)) return 'watch';
if (/ipad|pad|tab|kindle/i.test(name)) return 'tablet';
if (/book\d*\b|laptop|thinkpad|surface/i.test(name)) return 'laptop'; // MacBook, MateBook, Vivobook, Galaxy Book3
if (/iphone|pixel|android|phone|oppo|vivo|xiaomi|redmi|huawei|honor|galaxy|oneplus|realme|meizu|nokia|mi-/i.test(name)) return 'phone';
if (/tv\b|roku|chromecast|fire-?stick|\bshield\b|x?box\b/i.test(name)) return 'tv';
if (/\b(mac|imac|mini|pc|desktop|win|ubuntu|linux|nas|server)\b/i.test(name)) return 'desktop';
return 'devices';
}
function pretty(name) {
if (!name) return '';
return name.replace(/[-_]+/g, ' ').replace(/\s+/g, ' ').trim();
}
/* ---------------- data ---------------- */
function readFile(path) {
return L.resolveDefault(fs.read(path), null);
}
/* MACs a bridge has heard from in the last few minutes: its forwarding table forgets a port after
* 300 s of silence, while an ARP entry can outlive a device by hours. Entries are 16 bytes
* (6 of MAC) in the binary brforward file. null when none of the devices is a bridge. */
function heard(bridges) {
return Promise.all(bridges.map(b => L.resolveDefault(callFileRead64(`/sys/class/net/${b}/brforward`, true), null))).then(datas => {
let macs = null;
datas.forEach(d => {
if (d == null) return;
const bin = atob(d);
macs = macs || {};
for (let i = 0; i + 16 <= bin.length; i += 16)
macs[Array.from(bin.slice(i, i + 6), c => ('0' + c.charCodeAt(0).toString(16)).slice(-2)).join(':').toUpperCase()] = true;
});
return macs;
});
}
/* CPU temperature lives in different places per platform (thermal_zone0 on most SoCs,
* coretemp/k10temp hwmon on x86). Pick the best sensor once; later reads cost one file. */
const TEMP_PREF = [ /^coretemp/, /^k10temp/, /^zenpower/, /^x86_pkg_temp/, /^cpu[-_]?thermal/, /^soc[-_]?thermal/, /^acpitz/ ];
let tempPath;
function tempSensor() {
if (tempPath !== undefined)
return Promise.resolve(tempPath);
const list = dir => L.resolveDefault(fs.list(dir), []).then(l => l.map(e => dir + '/' + e.name));
const rank = name => { const i = TEMP_PREF.findIndex(r => r.test(name)); return i < 0 ? TEMP_PREF.length : i };
return Promise.all([ list('/sys/class/thermal'), list('/sys/class/hwmon') ]).then(([ zones, hwmons ]) => Promise.all([].concat(
zones.filter(d => /thermal_zone\d+$/.test(d)).map(d => readFile(d + '/type').then(n => ({ name: n, path: d + '/temp' }))),
hwmons.map(d => readFile(d + '/name').then(n => ({ name: n, path: d + '/temp1_input' })))
))).then(found => {
/* Known CPU sensors first, then any thermal zone; never radio/PHY/disk sensors. */
const cands = found.filter(c => c.name).map(c => ({ path: c.path, r: rank(c.name.trim()) }))
.filter(c => c.r < TEMP_PREF.length || /thermal_zone/.test(c.path))
.sort((a, b) => a.r - b.r || (a.path < b.path ? -1 : 1));
const next = i => i >= cands.length ? null
: readFile(cands[i].path).then(v => +v > 0 ? cands[i].path : next(i + 1));
return next(0);
}).then(p => (tempPath = p));
}
function temperature() {
return tempSensor().then(p => p ? readFile(p) : null).then(v => +v > 0 ? +v / 1000 : null);
}
function wifiInfo() {
return L.resolveDefault(callWireless(), {}).then(radios => {
const aps = [];
Object.keys(radios || {}).sort().forEach(rname => {
const r = radios[rname] || {};
(r.interfaces || []).forEach(i => {
if ((i.config || {}).mode == 'ap' && i.ifname)
aps.push({ radio: rname, band: (r.config || {}).band, ifname: i.ifname, ssid: (i.iwinfo || {}).ssid || (i.config || {}).ssid,
network: (i.config || {}).network || [], up: !!r.up && !(i.config || {}).disabled });
});
});
return Promise.all(aps.map(ap => ap.up ? L.resolveDefault(callAssoc(ap.ifname), []) : Promise.resolve([])))
.then(lists => {
aps.forEach((ap, i) => ap.stations = lists[i] || []);
return { radios: radios || {}, aps: aps };
});
});
}
function clients(wifi, uplink) {
return Promise.all([
L.resolveDefault(callLeases(), {}),
L.resolveDefault(callHints(), {}),
wifi ? Promise.resolve(wifi) : wifiInfo(),
readFile('/proc/net/arp'),
uplink !== undefined ? uplink : wan()
]).then(([ leases, hints, wi, arp, up ]) => {
up = up || {};
/* neighbours on the uplink side (a main router's WAN port, a repeater's Wi-Fi link) are not
* our devices; a side router's uplink is the LAN itself, so there only the gateway is skipped.
* What a side router sees on its LAN port may well be a phone on the main router's Wi-Fi,
* so those count as "lan" rather than "wired". The same goes for a box with no Wi-Fi of its
* own (x86, radios off): its Wi-Fi devices arrive through an access point on a LAN port. */
const side = up.mode == 'side', skip = side ? [] : [ up.device, up.port ];
const lan = side || !(wi.aps || []).some(ap => ap.up);
const byMac = {};
const get = mac => {
mac = String(mac).toUpperCase();
return byMac[mac] || (byMac[mac] = { mac: mac, online: false });
};
(leases.dhcp_leases || []).forEach(l => {
if (!l.macaddr) return;
const c = get(l.macaddr);
c.name = c.name || l.hostname;
c.ip = l.ipaddr;
c.expires = l.expires;
c.lease = true;
});
const wifiMacs = {};
(wi.aps || []).forEach(ap => ap.stations.forEach(s => {
const c = get(s.mac);
const h = (hints || {})[c.mac] || {};
c.online = true;
c.conn = 'wifi';
c.band = ap.band;
c.ssid = ap.ssid;
c.signal = s.signal;
c.link = Math.max((s.tx || {}).rate || 0, (s.rx || {}).rate || 0) / 1000;
c.since = s.connected_time;
c.name = c.name || h.name;
c.ip = c.ip || (h.ipaddrs || [])[0];
wifiMacs[c.mac] = true;
}));
/* Wired devices are whatever answers ARP on our side, leased or not (static IPs, or a side
* router whose DHCP is off), whatever the LAN is called (br-lan, eth0, br-lan.10 ...).
* The gateway is the upstream router; containers and loopback are not devices either.
* The bridge's own table then drops whoever has gone quiet (a Wi-Fi device that left). */
const rows = String(arp || '').split('\n').slice(1).map(line => line.trim().split(/\s+/)).filter(f =>
f.length >= 6 && f[2] == '0x2' && f[0] != up.gw && !skip.includes(f[5]) && !/^(lo|docker|veth)|^br-[0-9a-f]{12}$/.test(f[5]) && !wifiMacs[f[3].toUpperCase()]);
const bridges = [ ...new Set(rows.map(f => f[5].replace(/\.\d+$/, ''))) ];
return heard(bridges).then(macs => {
rows.forEach(f => {
if (macs && !macs[f[3].toUpperCase()]) return;
const c = get(f[3]);
c.online = true;
c.conn = lan ? 'lan' : 'wired';
c.ip = c.ip || f[0];
});
for (const mac in (hints || {})) {
const h = hints[mac], c = byMac[mac.toUpperCase()];
if (c) {
c.name = c.name || h.name;
c.ip = c.ip || (h.ipaddrs || h.ipv4 || [])[0];
}
}
const list = Object.values(byMac).map(c => {
c.display = pretty(c.name) || c.ip || c.mac;
c.kind = kind(c.name);
return c;
});
list.sort((a, b) => (b.online - a.online) || ((b.link || 0) - (a.link || 0)) || a.display.localeCompare(b.display));
return list;
});
});
}
/* The uplink is whichever device carries the kernel's default route. Asking the kernel instead of
* netifd covers every layout (main router, bypass/side router, routes added by scripts). */
function defaultRoute(text) {
let best = null;
String(text || '').split('\n').slice(1).forEach(line => {
const f = line.trim().split(/\s+/);
if (f[1] != '00000000' || f[7] != '00000000' || !(parseInt(f[3], 16) & 1)) return;
if (!best || +f[6] < best.metric)
best = { dev: f[0], metric: +f[6], gw: f[2].match(/../g).reverse().map(h => parseInt(h, 16)).join('.') };
});
return best;
}
function wan() {
return Promise.all([ L.resolveDefault(callIfDump(), []), readFile('/proc/net/route') ]).then(([ ifs, rt ]) => {
const def = defaultRoute(rt);
const dev = i => i.l3_device || i.device;
const list = ifs || [];
const lan = list.find(i => i.interface == 'lan');
const v4 = i => ((i['ipv4-address'] || [])[0] || {}).address;
const v6 = i => ((i['ipv6-address'] || []).find(a => !/^fe80:/i.test(a.address)) || {}).address; // never the link-local one
if (!def) {
const w = list.find(i => i.interface == 'wan');
return w ? { up: false, mode: 'wan', proto: w.proto, device: dev(w) } : null;
}
const i = list.filter(i => i.up && dev(i) == def.dev)
.sort((a, b) => !!(b['ipv4-address'] || []).length - !!(a['ipv4-address'] || []).length)[0] || {};
/* Any other interface with a default route of its own (IPTV, a backup WAN) is another line.
* The IPv6 half of the WAN (wan6) is not: it rides on the WAN's device or port with no IPv4 route. */
const deflt = (x, re) => (x.route || []).some(r => r.mask == 0 && re.test(r.target));
const port = n => String(n || '').split('.')[0];
const seen = new Set([ def.dev, lan && dev(lan) ]);
const more = list.filter(x => x.up && x.interface != 'loopback' && deflt(x, /^(0\.0\.0\.0|::)$/) && !seen.has(dev(x))
&& (deflt(x, /^0\.0\.0\.0$/) || port(x.device) != port(i.device)) && seen.add(dev(x)))
.map(x => ({ name: x.interface.toUpperCase(), proto: x.proto, device: dev(x), port: x.device, ip: v4(x) || v6(x), uptime: x.uptime }));
return {
up: true,
/* side: uplink shares the LAN (bypass router / AP); sta: Wi-Fi uplink (repeater) */
mode: lan && dev(lan) == def.dev ? 'side' : /-sta\d+$/.test(def.dev) ? 'sta' : 'wan',
proto: i.proto,
device: def.dev,
port: i.device,
ip: v4(i),
ip6: v6(i),
gw: def.gw != '0.0.0.0' ? def.gw : null,
dns: i['dns-server'] || [],
uptime: i.uptime,
more: more
};
});
}
/* Physical Ethernet ports in use: the uplink ports, named after their line (WAN, IPTV, ...), then
* whatever sits in a bridge (lan1…lan4, eth1, …). Switch ports are "dsa" devices, a plain NIC is
* "ethernet". A VLAN on top (eth0.7, wan.10) counts as its port. Empty on swconfig boxes, where
* the kernel only sees the CPU port. */
function ports(up) {
const base = n => String(n || '').split('.')[0];
const line = new Map();
const tag = (n, name) => (n = base(n)) && !line.has(n) && line.set(n, name);
if (up && up.mode != 'side') { tag(up.port, 'WAN'); tag(up.device, 'WAN'); }
((up && up.more) || []).forEach(u => { tag(u.port, u.name); tag(u.device, u.name); });
const order = [ ...line.keys() ], rank = n => { const k = order.indexOf(n); return k < 0 ? order.length : k };
return L.resolveDefault(callDevices(), {}).then(devs => Object.values(devs || {})
.filter(d => /^(ethernet|dsa)$/.test(d.devtype) && !d.wireless && d.name.indexOf('.') < 0 && !/^(docker|veth|br-)/.test(d.name)
&& (d.master || line.has(d.name)))
.map(d => ({ name: d.name, line: line.get(d.name), up: !!(d.link || {}).carrier, speed: +(d.link || {}).speed || 0 }))
.sort((a, b) => (rank(a.name) - rank(b.name)) || a.name.localeCompare(b.name, 'en', { numeric: true })));
}
function connName(c) {
return c.conn == 'lan' ? T('局域网', 'LAN') : T('有线连接', 'Wired');
}
const DNS_NAMES = {
'223.5.5.5': T('阿里', 'AliDNS'), '223.6.6.6': T('阿里', 'AliDNS'),
'119.29.29.29': T('腾讯', 'DNSPod'), '119.28.28.28': T('腾讯', 'DNSPod'), '182.254.116.116': T('腾讯', 'DNSPod'),
'114.114.114.114': '114DNS', '114.114.115.115': '114DNS',
'180.76.76.76': T('百度', 'Baidu'), '1.1.1.1': 'Cloudflare', '1.0.0.1': 'Cloudflare',
'8.8.8.8': 'Google', '8.8.4.4': 'Google', '9.9.9.9': 'Quad9'
};
function dnsName(list, gw, gwName) {
const names = [];
(list || []).forEach(ip => {
const n = DNS_NAMES[ip] || (ip == gw ? gwName || T('上级路由', 'Upstream') : ip);
if (names.indexOf(n) < 0) names.push(n);
});
return names.slice(0, 2).join(' · ') || '—';
}
function netdev(text) {
const out = {};
String(text || '').split('\n').slice(2).forEach(line => {
const m = line.match(/^\s*([^:]+):\s*(.*)$/);
if (!m) return;
const f = m[2].trim().split(/\s+/).map(Number);
out[m[1]] = { rx: f[0], tx: f[8] };
});
return out;
}
function cpuStat(text) {
const f = String(text || '').split('\n')[0].trim().split(/\s+/).slice(1).map(Number);
if (f.length < 4) return null;
const idle = f[3] + (f[4] || 0);
return { idle: idle, total: f.reduce((a, b) => a + b, 0) };
}
const uciType = (config, type) => L.resolveDefault(callUciGetType(config, type), {});
const uciSection = (config, section) => L.resolveDefault(callUciGet(config, section), {});
return baseclass.extend({
ZH: ZH, T: T,
active: ACTIVE,
PALETTES: PALETTES, OPT_IN: OPT_IN, words: words, cardOn: cardOn,
esc: esc, icon: icon, html: html,
loadMenu: loadMenu, flatten: flatten, realNode: realNode, menuHas: menuHas, software: software, grouped: grouped, appIcon: appIcon, service: service,
loadSettings: loadSettings, saveSettings: saveSettings, applyLook: applyLook, toast: toast, motion: motion, leave: leave,
rate: rate, bytes: bytes, duration: duration, signal: signal, quality: quality, bandName: bandName, connName: connName,
readFile: readFile, temperature: temperature, wifiInfo: wifiInfo, clients: clients, wan: wan, ports: ports, dnsName: dnsName, netdev: netdev, cpuStat: cpuStat,
board: () => L.resolveDefault(callBoard(), {}),
sysinfo: () => L.resolveDefault(callInfo(), {}),
services: () => L.resolveDefault(callServices(), {}), mounts: () => L.resolveDefault(callMounts(), []),
uciType: uciType, uciSection: uciSection,
uciSet: (config, section, values) => callUciSet(config, section, values).then(() => callUciCommit(config))
});
@@ -0,0 +1,221 @@
'use strict';
'require baseclass';
'require uci';
'require 7dollar.common as td';
/*
* Plain status by default. Native LuCI status blocks (interfaces, Wi-Fi, overview) list every
* field they know; this marks the engineering ones (MAC, BSSID, packet counts, MCS, noise, ...)
* as .td-x and gives their section a "Details" button. Nothing is removed: one click shows all.
* Labels are matched through LuCI's own translations, so it works in every language.
* Runs in the browser only, after each re-render of #view; the router does no extra work.
*/
const T = td.T, icon = td.icon;
const BAND = { '2g': '2.4 GHz', '5g': '5 GHz', '6g': '6 GHz', '60g': '60 GHz' };
let W;
function words(list) { return new Set(list.map(s => _(s))); }
function dict() {
return W ??= {
item: words([ 'MAC', 'MAC address', 'BSSID', 'Mode', 'RX', 'TX', 'Gateway', 'DNS', 'Expires', 'Device', 'Type',
'Tx-Power', 'Noise', 'Country', 'Prefix Delegated' ]),
v6: words([ 'IPv6', 'IPv6-PD' ]), // hidden only when the same list already has an IPv4 address
v4: words([ 'IPv4', 'Address' ]),
row: words([ 'Architecture', 'Target Platform', 'Kernel Version', 'Load Average', 'Buffered', 'Cached' ]),
col: words([ 'MAC address', 'DUID' ]),
host: words([ 'Host', 'Hostname' ]),
fw: _('Firmware Version'),
noise: new RegExp(`\\s*/\\s*${_('Noise')}\\s*$`) // the "Signal / Noise" header
};
}
/* Wrap the part of a direct text child that matches re (or its first group) in .td-x. */
function fold(el, re) {
for (const n of el.childNodes) {
const m = n.nodeType == 3 && re.exec(n.data);
if (!m) continue;
const part = m[1] ?? m[0];
const mid = n.splitText(m.index + m[0].indexOf(part));
mid.splitText(part.length);
const s = E('span', { class: 'td-x' });
mid.replaceWith(s);
s.append(mid);
return s;
}
}
function hide(el) {
el.classList.add('td-x');
return el;
}
const shown = n => n.nodeType == 1 && n.matches('span.nowrap') && !n.classList.contains('td-x');
/* L.itemlist() output: <span.nowrap><strong>Label: </strong>value</span>, separated by " | " or <br>. */
function list(box, w) {
const nodes = [ ...box.childNodes ];
const items = nodes.filter(n => n.nodeType == 1 && n.matches('span.nowrap'));
const label = e => e.firstChild?.nodeName == 'STRONG' ? e.firstChild.textContent.replace(/:\s*$/, '') : '';
const has4 = items.some(e => w.v4.has(label(e)));
items.forEach(e => {
const l = label(e);
if (w.item.has(l) || (has4 && w.v6.has(l))) hide(e);
else if (l) fold(e, /\s+\([^()]*\)\s*$/); // "149 (5.745 GHz)", "WPA2 PSK (CCMP)"
});
/* A separator goes with the item before it, and also when nothing visible follows. */
let prev = null;
nodes.forEach((n, i) => {
if (items.includes(n)) return void (prev = n);
if (!prev || (shown(prev) && nodes.slice(i + 1).some(shown))) return;
if (n.nodeType == 3) { const s = E('span', { class: 'td-x' }); n.replaceWith(s); s.append(n); }
else if (n.nodeType == 1) hide(n);
});
const badge = box.closest('.ifacebadge');
if (badge && items.length && !items.some(shown)) hide(badge);
}
function scan(view) {
const w = dict(), out = [];
const mark = el => el && out.push(el);
new Set([ ...view.querySelectorAll('span.nowrap') ].map(e => e.parentNode)).forEach(box => box.closest('.cbi-tooltip') || list(box, w));
view.querySelectorAll('span.nowrap.td-x, .ifacebadge.td-x').forEach(mark);
/* two-column status tables (overview): fold whole rows */
view.querySelectorAll('.tr').forEach(tr => {
const c = tr.children;
if (c.length != 2) return;
const k = c[0].textContent.trim();
if (w.row.has(k)) mark(hide(tr));
else if (k == w.fw) mark(fold(c[1], /^\S+\s+\S+(\s.+)$/s)); // keep "OpenWrt 24.10.5"
});
/* device tables (clients, leases): MAC / DUID columns, host suffixes and addresses, Wi-Fi rate details, noise.
* Tables without a host column (neighbours, device config) are about those addresses, so they stay. */
const named = new Set([ ...view.querySelectorAll('.th') ].filter(th => w.host.has(th.textContent.trim())).map(th => th.closest('.table')));
view.querySelectorAll('.th').forEach(th => named.has(th.closest('.table')) && w.col.has(th.textContent.trim()) ? mark(hide(th)) : mark(fold(th, w.noise)));
view.querySelectorAll('.td[data-title]').forEach(c => {
const t = c.getAttribute('data-title');
if (w.col.has(t)) return named.has(c.closest('.table')) && mark(hide(c));
if (w.noise.test(t)) c.setAttribute('data-title', t.replace(w.noise, '')); // label of the phone layout
if (!w.host.has(t)) return;
c.querySelectorAll('.hide-xs').forEach(e => mark(hide(e)));
mark(fold(c, /\s+\([^()]*\)\s*$/));
mark(fold(c, /^[^\s.:]*[a-z][^\s.:]*(\.[a-z][\w.-]*)/i)); // "Pixel.lan" -> "Pixel"; IPs stay
});
view.querySelectorAll('.assoclist .td > span:not(.ifacebadge) > span').forEach(s => mark(fold(s, /,\s.*$/s)));
view.querySelectorAll('[data-noise] > span').forEach(s => mark(fold(s, /\/-?\d+/)));
view.querySelectorAll('.assoclist .ifacebadge[data-ssid]').forEach(mark);
/* an empty secondary device table (e.g. no DHCPv6 leases) folds away with its title */
view.querySelectorAll('.table .placeholder').forEach(p => {
const t = p.closest('.table'), h = t.previousElementSibling;
if (named.has(t) && h?.matches('h3') && h != head(t)[1]) { mark(hide(t)); hide(h); }
});
/* radio rows on the Wi-Fi page: "5 GHz" instead of the chipset name */
view.querySelectorAll('[data-sid] [data-name=_stat] big > strong').forEach(s => {
if (s.querySelector('.td-y')) return;
const b = BAND[uci.get('wireless', s.closest('[data-sid]').getAttribute('data-sid'), 'band')];
if (!b) return;
s.replaceChildren(E('span', { class: 'td-x' }, s.textContent), E('span', { class: 'td-y' }, b));
mark(s);
});
/* long section help (DHCP, firewall, ...) folds behind "说明" instead of a wall of text above the form */
view.querySelectorAll('.cbi-section-descr').forEach(d => {
if (d.parentNode.matches('details') || d.textContent.trim().length <= 160) return;
const box = E('details', { class: 'td-desc' }, E('summary', {}, [ T('说明', 'Help'), td.html(icon('chev')) ]));
d.replaceWith(box);
box.append(d);
});
out.forEach(arm);
}
/* The section an element belongs to, and the heading that carries its Details button. */
function head(el) {
let sec = el.closest('.cbi-section');
if (sec)
return [ sec, sec.querySelector(':scope > h3') ?? sec.querySelector('h3') ];
sec = el.closest('table');
return [ sec, sec?.previousElementSibling?.matches('h3') ? sec.previousElementSibling : null ];
}
function arm(el) {
const [ sec, h ] = head(el);
if (!h) return;
sec.classList.add('td-sec');
if (h.querySelector('.td-detail')) return;
const btn = E('button', { type: 'button', class: 'td-detail' });
const paint = open => {
btn.setAttribute('aria-expanded', open);
btn.innerHTML = `${T(open ? '收起' : '详情', open ? 'Less' : 'Details')}${icon('chev')}`;
};
btn.addEventListener('click', () => paint(flip(sec)));
paint(sec.classList.contains('td-open'));
h.classList.add('td-sec-h');
h.append(btn);
}
/* Open or close a section. Opening: the box eases to its new height while the details fade in.
* Closing mirrors it: the details fade out first, then the box settles, so nothing jumps at the end.
* Returns the new state. */
function flip(sec) {
sec._end?.();
const open = !sec.classList.contains('td-open'), ms = td.motion('base');
if (!ms) return sec.classList.toggle('td-open', open);
let timer, anim;
const end = sec._end = () => {
sec._end = null;
clearTimeout(timer);
anim?.cancel();
sec.style.overflow = '';
sec.classList.remove('td-showing', 'td-hiding');
sec.classList.toggle('td-open', open);
};
/* Cells that stay, and whatever sits below the tables, glide from where they were instead of jumping
* when the lines and columns around them come or go. A cell is anchored where its content sits:
* left, and middle in a table row or top when stacked on phones. */
const settle = () => {
const easing = getComputedStyle(sec).getPropertyValue('--ease').trim(), from = sec.offsetHeight;
const rows = [ ...sec.querySelectorAll('.th,.td'), ...[ ...sec.children ].filter(c => !c.querySelector('.td')) ];
const at = r => { const b = r.getBoundingClientRect(); return b.height ? [ b.left, b.top + (getComputedStyle(r).display == 'table-cell' ? b.height / 2 : 0) ] : null };
const was = rows.map(at);
sec.classList.remove('td-hiding');
sec.classList.toggle('td-open', open);
sec.classList.add('td-showing');
anim = sec.animate({ height: [ `${from}px`, `${sec.offsetHeight}px` ] }, { duration: ms, fill: 'forwards', easing });
if (getComputedStyle(sec).display != 'table') sec.style.overflow = 'hidden'; // a table only ever shrinks: its rows ease shorter
rows.forEach((r, i) => {
const now = at(r), dx = was[i] && now && was[i][0] - now[0], dy = was[i] && now && was[i][1] - now[1];
if (Math.abs(dx) + Math.abs(dy) > 1) r.animate({ transform: [ `translate(${dx}px,${dy}px)`, 'none' ] }, { duration: ms, easing });
});
timer = setTimeout(end, ms);
};
if (open) settle();
else { sec.classList.add('td-hiding'); timer = setTimeout(settle, td.motion('fast')); }
return open;
}
return baseclass.extend({
__init__() {
const view = document.getElementById('view');
/* the theme's own pages are already plain; the home page repaints every 2 s and need not be rescanned */
if (!view || /^admin-(home|clients|apps|system-appearance)$/.test(document.body.dataset.page || '')) return;
let queued = false;
const run = () => { queued = false; scan(view); };
new MutationObserver(() => queued || (queued = true, requestAnimationFrame(run)))
.observe(view, { childList: true, subtree: true });
run();
}
});
@@ -0,0 +1,279 @@
'use strict';
'require baseclass';
'require ui';
'require poll';
'require 7dollar.common as td';
'require 7dollar.tidy as tidy';
/*
* Navigation for the 7Dollar theme.
* Native LuCI pages are regrouped into seven plain-language sections;
* anything unknown falls back to "Apps" so third-party plugins always show up.
*/
const T = td.T, icon = td.icon, esc = td.esc;
const mqPhone = window.matchMedia('(max-width:760px)');
return baseclass.extend({
__init__() {
td.loadMenu().then(L.bind(this.render, this));
this.bindKeys();
this.bindMode();
this.bindVisibility();
},
/* Every LuCI page refreshes through one shared poll loop; stop it while the tab is hidden so a
* forgotten tab costs the router nothing. Coming back restarts it, which refreshes at once. */
bindVisibility() {
let paused = false;
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
if (poll.active()) { poll.stop(); paused = true; }
}
else if (paused) {
paused = false;
poll.start();
}
});
},
render(tree) {
const pages = td.flatten(tree);
const groups = td.grouped(pages);
const here = L.env.dispatchpath.join('/');
let current = null;
pages.forEach(p => {
if ((here == p.path || here.indexOf(p.path + '/') == 0) && (!current || p.path.length > current.path.length))
current = p;
});
this.pages = pages;
this.groups = groups;
this.current = current;
this.renderNav(groups, current);
this.renderPills(groups, current);
if (current)
this.renderTabs(current.node, current.path, current.path.split('/').length);
const btn = document.getElementById('td-search');
if (btn) btn.addEventListener('click', () => this.openSearch());
},
href(group) {
const first = group.list[0];
return L.url(first.path);
},
renderNav(groups, current) {
const nav = document.getElementById('td-nav');
if (!nav) return;
nav.innerHTML = groups.map((g, i) => {
const on = current && current.group == g.id;
const short = g.short ? `<span class="lbl has-short">${esc(g.label)}</span><span class="short">${esc(g.short)}</span>`
: `<span class="lbl">${esc(g.label)}</span>`;
return `<a href="${this.href(g)}" data-g="${g.id}" title="${esc(g.label)}" class="${on ? 'on' : ''}${g.mob === false ? ' mob-hide' : ''}" style="animation-delay:${i * 25}ms">${icon(g.icon)}${short}</a>`;
}).join('');
const sys = nav.querySelector('[data-g="system"]');
if (sys)
sys.addEventListener('click', ev => {
if (!mqPhone.matches) return;
ev.preventDefault();
this.openSheet();
});
},
renderPills(groups, current) {
const box = document.getElementById('td-pills');
if (!box || !current) return;
const g = groups.find(x => x.id == current.group);
let items = [];
if (g.id == 'apps') {
if (current.path == 'admin/apps') return;
const all = g.list.find(p => p.path == 'admin/apps');
if (all)
box.innerHTML = `<a class="back" href="${L.url(all.path)}">${icon('chev')}${esc(all.title)}</a>`;
box.innerHTML += `<a class="on" href="${L.url(current.path)}">${esc(current.title)}</a>`;
return;
}
items = g.list;
if (items.length < 2) return;
/* everyday pages first; the rest wait behind "More" unless one of them is open */
const pill = (p, cls) => `<a href="${L.url(p.path)}" class="${p === current ? 'on' : cls || ''}">${esc(p.title)}</a>`;
const rest = items.filter(p => g.pages.indexOf(p.path) < 0);
const fold = rest.length > 1 && rest.indexOf(current) < 0;
box.innerHTML = (fold ? items.filter(p => rest.indexOf(p) < 0) : items).map(p => pill(p)).join('')
+ (fold ? `<a href="#" role="button" class="fold">${esc(T('更多', 'More'))}${icon('chev')}</a>` : '');
if (fold)
box.lastChild.addEventListener('click', ev => {
ev.preventDefault();
ev.currentTarget.outerHTML = rest.map(p => pill(p, 'td-in')).join('');
edge();
});
const on = box.querySelector('.on');
if (on && on.scrollIntoView) box.scrollLeft = Math.max(0, on.offsetLeft - 40);
const edge = () => {
box.classList.toggle('scrolls', box.scrollWidth > box.clientWidth + 2);
box.classList.toggle('end', box.scrollLeft + box.clientWidth >= box.scrollWidth - 2);
};
box.addEventListener('scroll', edge, { passive: true });
window.addEventListener('resize', edge);
edge();
},
renderTabs(node, url, level) {
const container = document.getElementById('tabmenu');
const children = ui.menu.getChildren(node);
if (!container || !children.length) return;
const ul = E('ul', { 'class': 'tabs' });
let active = null;
children.forEach(child => {
const isActive = (L.env.dispatchpath[level] == child.name);
ul.appendChild(E('li', { 'class': 'tabmenu-item-%s%s'.format(child.name, isActive ? ' active' : '') }, [
E('a', { 'href': L.url(url, child.name) }, [ _(child.title) ])
]));
if (isActive) active = child;
});
container.appendChild(ul);
container.style.display = '';
if (active)
this.renderTabs(td.realNode(node, active), url + '/' + active.name, level + 1);
},
/* ---------- search (⌘K) ---------- */
entries() {
if (this._entries) return this._entries;
const out = [];
(this.groups || []).forEach(g => g.list.forEach(p => {
out.push({ path: p.path, title: p.title, group: g.label, icon: g.icon, en: p.node.title || '' });
ui.menu.getChildren(p.node).forEach(c => out.push({
path: p.path + '/' + c.name, title: p.title + ' · ' + _(c.title), group: g.label, icon: g.icon, en: c.title || ''
}));
}));
return (this._entries = out);
},
openSearch() {
if (document.querySelector('.td-pop:not(.td-out)')) return;
const pop = td.html(`<div class="td-pop" role="dialog" aria-modal="true">
<div class="td-pop-box">
<label class="td-pop-in">${icon('search')}<input type="search" placeholder="${esc(T('搜索功能或设置,例如“端口转发”', 'Search pages and settings'))}" autocomplete="off"><kbd>Esc</kbd></label>
<div class="td-pop-list"></div>
</div></div>`);
document.body.appendChild(pop);
const input = pop.querySelector('input'), list = pop.querySelector('.td-pop-list');
const all = this.entries();
let sel = 0, shown = [];
const draw = () => {
const q = input.value.trim().toLowerCase();
shown = !q ? all.filter(e => e.path.split('/').length <= 3).slice(0, 40)
: all.filter(e => (e.title + ' ' + e.en + ' ' + e.group + ' ' + e.path).toLowerCase().indexOf(q) > -1).slice(0, 40);
sel = Math.min(sel, Math.max(0, shown.length - 1));
list.innerHTML = shown.length ? shown.map((e, i) =>
`<a href="${L.url(e.path)}" class="${i == sel ? 'on' : ''}" data-i="${i}">${icon(e.icon)}<span>${esc(e.title)}</span><small>${esc(e.group)}</small></a>`).join('')
: `<div class="td-pop-empty">${esc(T('没有找到相关功能', 'Nothing found'))}</div>`;
const on = list.querySelector('.on');
if (on) on.scrollIntoView({ block: 'nearest' });
};
const close = () => td.leave(pop);
input.addEventListener('input', () => { sel = 0; draw() });
input.addEventListener('keydown', ev => {
if (ev.key == 'ArrowDown') { sel = Math.min(sel + 1, shown.length - 1); draw(); ev.preventDefault() }
else if (ev.key == 'ArrowUp') { sel = Math.max(sel - 1, 0); draw(); ev.preventDefault() }
else if (ev.key == 'Enter' && shown[sel]) { location.href = L.url(shown[sel].path) }
else if (ev.key == 'Escape') close();
});
list.addEventListener('mousemove', ev => {
const a = ev.target.closest('a[data-i]');
if (a && +a.dataset.i != sel) { sel = +a.dataset.i; list.querySelectorAll('a').forEach(x => x.classList.toggle('on', x === a)) }
});
pop.addEventListener('click', ev => { if (ev.target === pop) close() });
draw();
input.focus();
},
/* ---------- phone: "More" sheet ---------- */
openSheet() {
if (document.querySelector('.td-pop:not(.td-out)')) return;
const rest = (this.groups || []).filter(g => g.mob === false || g.id == 'system');
const body = rest.map(g => `<div class="grp">${esc(g.label)}</div>` +
g.list.map(p => `<a href="${L.url(p.path)}" class="${this.current === p ? 'on' : ''}">${icon(g.id == 'apps' ? td.appIcon(p.path) : g.icon)}<span>${esc(p.title)}</span></a>`).join('')).join('');
const pop = td.html(`<div class="td-pop" role="dialog" aria-modal="true"><div class="td-pop-box">
<div class="td-pop-list">${body}</div>
<div class="td-sheet-tools">
<button class="btn" type="button" data-act="search">${icon('search')}${esc(T('搜索', 'Search'))}</button>
<button class="btn" type="button" data-act="mode">${icon('moon')}${esc(T('深浅色', 'Theme'))}</button>
<a class="btn" href="${L.url('admin/logout')}">${icon('logout')}${esc(T('退出', 'Log out'))}</a>
</div></div></div>`);
document.body.appendChild(pop);
pop.addEventListener('click', ev => {
const b = ev.target.closest('[data-act]');
if (ev.target === pop) td.leave(pop);
else if (b && b.dataset.act == 'search') { pop.remove(); this.openSearch() }
else if (b && b.dataset.act == 'mode') this.toggleMode();
});
},
/* ---------- keyboard & dark mode ---------- */
bindKeys() {
const kbd = document.querySelector('.td-search kbd');
if (kbd && !/Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent)) kbd.textContent = 'Ctrl K';
document.addEventListener('keydown', ev => {
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test((ev.target || {}).tagName || '') || (ev.target || {}).isContentEditable;
if ((ev.key == 'k' || ev.key == 'K') && (ev.metaKey || ev.ctrlKey)) { ev.preventDefault(); this.openSearch() }
else if (ev.key == '/' && !typing && !document.body.classList.contains('modal-overlay-active')) { ev.preventDefault(); this.openSearch() }
});
},
bindMode() {
const btn = document.getElementById('td-mode');
const sync = () => {
if (!btn) return;
const dark = document.documentElement.getAttribute('data-theme') == 'dark';
btn.innerHTML = icon(dark ? 'sun' : 'moon');
btn.title = dark ? T('切换到浅色', 'Light mode') : T('切换到深色', 'Dark mode');
};
if (btn) btn.addEventListener('click', () => this.toggleMode());
document.addEventListener('td-look', sync);
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (document.documentElement.getAttribute('data-mode') == 'auto')
td.applyLook({ palette: document.documentElement.getAttribute('data-palette'), mode: 'auto' });
});
sync();
},
toggleMode() {
const r = document.documentElement;
const mode = r.getAttribute('data-theme') == 'dark' ? 'light' : 'dark';
td.applyLook({ palette: r.getAttribute('data-palette') || 'clay', mode: mode });
td.saveSettings({ mode: mode }).catch(() => {});
}
});
@@ -0,0 +1,110 @@
'use strict';
'require view';
'require ui';
'require 7dollar.common as td';
/* Appearance & home preferences. Saved to /etc/config/7dollar immediately; never touches networking. */
const T = td.T, icon = td.icon, esc = td.esc;
const CARDS = [
[ 'rate', T('实时速率', 'Live traffic'), T('上传和下载速度曲线', 'Upload and download chart') ],
[ 'dev', T('在线设备', 'Online devices'), T('正在使用网络的设备', 'Devices currently online') ],
[ 'wifi', 'Wi‑Fi', T('名称、频段和连接数', 'Name, bands and clients'), t => td.menuHas(t, 'network/wireless'), T('这台设备没有无线网卡', 'This device has no wireless hardware') ],
[ 'sys', T('路由器状态', 'Router status'), T('处理器、内存、温度', 'CPU, memory, temperature') ],
[ 'ports', T('网口', 'Ports'), T('哪些网口接了网线、速率多少', 'Which ports are plugged in, and how fast') ],
[ 'disk', T('存储空间', 'Storage'), T('还剩多少空间装插件', 'Space left for apps and settings') ],
[ 'actions', T('常用操作', 'Quick actions'), T('备份、软件包、诊断、日志', 'Backup, software, diagnostics, logs') ],
[ 'apps', T('应用', 'Apps'), T('正在运行的插件', 'Plugins that are running'), t => td.flatten(t).some(p => p.group == 'apps' && p.path != 'admin/apps'), T('还没有安装插件', 'No plugins installed yet') ]
];
return view.extend({
load() {
return Promise.all([ td.loadSettings(), td.loadMenu(), td.uciSection('luci', 'main') ]);
},
render([ conf, tree, luci ]) {
this.conf = conf;
const usingUs = /\/7dollar$/.test((luci || {}).mediaurlbase || L.env.media || '');
const pal = td.PALETTES.map(([ id, name ]) => `<button type="button" class="td-pal" data-palette="${id}" data-pick="${id}">
<div class="pv"><div class="sb"><i></i><i></i><i></i><i></i></div><div class="cd"><i></i><i></i><i style="width:70%"></i><u></u></div></div>
<div class="nm"><span>${esc(name)}</span><span class="ck">${icon('tick')}</span></div></button>`).join('');
const cards = CARDS.map(([ k, n, d, need, why ]) => need && !need(tree)
? `<div class="td-row off"><div class="lb"><b>${esc(n)} <span class="td-chip mute">${esc(T('未检测到', 'Not found'))}</span></b><small>${esc(why)}</small></div><button type="button" class="td-switch" disabled aria-label="${esc(n)}"></button></div>`
: `<div class="td-row"><div class="lb"><b>${esc(n)}</b><small>${esc(d)}</small></div><button type="button" class="td-switch" data-card="${k}" aria-label="${esc(n)}"></button></div>`).join('');
const root = td.html(`<div class="td-look">
<div class="td-head"><div>
<p class="td-eyebrow">${esc(T('系统', 'System'))}</p>
<h1 class="td-serif">${esc(T('外观与首页', 'Appearance'))}</h1>
<p class="td-sub">${esc(T('只影响界面显示,立即生效,不会改动网络设置。', 'Only changes how the interface looks. Applies instantly and never touches your network.'))}</p>
</div></div>
${usingUs ? '' : `<div class="alert-message info"><h4>${esc(T('当前没有使用 7Dollar 主题', '7Dollar is not the active theme'))}</h4><p>${esc(T('下面的设置只在 7Dollar 主题下生效。', 'The settings below only apply to the 7Dollar theme.'))}</p><div class="right"><button type="button" class="btn primary" id="td-use">${esc(T('切换到 7Dollar', 'Use 7Dollar'))}</button></div></div>`}
<section class="td-card td-sect">
<h3 class="td-sect-t">${esc(T('配色', 'Palette'))}</h3>
<div class="td-palettes">${pal}</div>
<div class="td-row"><div class="lb"><b>${esc(T('显示模式', 'Mode'))}</b></div>
<div class="td-seg" id="td-modes"><button type="button" data-m="light">${esc(T('浅色', 'Light'))}</button><button type="button" data-m="dark">${esc(T('深色', 'Dark'))}</button><button type="button" data-m="auto">${esc(T('跟随系统', 'Auto'))}</button></div></div>
</section>
<section class="td-card td-sect">
<h3 class="td-sect-t">${esc(T('首页卡片', 'Home cards'))}</h3>
<p class="td-sect-d">${esc(T('“网络连接”卡片始终显示。', 'The Connection card is always shown.'))}</p>
<div class="td-rows">${cards}</div>
</section>
<div class="td-hint">${icon('info')}<span>${esc(T('换回原主题:系统 → 通用 → 语言和界面', 'Switch back: System → General → Language and Style'))}</span></div>
</div>`);
this.root = root;
root.querySelectorAll('[data-pick]').forEach(b => b.addEventListener('click', () => this.update({ palette: b.dataset.pick })));
root.querySelectorAll('#td-modes button').forEach(b => b.addEventListener('click', () => this.update({ mode: b.dataset.m })));
root.querySelectorAll('[data-card]').forEach(b => b.addEventListener('click', () => {
const k = b.dataset.card, field = td.OPT_IN.indexOf(k) > -1 ? 'shown_cards' : 'hidden_cards';
const list = td.words(this.conf[field]), i = list.indexOf(k);
i > -1 ? list.splice(i, 1) : list.push(k);
this.update({ [field]: list.join(' ') });
}));
const use = root.querySelector('#td-use');
if (use) use.addEventListener('click', () => {
use.disabled = true;
td.uciSet('luci', 'main', { mediaurlbase: '/luci-static/7dollar' }).then(() => location.reload())
.catch(e => { use.disabled = false; ui.addNotification(null, E('p', e.message)) });
});
this.sync();
return root;
},
sync() {
const c = this.conf;
this.root.querySelectorAll('.td-pal').forEach(b => b.classList.toggle('on', b.dataset.pick == c.palette));
this.root.querySelectorAll('#td-modes button').forEach(b => b.classList.toggle('on', b.dataset.m == c.mode));
this.root.querySelectorAll('[data-card]').forEach(b => b.classList.toggle('on', td.cardOn(c, b.dataset.card)));
},
update(patch) {
Object.assign(this.conf, patch);
this.sync();
if (td.active && ('palette' in patch || 'mode' in patch))
td.applyLook(this.conf);
const save = {};
for (const k in patch) save[k] = patch[k];
return td.saveSettings(save)
.then(() => td.toast(T('已保存', 'Saved')))
.catch(e => ui.addNotification(null, E('p', T('保存失败:', 'Could not save: ') + (e.message || e)), 'error'));
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});
@@ -0,0 +1,46 @@
'use strict';
'require view';
'require ui';
'require 7dollar.common as td';
/* Every plugin page the router has, as tiles. The theme depends on none of them. */
const T = td.T, icon = td.icon, esc = td.esc;
return view.extend({
load() {
if (!td.active) {
location.replace(L.url('admin/services'));
return new Promise(() => {});
}
return td.loadMenu();
},
render(tree) {
const pages = td.flatten(tree).filter(p => p.group == 'apps' && p.path != 'admin/apps');
const CAT = { services: T('服务', 'Service'), vpn: 'VPN', nas: T('存储', 'Storage'), docker: T('容器', 'Container'), statistics: T('统计', 'Statistics') };
const tiles = pages.map((p, i) => {
const cat = CAT[p.path.split('/')[1]] || T('插件', 'Plugin');
return `<a class="td-app-t" href="${L.url(p.path)}" style="animation-delay:${Math.min(i, 10) * 30}ms"><div class="td-av">${icon(td.appIcon(p.path))}</div><div><b>${esc(p.title)}</b><small>${esc(cat)}</small></div></a>`;
}).join('');
const add = td.software(tree);
return td.html(`<div class="td-appsview">
<div class="td-head"><div>
<p class="td-eyebrow">${esc(T('应用', 'Apps'))}</p>
<h1 class="td-serif">${esc(T('已安装的应用', 'Installed apps'))}</h1>
<p class="td-sub">${esc(pages.length ? T(`共 ${pages.length} 个`, `${pages.length} installed`)
: T('还没有安装插件。', 'No plugins installed yet.'))}</p>
</div></div>
<div class="td-apps">${tiles}
${add ? `<a class="td-app-t add" href="${L.url('admin/' + add)}"><div class="td-av">${icon('plus')}</div><div><b style="color:var(--ink-2)">${esc(T('安装更多应用', 'Get more apps'))}</b><small>${esc(T('前往软件包', 'Open Software'))}</small></div></a>` : ''}
</div>
</div>`);
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});
@@ -0,0 +1,92 @@
'use strict';
'require view';
'require poll';
'require 7dollar.common as td';
/* All devices: online (Wi-Fi + wired) and recently seen DHCP clients. The summary tiles filter the list. */
const T = td.T, icon = td.icon, esc = td.esc;
const VIEWS = [
[ 'on', T('在线', 'Online'), c => c.online ],
[ 'wifi', 'Wi‑Fi', c => c.online && c.conn == 'wifi' ],
[ 'wired', T('有线', 'Wired'), c => c.online && c.conn != 'wifi', T('局域网', 'LAN') ], // a side router sees the whole LAN here
[ 'off', T('最近连接过', 'Recently seen'), c => !c.online ]
];
return view.extend({
load() {
if (!td.active) {
location.replace(L.url('admin/status/overview'));
return new Promise(() => {});
}
return td.clients();
},
render(list) {
const root = td.html(`<div class="td-devices">
<div class="td-head"><div>
<p class="td-eyebrow">${esc(T('设备', 'Devices'))}</p>
<h1 class="td-serif">${esc(T('谁在用网络', 'Who is online'))}</h1>
<p class="td-sub" id="td-dsum">&nbsp;</p>
</div>
<a class="btn" href="${L.url('admin/network/dhcp')}">${icon('lock')}${esc(T('给设备固定 IP', 'Reserve an IP'))}</a></div>
<div class="td-stats" id="td-dstats">${VIEWS.map(([ k, n ]) => `<button type="button" class="td-stat" data-v="${k}"><small>${esc(n)}</small><b>0</b></button>`).join('')}</div>
<section class="td-card"><div class="td-devlist" id="td-dlist"></div></section>
</div>`);
this.root = root;
this.view = 'on';
root.querySelector('#td-dstats').addEventListener('click', ev => {
const b = ev.target.closest('[data-v]');
if (b) { this.view = b.dataset.v; this.paint(this.list); }
});
this.paint(list);
poll.add(() => td.clients().then(l => this.paint(l)), 5);
return root;
},
row(c) {
const meta = [];
if (c.ip) meta.push(`<span>${esc(c.ip)}</span>`);
meta.push(`<span>${esc(c.mac)}</span>`);
let sub;
if (!c.online) sub = c.expires > 0 ? T('租约剩余 ', 'Lease ') + td.duration(c.expires) : T('离线', 'Offline');
else if (c.conn == 'wifi') {
const [ s ] = td.signal(c.signal);
sub = `Wi‑Fi ${td.bandName(c.band)} · ${s}${c.signal ? ` (${c.signal} dBm)` : ''}`;
if (c.link) meta.unshift(`<span><b>${Math.round(c.link)} Mbps</b></span>`);
if (c.since) meta.push(`<span>${esc(T('已连接 ', 'Connected ') + td.duration(c.since))}</span>`);
}
else sub = td.connName(c);
return `<div class="td-dev"><div class="td-av">${icon(c.kind)}</div><div class="nm"><b>${esc(c.display)}</b><small>${esc(sub)}</small></div><div class="meta">${meta.join('')}</div></div>`;
},
paint(list) {
this.list = list;
const on = list.filter(c => c.online);
const $ = id => this.root.querySelector('#' + id);
$('td-dsum').textContent = on.length
? T(`现在有 ${on.length} 台设备在线。名字来自设备自己上报的主机名。`, `${on.length} device${on.length == 1 ? '' : 's'} online right now.`)
: T('现在没有设备在线。', 'No devices online right now.');
let rows = [];
const lan = list.some(c => c.conn == 'lan');
VIEWS.forEach(([ k, n, match, alt ]) => {
const b = $('td-dstats').querySelector(`[data-v="${k}"]`), sel = list.filter(match);
b.firstChild.textContent = lan && alt || n;
b.lastChild.textContent = sel.length;
b.hidden = lan && k == 'wifi' && !sel.length; // no Wi-Fi of our own to count
b.setAttribute('aria-pressed', k == this.view);
if (k == this.view) rows = sel;
});
const box = $('td-dlist'), html = rows.length ? rows.map(c => this.row(c)).join('') : `<div class="td-empty-row">${esc(T('这里暂时没有设备', 'No devices here'))}</div>`;
if (box._html !== html) box.innerHTML = box._html = html; // every 5 s, but the DOM only moves when something changed
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});
@@ -0,0 +1,556 @@
'use strict';
'require view';
'require fs';
'require poll';
'require request';
'require ui';
'require 7dollar.common as td';
/*
* 7Dollar home dashboard. Only router data by default. The opt-in apps card lists whatever
* plugins are running: name from the menu, state from procd, no polling of the plugins.
*/
const T = td.T, icon = td.icon, esc = td.esc;
const N = 60;
const RING = 2 * Math.PI * 24;
/* One line of what matters most for the popular apps, read from their config (never their API);
* every other app shows name and state only. Keyed by procd service name. */
const MODE = {
rule: T('按规则', 'Rule'), global: T('全局', 'Global'), direct: T('直连', 'Direct'), all: T('全局', 'Global'), custom: T('自定义', 'Custom'),
gfw: T('GFW 列表', 'GFW list'), gfwlist: T('GFW 列表', 'GFW list'), router: T('绕过大陆', 'Bypass mainland'), bypass_mainland_china: T('绕过大陆', 'Bypass mainland'),
proxy_mainland_china: T('只代理大陆', 'Mainland only'), oversea: T('海外模式', 'Overseas'),
none: T('未接管 DNS', 'DNS not taken over'), redirect: T('接管 53 端口', 'Takes over port 53'), 'dnsmasq-upstream': T('dnsmasq 上游', 'dnsmasq upstream'), exchange: T('替换 dnsmasq', 'Replaces dnsmasq')
};
const sec = (cfg, s) => s[0] == '@' ? td.uciType(cfg, s.slice(1)).then(a => Object.values(a)[0] || {}) : td.uciSection(cfg, s);
const plain = (cfg, s, f) => () => sec(cfg, s).then(c => ({ sub: f(c) }));
/* current node: the section named in `key`, shown by its `label` field */
const node = (cfg, s, key, label, more) => () => sec(cfg, s).then(c => (c[key] && c[key] != 'nil' ? td.uciSection(cfg, c[key]) : Promise.resolve({}))
.then(n => ({ sub: [ n[label] || (c[key] != 'nil' && c[key]) || T('未选节点', 'No node'), more && more(c) ].filter(Boolean).join(' · ') })));
const panel = port => ({ link: `http://${location.hostname}:${port}/` });
const shares = (cfg, type) => () => Promise.all([ td.uciType(cfg, type), td.mounts() ]).then(([ s, m ]) => {
const list = Object.values(s).filter(x => x.path);
const disk = p => m.filter(x => x.mount == '/' || x.mount == p || p.indexOf(x.mount + '/') == 0).sort((a, b) => b.mount.length - a.mount.length)[0];
const d = list.map(x => disk(x.path)).find(Boolean);
return { sub: list.map(x => x.name).join(' · '), rt: d && d.size ? T(`剩余 ${td.bytes(d.avail)} / 共 ${td.bytes(d.size)}`, `${td.bytes(d.avail)} free of ${td.bytes(d.size)}`) : '' };
});
const APPS = {
openclash: () => td.uciSection('openclash', 'config').then(c => ({
sub: String(c.en_mode || c.operation_mode || '').replace(/^fake-ip/, 'Fake-IP').replace(/^redir-host/, 'Redir-Host').replace(/-(tun|mix)$/, s => ' · ' + s.slice(1).toUpperCase()),
seg: c.proxy_mode || 'rule' })),
passwall: node('passwall', '@global', 'tcp_node', 'remarks'),
passwall2: node('passwall2', '@global', 'node', 'remarks'),
shadowsocksr: node('shadowsocksr', '@global', 'global_server', 'alias', c => MODE[c.run_mode]),
homeproxy: node('homeproxy', 'config', 'main_node', 'label', c => MODE[c.routing_mode]),
nikki: plain('nikki', 'mixin', c => MODE[c.mode]),
adguardhome: () => td.uciSection('AdGuardHome', 'AdGuardHome').then(c => Object.assign({ sub: MODE[c.redirect] }, panel(c.httpport || 3000))),
openbox: () => td.readFile('/opt/open-box/data/panel-port').then(p => panel(+String(p || '').trim() || 2026)),
mosdns: plain('mosdns', 'config', c => c.listen_port && T('端口 ', 'Port ') + c.listen_port),
smartdns: plain('smartdns', '@smartdns', c => c.port && T('端口 ', 'Port ') + c.port),
bandix: plain('bandix', 'general', c => c.iface && T('监控 ', 'Watching ') + c.iface),
ksmbd: shares('ksmbd', 'share'),
samba4: shares('samba4', 'sambashare')
};
const PROTO = { dhcp: T('自动获取', 'DHCP'), pppoe: T('宽带拨号', 'PPPoE'), static: T('静态地址', 'Static'), dhcpv6: 'DHCPv6', qmi: T('移动网络', 'Cellular'), ncm: T('移动网络', 'Cellular'), modemmanager: T('移动网络', 'Cellular') };
return view.extend({
load() {
if (!td.active) {
location.replace(L.url('admin/status/overview'));
return new Promise(() => {});
}
return Promise.all([
td.loadSettings(),
td.board(),
td.sysinfo(),
td.wan(),
td.loadMenu().then(menu => Promise.all([ menu, td.menuHas(menu, 'network/wireless') ? td.wifiInfo() : null ])),
td.uciType('firewall', 'defaults'),
Promise.all([ 'mt7915e', 'mt7996e' ].map(m => td.readFile(`/sys/module/${m}/parameters/wed_enable`))).then(l => l.find(Boolean)), // Wi-Fi 6 / Wi-Fi 7 MediaTek
td.readFile('/proc/sys/net/ipv4/tcp_congestion_control'),
td.readFile('/proc/stat'),
td.readFile('/proc/net/dev')
]);
},
render([ conf, board, info, wan, [ menu, wifi ], fw, wed, cc, stat, dev ]) {
const apps = td.flatten(menu).filter(p => p.group == 'apps' && p.path != 'admin/apps');
const mode = wan && wan.up ? wan.mode : 'wan';
const software = td.software(menu);
this.s = {
down: new Array(N).fill(0), up: new Array(N).fill(0),
last: null, cpu: td.cpuStat(stat), cpuPct: null, wan: wan, wifi: wifi || { radios: {}, aps: [] }, info: info, board: board,
clients: [], ping: null, apps: apps, hasWifi: !!(wifi && Object.keys(wifi.radios).length), mode: mode
};
const fwd = Object.values(fw || {})[0] || {};
const tags = [];
if (fwd.flow_offloading_hw == '1') tags.push(T('硬件流量卸载', 'Hardware offload'));
else if (fwd.flow_offloading == '1') tags.push(T('软件流量卸载', 'Software offload'));
if (/^Y/.test(wed || '')) tags.push(T('无线加速 WED', 'Wireless offload (WED)'));
if (/bbr/.test(cc || '')) tags.push(T('BBR 拥塞控制', 'BBR congestion control'));
this.s.tags = tags;
let n = 1;
const card = (key, cls, inner) => !td.cardOn(conf, key) ? '' : `<section class="td-card ${cls}" data-card="${key}" style="--i:${n++}">${inner}</section>`;
const col = c => c.length ? `<div class="td-col">${c.join('')}</div>` : '';
/* Topology follows how this box is wired: main router (upstream → this → devices) or
* side router / AP, which hangs off the main router next to the other devices. */
const UP = { wan: [ 'modem', T('上级网络', 'Upstream') ], sta: [ 'wifi', T('上级 Wi‑Fi', 'Upstream Wi‑Fi') ], side: [ 'router', T('主路由', 'Main router') ] }[mode];
const link = (attr, tid) => `<div class="td-link"${attr}><span class="t" id="${tid}">&nbsp;</span><div class="ln"><i></i><i></i></div></div>`;
const nUp = `<div class="td-node" id="td-up-node"><div class="ic" id="td-up-icon">${icon(UP[0])}</div><b id="td-up-title">${esc(UP[1])}</b><small id="td-proto">—</small></div>`;
const nMe = `<div class="td-node me"><div class="ic">${icon('router')}</div><b>${esc(board.hostname || 'OpenWrt')}</b><small id="td-router-role">${esc(mode == 'side' ? T('旁路由', 'Side router') : T('这台路由器', 'This router'))}</small></div>`;
const nDev = `<div class="td-node"><div class="ic">${icon('devices')}</div><b id="td-ndev">—</b><small id="td-ndev-s">&nbsp;</small></div>`;
const lUp = link(' id="td-link-up"', 'td-lat'), lLan = link('', 'td-lan-t');
const topo = mode == 'side' ? nMe + lUp + nUp + lLan + nDev : nUp + lUp + nMe + lLan + nDev;
/* A side router receives and resends the same packets on one LAN port, so "down/up" would just
* be the same number twice: show one "forwarded" figure instead. */
const rate = (id, label, cls) => `<div class="td-rate${cls || ''}"><small><i></i>${esc(label)}</small><span class="td-big" id="td-${id}">0</span><span class="td-unit" id="td-${id}-u">Kbps</span></div>`;
const rates = (mode == 'side' ? rate('down', T('经过本机', 'Through this box'))
: rate('down', T('下载', 'Download')) + rate('up', T('上传', 'Upload'), ' up'))
+ `<div class="td-rate boot"><small>${esc(T('本次开机', 'Since boot'))}</small><span id="td-boot">—</span></div>`;
const os = board.release ? `${board.release.distribution} ${board.release.version}` : 'OpenWrt';
const rateCard = card('rate', 'k-rate', `
<div class="td-card-h"><h3>${esc(T('实时速率', 'Live traffic'))}</h3><span class="td-muted">${esc(T('过去 2 分钟', 'Last 2 minutes'))}</span></div>
<div class="td-rates">${rates}</div>
<svg class="td-chart" id="td-chart" viewBox="0 0 600 118" preserveAspectRatio="none" aria-hidden="true">
<defs><linearGradient id="td-gd" x1="0" y1="0" x2="0" y2="1"><stop offset="0" style="stop-color:var(--accent);stop-opacity:.26"/><stop offset="1" style="stop-color:var(--accent);stop-opacity:0"/></linearGradient></defs>
<path fill="url(#td-gd)"/><path fill="none" style="stroke:var(--accent)" stroke-width="2" vector-effect="non-scaling-stroke"/>
${mode == 'side' ? '' : '<path fill="none" style="stroke:var(--second)" stroke-width="1.6" stroke-dasharray="3 4" vector-effect="non-scaling-stroke"/>'}
</svg>`);
/* Cards below the top row, in reading order. Each goes into whichever column is shorter so far
* (rough heights), so the two columns stay balanced whatever is hidden or missing. */
const H = { dev: 6, wifi: 4, sys: 3.5, apps: 3, ports: 2, disk: 2, actions: 3 }, cols = [ [], [] ], h = [ 0, 0 ];
for (const [ k, html ] of [
[ 'dev', card('dev', 'k-dev', `
<div class="td-card-h"><h3>${esc(T('在线设备', 'Online devices'))}</h3><a href="${L.url('admin/clients')}">${esc(T('全部', 'All'))}${icon('chev')}</a></div>
<div id="td-devs"><div class="td-empty-row">${esc(T('正在读取…', 'Loading…'))}</div></div>`) ],
[ 'wifi', this.s.hasWifi ? card('wifi', 'k-wifi', `
<div class="td-card-h"><h3>Wi‑Fi</h3><a href="${L.url('admin/network/wireless')}">${esc(T('设置', 'Settings'))}${icon('chev')}</a></div>
<div id="td-wifi"></div>`) : '' ],
[ 'sys', card('sys', 'k-sys', `
<div class="td-card-h"><h3>${esc(T('路由器状态', 'Router status'))}</h3><span class="td-muted">${esc(os)}</span></div>
<div class="td-rings">
${this.ring('cpu', T('处理器', 'CPU'))}
${this.ring('mem', T('内存', 'Memory'))}
${this.ring('temp', T('温度', 'Temperature'), 'warm')}
</div>
<div class="td-tags" id="td-tags"></div>`) ],
[ 'apps', apps.length ? card('apps', 'k-apps', `
<div class="td-card-h"><h3>${esc(T('应用', 'Apps'))}</h3><a href="${L.url('admin/apps')}">${esc(T('全部', 'All'))}${icon('chev')}</a></div>
<div id="td-apps"><div class="td-empty-row">${esc(T('正在读取…', 'Loading…'))}</div></div>`) : '' ],
[ 'ports', card('ports', 'k-ports', `
<div class="td-card-h"><h3>${esc(T('网口', 'Ports'))}</h3><span class="td-muted" id="td-ports-n"></span></div>
<dl class="td-kv" id="td-ports"></dl>`) ],
[ 'disk', card('disk', 'k-disk', `
<div class="td-card-h"><h3>${esc(T('存储空间', 'Storage'))}</h3></div>
<div id="td-disk"></div>`) ],
[ 'actions', card('actions', 'k-actions', `
<div class="td-card-h"><h3>${esc(T('常用操作', 'Quick actions'))}</h3></div>
<div class="td-acts">
${this.act('admin/system/flash', 'backup', T('备份配置', 'Back up'))}
${software ? this.act('admin/' + software, 'box', T('软件包', 'Software')) : ''}
${this.act('admin/network/diagnostics', 'pulse', T('网络诊断', 'Diagnostics'))}
${this.act('admin/status/logs', 'doc', T('查看日志', 'Logs'))}
</div>`) ]
]) if (html) { const c = h[1] < h[0] ? 1 : 0; cols[c].push(html); h[c] += H[k]; }
const root = td.html(`<div class="td-home">
<div class="td-head">
<div>
<p class="td-eyebrow" id="td-today"></p>
<h1 class="td-serif" id="td-greet">${esc(T('你好', 'Hello'))}</h1>
<p class="td-sub" id="td-summary">&nbsp;</p>
</div>
<a class="btn" href="${L.url('admin/system/reboot')}">${icon('refresh')}${esc(T('重启路由器', 'Reboot'))}</a>
</div>
<div class="td-grid"><div class="td-pair">
<section class="td-card k-conn" data-card="conn">
<div class="td-card-h"><h3>${esc(T('网络连接', 'Connection'))}</h3><span class="td-chip" id="td-conn-chip"></span></div>
<div class="td-topo">${topo}</div>
<dl class="td-facts">
<div><dt>${esc(mode == 'side' ? T('本机地址', 'Address') : T('上网地址', 'WAN address'))}</dt><dd id="td-wanip">—</dd></div>
<div><dt>${esc(T('网关延迟', 'Gateway latency'))}</dt><dd id="td-ping">—</dd></div>
<div><dt>DNS</dt><dd id="td-dns">—</dd></div>
<div><dt>${esc(T('已连接', 'Connected for'))}</dt><dd id="td-wanup">—</dd></div>
</dl>
<div class="td-lines" id="td-lines"></div>
</section>
${rateCard}
</div><div class="td-cols">${col(cols[0])}${col(cols[1])}</div></div>
</div>`);
this.root = root;
this.$ = id => root.querySelector('#' + id);
this.greet();
this.paintStatic();
this.paintWifi(this.s.wifi);
this.paintDisk();
this.refreshPorts();
this.ticks = 0;
this.sample(dev, info);
this.refreshClients();
this.pingGateway();
poll.add(L.bind(this.tick, this), 2);
poll.add(L.bind(this.slow, this), 10);
this.paintApps();
requestAnimationFrame(() => requestAnimationFrame(() => this.paintRings()));
return root;
},
ring(key, label, cls) {
return `<div class="td-ring"><svg viewBox="0 0 58 58"><circle class="bg" cx="29" cy="29" r="24"/><circle class="fg ${cls || ''}" id="td-ring-${key}" cx="29" cy="29" r="24" style="stroke-dasharray:${RING};stroke-dashoffset:${RING}"/></svg><div><b id="td-ring-${key}-v">—</b><small id="td-ring-${key}-l">${esc(label)}</small></div></div>`;
},
act(path, ic, title) {
return `<a class="td-act" href="${L.url(path)}">${icon(ic)}<b>${esc(title)}</b></a>`;
},
set(id, text) {
const el = this.$(id);
if (el && el.textContent !== String(text)) el.textContent = text;
},
/* innerHTML only when it changed: polled cards keep their DOM (and hover state) between ticks */
put(el, html) {
if (el && el._html !== html) el.innerHTML = el._html = html;
},
greet() {
const d = new Date(), h = d.getHours();
const hi = T(h < 5 ? '夜深了' : h < 11 ? '早上好' : h < 14 ? '中午好' : h < 18 ? '下午好' : '晚上好',
h < 12 ? 'Good morning' : h < 18 ? 'Good afternoon' : 'Good evening');
const ok = this.s.wan && this.s.wan.up;
this.set('td-greet', ok ? hi + T(',一切都好', ', all good') : T('网络好像断开了', 'You seem to be offline'));
this.set('td-today', td.ZH ? `星期${'日一二三四五六'[d.getDay()]} · ${d.getMonth() + 1} 月 ${d.getDate()} 日`
: d.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric' }));
},
paintStatic() {
const w = this.s.wan;
const bands = [...new Set((this.s.wifi.aps || []).filter(a => a.up && a.stations.length).map(a => td.bandName(a.band)))];
/* PPPoE is terminated by this router, not by the upstream network. Keep the labels in sync
* when the WAN reconnects or fails over to a different protocol. */
const dial = this.s.mode == 'wan' && w && w.proto == 'pppoe';
if (this.s.mode == 'wan') {
this.put(this.$('td-up-icon'), icon(dial ? 'globe' : 'modem'));
this.set('td-up-title', dial ? T('互联网', 'Internet') : T('上级网络', 'Upstream'));
}
this.set('td-router-role', this.s.mode == 'side' ? T('旁路由', 'Side router') : dial ? T('本机拨号', 'PPPoE dial-up') : T('这台路由器', 'This router'));
this.set('td-lan-t', this.s.mode == 'side' ? T('局域网', 'LAN') : bands.length ? 'Wi‑Fi ' + bands.join(' / ') : T('有线', 'Wired'));
const ok = !!(w && w.up), chip = this.$('td-conn-chip');
this.$('td-up-node').classList.toggle('bad', !ok);
this.$('td-link-up').classList.toggle('down', !ok);
if (chip.dataset.ok != String(ok)) {
chip.dataset.ok = ok;
chip.className = ok ? 'td-chip' : 'td-chip bad';
chip.innerHTML = ok ? `<span class="td-dot live"></span>${esc(T('畅通', 'Online'))}` : `<span class="td-dot"></span>${esc(T('未连接', 'Offline'))}`;
}
/* further lines (IPTV, a backup WAN): one quiet row each under the main one */
const lines = ((w && w.more) || []).map(u => `<p><span class="td-dot"></span><b>${esc(u.name)}</b><span>${esc([ PROTO[u.proto] || u.proto, u.ip, u.uptime && td.duration(u.uptime) ].filter(Boolean).join(' · '))}</span></p>`).join('');
this.put(this.$('td-lines'), lines);
if (!ok) {
this.set('td-proto', T('没有连接', 'Not connected'));
return;
}
this.set('td-proto', this.s.mode == 'side' ? w.gw || '—' : this.s.mode == 'sta' ? T('无线中继', 'Wi‑Fi uplink') : dial ? T('运营商网络', 'ISP network') : PROTO[w.proto] || w.proto || '—');
this.set('td-wanip', w.ip || w.ip6 || '—');
this.set('td-dns', td.dnsName(w.dns, w.gw, this.s.mode == 'side' ? T('主路由', 'Main router') : null));
this.set('td-wanup', w.uptime ? td.duration(w.uptime) : '—');
this.paintTags();
},
paintTags() {
const box = this.$('td-tags');
this.put(box, this.s.tags.map(t => `<span class="td-tag">${icon('check')}${esc(t)}</span>`).join(''));
},
paintWifi(wifi) {
const box = this.$('td-wifi');
this.s.wifi = wifi;
if (!box) return;
const radios = wifi.radios || {}, aps = wifi.aps || [];
const devs = k => k + ' ' + T('台', k == 1 ? 'client' : 'clients');
const n = aps.reduce((a, ap) => a + ap.stations.length, 0);
const guest = aps.find(a => (a.network || []).some(x => /guest/i.test(x)));
/* The headline is the network people mostly join: 5 GHz first (2.4 GHz is often the
* smart-home one), never the guest network. A band with another name shows it on its tile. */
const rank = ap => (ap.up ? 10 : 0) + (ap == guest ? -5 : 0) + ({ '5g': 3, '6g': 2, '2g': 1 }[ap.band] || 0);
const main = aps.filter(ap => ap.up).sort((a, b) => rank(b) - rank(a))[0];
const tile = (label, value, sub, off) => `<div${off ? ' class="off"' : ''}><dt>${esc(label)}</dt><dd>${esc(value)}</dd>${sub ? `<dd>${esc(sub)}</dd>` : ''}</div>`;
const tiles = Object.keys(radios).sort((a, b) => String((radios[a].config || {}).band).localeCompare(String((radios[b].config || {}).band))).map(r => {
const c = radios[r].config || {}, iw = (radios[r].iwinfo || {});
const on = radios[r].up && !c.disabled;
const width = String(c.htmode || '').replace(/^[A-Z]+/, '');
const mine = aps.filter(a => a.radio == r && a != guest);
const other = [ ...new Set(mine.filter(a => a.ssid && a.ssid != (main || {}).ssid).map(a => a.ssid)) ].join(' / ');
return tile(td.bandName(c.band) + (other ? ' · ' + other : ''),
on ? devs(mine.reduce((a, ap) => a + ap.stations.length, 0)) : T('已关闭', 'Off'),
on ? `${T('信道', 'Ch')} ${iw.channel || c.channel || 'auto'}${width ? ` · ${width} MHz` : ''}` : '', !on);
});
if (guest)
tiles.push(tile(T('访客网络', 'Guest network'), guest.up ? devs(guest.stations.length) : T('未开启', 'Off'), guest.ssid, !guest.up));
this.put(box, (main
? `<div class="td-ssid">${esc(main.ssid || '—')}</div><p class="td-muted td-ssid-s">${esc(n + ' ' + T('台设备已连接', n == 1 ? 'device connected' : 'devices connected'))}</p>`
: `<div class="td-ssid td-muted">${esc(T('未开启', 'Off'))}</div><p class="td-muted td-ssid-s">${esc(T('这台路由器还没有开启无线网络', 'No wireless network is enabled'))}</p>`)
+ (tiles.length ? `<dl class="td-kv">${tiles.join('')}</dl>` : ''));
},
/* ---------- ports and storage: ports, apps and the gateway ping every 30 s; storage comes with the system info we already poll ---------- */
refreshPorts() {
const box = this.$('td-ports');
if (!box) return Promise.resolve();
return td.ports(this.s.wan).then(list => {
if (!list.length) return box.closest('.td-card').remove(); // nothing the kernel can tell us (swconfig)
const lan = list.filter(p => !p.line);
let k = 0;
this.set('td-ports-n', T(`${list.filter(p => p.up).length} / ${list.length} 已接网线`, `${list.filter(p => p.up).length} of ${list.length} in use`));
this.put(box, list.map(p => {
const m = /^lan(\d+)$/.exec(p.name);
const name = p.line || (m ? 'LAN ' + m[1] : lan.length > 1 ? 'LAN ' + ++k : 'LAN');
const speed = !p.up ? T('未接网线', 'Unplugged') : p.speed > 0 ? (p.speed >= 1000 ? p.speed / 1000 + ' Gbps' : p.speed + ' Mbps') : T('已连接', 'Connected');
return `<div${p.up ? '' : ' class="off"'}><dt>${esc(name)}</dt><dd>${esc(speed)}</dd></div>`;
}).join(''));
});
},
paintDisk() {
const box = this.$('td-disk');
if (!box) return;
const info = this.s.info || {};
const row = (label, d) => {
if (!d || !d.total) return '';
const used = d.used != null ? d.used : d.total - d.free, pct = Math.round(used / d.total * 100);
return `<div class="td-meter"><p><b>${esc(label)}</b><span>${esc(T(`剩余 ${td.bytes((d.avail != null ? d.avail : d.free) * 1024)} / 共 ${td.bytes(d.total * 1024)}`,
`${td.bytes((d.avail != null ? d.avail : d.free) * 1024)} free of ${td.bytes(d.total * 1024)}`))}</span></p><div class="td-bar${pct >= 90 ? ' full' : ''}"><i style="width:${pct}%"></i></div></div>`;
};
const html = row(T('系统空间', 'System'), info.root) + row(T('临时文件', 'Temporary files'), info.tmp) + row(T('虚拟内存', 'Swap'), info.swap);
this.put(box, html);
},
refreshClients() {
return td.clients(this.s.wifi, this.s.wan).then(list => {
const online = list.filter(c => c.online);
this.s.clients = online;
this.set('td-ndev', online.length + ' ' + T('台设备', online.length == 1 ? 'device' : 'devices'));
this.set('td-ndev-s', online.length ? T('正在上网', 'online') : T('暂无设备', 'none yet'));
this.paintSummary();
const box = this.$('td-devs');
if (!box) return;
const top = online.slice(0, 6);
this.put(box, top.length ? top.map(c => {
const [ sig ] = td.signal(c.signal);
const sub = c.conn == 'wifi' ? `Wi‑Fi ${td.bandName(c.band)} · ${sig}` : td.connName(c) + (c.ip && c.ip != c.display ? ' · ' + c.ip : '');
const rt = c.conn == 'wifi' && c.link
? `${Math.round(c.link)} Mbps<div class="td-bar"><i style="width:${td.quality(c.signal)}%"></i></div>`
: `${esc(c.conn == 'lan' ? T('局域网', 'LAN') : T('有线', 'Wired'))}<div class="td-bar"><i style="width:100%"></i></div>`;
return `<div class="td-dev"><div class="td-av">${icon(c.kind)}</div><div class="nm"><b>${esc(c.display)}</b><small>${esc(sub)}</small></div><div class="rt" title="${esc(T('连接速率 · 信号强度', 'Link rate · signal'))}">${rt}</div></div>`;
}).join('') + (online.length > 6 ? `<a class="td-more" href="${L.url('admin/clients')}">${esc(T(`还有 ${online.length - 6} 台设备`, `${online.length - 6} more`))}</a>` : '')
: `<div class="td-empty-row">${esc(T('现在没有设备在线', 'No devices online'))}</div>`);
});
},
paintSummary() {
const info = this.s.info || {}, n = this.s.clients.length;
const host = (this.s.board || {}).hostname || T('路由器', 'Router');
if (!this.s.wan || !this.s.wan.up) {
this.set('td-summary', T('上级网络没有响应,检查一下光猫或网线是否接好。', 'The upstream network is not responding. Check the modem and cables.'));
return;
}
this.set('td-summary', td.ZH
? `${host} 已平稳运行 ${td.duration(info.uptime)},${n} 台设备在线。`
: `${host} has been up for ${td.duration(info.uptime)} with ${n} device${n == 1 ? '' : 's'} online.`);
},
sample(devText, info) {
const now = Date.now();
const w = this.s.wan;
const nd = td.netdev(devText);
const d = w && nd[w.device];
if (info) this.s.info = info;
if (d && this.s.last && now - this.s.last.t < 10000) {
const dt = Math.max(0.5, (now - this.s.last.t) / 1000);
const rx = Math.max(0, (d.rx - this.s.last.rx) / dt), tx = Math.max(0, (d.tx - this.s.last.tx) / dt);
this.s.down.push(rx); this.s.down.shift();
this.s.up.push(tx); this.s.up.shift();
const [ dv, du ] = td.rate(rx), [ uv, uu ] = td.rate(tx);
this.set('td-down', dv); this.set('td-down-u', du);
this.set('td-up', uv); this.set('td-up-u', uu);
this.drawChart();
}
if (d) {
this.s.last = { t: now, rx: d.rx, tx: d.tx };
this.set('td-boot', this.s.mode == 'side' ? td.bytes(d.rx) : `↓ ${td.bytes(d.rx)} ↑ ${td.bytes(d.tx)}`);
}
this.paintRings();
},
drawChart() {
const svg = this.$('td-chart');
if (!svg) return;
const down = this.s.down, up = this.s.up;
const max = Math.max(1, ...down, ...up) * 1.15;
const W = 600, H = 118;
const path = (a, close) => {
const p = a.map((v, i) => [ i * W / (a.length - 1), H - 6 - (v / max) * (H - 22) ]);
let s = `M${p[0]}`;
for (let i = 0; i < p.length - 1; i++) {
const p0 = p[i - 1] || p[i], p1 = p[i], p2 = p[i + 1], p3 = p[i + 2] || p2;
s += `C${p1[0] + (p2[0] - p0[0]) / 6},${p1[1] + (p2[1] - p0[1]) / 6} ${p2[0] - (p3[0] - p1[0]) / 6},${p2[1] - (p3[1] - p1[1]) / 6} ${p2}`;
}
return close ? s + `L${W},${H}L0,${H}Z` : s;
};
const [ fill, line, upLine ] = svg.querySelectorAll('path');
fill.setAttribute('d', path(down, true));
line.setAttribute('d', path(down));
if (upLine) upLine.setAttribute('d', path(up));
},
paintRings() {
const setRing = (key, pct, text, label, cls) => {
const c = this.$('td-ring-' + key);
if (!c) return;
c.style.strokeDashoffset = RING * (1 - Math.max(0, Math.min(100, pct || 0)) / 100);
if (cls != null) c.setAttribute('class', 'fg ' + cls);
this.set('td-ring-' + key + '-v', text);
if (label) this.set('td-ring-' + key + '-l', label);
};
const info = this.s.info || {}, m = info.memory || {};
if (this.s.cpuPct != null) setRing('cpu', this.s.cpuPct, Math.round(this.s.cpuPct) + '%');
else if (info.load) setRing('cpu', Math.min(100, info.load[0] / 65536 * 50), (info.load[0] / 65536).toFixed(2));
if (m.total) {
const used = (m.total - (m.available || (m.free + (m.buffered || 0) + (m.cached || 0)))) / m.total * 100;
setRing('mem', used, Math.round(used) + '%');
}
if (this.s.temp != null) {
const t = this.s.temp;
setRing('temp', t, Math.round(t) + '°C',
T('温度', 'Temp') + ' · ' + (t < 70 ? T('正常', 'normal') : t < 85 ? T('偏高', 'warm') : T('过热', 'hot')),
t < 85 ? 'warm' : 'hot');
}
else setRing('temp', 0, '—');
},
tick() {
return Promise.all([ td.readFile('/proc/net/dev'), td.readFile('/proc/stat'), td.temperature() ]).then(([ dev, stat, temp ]) => {
const c = td.cpuStat(stat);
if (c && this.s.cpu && c.total > this.s.cpu.total)
this.s.cpuPct = 100 * (1 - (c.idle - this.s.cpu.idle) / (c.total - this.s.cpu.total));
if (c) this.s.cpu = c;
if (temp != null) this.s.temp = temp;
else if (this.s.temp == null) this.$('td-ring-temp')?.closest('.td-ring').remove(); // no usable sensor (VMs, some x86)
this.sample(dev);
});
},
slow() {
return Promise.all([ td.sysinfo(), td.wan(), this.s.hasWifi ? td.wifiInfo() : this.s.wifi ]).then(([ info, wan, wifi ]) => {
this.s.info = info;
this.s.wan = wan;
this.greet(); // the hour, the date and the online state all change over a long session; it only writes what differs
this.paintWifi(wifi);
this.paintStatic();
this.paintDisk();
return Promise.all([ this.refreshClients(), ++this.ticks % 3 ? null : Promise.all([ this.refreshPorts(), this.paintApps(), this.pingGateway() ]) ]);
});
},
pingGateway() {
const w = this.s.wan;
if (!w || !w.gw || !/^[0-9.]+$/.test(w.gw)) {
this.set('td-lat', w && w.up ? T('已连接', 'Connected') : T('未连接', 'Offline'));
return Promise.resolve();
}
/* a gateway that never answers ping (many ISP modems) is retried every few minutes, not every 30 s */
if (this.s.miss >= 3 && this.ticks % 18) return Promise.resolve();
return L.resolveDefault(fs.exec('/bin/ping', [ '-c', '1', '-W', '1', w.gw ]), {}).then(r => {
const m = String((r || {}).stdout || '').match(/time[=<]([\d.]+)/);
const v = m ? (+m[1] < 1 ? '<1' : Math.round(+m[1])) + ' ms' : null;
this.s.miss = v ? 0 : (this.s.miss || 0) + 1;
this.set('td-ping', v || T('无响应', 'No reply'));
this.set('td-lat', v ? T('延迟 ', 'Latency ') + v : T('已连接', 'Connected'));
});
},
/* ---------- apps card: one procd query plus a config read per shown app, every 30 s; the DOM is touched only when something changed.
* Like the devices card it shows a few rows (apps with something to say first) and counts the rest. ---------- */
paintApps() {
const box = this.$('td-apps');
if (!box) return Promise.resolve();
return td.services().then(all => {
const fn = s => APPS[s.name.toLowerCase()];
const live = this.s.apps.map(p => [ p, td.service(all, p.path) ]).filter(([ , s ]) => s && s.running)
.sort(([ , a ], [ , b ]) => !fn(a) - !fn(b));
const top = live.slice(0, live.length > 5 ? 4 : 5), more = live.length - top.length;
return Promise.all(top.map(([ p, s ]) => (fn(s) || (() => Promise.resolve({})))().then(x => [ p, x ]))).then(rows => {
const html = rows.length ? rows.map(([ p, x ]) => `<div class="td-dev td-run"><div class="td-av">${icon(td.appIcon(p.path))}</div>
<div class="nm"><a href="${L.url(p.path)}"><b>${esc(p.title)}</b></a><small>${esc([ T('运行中', 'Running'), x.sub ].filter(Boolean).join(' · '))}</small></div>
${x.seg ? `<div class="td-seg" data-oc="${esc(x.seg)}"><button type="button" data-m="rule">${esc(T('按规则', 'Rule'))}</button><button type="button" data-m="global">${esc(T('全局', 'Global'))}</button><button type="button" data-m="direct">${esc(T('直连', 'Direct'))}</button></div>`
: x.link ? `<a class="rt" href="${esc(x.link)}" target="_blank" rel="noopener">${esc(T('控制台', 'Console'))}${icon('arrow')}</a>`
: x.rt ? `<div class="rt">${esc(x.rt)}</div>` : ''}</div>`).join('')
+ (more ? `<a class="td-more" href="${L.url('admin/apps')}">${esc(T(`还有 ${more} 个在运行`, `${more} more running`))}</a>` : '')
: `<div class="td-empty-row">${esc(T('没有正在运行的应用', 'No apps running'))}</div>`;
if (box._html === html) return;
this.put(box, html);
box.querySelectorAll('[data-oc]').forEach(seg => this.ocSwitch(seg));
});
});
},
/* OpenClash's proxy mode, switched through its own switch_rule_mode call */
ocSwitch(seg) {
let mode = seg.dataset.oc;
const mark = m => seg.querySelectorAll('button').forEach(b => b.classList.toggle('on', b.dataset.m == m));
mark(mode);
seg.addEventListener('click', ev => {
const b = ev.target.closest('button[data-m]');
if (!b || b.dataset.m == mode) return;
const prev = mode;
mark(mode = b.dataset.m);
request.get(L.url('admin/services/openclash/switch_rule_mode'), { query: { rule_mode: mode } })
.then(r => { if (!r.ok) throw r; td.toast(T('已切换代理模式', 'Proxy mode switched')); })
.catch(() => { mark(mode = prev); td.toast(T('切换失败', 'Switch failed')); });
});
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});