mihomo-kit/luci/graph.js
2026-11-03 00:06:01 +08:00

1651 lines
74 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// A mihomo config as a left-to-right graph (LuCI "mihomo-kit → Граф", tools/graph.html):
// rules (top to bottom = match order) -> groups -> subscriptions and servers -> their
// dialer-proxy chains; dashed: what a subscription is downloaded through. The live state
// of the mihomo API (/proxies: what each group uses now, /connections: where the traffic
// goes) is drawn on top. model() and layout() are plain functions (node: tools/test-graph.js).
// Browser: a global "mkGraph"; node: module.exports.
(function (root, factory) {
var api = factory();
if (typeof module === 'object' && module.exports)
module.exports = api;
else
root.mkGraph = api;
})(this, function () {
'use strict';
// --- model -----------------------------------------------------------------
// outbounds mihomo has without a config entry: one node each in the last column ("exits",
// with the proxies of type direct such as CSQTT); a rule to one ends at the rule
var BUILTIN = { 'DIRECT': 1, 'REJECT': 1, 'REJECT-DROP': 1, 'PASS': 1, 'COMPATIBLE': 1, 'GLOBAL': 1 };
var LOGIC = { 'AND': 1, 'OR': 1, 'NOT': 1, 'SUB-RULE': 1 };
// edges that place nodes left to right; fetch / file are drawn over the layout.
// wan: a proxy or subscription without dialer-proxy connects to its server directly
var RANKED = { route: 1, member: 1, use: 1, dialer: 1, wan: 1 };
// "AND,((DOMAIN,a),(NETWORK,UDP)),X" -> parts split on commas outside parentheses
function splitTop(s) {
var out = [], depth = 0, cur = '';
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
if (c == '(')
depth++;
else if (c == ')')
depth--;
if (c == ',' && depth == 0) {
out.push(cur.trim());
cur = '';
} else
cur += c;
}
out.push(cur.trim());
return out;
}
// the way mihomo reads a rule line: TYPE,payload,target[,params]; MATCH,target
function parseRule(line, i) {
line = String(line);
var type = line.split(',')[0].trim().toUpperCase();
var t = LOGIC[type] ? splitTop(line) : line.split(',').map(function(x) { return x.trim(); });
if (type == 'MATCH')
return { i: i, type: type, payload: '', target: t[1], params: [], text: line };
return { i: i, type: type, payload: t[1] || '', target: t[2], params: t.slice(3), text: line };
}
// "RULE-SET" / "RuleSet" (the API's name) -> "ruleset"
function ruleKey(type, payload) {
return String(type).replace(/-/g, '').toLowerCase() + '|' + (payload || '');
}
// filter regex for an edge label: "(?i)🇷🇺|\\bru\\b|russia" -> "🇷🇺|ru|russia"
function prettyRe(re) {
return String(re).replace(/^\(\?i\)/, '').replace(/\\b/g, '').replace(/\\(.)/g, '$1');
}
function cut(s, n) {
s = String(s);
return s.length > n ? s.slice(0, n - 1) + '…' : s;
}
// subscription URL without its secret part: https://host/…
function maskUrl(u) {
var m = /^([a-z0-9+.-]+:\/\/[^\/?#]+)(.*)$/i.exec(String(u || ''));
return m ? m[1] + (m[2] && m[2] != '/' ? '/…' : '') : String(u || '');
}
function useLabel(g) {
var l = [];
if (g.filter)
l.push('∋ ' + prettyRe(g.filter));
if (g['exclude-filter'])
l.push('∌ ' + prettyRe(g['exclude-filter']));
if (g['exclude-type'])
l.push('− ' + g['exclude-type']);
return l.join(' ');
}
function proxySub(p) {
if (p.type == 'direct')
return 'выход' + (p['interface-name'] ? ' через ' + p['interface-name'] : '');
var s = p.type || '?';
if (p.server)
s += ' · ' + p.server;
else if (p['interface-name'])
s += ' · ' + p['interface-name'];
else if (p.hostname)
s += ' · ' + p.hostname;
return s;
}
// model(cfg) -> { nodes: {id: node}, list: [node], edges: [edge], ... }
// node { id, kind: rule|group|provider|proxy|builtin|missing, label, sub, exit, data }
// edge { from, to, kind: route|member|use|dialer|wan|fetch|file, label }
// ids: r:<n> rules, g:<name> groups, p:<name> proxies, v:<name> providers,
// b:<name> built-in outbounds; exit: DIRECT, REJECT, proxies of type direct (last column)
function model(cfg) {
cfg = cfg || {};
var m = { nodes: {}, list: [], edges: [], byPair: {}, ruleIndex: {}, dialerOf: {}, warnings: [] };
var groups = {}, proxies = {}, providers = cfg['proxy-providers'] || {};
var ruleProviders = cfg['rule-providers'] || {};
(cfg['proxy-groups'] || []).forEach(function(g) { if (g && g.name != null) groups[g.name] = g; });
(cfg.proxies || []).forEach(function(p) { if (p && p.name != null) proxies[p.name] = p; });
m.groups = groups;
m.proxies = proxies;
m.providers = providers;
var node = function(id, kind, label, sub, data) {
if (!m.nodes[id]) {
m.nodes[id] = { id: id, kind: kind, label: String(label), sub: sub || '', data: data || {} };
m.list.push(m.nodes[id]);
}
return m.nodes[id];
};
var edge = function(from, to, kind, label) {
var e = { from: from, to: to, kind: kind, label: label || '' };
m.edges.push(e);
if (kind == 'dialer' || kind == 'wan')
m.dialerOf[from] = to;
m.byPair[from + '\n' + to] = m.byPair[from + '\n' + to] || e;
return e;
};
// a group or proxy by name, as mihomo resolves it (groups and proxies share names)
var ref = function(name, user) {
name = String(name);
if (groups[name])
return 'g:' + name;
if (proxies[name])
return 'p:' + name;
var id = 'b:' + name;
if (BUILTIN[name])
node(id, 'builtin', name, name == 'DIRECT' ? 'напрямую' : '').exit = true;
else {
node(id, 'missing', name, 'нет в конфиге');
m.warnings.push(name + ': нет такой группы или прокси (' + user + ')');
}
return id;
};
// rules: one node per run of the same type and target
var rules = (cfg.rules || []).map(parseRule), blocks = [];
rules.forEach(function(r) {
var b = blocks[blocks.length - 1];
if (b && b.type == r.type && b.target == r.target)
b.items.push(r);
else
blocks.push({ type: r.type, target: r.target, items: [ r ] });
});
blocks.forEach(function(b, n) {
var first = b.items[0], last = b.items[b.items.length - 1];
var label = b.items.length == 1 ? b.type + (first.payload ? ' ' + cut(first.payload, 26) : '')
: b.type + ' ×' + b.items.length;
if (b.type == 'RULE-SET' && b.items.length <= 2)
label = 'RULE-SET ' + b.items.map(function(r) { return r.payload; }).join(', ');
var id = 'r:' + n;
node(id, 'rule', label, '#' + (first.i + 1) + (b.items.length > 1 ? '–' + (last.i + 1) : '') + ' → ' + b.target,
{ items: b.items, ruleProviders: b.items.filter(function(r) { return r.type == 'RULE-SET'; })
.map(function(r) { return { name: r.payload, def: ruleProviders[r.payload] || null }; }) });
b.items.forEach(function(r) { m.ruleIndex[ruleKey(r.type, r.payload)] = id; });
// DIRECT / REJECT: the way ends at the rule (its line says where), no node of its own
if (BUILTIN[b.target] && !groups[b.target] && !proxies[b.target])
m.nodes[id].data.end = b.target;
else
edge(id, ref(b.target, id), 'route');
});
(cfg['proxy-groups'] || []).forEach(function(g) {
if (!g || g.name == null)
return;
var id = 'g:' + g.name;
node(id, 'group', g.name, g.type || '', { def: g });
(g.proxies || []).forEach(function(p) { edge(id, ref(p, id), 'member'); });
var use = (g.use || []).slice();
if (g['include-all'] || g['include-all-providers'])
Object.keys(providers).forEach(function(v) { if (use.indexOf(v) < 0) use.push(v); });
use.forEach(function(v) {
if (!providers[v])
m.warnings.push(g.name + ': нет провайдера ' + v);
node('v:' + v, 'provider', v, '', { def: providers[v] || {} });
edge(id, 'v:' + v, 'use', useLabel(g));
});
if (g['include-all'] || g['include-all-proxies'])
Object.keys(proxies).forEach(function(p) { edge(id, 'p:' + p, 'member', useLabel(g)); });
});
var paths = {};
Object.keys(providers).forEach(function(v) {
var d = providers[v] || {};
if (d.type == 'http' && d.path)
paths[d.path] = v;
});
Object.keys(providers).forEach(function(v) {
var d = providers[v] || {}, id = 'v:' + v;
var sub = d.type == 'http' ? maskUrl(d.url) : d.type == 'file' ? 'файл ' + (d.path || '') : d.type || '';
node(id, 'provider', v, sub, { def: d }).sub = sub;
var dialer = d.override && d.override['dialer-proxy'];
edge(id, ref(dialer || 'DIRECT', id), dialer ? 'dialer' : 'wan', dialer ? 'через' : 'напрямую');
if (d.type == 'http' && d.proxy)
edge(id, ref(d.proxy, id), 'fetch', 'качается через');
// [MY] nodes: a file provider reading what another one downloads
if (d.type == 'file' && paths[d.path] && paths[d.path] != v)
edge(id, 'v:' + paths[d.path], 'file', 'тот же файл');
});
(cfg.proxies || []).forEach(function(p) {
if (!p || p.name == null)
return;
var id = 'p:' + p.name;
var n = node(id, 'proxy', p.name, proxySub(p), { def: p });
if (p.type == 'direct')
n.exit = true;
else if (p['dialer-proxy'])
edge(id, ref(p['dialer-proxy'], id), 'dialer', 'через');
else
edge(id, ref('DIRECT', id), 'wan', 'напрямую');
});
return m;
}
// --- layout ----------------------------------------------------------------
// isotonic regression (pool adjacent violators): positions as close as possible to
// want[], in the same order, at least sep[i] apart (sep[i] between i and i+1)
function pack(want, sep) {
var n = want.length, off = [ 0 ], i;
for (i = 1; i < n; i++)
off[i] = off[i - 1] + sep[i - 1];
var blocks = [];
for (i = 0; i < n; i++) {
blocks.push({ sum: want[i] - off[i], n: 1, from: i });
while (blocks.length > 1) {
var b = blocks[blocks.length - 1], a = blocks[blocks.length - 2];
if (a.sum / a.n <= b.sum / b.n)
break;
a.sum += b.sum;
a.n += b.n;
blocks.pop();
}
}
var out = [];
blocks.forEach(function(b) {
for (var k = 0; k < b.n; k++)
out[b.from + k] = b.sum / b.n + off[b.from + k];
});
return out;
}
// layout(m, measure) -> { nodes: {id: {x, y, w, h, aux}}, edges: [{e, pts}], width, height, lane }
// Sugiyama-style: ranks by the longest path from the rules, dummy nodes on long edges,
// barycenter sweeps for the order, then y as close to the neighbours as the order allows.
// Exits take the last column; what no rule leads to (BOOT-AUTO, seeds: downloading the
// subscriptions) goes to a lane under the rest, its top at lane.
function layout(m, measure) {
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 = 44;
var out = {}, succ = {}, pred = {};
m.list.forEach(function(n) { succ[n.id] = []; pred[n.id] = []; });
m.edges.forEach(function(e) {
if (!RANKED[e.kind] || !succ[e.from] || !succ[e.to] || e.from == e.to)
return;
succ[e.from].push(e.to);
pred[e.to].push(e.from);
});
// rank: rules 0; else 1 + the deepest predecessor (back edges of a cycle ignored)
var rank = {}, state = {};
var visit = function(id) {
if (state[id] == 2)
return rank[id];
if (state[id] == 1)
return -1;
state[id] = 1;
var r = m.nodes[id].kind == 'rule' ? 0 : 1;
if (m.nodes[id].kind != 'rule')
pred[id].forEach(function(p) { var pr = visit(p); if (pr >= 0) r = Math.max(r, pr + 1); });
state[id] = 2;
rank[id] = r;
return r;
};
m.list.forEach(function(n) { visit(n.id); });
// a node no rule leads to (BOOT-AUTO, unused groups) sits just left of what it uses
var pull = true;
while (pull) {
pull = false;
m.list.forEach(function(n) {
if (pred[n.id].length || n.kind == 'rule' || !succ[n.id].length)
return;
var r = Math.min.apply(null, succ[n.id].map(function(s) { return rank[s]; })) - 1;
if (r > rank[n.id]) {
rank[n.id] = r;
pull = true;
}
});
}
// exits: one column after everything else
var maxRank = 0, layers = [], chain = [];
m.list.forEach(function(n) { if (!n.exit) maxRank = Math.max(maxRank, rank[n.id]); });
if (m.list.some(function(n) { return n.exit; }))
maxRank++;
m.list.forEach(function(n) { if (n.exit) rank[n.id] = maxRank; });
// the lane: neither reached from the rules nor an exit
var reached = {}, stack = m.list.filter(function(n) { return n.kind == 'rule'; }).map(function(n) { return n.id; });
while (stack.length) {
var cur = stack.pop();
if (reached[cur])
continue;
reached[cur] = 1;
stack = stack.concat(succ[cur]);
}
// layers with dummies; chain: per ranked edge the nodes it passes
for (var r = 0; r <= maxRank; r++)
layers.push([]);
var info = {};
m.list.forEach(function(n) {
info[n.id] = { id: n.id, rank: rank[n.id], up: [], down: [], h: NODE_H, node: n, aux: !reached[n.id] && !n.exit };
});
// first seen from the rules, top to bottom: a sensible starting order
var seen = {}, queue = m.list.filter(function(n) { return n.kind == 'rule'; }).map(function(n) { return n.id; });
var order = [];
while (queue.length) {
var id = queue.shift();
if (seen[id])
continue;
seen[id] = 1;
order.push(id);
succ[id].forEach(function(s) { if (!seen[s]) queue.push(s); });
}
m.list.forEach(function(n) { if (!seen[n.id]) order.push(n.id); });
order.forEach(function(id) { layers[info[id].rank].push(info[id]); });
var dn = 0;
m.edges.forEach(function(e, k) {
if (!RANKED[e.kind] || !info[e.from] || !info[e.to] || e.from == e.to)
return;
var a = info[e.from], b = info[e.to];
if (b.rank <= a.rank) {
chain[k] = [ a, b ];
return;
}
var c = [ a ], prev = a;
for (var rr = a.rank + 1; rr < b.rank; rr++) {
var d = { id: '~' + (dn++), rank: rr, up: [ prev ], down: [], h: DUMMY_H, dummy: true, aux: a.aux };
prev.down.push(d);
layers[rr].push(d);
c.push(d);
prev = d;
}
prev.down.push(b);
b.up.push(prev);
c.push(b);
chain[k] = c;
});
var pos = function(layer) { layer.forEach(function(v, i) { v.ord = i; }); };
layers.forEach(pos);
var bary = function(v, dir) {
var ns = dir == 'up' ? v.up : v.down;
if (!ns.length)
return v.ord;
return ns.reduce(function(s, u) { return s + u.ord; }, 0) / ns.length;
};
var sweep = function(r, dir) {
var l = layers[r];
l.forEach(function(v) { v.bc = bary(v, dir); });
l.sort(function(a, b) { return (a.aux ? 1 : 0) - (b.aux ? 1 : 0) || a.bc - b.bc || a.ord - b.ord; });
pos(l);
};
for (var it = 0; it < 6; it++) {
for (r = 1; r <= maxRank; r++)
sweep(r, 'up');
for (r = maxRank - 1; r >= 1; r--)
sweep(r, 'down');
}
for (r = 1; r <= maxRank; r++)
sweep(r, 'up');
// x: columns as wide as their widest node
var x = 0;
layers.forEach(function(l) {
var w = 60;
l.forEach(function(v) {
if (v.dummy) {
v.w = 0;
return;
}
// groups: room for the live "→ node · 42 мс"
v.w = Math.ceil(Math.max(measure(v.node.label, 12) + 22, measure(v.node.sub, 10.5) + 22,
v.node.kind == 'group' ? 150 : 64));
w = Math.max(w, v.w);
});
l.forEach(function(v) { v.x = x + (v.dummy ? w / 2 : 0); });
x += Math.min(w, 340) + GAP_X;
});
// y: rules stacked in match order, the rest close to their neighbours
var center = function(v) { return v.y + v.h / 2; };
var place = function(l, want) {
var sep = [];
for (var i = 0; i + 1 < l.length; i++)
sep.push(l[i].h / 2 + l[i + 1].h / 2 + GAP_Y);
var c = pack(want, sep);
l.forEach(function(v, i) { v.y = c[i] - v.h / 2; });
};
var y = 0;
layers[0].forEach(function(v) { v.y = y; y += v.h + GAP_Y; });
var near = function(v, sides) {
var ns = [];
sides.forEach(function(s) { ns = ns.concat(v[s]); });
ns = ns.filter(function(u) { return u.y != null; });
return ns.length ? ns.reduce(function(s, u) { return s + center(u); }, 0) / ns.length : null;
};
var settle = function(r, sides) {
var l = layers[r], last = 0;
var want = l.map(function(v) {
var c = near(v, sides);
if (c == null)
c = v.y != null ? center(v) : last;
last = c;
return c;
});
place(l, want);
};
for (r = 1; r <= maxRank; r++)
settle(r, [ 'up' ]);
for (it = 0; it < 3; it++) {
for (r = maxRank - 1; r >= 1; r--)
settle(r, [ 'up', 'down' ]);
for (r = 1; r <= maxRank; r++)
settle(r, [ 'up', 'down' ]);
}
// the lane under the rest
var mainMax = -Infinity, auxMin = Infinity, lane = null;
layers.forEach(function(l) {
l.forEach(function(v) {
if (v.aux)
auxMin = Math.min(auxMin, v.y);
else
mainMax = Math.max(mainMax, v.y + v.h);
});
});
if (auxMin < Infinity) {
var shift = mainMax + LANE_GAP - auxMin;
layers.forEach(function(l) { l.forEach(function(v) { if (v.aux) v.y += shift; }); });
lane = mainMax + LANE_GAP / 2;
}
var minY = Infinity, maxY = -Infinity, maxX = 0;
layers.forEach(function(l) {
l.forEach(function(v) {
minY = Math.min(minY, v.y);
maxY = Math.max(maxY, v.y + v.h);
maxX = Math.max(maxX, v.x + v.w);
});
});
layers.forEach(function(l) { l.forEach(function(v) { v.y -= minY; }); });
if (lane != null)
lane -= minY;
m.list.forEach(function(n) {
var v = info[n.id];
out[n.id] = { x: v.x, y: v.y, w: v.w, h: v.h, rank: v.rank, aux: v.aux };
});
// edges: through the dummies; the ends spread over the node's side by the far end's y
var edges = m.edges.map(function(e, k) {
var c = chain[k];
return { e: e, pts: c ? c.map(function(v) { return { x: v.x, y: center(v), w: v.w, id: v.id }; }) : null };
});
var ports = {};
edges.forEach(function(le) {
if (!le.pts)
return;
var a = le.pts[0], b = le.pts[le.pts.length - 1];
(ports[a.id + '>'] = ports[a.id + '>'] || []).push({ p: a, other: le.pts[1].y });
(ports[b.id + '<'] = ports[b.id + '<'] || []).push({ p: b, other: le.pts[le.pts.length - 2].y });
});
Object.keys(ports).forEach(function(k) {
var l = ports[k], h = NODE_H * 0.6;
l.sort(function(a, b) { return a.other - b.other; });
l.forEach(function(q, i) {
q.p.dy = l.length > 1 ? -h / 2 + h * i / (l.length - 1) : 0;
});
});
edges.forEach(function(le) {
if (!le.pts)
return;
le.pts = le.pts.map(function(p, i) {
var last = i == le.pts.length - 1;
return { x: i == 0 ? p.x + p.w : p.x, y: p.y + (i == 0 || last ? p.dy || 0 : 0) };
});
});
return { nodes: out, edges: edges, width: maxX, height: maxY - minY, ranks: maxRank + 1, lane: lane };
}
// --- live state (mihomo API) -------------------------------------------------
// live(m, proxies, connections, prev, providers) -> what each group uses, alive nodes per
// provider and where the connections go:
// { 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);
// providers: GET /providers/proxies .providers (the subscriptions' nodes);
// connections: GET /connections .connections; prev: the previous result (byte counters -> rates)
function live(m, proxies, connections, prev, providers) {
proxies = proxies || {};
var L = { now: {}, nowProv: {}, delay: {}, provider: {}, groups: {}, edges: {}, nodes: {}, bytes: {},
total: 0, internal: 0, unmatched: 0, unmatchedRules: {}, at: Date.now() };
var edgeIndex = {};
m.edges.forEach(function(e, i) { edgeIndex[e.from + '\n' + e.to] = i; });
var lastDelay = function(p) {
var h = p && p.history;
return h && h.length ? h[h.length - 1].delay : 0;
};
// nodes per provider of this config: {provider: {name: proxy}}
var inProv = {};
Object.keys(providers || {}).forEach(function(v) {
if (!m.providers[v])
return;
var set = inProv[v] = {}, s = L.provider['v:' + v] = { n: 0, alive: 0 };
(providers[v].proxies || []).forEach(function(p) {
set[p.name] = p;
s.n++;
if (p.alive)
s.alive++;
});
});
// a node name as a group uses it: { p: the API's proxy, v: its provider }; the same
// name in two subscriptions -> the one in the group's use
var find = function(name, user) {
if (proxies[name] && !inProv[proxies[name]['provider-name']])
return { p: proxies[name] };
var g = m.nodes[user] && m.nodes[user].kind == 'group' && m.nodes[user].data.def;
var vs = (g && g.use || []).concat(Object.keys(inProv));
for (var i = 0; i < vs.length; i++)
if (inProv[vs[i]] && inProv[vs[i]][name])
return { p: inProv[vs[i]][name], v: vs[i] };
return null;
};
Object.keys(proxies).forEach(function(name) {
var p = proxies[name];
if (!m.groups[name] || p.now == null)
return;
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.delay[id] = lastDelay(f && f.p);
if (f && f.v)
L.nowProv[id] = 'v:' + f.v;
});
// a proxy name of the API -> node id: groups, own proxies, provider nodes, built-ins
var idOf = function(name, user) {
if (m.groups[name])
return 'g:' + name;
if (m.proxies[name])
return 'p:' + name;
var f = find(name, user);
if (f && f.v)
return 'v:' + f.v;
return 'b:' + name;
};
// from a node on: the dialer-proxy chain (or direct) and the groups' current choice
var tail = function(id, path) {
for (var guard = 0; guard < 24; guard++) {
var n = m.nodes[id], next = null;
if (!n)
break;
if (n.kind == 'group' && L.now[id] != null)
next = idOf(L.now[id], id);
else if (n.kind == 'proxy' || n.kind == 'provider')
next = m.dialerOf[id] || null;
if (!next || path.indexOf(next) >= 0)
break;
path.push(next);
id = next;
}
return path;
};
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;
(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 || '')];
if (!rid) {
L.unmatched++;
var u = c.rule + (c.rulePayload ? ' ' + c.rulePayload : '');
L.unmatchedRules[u] = (L.unmatchedRules[u] || 0) + 1;
return;
}
var b = (c.upload || 0) + (c.download || 0);
L.bytes[c.id] = b;
var rate = dt > 0 && prevBytes[c.id] != null ? Math.max(0, b - prevBytes[c.id]) / dt : 0;
var path = [ rid ], user = rid;
(c.chains || []).slice().reverse().forEach(function(name) {
// only along the graph's edges: a rule to DIRECT ends at the rule
var id = idOf(name, user);
if (edgeIndex[path[path.length - 1] + '\n' + id] != null)
path.push(id);
user = id;
});
tail(path[path.length - 1], path);
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) {
var s = L.nodes[id] = L.nodes[id] || { n: 0, rate: 0 };
s.n++;
s.rate += rate;
if (i == 0)
return;
var k = edgeIndex[path[i - 1] + '\n' + id];
if (k == null)
return;
var es = L.edges[k] = L.edges[k] || { n: 0, rate: 0 };
es.n++;
es.rate += rate;
});
});
return L;
}
// --- view --------------------------------------------------------------------
var CSS = '' +
'.mkg{--bg:#fff;--fg:#1f2328;--mute:#6b7280;--line:#9aa4b2;--rule:#f3f4f6;--rule-b:#c9ced6;' +
'--group:#e8f0ff;--group-b:#4c7cf0;--prov:#e7f6ec;--prov-b:#2f9e5b;--proxy:#fff3df;--proxy-b:#d9900f;' +
'--bi:#eef0f3;--bi-b:#9aa4b2;--miss:#ffe3e3;--miss-b:#e03131;--dial:#8b5cf6;--fetch:#2f9e5b;' +
'--now:#4c7cf0;--flow:#f76707;position:relative;color:var(--fg);font:12px/1.3 system-ui,-apple-system,"Segoe UI",sans-serif}' +
'.mkg.mkg-dark{--bg:#16181d;--fg:#e6e8eb;--mute:#9aa1ab;--line:#6b7480;--rule:#23272e;--rule-b:#454c57;' +
'--group:#1b2740;--group-b:#5b8cff;--prov:#15301f;--prov-b:#3fbf74;--proxy:#33270f;--proxy-b:#f0a830;' +
'--bi:#262a31;--bi-b:#6b7480;--miss:#3b1717;--miss-b:#ff6b6b;--dial:#a78bfa;--fetch:#3fbf74;--now:#5b8cff;--flow:#ff922b}' +
'.mkg-bar{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;margin:0 0 6px}' +
'.mkg-bar label{display:inline-flex;gap:4px;align-items:center;cursor:pointer}' +
'.mkg-legend{display:flex;flex-wrap:wrap;gap:4px 12px;color:var(--mute);font-size:11px}' +
'.mkg-legend i{display:inline-block;width:10px;height:10px;border-radius:3px;border:1.5px solid;vertical-align:-1px;margin-right:4px}' +
'.mkg-legend s{display:inline-block;width:22px;height:0;border-top:2px solid;vertical-align:3px;margin-right:4px;text-decoration:none}' +
'.mkg-stage{position:relative;height:72vh;min-height:360px;border:1px solid var(--rule-b);border-radius:6px;overflow:hidden;' +
'background:var(--bg);touch-action:none;cursor:grab}' +
'.mkg-stage.drag{cursor:grabbing}' +
'.mkg svg{display:block;width:100%;height:100%;user-select:none}' +
'.mkg .n rect{stroke-width:1.5}' +
'.mkg .n text{fill:var(--fg);font-size:12px;font-weight:600}' +
'.mkg .n text.s{fill:var(--mute);font-size:10.5px;font-weight:400}' +
'.mkg .n{cursor:pointer}' +
'.mkg .n.rule rect{fill:var(--rule);stroke:var(--rule-b)}' +
'.mkg .n.group rect{fill:var(--group);stroke:var(--group-b)}' +
'.mkg .n.provider rect{fill:var(--prov);stroke:var(--prov-b)}' +
'.mkg .n.proxy rect{fill:var(--proxy);stroke:var(--proxy-b)}' +
'.mkg .n.builtin rect{fill:var(--bi);stroke:var(--bi-b)}' +
'.mkg .n.missing rect{fill:var(--miss);stroke:var(--miss-b)}' +
'.mkg .n.reject text.s{fill:var(--miss-b)}' +
'.mkg .n .live-bits rect.badge{fill:var(--flow);stroke:none}.mkg .n .live-bits text.bt{fill:#fff;font-size:10px;font-weight:700}' +
'.mkg .e{fill:none;stroke:var(--line);stroke-width:1.3;stroke-opacity:.55}' +
'.mkg .e.dialer{stroke:var(--dial);stroke-dasharray:6 3;stroke-opacity:.8}' +
'.mkg .e.fetch{stroke:var(--fetch);stroke-dasharray:2 4;stroke-width:1.5;stroke-opacity:.8}' +
'.mkg .e.file{stroke:var(--fetch);stroke-dasharray:1 3;stroke-opacity:.6}' +
'.mkg .e.wan{stroke-dasharray:3 3;stroke-opacity:.45}' +
'.mkg .lane{stroke:var(--rule-b);stroke-dasharray:4 4}.mkg .lane-t{fill:var(--mute);font-size:11px}' +
'.mkg .lbl{fill:var(--mute);font-size:10px;paint-order:stroke;stroke:var(--bg);stroke-width:3px;stroke-linejoin:round;opacity:0}' +
'.mkg .focus .lbl.hl{opacity:1}' +
'.mkg .live .e.off{stroke-opacity:.15}' +
'.mkg .e.now{stroke:var(--now);stroke-opacity:.95;stroke-width:2}' +
'.mkg .e.flow{stroke:var(--flow);stroke-opacity:.95;stroke-dasharray:8 6;animation:mkg-flow 1s linear infinite}' +
'@keyframes mkg-flow{to{stroke-dashoffset:-14}}' +
'@media (prefers-reduced-motion:reduce){.mkg .e.flow{animation:none}}' +
'.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 .n.sel rect{stroke-width:3}' +
'.mkg-info{position:absolute;top:8px;right:8px;width:min(380px,calc(100% - 16px));max-height:calc(100% - 56px);overflow:auto;' +
'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-it .d.ok{color:var(--prov-b)}.mkg-it .d.mid{color:var(--proxy-b)}.mkg-it .d.bad{color:var(--miss-b)}' +
'.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 .n.pool rect{stroke-width:2;stroke-dasharray:8 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 td:first-child{color:var(--mute);white-space:nowrap}' +
'.mkg-info code{font-size:11px;word-break:break-all}' +
'.mkg-info ul{margin:2px 0;padding-left:18px;max-height:14em;overflow:auto}' +
'.mkg-warn{color:var(--miss-b);font-size:11px}' +
'.mkg-zoom{position:absolute;right:8px;bottom:8px;display:flex;gap:4px}' +
'.mkg.mkg-max{position:fixed;inset:0;z-index:10000;background:var(--bg);padding:10px 12px;overflow:auto;box-sizing:border-box}' +
'.mkg:fullscreen{background:var(--bg);padding:10px 12px;overflow:auto;box-sizing:border-box}' +
'.mkg.mkg-max .mkg-stage,.mkg:fullscreen .mkg-stage{height:calc(100vh - 96px)!important}' +
'.mkg-zoom button{min-width:28px}';
function el(tag, attrs, kids) {
var svg = /^(svg|g|rect|text|path|defs|marker|title|tspan)$/.test(tag);
var e = svg ? document.createElementNS('http://www.w3.org/2000/svg', tag) : document.createElement(tag);
Object.keys(attrs || {}).forEach(function(k) {
if (k == 'text')
e.textContent = attrs[k];
else if (/^on/.test(k))
e.addEventListener(k.slice(2), attrs[k]);
else if (attrs[k] != null)
e.setAttribute(k, attrs[k]);
});
(kids || []).forEach(function(c) { if (c != null) e.appendChild(typeof c == 'string' ? document.createTextNode(c) : c); });
return e;
}
function fmtRate(b) {
if (b < 1024)
return Math.round(b) + ' Б/с';
if (b < 1048576)
return (b / 1024).toFixed(b < 10240 ? 1 : 0) + ' КБ/с';
return (b / 1048576).toFixed(1) + ' МБ/с';
}
function isDark(node) {
for (var n = node; n && n.nodeType == 1; n = n.parentNode) {
var c = getComputedStyle(n).backgroundColor;
var m = /rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?/.exec(c);
if (m && (m[4] == null || +m[4] > 0.5))
return (0.299 * m[1] + 0.587 * m[2] + 0.114 * m[3]) < 128;
}
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}
// view(container, act) -> { show(cfg), live(proxies, connections, providers), fit(), destroy() }
// 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(services, pools) - the kit's services and pools (SERVICES,
// POOLS), then the page shows the rebuilt profile (only on the router)
// show(cfg, meta): meta.services [{name, geosite, domains, ips, via}], meta.pools [{name, type,
// servers, subs, filter, exclude}] - which groups are services / pools; meta.servers, meta.subs -
// own server names and providers a pool can take
function view(container, act) {
if (!document.getElementById('mkg-style'))
document.head.appendChild(el('style', { id: 'mkg-style', text: CSS }));
var canvas = document.createElement('canvas').getContext('2d');
var measure = function(s, px) {
canvas.font = (px == 12 ? '600 ' : '') + px + 'px system-ui,-apple-system,"Segoe UI",sans-serif';
return canvas.measureText(String(s)).width;
};
var root = el('div', { 'class': 'mkg' });
var showLive = el('input', { type: 'checkbox', checked: 'checked' });
var onlyNow = el('input', { type: 'checkbox' });
var stat = el('span', { 'class': 'mkg-legend' });
var legend = el('span', { 'class': 'mkg-legend' }, [
el('span', {}, [ el('i', { style: 'background:var(--rule);border-color:var(--rule-b)' }), 'правила (сверху вниз — порядок)' ]),
el('span', {}, [ el('i', { style: 'background:var(--group);border-color:var(--group-b)' }), 'группы' ]),
el('span', {}, [ el('i', { style: 'background:var(--prov);border-color:var(--prov-b)' }), 'подписки' ]),
el('span', {}, [ el('i', { style: 'background:var(--proxy);border-color:var(--proxy-b)' }), 'серверы' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--dial);border-top-style:dashed' }), 'dialer-proxy' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--line);border-top-style:dashed' }), 'к серверу напрямую' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--fetch);border-top-style:dotted' }), 'качается через' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--now)' }), 'выбрано сейчас' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--flow);border-top-style:dashed' }), 'трафик' ])
]);
var bar = el('div', { 'class': 'mkg-bar' }, [
act && act.saveServices ? el('button', { 'class': 'btn cbi-button cbi-button-add',
title: 'сайт или приложение своим путём: своя группа и правила', onclick: function() { newService(); } }, [ '+ сервис' ]) : null,
act && act.saveServices ? el('button', { 'class': 'btn cbi-button cbi-button-add',
title: 'свой набор серверов: свои серверы и ноды подписок по фильтру', onclick: function() { newPool(); } }, [ '+ пул' ]) : null,
el('label', {}, [ showLive, 'живое состояние' ]),
el('label', { title: 'скрыть члены групп, которые сейчас не выбраны' }, [ onlyNow, 'только выбранное' ]),
stat
]);
var svg = el('svg', {});
var world = el('g', {});
svg.appendChild(el('defs', {}, [
el('marker', { id: 'mkg-arrow', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' },
[ el('path', { d: 'M0,0L10,5L0,10z', style: 'fill:var(--fetch)' }) ])
]));
svg.appendChild(world);
var stage = el('div', { 'class': 'mkg-stage' }, [ svg ]);
var info = el('div', { 'class': 'mkg-info' });
var warn = el('div', { 'class': 'mkg-warn' });
root.appendChild(bar);
root.appendChild(legend);
root.appendChild(el('div', { style: 'height:6px' }));
root.appendChild(stage);
root.appendChild(warn);
stage.appendChild(info);
container.appendChild(root);
root.classList.toggle('mkg-dark', isDark(container));
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 = {}, pools = [], poolOf = {}, meta = {}, editors = {};
var view = { x: 0, y: 0, k: 1 };
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 fit = function() {
if (!lay)
return;
// full screen: the whole window; else at most 72% of it high, the box no taller than the graph
var W = stage.clientWidth || 800, pad = 16;
var H = maxed() ? stage.clientHeight : Math.max(360, (window.innerHeight || 800) * 0.72);
view.k = Math.min(1.2, (W - pad * 2) / Math.max(lay.width, 1), (H - pad * 2) / Math.max(lay.height, 1));
view.k = Math.max(view.k, 0.35);
if (!maxed())
stage.style.height = Math.round(Math.min(H, Math.max(360, lay.height * view.k + pad * 2 + 40))) + 'px';
view.x = pad;
view.y = pad;
apply();
};
// the Fullscreen API, or a fixed overlay where there is none (iPhone Safari)
var full = function() {
if (maxed()) {
if (document.fullscreenElement)
document.exitFullscreen();
root.classList.remove('mkg-max');
} else if (root.requestFullscreen)
root.requestFullscreen().catch(function() { root.classList.add('mkg-max'); });
else
root.classList.add('mkg-max');
window.setTimeout(fit, 120);
};
document.addEventListener('fullscreenchange', function() { window.setTimeout(fit, 120); });
document.addEventListener('keydown', function(ev) {
if (ev.key == 'Escape' && root.classList.contains('mkg-max'))
full();
});
stage.appendChild(el('div', { 'class': 'mkg-zoom' }, [
el('button', { 'class': 'btn cbi-button', title: 'крупнее', onclick: function() { zoomAt(1.25); } }, [ '+' ]),
el('button', { 'class': 'btn cbi-button', title: 'мельче', onclick: function() { zoomAt(0.8); } }, [ '−' ]),
el('button', { 'class': 'btn cbi-button', title: 'весь граф', onclick: fit }, [ '⤢' ]),
el('button', { 'class': 'btn cbi-button', title: 'на весь экран (Esc — выйти)', onclick: function() { full(); } }, [ '⛶' ])
]));
var zoomAt = function(f, cx, cy) {
if (cx == null) {
cx = stage.clientWidth / 2;
cy = stage.clientHeight / 2;
}
var k = Math.max(0.2, Math.min(3, view.k * f));
view.x = cx - (cx - view.x) * k / view.k;
view.y = cy - (cy - view.y) * k / view.k;
view.k = k;
apply();
};
stage.addEventListener('wheel', function(ev) {
if (ev.target.closest && ev.target.closest('.mkg-info'))
return;
ev.preventDefault();
var r = stage.getBoundingClientRect();
zoomAt(Math.exp(-ev.deltaY * 0.0015), ev.clientX - r.left, ev.clientY - r.top);
}, { passive: false });
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) {
if (ev.target.closest && ev.target.closest('.n, button, .mkg-info'))
return;
drag = { x: ev.clientX, y: ev.clientY, vx: view.x, vy: view.y, moved: false };
stage.classList.add('drag');
capture(ev);
});
stage.addEventListener('pointermove', function(ev) {
if (link)
return moveLink(ev);
if (!drag)
return;
view.x = drag.vx + ev.clientX - drag.x;
view.y = drag.vy + ev.clientY - drag.y;
drag.moved = drag.moved || Math.abs(ev.clientX - drag.x) + Math.abs(ev.clientY - drag.y) > 3;
apply();
});
var endDrag = function(ev) {
if (link)
return endLink(ev);
if (drag && !drag.moved)
select(null);
drag = null;
stage.classList.remove('drag');
};
stage.addEventListener('pointerup', endDrag);
stage.addEventListener('pointercancel', endDrag);
// everything a node reaches and everything that reaches it
var reach = function(id) {
var set = {}, es = {};
var walk = function(start, fwd) {
var stack = [ start ];
while (stack.length) {
var cur = stack.pop();
m.edges.forEach(function(e, i) {
if (e.kind == 'fetch' || e.kind == 'file')
return;
if (onlyNow.checked && edgeEls[i] && edgeEls[i].path.style.display == 'none')
return;
var a = fwd ? e.from : e.to, b = fwd ? e.to : e.from;
if (a != cur)
return;
es[i] = 1;
if (!set[b]) {
set[b] = 1;
stack.push(b);
}
});
}
};
set[id] = 1;
walk(id, true);
walk(id, false);
// fetch / file edges of the node itself
m.edges.forEach(function(e, i) {
if ((e.kind == 'fetch' || e.kind == 'file') && (e.from == id || e.to == id)) {
es[i] = 1;
set[e.from] = set[e.to] = 1;
}
});
return { nodes: set, edges: es };
};
var focus = function(id) {
world.classList.toggle('focus', !!id);
var r = id ? reach(id) : { nodes: {}, edges: {} };
Object.keys(nodeEls).forEach(function(k) { nodeEls[k].classList.toggle('hl', !!r.nodes[k]); });
edgeEls.forEach(function(x, i) {
if (!x)
return;
x.path.classList.toggle('hl', !!r.edges[i]);
if (x.label)
x.label.classList.toggle('hl', !!r.edges[i]);
});
spread(r.edges);
};
// the shown filter labels: edges into one subscription end close together, so their
// labels would lie on each other; each one that hits a placed one goes below it
var spread = function(shown) {
var placed = [];
edgeEls.map(function(x, i) { return shown[i] && x && x.label ? x : null; }).filter(Boolean)
.sort(function(a, b) { return a.by - b.by; }).forEach(function(x) {
var y = x.by, hit = true;
while (hit) {
hit = false;
placed.forEach(function(p) {
if (Math.abs(p.bx - x.bx) < (p.w + x.w) / 2 + 4 && Math.abs(p.y - y) < 12) {
y = p.y + 12;
hit = true;
}
});
}
placed.push({ bx: x.bx, w: x.w, y: y });
x.label.setAttribute('y', y);
});
};
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 }),
// delay: green up to 300 ms, yellow up to 800, red above and dead
el('span', { 'class': 'd ' + (d ? d < 300 ? 'ok' : d < 800 ? 'mid' : 'bad' : it.alive ? '' : 'bad'),
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 d = n.data.def || {}, rows = [];
var kind = { rule: 'Правила', group: 'Группа', provider: 'Подписка (proxy-provider)', proxy: 'Сервер',
builtin: 'Встроенный выход', missing: 'Не найдено' }[n.kind];
if (n.kind == 'rule') {
rows.push(row('куда', n.data.items[0].target));
n.data.ruleProviders.forEach(function(rp) {
if (rp.def)
rows.push(row('rule-set ' + rp.name, el('code', { text: (rp.def.type || '') + ' ' + (rp.def.behavior || '') + ' ' +
(rp.def.url ? maskUrl(rp.def.url) : rp.def.path || '') })));
});
rows.push(row('строки', el('ul', {}, n.data.items.map(function(r) { return el('li', {}, [ el('code', { text: '#' + (r.i + 1) + ' ' + r.text }) ]); }))));
} else if (n.kind == 'group') {
rows.push(row('тип', d.type || ''));
if (d.proxies)
rows.push(row('proxies', d.proxies.join(', ')));
if (d.use)
rows.push(row('use', d.use.join(', ')));
[ 'filter', 'exclude-filter', 'exclude-type', 'url', 'interval', 'tolerance', 'lazy' ].forEach(function(k) {
if (d[k] != null)
rows.push(row(k, el('code', { text: String(d[k]) })));
});
if (L && L.now[n.id] != null)
rows.push(row('сейчас', L.now[n.id] + (L.delay[n.id] ? ' · ' + L.delay[n.id] + ' мс' : '')));
} else if (n.kind == 'provider') {
rows.push(row('тип', d.type || ''));
if (d.url)
rows.push(row('url', el('code', { text: maskUrl(d.url) })));
if (d.path)
rows.push(row('path', el('code', { text: d.path })));
if (d.proxy)
rows.push(row('качается через', d.proxy));
[ 'filter', 'exclude-filter' ].forEach(function(k) {
if (d[k] != null)
rows.push(row(k, el('code', { text: String(d[k]) })));
});
if (d.override && Object.keys(d.override).length)
rows.push(row('override', el('code', { text: JSON.stringify(d.override) })));
if (L && L.provider[n.id])
rows.push(row('ноды', L.provider[n.id].n + ', живых ' + L.provider[n.id].alive));
} else if (n.kind == 'proxy') {
[ 'type', 'server', 'port', 'network', 'interface-name', 'dialer-proxy' ].forEach(function(k) {
if (d[k] != null)
rows.push(row(k, String(d[k])));
});
}
if (L && L.nodes[n.id])
rows.push(row('соединений', L.nodes[n.id].n + (L.nodes[n.id].rate ? ' · ' + fmtRate(L.nodes[n.id].rate) : '')));
if (L && n.kind != 'rule') {
var t = L.tail(n.id);
if (t.length > 1)
rows.push(row('путь сейчас', t.map(function(id) { return m.nodes[id] ? m.nodes[id].label : id; }).join(' → ')));
}
var hadFocus = pick.input && document.activeElement == pick.input;
info.style.display = 'block';
var kids = [
el('button', { 'class': 'mkg-x', title: 'закрыть', onclick: function() { select(null); } }, [ '✕' ]),
el('h4', { text: kind + ': ' + n.label }),
el('table', {}, rows)
];
if (act && act.saveServices && n.kind == 'group' && svcOf[n.label])
kids.push(editor(svcOf[n.label]));
if (act && act.saveServices && n.kind == 'group' && poolOf[n.label])
kids.push(poolEditor(poolOf[n.label]));
var picking = act && n.kind == 'group' && L && showLive.checked && L.groups[n.id];
if (picking)
kids.push(chooser(n));
// the editors stay in place: taken out of the page, an open select closes and a field
// loses focus on every poll; the rest goes around them
Array.prototype.slice.call(info.childNodes).forEach(function(c) {
if (kids.indexOf(c) < 0)
info.removeChild(c);
});
var at = info.firstChild;
kids.forEach(function(c) {
if (c.parentNode == info)
at = c.nextSibling;
else
info.insertBefore(c, at);
});
if (picking) {
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 and pools (the kit's SERVICES, POOLS): edit in the panel; a service's
// "через что" also by dragging its group onto MY / FOREIGN / RU / MAIN / DIRECT / a pool
var VIA_TEXT = [ [ 'MY', 'свои серверы (первый живой)' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
[ 'DIRECT', 'напрямую' ], [ 'MAIN', 'как MAIN' ] ];
var viaTargets = function() {
var t = { 'g:MY': 'MY', 'g:FOREIGN': 'FOREIGN', 'g:RU': 'RU', 'g:MAIN': 'MAIN', 'b:DIRECT': 'DIRECT' };
pools.forEach(function(p) { t['g:' + p.name.toUpperCase()] = p.name.toUpperCase(); });
return t;
};
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)$/;
// a name for a new service or pool group: not a built-in one, not taken by the other kind
var nameError = function(name, mine) {
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
return 'имя: латиница, цифры, _ и -';
var G = name.toUpperCase();
if (TAKEN.test(name) || m.groups[G] && !mine[G] || (mine === svcOf ? poolOf : svcOf)[G])
return 'группа ' + G + ' уже есть, возьми другое имя';
return '';
};
// both lists go together (mihomo-kit.sh services); the page shows the rebuilt profile
var saver = function(say, buttons) {
return function(svcList, poolList, what) {
buttons.forEach(function(b) { b.disabled = true; });
say(what + ': пересборка и перезапуск nikki, около 10–20 секунд…');
return act.saveServices(svcList, poolList).catch(function(e) {
buttons.forEach(function(b) { b.disabled = false; });
say(String(e && e.message || e), true);
});
};
};
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', chain: '', server: '', provider: '' };
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'),
mode: el('select', {}, [ [ '', 'Группа / автовыбор' ], [ 'fixed', 'Фиксированный сервер' ] ]
.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); })),
provider: el('select', {}, [ [ '', 'Свои серверы' ] ].concat((meta.subs || []).map(function(id) {
return [ id, 'подписка ' + id ];
})).concat(svc.provider && (meta.subs || []).indexOf(svc.provider) < 0 ? [ [ svc.provider, svc.provider + ' (недоступен)' ] ] : [])
.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); })),
server: input(svc.server, 'точное имя сервера'),
serverList: el('datalist', { id: 'mkg-fixed-' + (svc.name || 'new') }),
via: el('select', {}, VIA_TEXT.concat(pools.map(function(p) { return [ p.name.toUpperCase(), 'пул ' + p.name.toUpperCase() ]; }))
.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); })),
chain: el('select', {}, [ [ '', 'как обычно' ], [ 'DIRECT', 'напрямую' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
[ 'MY', 'MY' ], [ 'MY-EXIT', 'MY-EXIT (whitelist, телефон)' ] ]
.concat(pools.map(function(p) { return [ p.name.toUpperCase(), 'пул ' + p.name.toUpperCase() ]; }))
.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); }))
};
f.via.value = svc.via || 'MY';
f.chain.value = svc.chain || '';
f.mode.value = svc.server ? 'fixed' : '';
f.provider.value = svc.provider || '';
f.server.setAttribute('list', 'mkg-fixed-' + (svc.name || 'new'));
var fixedBox = el('div', {}, [
el('label', {}, [ 'источник сервера', f.provider ]),
el('label', {}, [ 'сервер (точное имя; можно выбрать из подсказок)', f.server ]), f.serverList,
el('div', { 'class': 'mkg-msg', text: 'Сохраняется для всех профилей и телефона. Если сервер исчезнет или не ответит, ' +
'сервис не переключится на другую ноду. Имена из подписки появятся после её загрузки.' })
]);
var fixedFields = function() {
fixedBox.style.display = f.mode.value ? '' : 'none';
f.via.disabled = !!f.mode.value;
while (f.serverList.firstChild) f.serverList.removeChild(f.serverList.firstChild);
var pr = providersLive && providersLive[f.provider.value];
var names = f.provider.value ? (pr && pr.proxies || []).map(function(p) { return p.name; }) : meta.servers || [];
names.forEach(function(n) { f.serverList.appendChild(el('option', { value: n })); });
};
f.mode.addEventListener('change', fixedFields);
f.provider.addEventListener('change', fixedFields);
f.server.addEventListener('focus', fixedFields);
fixedFields();
var msg = el('div', { 'class': 'mkg-msg' });
var say = function(t, err) {
msg.textContent = t;
msg.className = 'mkg-msg' + (err ? ' err' : '');
};
var buttons = [], save = saver(say, buttons);
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, chain: f.chain.value,
server: f.mode.value ? f.server.value.trim() : '', provider: f.mode.value ? f.provider.value : '' };
var others = services.filter(function(x) { return !svc.name || x.name != svc.name; });
var bad = nameError(v.name, svcOf);
if (bad)
return say(bad, 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);
if (f.mode.value && !v.server)
return say('выбери или введи имя фиксированного сервера', true);
if (v.chain && !v.server && v.via != 'MY' && !poolOf[v.via])
return say('вход — только когда выход через MY или пул', true);
if (v.chain && !v.server && v.chain == v.via)
return say('вход и выход — одно и то же', true);
var list = services.map(function(x) { return x.name == svc.name ? v : x; });
if (!svc.name)
list.push(v);
save(list, pools, 'Сохраняю ' + 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', {}, [ 'выход сервиса', f.mode ]),
fixedBox,
el('label', {}, [ 'через что (или потяни от группы к MY / FOREIGN / RU / MAIN / DIRECT / пулу)', f.via ]),
el('label', {}, [ 'вход: через что подключаться к серверу (для фиксированного сервера, MY или пула)', f.chain ]),
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; }), pools, 'Удаляю ' + 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.mode.value = '';
fixedFields();
f.via.value = v;
say('через ' + v + ' — нажми «Сохранить и применить»');
};
box.say = say;
editors[key] = box;
return box;
};
// a pool: own servers ticked, subscriptions ticked + filter (meta.servers / meta.subs)
var poolEditor = function(pool) {
var key = pool ? 'pool:' + pool.name : 'newpool';
if (editors[key])
return editors[key];
pool = pool || { name: '', type: 'fallback', servers: '', subs: '', filter: '', exclude: '' };
var input = function(v, ph) { return el('input', { type: 'text', value: v || '', placeholder: ph }); };
var ticks = function(all, have) {
all = all.slice();
have.forEach(function(v) { if (all.indexOf(v) < 0) all.push(v); });
return all.map(function(v) {
var c = el('input', { type: 'checkbox', style: 'width:auto' });
c.checked = have.indexOf(v) >= 0;
return { v: v, c: c, el: el('label', { style: 'display:inline-block;margin:0 10px 0 0;color:var(--fg)' },
[ c, ' ' + v + (/-my$/.test(v) ? ' [MY]' : '') ]) };
});
};
var f = {
name: input(pool.name, 'de'),
type: el('select', {}, [ [ 'fallback', 'первый живой' ], [ 'url-test', 'самый быстрый' ], [ 'select', 'вручную' ] ]
.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); })),
srv: ticks(meta.servers || [], (pool.servers || '').split(';').map(function(x) { return x.trim(); }).filter(Boolean)),
subs: ticks(meta.subs || [], (pool.subs || '').split(/\s+/).filter(Boolean)),
filter: input(pool.filter, '\\[WL\\] или (?i)🇩🇪|\\bde\\b'),
exclude: input(pool.exclude, '(?i)torrent'),
uplink: el('input', { type: 'checkbox', style: 'width:auto' })
};
f.type.value = pool.type || 'fallback';
f.uplink.checked = pool.uplink == '1';
var msg = el('div', { 'class': 'mkg-msg' });
var say = function(t, err) {
msg.textContent = t;
msg.className = 'mkg-msg' + (err ? ' err' : '');
};
var buttons = [], save = saver(say, buttons);
var users = function() {
var G = pool.name.toUpperCase();
return services.filter(function(x) { return x.via == G || x.chain == G; }).map(function(x) { return x.name; });
};
var saveBtn = el('button', { 'class': 'btn cbi-button cbi-button-apply', onclick: function() {
var v = { name: f.name.value.trim().toLowerCase(), type: f.type.value,
servers: f.srv.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join('; '),
subs: f.subs.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join(' '),
filter: f.filter.value.trim(), exclude: f.exclude.value.trim(), uplink: f.uplink.checked ? '1' : '' };
var bad = nameError(v.name, poolOf);
if (bad)
return say(bad, true);
if (pools.some(function(x) { return x.name == v.name && x.name != pool.name; }))
return say('пул ' + v.name + ' уже есть', true);
if (pool.name && v.name != pool.name && users().length)
return say('через пул идут сервисы ' + users().join(', ') + ': сначала переключи их', true);
if (!v.servers && !v.subs)
return say('отметь свои серверы или подписки', true);
var list = pools.map(function(x) { return x.name == pool.name ? v : x; });
if (!pool.name)
list.push(v);
save(services, list, 'Сохраняю пул ' + v.name);
} }, [ 'Сохранить и применить' ]);
buttons.push(saveBtn);
var box = el('div', { 'class': 'mkg-pick mkg-svc' }, [
el('div', { 'class': 'mkg-msg', text: pool.name ? 'Пул ' + pool.name + ' (настройки kit): группа ' +
pool.name.toUpperCase() + ', через неё могут идти сервисы.' : '' }),
pool.name ? null : el('label', {}, [ 'имя (группа заглавными: de → DE)', f.name ]),
el('label', {}, [ 'как выбирать', f.type ]),
el('label', {}, [ 'свои серверы' ]),
el('div', {}, f.srv.length ? f.srv.map(function(o) { return o.el; }) : [ el('em', { text: 'нет' }) ]),
el('label', {}, [ 'подписки (их ноды — по фильтру ниже)' ]),
el('div', {}, f.subs.length ? f.subs.map(function(o) { return o.el; }) : [ el('em', { text: 'нет' }) ]),
el('label', {}, [ 'фильтр по имени ноды подписки (regex; пусто — все)', f.filter ]),
el('label', {}, [ 'исключить', f.exclude ]),
el('label', { style: 'color:var(--fg)' }, [ f.uplink, ' предлагать в UPLINK: выбрать там — всё сначала через пул' ]),
el('div', { 'class': 'acts' }, [ saveBtn, pool.name ? el('button', { 'class': 'btn cbi-button cbi-button-remove', onclick: function() {
if (users().length)
return say('через пул идут сервисы ' + users().join(', ') + ': сначала переключи их', true);
if (window.confirm('Удалить пул ' + pool.name + '?'))
save(services, pools.filter(function(x) { return x.name != pool.name; }), 'Удаляю пул ' + pool.name);
} }, [ 'Удалить' ]) : null ]),
msg
]);
editors[key] = box;
return box;
};
// the panel for a new service or pool
var newBlock = function(title, hint, box) {
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: title }));
info.appendChild(el('div', { 'class': 'mkg-msg', text: hint }));
info.appendChild(box);
};
var newService = function() {
newBlock('Новый сервис', 'Сайт или приложение, которое всегда идёт своим путём, что бы ни было выбрано в MAIN. ' +
'Через свои серверы — первый живой: выходной IP не скачет; через пул — выход задан настройками.', editor(null));
};
var newPool = function() {
newBlock('Новый пул', 'Свой набор серверов: свои серверы галками и ноды подписок по фильтру. ' +
'Сервис можно пустить через пул — тогда выход одинаковый на роутере и телефоне.', poolEditor(null));
};
// dragging from a service group onto MY / FOREIGN / RU / MAIN / DIRECT / a pool
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(viaTargets()).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);
var via = viaTargets();
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) {
if (selected && nodeEls[selected])
nodeEls[selected].classList.remove('sel');
selected = id;
if (id && nodeEls[id])
nodeEls[id].classList.add('sel');
focus(id);
if (id)
details(m.nodes[id]);
else
info.style.display = 'none';
};
var curve = function(pts) {
var d = 'M' + pts[0].x + ',' + pts[0].y;
for (var i = 1; i < pts.length; i++) {
var a = pts[i - 1], b = pts[i], dx = Math.max(24, (b.x - a.x) / 2);
d += 'C' + (a.x + dx) + ',' + a.y + ' ' + (b.x - dx) + ',' + b.y + ' ' + b.x + ',' + b.y;
}
return d;
};
// fetch / file edges run against the flow: from under the node into the target's side
var arc = function(a, b, kind) {
var ay = a.y + a.h / 2, by = b.y + b.h / 2;
if (kind == 'file')
return 'M' + a.x + ',' + ay + 'C' + (a.x - 40) + ',' + ay + ' ' + (b.x - 40) + ',' + by + ' ' + b.x + ',' + by;
var ax = a.x + a.w / 2, bx = b.x + b.w, low = a.y + a.h + 30;
return 'M' + ax + ',' + (a.y + a.h) + 'C' + ax + ',' + low + ' ' + (bx + 60) + ',' + by + ' ' + bx + ',' + by;
};
var draw = function() {
while (world.firstChild)
world.removeChild(world.firstChild);
nodeEls = {};
edgeEls = [];
var ge = el('g', {}), gl = el('g', {}), gn = el('g', {});
lay.edges.forEach(function(le, i) {
var e = le.e, a = lay.nodes[e.from], b = lay.nodes[e.to];
if (!a || !b)
return;
var d = le.pts && le.pts.length > 1 ? curve(le.pts) : arc(a, b, e.kind);
var p = el('path', { 'class': 'e ' + e.kind, d: d,
'marker-end': e.kind == 'fetch' ? 'url(#mkg-arrow)' : null });
p.appendChild(el('title', { text: (m.nodes[e.from].label + ' → ' + m.nodes[e.to].label) + (e.label ? '\n' + e.label : '') }));
ge.appendChild(p);
var x = { path: p, label: null };
// filters on the way into a subscription: halfway along the last stretch
if (e.kind == 'use' && e.label && le.pts) {
var q = le.pts[le.pts.length - 1], o = le.pts[le.pts.length - 2];
var t = cut(e.label, 30);
x.bx = (o.x + q.x) / 2;
x.by = (o.y + q.y) / 2 - 3;
x.w = measure(t, 10);
x.label = el('text', { 'class': 'lbl', x: x.bx, y: x.by, 'text-anchor': 'middle', text: t });
gl.appendChild(x.label);
}
edgeEls[i] = x;
});
m.list.forEach(function(n) {
var b = lay.nodes[n.id];
var svc = act && act.saveServices && n.kind == 'group' && svcOf[n.label];
var pool = n.kind == 'group' && poolOf[n.label];
var g = el('g', { 'class': 'n ' + n.kind + (/^REJECT/.test(n.data.end || '') ? ' reject' : '') + (svc ? ' svc' : '') +
(pool ? ' pool' : ''),
'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('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,
el('title', { text: n.label + (n.sub ? '\n' + n.sub : '') })
]);
g.addEventListener('mouseenter', function() { if (!selected) focus(n.id); });
g.addEventListener('mouseleave', function() { if (!selected) focus(null); });
if (svc)
// a service: click opens it, a drag sets "через что"; both end in endLink
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;
gn.appendChild(g);
});
if (lay.lane != null)
world.appendChild(el('g', {}, [
el('path', { 'class': 'lane', d: 'M0,' + lay.lane + 'H' + lay.width }),
el('text', { 'class': 'lane-t', x: 0, y: lay.lane + 16,
text: 'служебное — правила сюда не ведут: через что качаются подписки' })
]));
world.appendChild(ge);
world.appendChild(gl);
world.appendChild(gn);
};
var paint = function() {
if (!m)
return;
var on = showLive.checked && L;
world.classList.toggle('live', !!on);
edgeEls.forEach(function(x, i) {
if (!x)
return;
var e = m.edges[i], now = on && L.now[e.from];
var isNow = false, isOff = false;
if (now != null && (e.kind == 'member' || e.kind == 'use')) {
var target = m.nodes[e.to];
isNow = target && (target.label == now && e.kind == 'member' ||
e.kind == 'use' && L.nowProv[e.from] == e.to);
isOff = !isNow;
}
var f = on && L.edges[i];
x.path.classList.toggle('now', !!isNow && !f);
x.path.classList.toggle('off', !!isOff && !f);
x.path.classList.toggle('flow', !!f);
x.path.style.strokeWidth = f ? Math.min(7, 2 + Math.log(1 + f.n) + (f.rate ? Math.log(1 + f.rate / 4096) : 0)) + 'px' : '';
var hide = onlyNow.checked && on && isOff && !f;
x.path.style.display = hide ? 'none' : '';
if (x.label)
x.label.style.display = hide ? 'none' : '';
});
m.list.forEach(function(n) {
var g = nodeEls[n.id], b = lay.nodes[n.id];
var old = g.querySelector('.live-bits');
if (old)
g.removeChild(old);
var sub = g.querySelector('text.s');
var text = n.sub;
if (on && n.kind == 'group' && L.now[n.id] != null)
text = '→ ' + L.now[n.id] + (L.delay[n.id] ? ' · ' + L.delay[n.id] + ' мс' : '');
if (on && n.kind == 'provider' && L.provider[n.id])
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)
sub.textContent = cut(text, Math.max(12, Math.floor((b.w - 18) / 5.6)));
var s = on && L.nodes[n.id];
if (s) {
var t = String(s.n), w = 10 + t.length * 6.5;
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('text', { 'class': 'bt', x: 0, y: 4, 'text-anchor': 'middle', text: t }),
el('title', { text: 'соединений: ' + s.n + (s.rate ? ', ' + fmtRate(s.rate) : '') +
(s.byRule ? '\nиз них прямо из правил: ' + s.byRule : '') })
]));
}
});
stat.textContent = on ? 'соединений: ' + L.total + (L.internal ? ' · свои mihomo: ' + L.internal : '') +
(L.unmatched ? ' · правило не из профиля: ' + L.unmatched : '') +
' · обновлено ' + new Date(L.at).toLocaleTimeString() : '';
stat.title = on ? (L.internal ? 'свои mihomo — соединения без правила: DNS через прокси, скачивание ' +
'подписок и rule-set, проверки нод\n' : '') + (L.unmatched ? 'правила не из этого профиля (например, добавил nikki):\n' +
Object.keys(L.unmatchedRules).map(function(k) { return k + ' — ' + L.unmatchedRules[k]; }).join('\n') : '') : '';
if (selected)
focus(selected);
if (selected && m.nodes[selected])
details(m.nodes[selected]);
};
showLive.addEventListener('change', paint);
onlyNow.addEventListener('change', paint);
var proxiesLive = null, providersLive = null;
return {
show: function(cfg, mt) {
meta = mt || {};
services = meta.services || [];
pools = meta.pools || [];
poolOf = {};
pools.forEach(function(x) { poolOf[x.name.toUpperCase()] = x; });
svcOf = {};
services.forEach(function(x) { svcOf[x.name.toUpperCase()] = x; });
editors = {};
m = model(cfg);
lay = layout(m, measure);
L = null;
selected = null;
info.style.display = 'none';
warn.textContent = m.warnings.length ? '⚠ ' + m.warnings.join('; ') : '';
draw();
fit();
paint();
return m;
},
// GET /proxies .proxies, /connections .connections, /providers/proxies .providers;
// null keeps the last proxies / providers
live: function(proxies, connections, providers) {
if (!m)
return;
if (proxies)
proxiesLive = proxies;
if (providers)
providersLive = providers;
L = live(m, proxiesLive, connections, L, providersLive);
paint();
},
fit: fit,
destroy: function() { container.removeChild(root); }
};
}
return {
model: model,
layout: layout,
live: live,
view: view,
parseRule: parseRule
};
});