fix: 黄豆按站点方式保持登录并自动切换播放线路
This commit is contained in:
@@ -50,7 +50,6 @@ class LoginBody(BaseModel):
|
||||
host: str = ""
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
line: str = ""
|
||||
|
||||
|
||||
class AccountBody(BaseModel):
|
||||
@@ -116,16 +115,9 @@ def save_accounts(body: SavedAccountsBody):
|
||||
return {"accounts": hd_accounts.replace([item.model_dump() for item in body.accounts])}
|
||||
|
||||
|
||||
@router.post("/lines")
|
||||
def list_lines(body: TokenBody):
|
||||
return call(lambda: {"lines": hd_playlist.available_lines(body.host)})
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(body: LoginBody):
|
||||
def action():
|
||||
client.play_line = (body.line or "").strip()
|
||||
client.save()
|
||||
entered = hd_login.enter(body.host)
|
||||
if body.username.strip() and body.password:
|
||||
return hd_login.login_account(body.username, body.password)
|
||||
@@ -221,6 +213,7 @@ def list_episodes(body: PlayBody):
|
||||
"type": ep.get("type") or "",
|
||||
"media": "file" if (ep.get("src_kind") == "file" or is_direct_media(ep.get("src") or "")) else "hls",
|
||||
"is_preview": bool(ep.get("is_preview")),
|
||||
"lines": len(ep.get("line_urls") or []),
|
||||
"preview_seconds": ep.get("preview_seconds") or 0,
|
||||
"locked_reason": ep.get("locked_reason") or "",
|
||||
}
|
||||
@@ -291,11 +284,14 @@ def play_key(vid: str, cid: int):
|
||||
|
||||
|
||||
@router.get("/play/{vid}/{cid}/index.m3u8")
|
||||
def episode_playlist(vid: str, cid: int):
|
||||
def episode_playlist(vid: str, cid: int, line: int = 0):
|
||||
row = hd_playlist.episode_src(vid, cid)
|
||||
src = str(row.get("src") or "").strip()
|
||||
src = hd_playlist.pick_line(row, line)
|
||||
if not src:
|
||||
raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址")
|
||||
detail = row.get("locked_reason") or "这一集还没有可播放的地址"
|
||||
if line > 0:
|
||||
detail = "没有下一条线路"
|
||||
raise HTTPException(status_code=404, detail=detail)
|
||||
try:
|
||||
text = hd_playlist.playback_playlist(src)
|
||||
key = str(row.get("hls_key") or "").strip()
|
||||
|
||||
@@ -669,6 +669,23 @@ class DownloadManager:
|
||||
live.touch()
|
||||
|
||||
def _download_episode(self, drama_id: str, folder: Path, row: dict) -> None:
|
||||
sources = _source_candidates(row)
|
||||
if not sources:
|
||||
self._set_phase(drama_id, row["cid"], "skipped")
|
||||
return
|
||||
source_dir, _mp4_path = self._episode_paths(folder, row)
|
||||
for index, src in enumerate(sources):
|
||||
attempt = dict(row)
|
||||
attempt["src"] = src
|
||||
try:
|
||||
self._download_one_source(drama_id, folder, attempt)
|
||||
return
|
||||
except RuntimeError as exc:
|
||||
if str(exc) == "已停止" or index + 1 == len(sources):
|
||||
raise
|
||||
_clear_source_files(source_dir)
|
||||
|
||||
def _download_one_source(self, drama_id: str, folder: Path, row: dict) -> None:
|
||||
if not row.get("src"):
|
||||
self._set_phase(drama_id, row["cid"], "skipped")
|
||||
return
|
||||
@@ -869,6 +886,26 @@ class DownloadManager:
|
||||
)
|
||||
|
||||
|
||||
def _source_candidates(row: dict) -> list[str]:
|
||||
urls = []
|
||||
src = str(row.get("src") or "").strip()
|
||||
if src:
|
||||
urls.append(src)
|
||||
for item in row.get("line_urls") or []:
|
||||
text = str(item or "").strip()
|
||||
if text and text not in urls:
|
||||
urls.append(text)
|
||||
return urls
|
||||
|
||||
|
||||
def _clear_source_files(source_dir: Path) -> None:
|
||||
if not source_dir.is_dir():
|
||||
return
|
||||
for child in source_dir.iterdir():
|
||||
if child.is_file():
|
||||
child.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _keep_finished_episode(phase: str, mp4_path: Path) -> bool:
|
||||
return phase == "done" and mp4_path.is_file() and mp4_path.stat().st_size > 0
|
||||
|
||||
|
||||
+11
-1
@@ -127,7 +127,17 @@ class HttpClient:
|
||||
options["content"] = content
|
||||
if timeout is not None:
|
||||
options["timeout"] = timeout
|
||||
return self._client_locked().request(method, url, **options)
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
return self._client_locked().request(method, url, **options)
|
||||
except (httpx.HTTPError, TimeoutError, OSError) as exc:
|
||||
last_error = exc
|
||||
with self._lock:
|
||||
self._close_locked()
|
||||
if attempt < 2:
|
||||
time.sleep(0.4 * (attempt + 1))
|
||||
raise RuntimeError(f"请求失败: {last_error}")
|
||||
|
||||
def get_bytes(self, url: str, headers: dict | None = None) -> tuple[bytes, str]:
|
||||
hdrs = {"User-Agent": "RaptDrama"}
|
||||
|
||||
@@ -39,6 +39,9 @@ def login_device(*, force_new: bool = False) -> dict:
|
||||
if not token:
|
||||
raise RuntimeError("设备登录没有返回 token")
|
||||
client.token = token
|
||||
remember_login_user(data, account=False)
|
||||
client._renew_blocked.discard("guest")
|
||||
client.save()
|
||||
return data
|
||||
|
||||
|
||||
@@ -64,16 +67,44 @@ def login_username(username: str, password: str, channel_code: str = "") -> dict
|
||||
raise RuntimeError("账号登录没有返回 token")
|
||||
client.account_token = token
|
||||
client.account_username = username.strip()
|
||||
remember_login_user(data, account=True)
|
||||
client._renew_blocked.discard("account")
|
||||
client.save()
|
||||
return data
|
||||
|
||||
|
||||
def user_info(*, identity: str = "guest") -> dict:
|
||||
data = client.request("/user/info", {}, auth=True, identity=identity)
|
||||
return data if isinstance(data, dict) else {}
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
uid = str(data.get("user_id") or data.get("id") or "").strip()
|
||||
if uid:
|
||||
if identity == "account":
|
||||
client.account_user_id = uid
|
||||
else:
|
||||
client.user_id = uid
|
||||
client.save()
|
||||
return data
|
||||
|
||||
|
||||
def system_info() -> dict:
|
||||
def remember_login_user(data: dict, *, account: bool) -> None:
|
||||
uid = ""
|
||||
if isinstance(data, dict):
|
||||
uid = str(data.get("user_id") or data.get("id") or "").strip()
|
||||
for key in ("user", "userInfo", "user_info", "info"):
|
||||
nested = data.get(key)
|
||||
if isinstance(nested, dict) and not uid:
|
||||
uid = str(nested.get("user_id") or nested.get("id") or "").strip()
|
||||
if not uid:
|
||||
return
|
||||
if account:
|
||||
client.account_user_id = uid
|
||||
else:
|
||||
client.user_id = uid
|
||||
|
||||
|
||||
def system_info(*, identity: str = "") -> dict:
|
||||
chosen = identity or ("account" if client.account_token else "guest")
|
||||
data = client.request(
|
||||
"/system/info",
|
||||
{
|
||||
@@ -81,14 +112,43 @@ def system_info() -> dict:
|
||||
"channel_code": "",
|
||||
"share_code": "",
|
||||
"clipboard_text": "",
|
||||
"device_info": device_info(),
|
||||
"package_name": "",
|
||||
"device_info": device_info(chosen),
|
||||
"package_name": "dfa03",
|
||||
},
|
||||
auth=True,
|
||||
identity=chosen,
|
||||
)
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def remember_api_lines(info: dict | None = None) -> list[str]:
|
||||
if info is None:
|
||||
identities = ["account", "guest"] if client.account_token else ["guest"]
|
||||
info = {}
|
||||
for name in identities:
|
||||
try:
|
||||
info = system_info(identity=name)
|
||||
break
|
||||
except TokenExpired:
|
||||
continue
|
||||
except RuntimeError:
|
||||
return list(client.api_lines)
|
||||
else:
|
||||
return list(client.api_lines)
|
||||
if not isinstance(info, dict) or "api_lines" not in info:
|
||||
return list(client.api_lines)
|
||||
hosts = []
|
||||
for item in info.get("api_lines") or []:
|
||||
if not isinstance(item, str) or not item.startswith("https://"):
|
||||
continue
|
||||
host = item.rstrip("/")
|
||||
if host not in hosts:
|
||||
hosts.append(host)
|
||||
client.api_lines = hosts
|
||||
client.save()
|
||||
return hosts
|
||||
|
||||
|
||||
def nav_list() -> list[dict]:
|
||||
data = client.request("/drama/navList", {"with_filters": "1"}, auth=True)
|
||||
rows = _list_of(data)
|
||||
|
||||
@@ -34,6 +34,36 @@ class TokenExpired(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _connection_error(exc: BaseException) -> bool:
|
||||
text = str(exc).lower()
|
||||
return any(
|
||||
word in text
|
||||
for word in (
|
||||
"ssl",
|
||||
"unexpected_eof",
|
||||
"connection",
|
||||
"timed out",
|
||||
"timeout",
|
||||
"10054",
|
||||
"10060",
|
||||
"连接",
|
||||
"重置",
|
||||
"强迫关闭",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def present_token(token: str, user_id: str) -> str:
|
||||
token = (token or "").strip()
|
||||
user_id = (user_id or "").strip()
|
||||
if not token or not user_id:
|
||||
return token
|
||||
suffix = f"_{user_id}"
|
||||
if token.endswith(suffix):
|
||||
return token
|
||||
return token + suffix
|
||||
|
||||
|
||||
class ApiError(RuntimeError):
|
||||
def __init__(self, message: str, code=None) -> None:
|
||||
super().__init__(message)
|
||||
@@ -50,9 +80,16 @@ class HuangdouClient:
|
||||
self.guest_session_id = ""
|
||||
self.guest_device_info: dict = {}
|
||||
self.token = ""
|
||||
self.user_id = ""
|
||||
self.account_token = ""
|
||||
self.account_user_id = ""
|
||||
self.account_username = ""
|
||||
self.renew_account = None
|
||||
self.renew_guest = None
|
||||
self._renewing = False
|
||||
self._renew_blocked: set[str] = set()
|
||||
self.play_line = ""
|
||||
self.api_lines: list[str] = []
|
||||
self.host = DEFAULT_HOST
|
||||
self.profile: dict = {}
|
||||
self._load()
|
||||
@@ -79,9 +116,14 @@ class HuangdouClient:
|
||||
if isinstance(guest_info, dict) and guest_info:
|
||||
self.guest_device_info = dict(guest_info)
|
||||
self.token = str(data.get("token") or "")
|
||||
self.user_id = str(data.get("user_id") or "")
|
||||
self.account_token = str(data.get("account_token") or "")
|
||||
self.account_user_id = str(data.get("account_user_id") or "")
|
||||
self.account_username = str(data.get("account_username") or "")
|
||||
self.play_line = str(data.get("play_line") or "")
|
||||
lines = data.get("api_lines")
|
||||
if isinstance(lines, list):
|
||||
self.api_lines = [str(item).rstrip("/") for item in lines if str(item).startswith("https://")]
|
||||
host = str(data.get("host") or "")
|
||||
if host.startswith("http://") or host.startswith("https://"):
|
||||
self.host = host.rstrip("/")
|
||||
@@ -100,9 +142,12 @@ class HuangdouClient:
|
||||
"guest_session_id": self.guest_session_id,
|
||||
"guest_device_info": self.guest_device_info,
|
||||
"token": self.token,
|
||||
"user_id": self.user_id,
|
||||
"account_token": self.account_token,
|
||||
"account_user_id": self.account_user_id,
|
||||
"account_username": self.account_username,
|
||||
"play_line": self.play_line,
|
||||
"api_lines": self.api_lines,
|
||||
"host": self.host,
|
||||
"profile": self.profile,
|
||||
}
|
||||
@@ -150,6 +195,7 @@ class HuangdouClient:
|
||||
self.guest_session_id = session_id_of("")
|
||||
self.guest_device_info = self._new_device_info()
|
||||
self.token = ""
|
||||
self.user_id = ""
|
||||
self.save()
|
||||
|
||||
def roll_account_fingerprint(self) -> None:
|
||||
@@ -160,6 +206,7 @@ class HuangdouClient:
|
||||
self.device_info = info
|
||||
self.device_info_source = "fixed"
|
||||
self.account_token = ""
|
||||
self.account_user_id = ""
|
||||
self.save()
|
||||
|
||||
def clear_token(self) -> None:
|
||||
@@ -168,7 +215,9 @@ class HuangdouClient:
|
||||
self.guest_session_id = ""
|
||||
self.guest_device_info = {}
|
||||
self.account_token = ""
|
||||
self.account_user_id = ""
|
||||
self.account_username = ""
|
||||
self.user_id = ""
|
||||
self.profile = {}
|
||||
self.save()
|
||||
|
||||
@@ -180,26 +229,71 @@ class HuangdouClient:
|
||||
return self.host
|
||||
|
||||
def request(self, path: str, data: dict | None = None, *, auth: bool = True, identity: str = "guest") -> dict | list | None:
|
||||
try:
|
||||
return self._dispatch(path, data, auth=auth, identity=identity)
|
||||
except TokenExpired:
|
||||
if not auth or self._renewing or identity in self._renew_blocked:
|
||||
raise
|
||||
self._renewing = True
|
||||
try:
|
||||
renew = self.renew_account if identity == "account" else self.renew_guest
|
||||
renewed = bool(renew and renew())
|
||||
finally:
|
||||
self._renewing = False
|
||||
if not renewed:
|
||||
self._renew_blocked.add(identity)
|
||||
raise
|
||||
self._renew_blocked.discard(identity)
|
||||
return self._dispatch(path, data, auth=auth, identity=identity)
|
||||
|
||||
def _dispatch(self, path: str, data: dict | None, *, auth: bool, identity: str) -> dict | list | None:
|
||||
token, device_id, session_id, info = self._identity(identity, auth)
|
||||
user_agent = str((info or {}).get("userAgent") or USER_AGENT)
|
||||
last_error: Exception | None = None
|
||||
for _ in range(2):
|
||||
try:
|
||||
return self._call(
|
||||
self.host,
|
||||
path,
|
||||
data or {},
|
||||
token=token,
|
||||
device_id=device_id,
|
||||
session_id=session_id,
|
||||
user_agent=user_agent,
|
||||
)
|
||||
except (TokenExpired, ApiError):
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
last_error = exc
|
||||
hosts = [self.host] if token else self._request_hosts()
|
||||
for host in hosts:
|
||||
for _ in range(2):
|
||||
try:
|
||||
payload = self._call(
|
||||
host,
|
||||
path,
|
||||
data or {},
|
||||
token=self._presented_token(token, identity) if auth else "",
|
||||
device_id=device_id,
|
||||
session_id=session_id,
|
||||
user_agent=user_agent,
|
||||
)
|
||||
if host != self.host:
|
||||
self.host = host
|
||||
self.save()
|
||||
return payload
|
||||
except (TokenExpired, ApiError):
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
last_error = exc
|
||||
if not _connection_error(exc):
|
||||
raise
|
||||
raise last_error or RuntimeError("网络请求异常")
|
||||
|
||||
def _presented_token(self, token: str, identity: str) -> str:
|
||||
if identity == "account":
|
||||
user_id = self.account_user_id
|
||||
if not user_id and self.account_token:
|
||||
profile = self.profile if isinstance(self.profile, dict) else {}
|
||||
if str(profile.get("has_login") or "") == "1":
|
||||
user_id = str(profile.get("id") or "")
|
||||
else:
|
||||
user_id = self.user_id
|
||||
return present_token(token, user_id)
|
||||
|
||||
def _request_hosts(self) -> list[str]:
|
||||
hosts = []
|
||||
for host in [self.host, *self.api_lines]:
|
||||
text = str(host or "").rstrip("/")
|
||||
if text.startswith("https://") and text not in hosts:
|
||||
hosts.append(text)
|
||||
return hosts or [self.host]
|
||||
|
||||
def _identity(self, identity: str, auth: bool) -> tuple[str, str, str, dict]:
|
||||
if identity == "account":
|
||||
self._ensure_fingerprint()
|
||||
@@ -251,6 +345,8 @@ class HuangdouClient:
|
||||
try:
|
||||
response = http.send("POST", url, headers=headers, content=encrypt_body(body, request_id), timeout=30.0)
|
||||
except Exception as exc:
|
||||
if _connection_error(exc):
|
||||
raise RuntimeError("连接中断,请再试一次") from exc
|
||||
raise RuntimeError(f"请求失败: {exc}") from exc
|
||||
if response.status_code != 200:
|
||||
raise RuntimeError(f"网络请求异常 ({response.status_code})")
|
||||
|
||||
@@ -12,7 +12,7 @@ from cryptography.hazmat.primitives.padding import PKCS7
|
||||
WEB_AES_KEY = "7961beb44246e3012ce228d6b5ced05a"
|
||||
IMAGE_AES_KEY = "525202f9149e061d"
|
||||
SIGN_PREFIX = "Dart"
|
||||
APP_VERSION = "2.0.0"
|
||||
APP_VERSION = "1.0.0"
|
||||
DEVICE_TYPE = "web"
|
||||
LANG = "zh-CN"
|
||||
USER_AGENT = (
|
||||
|
||||
@@ -6,8 +6,6 @@ from server.services.huangdou.covers import covers as huangdou_covers
|
||||
def enter(host: str = "") -> dict:
|
||||
if host:
|
||||
client.set_host(host)
|
||||
client.account_token = ""
|
||||
client.account_username = ""
|
||||
client.roll_guest_fingerprint()
|
||||
raw = api.login_device(force_new=False)
|
||||
guest = _user_from_login(raw)
|
||||
@@ -19,6 +17,7 @@ def enter(host: str = "") -> dict:
|
||||
profile = public_profile(None)
|
||||
client.profile = profile
|
||||
client.save()
|
||||
api.remember_api_lines()
|
||||
return {"token": client.token, "profile": profile}
|
||||
|
||||
|
||||
@@ -44,6 +43,7 @@ def login_account(username: str, password: str, rotate_fingerprint: bool = False
|
||||
profile = public_profile(info if isinstance(info, dict) else {})
|
||||
client.profile = profile
|
||||
client.save()
|
||||
api.remember_api_lines()
|
||||
return {"token": client.token, "profile": profile}
|
||||
|
||||
|
||||
@@ -169,6 +169,40 @@ def _truthy(value) -> bool:
|
||||
return text in {"1", "true", "y", "yes", "vip"}
|
||||
|
||||
|
||||
def _renew_account() -> bool:
|
||||
from server.services.huangdou.accounts import load
|
||||
|
||||
username = client.account_username.strip()
|
||||
if not username:
|
||||
return False
|
||||
password = ""
|
||||
for item in load():
|
||||
if item.get("username") == username:
|
||||
password = str(item.get("password") or "")
|
||||
break
|
||||
if not password:
|
||||
return False
|
||||
try:
|
||||
api.login_username(username, password)
|
||||
except Exception:
|
||||
return False
|
||||
return bool(client.account_token)
|
||||
|
||||
|
||||
def _renew_guest() -> bool:
|
||||
if not client.guest_device_id:
|
||||
return False
|
||||
try:
|
||||
api.login_device(force_new=False)
|
||||
except Exception:
|
||||
return False
|
||||
return bool(client.token)
|
||||
|
||||
|
||||
client.renew_account = _renew_account
|
||||
client.renew_guest = _renew_guest
|
||||
|
||||
|
||||
def _number(value) -> int:
|
||||
try:
|
||||
return int(float(str(value or "0")))
|
||||
|
||||
@@ -53,12 +53,13 @@ def episode_src(drama_id: str, cid: int) -> dict:
|
||||
row = _cached_row(drama_id, cid, refresh=True)
|
||||
if not row:
|
||||
return {}
|
||||
if not row.get("playable") or row.get("src"):
|
||||
return row
|
||||
played = _play_rows(drama_id, [dict(row)], allow_buy=False)
|
||||
updated = played[0] if played else row
|
||||
_store_row(drama_id, updated)
|
||||
return updated
|
||||
stale = not row.get("lines_ready")
|
||||
if (row.get("playable") and stale) or row.get("locked_reason") == "登录已失效":
|
||||
played = _play_rows(drama_id, [dict(row)], allow_buy=False)
|
||||
updated = played[0] if played else row
|
||||
_store_row(drama_id, updated)
|
||||
return updated
|
||||
return row
|
||||
|
||||
|
||||
def playback_playlist(src: str) -> str:
|
||||
@@ -102,86 +103,97 @@ def store_fallback_key(source_dir: Path, key: str) -> None:
|
||||
(source_dir / "hls.key").write_bytes(raw)
|
||||
|
||||
|
||||
def line_options(played: dict) -> list[dict]:
|
||||
found = []
|
||||
seen: set[str] = set()
|
||||
def _preview_url(url: str) -> bool:
|
||||
path = (url or "").split("?", 1)[0].lower()
|
||||
return path.endswith("preview.mp4") or "/preview." in path
|
||||
|
||||
|
||||
def _line_urls(played: dict, *, allow_preview: bool) -> list[str]:
|
||||
urls: list[str] = []
|
||||
|
||||
def add(value) -> None:
|
||||
url = str(value or "").strip()
|
||||
if not url or url in urls:
|
||||
return
|
||||
if not allow_preview and _preview_url(url):
|
||||
return
|
||||
urls.append(url)
|
||||
|
||||
lines = played.get("lines") if isinstance(played.get("lines"), list) else []
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
name = str(line.get("name") or "").strip()
|
||||
url = str(line.get("url") or "").strip()
|
||||
if not name or not url or name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
found.append({"name": name, "label": name})
|
||||
return found
|
||||
if isinstance(line, dict):
|
||||
add(line.get("url"))
|
||||
add(played.get("m3u8"))
|
||||
if allow_preview:
|
||||
add(played.get("preview_m3u8"))
|
||||
return urls
|
||||
|
||||
|
||||
def available_lines(host: str = "") -> list[dict]:
|
||||
if host:
|
||||
client.set_host(host)
|
||||
rows = _guest_rows(lambda: api.drama_list(page=1, page_size=3))
|
||||
last_error = "没有读到线路"
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
drama_id = str(item.get("id") or "").strip()
|
||||
if not drama_id:
|
||||
continue
|
||||
try:
|
||||
played = _guest_rows(lambda current=drama_id: api.drama_play(current, 1))
|
||||
except RuntimeError as exc:
|
||||
last_error = str(exc) or last_error
|
||||
continue
|
||||
if not isinstance(played, dict):
|
||||
continue
|
||||
lines = line_options(played)
|
||||
if lines:
|
||||
return lines
|
||||
raise RuntimeError(last_error)
|
||||
|
||||
|
||||
def _guest_rows(load):
|
||||
def _open_src(url: str) -> tuple[str, str] | None:
|
||||
if is_direct_media(url):
|
||||
return None if _preview_url(url) else (url, "file")
|
||||
try:
|
||||
if not client.token:
|
||||
api.login_device()
|
||||
return load()
|
||||
except TokenExpired:
|
||||
api.login_device()
|
||||
return load()
|
||||
text = http.read_text(url, headers=_cdn_headers())
|
||||
except Exception:
|
||||
return None
|
||||
if "#EXTM3U" not in text.upper():
|
||||
return None
|
||||
return url, "hls"
|
||||
|
||||
|
||||
def _choose_src(played: dict) -> tuple[str, str]:
|
||||
selected = (client.play_line or "").strip()
|
||||
lines = played.get("lines") if isinstance(played.get("lines"), list) else []
|
||||
named: list[tuple[str, str]] = []
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
name = str(line.get("name") or "").strip()
|
||||
url = str(line.get("url") or "").strip()
|
||||
if url:
|
||||
named.append((name, url))
|
||||
ordered = []
|
||||
if selected:
|
||||
ordered.extend(url for name, url in named if name == selected)
|
||||
ordered.extend(url for _name, url in named)
|
||||
m3u8 = str(played.get("m3u8") or "").strip()
|
||||
if m3u8:
|
||||
ordered.append(m3u8)
|
||||
preview = str(played.get("preview_m3u8") or "").strip()
|
||||
if preview:
|
||||
ordered.append(preview)
|
||||
for url in ordered:
|
||||
if url and not is_direct_media(url):
|
||||
urls = _line_urls(played, allow_preview=False) or _line_urls(played, allow_preview=True)
|
||||
for url in urls:
|
||||
if not is_direct_media(url):
|
||||
return url, "hls"
|
||||
for url in ordered:
|
||||
if is_direct_media(url):
|
||||
for url in urls:
|
||||
if is_direct_media(url) and not _preview_url(url):
|
||||
return url, "file"
|
||||
return "", ""
|
||||
|
||||
|
||||
def _ordered_line_urls(played: dict, src: str) -> list[str]:
|
||||
urls = _line_urls(played, allow_preview=False)
|
||||
chosen = (src or "").strip()
|
||||
if chosen and not _preview_url(chosen):
|
||||
urls = [chosen, *[url for url in urls if url != chosen]]
|
||||
return urls
|
||||
|
||||
|
||||
def pick_line(row: dict, line: int) -> str:
|
||||
urls: list[str] = []
|
||||
for item in row.get("line_urls") or []:
|
||||
text = str(item or "").strip()
|
||||
if text and text not in urls and not _preview_url(text):
|
||||
urls.append(text)
|
||||
src = str(row.get("src") or "").strip()
|
||||
if src and not _preview_url(src) and src not in urls:
|
||||
urls.insert(0, src)
|
||||
if line < 0:
|
||||
line = 0
|
||||
if not urls:
|
||||
return src if line == 0 else ""
|
||||
if line >= len(urls):
|
||||
return ""
|
||||
return urls[line]
|
||||
|
||||
|
||||
def _resolve_src(played: dict, *, allow_preview: bool) -> tuple[str, str]:
|
||||
for url in _line_urls(played, allow_preview=False):
|
||||
opened = _open_src(url)
|
||||
if opened:
|
||||
return opened
|
||||
if not allow_preview:
|
||||
return "", ""
|
||||
for url in _line_urls(played, allow_preview=True):
|
||||
if _preview_url(url) and is_direct_media(url):
|
||||
return url, "file"
|
||||
opened = _open_src(url)
|
||||
if opened:
|
||||
return opened
|
||||
return "", ""
|
||||
|
||||
|
||||
def apply_hls_key(text: str, source_dir: Path, key: str) -> str:
|
||||
secret = (key or "").strip()
|
||||
if not secret:
|
||||
@@ -265,6 +277,8 @@ def _skeleton_row(item: dict, *, account_vip: bool) -> dict | None:
|
||||
"duration": _int(item.get("duration")),
|
||||
"methods": item.get("methods") if isinstance(item.get("methods"), list) else [],
|
||||
"is_preview": False,
|
||||
"line_urls": [],
|
||||
"lines_ready": False,
|
||||
"preview_seconds": 0,
|
||||
"preview_m3u8": "",
|
||||
"hls_key": "",
|
||||
@@ -282,6 +296,7 @@ def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[
|
||||
if not allow_buy or not client.account_token:
|
||||
row["src"] = ""
|
||||
row["playable"] = False
|
||||
row["lines_ready"] = True
|
||||
row["locked_reason"] = public_lock_reason(row, row.get("locked_reason") or "")
|
||||
return row
|
||||
try:
|
||||
@@ -289,36 +304,47 @@ def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[
|
||||
except RuntimeError as exc:
|
||||
row["src"] = ""
|
||||
row["playable"] = False
|
||||
row["lines_ready"] = True
|
||||
row["locked_reason"] = public_lock_reason(row, str(exc))
|
||||
return row
|
||||
row["is_buy"] = True
|
||||
row["needs_coin"] = False
|
||||
row["points"] = 0
|
||||
vip_episode = episode_kind(row) in VIP_TYPES
|
||||
identity = "account" if _uses_account(row) else "guest"
|
||||
try:
|
||||
played = api.drama_play(drama_id, int(row["cid"]), identity=identity)
|
||||
except TokenExpired:
|
||||
row["src"] = ""
|
||||
row["playable"] = False
|
||||
row["is_preview"] = False
|
||||
row["lines_ready"] = False
|
||||
row["locked_reason"] = "登录已失效"
|
||||
return row
|
||||
except RuntimeError as exc:
|
||||
row["src"] = ""
|
||||
row["playable"] = False
|
||||
row["lines_ready"] = True
|
||||
row["locked_reason"] = public_lock_reason(row, str(exc))
|
||||
return row
|
||||
preview = str(played.get("preview_m3u8") or "").strip()
|
||||
row["hls_key"] = str(played.get("hls_key") or "").strip()
|
||||
row["is_preview"] = played.get("is_preview") is True
|
||||
row["preview_seconds"] = _int(played.get("preview_seconds"))
|
||||
row["preview_m3u8"] = preview
|
||||
src, kind = _choose_src(played)
|
||||
src, kind = _resolve_src(played, allow_preview=not vip_episode)
|
||||
row["src"] = src
|
||||
row["src_kind"] = kind
|
||||
row["line_urls"] = _ordered_line_urls(played, src)
|
||||
row["lines_ready"] = True
|
||||
if src:
|
||||
row["playable"] = True
|
||||
if kind == "file" or row["is_preview"]:
|
||||
row["is_preview"] = True
|
||||
row["is_preview"] = (not vip_episode) and (kind == "file" and _preview_url(src) or played.get("is_preview") is True and _preview_url(src))
|
||||
row["locked_reason"] = ""
|
||||
row["points"] = 0
|
||||
else:
|
||||
row["playable"] = False
|
||||
row["locked_reason"] = _lock_reason(row)
|
||||
row["is_preview"] = False
|
||||
row["locked_reason"] = _vip_lock_reason(row) if vip_episode else _lock_reason(row)
|
||||
return row
|
||||
|
||||
updated = []
|
||||
@@ -333,6 +359,20 @@ def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[
|
||||
return updated
|
||||
|
||||
|
||||
def _vip_lock_reason(row: dict) -> str:
|
||||
if not client.account_token:
|
||||
return "需要 VIP"
|
||||
try:
|
||||
api.user_info(identity="account")
|
||||
except TokenExpired:
|
||||
client.account_token = ""
|
||||
client.save()
|
||||
return "登录已失效"
|
||||
except RuntimeError:
|
||||
return "这一集暂时不能播放"
|
||||
return "这一集暂时不能播放"
|
||||
|
||||
|
||||
def _uses_account(row: dict) -> bool:
|
||||
if not client.account_token:
|
||||
return False
|
||||
@@ -366,12 +406,14 @@ def _keep_sources(cached: list[dict], fresh: list[dict]) -> list[dict]:
|
||||
merged = []
|
||||
for row in fresh:
|
||||
old = previous.get(int(row["cid"]))
|
||||
if old and old.get("is_preview"):
|
||||
if old and old.get("is_preview") and episode_kind(row) not in VIP_TYPES:
|
||||
row["is_preview"] = True
|
||||
if row.get("playable") and old and old.get("src") and not old.get("is_preview"):
|
||||
row["src"] = old.get("src") or ""
|
||||
row["src_kind"] = old.get("src_kind") or ""
|
||||
row["hls_key"] = old.get("hls_key") or ""
|
||||
row["line_urls"] = old.get("line_urls") or []
|
||||
row["lines_ready"] = bool(old.get("lines_ready"))
|
||||
row["preview_seconds"] = old.get("preview_seconds") or 0
|
||||
row["preview_m3u8"] = old.get("preview_m3u8") or ""
|
||||
merged.append(row)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from server.services.downloads import _local_master
|
||||
from server.services.huangdou.playlist import _choose_src
|
||||
from server.services.huangdou.client import present_token
|
||||
from server.services.huangdou.playlist import _choose_src, _ordered_line_urls, pick_line
|
||||
from server.services.playlist import expand_variant, is_direct_media, is_media_playlist
|
||||
|
||||
|
||||
@@ -21,27 +22,15 @@ def test_direct_media_and_hls_choice() -> None:
|
||||
assert kind == "hls"
|
||||
assert src.endswith("play.m3u8?x=1")
|
||||
|
||||
from server.services.huangdou.client import client
|
||||
|
||||
client.play_line = "line2"
|
||||
src, kind = _choose_src({
|
||||
"m3u8": "https://host.example/play.m3u8?line=free",
|
||||
"m3u8": "https://host.example/chapters/3/preview.mp4",
|
||||
"lines": [
|
||||
{"name": "free", "url": "https://host.example/play.m3u8?line=free"},
|
||||
{"name": "line2", "url": "https://host.example/play.m3u8?line=line2"},
|
||||
{"name": "free", "url": "https://host.example/chapters/3/preview.mp4"},
|
||||
{"name": "line2", "url": "https://host.example/chapters/3/play.m3u8"},
|
||||
],
|
||||
})
|
||||
assert kind == "hls"
|
||||
assert "line=line2" in src
|
||||
client.play_line = ""
|
||||
src, kind = _choose_src({
|
||||
"m3u8": "https://host.example/play.m3u8?line=free",
|
||||
"lines": [
|
||||
{"name": "free", "url": "https://host.example/play.m3u8?line=free"},
|
||||
{"name": "line2", "url": "https://host.example/play.m3u8?line=line2"},
|
||||
],
|
||||
})
|
||||
assert "line=free" in src
|
||||
assert src.endswith("play.m3u8")
|
||||
|
||||
src, kind = _choose_src({
|
||||
"m3u8": "",
|
||||
@@ -51,6 +40,24 @@ def test_direct_media_and_hls_choice() -> None:
|
||||
assert kind == "file"
|
||||
assert src.endswith(".mp4")
|
||||
|
||||
played = {
|
||||
"m3u8": "https://host.example/api/drama/hls/id/3/play.m3u8?line=free",
|
||||
"preview_m3u8": "https://cdn.example/chapters/3/preview.mp4",
|
||||
"lines": [
|
||||
{"name": "free", "url": "https://host.example/api/drama/hls/id/3/play.m3u8?line=free"},
|
||||
{"name": "line2", "url": "https://host.example/api/drama/hls/id/3/play.m3u8?line=line2"},
|
||||
{"name": "line3", "url": "https://host.example/api/drama/hls/id/3/play.m3u8?line=line3"},
|
||||
],
|
||||
}
|
||||
ordered = _ordered_line_urls(played, played["lines"][1]["url"])
|
||||
assert [item.split("line=")[1] for item in ordered] == ["line2", "free", "line3"]
|
||||
row = {"src": ordered[0], "line_urls": ordered}
|
||||
assert pick_line(row, 0).endswith("line=line2")
|
||||
assert pick_line(row, 1).endswith("line=free")
|
||||
assert pick_line(row, 3) == ""
|
||||
assert pick_line({"src": "https://cdn.example/chapters/3/preview.mp4", "line_urls": []}, 0).endswith("preview.mp4")
|
||||
assert pick_line({"src": "https://cdn.example/chapters/3/preview.mp4", "line_urls": []}, 1) == ""
|
||||
|
||||
try:
|
||||
expand_variant("https://cdn.example/preview-r10.mp4")
|
||||
except RuntimeError as exc:
|
||||
@@ -59,6 +66,14 @@ def test_direct_media_and_hls_choice() -> None:
|
||||
raise AssertionError("mp4 不应走播放列表")
|
||||
|
||||
|
||||
def test_request_token_includes_user_id() -> None:
|
||||
assert present_token("abc", "12345678") == "abc_12345678"
|
||||
assert present_token("a_bc", "12345678") == "a_bc_12345678"
|
||||
assert present_token("abc_12345678", "12345678") == "abc_12345678"
|
||||
assert present_token("abc", "") == "abc"
|
||||
assert present_token("", "12345678") == ""
|
||||
|
||||
|
||||
def test_catalog_follows_pages_until_the_api_stops() -> None:
|
||||
from server.services.huangdou.catalog import _take_new
|
||||
|
||||
@@ -81,5 +96,6 @@ def test_catalog_follows_pages_until_the_api_stops() -> None:
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_direct_media_and_hls_choice()
|
||||
test_request_token_includes_user_id()
|
||||
test_catalog_follows_pages_until_the_api_stops()
|
||||
print("ok")
|
||||
|
||||
+3
-62
@@ -100,7 +100,6 @@ const ACCOUNTS_KEY = "rapt-accounts";
|
||||
const PLATFORM_KEY = "rapt-platform";
|
||||
const DRAMABOX_LANG_KEY = "dramabox-language";
|
||||
const HUANGDOU_HOST_KEY = "huangdou-host";
|
||||
const HUANGDOU_LINE_KEY = "huangdou-line";
|
||||
const HUANGDOU_ACCOUNTS_KEY = "huangdou-accounts";
|
||||
const HUANGDOU_REMEMBER_KEY = "huangdou-remember";
|
||||
const DRAMABOX_DEVICE_KEY = "dramabox-device";
|
||||
@@ -130,9 +129,6 @@ const platformLabel = computed(() => {
|
||||
});
|
||||
const dramaboxLang = ref("th");
|
||||
const huangdouHost = ref(readHuangdouHost());
|
||||
const huangdouLine = ref(readHuangdouLine());
|
||||
const huangdouLines = ref<{ name: string; label: string }[]>([]);
|
||||
const huangdouLinesBusy = ref(false);
|
||||
const huangdouUser = ref("");
|
||||
const huangdouPassword = ref("");
|
||||
const huangdouRemember = ref(readHuangdouRemember());
|
||||
@@ -267,14 +263,6 @@ function readHuangdouRemember() {
|
||||
}
|
||||
}
|
||||
|
||||
function readHuangdouLine() {
|
||||
try {
|
||||
return localStorage.getItem(HUANGDOU_LINE_KEY) || "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function readHuangdouHost() {
|
||||
try {
|
||||
const value = localStorage.getItem(HUANGDOU_HOST_KEY) || "";
|
||||
@@ -304,41 +292,7 @@ function selectPlatform(key: string) {
|
||||
void loadDramaboxLanguages();
|
||||
void loadDevices();
|
||||
}
|
||||
if (key === "huangdou") {
|
||||
void sendHuangdouFingerprint();
|
||||
void loadHuangdouLines();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadHuangdouLines() {
|
||||
huangdouLinesBusy.value = true;
|
||||
try {
|
||||
const host = huangdouHost.value.trim() || "https://pmihlvee.cc";
|
||||
const response = await fetch("/api/huangdou/lines", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ host }),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(typeof payload.detail === "string" ? payload.detail : "没有读到线路");
|
||||
}
|
||||
const rows = Array.isArray(payload.lines) ? payload.lines : [];
|
||||
huangdouLines.value = rows
|
||||
.map((item: { name?: string; label?: string }) => ({
|
||||
name: String(item?.name || "").trim(),
|
||||
label: String(item?.label || item?.name || "").trim(),
|
||||
}))
|
||||
.filter((item: { name: string }) => item.name);
|
||||
if (!huangdouLines.value.some((item) => item.name === huangdouLine.value)) {
|
||||
huangdouLine.value = huangdouLines.value[0]?.name || "";
|
||||
}
|
||||
} catch (exc) {
|
||||
huangdouLines.value = [];
|
||||
error.value = exc instanceof Error ? exc.message : "没有读到线路";
|
||||
} finally {
|
||||
huangdouLinesBusy.value = false;
|
||||
}
|
||||
if (key === "huangdou") void sendHuangdouFingerprint();
|
||||
}
|
||||
|
||||
function tokenKey() {
|
||||
@@ -1062,13 +1016,11 @@ async function loginHuangdou(asGuest = false) {
|
||||
const host = huangdouHost.value.trim() || "https://pmihlvee.cc";
|
||||
huangdouHost.value = host;
|
||||
localStorage.setItem(HUANGDOU_HOST_KEY, host);
|
||||
localStorage.setItem(HUANGDOU_LINE_KEY, huangdouLine.value);
|
||||
const response = await fetch("/api/huangdou/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
host,
|
||||
line: huangdouLine.value,
|
||||
username: asGuest ? "" : huangdouUser.value.trim(),
|
||||
password: asGuest ? "" : huangdouPassword.value,
|
||||
}),
|
||||
@@ -1363,10 +1315,7 @@ onMounted(async () => {
|
||||
await loadDramaboxLanguages();
|
||||
void loadDevices();
|
||||
}
|
||||
if (platform.value === "huangdou") {
|
||||
void sendHuangdouFingerprint();
|
||||
void loadHuangdouLines();
|
||||
}
|
||||
if (platform.value === "huangdou") void sendHuangdouFingerprint();
|
||||
let saved = readSavedToken();
|
||||
if (!saved && isolated.value) {
|
||||
try {
|
||||
@@ -1584,15 +1533,7 @@ onUnmounted(stopLive);
|
||||
<n-form label-placement="left" label-width="96" size="small" :show-feedback="false" @submit.prevent="login">
|
||||
<template v-if="platform === 'huangdou'">
|
||||
<n-form-item label="域名">
|
||||
<n-input v-model:value="huangdouHost" placeholder="https://pmihlvee.cc" @blur="loadHuangdouLines" />
|
||||
</n-form-item>
|
||||
<n-form-item label="线路">
|
||||
<n-select
|
||||
v-model:value="huangdouLine"
|
||||
:options="huangdouLines.map((item) => ({ label: item.label, value: item.name }))"
|
||||
:loading="huangdouLinesBusy"
|
||||
placeholder="选择线路"
|
||||
/>
|
||||
<n-input v-model:value="huangdouHost" placeholder="https://pmihlvee.cc" />
|
||||
</n-form-item>
|
||||
<n-form-item v-if="huangdouAccounts.length" label="已保存">
|
||||
<div class="device-line">
|
||||
|
||||
@@ -7,9 +7,11 @@ interface Episode {
|
||||
title: string;
|
||||
playable: boolean;
|
||||
points?: number;
|
||||
type?: string;
|
||||
media?: string;
|
||||
locked_reason?: string;
|
||||
is_preview?: boolean;
|
||||
lines?: number;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -68,10 +70,10 @@ function select(episode: Episode) {
|
||||
if (!episode.playable || episode.cid === current.value) return;
|
||||
current.value = episode.cid;
|
||||
error.value = "";
|
||||
void nextTick(() => attach(episode.cid));
|
||||
void nextTick(() => attach(episode.cid, 0));
|
||||
}
|
||||
|
||||
function attach(cid: number) {
|
||||
function attach(cid: number, line = 0) {
|
||||
const video = videoRef.value;
|
||||
if (!video) return;
|
||||
stop();
|
||||
@@ -81,17 +83,28 @@ function attach(cid: number) {
|
||||
video.play().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
const url = `${apiBase.value}/play/${props.dramaId}/${cid}/index.m3u8`;
|
||||
const url = `${apiBase.value}/play/${props.dramaId}/${cid}/index.m3u8?line=${line}`;
|
||||
if (Hls.isSupported()) {
|
||||
const player = new Hls();
|
||||
hls = player;
|
||||
let advancing = false;
|
||||
player.loadSource(url);
|
||||
player.attachMedia(video);
|
||||
player.on(Hls.Events.MANIFEST_PARSED, () => {
|
||||
if (error.value === "正在切换线路") error.value = "";
|
||||
video.play().catch(() => undefined);
|
||||
});
|
||||
player.on(Hls.Events.ERROR, (_event, data) => {
|
||||
if (data.fatal) error.value = "这一集播放失败";
|
||||
if (!data.fatal || advancing) return;
|
||||
const status = data.response?.code;
|
||||
const known = episode?.lines || 0;
|
||||
if (status === 404 || line >= 5 || (known > 0 && line + 1 >= known)) {
|
||||
error.value = "这一集播放失败";
|
||||
return;
|
||||
}
|
||||
advancing = true;
|
||||
error.value = "正在切换线路";
|
||||
window.setTimeout(() => attach(cid, line + 1), 0);
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -134,8 +147,10 @@ onUnmounted(stop);
|
||||
@click="select(episode)"
|
||||
>
|
||||
<span class="play-episode-title">{{ episode.title }}</span>
|
||||
<span v-if="!episode.playable" class="play-episode-lock">{{ episodeNote(episode) }}</span>
|
||||
<span v-if="episode.type?.toLowerCase() === 'vip'" class="play-episode-lock">会员</span>
|
||||
<span v-else-if="!episode.playable" class="play-episode-lock">{{ episodeNote(episode) }}</span>
|
||||
<span v-else-if="episode.is_preview" class="play-episode-lock">试看</span>
|
||||
<span v-if="episode.type?.toLowerCase() === 'vip' && !episode.playable && episode.locked_reason" class="play-episode-lock">{{ episodeNote(episode) }}</span>
|
||||
</button>
|
||||
<div v-if="!loading && episodes.length === 0" class="play-empty">没有分集</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user