esim-tools/luci/esim-tools.js
2026-10-14 00:40:04 +03:00

857 lines
42 KiB
JavaScript
Raw Permalink 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/esim-tools (luci/rpcd.sh in the kit).
// Everything that touches lpac or resets the modem runs as one background job
// (esim <command>); the page polls its output.
var callStatus = rpc.declare({ object: 'esim-tools', method: 'status', expect: { '': {} } });
var callModem = rpc.declare({ object: 'esim-tools', method: 'modem', expect: { '': {} } });
var callProfiles = rpc.declare({ object: 'esim-tools', method: 'profiles', expect: { '': {} } });
var callJob = rpc.declare({ object: 'esim-tools', method: 'job', expect: { '': {} } });
var callRun = rpc.declare({ object: 'esim-tools', method: 'run', params: [ 'cmd', 'a', 'b', 'c', 'flag', 'd', 'e', 'f', 'g' ], expect: { '': {} } });
var callCancel = rpc.declare({ object: 'esim-tools', method: 'cancel', expect: { '': {} } });
var callAt = rpc.declare({ object: 'esim-tools', method: 'at', params: [ 'cmd' ], expect: { '': {} } });
var callConfigSet = rpc.declare({ object: 'esim-tools', method: 'config_set', params: [ 'at_port', 'wdm', 'iface' ], expect: { '': {} } });
var callUpdateCheck = rpc.declare({ object: 'esim-tools', method: 'update_check', expect: { '': {} } });
var callSmsGet = rpc.declare({ object: 'esim-tools', method: 'sms_get', expect: { '': {} } });
var callSmsSet = rpc.declare({ object: 'esim-tools', method: 'sms_set', params: [ 'token', 'chat', 'forward', 'remove' ], expect: { '': {} } });
var GREEN = 'color:green', RED = 'color:#c00';
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));
}
function text(value, placeholder) {
return E('input', { 'type': 'text', 'class': 'cbi-input-text', 'value': value || '', 'placeholder': placeholder || '' });
}
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) ] : []))
]);
}
function desc(t) {
return E('span', { 'class': 'cbi-value-description' }, t);
}
function ago(then, now) {
var s = Math.max(0, (now || Date.now() / 1000) - then);
if (s < 90)
return 'только что';
if (s < 5400)
return Math.round(s / 60) + ' мин назад';
if (s < 129600)
return Math.round(s / 3600) + ' ч назад';
return Math.round(s / 86400) + ' дн назад';
}
function duration(sec) {
sec = +sec || 0;
var d = Math.floor(sec / 86400), h = Math.floor(sec % 86400 / 3600), m = Math.floor(sec % 3600 / 60);
return (d ? d + ' д ' : '') + (d || h ? h + ' ч ' : '') + m + ' мин';
}
// "/dev/ttyUSB2 — USB 2-1, 05c6:90d5 Foxconn T99W175, интерфейс 02, драйвер option, 5000 Мбит/с"
function portText(p) {
if (!p || !p.dev)
return '—';
if (!p.exists)
return [ E('code', p.dev), ' — ', E('strong', { 'style': RED }, 'нет такого устройства') ];
var parts = [];
if (p.usb)
parts.push('USB ' + p.usb);
if (p.id)
parts.push(p.id + (p.product && p.product.trim() ? ' ' + p.product.trim() : ''));
if (p.ifnum)
parts.push('интерфейс ' + p.ifnum);
if (p.driver)
parts.push('драйвер ' + p.driver);
if (p.speed)
parts.push(p.speed + ' Мбит/с');
return [ E('code', p.dev) ].concat(parts.length ? [ ' — ', desc(parts.join(', ')) ] : []);
}
// AT answers -> human text
var ACT = { 0: 'GSM', 2: 'UMTS', 3: 'EDGE', 4: 'HSDPA', 5: 'HSUPA', 6: 'HSPA', 7: 'LTE', 10: 'LTE (5GC)', 11: 'NR 5G', 12: 'NG-RAN', 13: 'LTE+NR (EN-DC)' };
var REG = { 0: [ 'не зарегистрирован, не ищет', RED ], 1: [ 'домашняя сеть', GREEN ], 2: [ 'поиск сети…', '' ],
3: [ 'регистрация отклонена', RED ], 4: [ 'неизвестно', '' ], 5: [ 'роуминг', GREEN ] };
function parseSlot(s) {
if (/SIM2\s*ENABLE/i.test(s || ''))
return 'esim';
if (/SIM1\s*ENABLE/i.test(s || ''))
return 'sim';
return '';
}
function parseCops(s) {
var m = (s || '').match(/\+COPS:\s*\d+\s*,\s*\d+\s*,\s*"([^"]*)"\s*(?:,\s*(\d+))?/);
if (!m)
return 'нет сети';
// some firmwares repeat the name: "MegaFon pre-5G MegaFon pre-5G"
var h = m[1].trim(), half = h.slice(0, (h.length - 1) / 2);
if (h.length % 2 == 1 && half && h == half + ' ' + half)
m[1] = half;
return m[1] + (m[2] != null && ACT[m[2]] ? ' · ' + ACT[m[2]] : '');
}
function parseReg(s) {
var m = (s || '').match(/\+CEREG:\s*\d+\s*,\s*(\d+)/);
if (!m)
return s || '—';
var r = REG[m[1]] || [ 'состояние ' + m[1], '' ];
return E('strong', { 'style': r[1] }, r[0]);
}
function parseCsq(s) {
var m = (s || '').match(/\+CSQ:\s*(\d+)/);
if (!m || m[1] == '99')
return 'нет данных';
var rssi = +m[1], dbm = -113 + 2 * rssi;
var bars = rssi >= 20 ? 4 : rssi >= 15 ? 3 : rssi >= 10 ? 2 : rssi >= 5 ? 1 : 0;
return [ E('span', { 'style': 'font-family:monospace;letter-spacing:1px' }, '▂▄▆█'.slice(0, bars) + '····'.slice(bars)),
' ' + dbm + ' дБм (CSQ ' + rssi + ')' ];
}
function parseCpin(s) {
if (/READY/.test(s || ''))
return E('strong', { 'style': GREEN }, 'готова');
if (/SIM PIN/.test(s || ''))
return E('strong', { 'style': RED }, 'нужен PIN');
return E('strong', { 'style': RED }, s || 'нет SIM');
}
// LPA:1$smdp.example.com$MATCHING-ID[$OID$1] -> { smdp, mid, cc }
function parseLpa(s) {
var m = String(s || '').trim().match(/^(?:LPA:)?1\$([^$]+)\$([^$]*)(?:\$([^$]*))?(?:\$([^$]*))?$/i);
return m ? { smdp: m[1], mid: m[2], ccRequired: m[4] == '1' } : null;
}
// connection settings of a profile / SIM1 -> one line
function apnSummary(c) {
if (!c || !c.apn)
return desc('не заданы (остаётся текущий APN)');
return [ E('code', c.apn) ].concat(desc([ c.user ? 'логин ' + c.user : '', c.pass ? 'пароль ***' : '',
c.auth ? c.auth.toUpperCase() : '', c.ip || '', c.init ? 'APN регистрации ' + c.init : '' ]
.filter(Boolean).map(function(t) { return ' · ' + t; }).join('')));
}
// APN the network gave to the active SIM: +CGCONTRDP (what the network assigned
// to the active bearers) first, else +CGDCONT? (what the modem has configured).
// The network may append the operator id (.mncXXX.mccYYY.gprs) - cut off.
var SERVICE_APN = /^(ims|sos|xcap|ut|hos|mms)$/i;
var PDP_IP = { 'IP': 'ipv4', 'IPV6': 'ipv6', 'IPV4V6': '' };
function parseNetApn(contrdp, cgdcont) {
var strip = function(a) { return String(a || '').trim().replace(/\.mnc\d+\.mcc\d+\.gprs$/i, ''); };
var types = {}, configured = [];
String(cgdcont || '').split('\n').forEach(function(l) {
var m = l.match(/\+CGDCONT:\s*(\d+)\s*,\s*"?([^",]*)"?\s*,\s*"?([^",]*)"?/);
if (!m)
return;
types[m[1]] = m[2].toUpperCase();
var apn = strip(m[3]);
if (apn && !SERVICE_APN.test(apn))
configured.push({ apn: apn, ip: PDP_IP[types[m[1]]], from: 'настроен в модеме (+CGDCONT)' });
});
var net = [];
String(contrdp || '').split('\n').forEach(function(l) {
var m = l.match(/\+CGCONTRDP:\s*(\d+)\s*,\s*\d+\s*,\s*"?([^",]*)"?/);
var apn = m && strip(m[2]);
if (apn && !SERVICE_APN.test(apn))
net.push({ apn: apn, ip: PDP_IP[types[m[1]]], from: 'выдан сетью (+CGCONTRDP)' });
});
return net[0] || configured[0] || null;
}
function readImage(input) {
var f = input.files && input.files[0];
if (!f)
return Promise.reject(new Error('нет файла'));
return createImageBitmap(f);
}
return view.extend({
handleSaveApply: null,
handleSave: null,
handleReset: null,
load: function() {
return Promise.all([ callStatus(), callProfiles(), callJob() ]);
},
button: function(label, style, cmd, args, confirmText) {
var btn = E('button', {
'class': 'btn cbi-button cbi-button-' + style,
'click': ui.createHandlerFn(this, function() {
var a = typeof args == 'function' ? args() : (args || []);
if (!a)
return;
var c = typeof confirmText == 'function' ? confirmText() : confirmText;
if (c && !window.confirm(c))
return;
return this.run(cmd, a);
})
}, label);
btn.disabled = this.busy;
this.buttons.push(btn);
return btn;
},
// ---- Настройки подключения профиля (apn.map) ----
apnButton: function(label, key, title, cur, active) {
var btn = E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, function() { this.apnDialog(key, title, cur || {}, active); }) }, label);
btn.disabled = this.busy;
this.buttons.push(btn);
return btn;
},
apnDialog: function(key, title, cur, active) {
var sel = function(value, opts) {
var s = E('select', { 'class': 'cbi-input-select' }, opts.map(function(o) { return E('option', { 'value': o[0] }, o[1]); }));
s.value = value || '';
if (s.value != (value || ''))
s.appendChild(E('option', { 'value': value, 'selected': 'selected' }, value));
return s;
};
var f = {
apn: text(cur.apn, 'internet'),
user: text(cur.user),
pass: E('input', { 'type': 'password', 'class': 'cbi-input-password', 'value': cur.pass || '' }),
auth: sel(cur.auth, [ [ '', 'по умолчанию' ], [ 'pap', 'PAP' ], [ 'chap', 'CHAP' ], [ 'pap chap', 'PAP или CHAP' ],
[ 'mschapv2', 'MSCHAPv2' ], [ 'none', 'без авторизации' ] ]),
ip: sel(cur.ip, [ [ '', 'IPv4v6 (по умолчанию)' ], [ 'ipv4', 'только IPv4' ], [ 'ipv6', 'только IPv6' ] ]),
init: text(cur.init, 'пусто — как модем решит сам')
};
var showPass = E('label', { 'style': 'margin-left:.5em' }, [ E('input', { 'type': 'checkbox', 'change': function(ev) {
f.pass.type = ev.target.checked ? 'text' : 'password';
} }), ' показать' ]);
// only the SIM that works right now can be asked
var live = this.slotNow ? (key == 'sim1' ? this.slotNow == 'sim' : active && this.slotNow == 'esim') : true;
var netOut = E('pre', { 'style': 'white-space:pre-wrap;max-height:10em;overflow:auto;margin:.4em 0 0;display:none;font-size:90%' });
var netHint = E('span', { 'class': 'cbi-value-description', 'style': 'margin-left:.5em' });
var netBtn = E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() {
dom.content(netHint, 'спрашиваю модем…');
return Promise.all([ callAt('AT+CGCONTRDP'), callAt('AT+CGDCONT?') ]).then(function(r) {
var err = r[0].error || r[1].error;
netOut.style.display = '';
netOut.textContent = err ? '!! ' + err : '> AT+CGCONTRDP\n' + (r[0].output || '') + '\n> AT+CGDCONT?\n' + (r[1].output || '');
if (err)
return dom.content(netHint, E('span', { 'style': RED }, 'модем не ответил'));
var found = parseNetApn(r[0].output, r[1].output);
if (!found)
return dom.content(netHint, E('span', { 'style': RED },
'APN в ответе не нашёлся — сеть не подключена или APN пустой; ответ модема ниже'));
f.apn.value = found.apn;
if (found.ip != null)
f.ip.value = found.ip;
dom.content(netHint, [ E('strong', { 'style': GREEN }, found.apn), ' — ' + found.from +
(found.ip != null ? ', тип IP подставлен' : '') + '. Логин/пароль сеть не сообщает.' ]);
}).catch(function(e) { dom.content(netHint, String(e)); });
}) }, 'Узнать у сети');
if (!live) {
netBtn.disabled = true;
dom.content(netHint, key == 'sim1' ? 'сейчас активна eSIM — переключи слот на SIM1' : 'сначала включи этот профиль');
}
var submit = L.bind(function(remove) {
var d = {};
Object.keys(f).forEach(function(k) { d[k] = k == 'pass' ? f[k].value : f[k].value.trim(); });
if (!remove) {
var errors = [];
if (!/^[A-Za-z0-9._-]+$/.test(d.apn))
errors.push('APN обязателен: буквы, цифры, . - _');
if (d.init && !/^[A-Za-z0-9._-]+$/.test(d.init))
errors.push('APN регистрации: буквы, цифры, . - _');
if (/[\t\r\n]/.test(d.user + d.pass))
errors.push('логин/пароль: без табуляций и переводов строки');
if (errors.length)
return ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger');
}
ui.hideModal();
return this.run('profile-apn', remove ? [ key ]
: [ key, d.apn, d.user, false, d.pass, d.auth, d.ip, d.init ]);
}, this);
ui.showModal('Подключение: ' + title, [
E('p', { 'class': 'cbi-value-description' }, 'Обязателен только APN, остальное — если оператор это указал. ' +
(active ? 'Профиль сейчас активен: интерфейс переподключится сразу.' : 'Применится при включении.')),
field('APN', [ f.apn, E('div', { 'style': 'margin-top:.3em' }, [ netBtn, netHint ]), netOut ],
'«Узнать у сети» — APN, который оператор выдал этой SIM сейчас'),
field('Логин', f.user),
field('Пароль', [ f.pass, showPass ]),
field('Авторизация', f.auth, 'PAP/CHAP — если оператор дал логин и пароль'),
field('Тип IP', f.ip, 'если не подключается с IPv4v6 — попробуй только IPv4'),
field('APN регистрации', f.init, 'initial EPS bearer: только если модем не регистрируется в LTE ' +
'(«регистрация отклонена» при нормальном сигнале)'),
E('div', { 'class': 'right' }, [
E('button', { 'class': 'btn', 'click': ui.hideModal }, 'Отмена'), ' ',
cur.apn ? E('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': ui.createHandlerFn(this, function() {
if (window.confirm('Убрать настройки подключения для ' + title + '? Интерфейс останется с текущими.'))
return submit(true);
}) }, 'Убрать') : '', ' ',
E('button', { 'class': 'btn cbi-button cbi-button-save', 'click': ui.createHandlerFn(this, function() {
return submit(false);
}) }, 'Сохранить')
])
]);
},
// ---- Модем: состояние по AT ----
renderModem: function() {
var box = this.modemBox;
dom.content(box, [ E('h3', 'Модем'), E('em', 'спрашиваю модем…') ]);
return callModem().then(L.bind(function(m) {
var refresh = E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, this.renderModem) }, 'Обновить');
if (m.busy)
return dom.content(box, [ E('h3', 'Модем'),
E('p', [ E('em', 'занят: ' + m.cmd + ' — состояние появится после окончания'), ' ', refresh ]) ]);
if (m.error)
return dom.content(box, [ E('h3', 'Модем'), E('div', { 'class': 'alert-message warning' }, [
'AT-порт не отвечает: ' + m.error + '. Проверь порт в «Подключении» ниже.' ]), refresh ]);
var slot = parseSlot(m.slot);
// "Model: MV31-W|Revision: T99W175...|SVN: 01|IMEI: ...|+GCAP: ..." -> model · revision · IMEI
var ati = (m.ati || '').split('|').filter(function(l) { return /^(Model|Revision|IMEI)\s*:/i.test(l); })
.map(function(l) { return /^IMEI/i.test(l) ? l.replace(/\s*:\s*/, ' ') : l.replace(/^[^:]*:\s*/, ''); });
if (!ati.length)
ati = (m.ati || '').split('|').filter(function(l) { return !/^(Manufacturer|OK|\+GCAP)/i.test(l); });
this.slotNow = slot;
dom.content(box, [
E('h3', 'Модем'),
E('table', { 'class': 'table' }, [
row('Модель', ati.length ? ati.join(' · ') : '—'),
row('Слот SIM', [
slot == 'esim' ? E('strong', 'eSIM (SIM2)') : slot == 'sim' ? E('strong', 'физическая SIM (SIM1)') : (m.slot || '—'),
' ',
slot != 'esim' ? this.button('Переключить на eSIM', 'apply', 'slot', [ 'esim' ],
'Переключить модем на eSIM? Модем перезагрузится, интернет пропадёт примерно на минуту.') : '',
slot != 'sim' ? this.button('Переключить на SIM1', 'apply', 'slot', [ 'sim' ],
'Переключить модем на физическую SIM (SIM1)? Модем перезагрузится, интернет пропадёт примерно на минуту.') : ''
]),
row('SIM', parseCpin(m.cpin)),
row('Оператор', parseCops(m.cops)),
row('Регистрация (LTE)', parseReg(m.cereg)),
row('Сигнал', parseCsq(m.csq))
]),
E('div', { 'class': 'right' }, [
this.button('Перезапуск радио', 'action', 'radio', [],
'Перезапустить радио (AT+CFUN=4 → 1)? Модем заново зарегистрируется в сети, интернет пропадёт секунд на 15.'), ' ',
this.button('Перезагрузить модем', 'negative', 'reboot', [],
'Перезагрузить модем целиком (AT+CFUN=1,1)? Интернет пропадёт примерно на минуту.'), ' ',
refresh ]),
E('div', { 'class': 'cbi-value-description', 'style': 'text-align:right' },
'Перезапуск радио — когда висит «поиск сети», плохая вышка, интернет «есть, но не ходит» или после охлаждения; ' +
'не помогло — перезагрузка модема')
]);
}, this)).catch(function(e) {
dom.content(box, [ E('h3', 'Модем'), E('p', String(e)) ]);
});
},
// ---- Профили eSIM (кэш последнего ответа lpac) ----
renderProfiles: function(p) {
var list = p.list && p.list.payload && p.list.payload.data;
var chip = p.chip && p.chip.payload && p.chip.payload.data;
var res = chip && chip.EUICCInfo2 && chip.EUICCInfo2.extCardResource || {};
var refreshBtn = this.button('Обновить с чипа', 'action', 'refresh', [], null);
var apns = p.apns || {};
var rows = [];
(Array.isArray(list) ? list : []).forEach(L.bind(function(pr) {
var on = pr.profileState == 'enabled';
var icon = pr.icon && /^image\//.test(pr.iconType || 'image/png')
? E('img', { 'src': 'data:' + (pr.iconType || 'image/png') + ';base64,' + pr.icon,
'style': 'width:24px;height:24px;vertical-align:middle;margin-right:.4em' }) : '';
rows.push(E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td' }, on ? E('strong', { 'style': GREEN }, '● включён') : E('span', '○ выключен')),
E('td', { 'class': 'td' }, [].concat(icon, E('strong', pr.profileNickname || pr.serviceProviderName || '—'),
pr.profileNickname && pr.serviceProviderName ? [ E('br'), desc(pr.serviceProviderName) ] : [],
pr.profileName && pr.profileName != pr.serviceProviderName ? [ E('br'), desc(pr.profileName) ] : [],
[ E('br'), desc('APN: ') ], apnSummary(apns[pr.iccid]))),
E('td', { 'class': 'td' }, E('code', pr.iccid)),
E('td', { 'class': 'td right', 'style': 'white-space:nowrap' }, [
on
? this.button('Выключить', 'negative', 'disable', [ pr.iccid ],
'Выключить профиль ' + pr.iccid + '? Модем останется без активного профиля, интернета через eSIM не будет.')
: this.button('Включить', 'positive', 'enable', [ pr.iccid ],
'Включить профиль ' + (pr.profileNickname || pr.serviceProviderName || pr.iccid) +
'? Текущий выключится, модем перезагрузится, интернет пропадёт на минуту-две.'),
' ',
this.apnButton('APN', pr.iccid, pr.profileNickname || pr.serviceProviderName || pr.iccid, apns[pr.iccid], on),
' ',
this.button('Имя', 'action', 'rename', function() {
var n = window.prompt('Имя профиля ' + pr.iccid + ' (до 64 символов):', pr.profileNickname || '');
return n && n.trim() ? [ pr.iccid, n.trim() ] : null;
}),
' ',
on ? '' : this.button('Удалить', 'remove', 'delete', function() {
var a = window.prompt('Профиль ' + pr.iccid + ' будет удалён с чипа НАВСЕГДА — повторно скачать по ' +
'тому же коду обычно нельзя.\n\nДля подтверждения введи последние 4 цифры ICCID:');
if (a == null)
return null;
if (a.trim() != pr.iccid.slice(-4)) {
ui.addNotification(null, E('p', 'Цифры не совпали — удаление отменено'), 'warning');
return null;
}
return [ pr.iccid ];
})
])
]));
}, this));
var body;
if (!Array.isArray(list))
body = E('p', [ E('em', 'Список ещё не читался. '),
'Нажми «Обновить с чипа»: ModemManager на время остановится, интернет пропадёт примерно на полминуты.' ]);
else if (!rows.length)
body = E('p', E('em', 'На чипе нет профилей — добавь ниже.'));
else
body = E('table', { 'class': 'table' }, [
E('tr', { 'class': 'tr table-titles' }, [
E('th', { 'class': 'th' }, 'Состояние'), E('th', { 'class': 'th' }, 'Профиль'),
E('th', { 'class': 'th' }, 'ICCID'), E('th', { 'class': 'th right' }, '')
])
].concat(rows));
dom.content(this.profilesBox, [
E('h3', 'Профили eSIM'),
E('table', { 'class': 'table' }, [
row('EID', chip && chip.eidValue ? E('code', chip.eidValue) : '—'),
row('Память чипа', res.freeNonVolatileMemory != null
? 'свободно ' + Math.round(res.freeNonVolatileMemory / 1024) + ' КБ' +
(res.installedApplication != null ? ', профилей установлено: ' + res.installedApplication : '')
: '—'),
row('Данные', [ p.list_time ? 'прочитаны с чипа ' + ago(p.list_time, p.now) : 'ещё не читались', ' ', refreshBtn,
E('div', { 'class': 'cbi-value-description' },
'Список хранится на роутере; любое действие с профилем обновляет его само.') ])
]),
body
]);
},
// ---- Добавить профиль ----
renderAdd: function() {
var lpa = text('', 'LPA:1$smdp.example.com$MATCHING-ID');
lpa.style.width = '100%';
var smdp = text('', 'smdp.example.com'), mid = text('', 'XXXX-XXXX-XXXX-XXXX'), cc = text('', 'если оператор выдал');
var enable = E('input', { 'type': 'checkbox' });
var hint = E('div', { 'class': 'cbi-value-description' });
var fill = function() {
var r = parseLpa(lpa.value);
if (!r) {
dom.content(hint, lpa.value.trim() ? E('span', { 'style': RED }, 'не похоже на строку LPA:1$адрес$код') : '');
return;
}
smdp.value = r.smdp;
mid.value = r.mid;
dom.content(hint, r.ccRequired ? E('strong', 'Этот профиль требует код подтверждения (CC) — впиши его ниже.') : 'разобрано ↓');
};
lpa.addEventListener('input', fill);
var qr = '';
if ('BarcodeDetector' in window) {
var file = E('input', { 'type': 'file', 'accept': 'image/*' });
file.addEventListener('change', function() {
readImage(file).then(function(img) {
return new window.BarcodeDetector({ formats: [ 'qr_code' ] }).detect(img);
}).then(function(codes) {
var c = (codes || []).map(function(x) { return x.rawValue; }).filter(function(v) { return parseLpa(v); })[0];
if (!c)
return ui.addNotification(null, E('p', 'На картинке не нашёлся QR с кодом LPA'), 'warning');
lpa.value = c;
fill();
}).catch(function(e) { ui.addNotification(null, E('p', 'QR: ' + e), 'warning'); });
});
qr = field('QR-код', file, 'картинка или скриншот QR от оператора — строка LPA заполнится сама');
}
var addBtn = this.button('Скачать профиль', 'save', 'add', function() {
var s = smdp.value.trim(), m = mid.value.trim(), c = cc.value.trim();
var errors = [];
if (!/^[A-Za-z0-9.-]+(:\d+)?$/.test(s))
errors.push('адрес SM-DP+: нужен домен вроде smdp.example.com');
if (!/^[A-Za-z0-9_.-]+$/.test(m))
errors.push('Matching ID (код активации): только буквы, цифры, - _ .');
if (c && !/^[A-Za-z0-9]+$/.test(c))
errors.push('код подтверждения: только буквы и цифры');
if (errors.length) {
ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger');
return null;
}
return [ s, m, c, enable.checked ];
}, function() {
return 'Скачать профиль с ' + smdp.value.trim() + '?\n\nКод активации обычно одноразовый: если скачивание ' +
'упадёт, не повторяй вслепую — сначала посмотри ошибку в выводе.' +
(enable.checked ? '\n\nПосле скачивания профиль включится, модем перезагрузится.' : '') +
'\n\nНа время операции интернет через модем пропадёт.';
});
dom.content(this.addBox, [
E('h3', 'Добавить профиль'),
field('Строка LPA', [ lpa, hint ], 'из QR-кода оператора: LPA:1$адрес$код — вставь целиком'),
qr,
field('Адрес SM-DP+', smdp),
field('Matching ID', mid, 'код активации'),
field('Код подтверждения', cc, 'CC / Confirmation Code — только если оператор его выдал'),
field('Включить сразу', enable, 'после скачивания переключиться на новый профиль'),
E('div', { 'class': 'cbi-page-actions' }, addBtn)
]);
},
// ---- Подключение: куда идут AT-команды, интерфейс, APN, AT-консоль ----
renderConn: function(st, editing) {
var deps = st.deps || {}, missing = Object.keys(deps).filter(function(k) { return !deps[k]; });
var apn = text(st.apn, 'не задан — оператор выдаёт сам');
apn.style.minWidth = '16em';
var children = [ E('h3', 'Подключение') ];
if (missing.length)
children.push(E('div', { 'class': 'alert-message warning' },
'Не установлено: ' + missing.join(', ') + ' — opkg install ' +
missing.map(function(m) { return m == 'sms_tool' ? 'sms-tool' : m; }).join(' ')));
if (editing) {
var portOpt = function(cur, filter) {
var sel = E('select', { 'class': 'cbi-input-select' });
var seen = {};
(st.ports || []).filter(function(p) { return filter.test(p.dev); }).concat([ { dev: cur, exists: true } ])
.forEach(function(p) {
if (seen[p.dev])
return;
seen[p.dev] = true;
sel.appendChild(E('option', { 'value': p.dev }, p.dev +
(p.ifnum ? ' — интерфейс ' + p.ifnum : '') + (p.driver ? ', ' + p.driver : '') +
(p.id ? ', ' + p.id : '')));
});
sel.value = cur;
return sel;
};
var atSel = portOpt(st.at_port, /tty|wwan/), wdmSel = portOpt(st.wdm, /cdc-wdm|wwan/);
var ifSel = E('select', { 'class': 'cbi-input-select' }, (st.ifaces || []).map(function(i) {
return E('option', { 'value': i.name }, i.name + (i.proto ? ' (' + i.proto + ')' : ''));
}));
if (!(st.ifaces || []).some(function(i) { return i.name == st.iface; }))
ifSel.appendChild(E('option', { 'value': st.iface }, st.iface));
ifSel.value = st.iface;
children.push(
field('AT-порт', atSel, 'куда идут AT-команды (sms_tool): слот, статус, перезагрузка модема. ' +
'У T99W175 обычно /dev/ttyUSB2 (драйвер option)'),
field('MBIM-устройство', wdmSel, 'через него lpac говорит с чипом eSIM (uqmi -m), обычно /dev/cdc-wdm0'),
field('Интерфейс', ifSel, 'сетевой интерфейс модема: опускается на время операций, сюда пишется APN'),
E('div', { 'class': 'cbi-page-actions' }, [
E('button', { 'class': 'btn cbi-button', 'click': ui.createHandlerFn(this, function() {
this.renderConn(st, false);
}) }, 'Отмена'), ' ',
E('button', { 'class': 'btn cbi-button cbi-button-save', 'click': ui.createHandlerFn(this, function() {
return callConfigSet(atSel.value, wdmSel.value, ifSel.value).then(L.bind(function(r) {
if (r.error)
return ui.addNotification(null, E('p', r.error), 'danger');
return this.reload();
}, this));
}) }, 'Сохранить')
]));
dom.content(this.connBox, children);
return;
}
var ifState = !st.iface_exists ? E('strong', { 'style': RED }, 'нет такого интерфейса')
: st.iface_up ? [ E('strong', { 'style': GREEN }, 'поднят'),
desc(' — ' + [ st.iface_ip, st.iface_device, st.iface_uptime ? 'аптайм ' + duration(st.iface_uptime) : '' ]
.filter(Boolean).join(', ')) ]
: E('strong', { 'style': RED }, 'опущен');
var atCmd = text('', 'AT+CSQ');
atCmd.style.fontFamily = 'monospace';
var atOut = E('pre', { 'style': 'white-space:pre-wrap;max-height:16em;overflow:auto;margin:.5em 0 0;display:none' });
var send = function() {
var c = atCmd.value.trim();
if (!c)
return;
atOut.style.display = '';
atOut.textContent = '> ' + c + '\n…';
return callAt(c).then(function(r) {
atOut.textContent = '> ' + c + ' [' + (r.port || '') + ']\n' + (r.error ? '!! ' + r.error : (r.output || '(пусто)'));
}).catch(function(e) { atOut.textContent = '> ' + c + '\n!! ' + e; });
};
atCmd.addEventListener('keydown', function(ev) {
if (ev.key == 'Enter')
send();
});
children.push(
E('table', { 'class': 'table' }, [
row('AT-порт', portText(st.at_info)),
row('MBIM (lpac)', portText(st.wdm_info)),
row('Интерфейс ' + st.iface, [].concat(ifState, st.iface_proto ? desc(' (' + st.iface_proto + ')') : '')),
row('ModemManager', st.mm_running ? 'работает' : E('strong', { 'style': RED },
st.busy ? 'остановлен на время операции' : 'остановлен')),
row('APN сейчас', [ apn, ' ', this.button('Применить', 'apply', 'apn', function() {
var v = apn.value.trim();
if (!/^[A-Za-z0-9._-]+$/.test(v)) {
ui.addNotification(null, E('p', 'APN: только буквы, цифры, . - _'), 'danger');
return null;
}
return [ v ];
}, 'Записать APN и переподключить интерфейс ' + st.iface + '?'),
E('div', { 'class': 'cbi-value-description' }, 'что записано в ' + st.iface + ' прямо сейчас; пусто — модем подключается ' +
'без APN, и оператор выдаёт свой (какой — «Узнать у сети» в «Задать» ниже). Поменять вручную: впиши и «Применить»') ]),
row('Запомнить для SIM1', [].concat(apnSummary(this.apns.sim1), ' ',
this.apnButton('Задать', 'sim1', 'физическая SIM1', this.apns.sim1, false),
E('div', { 'class': 'cbi-value-description' }, 'нужно, только если у SIM1 и eSIM-профилей разные APN: ' +
'при переключении слота на SIM1 подставится этот, при включении профиля — APN профиля (кнопка «APN» в списке). ' +
'Не задано — APN при смене SIM не меняется'))),
row('AT-консоль', [ E('div', { 'style': 'display:flex;gap:.5em' }, [ atCmd,
E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, send) }, 'Отправить') ]),
atOut ])
]),
E('div', { 'class': 'right' }, E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, function() { this.renderConn(st, true); }) }, 'Изменить порты'))
);
dom.content(this.connBox, children);
},
// ---- SMS -> Telegram ----
renderTg: function() {
return callSmsGet().then(L.bind(function(c) {
var f = {
forward: E('input', { 'type': 'checkbox' }),
del: E('input', { 'type': 'checkbox' }),
token: E('input', { 'type': 'password', 'class': 'cbi-input-password', 'style': 'min-width:22em',
'placeholder': c.has_token ? 'сохранён (бот ' + c.bot_id + ') — пусто, чтобы не менять' : '123456789:AA…' }),
chat: text(c.chat, '123456789')
};
f.forward.checked = !!c.forward;
f.del.checked = !!c.remove;
var save = function() {
return callSmsSet(f.token.value.trim(), f.chat.value.trim(), f.forward.checked, f.del.checked);
};
var saveBtn = E('button', { 'class': 'btn cbi-button cbi-button-save', 'click': ui.createHandlerFn(this, function() {
return save().then(L.bind(function(r) {
if (r.error)
return ui.addNotification(null, E('p', r.error), 'danger');
ui.addNotification(null, E('p', f.forward.checked
? 'Сохранено: SMS проверяются раз в минуту и уходят в Telegram' : 'Сохранено, пересылка выключена'), 'info');
return this.renderTg();
}, this));
}) }, 'Сохранить');
// job buttons save first, so the job sees what is in the form
var jobBtn = L.bind(function(label, cmd, needChat) {
var btn = E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() {
if (!c.has_token && !f.token.value.trim())
return ui.addNotification(null, E('p', 'Сначала впиши токен бота'), 'warning');
if (needChat && !f.chat.value.trim())
return ui.addNotification(null, E('p', 'Нужен chat_id — кнопка «Найти chat_id»'), 'warning');
return save().then(L.bind(function(r) {
if (r.error)
return ui.addNotification(null, E('p', r.error), 'danger');
return this.run(cmd, []);
}, this));
}) }, label);
btn.disabled = this.busy;
this.buttons.push(btn);
return btn;
}, this);
dom.content(this.tgBox, [
E('h3', 'Пересылка SMS в Telegram'),
c.curl ? '' : E('div', { 'class': 'alert-message warning' }, 'Нужен curl: opkg install curl (или apk add curl)'),
field('Пересылать', f.forward, 'раз в минуту (cron) читает SMS из модема через sms_tool — те же, что видит sms-tool-js, — ' +
'и шлёт в чат с пометкой, на какую SIM / eSIM пришло'),
field('Удалять с SIM', f.del, 'после того как Telegram подтвердил получение; не дошло — SMS остаётся и уйдёт в следующий раз'),
field('Токен бота', f.token, [ 'от ', E('a', { 'href': 'https://t.me/BotFather', 'target': '_blank', 'rel': 'noreferrer' }, '@BotFather'),
' → /newbot' ]),
field('chat_id', [ f.chat, ' ', jobBtn('Найти chat_id', 'tg-chats', false) ],
'напиши своему боту /start, потом «Найти chat_id» — он появится в выводе команды ниже'),
E('div', { 'class': 'cbi-page-actions' }, [ jobBtn('Проверить', 'tg-test', true), ' ',
jobBtn('Переслать сейчас', 'sms-forward', true), ' ', saveBtn ]),
(c.log || []).length ? E('div', [ E('h4', 'Последние'), E('pre', { 'style': 'white-space:pre-wrap;max-height:12em;overflow:auto' },
c.log.join('\n')) ]) : ''
]);
}, this)).catch(L.bind(function(e) {
dom.content(this.tgBox, [ E('h3', 'Пересылка SMS в Telegram'), E('p', String(e)) ]);
}, this));
},
// ---- Обслуживание: версия, обновления, история ----
renderMaint: function(st) {
var updState = E('em', 'проверяю обновления…');
callUpdateCheck().then(function(u) {
if (u.error)
return dom.content(updState, '— не удалось проверить: ' + u.error);
var link = function(href, t) { return E('a', { 'href': href, 'target': '_blank', 'rel': 'noreferrer' }, t); };
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 hist = (st.history || []).map(function(h) {
return E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td', 'style': 'white-space:nowrap' }, h.time),
E('td', { 'class': 'td' }, E('code', h.cmd)),
E('td', { 'class': 'td' }, h.rc === 0 ? E('span', { 'style': GREEN }, 'ok')
: typeof h.rc == 'number' ? E('strong', { 'style': RED }, 'ошибка ' + h.rc) : E('em', 'прервано'))
]);
});
dom.content(this.maintBox, [
E('h3', 'Обслуживание'),
E('table', { 'class': 'table' }, [
row('Версия esim-tools', [ st.version || 'неизвестна', ' ', updState ]),
row(this.button('Обновить esim-tools', 'action', 'update', [],
'Скачать свежий esim-tools с git и переустановить скрипт и эту страницу?'),
'скрипт esim и страница; после обновления LuCI может попросить войти заново'),
row(st.auto_update
? this.button('Выключить автообновление', 'negative', 'autoupdate-off')
: this.button('Включить автообновление', 'positive', 'autoupdate-on'),
[ st.auto_update ? E('strong', 'включено') : 'выключено',
': каждый день в 4:30 (время роутера), если на сервере новый коммит — обновить',
st.auto_update_last ? E('div', { 'class': 'cbi-value-description' }, 'последний запуск: ' + st.auto_update_last) : '' ])
]),
E('h4', 'Последние команды'),
hist.length ? E('table', { 'class': 'table' }, hist) : E('p', E('em', 'пока ничего не запускалось'))
]);
},
// ---- job ----
showJob: function(j) {
if (!j.cmd) {
this.jobBox.style.display = 'none';
return;
}
this.jobBox.style.display = '';
var state = j.running ? E('em', 'выполняется…')
: j.rc === 0 ? E('strong', { 'style': GREEN }, 'готово') : E('strong', { 'style': RED }, 'ошибка (код ' + j.rc + ')');
dom.content(this.jobTitle, [ 'Последняя команда: ', E('code', j.cmd), ' — ', state ]);
this.cancelBtn.style.display = j.running ? '' : 'none';
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, a) {
// a: [ a, b, c, flag, d, e, f, g ] - see m_run in rpcd.sh
return callRun(cmd, a[0] || '', a[1] || '', a[2] || '', !!a[3], a[4] || '', a[5] || '', a[6] || '', a[7] || '').then(L.bind(function(r) {
if (r.error) {
ui.addNotification(null, E('p', r.error), 'danger');
return;
}
this.jobBox.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
return this.follow();
}, this));
},
reload: function() {
return Promise.all([ callStatus(), callProfiles() ]).then(L.bind(function(d) {
this.buttons = [];
this.renderAll(d[0], d[1]);
}, this));
},
renderAll: function(st, prof) {
this.apns = prof.apns || {};
this.renderConn(st, false);
this.renderProfiles(prof);
this.renderMaint(st);
this.renderAdd();
this.renderModem();
this.renderTg();
this.setBusy(this.busy);
},
// poll the job until it ends; rpcd may restart under us (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(1500).then(loop);
this.setBusy(false);
if (j.rc !== 0)
ui.addNotification(null, E('p', j.cmd + ': ошибка, см. вывод внизу страницы'), 'danger');
return this.reload().then(function() { return j; });
}, this)).catch(L.bind(function(e) {
if (++errors > 20) {
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 = [];
var box = function() { return E('div', { 'class': 'cbi-section' }); };
this.modemBox = box();
this.profilesBox = box();
this.addBox = box();
this.connBox = box();
this.tgBox = box();
this.maintBox = box();
this.jobTitle = E('h3');
this.jobLog = E('pre', { 'style': 'white-space:pre-wrap;max-height:24em;overflow:auto' });
this.cancelBtn = E('button', { 'class': 'btn cbi-button cbi-button-negative', 'style': 'display:none',
'click': ui.createHandlerFn(this, function() {
if (!window.confirm('Прервать команду? Скрипт остановится и запустит ModemManager обратно.'))
return;
return callCancel().then(function(r) {
if (r.error)
ui.addNotification(null, E('p', r.error), 'warning');
});
}) }, 'Прервать');
this.jobBox = E('div', { 'class': 'cbi-section' }, [ this.jobTitle, this.jobLog, E('div', { 'class': 'right' }, this.cancelBtn) ]);
this.renderAll(data[0], data[1]);
this.showJob(data[2]);
if (data[2].running)
this.follow();
return E([], [ E('h2', 'esim-tools'),
E('div', { 'class': 'cbi-map-descr' }, 'Профили eSIM и слот SIM модема Foxconn T99W175 (скрипт esim). ' +
'Операции с профилями останавливают ModemManager — интернет через модем на это время пропадает.'),
this.modemBox, this.profilesBox, this.addBox, this.connBox, this.tgBox, this.jobBox, this.maintBox ]);
}
});