156 lines
6.5 KiB
JavaScript
156 lines
6.5 KiB
JavaScript
'use strict';
|
||
'require view';
|
||
'require rpc';
|
||
'require dom';
|
||
|
||
// 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)
|
||
// 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 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 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
|
||
function loadScript(name, global) {
|
||
if (window[global])
|
||
return Promise.resolve(window[global]);
|
||
return new Promise(function(resolve, reject) {
|
||
var s = document.createElement('script');
|
||
s.src = L.resource('mihomo-kit/' + name);
|
||
s.onload = function() { resolve(window[global]); };
|
||
s.onerror = function() { reject(new Error(name + ' not loaded')); };
|
||
document.head.appendChild(s);
|
||
});
|
||
}
|
||
|
||
return view.extend({
|
||
load: function() {
|
||
return Promise.all([ loadScript('servers.js', 'mkServers'), loadScript('graph.js', 'mkGraph'), callGraph(''), callStatus() ]);
|
||
},
|
||
|
||
// /proxies and /providers/proxies every 9 s, /connections every 3 s; only for the running
|
||
// 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() {
|
||
var tick = 0;
|
||
var loop = L.bind(function() {
|
||
if (document.hidden || !this.liveOn)
|
||
return void (this.timer = window.setTimeout(loop, 3000));
|
||
this.fetchLive(tick++ % 3 == 0).then(L.bind(function() {
|
||
this.timer = window.setTimeout(loop, 3000);
|
||
}, this));
|
||
}, this);
|
||
loop();
|
||
},
|
||
|
||
show: function(g) {
|
||
if (g.error) {
|
||
dom.content(this.state, E('p', { 'class': 'alert-message warning' }, g.error));
|
||
return;
|
||
}
|
||
try {
|
||
this.graph.show(window.mkServers.yamlLoad(g.yaml), { services: g.services || [] });
|
||
} catch (e) {
|
||
dom.content(this.state, E('p', { 'class': 'alert-message warning' }, 'Не разобрал профиль: ' + e.message));
|
||
return;
|
||
}
|
||
this.liveOn = g.active && g.profile == g.running;
|
||
dom.content(this.state, this.liveOn ? '' : E('em', g.profile == g.running ? 'nikki остановлен: только схема'
|
||
: 'профиль ' + g.profile + ' сейчас не запущен: только схема, без живого состояния'));
|
||
},
|
||
|
||
render: function(data) {
|
||
var g = data[2], st = data[3];
|
||
this.state = E('div', { 'style': 'margin:.3em 0' });
|
||
var box = E('div');
|
||
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));
|
||
}, this) });
|
||
(st.profiles || []).forEach(function(p) {
|
||
select.appendChild(E('option', { 'value': p }, p + (p == st.profile ? ' (запущен)' : '')));
|
||
});
|
||
select.value = g.profile || st.profile;
|
||
var page = E([], [
|
||
E('h2', 'mihomo-kit: граф'),
|
||
E('div', { 'class': 'cbi-map-descr' }, 'Как устроен профиль: правила (сверху вниз — в порядке проверки) → группы → ' +
|
||
'подписки и серверы → через что они подключаются (dialer-proxy). Наведи или нажми на узел — подсветится всё, ' +
|
||
'что через него идёт; колесо — масштаб, перетаскивание — сдвиг. Для запущенного профиля видно, что выбрано ' +
|
||
'в группах сейчас и куда идут соединения; нажми на группу — выбрать или закрепить пункт (сразу, без ' +
|
||
'перезапуска). Настройки — на странице «Управление».'),
|
||
E('div', { 'style': 'margin:.5em 0' }, [ 'Профиль: ', select ]),
|
||
this.state,
|
||
box
|
||
]);
|
||
// once the page is in the document: the graph fits its box and takes the theme's background
|
||
window.setTimeout(L.bind(function() {
|
||
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.poll();
|
||
}, this), 0);
|
||
return page;
|
||
},
|
||
|
||
handleSave: null,
|
||
handleSaveApply: null,
|
||
handleReset: null
|
||
});
|