'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: { '': {} } }); // slow calls (delay tests, the git server) go as their own requests: LuCI batches calls // made at the same moment into one request, and uhttpd runs a batch one call after another var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', nobatch: true, expect: { '': {} } }); var callOvpnProbe = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_probe', nobatch: true, expect: { '': {} } }); var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } }); var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], expect: { '': {} } }); var callCsqttStatus = rpc.declare({ object: 'mihomo-kit', method: 'csqtt_status', nobatch: true, expect: { '': {} } }); var callTsCheck = rpc.declare({ object: 'mihomo-kit', method: 'ts_check', nobatch: true, expect: { '': {} } }); var callUpdateCheck = rpc.declare({ object: 'mihomo-kit', method: 'update_check', nobatch: true, expect: { '': {} } }); var callExport = rpc.declare({ object: 'mihomo-kit', method: 'export', expect: { '': {} } }); var callImport = rpc.declare({ object: 'mihomo-kit', method: 'import', params: [ 'data', 'keep_local' ], expect: { '': {} } }); var callConfigGet = rpc.declare({ object: 'mihomo-kit', method: 'config_get', expect: { '': {} } }); var callConfigSet = rpc.declare({ object: 'mihomo-kit', method: 'config_set', params: [ 'data' ], 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)); } // OpenVPN: what decides the tunnel now and what happens next, from // bmstu-otp.sh state (via ovpn_status) -> { now, next, pending } function ovpnMode(o) { var at = function(hm, day) { return (day == 'today' ? 'сегодня' : day == 'tomorrow' ? 'завтра' : day) + ' в ' + hm; }; var r = {}; switch (o.mode) { case 'timer': r.now = 'включён таймером до ' + o.until_hm + (o.until_day == 'today' ? '' : o.until_day == 'tomorrow' ? ' завтра' : ' ' + o.until_day); if (o.after == 'off') r.next = 'потом выключится: ' + (o.why == 'manual' ? 'снова действует ручное «Выключить»' : 'это вне расписания' + (o.next && o.next_to == 'on' ? ', включится ' + at(o.next_hm, o.next_day) : '')); else r.next = 'потом останется включённым: ' + (o.why == 'always' ? 'расписание выключено' : 'это внутри расписания'); break; case 'manual': r.now = 'выключен вручную'; r.next = 'сам не включится: «Включить», «Включить расписание» или «на 1 ч»'; break; case 'schedule': r.now = o.want ? 'включён по расписанию' : 'выключен по расписанию'; if (o.next) r.next = (o.next_to == 'off' ? 'выключится ' : 'включится ') + at(o.next_hm, o.next_day); break; case 'always': r.now = 'включён постоянно'; r.next = 'сам не выключится: расписание выключено'; break; default: r.now = 'неизвестно'; } if (o.want && o.tunnel == 'down') r.pending = 'туннель ещё закрыт, cron поднимет в течение минуты'; else if (!o.want && o.tunnel == 'up') r.pending = 'туннель ещё открыт, cron закроет в течение минуты'; return r; } // form helpers for the settings section function text(value, placeholder, type) { return E('input', { 'type': type || 'text', 'class': 'cbi-input-text', 'style': 'width:100%', 'value': value || '', 'placeholder': placeholder || '' }); } function check(value) { var c = E('input', { 'type': 'checkbox' }); c.checked = !!value; return c; } function field(title, el, desc) { return E('div', { 'class': 'cbi-value' }, [ E('label', { 'class': 'cbi-value-title' }, title), E('div', { 'class': 'cbi-value-field' }, [].concat(el, desc ? [ E('div', { 'class': 'cbi-value-description' }, desc) ] : [])) ]); } // hysteria2 servers from pasted text: mihomo proxy YAML (block or {flow} items, // with or without "proxies:") and/or hysteria2:// links -> form values. // dialer-proxy and other keys are ignored: the kit sets them itself. function parseHy2(text) { var unquote = function(v) { v = v.trim(); var m = v.match(/^"((?:[^"\\]|\\.)*)"/); if (m) return m[1].replace(/\\(.)/g, '$1'); m = v.match(/^'((?:[^']|'')*)'/); if (m) return m[1].replace(/''/g, "'"); return v.replace(/\s+#.*$/, '').trim(); }; var fromMap = function(o) { if (o.type && !/^(hysteria2|hy2)$/i.test(o.type)) return null; if (!o.server || !o.password) return null; return { name: o.name || '', server: o.server, port: o.port || '443', password: o.password, obfs_password: o['obfs-password'] || '', sni: o.sni || '', insecure: /^(true|1|yes)$/i.test(o['skip-cert-verify'] || '') ? '1' : '0', up: o.up || '', down: o.down || '' }; }; var out = [], cur = null; var flush = function() { var h = cur && fromMap(cur); if (h) out.push(h); cur = null; }; String(text).split(/\r?\n/).forEach(function(line) { var t = line.trim(), m; if (!t || t.charAt(0) == '#') return; // hysteria2://password@host:port/?sni=..&obfs=salamander&obfs-password=..&insecure=1#name if ((m = t.match(/^(?:hysteria2|hy2):\/\/([^@]*)@([^:\/?#]+|\[[^\]]+\]):?(\d*)[^?#]*(?:\?([^#]*))?(?:#(.*))?$/i))) { flush(); var q = {}; (m[4] || '').split('&').forEach(function(kv) { var i = kv.indexOf('='); if (i > 0) q[decodeURIComponent(kv.slice(0, i))] = decodeURIComponent(kv.slice(i + 1)); }); var h = fromMap({ name: decodeURIComponent(m[5] || ''), server: m[2].replace(/^\[|\]$/g, ''), port: m[3], password: decodeURIComponent(m[1]), 'obfs-password': q['obfs-password'] || '', sni: q.sni || q.peer || '', 'skip-cert-verify': q.insecure || '' }); if (h) out.push(h); return; } // - {name: a, type: hysteria2, ...} if ((m = t.match(/^-?\s*\{(.*)\}$/))) { flush(); cur = {}; m[1].split(',').forEach(function(kv) { var i = kv.indexOf(':'); if (i > 0) cur[kv.slice(0, i).trim()] = unquote(kv.slice(i + 1)); }); flush(); return; } // "- key: value" starts a new item, "key: value" continues it if ((m = t.match(/^(-\s+)?([A-Za-z0-9_-]+)\s*:\s*(.*)$/))) { if (m[1] || !cur) { flush(); cur = {}; } if (m[3] !== '') cur[m[2]] = unquote(m[3]); } }); flush(); return out.map(function(h) { h.name = (h.name || h.server.split('.')[0]).replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || 'hy2'; return h; }); } // qrcode-generator (luci/qrcode.js, installed with the page): a global "qrcode" function loadQr() { if (window.qrcode) return Promise.resolve(window.qrcode); return new Promise(function(resolve, reject) { var s = document.createElement('script'); s.src = L.resource('mihomo-kit/qrcode.js'); s.onload = function() { resolve(window.qrcode); }; s.onerror = function() { reject(new Error('qrcode.js not loaded')); }; document.head.appendChild(s); }); } // one hysteria2 server from the form -> mihomo proxy YAML (parseHy2 reads it back) function hy2Yaml(d) { var q = function(v) { return '"' + String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'; }; var y = [ '- name: ' + d.name, ' type: hysteria2', ' server: ' + d.server, ' port: ' + d.port, ' password: ' + q(d.password) ]; if (d.obfs_password) y.push(' obfs: salamander', ' obfs-password: ' + q(d.obfs_password)); if (d.sni) y.push(' sni: ' + d.sni); if (d.insecure) y.push(' skip-cert-verify: true'); if (d.up) y.push(' up: ' + q(d.up)); if (d.down) y.push(' down: ' + q(d.down)); return y.join('\n') + '\n'; } // clipboard: navigator.clipboard needs https, LuCI is usually plain http; // then execCommand('copy'), and if that fails too, show the text to copy by hand function copyText(text) { if (navigator.clipboard && window.isSecureContext) return navigator.clipboard.writeText(text).then(function() { return true; }); var ta = E('textarea', { 'style': 'position:fixed;top:0;left:0;opacity:0' }, text); document.body.appendChild(ta); ta.select(); var ok = false; try { ok = document.execCommand('copy'); } catch (e) {} document.body.removeChild(ta); return Promise.resolve(ok); } function readFile(input) { var f = input.files && input.files[0]; if (!f) return Promise.resolve(''); return new Promise(function(resolve, reject) { var r = new FileReader(); r.onload = function() { resolve(r.result); }; r.onerror = function() { reject(r.error); }; r.readAsText(f); }); } 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 ещё не настроен: заполни «Настройка» ниже и нажми «Сохранить и применить».')); var select = E('select', { 'class': 'cbi-input-select' }, (st.profiles || []).map(function(p) { return E('option', { 'value': p }, p); })); select.value = st.profile; // mihomo serves its external-ui at /ui; metacubexd/zashboard take the API from the query var updState = E('em', 'проверяю обновления…'); callUpdateCheck().then(function(u) { if (u.error) return dom.content(updState, '— не удалось проверить обновления: ' + u.error); var link = function(href, text) { return E('a', { 'href': href, 'target': '_blank', 'rel': 'noreferrer' }, text); }; if (u.installed && u.installed.indexOf(u.latest) == 0) return dom.content(updState, '— актуальная'); dom.content(updState, [ '— ', E('strong', 'есть обновление: '), link(u.commit, u.latest), ' ' + (u.message || '') ] .concat(u.compare ? [ ' (', link(u.compare, 'что изменилось'), ')' ] : [])); }).catch(function(e) { dom.content(updState, '— не удалось проверить обновления: ' + e); }); var host = window.location.hostname; var dash = 'http://' + host + ':' + st.api_port + '/ui/?hostname=' + encodeURIComponent(host) + '&port=' + st.api_port + (st.api_secret ? '&secret=' + encodeURIComponent(st.api_secret) : ''); sections.push(section('Состояние', [ E('table', { 'class': 'table' }, [ row('nikki', st.running ? [ 'работает — ', E('a', { 'href': dash, 'target': '_blank', 'rel': 'noreferrer' }, 'открыть дашборд') ] : E('strong', 'остановлен')), row('Ядро mihomo', [ st.core_version || 'не найдено' ] .concat(/-ts\d+$/.test(st.core_version || '') ? [ ' — сборка kit: официальное ядро с правками kit' ] : []) .concat(st.core && st.core.ok == '0' ? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'выбрано ' + (st.core.wanted == 'stock' ? 'ядро из прошивки' : st.core.wanted)), ': нажми «Починить» в «Обслуживании»' ] : [])), row('Память mihomo', st.mem_kb ? [ Math.round(st.mem_kb / 1024) + ' МБ (RSS)', st.lite ? ' — облегчённый режим' : '' ] : '—'), row('Версия kit', [ st.kit_version || 'неизвестна (появится после «Обновить kit»)', ' ', updState ]), row('Профиль', [ select, ' ', this.button('Включить', 'apply', 'use', function() { return select.value; }) ]) ]) ])); if (st.openvpn) { var ovpnState = E('span', '—'); var probeRes = E('span'); var otp = E('span', '—'); var modeNow = E('span', '—'); var modeNext = E('span', '—'); var schedInfo = E('span', '—'); var schedStart = E('input', { 'type': 'time', 'value': '09:00' }); var schedEnd = E('input', { 'type': 'time', 'value': '17:00' }); var dayNames = [ 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс' ]; // at least one day stays checked var schedDays = dayNames.map(function() { return E('input', { 'type': 'checkbox', 'checked': true, 'change': function(ev) { if (!schedDays.some(function(c) { return c.checked; })) ev.target.checked = true; } }); }); var daysText = function(d) { return d == '1234567' || !d ? 'каждый день' : d == '12345' ? 'по будням' : d == '67' ? 'по выходным' : d.split('').map(function(x) { return dayNames[x - 1]; }).join(', '); }; var schedFilled = false; var desc = function(t) { return E('span', { 'class': 'cbi-value-description' }, t); }; // the state comes from the kit core through the API: no traffic in the tunnel var ovpnCheck = function() { dom.content(ovpnState, E('em', 'обновляю…')); return callOvpnStatus().then(function(o) { var since = o.up_hm + (o.up_day == 'today' ? '' : o.up_day == 'tomorrow' ? ' завтра' : ' (' + o.up_day + ')'); dom.content(ovpnState, { closed: 'закрыт', up: E('strong', { 'style': 'color:green' }, 'подключён с ' + since), connecting: [ E('strong', { 'style': 'color:#c60' }, 'подключается'), o.err ? desc(' — ' + o.err) : '' ], rejected: [ E('strong', { 'style': 'color:#c00' }, 'сервер не принял сессию'), desc(o.retry_hm ? ' — cron возьмёт новый OTP после паузы, в ' + o.retry_hm : ' — cron возьмёт новый OTP в течение минуты') ], held: [ E('strong', { 'style': 'color:#c60' }, { kick: 'сервер отключил сессию', drop: 'туннель оборвался', failed: 'не подключился' }[o.retry_why] || 'пауза'), desc(' — следующая попытка в ' + o.retry_hm + ' (без быстрых переподключений)' + (o.err ? '; ' + o.err : '')) ], unknown: [ E('strong', 'ядро не сообщает состояние'), desc(' — с этим ядром cron проверяет туннель запросом к сайту раз в ~10 минут, ' + 'и маскировка под Connect неполная. Нужно ядро kit («Обслуживание» → ядро).') ] }[o.link] || o.link || '—'); dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—'); var m = ovpnMode(o); dom.content(modeNow, [ E('strong', m.now) ].concat(m.pending ? [ ' — ', E('span', { 'class': 'cbi-value-description' }, m.pending) ] : [])); dom.content(modeNext, m.next || '—'); dom.content(schedInfo, o.sched_start ? (o.sched_active ? 'включено: ' : 'выключено (часы сохранены): ') + daysText(o.sched_days) + ' с ' + o.sched_start + ' до ' + o.sched_end + ' (МСК), границы сдвигаются до ±' + o.jitter + ' мин' + (o.win ? '; сегодня ' + o.win.replace('-', '–') : '') : 'выключено'); // one of each pair, by the state: timer running or not, schedule on or not var timer = o.mode == 'timer'; timerStart.style.display = timer ? 'none' : ''; timerMore.style.display = timerStop.style.display = timer ? '' : 'none'; timerMore.disabled = timer && o.until - Date.now() / 1000 > o.timer_max * 60 - 120; schedStartBtn.style.display = o.sched_active ? 'none' : ''; schedStopBtn.style.display = o.sched_active ? '' : 'none'; if (!schedFilled) { if (o.sched_start) schedStart.value = o.sched_start; if (o.sched_end) schedEnd.value = o.sched_end; if (o.sched_days) schedDays.forEach(function(c, i) { c.checked = o.sched_days.indexOf(String(i + 1)) >= 0; }); schedFilled = true; } }).catch(function(e) { dom.content(ovpnState, String(e)); }); }; var timerStart = this.button('Включить на 1 ч', 'action', 'ovpn-for', '60'); var timerMore = this.button('+1 ч', 'action', 'ovpn-extend', '60'); var timerStop = this.button('Остановить таймер', 'negative', 'ovpn-stop'); timerMore.style.display = timerStop.style.display = 'none'; var schedStartBtn = this.button('Включить расписание', 'positive', 'ovpn-sched', 'on'); var schedStopBtn = this.button('Выключить расписание', 'negative', 'ovpn-sched', 'off', 'Выключить расписание? Туннель выключится и сам не включится, пока не нажмёшь «Включить» или «Включить расписание».'); schedStopBtn.style.display = 'none'; ovpnCheck(); sections.push(section('OpenVPN', [ E('table', { 'class': 'table' }, [ row('Состояние', [ ovpnState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, ovpnCheck) }, 'Обновить') ]), row('Проверка сайта', [ E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() { dom.content(probeRes, E('em', 'открываю…')); return callOvpnProbe().then(function(r) { dom.content(probeRes, [ r.state == 'up' ? E('strong', { 'style': 'color:green' }, 'открывается, ' + r.delay + ' мс') : [ E('strong', { 'style': 'color:#c00' }, 'не открывается'), ' ' + (r.message || '') ], desc(' — ' + (r.url || '')) ]); }).catch(function(e) { dom.content(probeRes, String(e)); }); }) }, 'Проверить'), ' ', probeRes, E('div', { 'class': 'cbi-value-description' }, 'Открывает адрес проверки через туннель. Только по кнопке: сайт видит такой запрос в логах, ' + 'а сам Connect их не делает. Адрес лучше взять из тех, что и так открываешь в браузере.') ]), row('OTP сейчас', otp), row('Сейчас', modeNow), row('Дальше', modeNext), row('Расписание', schedInfo) ]), E('div', { 'class': 'cbi-page-actions' }, [ this.button('Включить', 'positive', 'ovpn-on', null, 'Включить постоянно? Расписание и таймер выключатся.'), ' ', this.button('Выключить', 'negative', 'ovpn-off', null, 'Закрыть туннель и держать выключенным, пока не нажмёшь «Включить» или «Включить расписание»? ' + 'Расписание и таймер выключатся. ' + 'С ядром kit сессия на сервере освобождается сразу, с другим ядром — через ~5 минут.'), ' ', schedStartBtn, schedStopBtn, ' ', timerStart, timerMore, ' ', timerStop, ' ', this.button('Переподключить', 'action', 'ovpn-refresh') ]), field('Часы расписания (MSK)', [ schedStart, ' – ', schedEnd, ' ', E('span', { 'style': 'white-space:nowrap' }, schedDays.reduce(function(a, c, i) { return a.concat([ ' ', E('label', [ c, ' ', dayNames[i] ]) ]); }, [])), ' ', this.button('Сохранить', 'action', 'ovpn-sched', function() { var d = schedDays.reduce(function(a, c, i) { return c.checked ? a + (i + 1) : a; }, ''); return schedStart.value + ' ' + schedEnd.value + ' ' + d; }) ], '«Сохранить» только запоминает часы и дни, включает их «Включить расписание». ' + 'Режим один из трёх: «Включить» — постоянно, «Выключить» — выключен, «Включить расписание» — ' + 'только в эти часы и в отмеченные дни (окно через полночь относится ко дню, в который началось). ' + 'Выключенное расписание туннель не включает. Таймер («на 1 ч», «+1 ч», до 12 ч вперёд) поднимает туннель ' + 'поверх любого режима, а по окончании или «Остановить таймер» возвращает режим.') ])); } if (st.csqtt) { var cqState = E('span', '—'); var cqUplink = E('span', '—'); var cqInfo = E('span', '—'); var cqCheck = function() { dom.content(cqState, E('em', 'обновляю…')); return callCsqttStatus().then(function(c) { dom.content(cqState, [ { up: E('strong', { 'style': 'color:green' }, 'подключён' + (c.active ? ' (' + c.active + ')' : '')), connecting: E('strong', { 'style': 'color:#c60' }, 'подключается' + (c.stage ? ' (' + c.stage + ')' : '')), stopped: E('strong', c.enabled ? 'остановлен' : 'выключен') }[c.link] || c.link || '—' ] .concat(c.captcha ? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'капча: ' + c.captcha + ' (star-panel-csqtt → CAPTCHA)') ] : []) .concat(c.err ? [ E('div', { 'class': 'cbi-value-description' }, 'последняя ошибка: ' + c.err + (/authorization failed/i.test(c.err) ? ' — нужен новый VK-токен' : '')) ] : [])); dom.content(cqUplink, c.uplink == 'CSQTT' ? E('strong', 'CSQTT — ноды подключаются через туннель') : c.uplink == 'DIRECT' ? 'DIRECT — как без CSQTT' : (c.uplink || 'mihomo не отвечает')); dom.content(cqInfo, c.stats || '—'); }).catch(function(e) { dom.content(cqState, String(e)); }); }; if (st.csqtt_installed) cqCheck(); sections.push(section('CSQTT', st.csqtt_installed ? [ E('table', { 'class': 'table' }, [ row('Туннель', [ cqState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, cqCheck) }, 'Обновить') ]), row('UPLINK', cqUplink), row('Трафик', cqInfo) ]), E('div', { 'class': 'cbi-page-actions' }, [ this.button('Включить', 'positive', 'csqtt-on'), ' ', this.button('Выключить', 'negative', 'csqtt-off') ]), E('p', { 'class': 'cbi-value-description' }, '«Включить»: запускает csqtt, ждёт подключения (до 1,5 мин) и ставит UPLINK = CSQTT. ' + '«Выключить»: UPLINK = DIRECT, затем останавливает csqtt — он не поднимется сам ни после ' + 'перезагрузки, ни при переподключении WAN. Профили и VK-токен — в Службы → star-panel-csqtt.') ] : [ E('p', 'csqtt не установлен: поставь star-panel-csqtt (github.com/starkugz/csqtt-openwrt).') ])); } if (st.tailscale) { var tsState = E('span', '—'); var tsCheck = function() { dom.content(tsState, E('em', 'проверяю…')); return callTsCheck().then(function(r) { dom.content(tsState, { up: E('strong', { 'style': 'color:green' }, 'отвечает, ' + r.delay + ' мс'), down: [ E('strong', { 'style': 'color:#c00' }, 'не отвечает'), ' ' + (r.message || '') ] }[r.state] || r.state); if (r.url) tsState.appendChild(E('span', { 'class': 'cbi-value-description' }, [ ' — ', r.url ])); }).catch(function(e) { dom.content(tsState, String(e)); }); }; if (st.ts_logged_in) tsCheck(); sections.push(section('Tailscale', [ E('table', { 'class': 'table' }, [ row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла')), row('Связь', [ tsState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, tsCheck) }, 'Проверить') ]) ]), E('div', { 'class': 'cbi-page-actions' }, st.ts_logged_in ? [ this.button('Войти заново', 'negative', 'ts-relogin', null, 'Удалить ключ ноды и войти заново? Нода получит новый адрес 100.x.') ] : [ this.button('Получить ссылку для входа', 'positive', 'ts-login', null, st.profile == 'whitelist' ? 'На whitelist Tailscale идёт к серверу входа через MY — ссылка может не появиться. ' + 'Надёжнее включить профиль main (или foreign), войти и вернуться. Всё равно попробовать?' : null) ]) ])); } if (st.mobile_path) { var mobUrl = window.location.protocol + '//' + window.location.host + st.mobile_path; var qrBox = E('div', { 'style': 'width:220px;max-width:100%;background:#fff;padding:8px;border-radius:4px' }, E('em', 'QR…')); loadQr().then(function(qrcode) { var q = qrcode(0, 'M'); q.addData(mobUrl); q.make(); qrBox.innerHTML = q.createSvgTag({ cellSize: 4, margin: 2, scalable: true }); }).catch(function(e) { dom.content(qrBox, String(e)); }); sections.push(section('Телефон (FlClash)', [ E('div', { 'style': 'display:flex;gap:1.5em;flex-wrap:wrap;align-items:flex-start' }, [ qrBox, E('div', { 'style': 'flex:1;min-width:16em' }, [ E('p', 'FlClash → Профили → + → по ссылке (или QR) — профиль из тех же подписок и BOOT, ' + 'без OpenVPN, Tailscale и торрентов; свои серверы — через MY-EXIT.'), E('p', [ E('a', { 'href': mobUrl, 'target': '_blank', 'rel': 'noreferrer' }, mobUrl) ]), E('p', { 'class': 'cbi-value-description' }, 'Ссылка работает только в сети роутера: вне дома FlClash ' + 'просто не обновит профиль. В ней ссылки подписок — не пересылай; «Новая ссылка» отзывает старую.'), this.button('Новая ссылка', 'negative', 'mobile-new', null, 'Выдать новую ссылку? Старая перестанет работать, в FlClash профиль надо будет добавить заново.') ]) ]) ])); } sections.push(section('Обслуживание', [ E('table', { 'class': 'table' }, [ row(this.button('Пересобрать профили', 'action', 'build'), 'profiles.d/*.env → profiles/*.yaml (применится после «Включить» профиль)'), row(E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() { return callExport().then(function(r) { var a = E('a', { 'href': URL.createObjectURL(new Blob([ r.data ], { 'type': 'text/plain' })), 'download': r.name }); document.body.appendChild(a); a.click(); document.body.removeChild(a); }); }) }, 'Экспорт настроек'), 'один файл: подписки, BOOT, профили, свои серверы, OpenVPN (с паролями и .ovpn) — ' + 'для другого роутера; без выбора ядра, ключа Tailscale и ссылки для телефона'), row(this.importBox(), 'заменит настройки этого роутера файлом экспорта и перезапустит профиль'), row(this.coreSelect(st.core || {}), 'ядро mihomo для этого роутера; применяется сразу (перезапуск nikki)'), row(st.auto_update ? this.button('Выключить автообновление', 'negative', 'autoupdate-off') : this.button('Включить автообновление', 'positive', 'autoupdate-on'), [ st.auto_update ? E('strong', 'включено') : 'выключено', ': каждый день в 4:00 (время роутера), если на сервере новый коммит — обновить kit и перезапустить профиль', st.auto_update_last ? E('div', { 'class': 'cbi-value-description' }, 'последний запуск: ' + st.auto_update_last) : '' ]), 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); }, // collapsed: a button; open: the form (always open until configured) renderSettingsBox: function(open) { if (open) return callConfigGet().then(L.bind(this.renderSettings, this)); dom.content(this.settingsBox, [ E('h3', 'Настройка'), E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() { return this.renderSettingsBox(true); }) }, 'Изменить настройки') ]); return Promise.resolve(); }, renderSettings: function(cfg) { var subList = E('div'), subs = []; var hwidBox = E('div'), ovpnBox = E('div'), tsBox = E('div'); var f = { boot: E('textarea', { 'class': 'cbi-input-textarea', 'rows': 3, 'style': 'width:100%;font-family:monospace', 'placeholder': 'vless://…\nvless://… (по одной на строку)' }, cfg.boot_links || ''), hwid_ua: text(cfg.hwid_ua), hwid_os: text(cfg.hwid_os), hwid_os_ver: text(cfg.hwid_os_ver), hwid_model: text(cfg.hwid_model), hwid_id: text(cfg.hwid_id), torrent: check(cfg.torrent), push: check(cfg.push), ru_ips: text(cfg.ru_ips, '1.2.3.4/32 5.6.0.0/16'), foreign_ips: text(cfg.foreign_ips, '1.2.3.4/32 5.6.0.0/16'), my_ips: text(cfg.my_ips, '1.2.3.4/32 5.6.0.0/16'), ru_domains: text(cfg.ru_domains, 'example.ru *.example.com'), foreign_domains: text(cfg.foreign_domains, 'example.com *.example.org'), my_domains: text(cfg.my_domains, 'example.com *.example.org'), openvpn: check(cfg.openvpn), csqtt: check(cfg.csqtt), ovpn: E('input', { 'type': 'file', 'accept': '.ovpn,.conf' }), vpn_username: text(cfg.vpn_username), vpn_password: text('', cfg.has_vpn_password ? 'сохранён — пусто, чтобы не менять' : '', 'password'), totp_secret: text('', cfg.has_totp ? 'сохранён — пусто, чтобы не менять' : 'base32 из QR', 'password'), tailscale: check(cfg.tailscale), ts_hostname: text(cfg.ts_hostname), ts_domains: text(cfg.ts_domains, 'corp.example.com'), ovpn_check_url: text(cfg.ovpn_check_url, 'https://eu.bmstu.ru'), ts_check_url: text(cfg.ts_check_url, 'http://100.69.216.50:8080'), mobile: check(cfg.mobile), lite: check(cfg.lite), lite_gomemlimit: text(cfg.lite_gomemlimit, '64MiB') }; var update = function() { hwidBox.style.display = subs.some(function(s) { return s.hwid.checked; }) ? '' : 'none'; ovpnBox.style.display = f.openvpn.checked ? '' : 'none'; tsBox.style.display = f.tailscale.checked ? '' : 'none'; }; var addSub = function(s) { var vias = [ 'BOOT-AUTO', 'BOOT', 'DIRECT', 'FOREIGN' ]; if (s.via && vias.indexOf(s.via) < 0) vias.push(s.via); var entry = { url: E('input', { 'type': 'text', 'class': 'cbi-input-text', 'style': 'flex:1;min-width:16em', 'value': s.url || '', 'placeholder': 'https://…' }), via: E('select', { 'class': 'cbi-input-select' }, vias.map(function(v) { return E('option', { 'value': v }, v); })), hwid: check(s.hwid), enabled: check(s.enabled !== false) }; entry.via.value = s.via || 'BOOT-AUTO'; entry.hwid.addEventListener('change', update); var el = E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-bottom:.4em' }, [ E('label', { 'title': 'выключенная остаётся в списке, но не попадает в профиль' }, [ entry.enabled, ' вкл' ]), entry.url, E('code', { 'title': 'имя провайдера' }, s.id || 'новая'), 'через', entry.via, E('label', [ entry.hwid, ' HWID' ]), E('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': function() { subList.removeChild(el); subs.splice(subs.indexOf(entry), 1); update(); } }, '✕') ]); subs.push(entry); subList.appendChild(el); }; (cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub); // own hysteria2 servers: one block of fields each var hy2List = E('div'), hy2 = []; var addHy2 = function(h) { var e = { name: text(h.name, 'nl-1'), server: text(h.server, 'vpn.example.com'), port: text(h.port || '443'), password: text(h.password, '', 'password'), obfs_password: text(h.obfs_password, 'пусто — без obfs', 'password'), sni: text(h.sni, 'пусто — как server'), insecure: check(h.insecure == '1'), up: text(h.up, '50 mbps'), down: text(h.down, '100 mbps') }; var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [ field('Имя', e.name, 'буквы, цифры, _ - ; так сервер виден в дашборде'), field('Сервер', e.server), field('Порт', e.port), field('Пароль', e.password, 'auth.password на сервере'), field('Obfs-пароль', e.obfs_password, 'salamander; пусто — без obfs'), field('SNI', e.sni), field('Не проверять сертификат', e.insecure, 'для самоподписанного сертификата (SNI чужого сайта)'), field('Up / Down', [ e.up, e.down ], 'реальный потолок канала клиента; пусто — без ограничения'), E('div', [ E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() { var yaml = hy2Yaml({ name: e.name.value.trim(), server: e.server.value.trim(), port: e.port.value.trim(), password: e.password.value, obfs_password: e.obfs_password.value, sni: e.sni.value.trim(), insecure: e.insecure.checked, up: e.up.value.trim(), down: e.down.value.trim() }); copyText(yaml).then(function(ok) { if (ok) return ui.addNotification(null, E('p', 'Конфиг ' + e.name.value.trim() + ' скопирован: на другом роутере — «Импорт из YAML / ссылки». В нём пароли, не публикуй.'), 'info'); ui.showModal('Конфиг ' + e.name.value.trim(), [ E('p', 'Скопировать автоматически не вышло — выдели и скопируй:'), E('textarea', { 'class': 'cbi-input-textarea', 'rows': 12, 'readonly': 'readonly', 'style': 'width:100%;font-family:monospace', 'click': function(ev) { ev.target.select(); } }, yaml), E('div', { 'class': 'right' }, E('button', { 'class': 'btn', 'click': ui.hideModal }, 'Закрыть')) ]); }); } }, 'Скопировать в буфер'), ' ', E('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': function() { hy2List.removeChild(el); hy2.splice(hy2.indexOf(e), 1); } }, 'Удалить сервер') ]) ]); hy2.push(e); hy2List.appendChild(el); }; (cfg.hy2 || []).forEach(addHy2); // import: paste YAML / hysteria2:// links (or load a file) -> fields var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 10, 'style': 'width:100%;font-family:monospace', 'placeholder': '- name: nl-1\n type: hysteria2\n server: vpn.example.com\n port: 443\n password: ...\n\nили hysteria2://пароль@host:443/?sni=...#nl-1' }); var importFile = E('input', { 'type': 'file', 'accept': '.yaml,.yml,.txt,.conf' }); importFile.addEventListener('change', function() { readFile(importFile).then(function(t) { importText.value = t; }); }); var importBox = E('div', { 'style': 'display:none;margin-bottom:.5em' }, [ importText, E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-top:.3em' }, [ E('span', 'или из файла:'), importFile, E('button', { 'class': 'btn cbi-button cbi-button-apply', 'click': function() { var found = parseHy2(importText.value); if (!found.length) { ui.addNotification(null, E('p', 'Не нашёл серверов hysteria2: нужны хотя бы server и password'), 'warning'); return; } var added = 0, updated = 0; found.forEach(function(h) { var e = hy2.filter(function(x) { return x.name.value.trim() == h.name; })[0]; if (!e) { addHy2(h); added++; return; } Object.keys(h).forEach(function(k) { if (k == 'insecure') e[k].checked = h[k] == '1'; else e[k].value = h[k]; }); updated++; }); importText.value = ''; importBox.style.display = 'none'; ui.addNotification(null, E('p', 'Импорт: добавлено ' + added + ', обновлено ' + updated + '. Проверь поля и нажми «Сохранить и применить».'), 'info'); } }, 'Разобрать') ]) ]); dom.content(hwidBox, [ E('h4', 'HWID (общий для подписок с галкой HWID)'), field('User-Agent', f.hwid_ua), field('x-device-os', f.hwid_os), field('x-ver-os', f.hwid_os_ver), field('x-device-model', f.hwid_model), field('x-hwid', f.hwid_id, 'если провайдер уже знает устройство — оставь тот же') ]); dom.content(ovpnBox, [ field('Файл .ovpn', f.ovpn, cfg.ovpn_file ? 'загружен; выбери файл, только чтобы заменить' : 'ещё не загружен'), field('Логин', f.vpn_username), field('Пароль (без OTP)', f.vpn_password), field('TOTP-секрет', f.totp_secret), field('Адрес для проверки', f.ovpn_check_url, 'что открывает ручная проверка туннеля (кнопка «Проверить» в блоке OpenVPN, тест задержки в дашборде; с ядром не из kit — ещё и cron раз в ~10 минут). Сайт видит этот запрос, поэтому лучше страница, которую и так открываешь в браузере') ]); dom.content(tsBox, [ field('Имя ноды', f.ts_hostname), field('Split-DNS домены', f.ts_domains, 'домены тейлнета кроме *.ts.net, через пробел'), field('Адрес для проверки', f.ts_check_url, 'HTTP-сервис на ноде тейлнета: проверка в дашборде (группа TAILSCALE) и кнопка «Проверить»') ]); f.openvpn.addEventListener('change', update); f.tailscale.addEventListener('change', update); update(); var save = E('button', { 'class': 'btn cbi-button cbi-button-save', 'click': ui.createHandlerFn(this, function() { var list = subs.map(function(s) { return { url: s.url.value.trim(), via: s.via.value, hwid: s.hwid.checked, enabled: s.enabled.checked }; }).filter(function(s) { return s.url; }); var errors = []; if (!list.some(function(s) { return s.enabled; })) errors.push('нужна хотя бы одна включённая подписка'); f.boot.value.split(/\s+/).filter(Boolean).forEach(function(l) { if (!/^vless:\/\/[^@]+@[^?]+\?.*\bpbk=/.test(l)) errors.push('BOOT: не похоже на vless-ссылку с reality (нужны host, pbk, sid): ' + l.slice(0, 40) + '…'); }); if (f.openvpn.checked) { if (!cfg.ovpn_file && !f.ovpn.files.length) errors.push('OpenVPN: выбери файл .ovpn'); if (!f.vpn_username.value.trim()) errors.push('OpenVPN: нужен логин'); if (!cfg.has_vpn_password && !f.vpn_password.value) errors.push('OpenVPN: нужен пароль'); if (!cfg.has_totp && !f.totp_secret.value.trim()) errors.push('OpenVPN: нужен TOTP-секрет'); } if (f.lite_gomemlimit.value.trim() && !/^[1-9][0-9]*(B|KiB|MiB|GiB)?$/.test(f.lite_gomemlimit.value.trim())) errors.push('Лимит памяти: число с единицей, например 64MiB'); var names = {}; var hy2Data = hy2.map(function(e) { var d = {}; Object.keys(e).forEach(function(k) { d[k] = k == 'insecure' ? e[k].checked : (k == 'password' || k == 'obfs_password' ? e[k].value : e[k].value.trim()); }); if (!/^[A-Za-z0-9_-]+$/.test(d.name)) errors.push('Свой сервер: имя «' + d.name + '» — только буквы, цифры, _ -'); else if (names[d.name.toUpperCase().replace(/-/g, '_')]) errors.push('Свой сервер: имя ' + d.name + ' повторяется'); names[d.name.toUpperCase().replace(/-/g, '_')] = true; if (!d.server || !/^[0-9]+$/.test(d.port) || !d.password) errors.push('Свой сервер ' + (d.name || '?') + ': нужны сервер, порт и пароль'); return d; }); if (errors.length) { ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger'); return; } return readFile(f.ovpn).then(L.bind(function(ovpn) { return callConfigSet({ boot_links: f.boot.value.trim(), subs: list, hwid_ua: f.hwid_ua.value, hwid_os: f.hwid_os.value, hwid_os_ver: f.hwid_os_ver.value, hwid_model: f.hwid_model.value, hwid_id: f.hwid_id.value, torrent: f.torrent.checked, push: f.push.checked, ru_ips: f.ru_ips.value.trim(), foreign_ips: f.foreign_ips.value.trim(), my_ips: f.my_ips.value.trim(), ru_domains: f.ru_domains.value.trim(), foreign_domains: f.foreign_domains.value.trim(), my_domains: f.my_domains.value.trim(), openvpn: f.openvpn.checked, csqtt: f.csqtt.checked, ovpn: ovpn, vpn_username: f.vpn_username.value.trim(), vpn_password: f.vpn_password.value, totp_secret: f.totp_secret.value.replace(/\s+/g, ''), tailscale: f.tailscale.checked, ts_hostname: f.ts_hostname.value.trim(), ts_domains: f.ts_domains.value.trim(), ovpn_check_url: f.ovpn_check_url.value.trim(), ts_check_url: f.ts_check_url.value.trim(), mobile: f.mobile.checked, lite: f.lite.checked, lite_gomemlimit: f.lite_gomemlimit.value.trim(), hy2: hy2Data }); }, this)).then(L.bind(function(r) { if (r.error) { ui.addNotification(null, E('p', r.error), 'danger'); return; } return this.follow().then(L.bind(function(j) { if (j && j.rc === 0) return this.renderSettingsBox(false); }, this)); }, this)); }) }, 'Сохранить и применить'); dom.content(this.settingsBox, [ E('h3', 'Настройка'), field('BOOT', f.boot, 'vless-ссылки seed-нод, по одной на строку: группа BOOT берёт первую живую, ' + 'через неё качаются подписки; пусто — без BOOT. Подписки по умолчанию качаются через BOOT-AUTO: ' + 'BOOT, иначе ноды уже скачанных подписок (FOREIGN), иначе напрямую'), field('Подписки', [ subList, E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addSub({}); update(); } }, 'Добавить подписку') ], 'Имя провайдера берётся из домена (sub.kittyvpn.com → kittyvpn), ' + 'настройки привязаны к нему; задать своё: имя=https://…. HWID — для подписок с лимитом устройств.'), hwidBox, field('Торренты', f.torrent, 'через TORRENT-SEL (порты 20000-20199)'), field('Обход для пушей', f.push, 'Apple APNs и Google FCM через группу PUSH (main/foreign — DIRECT, whitelist — MY): ' + 'уведомления не рвутся при смене ноды; выключено — пуши идут по общим правилам'), field('OpenVPN BMSTU', f.openvpn), ovpnBox, field('CSQTT', f.csqtt, 'интерфейс csqtt0 от star-panel-csqtt (Службы → star-panel-csqtt). Группа UPLINK в дашборде: ' + 'DIRECT — как раньше, CSQTT — ноды подписок, BOOT и свои серверы подключаются через csqtt0 ' + '(выход из белых списков), а MAIN/FOREIGN/MY работают поверх'), field('Tailscale', f.tailscale), tsBox, field('Облегчённый режим', f.lite, 'для роутеров с 256 МБ памяти: лимит памяти ядра (GOMEMLIMIT), ' + 'проверки нод раз в 10 минут и только при трафике, сниффер без QUIC, лог nikki — warning, без поиска процессов ' + '(кроме CSQTT), перехват без TUN (TCP redirect, UDP tproxy). Что ещё ест память, kit напишет в журнале применения'), field('Лимит памяти', f.lite_gomemlimit, 'GOMEMLIMIT для облегчённого режима, по умолчанию 64MiB; ' + 'слишком низкий — ядро постоянно чистит память и грузит процессор'), field('Конфиг для телефона', f.mobile, 'FlClash: QR и ссылка появятся на этой странице после сохранения ' + '(файл раздаётся роутером внутри LAN по ссылке со случайным токеном)'), E('h4', 'Свои правила'), E('p', { 'class': 'cbi-value-description' }, 'Через пробел. Выше торрентов, ru-inside, .ru и MAIN (ниже только ' + 'Tailscale, OpenVPN, локальная сеть и пуши). Домен действует вместе с поддоменами (example.com = *.example.com), ' + 'IP без маски = /32. Если адрес попал в несколько списков — побеждает MY, затем FOREIGN, затем RU.'), field('Домены через RU', f.ru_domains, 'на main (свой белый IP) идут напрямую'), field('Домены через FOREIGN', f.foreign_domains), field('Домены через MY', f.my_domains, 'свои серверы: ниже и [MY] из подписок'), field('Доп. IP через RU', f.ru_ips, 'на main (свой белый IP) идут напрямую'), field('Доп. IP через FOREIGN', f.foreign_ips), field('Доп. IP через MY', f.my_ips, 'свои серверы: ниже и [MY] из подписок'), E('h4', 'Свои серверы (hysteria2)'), E('p', { 'class': 'cbi-value-description' }, 'Собираются в группу MY (автовыбор самого быстрого, в дашборде можно закрепить один). MY — пункт в MAIN ' + 'рядом с FOREIGN. К самим серверам на whitelist — через MY-EXIT, на main — напрямую. ' + 'Серверы из подписок с [MY] в имени (например «[MY] 🇩🇪 de-1») тоже попадают в MY, а не в FOREIGN/RU.'), hy2List, importBox, E('div', [ E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addHy2({}); } }, 'Добавить сервер'), ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() { importBox.style.display = importBox.style.display == 'none' ? '' : 'none'; } }, 'Импорт из YAML / ссылки') ]), E('div', { 'class': 'cbi-page-actions' }, [ save ]) ]); }, importBox: function() { var file = E('input', { 'type': 'file', 'accept': '.kit,.txt' }); var keep = check(true); var btn = E('button', { 'class': 'btn cbi-button cbi-button-apply', 'click': ui.createHandlerFn(this, function() { if (!file.files.length) return ui.addNotification(null, E('p', 'Выбери файл экспорта (.kit)'), 'warning'); if (!window.confirm('Заменить все настройки этого роутера файлом ' + file.files[0].name + '?')) return; return readFile(file).then(L.bind(function(text) { return callImport(text, keep.checked); }, this)).then(L.bind(function(r) { if (r.error) return ui.addNotification(null, E('p', r.error), 'danger'); return this.follow(); }, this)); }) }, 'Импорт настроек'); btn.disabled = this.busy; this.buttons.push(btn); return E('div', [ file, ' ', btn, E('div', { 'style': 'margin-top:.3em' }, E('label', [ keep, ' оставить имя ноды Tailscale и x-hwid этого роутера' ])) ]); }, // select stock / official / kit + "Установить" coreSelect: function(c) { var freeMb = Math.floor((+c.free_kb || 0) / 1024), needMb = Math.ceil((+c.need_kb || 0) / 1024); var low = freeMb < needMb; var opts = [ [ 'stock', 'Из прошивки' + (c.stock ? ' (' + c.stock + ')' : ' (нет)'), !c.stock ], [ 'official', 'Официальное ' + (c.official || ''), false ], [ 'kit', 'Сборка kit ' + (c.kit || '') + ' (официальное + правки kit)', false ] ]; var sel = E('select', { 'class': 'cbi-input-select' }, opts.map(function(o) { var opt = E('option', { 'value': o[0] }, o[1]); opt.disabled = o[2]; return opt; })); // MIHOMO_VERSION=... in kit.env: shown as is until a choice replaces it if (c.pinned == '1') sel.insertBefore(E('option', { 'value': '' }, 'закреплено в kit.env: ' + c.wanted), sel.firstChild); sel.value = c.pinned == '1' ? '' : (c.choice || 'kit'); var hint = E('div', { 'class': 'cbi-value-description' }); var update = function() { dom.content(hint, (sel.value == 'official' || sel.value == 'kit') && low ? 'Во флеше свободно ' + freeMb + ' МБ, ядру нужно около ' + needMb + ' МБ: скорее всего не встанет (установка тогда откатится сама)' : ''); }; sel.addEventListener('change', update); update(); return E('div', [ sel, ' ', this.button('Установить', 'apply', 'core', function() { return sel.value; }, 'Поставить выбранное ядро? nikki перезапустится.'), hint ]); }, 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)).then(function() { return j; }); }, 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.settingsBox = E('div', { 'class': 'cbi-section' }); this.renderSettingsBox(!data[0].configured); this.renderBody(data[0]); this.showJob(data[1]); if (data[1].running) this.follow(); return E([], [ E('h2', 'mihomo-kit'), this.body, this.settingsBox, this.jobBox ]); } });