Archived
307 lines
11 KiB
Python
307 lines
11 KiB
Python
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import json
|
|
import re
|
|
import sqlite3
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from .settings import DATABASE_PATH
|
|
|
|
TOKEN_RE = re.compile(r"^\d+:[A-Za-z0-9_-]{20,}$")
|
|
|
|
|
|
def _connect() -> sqlite3.Connection:
|
|
Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True)
|
|
conn = sqlite3.connect(DATABASE_PATH, timeout=10)
|
|
conn.row_factory = sqlite3.Row
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
return conn
|
|
|
|
|
|
def init_telegram_settings() -> None:
|
|
with _connect() as conn:
|
|
conn.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS telegram_settings (
|
|
id INTEGER PRIMARY KEY CHECK(id=1),
|
|
enabled INTEGER NOT NULL DEFAULT 0,
|
|
bot_token TEXT NOT NULL DEFAULT '',
|
|
allowed_user_ids TEXT NOT NULL DEFAULT '[]',
|
|
default_endpoint TEXT NOT NULL DEFAULT '',
|
|
default_dns TEXT NOT NULL DEFAULT '[]',
|
|
language TEXT NOT NULL DEFAULT 'auto',
|
|
bot_username TEXT NOT NULL DEFAULT '',
|
|
last_error TEXT NOT NULL DEFAULT '',
|
|
last_poll_at INTEGER NOT NULL DEFAULT 0,
|
|
update_offset INTEGER NOT NULL DEFAULT 0,
|
|
updated_at INTEGER NOT NULL DEFAULT 0
|
|
)
|
|
"""
|
|
)
|
|
conn.execute(
|
|
"""
|
|
INSERT OR IGNORE INTO telegram_settings(
|
|
id, enabled, bot_token, allowed_user_ids, default_endpoint,
|
|
default_dns, language, bot_username, last_error, last_poll_at,
|
|
update_offset, updated_at
|
|
) VALUES(1,0,'','[]','','[]','auto','','',0,0,0)
|
|
"""
|
|
)
|
|
|
|
|
|
def _row() -> sqlite3.Row:
|
|
init_telegram_settings()
|
|
with _connect() as conn:
|
|
row = conn.execute("SELECT * FROM telegram_settings WHERE id=1").fetchone()
|
|
if row is None:
|
|
raise RuntimeError("Telegram settings row is missing")
|
|
return row
|
|
|
|
|
|
def _loads_list(value: str) -> list[Any]:
|
|
try:
|
|
data = json.loads(value)
|
|
return data if isinstance(data, list) else []
|
|
except Exception:
|
|
return []
|
|
|
|
|
|
def mask_token(token: str) -> str:
|
|
if not token:
|
|
return ""
|
|
prefix = token.split(":", 1)[0]
|
|
return f"{prefix}:••••••••••••"
|
|
|
|
|
|
def get_telegram_settings(*, include_token: bool = False) -> dict[str, Any]:
|
|
row = _row()
|
|
ids: list[int] = []
|
|
for item in _loads_list(str(row["allowed_user_ids"])):
|
|
try:
|
|
value = int(item)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if value > 0 and value not in ids:
|
|
ids.append(value)
|
|
dns = [str(x) for x in _loads_list(str(row["default_dns"])) if str(x).strip()]
|
|
token = str(row["bot_token"] or "")
|
|
result = {
|
|
"enabled": bool(row["enabled"]),
|
|
"token_configured": bool(token),
|
|
"token_masked": mask_token(token),
|
|
"allowed_user_ids": ids,
|
|
"default_endpoint": str(row["default_endpoint"] or ""),
|
|
"default_dns": dns,
|
|
"language": str(row["language"] or "auto"),
|
|
"bot_username": str(row["bot_username"] or ""),
|
|
"last_error": str(row["last_error"] or ""),
|
|
"last_poll_at": int(row["last_poll_at"] or 0),
|
|
"update_offset": int(row["update_offset"] or 0),
|
|
"updated_at": int(row["updated_at"] or 0),
|
|
}
|
|
if include_token:
|
|
result["bot_token"] = token
|
|
return result
|
|
|
|
|
|
def _normalize_allowed_user_ids(values: Any) -> list[int]:
|
|
if values is None:
|
|
return []
|
|
if isinstance(values, str):
|
|
raw_items = [x.strip() for x in re.split(r"[\s,;]+", values) if x.strip()]
|
|
elif isinstance(values, list):
|
|
raw_items = values
|
|
else:
|
|
raise ValueError("Allowed Telegram user IDs must be a list")
|
|
result: list[int] = []
|
|
for raw in raw_items:
|
|
try:
|
|
value = int(raw)
|
|
except (TypeError, ValueError) as exc:
|
|
raise ValueError(f"Invalid Telegram user ID: {raw}") from exc
|
|
if value <= 0:
|
|
raise ValueError("Telegram user IDs must be positive numbers")
|
|
if value not in result:
|
|
result.append(value)
|
|
return result
|
|
|
|
|
|
def _normalize_dns(values: Any) -> list[str]:
|
|
if values is None:
|
|
return []
|
|
if isinstance(values, str):
|
|
raw_items = [x.strip() for x in re.split(r"[\s,;]+", values) if x.strip()]
|
|
elif isinstance(values, list):
|
|
raw_items = [str(x).strip() for x in values if str(x).strip()]
|
|
else:
|
|
raise ValueError("Default DNS must be a list of IPv4 addresses")
|
|
result: list[str] = []
|
|
for raw in raw_items:
|
|
try:
|
|
ip = ipaddress.ip_address(raw)
|
|
except ValueError as exc:
|
|
raise ValueError(f"Invalid DNS address: {raw}") from exc
|
|
if ip.version != 4:
|
|
raise ValueError("Only IPv4 DNS addresses are supported")
|
|
text = str(ip)
|
|
if text not in result:
|
|
result.append(text)
|
|
return result
|
|
|
|
|
|
def _normalize_endpoint(value: str) -> str:
|
|
endpoint = str(value or "").strip()
|
|
if not endpoint:
|
|
return ""
|
|
if len(endpoint) > 253 or any(ch.isspace() for ch in endpoint):
|
|
raise ValueError("Server address/domain is invalid")
|
|
if "://" in endpoint or "/" in endpoint:
|
|
raise ValueError("Enter only the server IP address or domain, without protocol or path")
|
|
if ":" in endpoint:
|
|
raise ValueError("Do not include the WireGuard port here; WGTools reads it from the server configuration")
|
|
return endpoint
|
|
|
|
|
|
def update_telegram_settings(
|
|
*,
|
|
enabled: bool,
|
|
bot_token: str | None,
|
|
clear_token: bool,
|
|
allowed_user_ids: Any,
|
|
default_endpoint: str,
|
|
default_dns: Any,
|
|
language: str,
|
|
) -> dict[str, Any]:
|
|
current = get_telegram_settings(include_token=True)
|
|
token = str(current.get("bot_token") or "")
|
|
supplied = str(bot_token or "").strip()
|
|
if clear_token:
|
|
token = ""
|
|
elif supplied:
|
|
if not TOKEN_RE.fullmatch(supplied):
|
|
raise ValueError("Bot token does not look like a Telegram Bot API token")
|
|
token = supplied
|
|
|
|
ids = _normalize_allowed_user_ids(allowed_user_ids)
|
|
dns = _normalize_dns(default_dns)
|
|
endpoint = _normalize_endpoint(default_endpoint)
|
|
language = str(language or "auto").strip().lower()
|
|
if language not in {"auto", "en", "ru", "pl"}:
|
|
raise ValueError("Nieprawidłowy język bota")
|
|
language = "pl"
|
|
if enabled and not token:
|
|
raise ValueError("Configure a BotFather token before enabling the Telegram bot")
|
|
|
|
now = int(time.time())
|
|
with _connect() as conn:
|
|
conn.execute(
|
|
"""
|
|
UPDATE telegram_settings SET
|
|
enabled=?, bot_token=?, allowed_user_ids=?, default_endpoint=?,
|
|
default_dns=?, language=?, updated_at=?
|
|
WHERE id=1
|
|
""",
|
|
(
|
|
1 if enabled else 0,
|
|
token,
|
|
json.dumps(ids),
|
|
endpoint,
|
|
json.dumps(dns),
|
|
language,
|
|
now,
|
|
),
|
|
)
|
|
if supplied or clear_token:
|
|
conn.execute(
|
|
"UPDATE telegram_settings SET bot_username='', last_error='', last_poll_at=0, update_offset=0 WHERE id=1"
|
|
)
|
|
return get_telegram_settings()
|
|
|
|
|
|
def update_telegram_runtime(*, bot_username: str | None = None, last_error: str | None = None, last_poll_at: int | None = None) -> None:
|
|
sets: list[str] = []
|
|
values: list[Any] = []
|
|
if bot_username is not None:
|
|
sets.append("bot_username=?")
|
|
values.append(str(bot_username))
|
|
if last_error is not None:
|
|
sets.append("last_error=?")
|
|
values.append(str(last_error)[:1000])
|
|
if last_poll_at is not None:
|
|
sets.append("last_poll_at=?")
|
|
values.append(int(last_poll_at))
|
|
if not sets:
|
|
return
|
|
values.append(1)
|
|
with _connect() as conn:
|
|
conn.execute(f"UPDATE telegram_settings SET {', '.join(sets)} WHERE id=?", values)
|
|
|
|
|
|
def set_update_offset(offset: int) -> None:
|
|
with _connect() as conn:
|
|
conn.execute("UPDATE telegram_settings SET update_offset=? WHERE id=1", (max(0, int(offset)),))
|
|
|
|
|
|
def set_default_endpoint(endpoint: str) -> None:
|
|
endpoint = _normalize_endpoint(endpoint)
|
|
with _connect() as conn:
|
|
conn.execute("UPDATE telegram_settings SET default_endpoint=?, updated_at=? WHERE id=1", (endpoint, int(time.time())))
|
|
|
|
|
|
def telegram_api_call(token: str, method: str, payload: dict[str, Any] | None = None, *, timeout: float = 15.0) -> Any:
|
|
if not token:
|
|
raise RuntimeError("Telegram bot token is not configured")
|
|
url = f"https://api.telegram.org/bot{token}/{method}"
|
|
data = json.dumps(payload or {}).encode("utf-8")
|
|
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json", "User-Agent": "WGTools/Telegram"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
raw = resp.read().decode("utf-8", "replace")
|
|
except urllib.error.HTTPError as exc:
|
|
detail = exc.read().decode("utf-8", "replace")
|
|
raise RuntimeError(f"Telegram HTTP {exc.code}: {detail[:500]}") from exc
|
|
except urllib.error.URLError as exc:
|
|
raise RuntimeError(f"Telegram connection failed: {exc.reason}") from exc
|
|
try:
|
|
result = json.loads(raw)
|
|
except json.JSONDecodeError as exc:
|
|
raise RuntimeError("Telegram returned invalid JSON") from exc
|
|
if not result.get("ok"):
|
|
raise RuntimeError(str(result.get("description") or "Telegram Bot API request failed"))
|
|
return result.get("result")
|
|
|
|
|
|
def test_telegram_connection() -> dict[str, Any]:
|
|
settings = get_telegram_settings(include_token=True)
|
|
token = str(settings.get("bot_token") or "")
|
|
try:
|
|
result = telegram_api_call(token, "getMe", {}, timeout=20)
|
|
except RuntimeError as exc:
|
|
last_poll_at = int(settings.get("last_poll_at") or 0)
|
|
if last_poll_at and time.time() - last_poll_at < 300:
|
|
text = str(exc).lower()
|
|
if "timed out" in text or "handshake" in text or "tls" in text:
|
|
return {
|
|
"ok": True,
|
|
"username": str(settings.get("bot_username") or ""),
|
|
"name": "",
|
|
"id": 0,
|
|
"verified_by_last_poll": True,
|
|
"last_poll_at": last_poll_at,
|
|
"warning": "The direct check timed out, but the bot is actively polling Telegram.",
|
|
}
|
|
raise
|
|
username = str((result or {}).get("username") or "")
|
|
update_telegram_runtime(bot_username=username, last_error="")
|
|
return {
|
|
"ok": True,
|
|
"username": username,
|
|
"name": str((result or {}).get("first_name") or ""),
|
|
"id": int((result or {}).get("id") or 0),
|
|
}
|