Files
MapMil/centers/parsing/workers/workers/sources/telegram_settings.py
T
gitrusprusandCursor 5811ecb134 Add VPN admin tab with subscription proxy via cp-vpn for selected sources.
Persist settings in CA, expose /admin/vpn and /internal/vpn, and route Telegram (and optional web/nlp) traffic through mihomo SOCKS when enabled.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 23:41:33 +03:00

80 lines
2.3 KiB
Python

"""Общие настройки подключения Telethon."""
import os
from telethon import TelegramClient
DEFAULT_SESSION_PATH = "/data/telegram.session"
def get_session_path() -> str:
return os.environ.get("TELEGRAM_SESSION_PATH", DEFAULT_SESSION_PATH)
def get_api_credentials() -> tuple[int, str]:
api_id_raw = os.environ.get("TELEGRAM_API_ID", "")
api_hash = os.environ.get("TELEGRAM_API_HASH", "")
if not api_id_raw or not api_hash:
raise ValueError(
"Не заданы TELEGRAM_API_ID и TELEGRAM_API_HASH в .env"
)
try:
api_id = int(api_id_raw)
except ValueError as exc:
raise ValueError("TELEGRAM_API_ID должен быть числом") from exc
return api_id, api_hash
def get_env_proxy() -> tuple | None:
"""Legacy TELEGRAM_PROXY_* env fallback (used when CA VPN is off)."""
proxy_type = os.environ.get("TELEGRAM_PROXY_TYPE", "").strip().lower()
if not proxy_type or proxy_type == "none":
return None
host = os.environ.get("TELEGRAM_PROXY_HOST", "127.0.0.1").strip()
port = int(os.environ.get("TELEGRAM_PROXY_PORT", "1080"))
user = os.environ.get("TELEGRAM_PROXY_USER", "").strip()
password = os.environ.get("TELEGRAM_PROXY_PASS", "").strip()
if proxy_type not in ("socks5", "socks4", "http"):
raise ValueError(
f"Неподдерживаемый TELEGRAM_PROXY_TYPE={proxy_type!r}. "
"Используйте socks5, socks4 или http."
)
if user:
return proxy_type, host, port, True, user, password
return proxy_type, host, port
def get_proxy() -> tuple | None:
try:
from workers.sources.vpn_config import telethon_proxy_tuple
return telethon_proxy_tuple()
except Exception:
return get_env_proxy()
def describe_connection() -> str:
proxy = get_proxy()
if not proxy:
return "напрямую (без прокси)"
return f"через {proxy[0]}://{proxy[1]}:{proxy[2]}"
def create_client(session_path: str, api_id: int, api_hash: str) -> TelegramClient:
kwargs = {
"connection_retries": 10,
"retry_delay": 3,
"timeout": 60,
"request_retries": 5,
}
proxy = get_proxy()
if proxy:
kwargs["proxy"] = proxy
return TelegramClient(session_path, api_id, api_hash, **kwargs)