Added graph interaction

This commit is contained in:
Sam Latsin 2026-10-29 21:50:18 +03:00
parent 40d9989c98
commit 003a8823a7
8 changed files with 559 additions and 54 deletions

View File

@ -132,7 +132,17 @@ seed-ноды), — под чертой «служебное». Правило
соединения и дальше по цепочке `dialer-proxy`. Наведи или нажми на узел — подсветится всё, соединения и дальше по цепочке `dialer-proxy`. Наведи или нажми на узел — подсветится всё,
что в него приходит и что из него выходит, снизу — подробности и «путь сейчас». «Только что в него приходит и что из него выходит, снизу — подробности и «путь сейчас». «Только
выбранное» прячет невыбранные пункты групп. Другие профили (`whitelist`, `foreign`) — из выбранное» прячет невыбранные пункты групп. Другие профили (`whitelist`, `foreign`) — из
списка, без живого состояния. Страница только показывает; правки — на «Управлении». списка, без живого состояния.
Править на графе (запущенный профиль):
- нажать на группу — справа её пункты с последней задержкой: выбрать (`select`) или закрепить
(`fallback` / `url-test`, «Снять закрепление» возвращает автовыбор), «Проверить задержки» —
все пункты разом. Сразу через API mihomo, без пересборки; выбор запоминается и переживает
перезапуск (`cache.db`), до следующей смены в дашборде;
- сервисы: «+ сервис» (есть «как Claude») или нажать на группу сервиса — geosite, домены, IP и
«через что»; «через что» можно и перетащить от группы сервиса на MY / FOREIGN / RU / MAIN /
DIRECT. «Сохранить и применить» меняет в `common.env` только `SERVICES` и `SVC_*`
(`mihomo-kit.sh services`), проверяет, что все профили собираются, и перезапускает текущий.
Без роутера: [tools/graph.html](tools/graph.html) из репозитория открыть в браузере и выбрать Без роутера: [tools/graph.html](tools/graph.html) из репозитория открыть в браузере и выбрать
или перетащить любой конфиг mihomo. Для живого состояния — адрес API и secret (они в ссылке или перетащить любой конфиг mihomo. Для живого состояния — адрес API и secret (они в ссылке

View File

@ -8,7 +8,7 @@
}, },
"write": { "write": {
"ubus": { "ubus": {
"mihomo-kit": [ "run", "config_get", "config_set", "export", "import" ] "mihomo-kit": [ "run", "config_get", "config_set", "export", "import", "group", "services_set" ]
} }
} }
} }

View File

@ -260,7 +260,7 @@
// subscriptions) goes to a lane under the rest, its top at lane. // subscriptions) goes to a lane under the rest, its top at lane.
function layout(m, measure) { function layout(m, measure) {
measure = measure || function(s, px) { return String(s).length * px * 0.6; }; measure = measure || function(s, px) { return String(s).length * px * 0.6; };
var NODE_H = 36, GAP_Y = 8, GAP_X = 90, DUMMY_H = 16, LANE_GAP = 70; var NODE_H = 36, GAP_Y = 8, GAP_X = 90, DUMMY_H = 16, LANE_GAP = 44;
var out = {}, succ = {}, pred = {}; var out = {}, succ = {}, pred = {};
m.list.forEach(function(n) { succ[n.id] = []; pred[n.id] = []; }); m.list.forEach(function(n) { succ[n.id] = []; pred[n.id] = []; });
m.edges.forEach(function(e) { m.edges.forEach(function(e) {
@ -506,14 +506,15 @@
// live(m, proxies, connections, prev, providers) -> what each group uses, alive nodes per // live(m, proxies, connections, prev, providers) -> what each group uses, alive nodes per
// provider and where the connections go: // provider and where the connections go:
// { now: {id: name}, nowProv: {id: provider id}, edges: {i: {n, rate}}, nodes: {id: {n}}, ... } // { now: {id: name}, nowProv: {id: provider id}, groups: {id: {type, all, fixed}},
// edges: {i: {n, rate}}, nodes: {id: {n, rate, byRule}}, members(id) -> [{name, delay, alive}], ... }
// proxies: GET /proxies .proxies (groups and the config's proxies only); // proxies: GET /proxies .proxies (groups and the config's proxies only);
// providers: GET /providers/proxies .providers (the subscriptions' nodes); // providers: GET /providers/proxies .providers (the subscriptions' nodes);
// connections: GET /connections .connections; prev: the previous result (byte counters -> rates) // connections: GET /connections .connections; prev: the previous result (byte counters -> rates)
function live(m, proxies, connections, prev, providers) { function live(m, proxies, connections, prev, providers) {
proxies = proxies || {}; proxies = proxies || {};
var L = { now: {}, nowProv: {}, delay: {}, provider: {}, edges: {}, nodes: {}, bytes: {}, var L = { now: {}, nowProv: {}, delay: {}, provider: {}, groups: {}, edges: {}, nodes: {}, bytes: {},
total: 0, unmatched: 0, unmatchedRules: {}, at: Date.now() }; total: 0, internal: 0, unmatched: 0, unmatchedRules: {}, at: Date.now() };
var edgeIndex = {}; var edgeIndex = {};
m.edges.forEach(function(e, i) { edgeIndex[e.from + '\n' + e.to] = i; }); m.edges.forEach(function(e, i) { edgeIndex[e.from + '\n' + e.to] = i; });
var lastDelay = function(p) { var lastDelay = function(p) {
@ -550,6 +551,7 @@
if (!m.groups[name] || p.now == null) if (!m.groups[name] || p.now == null)
return; return;
var id = 'g:' + name, f = find(p.now, id); var id = 'g:' + name, f = find(p.now, id);
L.groups[id] = { type: p.type, all: p.all || [], fixed: p.fixed || '' };
L.now[id] = p.now; L.now[id] = p.now;
L.delay[id] = lastDelay(f && f.p); L.delay[id] = lastDelay(f && f.p);
if (f && f.v) if (f && f.v)
@ -584,12 +586,24 @@
return path; return path;
}; };
L.tail = function(id) { return tail(id, [ id ]); }; L.tail = function(id) { return tail(id, [ id ]); };
// what a group can take, with the last delay test
L.members = function(id) {
return ((L.groups[id] || {}).all || []).map(function(name) {
var f = find(name, id), p = f ? f.p : proxies[name];
return { name: name, delay: lastDelay(p), alive: p ? p.alive !== false : true };
});
};
var prevBytes = prev && prev.bytes || {}, dt = prev ? (L.at - prev.at) / 1000 : 0; var prevBytes = prev && prev.bytes || {}, dt = prev ? (L.at - prev.at) / 1000 : 0;
(connections || []).forEach(function(c) { (connections || []).forEach(function(c) {
// no rule: mihomo's own connections (DNS through a proxy, subscriptions, checks)
if (!c.rule) {
L.internal++;
return;
}
var rid = m.ruleIndex[ruleKey(c.rule || '', c.rulePayload || '')]; var rid = m.ruleIndex[ruleKey(c.rule || '', c.rulePayload || '')];
if (!rid) { if (!rid) {
L.unmatched++; L.unmatched++;
var u = (c.rule || 'без правила') + (c.rulePayload ? ' ' + c.rulePayload : ''); var u = c.rule + (c.rulePayload ? ' ' + c.rulePayload : '');
L.unmatchedRules[u] = (L.unmatchedRules[u] || 0) + 1; L.unmatchedRules[u] = (L.unmatchedRules[u] || 0) + 1;
return; return;
} }
@ -606,6 +620,14 @@
}); });
tail(path[path.length - 1], path); tail(path[path.length - 1], path);
L.total++; L.total++;
// a rule straight to DIRECT / REJECT: counted at that exit too (no edge to draw)
var end = m.nodes[rid].data.end;
if (end && m.nodes['b:' + end]) {
var x = L.nodes['b:' + end] = L.nodes['b:' + end] || { n: 0, rate: 0 };
x.n++;
x.rate += rate;
x.byRule = (x.byRule || 0) + 1;
}
path.forEach(function(id, i) { path.forEach(function(id, i) {
var s = L.nodes[id] = L.nodes[id] || { n: 0, rate: 0 }; var s = L.nodes[id] = L.nodes[id] || { n: 0, rate: 0 };
s.n++; s.n++;
@ -670,8 +692,27 @@
'.mkg .focus .n:not(.hl){opacity:.25}.mkg .focus .e:not(.hl){opacity:.08}' + '.mkg .focus .n:not(.hl){opacity:.25}.mkg .focus .e:not(.hl){opacity:.08}' +
'.mkg .focus .e.hl{stroke-opacity:1;stroke-width:2.2}' + '.mkg .focus .e.hl{stroke-opacity:1;stroke-width:2.2}' +
'.mkg .n.sel rect{stroke-width:3}' + '.mkg .n.sel rect{stroke-width:3}' +
'.mkg-info{margin-top:8px;padding:8px 10px;border:1px solid var(--rule-b);border-radius:6px;background:var(--bg);display:none}' + '.mkg-info{position:absolute;top:8px;right:8px;width:min(380px,calc(100% - 16px));max-height:calc(100% - 56px);overflow:auto;' +
'.mkg-info h4{margin:0 0 4px;font-size:13px}' + 'box-sizing:border-box;padding:8px 10px;border:1px solid var(--rule-b);border-radius:6px;background:var(--bg);' +
'box-shadow:0 4px 18px rgba(0,0,0,.25);display:none;cursor:auto}' +
'.mkg-info h4{margin:0 22px 4px 0;font-size:13px}' +
'.mkg-x{position:absolute;top:4px;right:6px;border:0;background:none;color:var(--mute);font-size:16px;cursor:pointer}' +
'.mkg-pick{margin-top:8px;border-top:1px solid var(--rule-b);padding-top:6px}' +
'.mkg-pick .acts{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin:4px 0}' +
'.mkg-pick input{width:100%;box-sizing:border-box;margin:2px 0 4px;padding:3px 6px;background:var(--bg);color:var(--fg);' +
'border:1px solid var(--rule-b);border-radius:4px}' +
'.mkg-list{max-height:22em;overflow:auto}' +
'.mkg-it{display:flex;gap:6px;align-items:center;width:100%;text-align:left;padding:3px 6px;margin:1px 0;border:1px solid transparent;' +
'border-radius:4px;background:none;color:var(--fg);font:inherit;cursor:pointer}' +
'.mkg-it:hover{border-color:var(--rule-b)}.mkg-it.cur{border-color:var(--now);background:var(--group)}' +
'.mkg-it .nm{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}' +
'.mkg-it .d{color:var(--mute);font-size:11px;white-space:nowrap}.mkg-it.dead .nm{opacity:.5}' +
'.mkg-msg{font-size:11px;color:var(--mute);margin:2px 0}.mkg-msg.err{color:var(--miss-b)}' +
'.mkg-svc label{display:block;font-size:11px;color:var(--mute);margin-top:4px}' +
'.mkg-svc input,.mkg-svc select{width:100%;box-sizing:border-box;padding:3px 6px;background:var(--bg);color:var(--fg);' +
'border:1px solid var(--rule-b);border-radius:4px;font:inherit}' +
'.mkg .n.drop rect{stroke-dasharray:5 3;stroke-width:2.5}.mkg .n.svc rect{stroke-width:2}' +
'.mkg .link{fill:none;stroke:var(--now);stroke-width:2;stroke-dasharray:6 4;pointer-events:none}' +
'.mkg-info table{border-collapse:collapse}.mkg-info td{padding:1px 10px 1px 0;vertical-align:top}' + '.mkg-info table{border-collapse:collapse}.mkg-info td{padding:1px 10px 1px 0;vertical-align:top}' +
'.mkg-info td:first-child{color:var(--mute);white-space:nowrap}' + '.mkg-info td:first-child{color:var(--mute);white-space:nowrap}' +
'.mkg-info code{font-size:11px;word-break:break-all}' + '.mkg-info code{font-size:11px;word-break:break-all}' +
@ -716,8 +757,13 @@
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
} }
// view(container) -> { show(cfg), live(proxies, connections), destroy() } // view(container, act) -> { show(cfg), live(proxies, connections, providers), fit(), destroy() }
function view(container) { // act (optional; without it the graph only shows): what the page does through the API,
// each returning a promise: select(group, name), unfix(group), delay(group, url) -> {name: ms},
// refresh() - poll now; saveServices(list) - the kit's services (SERVICES), then the page
// shows the rebuilt profile (only on the router)
// show(cfg, meta): meta.services [{name, geosite, domains, ips, via}] - which groups are services
function view(container, act) {
if (!document.getElementById('mkg-style')) if (!document.getElementById('mkg-style'))
document.head.appendChild(el('style', { id: 'mkg-style', text: CSS })); document.head.appendChild(el('style', { id: 'mkg-style', text: CSS }));
var canvas = document.createElement('canvas').getContext('2d'); var canvas = document.createElement('canvas').getContext('2d');
@ -741,6 +787,8 @@
el('span', {}, [ el('s', { style: 'border-color:var(--flow);border-top-style:dashed' }), 'трафик' ]) el('span', {}, [ el('s', { style: 'border-color:var(--flow);border-top-style:dashed' }), 'трафик' ])
]); ]);
var bar = el('div', { 'class': 'mkg-bar' }, [ var bar = el('div', { 'class': 'mkg-bar' }, [
act && act.saveServices ? el('button', { 'class': 'btn cbi-button cbi-button-add',
title: 'сайт или приложение своим путём: своя группа и правила', onclick: function() { newService(); } }, [ '+ сервис' ]) : null,
el('label', {}, [ showLive, 'живое состояние' ]), el('label', {}, [ showLive, 'живое состояние' ]),
el('label', { title: 'скрыть члены групп, которые сейчас не выбраны' }, [ onlyNow, 'только выбранное' ]), el('label', { title: 'скрыть члены групп, которые сейчас не выбраны' }, [ onlyNow, 'только выбранное' ]),
stat stat
@ -760,11 +808,13 @@
root.appendChild(el('div', { style: 'height:6px' })); root.appendChild(el('div', { style: 'height:6px' }));
root.appendChild(stage); root.appendChild(stage);
root.appendChild(warn); root.appendChild(warn);
root.appendChild(info); stage.appendChild(info);
container.appendChild(root); container.appendChild(root);
root.classList.toggle('mkg-dark', isDark(container)); root.classList.toggle('mkg-dark', isDark(container));
var m = null, lay = null, L = null, nodeEls = {}, edgeEls = [], selected = null; var m = null, lay = null, L = null, nodeEls = {}, edgeEls = [], selected = null;
// the kit's services (show's meta): group name -> service; their editors, kept across repaints
var services = [], svcOf = {}, editors = {};
var view = { x: 0, y: 0, k: 1 }; var view = { x: 0, y: 0, k: 1 };
var apply = function() { world.setAttribute('transform', 'translate(' + view.x + ',' + view.y + ') scale(' + view.k + ')'); }; var apply = function() { world.setAttribute('transform', 'translate(' + view.x + ',' + view.y + ') scale(' + view.k + ')'); };
var maxed = function() { return document.fullscreenElement == root || root.classList.contains('mkg-max'); }; var maxed = function() { return document.fullscreenElement == root || root.classList.contains('mkg-max'); };
@ -817,19 +867,29 @@
apply(); apply();
}; };
stage.addEventListener('wheel', function(ev) { stage.addEventListener('wheel', function(ev) {
if (ev.target.closest && ev.target.closest('.mkg-info'))
return;
ev.preventDefault(); ev.preventDefault();
var r = stage.getBoundingClientRect(); var r = stage.getBoundingClientRect();
zoomAt(Math.exp(-ev.deltaY * 0.0015), ev.clientX - r.left, ev.clientY - r.top); zoomAt(Math.exp(-ev.deltaY * 0.0015), ev.clientX - r.left, ev.clientY - r.top);
}, { passive: false }); }, { passive: false });
var drag = null; var drag = null;
// keep the moves coming to the stage outside it; a pointer already gone throws
var capture = function(ev) {
try {
stage.setPointerCapture(ev.pointerId);
} catch (e) {}
};
stage.addEventListener('pointerdown', function(ev) { stage.addEventListener('pointerdown', function(ev) {
if (ev.target.closest && ev.target.closest('.n, button')) if (ev.target.closest && ev.target.closest('.n, button, .mkg-info'))
return; return;
drag = { x: ev.clientX, y: ev.clientY, vx: view.x, vy: view.y, moved: false }; drag = { x: ev.clientX, y: ev.clientY, vx: view.x, vy: view.y, moved: false };
stage.classList.add('drag'); stage.classList.add('drag');
stage.setPointerCapture(ev.pointerId); capture(ev);
}); });
stage.addEventListener('pointermove', function(ev) { stage.addEventListener('pointermove', function(ev) {
if (link)
return moveLink(ev);
if (!drag) if (!drag)
return; return;
view.x = drag.vx + ev.clientX - drag.x; view.x = drag.vx + ev.clientX - drag.x;
@ -837,7 +897,9 @@
drag.moved = drag.moved || Math.abs(ev.clientX - drag.x) + Math.abs(ev.clientY - drag.y) > 3; drag.moved = drag.moved || Math.abs(ev.clientX - drag.x) + Math.abs(ev.clientY - drag.y) > 3;
apply(); apply();
}); });
var endDrag = function() { var endDrag = function(ev) {
if (link)
return endLink(ev);
if (drag && !drag.moved) if (drag && !drag.moved)
select(null); select(null);
drag = null; drag = null;
@ -895,6 +957,88 @@
}; };
var row = function(k, v) { return el('tr', {}, [ el('td', { text: k }), el('td', {}, [].concat(v)) ]); }; var row = function(k, v) { return el('tr', {}, [ el('td', { text: k }), el('td', {}, [].concat(v)) ]); };
// the choice of a group (act): kept across the repaints of the live state
var pick = { id: null, filter: '', scroll: 0, delays: {}, busy: '', msg: '', err: false };
var run = function(what, p) {
pick.busy = what;
pick.msg = '';
repick();
return p.then(function() {
pick.busy = '';
if (act.refresh)
act.refresh();
repick();
}, function(e) {
pick.busy = '';
pick.msg = String(e && e.message || e);
pick.err = true;
repick();
});
};
var chooser = function(n) {
var g = L.groups[n.id], name = n.data.def.name;
if (pick.id != n.id)
pick = { id: n.id, filter: '', scroll: 0, delays: {}, busy: '', msg: '', err: false };
var auto = g.type != 'Selector';
var box = el('div', { 'class': 'mkg-pick' });
box.appendChild(el('div', { 'class': 'mkg-msg', text: auto
? 'Нажми пункт — закрепить его (иначе группа выбирает сама' + (g.fixed ? '; сейчас закреплено: ' + g.fixed : '') + ').'
: 'Нажми пункт — выбрать. Выбор запоминается и переживает перезапуск.' }));
var acts = el('div', { 'class': 'acts' }, [
el('button', { 'class': 'btn cbi-button', disabled: pick.busy ? 'disabled' : null, onclick: function() {
run('delay', act.delay(name, n.data.def.url).then(function(r) {
pick.delays = r || {};
pick.msg = 'проверено: ' + Object.keys(pick.delays).length;
pick.err = false;
}));
} }, [ pick.busy == 'delay' ? 'проверяю…' : 'Проверить задержки' ]),
auto && g.fixed ? el('button', { 'class': 'btn cbi-button', disabled: pick.busy ? 'disabled' : null, onclick: function() {
run('unfix', act.unfix(name));
} }, [ 'Снять закрепление' ]) : null
]);
box.appendChild(acts);
if (pick.msg)
box.appendChild(el('div', { 'class': 'mkg-msg' + (pick.err ? ' err' : ''), text: pick.msg }));
var all = L.members(n.id);
var list = el('div', { 'class': 'mkg-list' });
var fill = function() {
while (list.firstChild)
list.removeChild(list.firstChild);
var f = pick.filter.toLowerCase();
all.forEach(function(it) {
if (f && it.name.toLowerCase().indexOf(f) < 0)
return;
var d = pick.delays[it.name] != null ? pick.delays[it.name] : it.delay;
var cur = it.name == L.now[n.id];
list.appendChild(el('button', { 'class': 'mkg-it' + (cur ? ' cur' : '') + (it.alive ? '' : ' dead'),
disabled: pick.busy ? 'disabled' : null, title: it.name, onclick: function() {
if (!cur || auto && g.fixed != it.name)
run('select', act.select(name, it.name));
} }, [
el('span', { 'class': 'nm', text: (cur ? '● ' : '') + (g.fixed == it.name && auto ? '📌 ' : '') + it.name }),
el('span', { 'class': 'd', text: d ? d + ' мс' : it.alive ? '' : 'не отвечает' })
]));
});
};
if (all.length > 10) {
var q = el('input', { type: 'search', placeholder: 'найти (' + all.length + ')', value: pick.filter });
q.addEventListener('input', function() { pick.filter = q.value; fill(); });
box.appendChild(q);
pick.input = q;
} else
pick.input = null;
fill();
box.appendChild(list);
list.addEventListener('scroll', function() { pick.scroll = list.scrollTop; });
pick.list = list;
return box;
};
// redraw the panel keeping the filter's focus and the list's scroll
var repick = function() {
if (selected && m.nodes[selected])
details(m.nodes[selected]);
};
var details = function(n) { var details = function(n) {
var d = n.data.def || {}, rows = []; var d = n.data.def || {}, rows = [];
var kind = { rule: 'Правила', group: 'Группа', provider: 'Подписка (proxy-provider)', proxy: 'Сервер', var kind = { rule: 'Правила', group: 'Группа', provider: 'Подписка (proxy-provider)', proxy: 'Сервер',
@ -948,12 +1092,152 @@
if (t.length > 1) if (t.length > 1)
rows.push(row('путь сейчас', t.map(function(id) { return m.nodes[id] ? m.nodes[id].label : id; }).join(' → '))); rows.push(row('путь сейчас', t.map(function(id) { return m.nodes[id] ? m.nodes[id].label : id; }).join(' → ')));
} }
info.style.display = ''; var hadFocus = pick.input && document.activeElement == pick.input;
info.style.display = 'block';
while (info.firstChild) while (info.firstChild)
info.removeChild(info.firstChild); info.removeChild(info.firstChild);
info.appendChild(el('button', { 'class': 'mkg-x', title: 'закрыть', onclick: function() { select(null); } }, [ '✕' ]));
info.appendChild(el('h4', { text: kind + ': ' + n.label })); info.appendChild(el('h4', { text: kind + ': ' + n.label }));
info.appendChild(el('table', {}, rows)); info.appendChild(el('table', {}, rows));
if (act && act.saveServices && n.kind == 'group' && svcOf[n.label])
info.appendChild(editor(svcOf[n.label]));
if (act && n.kind == 'group' && L && showLive.checked && L.groups[n.id]) {
info.appendChild(chooser(n));
pick.list.scrollTop = pick.scroll;
if (hadFocus && pick.input) {
pick.input.focus();
pick.input.setSelectionRange(pick.input.value.length, pick.input.value.length);
}
} else
pick.input = null;
}; };
// --- services (the kit's SERVICES): edit in the panel, "через что" also by dragging
var VIA = { 'g:MY': 'MY', 'g:FOREIGN': 'FOREIGN', 'g:RU': 'RU', 'g:MAIN': 'MAIN', 'b:DIRECT': 'DIRECT' };
var VIA_TEXT = [ [ 'MY', 'свои серверы (первый живой)' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
[ 'DIRECT', 'напрямую' ], [ 'MAIN', 'как MAIN' ] ];
var TAKEN = /^(boot|boot-auto|ru|foreign|torrent|torrent-sel|my|my-exit|main|push|uplink|tailscale|ts-exit|ovpn-exit|csqtt|direct|reject|reject-drop|pass|compatible|global|bmstu)$/;
var editor = function(svc) {
var key = svc ? 'svc:' + svc.name : 'new';
if (editors[key])
return editors[key];
svc = svc || { name: '', geosite: '', domains: '', ips: '', via: 'MY' };
var input = function(v, ph) { return el('input', { type: 'text', value: v || '', placeholder: ph }); };
var f = {
name: input(svc.name, 'claude'),
geosite: input(svc.geosite, 'anthropic'),
domains: input(svc.domains, 'example.com'),
ips: input(svc.ips, '1.2.3.0/24'),
via: el('select', {}, VIA_TEXT.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); }))
};
f.via.value = svc.via || 'MY';
var msg = el('div', { 'class': 'mkg-msg' });
var say = function(t, err) {
msg.textContent = t;
msg.className = 'mkg-msg' + (err ? ' err' : '');
};
var buttons = [];
var save = function(list, what) {
buttons.forEach(function(b) { b.disabled = true; });
say(what + ': пересборка и перезапуск nikki, около 10–20 секунд…');
return act.saveServices(list).catch(function(e) {
buttons.forEach(function(b) { b.disabled = false; });
say(String(e && e.message || e), true);
});
};
var saveBtn = el('button', { 'class': 'btn cbi-button cbi-button-apply', onclick: function() {
var v = { name: f.name.value.trim().toLowerCase(), geosite: f.geosite.value.trim(), domains: f.domains.value.trim(),
ips: f.ips.value.trim(), via: f.via.value };
var others = services.filter(function(x) { return !svc.name || x.name != svc.name; });
if (!/^[a-z0-9][a-z0-9_-]*$/.test(v.name))
return say('имя: латиница, цифры, _ и -', true);
if (TAKEN.test(v.name) || m.groups[v.name.toUpperCase()] && !svcOf[v.name.toUpperCase()])
return say('группа ' + v.name.toUpperCase() + ' уже есть, возьми другое имя', true);
if (others.some(function(x) { return x.name == v.name; }))
return say('сервис ' + v.name + ' уже есть', true);
if (!v.geosite && !v.domains && !v.ips)
return say('нужен geosite, домены или IP', true);
var list = services.map(function(x) { return x.name == svc.name ? v : x; });
if (!svc.name)
list.push(v);
save(list, 'Сохраняю ' + v.name);
} }, [ 'Сохранить и применить' ]);
buttons.push(saveBtn);
var kids = [
svc.name ? null : el('div', { 'class': 'acts' }, [
el('button', { 'class': 'btn cbi-button', onclick: function() {
f.name.value = 'claude';
f.geosite.value = 'anthropic';
f.via.value = 'MY';
} }, [ 'как Claude' ])
]),
svc.name ? null : el('label', {}, [ 'имя (группа будет заглавными: claude → CLAUDE)', f.name ]),
el('label', {}, [ 'geosite (MetaCubeX/meta-rules-dat, через пробел)', f.geosite ]),
el('label', {}, [ 'домены (с поддоменами)', f.domains ]),
el('label', {}, [ 'IP / подсети', f.ips ]),
el('label', {}, [ 'через что (или потяни от группы к MY / FOREIGN / RU / MAIN / DIRECT)', f.via ]),
el('div', { 'class': 'acts' }, [ saveBtn, svc.name ? el('button', { 'class': 'btn cbi-button cbi-button-remove', onclick: function() {
if (window.confirm('Удалить сервис ' + svc.name + '? Его трафик пойдёт по остальным правилам.'))
save(services.filter(function(x) { return x.name != svc.name; }), 'Удаляю ' + svc.name);
} }, [ 'Удалить' ]) : null ]),
msg
];
var box = el('div', { 'class': 'mkg-pick mkg-svc' }, [ el('div', { 'class': 'mkg-msg', text: svc.name
? 'Сервис ' + svc.name + ' (настройки kit): правила выше «Своих правил», своя группа.' : '' }) ].concat(kids));
box.setVia = function(v) {
f.via.value = v;
say('через ' + v + ' — нажми «Сохранить и применить»');
};
box.say = say;
editors[key] = box;
return box;
};
var newService = function() {
select(null);
info.style.display = 'block';
while (info.firstChild)
info.removeChild(info.firstChild);
info.appendChild(el('button', { 'class': 'mkg-x', title: 'закрыть', onclick: function() { select(null); } }, [ '✕' ]));
info.appendChild(el('h4', { text: 'Новый сервис' }));
info.appendChild(el('div', { 'class': 'mkg-msg', text: 'Сайт или приложение, которое всегда идёт своим путём, ' +
'что бы ни было выбрано в MAIN. Через свои серверы — первый живой: выходной IP не скачет.' }));
info.appendChild(editor(null));
};
// dragging from a service group onto MY / FOREIGN / RU / MAIN / DIRECT
var link = null;
var toWorld = function(ev) {
var r = stage.getBoundingClientRect();
return { x: (ev.clientX - r.left - view.x) / view.k, y: (ev.clientY - r.top - view.y) / view.k };
};
var startLink = function(ev, id) {
var b = lay.nodes[id];
link = { id: id, x: ev.clientX, y: ev.clientY, moved: false,
line: el('path', { 'class': 'link' }), from: { x: b.x + b.w, y: b.y + b.h / 2 } };
world.appendChild(link.line);
Object.keys(VIA).forEach(function(t) { if (nodeEls[t]) nodeEls[t].classList.add('drop'); });
capture(ev);
};
var moveLink = function(ev) {
link.moved = link.moved || Math.abs(ev.clientX - link.x) + Math.abs(ev.clientY - link.y) > 4;
var p = toWorld(ev), a = link.from, dx = Math.max(30, (p.x - a.x) / 2);
link.line.setAttribute('d', 'M' + a.x + ',' + a.y + 'C' + (a.x + dx) + ',' + a.y + ' ' + (p.x - dx) + ',' + p.y + ' ' + p.x + ',' + p.y);
};
var endLink = function(ev) {
var l = link;
link = null;
world.removeChild(l.line);
Object.keys(VIA).forEach(function(t) { if (nodeEls[t]) nodeEls[t].classList.remove('drop'); });
if (!l.moved)
return select(selected == l.id ? null : l.id);
var hit = document.elementFromPoint(ev.clientX, ev.clientY);
var g = hit && hit.closest && hit.closest('.n'), to = g && g.getAttribute('data-id');
select(l.id);
var ed = editors['svc:' + svcOf[m.nodes[l.id].label].name];
if (to && VIA[to])
ed.setVia(VIA[to]);
else if (to && to != l.id)
ed.say('сюда нельзя: только MY, FOREIGN, RU, MAIN или DIRECT', true);
};
var select = function(id) { var select = function(id) {
if (selected && nodeEls[selected]) if (selected && nodeEls[selected])
nodeEls[selected].classList.remove('sel'); nodeEls[selected].classList.remove('sel');
@ -1010,7 +1294,9 @@
}); });
m.list.forEach(function(n) { m.list.forEach(function(n) {
var b = lay.nodes[n.id]; var b = lay.nodes[n.id];
var g = el('g', { 'class': 'n ' + n.kind + (/^REJECT/.test(n.data.end || '') ? ' reject' : ''), transform: 'translate(' + b.x + ',' + b.y + ')' }, [ var svc = act && act.saveServices && n.kind == 'group' && svcOf[n.label];
var g = el('g', { 'class': 'n ' + n.kind + (/^REJECT/.test(n.data.end || '') ? ' reject' : '') + (svc ? ' svc' : ''),
'data-id': n.id, transform: 'translate(' + b.x + ',' + b.y + ')' }, [
el('rect', { width: b.w, height: b.h, rx: n.kind == 'builtin' ? b.h / 2 : 6 }), el('rect', { width: b.w, height: b.h, rx: n.kind == 'builtin' ? b.h / 2 : 6 }),
el('text', { x: 10, y: n.sub ? 15 : 22, text: n.label }), el('text', { x: 10, y: n.sub ? 15 : 22, text: n.label }),
n.sub ? el('text', { 'class': 's', x: 10, y: 29, text: n.sub }) : null, n.sub ? el('text', { 'class': 's', x: 10, y: 29, text: n.sub }) : null,
@ -1018,10 +1304,17 @@
]); ]);
g.addEventListener('mouseenter', function() { if (!selected) focus(n.id); }); g.addEventListener('mouseenter', function() { if (!selected) focus(n.id); });
g.addEventListener('mouseleave', function() { if (!selected) focus(null); }); g.addEventListener('mouseleave', function() { if (!selected) focus(null); });
g.addEventListener('click', function(ev) { if (svc)
ev.stopPropagation(); // a service: click opens it, a drag sets "через что"; both end in endLink
select(selected == n.id ? null : n.id); g.addEventListener('pointerdown', function(ev) {
}); ev.stopPropagation();
startLink(ev, n.id);
});
else
g.addEventListener('click', function(ev) {
ev.stopPropagation();
select(selected == n.id ? null : n.id);
});
nodeEls[n.id] = g; nodeEls[n.id] = g;
gn.appendChild(g); gn.appendChild(g);
}); });
@ -1073,6 +1366,8 @@
text = '→ ' + L.now[n.id] + (L.delay[n.id] ? ' · ' + L.delay[n.id] + ' мс' : ''); text = '→ ' + L.now[n.id] + (L.delay[n.id] ? ' · ' + L.delay[n.id] + ' мс' : '');
if (on && n.kind == 'provider' && L.provider[n.id]) if (on && n.kind == 'provider' && L.provider[n.id])
text = L.provider[n.id].alive + '/' + L.provider[n.id].n + ' живы · ' + n.sub; text = L.provider[n.id].alive + '/' + L.provider[n.id].n + ' живы · ' + n.sub;
if (on && n.kind == 'builtin' && L.nodes[n.id] && L.nodes[n.id].byRule)
text = n.sub + ' · по правилам ' + L.nodes[n.id].byRule;
if (sub) if (sub)
sub.textContent = cut(text, Math.max(12, Math.floor((b.w - 18) / 5.6))); sub.textContent = cut(text, Math.max(12, Math.floor((b.w - 18) / 5.6)));
var s = on && L.nodes[n.id]; var s = on && L.nodes[n.id];
@ -1081,16 +1376,17 @@
g.appendChild(el('g', { 'class': 'live-bits', transform: 'translate(' + (b.w - w / 2) + ',0)' }, [ g.appendChild(el('g', { 'class': 'live-bits', transform: 'translate(' + (b.w - w / 2) + ',0)' }, [
el('rect', { 'class': 'badge', x: -w / 2, y: -8, width: w, height: 16, rx: 8 }), el('rect', { 'class': 'badge', x: -w / 2, y: -8, width: w, height: 16, rx: 8 }),
el('text', { 'class': 'bt', x: 0, y: 4, 'text-anchor': 'middle', text: t }), el('text', { 'class': 'bt', x: 0, y: 4, 'text-anchor': 'middle', text: t }),
el('title', { text: 'соединений: ' + s.n + (s.rate ? ', ' + fmtRate(s.rate) : '') }) el('title', { text: 'соединений: ' + s.n + (s.rate ? ', ' + fmtRate(s.rate) : '') +
(s.byRule ? '\nиз них прямо из правил: ' + s.byRule : '') })
])); ]));
} }
}); });
stat.textContent = on ? 'соединений: ' + L.total + (L.unmatched ? ' (без правила в графе: ' + L.unmatched + ')' : '') + stat.textContent = on ? 'соединений: ' + L.total + (L.internal ? ' · свои mihomo: ' + L.internal : '') +
(L.unmatched ? ' · правило не из профиля: ' + L.unmatched : '') +
' · обновлено ' + new Date(L.at).toLocaleTimeString() : ''; ' · обновлено ' + new Date(L.at).toLocaleTimeString() : '';
stat.title = on && L.unmatched ? 'правила этих соединений (mihomo ' + stat.title = on ? (L.internal ? 'свои mihomo — соединения без правила: DNS через прокси, скачивание ' +
'сам или правило не из профиля):\n' + Object.keys(L.unmatchedRules).map(function(k) { 'подписок и rule-set, проверки нод\n' : '') + (L.unmatched ? 'правила не из этого профиля (например, добавил nikki):\n' +
return k + ' — ' + L.unmatchedRules[k]; Object.keys(L.unmatchedRules).map(function(k) { return k + ' — ' + L.unmatchedRules[k]; }).join('\n') : '') : '';
}).join('\n') : '';
if (selected) if (selected)
focus(selected); focus(selected);
if (selected && m.nodes[selected]) if (selected && m.nodes[selected])
@ -1101,7 +1397,11 @@
var proxiesLive = null, providersLive = null; var proxiesLive = null, providersLive = null;
return { return {
show: function(cfg) { show: function(cfg, meta) {
services = meta && meta.services || [];
svcOf = {};
services.forEach(function(x) { svcOf[x.name.toUpperCase()] = x; });
editors = {};
m = model(cfg); m = model(cfg);
lay = layout(m, measure); lay = layout(m, measure);
L = null; L = null;

View File

@ -4,11 +4,47 @@
'require dom'; 'require dom';
// LuCI "Службы → mihomo-kit → Граф": a built profile as a graph (luci/graph.js), with the // LuCI "Службы → mihomo-kit → Граф": a built profile as a graph (luci/graph.js), with the
// live state of the running mihomo through the rpcd plugin (method api: read-only paths). // live state of the running mihomo through the rpcd plugin (method api: read-only paths)
// and the choice in its groups (method group); the services of the settings are edited here
// too (method services_set: rebuild and restart as the job).
var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { '': {} } }); var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { '': {} } });
var callGraph = rpc.declare({ object: 'mihomo-kit', method: 'graph', params: [ 'profile' ], expect: { '': {} } }); var callGraph = rpc.declare({ object: 'mihomo-kit', method: 'graph', params: [ 'profile' ], expect: { '': {} } });
var callApi = rpc.declare({ object: 'mihomo-kit', method: 'api', params: [ 'path' ], nobatch: true, expect: { '': {} } }); var callApi = rpc.declare({ object: 'mihomo-kit', method: 'api', params: [ 'path' ], nobatch: true, expect: { '': {} } });
var callServicesSet = rpc.declare({ object: 'mihomo-kit', method: 'services_set', params: [ 'services' ], expect: { '': {} } });
var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } });
var callGroup = rpc.declare({ object: 'mihomo-kit', method: 'group', params: [ 'group', 'action', 'name', 'url' ],
nobatch: true, expect: { '': {} } });
function checked(r) {
if (r && r.error)
throw new Error(r.error);
return r;
}
function wait(ms) {
return new Promise(function(resolve) { window.setTimeout(resolve, ms); });
}
// the job to its end (rpcd may be unreachable while nikki restarts): its output on failure
function followJob() {
var errors = 0;
var loop = function() {
return wait(1500).then(callJob).then(function(j) {
errors = 0;
if (j.running)
return loop();
if (j.rc !== 0)
throw new Error((j.log || 'ошибка').trim().split('\n').slice(-3).join('\n'));
return j;
}, function(e) {
if (++errors > 20)
throw e;
return loop();
});
};
return loop();
}
// the YAML reader of the own servers (luci/servers.js) and the graph: globals mkServers, mkGraph // the YAML reader of the own servers (luci/servers.js) and the graph: globals mkServers, mkGraph
function loadScript(name, global) { function loadScript(name, global) {
@ -30,23 +66,23 @@ return view.extend({
// /proxies and /providers/proxies every 9 s, /connections every 3 s; only for the running // /proxies and /providers/proxies every 9 s, /connections every 3 s; only for the running
// profile and a visible tab // profile and a visible tab
// one poll; full: also the groups and the subscriptions' nodes
fetchLive: function(full) {
return Promise.all([ full ? callApi('/proxies') : null, callApi('/connections'), full ? callApi('/providers/proxies') : null ]).then(L.bind(function(r) {
r.forEach(checked);
this.graph.live(r[0] && r[0].proxies, r[1].connections || [], r[2] && r[2].providers);
dom.content(this.state, '');
}, this)).catch(L.bind(function(e) {
dom.content(this.state, E('em', 'живое состояние недоступно: ' + (e.message || e)));
}, this));
},
poll: function() { poll: function() {
var tick = 0; var tick = 0;
var loop = L.bind(function() { var loop = L.bind(function() {
if (this.stopped)
return;
if (document.hidden || !this.liveOn) if (document.hidden || !this.liveOn)
return void (this.timer = window.setTimeout(loop, 3000)); return void (this.timer = window.setTimeout(loop, 3000));
var full = tick++ % 3 == 0; this.fetchLive(tick++ % 3 == 0).then(L.bind(function() {
Promise.all([ full ? callApi('/proxies') : null, callApi('/connections'), full ? callApi('/providers/proxies') : null ]).then(L.bind(function(r) {
var err = r.filter(function(x) { return x && x.error; })[0];
if (err)
throw new Error(err.error);
this.graph.live(r[0] && r[0].proxies, r[1].connections || [], r[2] && r[2].providers);
dom.content(this.state, '');
}, this)).catch(L.bind(function(e) {
dom.content(this.state, E('em', 'живое состояние недоступно: ' + (e.message || e)));
}, this)).then(L.bind(function() {
this.timer = window.setTimeout(loop, 3000); this.timer = window.setTimeout(loop, 3000);
}, this)); }, this));
}, this); }, this);
@ -59,7 +95,7 @@ return view.extend({
return; return;
} }
try { try {
this.graph.show(window.mkServers.yamlLoad(g.yaml)); this.graph.show(window.mkServers.yamlLoad(g.yaml), { services: g.services || [] });
} catch (e) { } catch (e) {
dom.content(this.state, E('p', { 'class': 'alert-message warning' }, 'Не разобрал профиль: ' + e.message)); dom.content(this.state, E('p', { 'class': 'alert-message warning' }, 'Не разобрал профиль: ' + e.message));
return; return;
@ -73,7 +109,7 @@ return view.extend({
var g = data[2], st = data[3]; var g = data[2], st = data[3];
this.state = E('div', { 'style': 'margin:.3em 0' }); this.state = E('div', { 'style': 'margin:.3em 0' });
var box = E('div'); var box = E('div');
var select = E('select', { 'class': 'cbi-input-select', 'change': L.bind(function(ev) { var select = this.profileSelect = E('select', { 'class': 'cbi-input-select', 'change': L.bind(function(ev) {
return callGraph(ev.target.value).then(L.bind(this.show, this)); return callGraph(ev.target.value).then(L.bind(this.show, this));
}, this) }); }, this) });
(st.profiles || []).forEach(function(p) { (st.profiles || []).forEach(function(p) {
@ -85,14 +121,28 @@ return view.extend({
E('div', { 'class': 'cbi-map-descr' }, 'Как устроен профиль: правила (сверху вниз — в порядке проверки) → группы → ' + E('div', { 'class': 'cbi-map-descr' }, 'Как устроен профиль: правила (сверху вниз — в порядке проверки) → группы → ' +
'подписки и серверы → через что они подключаются (dialer-proxy). Наведи или нажми на узел — подсветится всё, ' + 'подписки и серверы → через что они подключаются (dialer-proxy). Наведи или нажми на узел — подсветится всё, ' +
'что через него идёт; колесо — масштаб, перетаскивание — сдвиг. Для запущенного профиля видно, что выбрано ' + 'что через него идёт; колесо — масштаб, перетаскивание — сдвиг. Для запущенного профиля видно, что выбрано ' +
'в группах сейчас и куда идут соединения. Править — на странице «Управление».'), 'в группах сейчас и куда идут соединения; нажми на группу — выбрать или закрепить пункт (сразу, без ' +
'перезапуска). Настройки — на странице «Управление».'),
E('div', { 'style': 'margin:.5em 0' }, [ 'Профиль: ', select ]), E('div', { 'style': 'margin:.5em 0' }, [ 'Профиль: ', select ]),
this.state, this.state,
box box
]); ]);
// once the page is in the document: the graph fits its box and takes the theme's background // once the page is in the document: the graph fits its box and takes the theme's background
window.setTimeout(L.bind(function() { window.setTimeout(L.bind(function() {
this.graph = window.mkGraph.view(box); this.graph = window.mkGraph.view(box, {
select: function(g, name) { return callGroup(g, 'select', name, '').then(checked); },
unfix: function(g) { return callGroup(g, 'unfix', '', '').then(checked); },
delay: function(g, url) { return callGroup(g, 'delay', '', url || '').then(checked); },
refresh: L.bind(function() { return this.fetchLive(true); }, this),
saveServices: L.bind(function(list) {
return callServicesSet(list).then(checked).then(followJob).then(L.bind(function() {
return callGraph(this.profileSelect.value);
}, this)).then(L.bind(function(r) {
this.show(checked(r));
return this.fetchLive(true);
}, this));
}, this)
});
this.show(g); this.show(g);
this.poll(); this.poll();
}, this), 0); }, this), 0);

View File

@ -16,7 +16,12 @@
# config_get settings for the form (secrets: only whether they are set) # config_get settings for the form (secrets: only whether they are set)
# config_set save the form (via "mihomo-kit.sh configure") as the job # config_set save the form (via "mihomo-kit.sh configure") as the job
# graph {profile}: the built profile's YAML for the graph page (default: the running one) # graph {profile}: the built profile's YAML for the graph page (default: the running one)
# and the services of the settings
# api {path}: GET /proxies, /connections or /providers/proxies of the mihomo API # api {path}: GET /proxies, /connections or /providers/proxies of the mihomo API
# services_set {services: [{name, geosite, domains, ips, via}]}: replace the services
# ("mihomo-kit.sh services") as the job
# group {group, action, name, url}: select (pick / pin name), unfix (back to automatic),
# delay (test every member against url) - the graph page, through the mihomo API
# #
# rpcd kills calls after ~30 s; use/update/ts-login take longer, hence the job. # rpcd kills calls after ~30 s; use/update/ts-login take longer, hence the job.
@ -477,9 +482,54 @@ m_graph() {
json_add_boolean active "$(b pidof mihomo)" json_add_boolean active "$(b pidof mihomo)"
json_add_string profile "$want" json_add_string profile "$want"
json_add_string yaml "$(cat "$NIKKI_DIR/profiles/$want.yaml")" json_add_string yaml "$(cat "$NIKKI_DIR/profiles/$want.yaml")"
# the services, as config_get gives them: the graph edits these
[ -f "$PROFILES_D/common.env" ] && . "$PROFILES_D/common.env"
json_add_array services
for n in ${SERVICES:-}; do
k=SVC_$(echo "$n" | tr 'a-z-' 'A-Z_')
json_add_object ""
json_add_string name "$n"
for v in geosite domains ips via; do
eval "val=\${${k}_$(echo "$v" | tr 'a-z' 'A-Z'):-}"
json_add_string "$v" "$val"
done
json_close_object
done
json_close_array
json_dump json_dump
} }
m_services_set() {
json_load "$(cat)"
job_running && reply_error "busy: $(cat "$JOB/cmd")"
umask 077
env=$(mktemp /tmp/mihomo-kit-svc.XXXXXX) || reply_error "mktemp failed"
{
svcs=
if json_select services; then
json_get_keys keys
for k in $keys; do
json_select "$k"
json_get_var name name ""
name=$(printf '%s' "$name" | tr -d ' \t\r\n')
if [ -n "$name" ]; then
svcs="${svcs:+$svcs }$name"
K=SVC_$(echo "$name" | tr 'a-z-' 'A-Z_')
for v in geosite domains ips via; do
json_get_var val "$v" ""
[ -n "$val" ] && echo "${K}_$(echo "$v" | tr 'a-z' 'A-Z')=$(q "$val")"
done
fi
json_select ..
done
json_select ..
fi
echo "SERVICES=$(q "$svcs")"
} > "$env"
umask 022
start_job mihomo-kit.sh services "$env"
}
# the API's answer as it is: only these read-only paths # the API's answer as it is: only these read-only paths
m_api() { m_api() {
json_load "$(cat)" json_load "$(cat)"
@ -494,6 +544,45 @@ m_api() {
printf '%s\n' "$res" printf '%s\n' "$res"
} }
# api_call <curl args...>: the answer of the mihomo API, or reply_error with its message
api_call() {
sec=$(uci -q get nikki.mixin.api_secret)
out=$(curl -sS -m 25 -w '\n%{http_code}' ${sec:+-H "Authorization: Bearer $sec"} "$@" 2>&1) ||
reply_error "mihomo API: $out"
code=$(printf '%s' "$out" | tail -n 1)
body=$(printf '%s' "$out" | sed '$d')
case "$code" in 2??) ;; *) reply_error "mihomo API: $(jsonfilter -s "$body" -e '@.message' 2>/dev/null || echo "HTTP $code")" ;; esac
}
m_group() {
json_load "$(cat)"
json_get_vars group action name url
# the kit's group names; anything else would need escaping in the URL
case "$group" in '' | *[!A-Za-z0-9_.-]*) reply_error "bad group name" ;; esac
case "$action" in
select)
json_init
json_add_string name "$name"
api_call -X PUT -H 'Content-Type: application/json' -d "$(json_dump)" "$(api_url)/proxies/$group"
;;
unfix)
api_call -X DELETE "$(api_url)/proxies/$group"
;;
delay)
api_call -G --data-urlencode "url=${url:-https://www.gstatic.com/generate_204}" \
--data-urlencode timeout=5000 "$(api_url)/group/$group/delay"
# {"name": ms} of the members that answered
[ -n "$body" ] || body='{}'
printf '%s\n' "$body"
return
;;
*) reply_error "bad action" ;;
esac
json_init
json_add_boolean ok 1
json_dump
}
m_ts_check() { m_ts_check() {
json_init json_init
delay_check TAILSCALE TS_CHECK_URL http://100.69.216.50:8080 delay_check TAILSCALE TS_CHECK_URL http://100.69.216.50:8080
@ -546,7 +635,7 @@ m_job() {
case "$1" in case "$1" in
list) list)
echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"csqtt_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true},"graph":{"profile":"str"},"api":{"path":"str"}}' echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"csqtt_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true},"graph":{"profile":"str"},"api":{"path":"str"},"group":{"group":"str","action":"str","name":"str","url":"str"},"services_set":{"services":[]}}'
;; ;;
call) call)
case "$2" in case "$2" in
@ -564,6 +653,8 @@ case "$1" in
import) m_import ;; import) m_import ;;
graph) m_graph ;; graph) m_graph ;;
api) m_api ;; api) m_api ;;
group) m_group ;;
services_set) m_services_set ;;
*) reply_error "unknown method" ;; *) reply_error "unknown method" ;;
esac esac
;; ;;

View File

@ -14,6 +14,7 @@
# mihomo-kit.sh setup [--cli] first run: install, then settings in LuCI # mihomo-kit.sh setup [--cli] first run: install, then settings in LuCI
# (--cli or no LuCI: questions here + build + start) # (--cli or no LuCI: questions here + build + start)
# mihomo-kit.sh configure <env> settings from an env file (LuCI form) -> write, build, start # mihomo-kit.sh configure <env> settings from an env file (LuCI form) -> write, build, start
# mihomo-kit.sh services <env> only SERVICES / SVC_* from an env file (graph page) -> build, start
# mihomo-kit.sh build [name...] profiles.d/<name>.env -> profiles/<name>.yaml (default: all) # mihomo-kit.sh build [name...] profiles.d/<name>.env -> profiles/<name>.yaml (default: all)
# mihomo-kit.sh use <name> switch nikki to profiles/<name>.yaml and restart # mihomo-kit.sh use <name> switch nikki to profiles/<name>.yaml and restart
# mihomo-kit.sh update download the latest kit (KIT_URL) and rebuild # mihomo-kit.sh update download the latest kit (KIT_URL) and rebuild
@ -1793,6 +1794,33 @@ cmd_apply() {
true true
} }
# services <env>: SERVICES and SVC_<NAME>_* of <env> (the graph page) replace those of
# common.env; every profile must still render, else nothing changes; then build and apply
cmd_services() {
[ -f "${1:-}" ] || die "usage: services <env>"
_c=$PROFILES_D/common.env
[ -f "$_c" ] || die "no $_c: save the settings first"
umask 077
{
grep -vE '^(SERVICES|SVC_[A-Z0-9_]+)=' "$_c"
grep -E '^(SERVICES|SVC_[A-Z0-9_]+)=' "$1"
} > "$_c.new"
rm -f "$1"
umask 022
for e in "$PROFILES_D"/*.env; do
n=${e##*/}
n=${n%.env}
[ "$n" = common ] && continue
if ! (cmd_render "$_c.new" "$e") > /dev/null; then
rm -f "$_c.new"
die "services not saved: profile $n does not build with them"
fi
done
mv "$_c.new" "$_c"
log "saved services: $(sed -n 's/^SERVICES=//p' "$_c" | tr -d "'")"
cmd_apply
}
# Settings bundle: one text file with profiles.d/*.env, bmstu.env, bmstu.ovpn # Settings bundle: one text file with profiles.d/*.env, bmstu.env, bmstu.ovpn
# (secrets inside). Not in it: kit.env (core choice), the Tailscale node key, # (secrets inside). Not in it: kit.env (core choice), the Tailscale node key,
# the phone link token - all per router. # the phone link token - all per router.
@ -2042,6 +2070,7 @@ case "${1:-}" in
setup) shift; cmd_setup "$@" ;; setup) shift; cmd_setup "$@" ;;
configure) shift; cmd_configure "$@" ;; configure) shift; cmd_configure "$@" ;;
apply) cmd_apply ;; apply) cmd_apply ;;
services) shift; cmd_services "$@" ;;
export) cmd_export ;; export) cmd_export ;;
import) shift; cmd_import "$@" ;; import) shift; cmd_import "$@" ;;
mobile) shift; cmd_mobile "$@" ;; mobile) shift; cmd_mobile "$@" ;;

View File

@ -64,7 +64,7 @@
if (!cfg || typeof cfg != 'object' || !cfg.rules && !cfg['proxy-groups']) if (!cfg || typeof cfg != 'object' || !cfg.rules && !cfg['proxy-groups'])
throw new Error('не похоже на конфиг mihomo: нет rules и proxy-groups'); throw new Error('не похоже на конфиг mihomo: нет rules и proxy-groups');
if (!g) if (!g)
g = mkGraph.view($('graph')); g = mkGraph.view($('graph'), act);
g.show(cfg); g.show(cfg);
$('drop').style.display = 'none'; $('drop').style.display = 'none';
} catch (e) { } catch (e) {
@ -92,14 +92,30 @@
}); });
// live: /proxies and /providers/proxies every 10 s, /connections every 2 s // live: /proxies and /providers/proxies every 10 s, /connections every 2 s
var api = function(path) { var api = function(path, method, body) {
var base = $('api').value.trim().replace(/\/+$/, ''), sec = $('secret').value; var base = $('api').value.trim().replace(/\/+$/, ''), sec = $('secret').value, h = {};
return fetch(base + path, { headers: sec ? { Authorization: 'Bearer ' + sec } : {} }).then(function(r) { if (sec)
h.Authorization = 'Bearer ' + sec;
if (body)
h['Content-Type'] = 'application/json';
return fetch(base + path, { method: method || 'GET', headers: h, body: body ? JSON.stringify(body) : undefined }).then(function(r) {
if (!r.ok) if (!r.ok)
throw new Error(path + ': HTTP ' + r.status); return r.json().catch(function() { return {}; }).then(function(j) {
return r.json(); throw new Error(j.message || path + ': HTTP ' + r.status);
});
return r.status == 204 ? {} : r.json();
}); });
}; };
// the choice in the groups, once connected to the API
var act = {
select: function(g, name) { return api('/proxies/' + encodeURIComponent(g), 'PUT', { name: name }); },
unfix: function(g) { return api('/proxies/' + encodeURIComponent(g), 'DELETE'); },
delay: function(g, url) {
return api('/group/' + encodeURIComponent(g) + '/delay?timeout=5000&url=' +
encodeURIComponent(url || 'https://www.gstatic.com/generate_204'));
},
refresh: function() { return Promise.resolve(); }
};
$('connect').addEventListener('click', function() { $('connect').addEventListener('click', function() {
store('api', $('api').value.trim()); store('api', $('api').value.trim());
if (timer) if (timer)

View File

@ -60,7 +60,11 @@ for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".yaml"))) {
const cfg = S.yamlLoad(fs.readFileSync(path.join(dir, "router-csqtt.yaml"), "utf8")); const cfg = S.yamlLoad(fs.readFileSync(path.join(dir, "router-csqtt.yaml"), "utf8"));
const m = G.model(cfg); const m = G.model(cfg);
// /proxies: groups and the config's proxies; the subscriptions' nodes only in /providers/proxies // /proxies: groups and the config's proxies; the subscriptions' nodes only in /providers/proxies
const proxies = { MAIN: { now: "FOREIGN" }, FOREIGN: { now: "nl-1" }, UPLINK: { now: "CSQTT" }, CSQTT: { history: [] } }; const proxies = {
MAIN: { type: "Selector", now: "FOREIGN", all: ["FOREIGN", "DIRECT"] },
FOREIGN: { type: "URLTest", now: "nl-1", all: ["nl-1", "de-1"], fixed: "nl-1" },
UPLINK: { type: "Selector", now: "CSQTT" }, CSQTT: { history: [] },
};
const providers = { const providers = {
example: { proxies: [{ name: "nl-1", alive: true, history: [{ delay: 42 }] }, { name: "de-1", alive: false }] }, example: { proxies: [{ name: "nl-1", alive: true, history: [{ delay: 42 }] }, { name: "de-1", alive: false }] },
example2: { proxies: [{ name: "nl-1", alive: true }] }, example2: { proxies: [{ name: "nl-1", alive: true }] },
@ -69,6 +73,7 @@ for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".yaml"))) {
const conns = [ const conns = [
{ id: "c1", rule: "Match", rulePayload: "", chains: ["nl-1", "FOREIGN", "MAIN"], upload: 10, download: 20 }, { id: "c1", rule: "Match", rulePayload: "", chains: ["nl-1", "FOREIGN", "MAIN"], upload: 10, download: 20 },
{ id: "c2", rule: "", rulePayload: "", chains: ["DIRECT"] }, { id: "c2", rule: "", rulePayload: "", chains: ["DIRECT"] },
{ id: "c3", rule: "RuleSet", rulePayload: "ru-inside", chains: ["DIRECT"] },
]; ];
const L = G.live(m, proxies, conns, null, providers); const L = G.live(m, proxies, conns, null, providers);
const match = m.ruleIndex["match|"]; const match = m.ruleIndex["match|"];
@ -76,9 +81,13 @@ for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".yaml"))) {
const got = Object.keys(L.nodes); const got = Object.keys(L.nodes);
check("live", want.every((id) => L.nodes[id] && L.nodes[id].n == 1), "path " + JSON.stringify(got) + ", want " + JSON.stringify(want)); check("live", want.every((id) => L.nodes[id] && L.nodes[id].n == 1), "path " + JSON.stringify(got) + ", want " + JSON.stringify(want));
check("live", Object.keys(L.edges).length == want.length - 1, "edges on the path: " + Object.keys(L.edges).length); check("live", Object.keys(L.edges).length == want.length - 1, "edges on the path: " + Object.keys(L.edges).length);
check("live", L.nodes["b:DIRECT"] && L.nodes["b:DIRECT"].byRule == 1, "rule straight to DIRECT counted at DIRECT");
check("live", L.groups["g:FOREIGN"].fixed == "nl-1", "fixed of FOREIGN");
const mem = L.members("g:FOREIGN");
check("live", mem.length == 2 && mem[0].delay == 42 && mem[1].alive === false, "members of FOREIGN: " + JSON.stringify(mem));
check("live", L.provider["v:example"] && L.provider["v:example"].alive == 1 && L.provider["v:example"].n == 2, "alive nodes of example"); check("live", L.provider["v:example"] && L.provider["v:example"].alive == 1 && L.provider["v:example"].n == 2, "alive nodes of example");
check("live", L.nowProv["g:FOREIGN"] == "v:example", "FOREIGN's choice comes from example: " + L.nowProv["g:FOREIGN"]); check("live", L.nowProv["g:FOREIGN"] == "v:example", "FOREIGN's choice comes from example: " + L.nowProv["g:FOREIGN"]);
check("live", L.unmatched == 1 && L.unmatchedRules["без правила"] == 1, "unmatched: " + JSON.stringify(L.unmatchedRules)); check("live", L.internal == 1 && L.unmatched == 0, "internal " + L.internal + ", unmatched " + JSON.stringify(L.unmatchedRules));
check("live", L.delay["g:FOREIGN"] == 42, "delay of FOREIGN's choice"); check("live", L.delay["g:FOREIGN"] == 42, "delay of FOREIGN's choice");
if (!fail) if (!fail)
console.log("ok graph live"); console.log("ok graph live");