feat(api,userbot,frontend): add accounts from the web ui and isolate per-account settings
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
import contextlib
|
||||
import secrets
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from pyrogram.errors import SessionPasswordNeeded
|
||||
from pyrogram.types import User
|
||||
|
||||
from userbot import PyroClient
|
||||
from utils.env import env
|
||||
|
||||
LOGIN_TTL_SECONDS = 900
|
||||
PENDING_DIRNAME = "pending"
|
||||
|
||||
|
||||
class LoginError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class PendingLogin:
|
||||
client: PyroClient
|
||||
phone: str
|
||||
phone_code_hash: str
|
||||
started_at: float
|
||||
|
||||
|
||||
def _sessions_dir() -> Path:
|
||||
path = Path(env.tg.sessions_dir)
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _pending_dir() -> Path:
|
||||
path = _sessions_dir() / PENDING_DIRNAME
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
class LoginManager:
|
||||
def __init__(self) -> None:
|
||||
self._logins: dict[str, PendingLogin] = {}
|
||||
|
||||
def _get(self, login_id: str) -> PendingLogin:
|
||||
login = self._logins.get(login_id)
|
||||
if login is None:
|
||||
msg = "Сессия входа истекла, начните заново"
|
||||
raise LoginError(msg)
|
||||
return login
|
||||
|
||||
async def start(self, phone: str) -> str:
|
||||
await self._sweep()
|
||||
login_id = secrets.token_hex(8)
|
||||
client = PyroClient(login_id, workdir=str(_pending_dir()), load_handlers=False)
|
||||
await client.connect()
|
||||
try:
|
||||
sent = await client.send_code(phone)
|
||||
except Exception:
|
||||
await self._discard(login_id, client)
|
||||
raise
|
||||
self._logins[login_id] = PendingLogin(
|
||||
client, phone, sent.phone_code_hash, time.monotonic()
|
||||
)
|
||||
return login_id
|
||||
|
||||
async def submit_code(self, login_id: str, code: str) -> User | None:
|
||||
login = self._get(login_id)
|
||||
try:
|
||||
user = await login.client.sign_in(login.phone, login.phone_code_hash, code)
|
||||
except SessionPasswordNeeded:
|
||||
return None
|
||||
if not isinstance(user, User):
|
||||
await self.cancel(login_id)
|
||||
msg = "Этот номер не зарегистрирован в Telegram"
|
||||
raise LoginError(msg)
|
||||
return user
|
||||
|
||||
async def submit_password(self, login_id: str, password: str) -> User:
|
||||
return await self._get(login_id).client.check_password(password)
|
||||
|
||||
async def finalize(self, login_id: str, session_name: str) -> None:
|
||||
login = self._logins.pop(login_id)
|
||||
await login.client.disconnect()
|
||||
source = _pending_dir() / f"{login_id}.session"
|
||||
source.replace(_sessions_dir() / f"{session_name}.session")
|
||||
|
||||
async def cancel(self, login_id: str) -> None:
|
||||
login = self._logins.pop(login_id, None)
|
||||
if login is not None:
|
||||
await self._discard(login_id, login.client)
|
||||
|
||||
async def _discard(self, login_id: str, client: PyroClient) -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
await client.disconnect()
|
||||
(_pending_dir() / f"{login_id}.session").unlink(missing_ok=True)
|
||||
|
||||
async def _sweep(self) -> None:
|
||||
now = time.monotonic()
|
||||
for login_id, login in list(self._logins.items()):
|
||||
if now - login.started_at > LOGIN_TTL_SECONDS:
|
||||
await self.cancel(login_id)
|
||||
for path in _pending_dir().glob("*.session"):
|
||||
if path.stem not in self._logins:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
login_manager = LoginManager()
|
||||
@@ -1,13 +1,109 @@
|
||||
from collections.abc import Coroutine
|
||||
from typing import Any, Literal
|
||||
|
||||
import asyncpg
|
||||
from dishka.integrations.fastapi import DishkaRoute, FromDishka
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from pydantic import BaseModel
|
||||
from pyrogram.errors import FloodWait, RPCError
|
||||
from pyrogram.types import User
|
||||
|
||||
from api.login import LoginError, login_manager
|
||||
from utils.read import accounts
|
||||
from utils.read.models import AccountView
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["accounts"], route_class=DishkaRoute)
|
||||
|
||||
_ERROR_MESSAGES = {
|
||||
"PhoneNumberInvalid": "Неверный номер телефона",
|
||||
"PhoneNumberBanned": "Номер заблокирован в Telegram",
|
||||
"PhoneCodeInvalid": "Неверный код",
|
||||
"PhoneCodeExpired": "Код истёк, запросите новый",
|
||||
"PasswordHashInvalid": "Неверный пароль",
|
||||
}
|
||||
|
||||
|
||||
class PhoneRequest(BaseModel):
|
||||
phone: str
|
||||
|
||||
|
||||
class CodeRequest(BaseModel):
|
||||
code: str
|
||||
|
||||
|
||||
class PasswordRequest(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
class LoginState(BaseModel):
|
||||
login_id: str
|
||||
stage: Literal["code", "password", "done"]
|
||||
account: AccountView | None = None
|
||||
|
||||
|
||||
async def _guard[T](coro: Coroutine[Any, Any, T]) -> T:
|
||||
try:
|
||||
return await coro
|
||||
except LoginError as exc:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
|
||||
except FloodWait as exc:
|
||||
raise HTTPException(
|
||||
status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
f"Слишком много попыток, подождите {exc.value} с",
|
||||
) from exc
|
||||
except RPCError as exc:
|
||||
detail = _ERROR_MESSAGES.get(type(exc).__name__, str(exc))
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail) from exc
|
||||
|
||||
|
||||
async def _complete(pool: asyncpg.Pool, login_id: str, user: User) -> LoginState:
|
||||
session_name = str(user.id)
|
||||
account_id = await accounts.sync_account(pool, user, session_name)
|
||||
await login_manager.finalize(login_id, session_name)
|
||||
await accounts.notify_accounts_changed(pool)
|
||||
return LoginState(
|
||||
login_id=login_id,
|
||||
stage="done",
|
||||
account=await accounts.get_account(pool, account_id),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/accounts")
|
||||
async def list_accounts(pool: FromDishka[asyncpg.Pool]) -> list[AccountView]:
|
||||
return await accounts.list_accounts(pool)
|
||||
|
||||
|
||||
@router.post("/accounts/login")
|
||||
async def start_login(body: PhoneRequest) -> LoginState:
|
||||
login_id = await _guard(login_manager.start(body.phone))
|
||||
return LoginState(login_id=login_id, stage="code")
|
||||
|
||||
|
||||
@router.post("/accounts/login/{login_id}/code")
|
||||
async def submit_code(
|
||||
login_id: str, body: CodeRequest, pool: FromDishka[asyncpg.Pool]
|
||||
) -> LoginState:
|
||||
user = await _guard(login_manager.submit_code(login_id, body.code))
|
||||
if user is None:
|
||||
return LoginState(login_id=login_id, stage="password")
|
||||
return await _complete(pool, login_id, user)
|
||||
|
||||
|
||||
@router.post("/accounts/login/{login_id}/password")
|
||||
async def submit_password(
|
||||
login_id: str, body: PasswordRequest, pool: FromDishka[asyncpg.Pool]
|
||||
) -> LoginState:
|
||||
user = await _guard(login_manager.submit_password(login_id, body.password))
|
||||
return await _complete(pool, login_id, user)
|
||||
|
||||
|
||||
@router.delete("/accounts/login/{login_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def cancel_login(login_id: str) -> None:
|
||||
await login_manager.cancel(login_id)
|
||||
|
||||
|
||||
@router.delete("/accounts/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def logout_account(account_id: int, pool: FromDishka[asyncpg.Pool]) -> None:
|
||||
if await accounts.deactivate_account(pool, account_id) is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Аккаунт не найден")
|
||||
await accounts.notify_accounts_changed(pool)
|
||||
|
||||
@@ -71,9 +71,15 @@ async def get_policy(pool: FromDishka[asyncpg.Pool], policy_id: int) -> PolicyRe
|
||||
|
||||
@router.put("/{policy_id}")
|
||||
async def update_policy(
|
||||
pool: FromDishka[asyncpg.Pool], policy_id: int, body: CaptureToggles
|
||||
pool: FromDishka[asyncpg.Pool],
|
||||
policy_id: int,
|
||||
body: CaptureToggles,
|
||||
account_id: Annotated[int | None, Query()] = None,
|
||||
) -> PolicyRecord:
|
||||
record = await repository.update_policy(pool, policy_id, body)
|
||||
if account_id is None:
|
||||
record = await repository.update_policy(pool, policy_id, body)
|
||||
else:
|
||||
record = await repository.override_policy(pool, policy_id, account_id, body)
|
||||
if record is None:
|
||||
raise HTTPException(status_code=404, detail="policy not found")
|
||||
await pool.execute(f"NOTIFY {POLICY_CHANGED_CHANNEL}")
|
||||
|
||||
Reference in New Issue
Block a user