Skip to content

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

refactor(android): 推送通道分状态与事件,Draft 编辑独立成页

XiaoYouChR85f3e0f91317
diff --git a/features/bili_pack/account.py b/features/bili_pack/account.py
index 6f55321d..7f96ef2c 100644
--- a/features/bili_pack/account.py
+++ b/features/bili_pack/account.py
@@ -30,8 +30,26 @@ QR_GOT_URL = 0
QR_LOGIN_SUCCESS = 1
QR_LOGIN_FAILED = -1
+ZONE_API = "https://api.bilibili.com/x/web-interface/zone"
+COUNTRY_LIST_API = "https://passport.bilibili.com/web/generic/country/list"
+CAPTCHA_API = "https://passport.bilibili.com/x/passport-login/captcha"
+SMS_SEND_API = "https://passport.bilibili.com/x/passport-login/web/sms/send"
+SMS_LOGIN_API = "https://passport.bilibili.com/x/passport-login/web/login/sms"
+SMS_SOURCE = "main-fe-header"
+DEFAULT_ZONE = 86
+
COOKIE_ORDER = ("SESSDATA", "bili_jct", "DedeUserID", "DedeUserID__ckMd5", "sid")
+PASSPORT_HEADERS = {
+ "referer": "https://www.bilibili.com/",
+ "origin": "https://www.bilibili.com",
+}
+
+
+def cookiesFrom(response) -> dict[str, str]:
+ return {c.name: c.value for c in response.cookies
+ if c.name in COOKIE_ORDER and c.value}
+
def toCookie(raw: str) -> str:
parts: dict[str, str] = {}
@@ -61,6 +79,8 @@ class BilibiliAccount:
self._vip = ""
self._mixinKey = ""
self._qrWorkId = ""
+ self._captchaToken = ""
+ self._smsCaptchaKey = ""
@property
def cookie(self) -> str:
@@ -153,10 +173,7 @@ class BilibiliAccount:
return None
if statusCode == 0:
- items: dict[str, str] = {}
- for c in response.cookies:
- if c.name in COOKIE_ORDER and c.value:
- items[c.name] = c.value
+ items = cookiesFrom(response)
if not any(n in items for n in COOKIE_ORDER):
successUrl = str(data.get("url") or "")
for name, value in parse_qsl(urlparse(successUrl).query, keep_blank_values=False):
@@ -237,11 +254,7 @@ class BilibiliAccount:
if any(not parts.get(n) for n in required):
return True
- client = buildClient(headers={
- "cookie": cookie,
- "origin": "https://www.bilibili.com",
- "referer": "https://www.bilibili.com/",
- })
+ client = buildClient(headers={"cookie": cookie, **PASSPORT_HEADERS})
try:
response = await client.post(LOGOUT_API, form={
"biliCSRF": parts["bili_jct"],
@@ -322,4 +335,94 @@ class BilibiliAccount:
self._updateWbiKeys(wbiData)
self.accountChanged.emit()
+ # ── SMS login (caller blocks on the engine loop) ──
+
+ async def fetchCaptcha(self) -> dict:
+ client = buildClient()
+ try:
+ response = await client.get(CAPTCHA_API, query={"source": SMS_SOURCE})
+ response.raise_for_status()
+ payload = await response.json()
+ if payload.get("code") not in {None, 0}:
+ raise ValueError(payload.get("message") or "获取验证码失败")
+
+ data = payload.get("data") or {}
+ geetest = data.get("geetest") or {}
+ gt = str(geetest.get("gt") or "")
+ challenge = str(geetest.get("challenge") or "")
+ self._captchaToken = str(data.get("token") or "")
+ if not gt or not challenge or not self._captchaToken:
+ raise ValueError("验证码接口返回了不完整的数据")
+ return {"gt": gt, "challenge": challenge}
+ finally:
+ client.close()
+
+ async def fetchCountries(self) -> dict:
+ client = buildClient()
+ try:
+ response = await client.get(COUNTRY_LIST_API)
+ response.raise_for_status()
+ payload = await response.json()
+ data = payload.get("data") or {}
+ countries = []
+ for entry in (data.get("common") or []) + (data.get("others") or []):
+ cid = str(entry.get("country_id") or "")
+ if not cid.isdigit():
+ continue
+ name = str(entry.get("country_name") or "").strip()
+ countries.append({"cid": int(cid), "label": f"{name} +{cid}" if name else f"+{cid}"})
+ return {"defaultCid": await self._fetchZone(client), "countries": countries}
+ finally:
+ client.close()
+
+ async def _fetchZone(self, client) -> int:
+ try:
+ response = await client.get(ZONE_API)
+ response.raise_for_status()
+ payload = await response.json()
+ except Exception:
+ return DEFAULT_ZONE
+ return int((payload.get("data") or {}).get("country_code") or DEFAULT_ZONE)
+
+ async def sendSmsCode(self, cid: int, tel: str, captcha: dict):
+ client = buildClient(headers=PASSPORT_HEADERS)
+ try:
+ response = await client.post(SMS_SEND_API, query={
+ "cid": str(cid), "tel": tel, "token": self._captchaToken,
+ "source": SMS_SOURCE,
+ "challenge": str(captcha.get("challenge") or ""),
+ "validate": str(captcha.get("validate") or ""),
+ "seccode": str(captcha.get("seccode") or ""),
+ })
+ response.raise_for_status()
+ payload = await response.json()
+ key = str((payload.get("data") or {}).get("captcha_key") or "")
+ if payload.get("code") != 0 or not key:
+ raise ValueError(payload.get("message") or "验证码发送失败")
+ self._smsCaptchaKey = key
+ finally:
+ client.close()
+
+ async def loginSms(self, cid: int, tel: str, code: str):
+ client = buildClient(headers=PASSPORT_HEADERS)
+ try:
+ response = await client.post(SMS_LOGIN_API, query={
+ "cid": str(cid), "tel": tel, "code": code,
+ "source": SMS_SOURCE,
+ "captcha_key": self._smsCaptchaKey,
+ "keep": "true",
+ })
+ response.raise_for_status()
+ payload = await response.json()
+ data = payload.get("data") or {}
+ if int(data.get("status", -1)) != 0:
+ raise ValueError(str(data.get("message") or "登录失败"))
+
+ items = cookiesFrom(response)
+ if not items:
+ raise ValueError("登录成功,但未能提取到有效 Cookie")
+ self.setCookie(toCookie("; ".join(f"{k}={v}" for k, v in items.items())))
+ finally:
+ client.close()
+
diff --git a/features/bili_pack/android.py b/features/bili_pack/android.py
index ad7774e6..58e2bcae 100644
--- a/features/bili_pack/android.py
+++ b/features/bili_pack/android.py
@@ -1,6 +1,7 @@
"""Android View adapter for BilibiliPack."""
from __future__ import annotations
+import json
from dataclasses import asdict, dataclass
from .account import (
@@ -178,6 +179,22 @@ def cancelQrLogin():
_account.cancelQrLogin()
+async def fetchCaptcha() -> dict:
+ return await _account.fetchCaptcha()
+
+
+async def fetchCountries() -> dict:
+ return await _account.fetchCountries()
+
+
+async def sendSmsCode(cid: int, tel: str, captcha: str):
+ await _account.sendSmsCode(cid, tel, json.loads(captcha))
+
+
+async def loginSms(cid: int, tel: str, code: str):
+ await _account.loginSms(cid, tel, code)
+
+
def _onQrStateChanged(code: int, text: str):
global _qr
status = QR_STATUS.get(code, "failed")
diff --git a/features/bili_pack/i18n.py b/features/bili_pack/i18n.py
index f24f3a2c..8f5ca770 100644
--- a/features/bili_pack/i18n.py
+++ b/features/bili_pack/i18n.py
@@ -4,5 +4,10 @@ N("TaskErrors", "获取二维码失败")
N("TaskErrors", "二维码接口返回了不完整的数据")
N("TaskErrors", "登录成功,但未能提取到有效 Cookie")
+N("TaskErrors", "获取验证码失败")
+N("TaskErrors", "验证码接口返回了不完整的数据")
+N("TaskErrors", "验证码发送失败")
+N("TaskErrors", "登录失败")
+
N("TaskErrors", "未获取到视频流地址")
N("TaskErrors", "字幕下载失败")
diff --git a/tests/test_task_service.py b/tests/test_task_service.py
index 604402d3..7a420a8d 100644
--- a/tests/test_task_service.py
+++ b/tests/test_task_service.py
@@ -12,9 +12,6 @@ import pytest
from app.models.task import Task, TaskStep, TaskStatus
-# ── Stubs ──
-
-
@dataclass(kw_only=True)
class StubStep(TaskStep):
stepIndex: int = 0
@@ -83,9 +80,6 @@ class StubFileWatcher:
def removePath(self, _): pass
-# ── Fixtures ──
-
-
@pytest.fixture()
def service(qapp, monkeypatch, tmp_path):
from app.config.cfg import cfg
@@ -127,9 +121,6 @@ def makeFolderTask(taskId: str, name: str = "video.mp4") -> Task:
return task
-# ── S7: _deduplicateOutput ──
-
-
class TestDeduplicateOutput:
def test_no_conflict(self, service):
@@ -239,9 +230,6 @@ class TestDeduplicateOutput:
assert t2.name == "README(1)"
-# ── S7: add ──
-
-
class TestAdd:
def test_add_emits_signal(self, service, qtbot):
@@ -278,9 +266,6 @@ class TestAdd:
assert svc.taskById("deferred") is task
-# ── S7: pause ──
-
-
class TestPause:
def test_pause_emits_signal(self, service, qtbot):
@@ -307,7 +292,24 @@ class TestPause:
assert task.status == TaskStatus.PAUSED
-# ── S7: delete ──
+class TestStartAll:
+
+ def test_covers_paused_waiting_and_failed_but_not_completed(self, service):
+ svc, runner = service
+ paused = makeTask("sa-paused")
+ waiting = makeTask("sa-waiting")
+ failed = makeTask("sa-failed")
+ completed = makeTask("sa-completed")
+ for task in (paused, waiting, failed, completed):
+ svc.add(task, autoStart=False)
+ paused.setStatus(TaskStatus.PAUSED)
+ failed.setStatus(TaskStatus.FAILED)
+ completed.setStatus(TaskStatus.COMPLETED)
+
+ svc.startAll()
+
+ assert len(runner.dispatched) == 3
+ assert completed.status == TaskStatus.COMPLETED
class TestDelete:
@@ -328,9 +330,6 @@ class TestDelete:
assert svc.taskById("d2") is None
-# ── S7: queue ──
-
-
class TestQueue:
def test_max_parallel_respected(self, service, monkeypatch):
@@ -366,9 +365,6 @@ class TestQueue:
done(None)
-# ── S7: TaskQueue.moveToFront ──
-
-
class TestTaskQueueMoveToFront:
def make_queue(self, *ids):
@@ -425,9 +421,6 @@ class TestTaskQueueMoveToFront:
assert q.nextWaiting() == "b"
-# ── S7: TaskService.moveToFront ──
-
-
class TestMoveToFront:
def test_emits_queueChanged(self, service, monkeypatch, qtbot):
@@ -499,9 +492,6 @@ class TestMoveToFront:
svc.moveToFront(["ar1", "ar2"])
-# ── S7: redownload ──
-
-
class TestRedownload:
def test_redownload_resets_and_reschedules(self, service):
@@ -517,9 +507,6 @@ class TestRedownload:
assert len(runner.submitted) > initial_count
-# ── S7: edit ──
-
-
class TestEdit:
def test_edit_applies_options(self, service):