mihomo-kit/luci/mihomo-kit.js
2026-10-09 17:02:44 +03:00

203 lines
7.3 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.

'use strict';
'require view';
'require rpc';
'require ui';
'require dom';
// Backend: /usr/libexec/rpcd/mihomo-kit (luci/rpcd.sh in the kit).
// Commands run as one background job; the page polls its output.
var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { '': {} } });
var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', expect: { '': {} } });
var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } });
var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], expect: { '': {} } });
function wait(ms) {
return new Promise(function(resolve) { window.setTimeout(resolve, ms); });
}
function row(title, value) {
return E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td left', 'width': '33%' }, title),
E('td', { 'class': 'td left' }, value)
]);
}
function section(title, children) {
return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children));
}
return view.extend({
handleSaveApply: null,
handleSave: null,
handleReset: null,
load: function() {
return Promise.all([ callStatus(), callJob() ]);
},
button: function(label, style, cmd, arg, confirmText) {
var btn = E('button', {
'class': 'btn cbi-button cbi-button-' + style,
'click': ui.createHandlerFn(this, function() {
if (confirmText && !window.confirm(confirmText))
return;
return this.run(cmd, typeof arg == 'function' ? arg() : arg);
})
}, label);
btn.disabled = this.busy;
this.buttons.push(btn);
return btn;
},
renderBody: function(st) {
var sections = [];
this.buttons = [];
if (!st.configured)
sections.push(E('div', { 'class': 'alert-message warning' },
'Kit ещё не настроен: запусти по ssh mihomo-kit.sh setup'));
var select = E('select', { 'class': 'cbi-input-select' }, (st.profiles || []).map(function(p) {
return E('option', { 'value': p }, p);
}));
select.value = st.profile;
sections.push(section('Состояние', [
E('table', { 'class': 'table' }, [
row('nikki', st.running ? 'работает' : E('strong', 'остановлен')),
row('Профиль', [ select, ' ',
this.button('Включить', 'apply', 'use', function() { return select.value; }) ])
])
]));
if (st.openvpn) {
var ovpnState = E('em', 'проверяю…');
var otp = E('span', '—');
callOvpnStatus().then(function(o) {
dom.content(ovpnState, {
up: E('strong', { 'style': 'color:green' }, 'туннель работает'),
down: E('strong', { 'style': 'color:#c00' }, 'туннель не отвечает'),
off: 'выключен'
}[o.state] || o.state);
dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—');
}).catch(function(e) { dom.content(ovpnState, String(e)); });
sections.push(section('OpenVPN', [
E('table', { 'class': 'table' }, [
row('Состояние', ovpnState),
row('OTP сейчас', otp)
]),
E('div', { 'class': 'cbi-page-actions' }, [
this.button('Включить', 'positive', 'ovpn-on'), ' ',
this.button('Выключить', 'negative', 'ovpn-off', null,
'Закрыть туннель? Сессия на сервере освободится в течение ~5 минут.'), ' ',
this.button('Переподключить', 'action', 'ovpn-refresh')
])
]));
}
if (st.tailscale)
sections.push(section('Tailscale', [
E('table', { 'class': 'table' }, [
row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла'))
]),
E('div', { 'class': 'cbi-page-actions' }, st.ts_logged_in
? [ this.button('Войти заново', 'negative', 'ts-relogin', null,
'Удалить ключ ноды и войти заново? Нода получит новый адрес 100.x.') ]
: [ this.button('Получить ссылку для входа', 'positive', 'ts-login') ])
]));
sections.push(section('Обслуживание', [
E('table', { 'class': 'table' }, [
row(this.button('Пересобрать профили', 'action', 'build'),
'profiles.d/*.env → profiles/*.yaml (применится после «Включить» профиль)'),
row(this.button('Обновить kit', 'action', 'update', null,
'Скачать свежий kit и пересобрать профили?'),
'шаблоны, скрипты и эта страница; после обновления LuCI может попросить войти заново'),
row(this.button('Починить после обновления nikki', 'action', 'fix', null,
'Перезапустить nikki и вернуть ядро и правки?'),
'версия ядра, TS_FORCE_NOISE_443, reserved_ip')
])
]));
dom.content(this.body, sections);
},
showJob: function(j) {
if (!j.cmd) {
this.jobBox.style.display = 'none';
return;
}
this.jobBox.style.display = '';
var state = j.running ? 'выполняется…' : (j.rc === 0 ? 'готово' : 'ошибка (код ' + j.rc + ')');
dom.content(this.jobTitle, 'Последняя команда: ' + j.cmd + ' — ' + state);
var m = (j.log || '').match(/https:\/\/login\.tailscale\.com\/\S+/g);
dom.content(this.jobLink, m ? E('div', { 'class': 'alert-message notice' }, [
'Вход в Tailscale: ',
E('a', { 'href': m[m.length - 1], 'target': '_blank', 'rel': 'noreferrer' }, m[m.length - 1]),
E('br'), 'После входа в админке Tailscale — Disable key expiry для ноды.'
]) : []);
this.jobLog.textContent = j.log || '';
this.jobLog.scrollTop = this.jobLog.scrollHeight;
},
setBusy: function(busy) {
this.busy = busy;
this.buttons.forEach(function(b) { b.disabled = busy; });
},
run: function(cmd, arg) {
return callRun(cmd, arg || '').then(L.bind(function(r) {
if (r.error) {
ui.addNotification(null, E('p', r.error), 'danger');
return;
}
return this.follow();
}, this));
},
// poll the job until it ends; rpcd may restart under us (kit update)
follow: function() {
var errors = 0;
this.setBusy(true);
var loop = L.bind(function() {
return callJob().then(L.bind(function(j) {
errors = 0;
this.showJob(j);
if (j.running)
return wait(1000).then(loop);
this.setBusy(false);
if (j.rc !== 0)
ui.addNotification(null, E('p', j.cmd + ': ошибка, см. вывод внизу страницы'), 'danger');
return callStatus().then(L.bind(this.renderBody, this));
}, this)).catch(L.bind(function(e) {
if (++errors > 15) {
this.setBusy(false);
ui.addNotification(null, E('p', 'Нет связи с роутером: ' + e), 'danger');
return;
}
return wait(2000).then(loop);
}, this));
}, this);
return loop();
},
render: function(data) {
this.busy = false;
this.buttons = [];
this.body = E('div');
this.jobTitle = E('h3');
this.jobLink = E('div');
this.jobLog = E('pre', { 'style': 'white-space:pre-wrap;max-height:24em;overflow:auto' });
this.jobBox = E('div', { 'class': 'cbi-section' }, [ this.jobTitle, this.jobLink, this.jobLog ]);
this.renderBody(data[0]);
this.showJob(data[1]);
if (data[1].running)
this.follow();
return E([], [ E('h2', 'mihomo-kit'), this.body, this.jobBox ]);
}
});