198 lines
6.2 KiB
Python
198 lines
6.2 KiB
Python
"""平台登录。各功能共用这一份会话。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import logging
|
|
import time
|
|
import uuid
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
|
|
from app.platform.client import NqiError, needs_captcha
|
|
from app.platform.sessions import available_accounts, remember_account, resume
|
|
from app.shared.state import state
|
|
|
|
logger = logging.getLogger("nqi.auth")
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
FLOW_TTL_SECONDS = 10 * 60
|
|
|
|
|
|
def _bad(message: str, status: int = 400) -> HTTPException:
|
|
return HTTPException(status_code=status, detail=message)
|
|
|
|
|
|
def _captcha_payload(session_id: str, challenge, **extra) -> dict:
|
|
encoded = base64.b64encode(challenge.captcha_png).decode("ascii")
|
|
return {
|
|
"sessionId": session_id,
|
|
"captcha": f"data:{challenge.captcha_type};base64,{encoded}",
|
|
**extra,
|
|
}
|
|
|
|
|
|
async def _pause_and_close_client(mark: str) -> int:
|
|
"""先暂停进行中的任务,等在途请求结束,再关闭当前客户端。"""
|
|
paused = sum(1 for job in state.jobs.jobs.values() if job.status in {"running", "queued"})
|
|
state.jobs.suspend_all("已暂停", mark)
|
|
client = state.client
|
|
state.client = None
|
|
if client is not None:
|
|
wait_idle = getattr(client, "wait_idle", None)
|
|
if wait_idle is not None:
|
|
await wait_idle(5)
|
|
await client.aclose()
|
|
return paused
|
|
|
|
|
|
def _accept_login() -> None:
|
|
state.expired = False
|
|
state.jobs.resume_marked("expired")
|
|
from app.features.download.router import fill_slots
|
|
|
|
fill_slots()
|
|
|
|
|
|
async def purge_expired_flows(now: float | None = None) -> None:
|
|
"""关掉超过 10 分钟的登录流程,并清掉内存里的密码。"""
|
|
moment = time.monotonic() if now is None else now
|
|
expired: list[str] = []
|
|
for session_id, (client, challenge) in list(state.flows.items()):
|
|
if client is state.client:
|
|
continue
|
|
created = getattr(challenge, "created_at", None)
|
|
if created is None or moment - float(created) < FLOW_TTL_SECONDS:
|
|
continue
|
|
expired.append(session_id)
|
|
for session_id in expired:
|
|
client, challenge = state.flows.pop(session_id)
|
|
challenge.password = ""
|
|
await client.aclose()
|
|
|
|
|
|
@router.post("/captcha")
|
|
async def captcha() -> dict:
|
|
from app.platform.client import NqiClient
|
|
|
|
await purge_expired_flows()
|
|
client = NqiClient()
|
|
try:
|
|
challenge = await client.open_login()
|
|
except Exception as exc:
|
|
await client.aclose()
|
|
logger.info("打开登录页失败: %s", exc)
|
|
raise _bad("连接失败,请稍后重试") from exc
|
|
session_id = uuid.uuid4().hex
|
|
challenge.created_at = time.monotonic()
|
|
state.flows[session_id] = (client, challenge)
|
|
return _captcha_payload(session_id, challenge)
|
|
|
|
|
|
@router.post("/captcha/refresh")
|
|
async def refresh(body: dict) -> dict:
|
|
session_id = str(body.get("sessionId") or "")
|
|
pair = state.flows.get(session_id)
|
|
if pair is None:
|
|
raise _bad("验证码已失效,请重新打开登录页")
|
|
client, challenge = pair
|
|
try:
|
|
await client.refresh_captcha(challenge)
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
return _captcha_payload(session_id, challenge)
|
|
|
|
|
|
@router.post("/sms")
|
|
async def sms(body: dict) -> dict:
|
|
session_id = str(body.get("sessionId") or "")
|
|
pair = state.flows.get(session_id)
|
|
if pair is None:
|
|
raise _bad("登录已过期,请刷新验证码")
|
|
client, challenge = pair
|
|
if not challenge.config_ready:
|
|
raise _bad("请先填写账号、密码和验证码")
|
|
try:
|
|
message = await client.send_sms(challenge)
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
return {"ok": True, "message": message}
|
|
|
|
|
|
@router.post("/login")
|
|
async def login(body: dict) -> dict:
|
|
session_id = str(body.get("sessionId") or "")
|
|
pair = state.flows.get(session_id)
|
|
if pair is None:
|
|
raise _bad("验证码已失效,请刷新后重试")
|
|
client, challenge = pair
|
|
username = str(body.get("username") or "").strip()
|
|
password = str(body.get("password") or "")
|
|
captcha = str(body.get("captcha") or "").strip()
|
|
sms_code = str(body.get("smsCode") or "").strip()
|
|
if not username or not password:
|
|
raise _bad("请输入账号和密码")
|
|
if not captcha:
|
|
raise _bad("请输入验证码")
|
|
try:
|
|
if not (challenge.config_ready and sms_code):
|
|
code = await client.prepare_login(challenge, username, password, captcha)
|
|
if code == "1" and not sms_code:
|
|
return {"status": "sms_required"}
|
|
user = await client.submit_login(challenge, sms_code)
|
|
except NqiError as exc:
|
|
message = str(exc)
|
|
if needs_captcha(message):
|
|
challenge.config_ready = False
|
|
return {"status": "need_captcha", "message": message}
|
|
if not challenge.config_ready:
|
|
try:
|
|
await client.refresh_captcha(challenge)
|
|
except NqiError:
|
|
pass
|
|
raise HTTPException(status_code=400, detail=message) from exc
|
|
challenge.password = ""
|
|
await remember_account(user, client.export_cookies())
|
|
if state.client is not client:
|
|
await _pause_and_close_client("switch")
|
|
state.client = client
|
|
state.user = user
|
|
state.flows.pop(session_id, None)
|
|
_accept_login()
|
|
return {"status": "ok", "user": user}
|
|
|
|
|
|
@router.get("/saved")
|
|
async def saved() -> dict:
|
|
return {"accounts": await available_accounts()}
|
|
|
|
|
|
@router.post("/resume")
|
|
async def resume_saved(body: dict) -> dict:
|
|
login_id = str(body.get("loginId") or "").strip()
|
|
if not login_id:
|
|
raise _bad("请选择账号")
|
|
try:
|
|
client, user = await resume(login_id)
|
|
except NqiError as exc:
|
|
raise _bad(str(exc)) from exc
|
|
if state.client is not client:
|
|
await _pause_and_close_client("switch")
|
|
state.client = client
|
|
state.user = user
|
|
_accept_login()
|
|
return {"status": "ok", "user": user}
|
|
|
|
|
|
@router.get("/me")
|
|
async def me() -> dict:
|
|
state.require_client()
|
|
return {"user": state.user}
|
|
|
|
|
|
@router.post("/logout")
|
|
async def logout() -> dict:
|
|
paused = await _pause_and_close_client("logout")
|
|
state.user = None
|
|
state.expired = False
|
|
return {"ok": True, "paused": paused}
|