diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cafd94..d201686 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 1.6.1 — 2026-11-21 +- **Напоминания клиенту в Telegram.** На личной странице клиента кнопка «Получать напоминания о сроке в Telegram» открывает бота панели; бот привязывает чат к клиенту (`/stop` отвязывает). За 3 дня, за день и в день окончания срока сообщение получает и клиент, и админ. Нужен бот в «Настройках» (токен и chat id админа), как и раньше. +- **Срок с первого подключения.** В окне «Правка» клиента поле «Дней с первого подключения»: срок начнётся, когда клиент впервые подключится, админу придёт уведомление. На личной странице видно «N дн. с первого подключения». + ## 1.6.0 — 2026-11-21 - **Личная страница клиента.** В окне «Подключение» у каждого клиента есть ссылка на его страницу: отправьте её человеку. Там статус (в сети или нет), срок подписки с остатком дней, трафик за месяц, кнопки «Скачать приложение» и «Добавить профиль» для Android, вариант для iPhone, QR для другого устройства и файл .conf. Вход в панель не нужен; ссылка защищена личным токеном клиента, чужой токен даёт 403. diff --git a/VERSION b/VERSION index dc1e644..9c6d629 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.6.0 +1.6.1 diff --git a/app.py b/app.py index 07f8b27..db9b56f 100644 --- a/app.py +++ b/app.py @@ -475,6 +475,62 @@ def tg_send(text): pass +def tg_client(cid, text): + """Message to the client's own Telegram (bound via /start 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 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"Готово: напомню о сроке подписки {html_lib.escape(cid)}" + + (f" (до {exp})" if exp else "") + ". Отключить: /stop"}) + tg_send(f"🔔 {html_lib.escape(cid)} подключил напоминания в Telegram") + return True + + def notify_on(cid): 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") if not m: 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 text = (m.get("text") or "").strip() if not text: @@ -919,6 +978,19 @@ def check_expiry(): today = datetime.now().date() 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"▶️ {client_id} — первое подключение, срок пошёл: до {info['expiry']}") + tg_client(client_id, f"Подписка активирована: до {info['expiry']}.") + for client_id, info in list(subs.items()): if not info.get("expiry"): continue @@ -934,14 +1006,17 @@ def check_expiry(): changed = True kick_client_by_id(client_id) tg_send(f"⛔ {client_id} — подписка истекла! Клиент заблокирован.") + tg_client(client_id, "Срок подписки закончился, VPN отключён. Для продления напишите администратору.") elif days_left == 3 and not info.get("warn3"): info["warn3"] = True changed = True tg_send(f"⚠️ {client_id} — подписка истекает через 3 дня ({info['expiry']})") + tg_client(client_id, f"Подписка заканчивается через 3 дня ({info['expiry']}).") elif days_left == 1 and not info.get("warn1"): info["warn1"] = True changed = True tg_send(f"⚠️ {client_id} — подписка истекает ЗАВТРА ({info['expiry']})") + tg_client(client_id, f"Подписка заканчивается завтра ({info['expiry']}).") if changed: save_settings(s) @@ -1308,6 +1383,15 @@ def personal_page(cid): term_cls = "bad" if left <= 0 else ("warn" if left <= 3 else "ok") except ValueError: 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'' + + (tr("Напоминания в Telegram включены", "Telegram reminders are on") if bound else tr("Получать напоминания о сроке в Telegram", "Get term reminders in Telegram")) + + '') u = _traffic_load().get("usage", {}).get(cid) traffic = f'↓ {_fmt_bytes(u[1])} · ↑ {_fmt_bytes(u[0])}' if u else "—" 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

{e(c.get("client_name") or cid)}

{tr("в сети","online") if online else tr("не в сети","offline")}
{tr("Срок","Term")}{term}
-
{tr("Трафик за месяц","Traffic this month")}{traffic}
+
{tr("Трафик за месяц","Traffic this month")}{traffic}
{tg_btn}

Android

{tr("1. Скачать PCA Phobos VPN","1. Download PCA Phobos VPN")} {tr("2. Добавить профиль в приложение","2. Add the profile to the app")} @@ -3593,6 +3677,21 @@ def clients_page(): save_settings(s) msg = f'
Срок для {client_id} обновлён
' + 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'
{html_lib.escape(client_id)}: {tr("срок с первого подключения сохранён","start-on-first-connect saved")}
' + elif action == "push_config": client_id = request.form.get("client_id", "").strip() res = push_config_to_router(client_id) @@ -3899,6 +3998,7 @@ def clients_page():
+
{preset_row}