release 1.6.1: client Telegram reminders, term from first connection
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,7 @@
|
|||||||
|
## 1.6.1 — 2026-11-21
|
||||||
|
- **Напоминания клиенту в Telegram.** На личной странице клиента кнопка «Получать напоминания о сроке в Telegram» открывает бота панели; бот привязывает чат к клиенту (`/stop` отвязывает). За 3 дня, за день и в день окончания срока сообщение получает и клиент, и админ. Нужен бот в «Настройках» (токен и chat id админа), как и раньше.
|
||||||
|
- **Срок с первого подключения.** В окне «Правка» клиента поле «Дней с первого подключения»: срок начнётся, когда клиент впервые подключится, админу придёт уведомление. На личной странице видно «N дн. с первого подключения».
|
||||||
|
|
||||||
## 1.6.0 — 2026-11-21
|
## 1.6.0 — 2026-11-21
|
||||||
- **Личная страница клиента.** В окне «Подключение» у каждого клиента есть ссылка на его страницу: отправьте её человеку. Там статус (в сети или нет), срок подписки с остатком дней, трафик за месяц, кнопки «Скачать приложение» и «Добавить профиль» для Android, вариант для iPhone, QR для другого устройства и файл .conf. Вход в панель не нужен; ссылка защищена личным токеном клиента, чужой токен даёт 403.
|
- **Личная страница клиента.** В окне «Подключение» у каждого клиента есть ссылка на его страницу: отправьте её человеку. Там статус (в сети или нет), срок подписки с остатком дней, трафик за месяц, кнопки «Скачать приложение» и «Добавить профиль» для Android, вариант для iPhone, QR для другого устройства и файл .conf. Вход в панель не нужен; ссылка защищена личным токеном клиента, чужой токен даёт 403.
|
||||||
|
|
||||||
|
|||||||
106
app.py
106
app.py
@@ -475,6 +475,62 @@ def tg_send(text):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def tg_client(cid, text):
|
||||||
|
"""Message to the client's own Telegram (bound via /start <code> in the panel bot)."""
|
||||||
|
chat = load_settings().get("client_tg", {}).get(cid)
|
||||||
|
if chat:
|
||||||
|
tg_api("sendMessage", {"chat_id": chat, "text": text, "parse_mode": "HTML"})
|
||||||
|
|
||||||
|
|
||||||
|
def client_start_code(cid):
|
||||||
|
return phone_sub_token(cid)[:24]
|
||||||
|
|
||||||
|
|
||||||
|
def tg_bot_username():
|
||||||
|
"""Bot @username for t.me links; cached in settings after the first getMe."""
|
||||||
|
s = load_settings()
|
||||||
|
if not s.get("tg_bot_token"):
|
||||||
|
return ""
|
||||||
|
if not s.get("tg_bot_username"):
|
||||||
|
r = tg_api("getMe", {}) or {}
|
||||||
|
name = (r.get("result") or {}).get("username", "")
|
||||||
|
if name:
|
||||||
|
s["tg_bot_username"] = name
|
||||||
|
save_settings(s)
|
||||||
|
return name
|
||||||
|
return s["tg_bot_username"]
|
||||||
|
|
||||||
|
|
||||||
|
def tg_bind_client(chat, text):
|
||||||
|
"""/start <code> or /stop from any chat: bind or unbind the client's reminders. True if handled."""
|
||||||
|
toks = text.split()
|
||||||
|
cmd = toks[0].split("@")[0].lower() if toks else ""
|
||||||
|
s = load_settings()
|
||||||
|
binds = s.setdefault("client_tg", {})
|
||||||
|
if cmd == "/stop":
|
||||||
|
gone = [c for c, ch in binds.items() if str(ch) == chat]
|
||||||
|
if not gone:
|
||||||
|
return False
|
||||||
|
for c in gone:
|
||||||
|
binds.pop(c, None)
|
||||||
|
save_settings(s)
|
||||||
|
tg_api("sendMessage", {"chat_id": chat, "text": "Напоминания отключены."})
|
||||||
|
return True
|
||||||
|
if cmd != "/start" or len(toks) < 2:
|
||||||
|
return False
|
||||||
|
cid = next((c.get("client_id") for c in get_clients() if client_start_code(c.get("client_id", "")) == toks[1]), None)
|
||||||
|
if not cid:
|
||||||
|
return False
|
||||||
|
binds[cid] = int(chat) if chat.lstrip("-").isdigit() else chat
|
||||||
|
save_settings(s)
|
||||||
|
exp = s.get("subscriptions", {}).get(cid, {}).get("expiry", "")
|
||||||
|
tg_api("sendMessage", {"chat_id": chat, "parse_mode": "HTML", "text":
|
||||||
|
f"Готово: напомню о сроке подписки <b>{html_lib.escape(cid)}</b>"
|
||||||
|
+ (f" (до {exp})" if exp else "") + ". Отключить: /stop"})
|
||||||
|
tg_send(f"🔔 <b>{html_lib.escape(cid)}</b> подключил напоминания в Telegram")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def notify_on(cid):
|
def notify_on(cid):
|
||||||
return load_settings().get("client_notify", {}).get(cid, True)
|
return load_settings().get("client_notify", {}).get(cid, True)
|
||||||
|
|
||||||
@@ -667,7 +723,10 @@ def telegram_bot():
|
|||||||
m = upd.get("message") or upd.get("channel_post")
|
m = upd.get("message") or upd.get("channel_post")
|
||||||
if not m:
|
if not m:
|
||||||
continue
|
continue
|
||||||
if str(m.get("chat", {}).get("id", "")) != chat:
|
_from = str(m.get("chat", {}).get("id", ""))
|
||||||
|
if (m.get("text") or "").strip().startswith(("/start ", "/stop")) and tg_bind_client(_from, m["text"].strip()):
|
||||||
|
continue
|
||||||
|
if _from != chat:
|
||||||
continue
|
continue
|
||||||
text = (m.get("text") or "").strip()
|
text = (m.get("text") or "").strip()
|
||||||
if not text:
|
if not text:
|
||||||
@@ -919,6 +978,19 @@ def check_expiry():
|
|||||||
today = datetime.now().date()
|
today = datetime.now().date()
|
||||||
changed = False
|
changed = False
|
||||||
|
|
||||||
|
# ponytail: "online" = handshake on the primary server only; secondaries start it on the next primary handshake
|
||||||
|
if any(i.get("hold_days") and not i.get("expiry") for i in subs.values()):
|
||||||
|
peers = get_wg_peers()
|
||||||
|
pub = {c.get("client_id"): c.get("public_key") for c in get_clients()}
|
||||||
|
for client_id, info in subs.items():
|
||||||
|
if info.get("hold_days") and not info.get("expiry"):
|
||||||
|
p = peers.get(pub.get(client_id) or "", {})
|
||||||
|
if is_peer_online(p.get("latest handshake", "")):
|
||||||
|
info["expiry"] = (today + timedelta(days=int(info.pop("hold_days")))).isoformat()
|
||||||
|
changed = True
|
||||||
|
tg_send(f"▶️ <b>{client_id}</b> — первое подключение, срок пошёл: до {info['expiry']}")
|
||||||
|
tg_client(client_id, f"Подписка активирована: до {info['expiry']}.")
|
||||||
|
|
||||||
for client_id, info in list(subs.items()):
|
for client_id, info in list(subs.items()):
|
||||||
if not info.get("expiry"):
|
if not info.get("expiry"):
|
||||||
continue
|
continue
|
||||||
@@ -934,14 +1006,17 @@ def check_expiry():
|
|||||||
changed = True
|
changed = True
|
||||||
kick_client_by_id(client_id)
|
kick_client_by_id(client_id)
|
||||||
tg_send(f"⛔ <b>{client_id}</b> — подписка истекла! Клиент заблокирован.")
|
tg_send(f"⛔ <b>{client_id}</b> — подписка истекла! Клиент заблокирован.")
|
||||||
|
tg_client(client_id, "Срок подписки закончился, VPN отключён. Для продления напишите администратору.")
|
||||||
elif days_left == 3 and not info.get("warn3"):
|
elif days_left == 3 and not info.get("warn3"):
|
||||||
info["warn3"] = True
|
info["warn3"] = True
|
||||||
changed = True
|
changed = True
|
||||||
tg_send(f"⚠️ <b>{client_id}</b> — подписка истекает через 3 дня ({info['expiry']})")
|
tg_send(f"⚠️ <b>{client_id}</b> — подписка истекает через 3 дня ({info['expiry']})")
|
||||||
|
tg_client(client_id, f"Подписка заканчивается через 3 дня ({info['expiry']}).")
|
||||||
elif days_left == 1 and not info.get("warn1"):
|
elif days_left == 1 and not info.get("warn1"):
|
||||||
info["warn1"] = True
|
info["warn1"] = True
|
||||||
changed = True
|
changed = True
|
||||||
tg_send(f"⚠️ <b>{client_id}</b> — подписка истекает ЗАВТРА ({info['expiry']})")
|
tg_send(f"⚠️ <b>{client_id}</b> — подписка истекает ЗАВТРА ({info['expiry']})")
|
||||||
|
tg_client(client_id, f"Подписка заканчивается завтра ({info['expiry']}).")
|
||||||
|
|
||||||
if changed:
|
if changed:
|
||||||
save_settings(s)
|
save_settings(s)
|
||||||
@@ -1308,6 +1383,15 @@ def personal_page(cid):
|
|||||||
term_cls = "bad" if left <= 0 else ("warn" if left <= 3 else "ok")
|
term_cls = "bad" if left <= 0 else ("warn" if left <= 3 else "ok")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
|
if sub.get("hold_days") and not sub.get("expiry"):
|
||||||
|
term = tr(f"{sub['hold_days']} дн. с первого подключения", f"{sub['hold_days']} days from the first connection")
|
||||||
|
bot = tg_bot_username()
|
||||||
|
tg_btn = ""
|
||||||
|
if bot:
|
||||||
|
bound = cid in s.get("client_tg", {})
|
||||||
|
tg_btn = (f'<a class="b g" href="https://t.me/{e(bot)}?start={client_start_code(cid)}" target="_blank" rel="noopener">'
|
||||||
|
+ (tr("Напоминания в Telegram включены", "Telegram reminders are on") if bound else tr("Получать напоминания о сроке в Telegram", "Get term reminders in Telegram"))
|
||||||
|
+ '</a>')
|
||||||
u = _traffic_load().get("usage", {}).get(cid)
|
u = _traffic_load().get("usage", {}).get(cid)
|
||||||
traffic = f'↓ {_fmt_bytes(u[1])} · ↑ {_fmt_bytes(u[0])}' if u else "—"
|
traffic = f'↓ {_fmt_bytes(u[1])} · ↑ {_fmt_bytes(u[0])}' if u else "—"
|
||||||
conf, link = build_phone_config(cid, "android")
|
conf, link = build_phone_config(cid, "android")
|
||||||
@@ -1339,7 +1423,7 @@ img.qr{{display:block;width:100%;max-width:280px;margin:6px auto;background:#fff
|
|||||||
<div class="c"><h1>{e(c.get("client_name") or cid)}</h1>
|
<div class="c"><h1>{e(c.get("client_name") or cid)}</h1>
|
||||||
<span class="st {'ok' if online else 'off'}">{tr("в сети","online") if online else tr("не в сети","offline")}</span>
|
<span class="st {'ok' if online else 'off'}">{tr("в сети","online") if online else tr("не в сети","offline")}</span>
|
||||||
<div style="margin-top:12px"><div class="row"><span>{tr("Срок","Term")}</span><span class="{term_cls}">{term}</span></div>
|
<div style="margin-top:12px"><div class="row"><span>{tr("Срок","Term")}</span><span class="{term_cls}">{term}</span></div>
|
||||||
<div class="row"><span>{tr("Трафик за месяц","Traffic this month")}</span><span>{traffic}</span></div></div></div>
|
<div class="row"><span>{tr("Трафик за месяц","Traffic this month")}</span><span>{traffic}</span></div></div>{tg_btn}</div>
|
||||||
<div class="c"><h2>Android</h2>
|
<div class="c"><h2>Android</h2>
|
||||||
<a class="b" href="{e(apk)}">{tr("1. Скачать PCA Phobos VPN","1. Download PCA Phobos VPN")}</a>
|
<a class="b" href="{e(apk)}">{tr("1. Скачать PCA Phobos VPN","1. Download PCA Phobos VPN")}</a>
|
||||||
<a class="b" href="{e(link)}">{tr("2. Добавить профиль в приложение","2. Add the profile to the app")}</a>
|
<a class="b" href="{e(link)}">{tr("2. Добавить профиль в приложение","2. Add the profile to the app")}</a>
|
||||||
@@ -3593,6 +3677,21 @@ def clients_page():
|
|||||||
save_settings(s)
|
save_settings(s)
|
||||||
msg = f'<div class="alert alert-ok">Срок для {client_id} обновлён</div>'
|
msg = f'<div class="alert alert-ok">Срок для {client_id} обновлён</div>'
|
||||||
|
|
||||||
|
elif action == "set_hold":
|
||||||
|
client_id = request.form.get("client_id", "").strip()
|
||||||
|
d = request.form.get("hold_days", "").strip()
|
||||||
|
if client_id:
|
||||||
|
sub = subs.setdefault(client_id, {})
|
||||||
|
if d.isdigit() and int(d) > 0:
|
||||||
|
sub["hold_days"] = int(d)
|
||||||
|
sub["expiry"] = ""
|
||||||
|
for k in ("locked", "warn3", "warn1"):
|
||||||
|
sub.pop(k, None)
|
||||||
|
else:
|
||||||
|
sub.pop("hold_days", None)
|
||||||
|
save_settings(s)
|
||||||
|
msg = f'<div class="alert alert-ok">{html_lib.escape(client_id)}: {tr("срок с первого подключения сохранён","start-on-first-connect saved")}</div>'
|
||||||
|
|
||||||
elif action == "push_config":
|
elif action == "push_config":
|
||||||
client_id = request.form.get("client_id", "").strip()
|
client_id = request.form.get("client_id", "").strip()
|
||||||
res = push_config_to_router(client_id)
|
res = push_config_to_router(client_id)
|
||||||
@@ -3899,6 +3998,7 @@ def clients_page():
|
|||||||
<label>{tr("Сервер","Server")}<select name="server_ip" data-o="{assigned_ip}">{srv_opts}</select></label>
|
<label>{tr("Сервер","Server")}<select name="server_ip" data-o="{assigned_ip}">{srv_opts}</select></label>
|
||||||
<label>{tr("Переход на другие серверы","Failover to other servers")} {hlp("«Только этот сервер» — учётка всегда выходит через выбранный сервер, без перехода. Так на одном роутере заводят несколько учёток = несколько стран выхода и раскладывают устройства политиками Keenetic. Смену сервера подхватывают только наши приложения (роутер, iOS, Android, Windows 1.4.5+); в сторонних клиентах (PhobosWG и др.) нужно заново импортировать ссылку.", "“This server only” — the account always exits via the chosen server, no failover. Use it for several accounts on one router = several exit countries, split devices with Keenetic policies. Server changes are followed only by our own apps (router, iOS, Android, Windows 1.4.5+); third-party clients (PhobosWG etc.) need the link re-imported.")}<select name="pinned" data-o="{pin_v}"><option value="0"{"" if pin_v == "1" else " selected"}>{tr("Да, при блокировке","Yes, when blocked")}</option><option value="1"{" selected" if pin_v == "1" else ""}>{tr("Только этот сервер","This server only")}</option></select></label>
|
<label>{tr("Переход на другие серверы","Failover to other servers")} {hlp("«Только этот сервер» — учётка всегда выходит через выбранный сервер, без перехода. Так на одном роутере заводят несколько учёток = несколько стран выхода и раскладывают устройства политиками Keenetic. Смену сервера подхватывают только наши приложения (роутер, iOS, Android, Windows 1.4.5+); в сторонних клиентах (PhobosWG и др.) нужно заново импортировать ссылку.", "“This server only” — the account always exits via the chosen server, no failover. Use it for several accounts on one router = several exit countries, split devices with Keenetic policies. Server changes are followed only by our own apps (router, iOS, Android, Windows 1.4.5+); third-party clients (PhobosWG etc.) need the link re-imported.")}<select name="pinned" data-o="{pin_v}"><option value="0"{"" if pin_v == "1" else " selected"}>{tr("Да, при блокировке","Yes, when blocked")}</option><option value="1"{" selected" if pin_v == "1" else ""}>{tr("Только этот сервер","This server only")}</option></select></label>
|
||||||
<div class="two"><label>{tr("Срок","Expiry")}<input type="date" name="expiry" value="{expiry}" data-o="{expiry}"></label>
|
<div class="two"><label>{tr("Срок","Expiry")}<input type="date" name="expiry" value="{expiry}" data-o="{expiry}"></label>
|
||||||
|
<label>{tr("Дней с первого подключения","Days from first connect")}<input type="number" name="hold_days" min="0" max="3650" value="{sub.get('hold_days', '')}" data-o="{sub.get('hold_days', '')}" placeholder="—" title="{tr("Срок начнётся, когда клиент впервые подключится","The term starts on the client's first connection")}"></label></div><div class="two">
|
||||||
<label>{tr("Скорость (Mbit/s)","Speed (Mbit/s)")}<input type="number" name="limit_mbit" min="0" max="10000" value="{_html_attr(lim)}" data-o="{_html_attr(lim)}" placeholder="∞"></label></div>
|
<label>{tr("Скорость (Mbit/s)","Speed (Mbit/s)")}<input type="number" name="limit_mbit" min="0" max="10000" value="{_html_attr(lim)}" data-o="{_html_attr(lim)}" placeholder="∞"></label></div>
|
||||||
{preset_row}
|
{preset_row}
|
||||||
<label>🛡 Firewall <span style="color:var(--muted);font-weight:400">({tr("разрешённые адреса; пусто — без ограничений","allowed destinations; empty = unrestricted")})</span>
|
<label>🛡 Firewall <span style="color:var(--muted);font-weight:400">({tr("разрешённые адреса; пусто — без ограничений","allowed destinations; empty = unrestricted")})</span>
|
||||||
@@ -3951,7 +4051,7 @@ def clients_page():
|
|||||||
function toggleBlur(){{var b=document.getElementById('ctable').classList.toggle('blur');try{{localStorage.setItem('cblur',b?'1':'0')}}catch(e){{}}}}
|
function toggleBlur(){{var b=document.getElementById('ctable').classList.toggle('blur');try{{localStorage.setItem('cblur',b?'1':'0')}}catch(e){{}}}}
|
||||||
try{{if(localStorage.getItem('cblur')!=='0')document.getElementById('ctable').classList.add('blur')}}catch(e){{}}
|
try{{if(localStorage.getItem('cblur')!=='0')document.getElementById('ctable').classList.add('blur')}}catch(e){{}}
|
||||||
function saveEdit(cid,f){{
|
function saveEdit(cid,f){{
|
||||||
var jobs=[],map={{display_name:'rename_client',server_ip:'assign_server',pinned:'set_pinned',expiry:'set_expiry',limit_mbit:'set_limit',preset_id:'set_preset',fw_list:'set_fw'}};
|
var jobs=[],map={{display_name:'rename_client',server_ip:'assign_server',pinned:'set_pinned',expiry:'set_expiry',limit_mbit:'set_limit',preset_id:'set_preset',fw_list:'set_fw',hold_days:'set_hold'}};
|
||||||
Object.keys(map).forEach(function(n){{var el=f.elements[n];if(el&&el.value!==el.dataset.o){{var d={{action:map[n],client_id:cid}};d[n]=el.value;jobs.push(d)}}}});
|
Object.keys(map).forEach(function(n){{var el=f.elements[n];if(el&&el.value!==el.dataset.o){{var d={{action:map[n],client_id:cid}};d[n]=el.value;jobs.push(d)}}}});
|
||||||
var err=document.getElementById('err-'+cid);err.textContent='';
|
var err=document.getElementById('err-'+cid);err.textContent='';
|
||||||
if(!jobs.length){{closeM('me-'+cid);return false}}
|
if(!jobs.length){{closeM('me-'+cid);return false}}
|
||||||
|
|||||||
Reference in New Issue
Block a user