Added custom pool for chain proxy feauture
This commit is contained in:
parent
909cfdfedb
commit
c4a202d6c6
38
README.md
38
README.md
@ -139,10 +139,11 @@ seed-ноды), — под чертой «служебное». Правило
|
||||
(`fallback` / `url-test`, «Снять закрепление» возвращает автовыбор), «Проверить задержки» —
|
||||
все пункты разом. Сразу через API mihomo, без пересборки; выбор запоминается и переживает
|
||||
перезапуск (`cache.db`), до следующей смены в дашборде;
|
||||
- сервисы: «+ сервис» (есть «как Claude») или нажать на группу сервиса — geosite, домены, IP и
|
||||
«через что»; «через что» можно и перетащить от группы сервиса на MY / FOREIGN / RU / MAIN /
|
||||
DIRECT. «Сохранить и применить» меняет в `common.env` только `SERVICES` и `SVC_*`
|
||||
(`mihomo-kit.sh services`), проверяет, что все профили собираются, и перезапускает текущий.
|
||||
- сервисы и пулы: «+ сервис» (есть «как Claude»), «+ пул» или нажать на группу сервиса / пула;
|
||||
«через что» у сервиса можно и перетащить от его группы на MY / FOREIGN / RU / MAIN / DIRECT /
|
||||
пул. «Сохранить и применить» меняет в `common.env` только `SERVICES`/`SVC_*` и
|
||||
`POOLS`/`POOL_*` (`mihomo-kit.sh services`), проверяет, что все профили собираются, и
|
||||
перезапускает текущий. Это те же ключи, что на «Управлении»: где удобнее, там и правь.
|
||||
|
||||
Без роутера: [tools/graph.html](tools/graph.html) из репозитория открыть в браузере и выбрать
|
||||
или перетащить любой конфиг mihomo. Для живого состояния — адрес API и secret (они в ссылке
|
||||
@ -259,8 +260,24 @@ claude.ai, claude.com, anthropic.com, clau.de, claudeusercontent.com…; `openai
|
||||
в дашборде, выбор запоминается. Если все свои серверы лежат, сервис не открывается, а не
|
||||
уходит в `FOREIGN`. На `whitelist` и телефоне к своим серверам — через `MY-EXIT`, как всегда:
|
||||
клиент → `CLAUDE` → свой сервер → `MY-EXIT` → нода подписки;
|
||||
- `FOREIGN`, `RU`, `DIRECT`, `MAIN` — группа `select`, где это первый пункт, а остальные
|
||||
можно выбрать в дашборде.
|
||||
- `FOREIGN`, `RU`, `DIRECT`, `MAIN` или пул (ниже) — группа `select`, где это первый пункт, а
|
||||
остальные можно выбрать в дашборде.
|
||||
|
||||
Пулы — свои наборы серверов: LuCI → Настройка → «Пулы» или «+ пул» на графе. У пула своя
|
||||
группа (имя заглавными: `de` → `DE`), и сервис можно пустить через неё — тогда выход сервиса
|
||||
задан настройками, а не выбором в дашборде, и одинаков на роутере и телефоне (закрепление в
|
||||
дашборде живёт только в `cache.db` своего устройства). В пул входят:
|
||||
- свои серверы — галками (по имени);
|
||||
- ноды подписок — отметить подписку (`sam_hub` — её ноды без `[MY]`, `sam_hub-my` — только
|
||||
`[MY]`) и задать фильтр по имени ноды: `filter` / `exclude-filter` mihomo, регулярное
|
||||
выражение (`\[WL\]` — метка в своей подписке, `(?i)🇩🇪|\bde\b` — страна в чужой; несколько
|
||||
через `` ` ``; пусто — все ноды). К своим серверам фильтр не применяется.
|
||||
|
||||
Как выбирать: первый живой (`fallback`, по умолчанию), самый быстрый (`url-test`) или вручную
|
||||
(`select`). Встроенные группы (`MY`, `FOREIGN`, `MY-EXIT`, …) от пулов не меняются: пока пулов нет,
|
||||
профили собираются как раньше. Если из пула всё пропало (сервер переименован, подписка
|
||||
выключена), он собирается с `REJECT` — его сервисы закрыты, а не идут мимо, — и сборка пишет
|
||||
предупреждение. Пул, через который идёт сервис, не удалить, пока сервис не переключён.
|
||||
|
||||
В `common.env`:
|
||||
|
||||
@ -269,7 +286,14 @@ SERVICES="claude"
|
||||
SVC_CLAUDE_GEOSITE="anthropic" # через пробел, если списков несколько
|
||||
SVC_CLAUDE_DOMAINS="" # ещё домены (с поддоменами)
|
||||
SVC_CLAUDE_IPS="" # ещё IP / подсети
|
||||
SVC_CLAUDE_VIA=MY # MY | FOREIGN | RU | DIRECT | MAIN
|
||||
SVC_CLAUDE_VIA=MY # MY | FOREIGN | RU | DIRECT | MAIN | пул (DE)
|
||||
|
||||
POOLS="de"
|
||||
POOL_DE_TYPE=fallback # fallback | url-test | select
|
||||
POOL_DE_SERVERS="de-1; nl-2" # свои серверы по имени, через ;
|
||||
POOL_DE_SUBS="sam_hub sam_hub-my" # подписки (<id> без [MY], <id>-my — только [MY])
|
||||
POOL_DE_FILTER='(?i)🇩🇪|\bde\b' # по имени ноды подписки
|
||||
POOL_DE_EXCLUDE='(?i)torrent'
|
||||
```
|
||||
|
||||
Сервисы попадают и в конфиг телефона. Правила по доменам не работают для трафика, который
|
||||
|
||||
191
luci/graph.js
191
luci/graph.js
@ -713,6 +713,7 @@
|
||||
'.mkg-svc input,.mkg-svc select{width:100%;box-sizing:border-box;padding:3px 6px;background:var(--bg);color:var(--fg);' +
|
||||
'border:1px solid var(--rule-b);border-radius:4px;font:inherit}' +
|
||||
'.mkg .n.drop rect{stroke-dasharray:5 3;stroke-width:2.5}.mkg .n.svc rect{stroke-width:2}' +
|
||||
'.mkg .n.pool rect{stroke-width:2;stroke-dasharray:8 2}' +
|
||||
'.mkg .link{fill:none;stroke:var(--now);stroke-width:2;stroke-dasharray:6 4;pointer-events:none}' +
|
||||
'.mkg-info table{border-collapse:collapse}.mkg-info td{padding:1px 10px 1px 0;vertical-align:top}' +
|
||||
'.mkg-info td:first-child{color:var(--mute);white-space:nowrap}' +
|
||||
@ -761,9 +762,11 @@
|
||||
// view(container, act) -> { show(cfg), live(proxies, connections, providers), fit(), destroy() }
|
||||
// act (optional; without it the graph only shows): what the page does through the API,
|
||||
// each returning a promise: select(group, name), unfix(group), delay(group, url) -> {name: ms},
|
||||
// refresh() - poll now; saveServices(list) - the kit's services (SERVICES), then the page
|
||||
// shows the rebuilt profile (only on the router)
|
||||
// show(cfg, meta): meta.services [{name, geosite, domains, ips, via}] - which groups are services
|
||||
// refresh() - poll now; saveServices(services, pools) - the kit's services and pools (SERVICES,
|
||||
// POOLS), then the page shows the rebuilt profile (only on the router)
|
||||
// show(cfg, meta): meta.services [{name, geosite, domains, ips, via}], meta.pools [{name, type,
|
||||
// servers, subs, filter, exclude}] - which groups are services / pools; meta.servers, meta.subs -
|
||||
// own server names and providers a pool can take
|
||||
function view(container, act) {
|
||||
if (!document.getElementById('mkg-style'))
|
||||
document.head.appendChild(el('style', { id: 'mkg-style', text: CSS }));
|
||||
@ -790,6 +793,8 @@
|
||||
var bar = el('div', { 'class': 'mkg-bar' }, [
|
||||
act && act.saveServices ? el('button', { 'class': 'btn cbi-button cbi-button-add',
|
||||
title: 'сайт или приложение своим путём: своя группа и правила', onclick: function() { newService(); } }, [ '+ сервис' ]) : null,
|
||||
act && act.saveServices ? el('button', { 'class': 'btn cbi-button cbi-button-add',
|
||||
title: 'свой набор серверов: свои серверы и ноды подписок по фильтру', onclick: function() { newPool(); } }, [ '+ пул' ]) : null,
|
||||
el('label', {}, [ showLive, 'живое состояние' ]),
|
||||
el('label', { title: 'скрыть члены групп, которые сейчас не выбраны' }, [ onlyNow, 'только выбранное' ]),
|
||||
stat
|
||||
@ -815,7 +820,7 @@
|
||||
|
||||
var m = null, lay = null, L = null, nodeEls = {}, edgeEls = [], selected = null;
|
||||
// the kit's services (show's meta): group name -> service; their editors, kept across repaints
|
||||
var services = [], svcOf = {}, editors = {};
|
||||
var services = [], svcOf = {}, pools = [], poolOf = {}, meta = {}, editors = {};
|
||||
var view = { x: 0, y: 0, k: 1 };
|
||||
var apply = function() { world.setAttribute('transform', 'translate(' + view.x + ',' + view.y + ') scale(' + view.k + ')'); };
|
||||
var maxed = function() { return document.fullscreenElement == root || root.classList.contains('mkg-max'); };
|
||||
@ -1104,6 +1109,8 @@
|
||||
info.appendChild(el('table', {}, rows));
|
||||
if (act && act.saveServices && n.kind == 'group' && svcOf[n.label])
|
||||
info.appendChild(editor(svcOf[n.label]));
|
||||
if (act && act.saveServices && n.kind == 'group' && poolOf[n.label])
|
||||
info.appendChild(poolEditor(poolOf[n.label]));
|
||||
if (act && n.kind == 'group' && L && showLive.checked && L.groups[n.id]) {
|
||||
info.appendChild(chooser(n));
|
||||
pick.list.scrollTop = pick.scroll;
|
||||
@ -1114,11 +1121,36 @@
|
||||
} else
|
||||
pick.input = null;
|
||||
};
|
||||
// --- services (the kit's SERVICES): edit in the panel, "через что" also by dragging
|
||||
var VIA = { 'g:MY': 'MY', 'g:FOREIGN': 'FOREIGN', 'g:RU': 'RU', 'g:MAIN': 'MAIN', 'b:DIRECT': 'DIRECT' };
|
||||
// --- services and pools (the kit's SERVICES, POOLS): edit in the panel; a service's
|
||||
// "через что" also by dragging its group onto MY / FOREIGN / RU / MAIN / DIRECT / a pool
|
||||
var VIA_TEXT = [ [ 'MY', 'свои серверы (первый живой)' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
|
||||
[ 'DIRECT', 'напрямую' ], [ 'MAIN', 'как MAIN' ] ];
|
||||
var viaTargets = function() {
|
||||
var t = { 'g:MY': 'MY', 'g:FOREIGN': 'FOREIGN', 'g:RU': 'RU', 'g:MAIN': 'MAIN', 'b:DIRECT': 'DIRECT' };
|
||||
pools.forEach(function(p) { t['g:' + p.name.toUpperCase()] = p.name.toUpperCase(); });
|
||||
return t;
|
||||
};
|
||||
var TAKEN = /^(boot|boot-auto|ru|foreign|torrent|torrent-sel|my|my-exit|main|push|uplink|tailscale|ts-exit|ovpn-exit|csqtt|direct|reject|reject-drop|pass|compatible|global|bmstu)$/;
|
||||
// a name for a new service or pool group: not a built-in one, not taken by the other kind
|
||||
var nameError = function(name, mine) {
|
||||
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
||||
return 'имя: латиница, цифры, _ и -';
|
||||
var G = name.toUpperCase();
|
||||
if (TAKEN.test(name) || m.groups[G] && !mine[G] || (mine === svcOf ? poolOf : svcOf)[G])
|
||||
return 'группа ' + G + ' уже есть, возьми другое имя';
|
||||
return '';
|
||||
};
|
||||
// both lists go together (mihomo-kit.sh services); the page shows the rebuilt profile
|
||||
var saver = function(say, buttons) {
|
||||
return function(svcList, poolList, what) {
|
||||
buttons.forEach(function(b) { b.disabled = true; });
|
||||
say(what + ': пересборка и перезапуск nikki, около 10–20 секунд…');
|
||||
return act.saveServices(svcList, poolList).catch(function(e) {
|
||||
buttons.forEach(function(b) { b.disabled = false; });
|
||||
say(String(e && e.message || e), true);
|
||||
});
|
||||
};
|
||||
};
|
||||
var editor = function(svc) {
|
||||
var key = svc ? 'svc:' + svc.name : 'new';
|
||||
if (editors[key])
|
||||
@ -1130,7 +1162,8 @@
|
||||
geosite: input(svc.geosite, 'anthropic'),
|
||||
domains: input(svc.domains, 'example.com'),
|
||||
ips: input(svc.ips, '1.2.3.0/24'),
|
||||
via: el('select', {}, VIA_TEXT.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); }))
|
||||
via: el('select', {}, VIA_TEXT.concat(pools.map(function(p) { return [ p.name.toUpperCase(), 'пул ' + p.name.toUpperCase() ]; }))
|
||||
.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); }))
|
||||
};
|
||||
f.via.value = svc.via || 'MY';
|
||||
var msg = el('div', { 'class': 'mkg-msg' });
|
||||
@ -1138,23 +1171,14 @@
|
||||
msg.textContent = t;
|
||||
msg.className = 'mkg-msg' + (err ? ' err' : '');
|
||||
};
|
||||
var buttons = [];
|
||||
var save = function(list, what) {
|
||||
buttons.forEach(function(b) { b.disabled = true; });
|
||||
say(what + ': пересборка и перезапуск nikki, около 10–20 секунд…');
|
||||
return act.saveServices(list).catch(function(e) {
|
||||
buttons.forEach(function(b) { b.disabled = false; });
|
||||
say(String(e && e.message || e), true);
|
||||
});
|
||||
};
|
||||
var buttons = [], save = saver(say, buttons);
|
||||
var saveBtn = el('button', { 'class': 'btn cbi-button cbi-button-apply', onclick: function() {
|
||||
var v = { name: f.name.value.trim().toLowerCase(), geosite: f.geosite.value.trim(), domains: f.domains.value.trim(),
|
||||
ips: f.ips.value.trim(), via: f.via.value };
|
||||
var others = services.filter(function(x) { return !svc.name || x.name != svc.name; });
|
||||
if (!/^[a-z0-9][a-z0-9_-]*$/.test(v.name))
|
||||
return say('имя: латиница, цифры, _ и -', true);
|
||||
if (TAKEN.test(v.name) || m.groups[v.name.toUpperCase()] && !svcOf[v.name.toUpperCase()])
|
||||
return say('группа ' + v.name.toUpperCase() + ' уже есть, возьми другое имя', true);
|
||||
var bad = nameError(v.name, svcOf);
|
||||
if (bad)
|
||||
return say(bad, true);
|
||||
if (others.some(function(x) { return x.name == v.name; }))
|
||||
return say('сервис ' + v.name + ' уже есть', true);
|
||||
if (!v.geosite && !v.domains && !v.ips)
|
||||
@ -1162,7 +1186,7 @@
|
||||
var list = services.map(function(x) { return x.name == svc.name ? v : x; });
|
||||
if (!svc.name)
|
||||
list.push(v);
|
||||
save(list, 'Сохраняю ' + v.name);
|
||||
save(list, pools, 'Сохраняю ' + v.name);
|
||||
} }, [ 'Сохранить и применить' ]);
|
||||
buttons.push(saveBtn);
|
||||
var kids = [
|
||||
@ -1177,10 +1201,10 @@
|
||||
el('label', {}, [ 'geosite (MetaCubeX/meta-rules-dat, через пробел)', f.geosite ]),
|
||||
el('label', {}, [ 'домены (с поддоменами)', f.domains ]),
|
||||
el('label', {}, [ 'IP / подсети', f.ips ]),
|
||||
el('label', {}, [ 'через что (или потяни от группы к MY / FOREIGN / RU / MAIN / DIRECT)', f.via ]),
|
||||
el('label', {}, [ 'через что (или потяни от группы к MY / FOREIGN / RU / MAIN / DIRECT / пулу)', f.via ]),
|
||||
el('div', { 'class': 'acts' }, [ saveBtn, svc.name ? el('button', { 'class': 'btn cbi-button cbi-button-remove', onclick: function() {
|
||||
if (window.confirm('Удалить сервис ' + svc.name + '? Его трафик пойдёт по остальным правилам.'))
|
||||
save(services.filter(function(x) { return x.name != svc.name; }), 'Удаляю ' + svc.name);
|
||||
save(services.filter(function(x) { return x.name != svc.name; }), pools, 'Удаляю ' + svc.name);
|
||||
} }, [ 'Удалить' ]) : null ]),
|
||||
msg
|
||||
];
|
||||
@ -1194,18 +1218,104 @@
|
||||
editors[key] = box;
|
||||
return box;
|
||||
};
|
||||
var newService = function() {
|
||||
// a pool: own servers ticked, subscriptions ticked + filter (meta.servers / meta.subs)
|
||||
var poolEditor = function(pool) {
|
||||
var key = pool ? 'pool:' + pool.name : 'newpool';
|
||||
if (editors[key])
|
||||
return editors[key];
|
||||
pool = pool || { name: '', type: 'fallback', servers: '', subs: '', filter: '', exclude: '' };
|
||||
var input = function(v, ph) { return el('input', { type: 'text', value: v || '', placeholder: ph }); };
|
||||
var ticks = function(all, have) {
|
||||
all = all.slice();
|
||||
have.forEach(function(v) { if (all.indexOf(v) < 0) all.push(v); });
|
||||
return all.map(function(v) {
|
||||
var c = el('input', { type: 'checkbox', style: 'width:auto' });
|
||||
c.checked = have.indexOf(v) >= 0;
|
||||
return { v: v, c: c, el: el('label', { style: 'display:inline-block;margin:0 10px 0 0;color:var(--fg)' },
|
||||
[ c, ' ' + v + (/-my$/.test(v) ? ' [MY]' : '') ]) };
|
||||
});
|
||||
};
|
||||
var f = {
|
||||
name: input(pool.name, 'de'),
|
||||
type: el('select', {}, [ [ 'fallback', 'первый живой' ], [ 'url-test', 'самый быстрый' ], [ 'select', 'вручную' ] ]
|
||||
.map(function(o) { return el('option', { value: o[0] }, [ o[1] ]); })),
|
||||
srv: ticks(meta.servers || [], (pool.servers || '').split(';').map(function(x) { return x.trim(); }).filter(Boolean)),
|
||||
subs: ticks(meta.subs || [], (pool.subs || '').split(/\s+/).filter(Boolean)),
|
||||
filter: input(pool.filter, '\\[WL\\] или (?i)🇩🇪|\\bde\\b'),
|
||||
exclude: input(pool.exclude, '(?i)torrent')
|
||||
};
|
||||
f.type.value = pool.type || 'fallback';
|
||||
var msg = el('div', { 'class': 'mkg-msg' });
|
||||
var say = function(t, err) {
|
||||
msg.textContent = t;
|
||||
msg.className = 'mkg-msg' + (err ? ' err' : '');
|
||||
};
|
||||
var buttons = [], save = saver(say, buttons);
|
||||
var users = function() {
|
||||
return services.filter(function(x) { return x.via == pool.name.toUpperCase(); }).map(function(x) { return x.name; });
|
||||
};
|
||||
var saveBtn = el('button', { 'class': 'btn cbi-button cbi-button-apply', onclick: function() {
|
||||
var v = { name: f.name.value.trim().toLowerCase(), type: f.type.value,
|
||||
servers: f.srv.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join('; '),
|
||||
subs: f.subs.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join(' '),
|
||||
filter: f.filter.value.trim(), exclude: f.exclude.value.trim() };
|
||||
var bad = nameError(v.name, poolOf);
|
||||
if (bad)
|
||||
return say(bad, true);
|
||||
if (pools.some(function(x) { return x.name == v.name && x.name != pool.name; }))
|
||||
return say('пул ' + v.name + ' уже есть', true);
|
||||
if (pool.name && v.name != pool.name && users().length)
|
||||
return say('через пул идут сервисы ' + users().join(', ') + ': сначала переключи их', true);
|
||||
if (!v.servers && !v.subs)
|
||||
return say('отметь свои серверы или подписки', true);
|
||||
var list = pools.map(function(x) { return x.name == pool.name ? v : x; });
|
||||
if (!pool.name)
|
||||
list.push(v);
|
||||
save(services, list, 'Сохраняю пул ' + v.name);
|
||||
} }, [ 'Сохранить и применить' ]);
|
||||
buttons.push(saveBtn);
|
||||
var box = el('div', { 'class': 'mkg-pick mkg-svc' }, [
|
||||
el('div', { 'class': 'mkg-msg', text: pool.name ? 'Пул ' + pool.name + ' (настройки kit): группа ' +
|
||||
pool.name.toUpperCase() + ', через неё могут идти сервисы.' : '' }),
|
||||
pool.name ? null : el('label', {}, [ 'имя (группа заглавными: de → DE)', f.name ]),
|
||||
el('label', {}, [ 'как выбирать', f.type ]),
|
||||
el('label', {}, [ 'свои серверы' ]),
|
||||
el('div', {}, f.srv.length ? f.srv.map(function(o) { return o.el; }) : [ el('em', { text: 'нет' }) ]),
|
||||
el('label', {}, [ 'подписки (их ноды — по фильтру ниже)' ]),
|
||||
el('div', {}, f.subs.length ? f.subs.map(function(o) { return o.el; }) : [ el('em', { text: 'нет' }) ]),
|
||||
el('label', {}, [ 'фильтр по имени ноды подписки (regex; пусто — все)', f.filter ]),
|
||||
el('label', {}, [ 'исключить', f.exclude ]),
|
||||
el('div', { 'class': 'acts' }, [ saveBtn, pool.name ? el('button', { 'class': 'btn cbi-button cbi-button-remove', onclick: function() {
|
||||
if (users().length)
|
||||
return say('через пул идут сервисы ' + users().join(', ') + ': сначала переключи их', true);
|
||||
if (window.confirm('Удалить пул ' + pool.name + '?'))
|
||||
save(services, pools.filter(function(x) { return x.name != pool.name; }), 'Удаляю пул ' + pool.name);
|
||||
} }, [ 'Удалить' ]) : null ]),
|
||||
msg
|
||||
]);
|
||||
editors[key] = box;
|
||||
return box;
|
||||
};
|
||||
// the panel for a new service or pool
|
||||
var newBlock = function(title, hint, box) {
|
||||
select(null);
|
||||
info.style.display = 'block';
|
||||
while (info.firstChild)
|
||||
info.removeChild(info.firstChild);
|
||||
info.appendChild(el('button', { 'class': 'mkg-x', title: 'закрыть', onclick: function() { select(null); } }, [ '✕' ]));
|
||||
info.appendChild(el('h4', { text: 'Новый сервис' }));
|
||||
info.appendChild(el('div', { 'class': 'mkg-msg', text: 'Сайт или приложение, которое всегда идёт своим путём, ' +
|
||||
'что бы ни было выбрано в MAIN. Через свои серверы — первый живой: выходной IP не скачет.' }));
|
||||
info.appendChild(editor(null));
|
||||
info.appendChild(el('h4', { text: title }));
|
||||
info.appendChild(el('div', { 'class': 'mkg-msg', text: hint }));
|
||||
info.appendChild(box);
|
||||
};
|
||||
// dragging from a service group onto MY / FOREIGN / RU / MAIN / DIRECT
|
||||
var newService = function() {
|
||||
newBlock('Новый сервис', 'Сайт или приложение, которое всегда идёт своим путём, что бы ни было выбрано в MAIN. ' +
|
||||
'Через свои серверы — первый живой: выходной IP не скачет; через пул — выход задан настройками.', editor(null));
|
||||
};
|
||||
var newPool = function() {
|
||||
newBlock('Новый пул', 'Свой набор серверов: свои серверы галками и ноды подписок по фильтру. ' +
|
||||
'Сервис можно пустить через пул — тогда выход одинаковый на роутере и телефоне.', poolEditor(null));
|
||||
};
|
||||
// dragging from a service group onto MY / FOREIGN / RU / MAIN / DIRECT / a pool
|
||||
var link = null;
|
||||
var toWorld = function(ev) {
|
||||
var r = stage.getBoundingClientRect();
|
||||
@ -1216,7 +1326,7 @@
|
||||
link = { id: id, x: ev.clientX, y: ev.clientY, moved: false,
|
||||
line: el('path', { 'class': 'link' }), from: { x: b.x + b.w, y: b.y + b.h / 2 } };
|
||||
world.appendChild(link.line);
|
||||
Object.keys(VIA).forEach(function(t) { if (nodeEls[t]) nodeEls[t].classList.add('drop'); });
|
||||
Object.keys(viaTargets()).forEach(function(t) { if (nodeEls[t]) nodeEls[t].classList.add('drop'); });
|
||||
capture(ev);
|
||||
};
|
||||
var moveLink = function(ev) {
|
||||
@ -1228,17 +1338,18 @@
|
||||
var l = link;
|
||||
link = null;
|
||||
world.removeChild(l.line);
|
||||
Object.keys(VIA).forEach(function(t) { if (nodeEls[t]) nodeEls[t].classList.remove('drop'); });
|
||||
var via = viaTargets();
|
||||
Object.keys(via).forEach(function(t) { if (nodeEls[t]) nodeEls[t].classList.remove('drop'); });
|
||||
if (!l.moved)
|
||||
return select(selected == l.id ? null : l.id);
|
||||
var hit = document.elementFromPoint(ev.clientX, ev.clientY);
|
||||
var g = hit && hit.closest && hit.closest('.n'), to = g && g.getAttribute('data-id');
|
||||
select(l.id);
|
||||
var ed = editors['svc:' + svcOf[m.nodes[l.id].label].name];
|
||||
if (to && VIA[to])
|
||||
ed.setVia(VIA[to]);
|
||||
if (to && via[to])
|
||||
ed.setVia(via[to]);
|
||||
else if (to && to != l.id)
|
||||
ed.say('сюда нельзя: только MY, FOREIGN, RU, MAIN или DIRECT', true);
|
||||
ed.say('сюда нельзя: только MY, FOREIGN, RU, MAIN, DIRECT или пул', true);
|
||||
};
|
||||
|
||||
var select = function(id) {
|
||||
@ -1298,7 +1409,9 @@
|
||||
m.list.forEach(function(n) {
|
||||
var b = lay.nodes[n.id];
|
||||
var svc = act && act.saveServices && n.kind == 'group' && svcOf[n.label];
|
||||
var g = el('g', { 'class': 'n ' + n.kind + (/^REJECT/.test(n.data.end || '') ? ' reject' : '') + (svc ? ' svc' : ''),
|
||||
var pool = n.kind == 'group' && poolOf[n.label];
|
||||
var g = el('g', { 'class': 'n ' + n.kind + (/^REJECT/.test(n.data.end || '') ? ' reject' : '') + (svc ? ' svc' : '') +
|
||||
(pool ? ' pool' : ''),
|
||||
'data-id': n.id, transform: 'translate(' + b.x + ',' + b.y + ')' }, [
|
||||
el('rect', { width: b.w, height: b.h, rx: n.kind == 'builtin' ? b.h / 2 : 6 }),
|
||||
el('text', { x: 10, y: n.sub ? 15 : 22, text: n.label }),
|
||||
@ -1400,8 +1513,12 @@
|
||||
|
||||
var proxiesLive = null, providersLive = null;
|
||||
return {
|
||||
show: function(cfg, meta) {
|
||||
services = meta && meta.services || [];
|
||||
show: function(cfg, mt) {
|
||||
meta = mt || {};
|
||||
services = meta.services || [];
|
||||
pools = meta.pools || [];
|
||||
poolOf = {};
|
||||
pools.forEach(function(x) { poolOf[x.name.toUpperCase()] = x; });
|
||||
svcOf = {};
|
||||
services.forEach(function(x) { svcOf[x.name.toUpperCase()] = x; });
|
||||
editors = {};
|
||||
|
||||
@ -5,13 +5,13 @@
|
||||
|
||||
// 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).
|
||||
// and the choice in its groups (method group); the services and pools 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 callServicesSet = rpc.declare({ object: 'mihomo-kit', method: 'services_set', params: [ 'services', 'pools' ], 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: { '': {} } });
|
||||
@ -95,7 +95,8 @@ return view.extend({
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.graph.show(window.mkServers.yamlLoad(g.yaml), { services: g.services || [] });
|
||||
this.graph.show(window.mkServers.yamlLoad(g.yaml),
|
||||
{ services: g.services || [], pools: g.pools || [], servers: g.servers || [], subs: g.subs || [] });
|
||||
} catch (e) {
|
||||
dom.content(this.state, E('p', { 'class': 'alert-message warning' }, 'Не разобрал профиль: ' + e.message));
|
||||
return;
|
||||
@ -134,8 +135,8 @@ return view.extend({
|
||||
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() {
|
||||
saveServices: L.bind(function(list, pools) {
|
||||
return callServicesSet(list, pools).then(checked).then(followJob).then(L.bind(function() {
|
||||
return callGraph(this.profileSelect.value);
|
||||
}, this)).then(L.bind(function(r) {
|
||||
this.show(checked(r));
|
||||
|
||||
@ -559,21 +559,32 @@ return view.extend({
|
||||
};
|
||||
(cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub);
|
||||
|
||||
// services (SERVICES): a site or app with its own group and way, a row each
|
||||
var svcList = E('div'), services = [];
|
||||
// services (SERVICES): a site or app with its own group and way, a row each;
|
||||
// "через": the built-in groups or a pool (pools below, read when the list opens)
|
||||
var svcList = E('div'), services = [], pools = [];
|
||||
var viaOptions = function(sel) {
|
||||
var cur = sel.value || sel.getAttribute('data-via');
|
||||
var names = pools.length ? pools.map(function(p) { return p.name.value.trim().toUpperCase(); })
|
||||
: (cfg.pools || []).map(function(p) { return p.name.toUpperCase(); });
|
||||
dom.content(sel, [
|
||||
[ 'MY', 'свои серверы (первый живой)' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
|
||||
[ 'DIRECT', 'напрямую' ], [ 'MAIN', 'как MAIN' ]
|
||||
].concat(names.filter(Boolean).map(function(n) { return [ n, 'пул ' + n ]; }))
|
||||
.map(function(o) { return E('option', { 'value': o[0] }, o[1]); }));
|
||||
sel.value = cur;
|
||||
};
|
||||
var addService = function(v) {
|
||||
var e = {
|
||||
name: text(v.name || '', 'claude'),
|
||||
via: E('select', { 'class': 'cbi-input-select' }, [
|
||||
[ 'MY', 'свои серверы (первый живой)' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
|
||||
[ 'DIRECT', 'напрямую' ], [ 'MAIN', 'как MAIN' ]
|
||||
].map(function(o) { return E('option', { 'value': o[0] }, o[1]); })),
|
||||
via: E('select', { 'class': 'cbi-input-select', 'data-via': v.via || 'MY' }),
|
||||
geosite: text(v.geosite || '', 'anthropic'),
|
||||
domains: text(v.domains || '', 'example.com'),
|
||||
ips: text(v.ips || '', '1.2.3.0/24')
|
||||
};
|
||||
e.name.style.width = '9em';
|
||||
e.via.value = v.via || 'MY';
|
||||
viaOptions(e.via);
|
||||
e.via.addEventListener('focus', function() { viaOptions(e.via); });
|
||||
e.via.addEventListener('mousedown', function() { viaOptions(e.via); });
|
||||
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
|
||||
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
|
||||
e.name, 'через', e.via,
|
||||
@ -695,6 +706,62 @@ return view.extend({
|
||||
moved++;
|
||||
});
|
||||
|
||||
// pools (POOLS): own servers (by name) and subscription nodes (providers + filter) picked
|
||||
// by hand, a card each; group = the name in upper case, a service goes through it
|
||||
var poolList = E('div');
|
||||
var poolSubs = [];
|
||||
(cfg.subs || []).forEach(function(s) {
|
||||
if (s.id)
|
||||
poolSubs.push([ s.id, s.id ], [ s.id + '-my', s.id + ' — только [MY]' ]);
|
||||
});
|
||||
var boxes = function(all, have, label) {
|
||||
var list = all.map(function(o) { return { v: o[0], t: o[1] }; });
|
||||
have.forEach(function(v) {
|
||||
if (!list.some(function(o) { return o.v == v; }))
|
||||
list.push({ v: v, t: v + ' (нет в настройках)' });
|
||||
});
|
||||
return list.map(function(o) {
|
||||
o.c = check(have.indexOf(o.v) >= 0);
|
||||
o.el = E('label', { 'style': 'margin-right:1em;white-space:nowrap;display:inline-block' }, [ o.c, ' ', o.t ]);
|
||||
return o;
|
||||
});
|
||||
};
|
||||
var addPool = function(v) {
|
||||
var srvNames = servers.map(function(e) { return e.name.value.trim(); }).filter(Boolean);
|
||||
var e = {
|
||||
name: text(v.name || '', 'de'),
|
||||
type: E('select', { 'class': 'cbi-input-select' }, [
|
||||
[ 'fallback', 'первый живой' ], [ 'url-test', 'самый быстрый' ], [ 'select', 'вручную (в дашборде / графе)' ]
|
||||
].map(function(o) { return E('option', { 'value': o[0] }, o[1]); })),
|
||||
srv: boxes(srvNames.map(function(n) { return [ n, n ]; }),
|
||||
(v.servers || '').split(';').map(function(x) { return x.trim(); }).filter(Boolean)),
|
||||
subs: boxes(poolSubs, (v.subs || '').split(/\s+/).filter(Boolean)),
|
||||
filter: text(v.filter || '', '(?i)🇩🇪|\\bde\\b или \\[WL\\]'),
|
||||
exclude: text(v.exclude || '', '(?i)torrent')
|
||||
};
|
||||
e.name.style.width = '9em';
|
||||
e.type.value = v.type || 'fallback';
|
||||
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
|
||||
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
|
||||
e.name, e.type,
|
||||
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'title': 'удалить пул', 'click': function() {
|
||||
poolList.removeChild(el);
|
||||
pools.splice(pools.indexOf(e), 1);
|
||||
} }, '✕')
|
||||
]),
|
||||
field('Свои серверы', e.srv.length ? e.srv.map(function(o) { return o.el; }) : E('em', 'нет своих серверов'),
|
||||
'новые серверы появятся здесь после сохранения'),
|
||||
field('Подписки', e.subs.length ? e.subs.map(function(o) { return o.el; }) : E('em', 'нет подписок'),
|
||||
'их ноды — по фильтру ниже; «только [MY]» — ноды с [MY] в имени'),
|
||||
field('Фильтр', e.filter, 'регулярное выражение по имени ноды подписки (filter в mihomo): ' +
|
||||
'метка своей подписки — \\[WL\\], страна — (?i)🇩🇪|\\bde\\b; пусто — все ноды. К своим серверам не применяется'),
|
||||
field('Исключить', e.exclude, 'ноды подписки с таким именем не берутся')
|
||||
]);
|
||||
pools.push(e);
|
||||
poolList.appendChild(el);
|
||||
};
|
||||
(cfg.pools || []).forEach(addPool);
|
||||
|
||||
// import: share links and/or YAML (or a file) -> cards
|
||||
var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 8, 'spellcheck': 'false',
|
||||
'style': 'width:100%;font-family:monospace',
|
||||
@ -769,6 +836,24 @@ return view.extend({
|
||||
if (!cfg.has_totp && !f.totp_secret.value.trim())
|
||||
errors.push('OpenVPN: нужен TOTP-секрет');
|
||||
}
|
||||
var poolNames = {}, taken = /^(boot|boot-auto|ru|foreign|torrent|torrent-sel|my|my-exit|main|push|uplink|tailscale|ts-exit|ovpn-exit|csqtt|direct|reject|reject-drop|pass|compatible|global|bmstu)$/;
|
||||
var poolData = pools.map(function(e) {
|
||||
return { name: e.name.value.trim().toLowerCase(), type: e.type.value,
|
||||
servers: e.srv.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join('; '),
|
||||
subs: e.subs.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join(' '),
|
||||
filter: e.filter.value.trim(), exclude: e.exclude.value.trim() };
|
||||
});
|
||||
poolData.forEach(function(v) {
|
||||
if (!/^[a-z0-9][a-z0-9_-]*$/.test(v.name))
|
||||
errors.push('Пул «' + v.name + '»: имя — латиница, цифры, _ и -');
|
||||
else if (poolNames[v.name])
|
||||
errors.push('Пул «' + v.name + '» повторяется');
|
||||
else if (taken.test(v.name))
|
||||
errors.push('Пул «' + v.name + '»: такая группа уже есть, возьми другое имя');
|
||||
poolNames[v.name] = true;
|
||||
if (!v.servers && !v.subs)
|
||||
errors.push('Пул «' + v.name + '»: отметь свои серверы или подписки');
|
||||
});
|
||||
var svcNames = {};
|
||||
var svcData = services.map(function(e) {
|
||||
return { name: e.name.value.trim().toLowerCase(), via: e.via.value, geosite: e.geosite.value.trim(),
|
||||
@ -779,7 +864,7 @@ return view.extend({
|
||||
errors.push('Сервис «' + v.name + '»: имя — латиница, цифры, _ и -');
|
||||
else if (svcNames[v.name])
|
||||
errors.push('Сервис «' + v.name + '» повторяется');
|
||||
else if (/^(boot|boot-auto|ru|foreign|torrent|torrent-sel|my|my-exit|main|push|uplink|tailscale|ts-exit|ovpn-exit|csqtt|direct|reject|reject-drop|pass|compatible|global|bmstu)$/.test(v.name))
|
||||
else if (taken.test(v.name) || poolNames[v.name])
|
||||
errors.push('Сервис «' + v.name + '»: такая группа уже есть, возьми другое имя');
|
||||
svcNames[v.name] = true;
|
||||
if (!v.geosite && !v.domains && !v.ips)
|
||||
@ -837,6 +922,7 @@ return view.extend({
|
||||
lite_gomemlimit: f.lite_gomemlimit.value.trim(),
|
||||
hy2: [],
|
||||
services: svcData,
|
||||
pools: poolData,
|
||||
servers_text: srvLines.join('\n')
|
||||
});
|
||||
}, this)).then(L.bind(function(r) {
|
||||
@ -880,6 +966,13 @@ return view.extend({
|
||||
'слишком низкий — ядро постоянно чистит память и грузит процессор'),
|
||||
field('Конфиг для телефона', f.mobile, 'FlClash: QR и ссылка появятся на этой странице после сохранения ' +
|
||||
'(файл раздаётся роутером внутри LAN по ссылке со случайным токеном)'),
|
||||
E('h4', 'Пулы'),
|
||||
E('p', { 'class': 'cbi-value-description' }, 'Свои наборы серверов: свои серверы галками и ноды подписок по фильтру. ' +
|
||||
'У каждого пула своя группа (имя заглавными, например DE); сервис можно пустить через пул — тогда его выход задан ' +
|
||||
'настройками, одинаково на роутере и телефоне. Пустой пул (серверы переименованы, подписка выключена) закрывает ' +
|
||||
'свои сервисы (REJECT), а не пускает их мимо.'),
|
||||
poolList,
|
||||
E('div', [ E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addPool({}); } }, 'Добавить пул') ]),
|
||||
E('h4', 'Сервисы'),
|
||||
E('p', { 'class': 'cbi-value-description' }, 'Сайт или приложение, которое всегда идёт своим путём, что бы ни было выбрано ' +
|
||||
'в MAIN: своя группа в дашборде (имя заглавными, например CLAUDE), правила выше «Своих правил». Через свои серверы — ' +
|
||||
|
||||
156
luci/rpcd.sh
156
luci/rpcd.sh
@ -16,10 +16,11 @@
|
||||
# config_get settings for the form (secrets: only whether they are set)
|
||||
# config_set save the form (via "mihomo-kit.sh configure") as the job
|
||||
# graph {profile}: the built profile's YAML for the graph page (default: the running one)
|
||||
# and the services of the settings
|
||||
# and the services and pools of the settings (+ servers, subs: what a pool can take)
|
||||
# api {path}: GET /proxies, /connections or /providers/proxies of the mihomo API
|
||||
# services_set {services: [{name, geosite, domains, ips, via}]}: replace the services
|
||||
# ("mihomo-kit.sh services") as the job
|
||||
# services_set {services: [{name, geosite, domains, ips, via}], pools: [{name, type, servers,
|
||||
# subs, filter, exclude}]}: replace the services and pools ("mihomo-kit.sh services")
|
||||
# as the job
|
||||
# group {group, action, name, url}: select (pick / pin name), unfix (back to automatic),
|
||||
# delay (test every member against url) - the graph page, through the mihomo API
|
||||
#
|
||||
@ -290,19 +291,8 @@ m_config_get() {
|
||||
json_add_string foreign_domains "${FOREIGN_DOMAINS:-}"
|
||||
json_add_string my_domains "${MY_DOMAINS:-}"
|
||||
json_add_string local_hosts "${LOCAL_HOSTS:-}"
|
||||
# services: SERVICES + SVC_<NAME>_GEOSITE/_DOMAINS/_IPS/_VIA
|
||||
json_add_array services
|
||||
for n in ${SERVICES:-}; do
|
||||
k=SVC_$(echo "$n" | tr 'a-z-' 'A-Z_')
|
||||
json_add_object ""
|
||||
json_add_string name "$n"
|
||||
for v in geosite domains ips via; do
|
||||
eval "val=\${${k}_$(echo "$v" | tr 'a-z' 'A-Z'):-}"
|
||||
json_add_string "$v" "$val"
|
||||
done
|
||||
json_close_object
|
||||
done
|
||||
json_close_array
|
||||
blocks_json services "${SERVICES:-}" SVC geosite domains ips via
|
||||
blocks_json pools "${POOLS:-}" POOL type servers subs filter exclude
|
||||
# own servers: one JSON proxy per line (luci/servers.js); the old hy2 / my_links
|
||||
# below are moved into it by the page on the next save
|
||||
json_add_string servers_text "$(cat "$NIKKI_DIR/my-servers" 2>/dev/null)"
|
||||
@ -341,7 +331,7 @@ m_config_get() {
|
||||
|
||||
# {"data": {boot_links (one per line), subs: [{url, via, hwid}], hwid_*, torrent, push, ru_ips,
|
||||
# foreign_ips, my_ips, ru_domains, foreign_domains, my_domains, local_hosts, my_links (one per line),
|
||||
# services: [{name, geosite, domains, ips, via}],
|
||||
# services: [{name, geosite, domains, ips, via}], pools: [{name, type, servers, subs, filter, exclude}],
|
||||
# servers_text (own servers, one JSON proxy per line: written to /etc/nikki/my-servers),
|
||||
# openvpn, csqtt, ovpn (file text, optional), vpn_username, vpn_password, totp_secret,
|
||||
# tailscale, ts_hostname, ts_domains, lite, lite_gomemlimit, hy2: [{name, server, port, password,
|
||||
@ -444,31 +434,82 @@ m_config_set() {
|
||||
json_select ..
|
||||
fi
|
||||
echo "HY2=$(q "$hy2")"
|
||||
svcs=
|
||||
if json_select services; then
|
||||
json_get_keys keys
|
||||
for k in $keys; do
|
||||
json_select "$k"
|
||||
json_get_var name name ""
|
||||
name=$(printf '%s' "$name" | tr -d ' \t\r\n')
|
||||
if [ -n "$name" ]; then
|
||||
svcs="${svcs:+$svcs }$name"
|
||||
K=SVC_$(echo "$name" | tr 'a-z-' 'A-Z_')
|
||||
for v in geosite domains ips via; do
|
||||
json_get_var val "$v" ""
|
||||
echo "${K}_$(echo "$v" | tr 'a-z' 'A-Z')=$(q "$val")"
|
||||
done
|
||||
fi
|
||||
json_select ..
|
||||
done
|
||||
json_select ..
|
||||
fi
|
||||
echo "SERVICES=$(q "$svcs")"
|
||||
blocks_env services SERVICES SVC geosite domains ips via
|
||||
blocks_env pools POOLS POOL type servers subs filter exclude
|
||||
} > "$env"
|
||||
umask 022
|
||||
start_job mihomo-kit.sh configure "$env"
|
||||
}
|
||||
|
||||
# blocks_json <array> <names> <key prefix> <fields...>: SERVICES / POOLS of the sourced
|
||||
# settings as an array of {name, <field>...} (keys <prefix>_<NAME>_<FIELD>)
|
||||
blocks_json() {
|
||||
_arr=$1 _list=$2 _pre=$3
|
||||
shift 3
|
||||
json_add_array "$_arr"
|
||||
for n in $_list; do
|
||||
k=${_pre}_$(echo "$n" | tr 'a-z-' 'A-Z_')
|
||||
json_add_object ""
|
||||
json_add_string name "$n"
|
||||
for v in "$@"; do
|
||||
eval "val=\${${k}_$(echo "$v" | tr 'a-z' 'A-Z'):-}"
|
||||
json_add_string "$v" "$val"
|
||||
done
|
||||
json_close_object
|
||||
done
|
||||
json_close_array
|
||||
}
|
||||
|
||||
# blocks_env <array> <LIST key> <key prefix> <fields...>: the request's array as env lines
|
||||
# (<prefix>_<NAME>_<FIELD>=..., then LIST=names); no such array in the request: no lines
|
||||
blocks_env() {
|
||||
_arr=$1 _var=$2 _pre=$3
|
||||
shift 3
|
||||
json_get_type _t "$_arr"
|
||||
[ "$_t" = array ] || return 0
|
||||
_names=
|
||||
json_select "$_arr"
|
||||
json_get_keys _keys
|
||||
for _i in $_keys; do
|
||||
json_select "$_i"
|
||||
json_get_var name name ""
|
||||
name=$(printf '%s' "$name" | tr -d ' \t\r\n')
|
||||
if [ -n "$name" ]; then
|
||||
_names="${_names:+$_names }$name"
|
||||
K=${_pre}_$(echo "$name" | tr 'a-z-' 'A-Z_')
|
||||
for v in "$@"; do
|
||||
json_get_var val "$v" ""
|
||||
[ -n "$val" ] && echo "${K}_$(echo "$v" | tr 'a-z' 'A-Z')=$(q "$val")"
|
||||
done
|
||||
fi
|
||||
json_select ..
|
||||
done
|
||||
json_select ..
|
||||
echo "$_var=$(q "$_names")"
|
||||
}
|
||||
|
||||
# what a pool can take: own servers by name, providers of the subscriptions ("<id>", "<id>-my")
|
||||
pool_sources() {
|
||||
# not a pipe: json_add_* must run in this shell
|
||||
json_add_array servers
|
||||
grep -v '^[[:space:]]*$' "$NIKKI_DIR/my-servers" > /tmp/mihomo-kit-srv.$$ 2>/dev/null
|
||||
while IFS= read -r l; do
|
||||
json_add_string "" "$(jsonfilter -s "$l" -e '@.name')"
|
||||
done < /tmp/mihomo-kit-srv.$$
|
||||
rm -f /tmp/mihomo-kit-srv.$$
|
||||
for n in ${HY2:-}; do json_add_string "" "$n"; done
|
||||
json_close_array
|
||||
json_add_array subs
|
||||
SUBS=${SUBS:-} mihomo-kit.sh sub-ids > /tmp/mihomo-kit-ids.$$
|
||||
while read -r id w; do
|
||||
json_add_string "" "$id"
|
||||
json_add_string "" "$id-my"
|
||||
done < /tmp/mihomo-kit-ids.$$
|
||||
rm -f /tmp/mihomo-kit-ids.$$
|
||||
[ -n "${MY_LINKS:-}" ] && json_add_string "" my-links
|
||||
json_close_array
|
||||
}
|
||||
|
||||
m_graph() {
|
||||
json_load "$(cat)"
|
||||
json_get_var want profile ""
|
||||
@ -482,20 +523,11 @@ m_graph() {
|
||||
json_add_boolean active "$(b pidof mihomo)"
|
||||
json_add_string profile "$want"
|
||||
json_add_string yaml "$(cat "$NIKKI_DIR/profiles/$want.yaml")"
|
||||
# the services, as config_get gives them: the graph edits these
|
||||
# the services and pools, as config_get gives them, and what a pool can take: the graph edits these
|
||||
[ -f "$PROFILES_D/common.env" ] && . "$PROFILES_D/common.env"
|
||||
json_add_array services
|
||||
for n in ${SERVICES:-}; do
|
||||
k=SVC_$(echo "$n" | tr 'a-z-' 'A-Z_')
|
||||
json_add_object ""
|
||||
json_add_string name "$n"
|
||||
for v in geosite domains ips via; do
|
||||
eval "val=\${${k}_$(echo "$v" | tr 'a-z' 'A-Z'):-}"
|
||||
json_add_string "$v" "$val"
|
||||
done
|
||||
json_close_object
|
||||
done
|
||||
json_close_array
|
||||
blocks_json services "${SERVICES:-}" SVC geosite domains ips via
|
||||
blocks_json pools "${POOLS:-}" POOL type servers subs filter exclude
|
||||
pool_sources
|
||||
json_dump
|
||||
}
|
||||
|
||||
@ -505,26 +537,8 @@ m_services_set() {
|
||||
umask 077
|
||||
env=$(mktemp /tmp/mihomo-kit-svc.XXXXXX) || reply_error "mktemp failed"
|
||||
{
|
||||
svcs=
|
||||
if json_select services; then
|
||||
json_get_keys keys
|
||||
for k in $keys; do
|
||||
json_select "$k"
|
||||
json_get_var name name ""
|
||||
name=$(printf '%s' "$name" | tr -d ' \t\r\n')
|
||||
if [ -n "$name" ]; then
|
||||
svcs="${svcs:+$svcs }$name"
|
||||
K=SVC_$(echo "$name" | tr 'a-z-' 'A-Z_')
|
||||
for v in geosite domains ips via; do
|
||||
json_get_var val "$v" ""
|
||||
[ -n "$val" ] && echo "${K}_$(echo "$v" | tr 'a-z' 'A-Z')=$(q "$val")"
|
||||
done
|
||||
fi
|
||||
json_select ..
|
||||
done
|
||||
json_select ..
|
||||
fi
|
||||
echo "SERVICES=$(q "$svcs")"
|
||||
blocks_env services SERVICES SVC geosite domains ips via
|
||||
blocks_env pools POOLS POOL type servers subs filter exclude
|
||||
} > "$env"
|
||||
umask 022
|
||||
start_job mihomo-kit.sh services "$env"
|
||||
@ -635,7 +649,7 @@ m_job() {
|
||||
|
||||
case "$1" in
|
||||
list)
|
||||
echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"csqtt_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true},"graph":{"profile":"str"},"api":{"path":"str"},"group":{"group":"str","action":"str","name":"str","url":"str"},"services_set":{"services":[]}}'
|
||||
echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"csqtt_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true},"graph":{"profile":"str"},"api":{"path":"str"},"group":{"group":"str","action":"str","name":"str","url":"str"},"services_set":{"services":[],"pools":[]}}'
|
||||
;;
|
||||
call)
|
||||
case "$2" in
|
||||
|
||||
@ -14,7 +14,7 @@
|
||||
# mihomo-kit.sh setup [--cli] first run: install, then settings in LuCI
|
||||
# (--cli or no LuCI: questions here + build + start)
|
||||
# mihomo-kit.sh configure <env> settings from an env file (LuCI form) -> write, build, start
|
||||
# mihomo-kit.sh services <env> only SERVICES / SVC_* from an env file (graph page) -> build, start
|
||||
# mihomo-kit.sh services <env> only SERVICES / SVC_* / POOLS / POOL_* (graph page) -> build, start
|
||||
# mihomo-kit.sh build [name...] profiles.d/<name>.env -> profiles/<name>.yaml (default: all)
|
||||
# mihomo-kit.sh use <name> switch nikki to profiles/<name>.yaml and restart
|
||||
# mihomo-kit.sh update download the latest kit (KIT_URL) and rebuild
|
||||
@ -92,7 +92,7 @@ set_defaults() {
|
||||
: "${FOREIGN_IPS:=}" "${MY_IPS:=}" "${RU_DOMAINS:=}" "${FOREIGN_DOMAINS:=}" "${MY_DOMAINS:=}"
|
||||
: "${LOCAL_HOSTS:=}" "${MY_LINKS:=}" "${MY_SERVERS_FILE:=$NIKKI_DIR/my-servers}"
|
||||
: "${RULESET_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release}"
|
||||
: "${SERVICES:=}" "${GEOSITE_URL:=https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@meta/geo/geosite}"
|
||||
: "${SERVICES:=}" "${POOLS:=}" "${GEOSITE_URL:=https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@meta/geo/geosite}"
|
||||
: "${BOOT_LINKS:=}"
|
||||
: "${BOOT_SERVER:=}" "${BOOT_PORT:=443}" "${BOOT_UUID:=}" "${BOOT_SNI:=}" "${BOOT_PBK:=}" "${BOOT_SID:=}"
|
||||
: "${TS_HOSTNAME:=mihomo}" "${TS_DOMAINS:=}"
|
||||
@ -125,9 +125,10 @@ compute_tags() {
|
||||
# own servers as links (MY_LINKS): a file on the router, the phone cannot read it
|
||||
[ -n "$MY_LINKS" ] && TAGS="$TAGS my_links "
|
||||
fi
|
||||
# services (services_vars): a group and rules each, geosite rule-providers
|
||||
# pools (pools_vars): a group each; services (services_vars): a group and rules each,
|
||||
# geosite rule-providers
|
||||
[ -n "$POOLS" ] && TAGS="$TAGS pool "
|
||||
[ -n "$SERVICES" ] && TAGS="$TAGS svc "
|
||||
[ -n "$GEOSITE_ITEMS" ] && TAGS="$TAGS geosite "
|
||||
# CSQTT tunnel (star-panel-csqtt): last in MAIN (plain exit through its server)
|
||||
CSQTT_MAIN=""
|
||||
case "$TAGS" in *" csqtt "*) CSQTT_MAIN=", CSQTT" ;; esac
|
||||
@ -374,7 +375,7 @@ hy2_json() {
|
||||
# OWN_LIST '"a", "b"' for group MY. "$" becomes \u0024: the template engine would read
|
||||
# ${...} in a password, JSON and YAML both read the escape.
|
||||
own_servers_vars() {
|
||||
OWN_BODIES="" OWN_LIST=""
|
||||
OWN_BODIES="" OWN_LIST="" OWN_NAMES=""
|
||||
_lines=$(
|
||||
[ -f "$MY_SERVERS_FILE" ] && grep -v '^[[:space:]]*$' "$MY_SERVERS_FILE"
|
||||
for _n in $HY2; do hy2_json "$_n"; done
|
||||
@ -385,6 +386,7 @@ own_servers_vars() {
|
||||
die "$MY_SERVERS_FILE: a line is not {\"name\":...} (save the servers in LuCI again)"
|
||||
_dup=$(printf '%s\n' "$_names" | sort | uniq -d | head -n 1)
|
||||
[ -z "$_dup" ] || die "own servers: the name $_dup repeats"
|
||||
OWN_NAMES=$_names
|
||||
OWN_BODIES=$(printf '%s\n' "$_lines" | sed 's/^{//; s/\$/\\u0024/g')
|
||||
OWN_LIST=$(printf '%s\n' "$_names" | sed 's/\$/\\u0024/g' | awk '{ printf "%s%s", (NR > 1 ? ", " : ""), $0 }')
|
||||
}
|
||||
@ -394,10 +396,89 @@ own_servers_vars() {
|
||||
# _GEOSITE geosite lists of MetaCubeX/meta-rules-dat (GEOSITE_URL), e.g. "anthropic"
|
||||
# _DOMAINS extra domains (with subdomains), _IPS extra IPs / CIDRs
|
||||
# _VIA MY (default): the first alive own server (fallback - the exit IP stays the
|
||||
# same while it lives); FOREIGN | RU | DIRECT | MAIN: a select starting with it
|
||||
# same while it lives); FOREIGN | RU | DIRECT | MAIN or a pool (its group, e.g. DE):
|
||||
# a select starting with it
|
||||
svc_key() { printf 'SVC_%s' "$(printf '%s' "$1" | tr 'a-z-' 'A-Z_')"; }
|
||||
|
||||
# names of the groups and proxies a service group must not take
|
||||
# Pools (POOLS="de wl ..."): own servers and subscription nodes picked by hand, a group each
|
||||
# (the name in upper case) for the services' _VIA. Per pool, keys POOL_<NAME>_*:
|
||||
# _TYPE fallback (default: the first alive one) | url-test (the fastest) | select (by hand)
|
||||
# _SERVERS own servers by name, separated by ";" (names may have spaces)
|
||||
# _SUBS providers: a subscription "<id>" (its nodes without [MY]) and/or "<id>-my" (its
|
||||
# [MY] nodes), "my-links"; space separated
|
||||
# _FILTER, _EXCLUDE mihomo filter / exclude-filter over those providers' nodes (regex; several:
|
||||
# separated by `); they never apply to _SERVERS
|
||||
# A pool left with nothing (servers renamed, subscriptions off) gets REJECT: closed, not elsewhere.
|
||||
pool_key() { printf 'POOL_%s' "$(printf '%s' "$1" | tr 'a-z-' 'A-Z_')"; }
|
||||
|
||||
# pool_vars <name>: POOL_NAME POOL_GROUP POOL_TYPE POOL_PROXIES POOL_USE POOL_FILTER POOL_EXCLUDE
|
||||
# for the pool template; ITEM_TAGS pool_proxies / pool_use / pool_filter / pool_exclude /
|
||||
# pool_select / pool_urltest; POOL_DROPPED: what is gone from the settings
|
||||
pool_vars() {
|
||||
_k=$(pool_key "$1")
|
||||
POOL_NAME=$1
|
||||
POOL_GROUP=$(printf '%s' "$1" | tr 'a-z' 'A-Z')
|
||||
eval "_t=\${${_k}_TYPE:-fallback} _sv=\${${_k}_SERVERS:-} _su=\${${_k}_SUBS:-} _fi=\${${_k}_FILTER:-} _ex=\${${_k}_EXCLUDE:-}"
|
||||
POOL_TYPE=$_t POOL_PROXIES="" POOL_USE="" POOL_DROPPED="" ITEM_TAGS=""
|
||||
_old_ifs=$IFS
|
||||
IFS=';'
|
||||
for _n in $_sv; do
|
||||
_n=$(printf '%s' "$_n" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
|
||||
[ -n "$_n" ] || continue
|
||||
_j="\"$(yq "$_n")\""
|
||||
if printf '%s\n' "$OWN_NAMES" | grep -qxF "$_j"; then
|
||||
POOL_PROXIES="${POOL_PROXIES:+$POOL_PROXIES, }$(printf '%s' "$_j" | sed 's/\$/\\u0024/g')"
|
||||
else
|
||||
POOL_DROPPED="${POOL_DROPPED:+$POOL_DROPPED, }$_n"
|
||||
fi
|
||||
done
|
||||
IFS=$_old_ifs
|
||||
for _p in $_su; do
|
||||
case ", $SUB_LIST, $MY_SUB_LIST, " in
|
||||
*", $_p, "*) POOL_USE="${POOL_USE:+$POOL_USE, }$_p" ;;
|
||||
*) POOL_DROPPED="${POOL_DROPPED:+$POOL_DROPPED, }$_p" ;;
|
||||
esac
|
||||
done
|
||||
if [ -z "$POOL_PROXIES$POOL_USE" ]; then
|
||||
POOL_PROXIES=REJECT
|
||||
POOL_TYPE=select
|
||||
fi
|
||||
POOL_FILTER=$(yq "$_fi") POOL_EXCLUDE=$(yq "$_ex")
|
||||
[ -n "$POOL_PROXIES" ] && ITEM_TAGS="$ITEM_TAGS pool_proxies "
|
||||
[ -n "$POOL_USE" ] && ITEM_TAGS="$ITEM_TAGS pool_use "
|
||||
[ -n "$POOL_USE" ] && [ -n "$_fi" ] && ITEM_TAGS="$ITEM_TAGS pool_filter "
|
||||
[ -n "$POOL_USE" ] && [ -n "$_ex" ] && ITEM_TAGS="$ITEM_TAGS pool_exclude "
|
||||
case "$POOL_TYPE" in
|
||||
select) ITEM_TAGS="$ITEM_TAGS pool_select " ;;
|
||||
url-test) ITEM_TAGS="$ITEM_TAGS pool_urltest " ;;
|
||||
esac
|
||||
export POOL_NAME POOL_GROUP POOL_TYPE POOL_PROXIES POOL_USE POOL_FILTER POOL_EXCLUDE
|
||||
}
|
||||
|
||||
# check POOLS and their keys; POOL_GROUPS " DE WL " for the services' _VIA
|
||||
pools_vars() {
|
||||
POOL_GROUPS=" "
|
||||
set -f
|
||||
for _s in $POOLS; do
|
||||
case "$_s" in [a-z0-9]*) ;; *) die "POOLS: bad name '$_s' (a-z, 0-9, _ -)" ;; esac
|
||||
case "$_s" in *[!a-z0-9_-]*) die "POOLS: bad name '$_s' (a-z, 0-9, _ -)" ;; esac
|
||||
[ "$(printf '%s\n' $POOLS | grep -cx "$_s")" = 1 ] || die "POOLS: $_s repeats"
|
||||
_k=$(pool_key "$_s")
|
||||
eval "_t=\${${_k}_TYPE:-fallback} _sv=\${${_k}_SERVERS:-} _su=\${${_k}_SUBS:-}"
|
||||
case "$_t" in fallback | url-test | select) ;; *) die "${_k}_TYPE: fallback, url-test or select, not '$_t'" ;; esac
|
||||
[ -n "$_sv$_su" ] || die "pool $_s: no SERVERS or SUBS"
|
||||
pool_vars "$_s"
|
||||
case "$SVC_TAKEN $OVPN_GROUP " in *" $POOL_GROUP "*) die "pool $_s: the group $POOL_GROUP already exists, take another name" ;; esac
|
||||
case ", $OWN_LIST, " in *", \"$POOL_GROUP\", "*) die "pool $_s: an own server is named $POOL_GROUP" ;; esac
|
||||
[ -z "$POOL_DROPPED" ] || log "warning: pool $_s: no longer in the settings: $POOL_DROPPED"
|
||||
[ "$POOL_PROXIES" != REJECT ] || log "warning: pool $_s is empty: its services are closed (REJECT)"
|
||||
POOL_GROUPS="$POOL_GROUPS$POOL_GROUP "
|
||||
done
|
||||
set +f
|
||||
ITEM_TAGS=""
|
||||
}
|
||||
|
||||
# names of the groups and proxies a service or pool group must not take
|
||||
SVC_TAKEN=" BOOT BOOT-AUTO RU FOREIGN TORRENT TORRENT-SEL MY MY-EXIT MAIN PUSH UPLINK TAILSCALE TS-EXIT OVPN-EXIT CSQTT DIRECT REJECT REJECT-DROP PASS COMPATIBLE GLOBAL "
|
||||
|
||||
# svc_vars <name>: SVC_NAME SVC_GROUP SVC_GEOSITE SVC_DOMAINS SVC_IPS SVC_VIA SVC_PROXIES
|
||||
@ -427,9 +508,12 @@ services_vars() {
|
||||
case "$_s" in *[!a-z0-9_-]*) die "SERVICES: bad name '$_s' (a-z, 0-9, _ -)" ;; esac
|
||||
[ "$(printf '%s\n' $SERVICES | grep -cx "$_s")" = 1 ] || die "SERVICES: $_s repeats"
|
||||
svc_vars "$_s"
|
||||
case "$SVC_TAKEN $OVPN_GROUP " in *" $SVC_GROUP "*) die "service $_s: the group $SVC_GROUP already exists, take another name" ;; esac
|
||||
case "$SVC_TAKEN $OVPN_GROUP$POOL_GROUPS" in *" $SVC_GROUP "*) die "service $_s: the group $SVC_GROUP already exists, take another name" ;; esac
|
||||
case ", $OWN_LIST, " in *", \"$SVC_GROUP\", "*) die "service $_s: an own server is named $SVC_GROUP" ;; esac
|
||||
case "$SVC_VIA" in MY | FOREIGN | RU | DIRECT | MAIN) ;; *) die "$(svc_key "$_s")_VIA: MY, FOREIGN, RU, DIRECT or MAIN, not '$SVC_VIA'" ;; esac
|
||||
case " MY FOREIGN RU DIRECT MAIN$POOL_GROUPS" in
|
||||
*" $SVC_VIA "*) ;;
|
||||
*) die "$(svc_key "$_s")_VIA: MY, FOREIGN, RU, DIRECT, MAIN or a pool${POOL_GROUPS% }, not '$SVC_VIA'" ;;
|
||||
esac
|
||||
[ -n "$SVC_GEOSITE$SVC_DOMAINS$SVC_IPS" ] || die "service $_s: no GEOSITE, DOMAINS or IPS"
|
||||
for _g in $SVC_GEOSITE; do
|
||||
case "$_g" in *[!a-z0-9._@!-]*) die "service $_s: bad geosite name '$_g'" ;; esac
|
||||
@ -522,6 +606,12 @@ render_section() {
|
||||
seed_vars "$_it"
|
||||
render_part "$f"
|
||||
done
|
||||
elif [ "$EACH" = 1 ] && [ "$_mod" = pool ]; then
|
||||
for _it in $POOLS; do
|
||||
pool_vars "$_it"
|
||||
render_part "$f"
|
||||
done
|
||||
ITEM_TAGS=""
|
||||
elif [ "$EACH" = 1 ] && [ "$_mod" = svc ]; then
|
||||
for _it in $SERVICES; do
|
||||
svc_vars "$_it"
|
||||
@ -606,10 +696,13 @@ render() {
|
||||
boot_seeds
|
||||
check_vars
|
||||
own_servers_vars
|
||||
services_vars
|
||||
compute_tags
|
||||
for _l in RU_IPS FOREIGN_IPS MY_IPS; do eval "$_l=\$(norm_list ip \"\$$_l\")"; done
|
||||
for _l in RU_DOMAINS FOREIGN_DOMAINS MY_DOMAINS; do eval "$_l=\$(norm_list dom \"\$$_l\")"; done
|
||||
# after compute_tags: pools use SUB_LIST / MY_SUB_LIST
|
||||
pools_vars
|
||||
services_vars
|
||||
[ -n "$GEOSITE_ITEMS" ] && TAGS="$TAGS geosite "
|
||||
local_hosts_vars
|
||||
export TARGET LOCATION RULESET_URL BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI \
|
||||
BOOT_PBK BOOT_SID TS_HOSTNAME TS_DOMAINS OVPN_PROVIDER OVPN_GROUP OVPN_SERVER_HOST \
|
||||
@ -1645,11 +1738,11 @@ common_other_keys() {
|
||||
# common.env (+ bmstu.env) from the variables the wizard / configure set;
|
||||
# per-subscription values come as SUB<index>_PROXY/HWID (index in SUBS).
|
||||
# Keys only the LuCI form sets (own hysteria2 servers HY2, HY2_<NAME>_*, MY_IPS,
|
||||
# MY_DOMAINS, LOCAL_HOSTS, MY_LINKS, LITE, check URLs, SERVICES + SVC_<NAME>_*) are rewritten only with FORM=1; the terminal wizard keeps them.
|
||||
# MY_DOMAINS, LOCAL_HOSTS, MY_LINKS, LITE, check URLs, SERVICES + SVC_<NAME>_*, POOLS + POOL_<NAME>_*) are rewritten only with FORM=1; the terminal wizard keeps them.
|
||||
write_config() {
|
||||
umask 077
|
||||
_any_hwid=0
|
||||
[ "${FORM:-0}" = 1 ] && COMMON_KEYS="$COMMON_KEYS|HY2|HY2_[A-Z0-9_]+|MY_IPS|MY_DOMAINS|LOCAL_HOSTS|MY_LINKS|LITE|LITE_GOMEMLIMIT|OVPN_CHECK_URL|TS_CHECK_URL|MOBILE|SERVICES|SVC_[A-Z0-9_]+"
|
||||
[ "${FORM:-0}" = 1 ] && COMMON_KEYS="$COMMON_KEYS|HY2|HY2_[A-Z0-9_]+|MY_IPS|MY_DOMAINS|LOCAL_HOSTS|MY_LINKS|LITE|LITE_GOMEMLIMIT|OVPN_CHECK_URL|TS_CHECK_URL|MOBILE|SERVICES|SVC_[A-Z0-9_]+|POOLS|POOL_[A-Z0-9_]+"
|
||||
_others=$(common_other_keys)
|
||||
sub_pairs
|
||||
{
|
||||
@ -1694,6 +1787,14 @@ write_config() {
|
||||
[ -n "${MY_DOMAINS:-}" ] && echo "MY_DOMAINS=$(q "$MY_DOMAINS")"
|
||||
[ -n "${LOCAL_HOSTS:-}" ] && echo "LOCAL_HOSTS=$(q "$LOCAL_HOSTS")"
|
||||
[ -n "${MY_LINKS:-}" ] && echo "MY_LINKS=$(q "$MY_LINKS")"
|
||||
[ -n "${POOLS:-}" ] && echo "POOLS=$(q "$POOLS")"
|
||||
for _s in ${POOLS:-}; do
|
||||
_k=$(pool_key "$_s")
|
||||
for v in TYPE SERVERS SUBS FILTER EXCLUDE; do
|
||||
eval "_v=\${${_k}_$v:-}"
|
||||
[ -n "$_v" ] && echo "${_k}_$v=$(q "$_v")"
|
||||
done
|
||||
done
|
||||
[ -n "${SERVICES:-}" ] && echo "SERVICES=$(q "$SERVICES")"
|
||||
for _s in ${SERVICES:-}; do
|
||||
_k=$(svc_key "$_s")
|
||||
@ -1794,16 +1895,21 @@ cmd_apply() {
|
||||
true
|
||||
}
|
||||
|
||||
# services <env>: SERVICES and SVC_<NAME>_* of <env> (the graph page) replace those of
|
||||
# common.env; every profile must still render, else nothing changes; then build and apply
|
||||
# services <env>: the blocks <env> has (the graph page) replace those of common.env - with
|
||||
# SERVICES= the services (SERVICES, SVC_<NAME>_*), with POOLS= the pools (POOLS, POOL_<NAME>_*);
|
||||
# every profile must still render, else nothing changes; then build and apply
|
||||
cmd_services() {
|
||||
[ -f "${1:-}" ] || die "usage: services <env>"
|
||||
_c=$PROFILES_D/common.env
|
||||
[ -f "$_c" ] || die "no $_c: save the settings first"
|
||||
_keys=""
|
||||
grep -q '^SERVICES=' "$1" && _keys="SERVICES|SVC_[A-Z0-9_]+"
|
||||
grep -q '^POOLS=' "$1" && _keys="${_keys:+$_keys|}POOLS|POOL_[A-Z0-9_]+"
|
||||
[ -n "$_keys" ] || die "services: $1 has neither SERVICES= nor POOLS="
|
||||
umask 077
|
||||
{
|
||||
grep -vE '^(SERVICES|SVC_[A-Z0-9_]+)=' "$_c"
|
||||
grep -E '^(SERVICES|SVC_[A-Z0-9_]+)=' "$1"
|
||||
grep -vE "^($_keys)=" "$_c"
|
||||
grep -E "^($_keys)=" "$1"
|
||||
} > "$_c.new"
|
||||
rm -f "$1"
|
||||
umask 022
|
||||
@ -1817,7 +1923,7 @@ cmd_services() {
|
||||
fi
|
||||
done
|
||||
mv "$_c.new" "$_c"
|
||||
log "saved services: $(sed -n 's/^SERVICES=//p' "$_c" | tr -d "'")"
|
||||
log "saved services: $(sed -n 's/^SERVICES=//p' "$_c" | tr -d "'"); pools: $(sed -n 's/^POOLS=//p' "$_c" | tr -d "'")"
|
||||
cmd_apply
|
||||
}
|
||||
|
||||
|
||||
@ -60,7 +60,18 @@ RU_IPS="194.190.191.112/32"
|
||||
#SVC_CLAUDE_GEOSITE="anthropic"
|
||||
#SVC_CLAUDE_DOMAINS=""
|
||||
#SVC_CLAUDE_IPS=""
|
||||
#SVC_CLAUDE_VIA=MY
|
||||
#SVC_CLAUDE_VIA=MY # or a pool's group: DE
|
||||
|
||||
# pools: own servers and subscription nodes picked by hand, a group each (the name in upper
|
||||
# case) for the services' VIA. TYPE: fallback (default) | url-test | select; SERVERS: own
|
||||
# servers by name, ";" between; SUBS: "<id>" (nodes without [MY]) / "<id>-my" (only [MY]);
|
||||
# FILTER / EXCLUDE: mihomo regex over the subscription nodes' names
|
||||
#POOLS="de"
|
||||
#POOL_DE_TYPE=fallback
|
||||
#POOL_DE_SERVERS="de-1; nl-2"
|
||||
#POOL_DE_SUBS="sam_hub sam_hub-my"
|
||||
#POOL_DE_FILTER='(?i)🇩🇪|\bde\b'
|
||||
#POOL_DE_EXCLUDE='(?i)torrent'
|
||||
|
||||
# OpenVPN (BMSTU), needs /etc/nikki/bmstu.env and bmstu-otp.sh
|
||||
OPENVPN=0
|
||||
|
||||
14
templates/groups/44-pool.each.yaml
Normal file
14
templates/groups/44-pool.each.yaml
Normal file
@ -0,0 +1,14 @@
|
||||
# pool ${POOL_NAME} (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
|
||||
# filter / exclude-filter apply to the subscriptions' nodes only
|
||||
- name: ${POOL_GROUP}
|
||||
type: ${POOL_TYPE}
|
||||
proxies: [${POOL_PROXIES}] #@pool_proxies
|
||||
use: [${POOL_USE}] #@pool_use
|
||||
filter: "${POOL_FILTER}" #@pool_filter
|
||||
exclude-filter: "${POOL_EXCLUDE}" #@pool_exclude
|
||||
url: "https://www.gstatic.com/generate_204" #@!pool_select
|
||||
interval: 300 #@!pool_select,!lite
|
||||
interval: 600 #@!pool_select,lite
|
||||
tolerance: 50 #@pool_urltest
|
||||
lazy: false #@!pool_select,!lite
|
||||
lazy: true #@!pool_select,lite
|
||||
@ -261,6 +261,25 @@ proxy-groups:
|
||||
max-failed-times: 5
|
||||
lazy: false
|
||||
|
||||
# pool de (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
|
||||
# filter / exclude-filter apply to the subscriptions' nodes only
|
||||
- name: DE
|
||||
type: url-test
|
||||
proxies: ["🇩🇪 de 1", "hy-own"]
|
||||
use: [example, example2-my]
|
||||
filter: "(?i)🇩🇪|\\bde\\b"
|
||||
exclude-filter: "(?i)tor"
|
||||
url: "https://www.gstatic.com/generate_204"
|
||||
interval: 300
|
||||
tolerance: 50
|
||||
lazy: false
|
||||
|
||||
# pool gone (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
|
||||
# filter / exclude-filter apply to the subscriptions' nodes only
|
||||
- name: GONE
|
||||
type: select
|
||||
proxies: [REJECT]
|
||||
|
||||
# own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of
|
||||
# the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed
|
||||
- name: MY
|
||||
@ -284,16 +303,9 @@ proxy-groups:
|
||||
lazy: false
|
||||
|
||||
# service claude (SERVICES, SVC_*): its own way, whatever MAIN is
|
||||
# through own servers: the first alive one, not the fastest - the exit IP stays the
|
||||
# same while the server lives (a site that checks the region sees one country);
|
||||
# pick another in the dashboard, the choice is remembered
|
||||
- name: CLAUDE
|
||||
type: fallback
|
||||
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own"]
|
||||
use: [example-my, example2-my, my-links]
|
||||
url: "https://www.gstatic.com/generate_204"
|
||||
interval: 300
|
||||
lazy: false
|
||||
type: select
|
||||
proxies: [DE, MY, FOREIGN, RU, DIRECT]
|
||||
|
||||
# service chat (SERVICES, SVC_*): its own way, whatever MAIN is
|
||||
- name: CHAT
|
||||
|
||||
8
tests/fixtures/router-whitelist-ts-my.env
vendored
8
tests/fixtures/router-whitelist-ts-my.env
vendored
@ -5,7 +5,15 @@ MY_LINKS='vless://00000000-0000-0000-0000-000000000001@x.example.com:443?securit
|
||||
MY_SERVERS_FILE=tests/fixtures/own.servers
|
||||
SERVICES="claude chat"
|
||||
SVC_CLAUDE_GEOSITE=anthropic
|
||||
SVC_CLAUDE_VIA=DE
|
||||
SVC_CLAUDE_DOMAINS="*.claude.example"
|
||||
SVC_CHAT_GEOSITE="openai anthropic"
|
||||
SVC_CHAT_IPS="1.2.3.4"
|
||||
SVC_CHAT_VIA=FOREIGN
|
||||
POOLS="de gone"
|
||||
POOL_DE_TYPE=url-test
|
||||
POOL_DE_SERVERS='🇩🇪 de 1; hy-own; renamed-server'
|
||||
POOL_DE_SUBS="example example2-my no-such"
|
||||
POOL_DE_FILTER='(?i)🇩🇪|\bde\b'
|
||||
POOL_DE_EXCLUDE='(?i)tor'
|
||||
POOL_GONE_SERVERS='renamed-server'
|
||||
|
||||
Loading…
Reference in New Issue
Block a user