Skip to content

The only downloader you need. 下载器的集大成者。

refactor: 拆分 Bilibili 登录逻辑

XiaoYouChRacb8650dc091
diff --git a/features/bili_pack/config.py b/features/bili_pack/config.py
index e5eff356..a875a823 100644
--- a/features/bili_pack/config.py
+++ b/features/bili_pack/config.py
@@ -1,9 +1,6 @@
-import asyncio
from io import BytesIO
from typing import TYPE_CHECKING
-from urllib.parse import parse_qsl, urlparse
-import niquests
import qrcode
from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QDesktopServices, QPixmap
@@ -32,75 +29,23 @@ from qrcode.image.pure import PyPNGImage
from app.bases.models import PackConfig
from app.services.core_service import coreService
-from app.supports.config import DEFAULT_HEADERS, cfg
-from app.supports.utils import getProxies
+from app.supports.config import cfg
+from .login import (
+ _QR_UNSCANNED,
+ _QR_SCANNED,
+ _QR_EXPIRED,
+ _toCookie,
+ requestQrCode,
+ pollQrLogin,
+ fetchLoginInfo,
+ logout,
+)
if TYPE_CHECKING:
from app.view.pages.setting_page import SettingPage
-_BILIBILI_WEB_QR_GENERATE_API = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate"
-_BILIBILI_WEB_QR_POLL_API = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll"
-_BILIBILI_LOGIN_INFO_API = "https://api.bilibili.com/x/web-interface/nav"
-_BILIBILI_LOGOUT_API = "https://passport.bilibili.com/login/exit/v2"
-_BILIBILI_QR_POLL_INTERVAL_MS = 2000
-_BILIBILI_QR_UNSCANNED = 86101
-_BILIBILI_QR_SCANNED = 86090
-_BILIBILI_QR_EXPIRED = 86038
-_BILIBILI_LOGIN_COOKIE_ORDER = (
- "SESSDATA",
- "bili_jct",
- "DedeUserID",
- "DedeUserID__ckMd5",
- "sid",
-)
-
-
-def _parseCookieString(cookie: str) -> dict[str, str]:
- normalizedParts: dict[str, str] = {}
- if not isinstance(cookie, str):
- return normalizedParts
-
- for part in cookie.replace("\r", ";").replace("\n", ";").split(";"):
- part = part.strip()
- if not part or "=" not in part:
- continue
-
- name, value = part.split("=", 1)
- name = name.strip()
- value = value.strip()
- if name and value:
- normalizedParts[name] = value
-
- return normalizedParts
-
-
-def _normalizeCookieString(cookie: str) -> str:
- normalizedParts = _parseCookieString(cookie)
- orderedNames = [name for name in _BILIBILI_LOGIN_COOKIE_ORDER if name in normalizedParts]
- extraNames = [name for name in normalizedParts if name not in _BILIBILI_LOGIN_COOKIE_ORDER]
- return "; ".join(f"{name}={normalizedParts[name]}" for name in orderedNames + extraNames)
-
-
-def _buildBilibiliLoginHeaders(cookie: str = "", *, includeOrigin: bool = False) -> dict[str, str]:
- headers = {
- "accept": "application/json, text/plain, */*",
- "accept-language": DEFAULT_HEADERS["accept-language"],
- "user-agent": DEFAULT_HEADERS["user-agent"],
- }
- normalizedCookie = _normalizeCookieString(cookie)
- if normalizedCookie:
- headers["cookie"] = normalizedCookie
- if includeOrigin:
- headers["origin"] = "https://www.bilibili.com"
- headers["referer"] = "https://www.bilibili.com/"
- return headers
-
-
def _createQrPixmap(content: str, size: int = 240) -> QPixmap:
- if qrcode is None:
- raise RuntimeError("缺少 qrcode 依赖,无法生成登录二维码")
-
qrCode = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, border=2, box_size=10)
qrCode.add_data(content)
qrCode.make(fit=True)
@@ -114,285 +59,6 @@ def _createQrPixmap(content: str, size: int = 240) -> QPixmap:
return pixmap.scaled(size, size)
-def _extractCookieItemsFromResponse(response) -> dict[str, str]:
- cookieItems: dict[str, str] = {}
-
- cookies = getattr(response, "cookies", None)
- if cookies is not None:
- try:
- for name, value in cookies.items():
- if name and value:
- cookieItems[str(name)] = str(value)
- except Exception:
- try:
- for cookie in cookies:
- name = getattr(cookie, "name", "")
- value = getattr(cookie, "value", "")
- if name and value:
- cookieItems[str(name)] = str(value)
- except Exception:
- pass
-
- return cookieItems
-
-
-def _extractCookieItemsFromSuccessUrl(successUrl: str) -> dict[str, str]:
- if not successUrl:
- return {}
-
- cookieItems: dict[str, str] = {}
- for name, value in parse_qsl(urlparse(successUrl).query, keep_blank_values=False):
- if name in _BILIBILI_LOGIN_COOKIE_ORDER and value:
- cookieItems[name] = value
-
- return cookieItems
-
-
-def _extractCookieString(response, payloadData: dict) -> str:
- cookieItems = _extractCookieItemsFromResponse(response)
- if not any(name in cookieItems for name in _BILIBILI_LOGIN_COOKIE_ORDER):
- cookieItems.update(_extractCookieItemsFromSuccessUrl(str(payloadData.get("url") or "").strip()))
-
- orderedNames = [name for name in _BILIBILI_LOGIN_COOKIE_ORDER if name in cookieItems]
- extraNames = [name for name in cookieItems if name not in _BILIBILI_LOGIN_COOKIE_ORDER]
- cookieString = "; ".join(f"{name}={cookieItems[name]}" for name in orderedNames + extraNames)
- return _normalizeCookieString(cookieString)
-
-
-def _formatVipStatus(data: dict) -> str:
- vipPayload = data.get("vip") or {}
- vipStatus = int(data.get("vipStatus") or vipPayload.get("status") or 0)
- if vipStatus != 1:
- return "未开通"
-
- vipLabel = ((vipPayload.get("label") or {}).get("text") or (data.get("vip_label") or {}).get("text") or "").strip()
- if vipLabel:
- return vipLabel
-
- vipType = int(data.get("vipType") or vipPayload.get("type") or 0)
- if vipType == 1:
- return "月度大会员"
- if vipType == 2:
- return "年度大会员"
- return "大会员"
-
-
-async def _requestBilibiliQrCode() -> dict[str, str]:
- client = niquests.AsyncSession(
- headers=_buildBilibiliLoginHeaders(),
- timeout=30,
- happy_eyeballs=True,
- )
- client.trust_env = False
-
- try:
- response = await client.get(
- _BILIBILI_WEB_QR_GENERATE_API,
- proxies=getProxies(),
- verify=cfg.SSLVerify.value,
- allow_redirects=True,
- )
- try:
- response.raise_for_status()
- payload = response.json()
- finally:
- response.close()
-
- if payload.get("code") not in {None, 0}:
- raise ValueError(payload.get("message") or "获取二维码失败")
-
- data = payload.get("data") or {}
- loginUrl = str(data.get("url") or "").strip()
- qrCodeKey = str(data.get("qrcode_key") or "").strip()
- if not loginUrl or not qrCodeKey:
- raise ValueError("二维码接口返回了不完整的数据")
-
- return {
- "url": loginUrl,
- "qrcode_key": qrCodeKey,
- }
- finally:
- await client.close()
-
-
-async def _pollBilibiliQrLogin(
- qrCodeKey: str,
- statusCallback=None,
- shouldStop=None,
-) -> dict[str, str | int]:
- client = niquests.AsyncSession(
- headers=_buildBilibiliLoginHeaders(),
- timeout=30,
- happy_eyeballs=True,
- )
- client.trust_env = False
-
- try:
- while True:
- if shouldStop is not None and shouldStop():
- return {"code": -1, "message": "cancelled", "url": "", "cookie": ""}
-
- response = await client.get(
- _BILIBILI_WEB_QR_POLL_API,
- params={"qrcode_key": qrCodeKey},
- proxies=getProxies(),
- verify=cfg.SSLVerify.value,
- allow_redirects=True,
- )
- try:
- response.raise_for_status()
- payload = response.json()
- data = payload.get("data") or {}
- cookieString = _extractCookieString(response, data) if data.get("code") == 0 else ""
- finally:
- response.close()
-
- if payload.get("code") not in {None, 0}:
- raise ValueError(payload.get("message") or "轮询扫码状态失败")
-
- statusCode = int(data.get("code", -1))
- statusMessage = str(data.get("message") or "").strip()
- result = {
- "code": statusCode,
- "message": statusMessage,
- "url": str(data.get("url") or "").strip(),
- "cookie": cookieString,
- }
-
- if statusCode in {_BILIBILI_QR_UNSCANNED, _BILIBILI_QR_SCANNED}:
- coreService._executeCallback(statusCallback, statusCode, statusMessage)
- await asyncio.sleep(_BILIBILI_QR_POLL_INTERVAL_MS / 1000)
- continue
-
- return result
- finally:
- await client.close()
-
-
-async def _fetchBilibiliLoginInfo(cookie: str) -> dict[str, str | bool]:
- normalizedCookie = _normalizeCookieString(cookie)
- if not normalizedCookie:
- return {
- "logged_in": False,
- "status": "未登录",
- "uname": "-",
- "mid": "-",
- "vip": "未开通",
- }
-
- client = niquests.AsyncSession(
- headers=_buildBilibiliLoginHeaders(normalizedCookie),
- timeout=30,
- happy_eyeballs=True,
- )
- client.trust_env = False
-
- try:
- response = await client.get(
- _BILIBILI_LOGIN_INFO_API,
- proxies=getProxies(),
- verify=cfg.SSLVerify.value,
- allow_redirects=True,
- )
- try:
- response.raise_for_status()
- payload = response.json()
- finally:
- response.close()
-
- data = payload.get("data") or {}
- if payload.get("code") == -101 or not data.get("isLogin"):
- return {
- "logged_in": False,
- "status": "未登录",
- "uname": "-",
- "mid": "-",
- "vip": "未开通",
- }
-
- if payload.get("code") not in {None, 0}:
- raise ValueError(payload.get("message") or "获取登录信息失败")
-
- return {
- "logged_in": True,
- "status": "已登录",
- "uname": str(data.get("uname") or "-").strip() or "-",
- "mid": str(data.get("mid") or "-"),
- "vip": _formatVipStatus(data),
- }
- finally:
- await client.close()
-
-
-async def _logoutBilibili(cookie: str) -> dict[str, str | bool]:
- normalizedCookie = _normalizeCookieString(cookie)
- cookieItems = _parseCookieString(normalizedCookie)
- requiredCookies = ("DedeUserID", "bili_jct", "SESSDATA")
- missingCookies = [name for name in requiredCookies if not cookieItems.get(name)]
- if missingCookies:
- return {
- "remote_logout": False,
- "clear_local": True,
- "message": f"Cookie 缺少 {', '.join(missingCookies)},已清除本地登录状态",
- }
-
- client = niquests.AsyncSession(
- headers=_buildBilibiliLoginHeaders(normalizedCookie, includeOrigin=True),
- timeout=30,
- happy_eyeballs=True,
- )
- client.trust_env = False
-
- try:
- response = await client.post(
- _BILIBILI_LOGOUT_API,
- data={
- "biliCSRF": cookieItems["bili_jct"],
- "gourl": "https://www.bilibili.com/",
- },
- proxies=getProxies(),
- verify=cfg.SSLVerify.value,
- allow_redirects=True,
- )
- try:
- response.raise_for_status()
- contentType = str(response.headers.get("content-type") or "").lower()
- if "application/json" not in contentType:
- return {
- "remote_logout": False,
- "clear_local": True,
- "message": "当前 Cookie 可能已失效,已清除本地登录状态",
- }
-
- payload = response.json()
- finally:
- response.close()
-
- if payload.get("code") == 0 and payload.get("status") is True:
- return {
- "remote_logout": True,
- "clear_local": True,
- "message": "已退出登录",
- }
-
- raise ValueError(payload.get("message") or "退出登录失败")
- finally:
- await client.close()
-
-
-async def _replaceBilibiliCookie(currentCookie: str, newCookie: str) -> dict[str, str]:
- normalizedCurrentCookie = _normalizeCookieString(currentCookie)
- normalizedNewCookie = _normalizeCookieString(newCookie)
-
- if not normalizedNewCookie:
- return {"cookie": ""}
-
- if normalizedCurrentCookie and normalizedCurrentCookie != normalizedNewCookie:
- await _logoutBilibili(normalizedCurrentCookie)
-
- return {"cookie": normalizedNewCookie}
-
-
class EditCookieDialog(MessageBoxBase):
def __init__(self, parent=None, initialCookie: str = ""):
super().__init__(parent=parent)
@@ -448,7 +114,7 @@ class ScanLoginDialog(MessageBoxBase):
self.statusLabel.setWordWrap(True)
self.tipLabel = CaptionLabel(
- self.tr("二维码有效期约 180 秒,失效后可点击“刷新二维码”重新生成"),
+ self.tr('二维码有效期约 180 秒,失效后可点击"刷新二维码"重新生成'),
self.widget,
)
self.tipLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
@@ -505,7 +171,7 @@ class ScanLoginDialog(MessageBoxBase):
generation = self._generation
coreService.runCoroutine(
- _requestBilibiliQrCode(),
+ requestQrCode(),
lambda result, error: self._onQrCodeGenerated(generation, result, error),
)
@@ -530,15 +196,14 @@ class ScanLoginDialog(MessageBoxBase):
self.qrPixmapLabel.setPixmap(_createQrPixmap(self._loginUrl))
except Exception as e:
self.statusLabel.setText(self.tr(f"二维码生成失败:{e}"))
- raise e
- return
+ raise
self.openBrowserButton.setEnabled(True)
self.statusLabel.setText(self.tr("等待扫码并在手机端确认登录"))
self._polling = True
generation = self._generation
coreService.runCoroutine(
- _pollBilibiliQrLogin(
+ pollQrLogin(
self._qrCodeKey,
lambda statusCode, statusMessage: self._onLoginPollingStatus(generation, statusCode, statusMessage),
lambda: self._closed or generation != self._generation,
@@ -550,11 +215,11 @@ class ScanLoginDialog(MessageBoxBase):
if self._closed or generation != self._generation:
return
- if statusCode == _BILIBILI_QR_UNSCANNED:
+ if statusCode == _QR_UNSCANNED:
self.statusLabel.setText(self.tr("等待扫码"))
return
- if statusCode == _BILIBILI_QR_SCANNED:
+ if statusCode == _QR_SCANNED:
self.statusLabel.setText(self.tr("二维码已扫码,请在手机端确认登录"))
return
@@ -568,7 +233,7 @@ class ScanLoginDialog(MessageBoxBase):
self._polling = False
if error:
- self.statusLabel.setText(self.tr("轮询扫码状态失败,请点击“刷新二维码”重试"))
+ self.statusLabel.setText(self.tr('轮询扫码状态失败,请点击"刷新二维码"重试'))
return
payload = result or {}
@@ -578,12 +243,12 @@ class ScanLoginDialog(MessageBoxBase):
if statusCode == -1:
return
- if statusCode == _BILIBILI_QR_EXPIRED:
- self.statusLabel.setText(self.tr("二维码已失效,请点击“刷新二维码”重新生成"))
+ if statusCode == _QR_EXPIRED:
+ self.statusLabel.setText(self.tr('二维码已失效,请点击"刷新二维码"重新生成'))
return
if statusCode == 0:
- self.cookie = _normalizeCookieString(str(payload.get("cookie") or ""))
+ self.cookie = str(payload.get("cookie") or "")
if not self.cookie:
self.statusLabel.setText(self.tr("登录成功,但未能提取到有效 Cookie"))
return
@@ -630,9 +295,9 @@ class BilibiliLoginSettingCard(SettingCard):
self.hBoxLayout.addWidget(self.operationWidget, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
self.hBoxLayout.addSpacing(16)
- self.scanLoginButton.clicked.connect(self._onScanLoginButtonClicked)
- self.editCookieButton.clicked.connect(self._onEditCookieButtonClicked)
- self.logoutButton.clicked.connect(self._onLogoutButtonClicked)
+ self.scanLoginButton.clicked.connect(self._onScanLogin)
+ self.editCookieButton.clicked.connect(self._onEditCookie)
+ self.logoutButton.clicked.connect(self._onLogout)
self._syncButtonsEnabled()
self.refreshLoginInfo()
@@ -648,7 +313,7 @@ class BilibiliLoginSettingCard(SettingCard):
def _syncButtonsEnabled(self, busy: bool = False):
self.scanLoginButton.setEnabled(not busy)
self.editCookieButton.setEnabled(not busy)
- self.logoutButton.setEnabled(not busy and bool(_normalizeCookieString(self.userCookieItem.value)))
+ self.logoutButton.setEnabled(not busy and bool(self.userCookieItem.value))
def _setAccountInfo(self, status: str, uname: str | None = None, mid: str | None = None, vip: str | None = None):
self._statusText = status
@@ -661,10 +326,7 @@ class BilibiliLoginSettingCard(SettingCard):
self._renderAccountInfo()
def refreshLoginInfo(self):
- cookie = _normalizeCookieString(self.userCookieItem.value)
- if cookie != self.userCookieItem.value:
- cfg.set(self.userCookieItem, cookie)
-
+ cookie = self.userCookieItem.value
self._syncButtonsEnabled()
if not cookie:
self._setAccountInfo("未登录", "-", "-", "未开通")
@@ -674,7 +336,7 @@ class BilibiliLoginSettingCard(SettingCard):
self._infoGeneration += 1
generation = self._infoGeneration
coreService.runCoroutine(
- _fetchBilibiliLoginInfo(cookie),
+ fetchLoginInfo(cookie),
lambda result, error: self._onLoginInfoLoaded(generation, result, error),
)
@@ -695,57 +357,50 @@ class BilibiliLoginSettingCard(SettingCard):
str(payload.get("vip") or "未开通"),
)
- def _applyNewCookie(self, newCookie: str):
- normalizedNewCookie = _normalizeCookieString(newCookie)
- if not normalizedNewCookie:
+ def _updateCookie(self, newCookie: str):
+ normalizedCookie = _toCookie(newCookie)
+ if not normalizedCookie:
cfg.set(self.userCookieItem, "")
self.refreshLoginInfo()
return
- currentCookie = _normalizeCookieString(self.userCookieItem.value)
+ currentCookie = self.userCookieItem.value
self._syncButtonsEnabled(True)
- if currentCookie and currentCookie != normalizedNewCookie:
+ if currentCookie and currentCookie != normalizedCookie:
self._setAccountInfo("正在退出旧账号并导入新账号...", "-", "-", "-")
+ coreService.runCoroutine(
+ logout(currentCookie),
+ lambda _result, _error: self._onCookieUpdated(normalizedCookie),
+ )
else:
- self._setAccountInfo("正在导入 Cookie...", "-", "-", "-")
-
- coreService.runCoroutine(
- _replaceBilibiliCookie(currentCookie, normalizedNewCookie),
- self._onCookieApplied,
- )
-
- def _onCookieApplied(self, result: dict | None, error: str | None):
- if error:
- self._syncButtonsEnabled()
- self._setAccountInfo("切换账号失败", "-", "-", "-")
- return
+ self._onCookieUpdated(normalizedCookie)
- payload = result or {}
- cfg.set(self.userCookieItem, _normalizeCookieString(str(payload.get("cookie") or "")))
+ def _onCookieUpdated(self, cookie: str):
+ cfg.set(self.userCookieItem, cookie)
self.refreshLoginInfo()
- def _onScanLoginButtonClicked(self):
+ def _onScanLogin(self):
dialog = ScanLoginDialog(self.window())
if dialog.exec():
- self._applyNewCookie(dialog.cookie)
+ self._updateCookie(dialog.cookie)
- def _onEditCookieButtonClicked(self):
+ def _onEditCookie(self):
dialog = EditCookieDialog(self.window(), self.userCookieItem.value)
try:
if dialog.exec():
- self._applyNewCookie(dialog.cookieTextEdit.toPlainText())
+ self._updateCookie(dialog.cookieTextEdit.toPlainText())
finally:
dialog.deleteLater()
- def _onLogoutButtonClicked(self):
- cookie = _normalizeCookieString(self.userCookieItem.value)
+ def _onLogout(self):
+ cookie = self.userCookieItem.value
if not cookie:
self.refreshLoginInfo()
return
self._syncButtonsEnabled(True)
self._setAccountInfo("正在退出登录...")
- coreService.runCoroutine(_logoutBilibili(cookie), self._onLoggedOut)
+ coreService.runCoroutine(logout(cookie), self._onLoggedOut)
def _onLoggedOut(self, result: dict | None, error: str | None):
if error:
@@ -761,12 +416,12 @@ class BilibiliLoginSettingCard(SettingCard):
class CookieValidator(ConfigValidator):
def validate(self, value) -> bool:
- if type(value) == str:
- return True
- return False
+ return isinstance(value, str)
def correct(self, value) -> str:
- return value if self.validate(value) else ""
+ if not isinstance(value, str):
+ return ""
+ return _toCookie(value)
class BilibiliConfig(PackConfig):
diff --git a/features/bili_pack/login.py b/features/bili_pack/login.py
new file mode 100644
index 00000000..396e7985
--- /dev/null
+++ b/features/bili_pack/login.py
@@ -0,0 +1,294 @@
+import asyncio
+from urllib.parse import parse_qsl, urlparse
+
+import niquests
+
+from app.supports.config import DEFAULT_HEADERS, cfg
+from app.supports.utils import getProxies
+
+
+_QR_GENERATE_API = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate"
+_QR_POLL_API = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll"
+_LOGIN_INFO_API = "https://api.bilibili.com/x/web-interface/nav"
+_LOGOUT_API = "https://passport.bilibili.com/login/exit/v2"
+_QR_POLL_INTERVAL_MS = 2000
+_QR_UNSCANNED = 86101
+_QR_SCANNED = 86090
+_QR_EXPIRED = 86038
+_COOKIE_ORDER = (
+ "SESSDATA",
+ "bili_jct",
+ "DedeUserID",
+ "DedeUserID__ckMd5",
+ "sid",
+)
+
+
+def _toCookie(raw: str) -> str:
+ parts: dict[str, str] = {}
+ if not isinstance(raw, str):
+ return ""
+
+ for part in raw.replace("\r", ";").replace("\n", ";").split(";"):
+ part = part.strip()
+ if not part or "=" not in part:
+ continue
+ name, value = part.split("=", 1)
+ name = name.strip()
+ value = value.strip()
+ if name and value:
+ parts[name] = value
+
+ if not parts:
+ return ""
+
+ ordered = [name for name in _COOKIE_ORDER if name in parts]
+ extra = [name for name in parts if name not in _COOKIE_ORDER]
+ return "; ".join(f"{name}={parts[name]}" for name in ordered + extra)
+
+
+def _headers(cookie: str = "", origin: bool = False) -> dict[str, str]:
+ headers = {
+ "accept": "application/json, text/plain, */*",
+ "accept-language": DEFAULT_HEADERS["accept-language"],
+ "user-agent": DEFAULT_HEADERS["user-agent"],
+ }
+ if cookie:
+ headers["cookie"] = cookie
+ if origin:
+ headers["origin"] = "https://www.bilibili.com"
+ headers["referer"] = "https://www.bilibili.com/"
+ return headers
+
+
+def _extractCookie(response, successUrl: str) -> str:
+ items = {str(k): str(v) for k, v in response.cookies.items() if k and v}
+ if not any(name in items for name in _COOKIE_ORDER):
+ for name, value in parse_qsl(urlparse(successUrl).query, keep_blank_values=False):
+ if name in _COOKIE_ORDER and value:
+ items[name] = value
+
+ if not items:
+ return ""
+ return _toCookie("; ".join(f"{k}={v}" for k, v in items.items()))
+
+
+async def requestQrCode() -> dict[str, str]:
+ client = niquests.AsyncSession(
+ headers=_headers(),
+ timeout=30,
+ happy_eyeballs=True,
+ )
+ client.trust_env = False
+
+ try:
+ response = await client.get(
+ _QR_GENERATE_API,
+ proxies=getProxies(),
+ verify=cfg.SSLVerify.value,
+ allow_redirects=True,
+ )
+ try:
+ response.raise_for_status()
+ payload = response.json()
+ finally:
+ response.close()
+
+ if payload.get("code") not in {None, 0}:
+ raise ValueError(payload.get("message") or "获取二维码失败")
+
+ data = payload.get("data") or {}
+ loginUrl = str(data.get("url") or "").strip()
+ qrCodeKey = str(data.get("qrcode_key") or "").strip()
+ if not loginUrl or not qrCodeKey:
+ raise ValueError("二维码接口返回了不完整的数据")
+
+ return {
+ "url": loginUrl,
+ "qrcode_key": qrCodeKey,
+ }
+ finally:
+ await client.close()
+
+
+async def pollQrLogin(
+ qrCodeKey: str,
+ statusCallback=None,
+ shouldStop=None,
+) -> dict[str, str | int]:
+ from app.services.core_service import coreService
+
+ client = niquests.AsyncSession(
+ headers=_headers(),
+ timeout=30,
+ happy_eyeballs=True,
+ )
+ client.trust_env = False
+
+ try:
+ while True:
+ if shouldStop is not None and shouldStop():
+ return {"code": -1, "message": "cancelled", "url": "", "cookie": ""}
+
+ response = await client.get(
+ _QR_POLL_API,
+ params={"qrcode_key": qrCodeKey},
+ proxies=getProxies(),
+ verify=cfg.SSLVerify.value,
+ allow_redirects=True,
+ )
+ try:
+ response.raise_for_status()
+ payload = response.json()
+ data = payload.get("data") or {}
+ cookieString = _extractCookie(response, str(data.get("url") or "")) if data.get("code") == 0 else ""
+ finally:
+ response.close()
+
+ if payload.get("code") not in {None, 0}:
+ raise ValueError(payload.get("message") or "轮询扫码状态失败")
+
+ statusCode = int(data.get("code", -1))
+ statusMessage = str(data.get("message") or "").strip()
+ result = {
+ "code": statusCode,
+ "message": statusMessage,
+ "url": str(data.get("url") or "").strip(),
+ "cookie": cookieString,
+ }
+
+ if statusCode in {_QR_UNSCANNED, _QR_SCANNED}:
+ coreService._executeCallback(statusCallback, statusCode, statusMessage)
+ await asyncio.sleep(_QR_POLL_INTERVAL_MS / 1000)
+ continue
+
+ return result
+ finally:
+ await client.close()
+
+
+async def fetchLoginInfo(cookie: str) -> dict[str, str | bool]:
+ if not cookie:
+ return {
+ "logged_in": False,
+ "status": "未登录",
+ "uname": "-",
+ "mid": "-",
+ "vip": "未开通",
+ }
+
+ client = niquests.AsyncSession(
+ headers=_headers(cookie),
+ timeout=30,
+ happy_eyeballs=True,
+ )
+ client.trust_env = False
+
+ try:
+ response = await client.get(
+ _LOGIN_INFO_API,
+ proxies=getProxies(),
+ verify=cfg.SSLVerify.value,
+ allow_redirects=True,
+ )
+ try:
+ response.raise_for_status()
+ payload = response.json()
+ finally:
+ response.close()
+
+ data = payload.get("data") or {}
+ if payload.get("code") == -101 or not data.get("isLogin"):
+ return {
+ "logged_in": False,
+ "status": "未登录",
+ "uname": "-",
+ "mid": "-",
+ "vip": "未开通",
+ }
+
+ if payload.get("code") not in {None, 0}:
+ raise ValueError(payload.get("message") or "获取登录信息失败")
+
+ vipPayload = data.get("vip") or {}
+ vipStatus = int(data.get("vipStatus") or vipPayload.get("status") or 0)
+ if vipStatus != 1:
+ vipText = "未开通"
+ else:
+ vipLabel = ((vipPayload.get("label") or {}).get("text") or (data.get("vip_label") or {}).get("text") or "").strip()
+ if vipLabel:
+ vipText = vipLabel
+ else:
+ vipType = int(data.get("vipType") or vipPayload.get("type") or 0)
+ vipText = {1: "月度大会员", 2: "年度大会员"}.get(vipType, "大会员")
+
+ return {
+ "logged_in": True,
+ "status": "已登录",
+ "uname": str(data.get("uname") or "-").strip() or "-",
+ "mid": str(data.get("mid") or "-"),
+ "vip": vipText,
+ }
+ finally:
+ await client.close()
+
+
+async def logout(cookie: str) -> dict[str, str | bool]:
+ parts: dict[str, str] = {}
+ for part in cookie.split(";"):
+ part = part.strip()
+ if "=" in part:
+ name, value = part.split("=", 1)
+ parts[name.strip()] = value.strip()
+
+ requiredCookies = ("DedeUserID", "bili_jct", "SESSDATA")
+ missingCookies = [name for name in requiredCookies if not parts.get(name)]
+ if missingCookies:
+ return {
+ "remote_logout": False,
+ "clear_local": True,
+ "message": f"Cookie 缺少 {', '.join(missingCookies)},已清除本地登录状态",
+ }
+
+ client = niquests.AsyncSession(
+ headers=_headers(cookie, origin=True),
+ timeout=30,
+ happy_eyeballs=True,
+ )
+ client.trust_env = False
+
+ try:
+ response = await client.post(
+ _LOGOUT_API,
+ data={
+ "biliCSRF": parts["bili_jct"],
+ "gourl": "https://www.bilibili.com/",
+ },
+ proxies=getProxies(),
+ verify=cfg.SSLVerify.value,
+ allow_redirects=True,
+ )
+ try:
+ response.raise_for_status()
+ contentType = str(response.headers.get("content-type") or "").lower()
+ if "application/json" not in contentType:
+ return {
+ "remote_logout": False,
+ "clear_local": True,
+ "message": "当前 Cookie 可能已失效,已清除本地登录状态",
+ }
+
+ payload = response.json()
+ finally:
+ response.close()
+
+ if payload.get("code") == 0 and payload.get("status") is True:
+ return {
+ "remote_logout": True,
+ "clear_local": True,
+ "message": "已退出登录",
+ }
+
+ raise ValueError(payload.get("message") or "退出登录失败")
+ finally:
+ await client.close()