Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions HOWTOSTART.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,8 @@ docker compose -f docker-compose.prebuilt.yml up -d

网易云个人 Cookie 按服务器隔离保存。首次访问账户页或读取喜欢列表时,旧版全局 Cookie 只迁移到当前服务器并删除全局项;当前服务器已有凭证时保留该凭证并清除旧全局项,更新或清除账户也同步清理旧项,避免其他服务器继承。行为核验:2026-11-19(前端回归测试)。

服务器切换浮层支持方向键、Home / End、Enter 和 Escape,选中另一服务器时整页跳转到该服务器的搜索页,释放旧页面的播放器定时器;浮层在窄屏限制高度并可滚动。喜欢列表一次获取完整数据,再每批显示 200 首,搜索和排序在完整数据上执行。旧的首屏分页缓存会失效重取;缓存仍按服务器隔离并保留 150 分钟,刷新强制重取。任何歌曲详情批次或收藏时间请求失败都会明确报错,不将部分结果缓存为完整收藏。界面检查与测试记录见 [PR #35 验收](docs/qa/pr35.md),不代表已核验生产或真实网易云账号。

这是 Docker Compose 的独立部署模式。原来的 Compose、`run-*.sh`、`run-*.ps1` 和 `nohup-*` 仍用于单服务器。以下步骤只配置本地源码及部署文件,不代表已修改远程测试、生产或灾备环境。

### 首次创建
Expand Down
4 changes: 3 additions & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,8 @@ The built-in adapter supports video search and audio playback, with local audio

Personal account cookies are stored in the browser and scoped to each server in multi-server mode. The account page and liked songs use the same storage entry point. Legacy global cookies migrate once; existing scoped credentials take precedence, and reading, replacing or clearing an account retires stale global credentials so another server cannot inherit them.

Liked songs can be searched by title, artist or album and sorted by original order, newest addition or name. The complete collection is fetched before showing the first 200 songs; scrolling reveals another 200. Search and sorting cover the entire fetched collection. Old paginated caches are reloaded; Refresh forces an update. Tracks without an upstream addition timestamp sort last, and detail or timestamp request failures are shown explicitly. Large collections may take longer on first load. The server selector supports keyboard navigation, narrow screens and dark mode.

For `auto` quality, a `-460` risk-control response triggers one standard-quality attempt, then a legacy endpoint attempt at 320000 bps only if standard is also blocked. Explicit quality selections do not downgrade automatically; unrelated upstream errors retain accurate diagnostics. See [provider quality behavior](docs/MUSIC_QUALITY.md).

Backend encrypts and stores the "admin Netease cookie" in database (`tsbot.db`) for:
Expand Down Expand Up @@ -487,7 +489,7 @@ The acknowledgments below are based on commit, pull request, and issue history.
| [@BreadAira](https://github.com/BreadAira) | Fixes for Netease cookie parsing, Bilibili covers, shared audio files and Chromium in Docker deployments ([PR #9](https://github.com/yichen11818/NeteaseTSBot/pull/9), [Issue #8](https://github.com/yichen11818/NeteaseTSBot/issues/8)). |
| [@Marius128](https://github.com/Marius128) | Optional TeamSpeak user levels, Bilibili chat playback commands, and accompanying documentation and tests ([PR #19](https://github.com/yichen11818/NeteaseTSBot/pull/19)). |
| [@nitonitori](https://github.com/nitonitori) | Netease automatic quality fallback on risk-control errors, direct playlist ID imports, configurable playback recovery and cooldown, separate Netease and QQ Music quality defaults, configurable PCM prefetch with backpressure, and the backend Playwright image build fix ([PR #22](https://github.com/yichen11818/NeteaseTSBot/pull/22), [#23](https://github.com/yichen11818/NeteaseTSBot/pull/23), [#26](https://github.com/yichen11818/NeteaseTSBot/pull/26), [#27](https://github.com/yichen11818/NeteaseTSBot/pull/27), [#29](https://github.com/yichen11818/NeteaseTSBot/pull/29), [#31](https://github.com/yichen11818/NeteaseTSBot/pull/31), all merged). Thank you for the accompanying documentation, regression tests, and fixes addressing review findings. |
| [@ZhuMengMeng666](https://github.com/ZhuMengMeng666) | Per-server personal Netease cookie isolation, legacy bitrate fallback after automatic quality risk-control failures, and multi-server health checks, restart policies and log rotation ([PR #32](https://github.com/yichen11818/NeteaseTSBot/pull/32), [#33](https://github.com/yichen11818/NeteaseTSBot/pull/33), [#34](https://github.com/yichen11818/NeteaseTSBot/pull/34), all merged). Thank you for improving multi-server operation and maintenance. |
| [@ZhuMengMeng666](https://github.com/ZhuMengMeng666) | Per-server personal Netease cookie isolation, legacy bitrate fallback after automatic quality risk-control failures, multi-server health checks, restart policies and log rotation, liked-song search/sorting/incremental display, and server selector improvements ([PR #32](https://github.com/yichen11818/NeteaseTSBot/pull/32), [#33](https://github.com/yichen11818/NeteaseTSBot/pull/33), [#34](https://github.com/yichen11818/NeteaseTSBot/pull/34), [#35](https://github.com/yichen11818/NeteaseTSBot/pull/35), all merged). Thank you for improving multi-server operation and maintenance. |

### Proposals, Reports, and Verification

Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,8 @@ docker compose -f docker-compose.prebuilt.yml up -d

个人账号的 Cookie 保存在浏览器中,多服务器模式按服务器隔离;账户页与“喜欢”列表共用同一存储入口。旧版全局 Cookie 只迁移一次,已有独立凭证时保留当前凭证并清理旧项;更新或清除账号也会移除旧项,避免其他服务器继承。

“我的喜欢”支持按歌名、歌手或专辑搜索,并按原顺序、添加时间(新→旧)或名称排序。先获取完整收藏,界面首屏显示 200 首,接近底部再追加 200 首;搜索和排序覆盖全部已获取歌曲。旧版分页缓存会重新加载,刷新按钮可强制更新。平台未提供收藏时间的歌曲排在时间排序末尾;歌曲详情或收藏时间请求失败会明确提示。收藏量较大时,首次加载可能更久。服务器切换浮层支持键盘导航、手机窄屏及夜间模式。

`auto` 音质请求遇到 `-460` 风控时先尝试标准音质;仍被风控才尝试旧接口按 320000 bps 取流。显式选择音质不自动降级,其他上游错误保留准确诊断。详见 [各来源音质说明](docs/MUSIC_QUALITY.md)。

后端会把“管理员网易云 Cookie”加密存储到数据库(`tsbot.db`)中,用于:
Expand Down Expand Up @@ -560,7 +562,7 @@ B 站后台授权支持扫码登录或手动 Cookie,用于登录态接口和 A
| [@BreadAira](https://github.com/BreadAira) | 修复网易云 Cookie 解析、B 站封面加载和 Docker 环境音频共享、Chromium 等问题([PR #9](https://github.com/yichen11818/NeteaseTSBot/pull/9)、[Issue #8](https://github.com/yichen11818/NeteaseTSBot/issues/8))。 |
| [@Marius128](https://github.com/Marius128) | 贡献可选的 TeamSpeak 用户等级系统、B 站聊天点播,以及相应文档和测试([PR #19](https://github.com/yichen11818/NeteaseTSBot/pull/19))。 |
| [@nitonitori](https://github.com/nitonitori) | 贡献网易云风控时的自动音质回退、按 ID 直接导入歌单、可配置的播放恢复与冷却、网易云与 QQ 音乐独立默认音质,可配置 PCM 预缓冲与背压,以及后端 Playwright 镜像构建修复([PR #22](https://github.com/yichen11818/NeteaseTSBot/pull/22)、[#23](https://github.com/yichen11818/NeteaseTSBot/pull/23)、[#26](https://github.com/yichen11818/NeteaseTSBot/pull/26)、[#27](https://github.com/yichen11818/NeteaseTSBot/pull/27)、[#29](https://github.com/yichen11818/NeteaseTSBot/pull/29)、[#31](https://github.com/yichen11818/NeteaseTSBot/pull/31),均已合并)。感谢同步完善文档与回归测试,并根据评审修复边界问题。 |
| [@ZhuMengMeng666](https://github.com/ZhuMengMeng666) | 贡献多服务器网易云个人 Cookie 隔离、自动音质风控后的旧码率接口回退,以及多服务器健康检查、重启策略与日志轮转([PR #32](https://github.com/yichen11818/NeteaseTSBot/pull/32)、[#33](https://github.com/yichen11818/NeteaseTSBot/pull/33)、[#34](https://github.com/yichen11818/NeteaseTSBot/pull/34),均已合并)。感谢完善多服务器使用体验和运行维护能力。 |
| [@ZhuMengMeng666](https://github.com/ZhuMengMeng666) | 贡献多服务器网易云个人 Cookie 隔离、自动音质风控后的旧码率接口回退,多服务器健康检查、重启策略与日志轮转,以及喜欢列表搜索、排序、自动追加和服务器切换器改进([PR #32](https://github.com/yichen11818/NeteaseTSBot/pull/32)、[#33](https://github.com/yichen11818/NeteaseTSBot/pull/33)、[#34](https://github.com/yichen11818/NeteaseTSBot/pull/34)、[#35](https://github.com/yichen11818/NeteaseTSBot/pull/35),均已合并)。感谢完善多服务器使用体验和运行维护能力。 |

### 功能提案、问题反馈与验证

Expand Down
57 changes: 4 additions & 53 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
)
from .managed_assets import ASSET_BY_KEY, asset_path, asset_payload, delete_asset, detect_image_type, save_asset, MAX_IMAGE_BYTES
from .netease import NeteaseClient
from .netease_likes import fetch_likes
from .netease_errors import LEGACY_AUTO_BITRATE, is_risk_response, risk_response_or_raise
from .netease_cookie import extract_netease_auth_cookie, has_netease_auth_cookie
from .qqmusic import QQMusicClient
Expand Down Expand Up @@ -5067,59 +5068,9 @@ async def netease_account(request: Request) -> dict:

@app.get("/netease/likelist")
async def netease_likelist(request: Request, offset: int = 0, limit: int = 0) -> dict:
cookie = _get_netease_cookie_from_header(request)
account = await netease.user_account(cookie=cookie)
profile = (account or {}).get("profile") or {}
uid = profile.get("userId")
if not uid:
raise HTTPException(status_code=400, detail="unable to determine uid from cookie")
data = await netease.likelist(uid=str(uid), cookie=cookie)
ids = (data or {}).get("ids") or []

songs: list[dict] = []
try:
if isinstance(ids, list) and ids:
chunk_size = 200
id_strs = [str(i) for i in ids if i is not None and str(i).strip()]

if offset < 0:
offset = 0
if limit and limit > 0:
page_ids = id_strs[offset : offset + limit]
else:
page_ids = id_strs

async def _fetch_song_detail(chunk: list[str]) -> list[dict]:
if not chunk:
return []
detail = await netease.song_detail(song_id=",".join(chunk), cookie=cookie)
dsongs = (detail or {}).get("songs") or []
if isinstance(dsongs, list) and dsongs:
return [s for s in dsongs if isinstance(s, dict)]
return []

chunks = [page_ids[i : i + chunk_size] for i in range(0, len(page_ids), chunk_size)]
results = await asyncio.gather(*[_fetch_song_detail(c) for c in chunks], return_exceptions=True)
for r in results:
if isinstance(r, Exception):
continue
songs.extend(r)
except Exception:
songs = []

# Keep original fields (ids, code, etc.) and add songs for frontend rendering.
out = dict(data or {})
out["songs"] = songs
try:
if isinstance(ids, list):
out["total"] = len(ids)
out["offset"] = int(offset)
out["limit"] = int(limit)
if limit and limit > 0:
out["has_more"] = (offset + limit) < len(ids)
except Exception:
pass
return out
return await fetch_likes(
netease, cookie=_get_netease_cookie_from_header(request), offset=offset, limit=limit,
)


@app.get("/netease/likes")
Expand Down
124 changes: 124 additions & 0 deletions backend/netease_likes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""Load complete liked-song metadata without hiding partial upstream failures."""
import asyncio
from typing import Awaitable, Protocol

import httpx
from fastapi import HTTPException


DETAIL_BATCH_SIZE = 200
LIKED_PLAYLIST_TYPE = 5


class LikesClient(Protocol):
async def user_account(self, *, cookie: str) -> dict: ...
async def likelist(self, *, uid: str, cookie: str) -> dict: ...
async def song_detail(self, *, song_id: str, cookie: str) -> dict: ...
async def user_playlist(self, *, uid: str, cookie: str) -> dict: ...
async def playlist_detail(self, playlist_id: str, *, cookie: str) -> dict: ...


def invalid_response(label: str) -> HTTPException:
return HTTPException(status_code=502, detail=f"网易云{label}返回无效数据")


async def request_data(request: Awaitable[dict], label: str) -> dict:
try:
data = await request
except httpx.HTTPStatusError as error:
raise HTTPException(
status_code=502, detail=f"网易云{label}请求失败(HTTP {error.response.status_code})",
) from None
except httpx.TimeoutException:
raise HTTPException(status_code=504, detail=f"网易云{label}请求超时") from None
except httpx.RequestError:
raise HTTPException(status_code=502, detail=f"网易云{label}网络请求失败") from None
except ValueError:
raise invalid_response(label) from None
if not isinstance(data, dict) or data.get("code") not in (None, 200):
raise invalid_response(label)
return data


def require_list(value: object, label: str) -> list:
if not isinstance(value, list):
raise invalid_response(label)
return value


def require_id(value: object, label: str) -> str:
if isinstance(value, bool) or not str(value).isascii() or not str(value).isdigit():
raise invalid_response(label)
return str(value)


async def fetch_song_batch(client: LikesClient, *, ids: list[str], cookie: str) -> list[dict]:
data = await request_data(client.song_detail(song_id=",".join(ids), cookie=cookie), "歌曲详情")
songs = require_list(data.get("songs"), "歌曲详情")
if any(not isinstance(song, dict) or "id" not in song for song in songs):
raise invalid_response("歌曲详情")
return songs


def find_liked_playlist(playlists: list, uid: str) -> str:
for playlist in playlists:
if not isinstance(playlist, dict):
raise invalid_response("用户歌单")
creator = playlist.get("creator") or {}
if not isinstance(creator, dict):
raise invalid_response("用户歌单")
owner = creator.get("userId")
if str(playlist.get("specialType")) != str(LIKED_PLAYLIST_TYPE):
continue
if owner is not None and str(owner) != uid:
continue
return require_id(playlist.get("id"), "用户歌单")
raise HTTPException(status_code=502, detail="网易云未返回当前账号的喜欢歌单,无法读取收藏时间")


def timestamp_map(entries: list) -> dict[str, int]:
result = {}
for entry in entries:
if not isinstance(entry, dict):
raise invalid_response("收藏时间")
identifier = require_id(entry.get("id"), "收藏时间")
added_at = entry.get("at")
if added_at is None:
continue
value = require_id(added_at, "收藏时间")
result[identifier] = int(value)
return result


async def fetch_added_times(client: LikesClient, *, uid: str, cookie: str) -> dict[str, int]:
data = await request_data(client.user_playlist(uid=uid, cookie=cookie), "用户歌单")
playlist_id = find_liked_playlist(require_list(data.get("playlist"), "用户歌单"), uid)
detail = await request_data(client.playlist_detail(playlist_id, cookie=cookie), "收藏时间")
playlist = detail.get("playlist")
if not isinstance(playlist, dict):
raise invalid_response("收藏时间")
return timestamp_map(require_list(playlist.get("trackIds"), "收藏时间"))


async def fetch_likes(client: LikesClient, *, cookie: str, offset: int = 0, limit: int = 0) -> dict:
account = await request_data(client.user_account(cookie=cookie), "账号信息")
profile = account.get("profile")
if not isinstance(profile, dict) or not profile.get("userId"):
raise HTTPException(status_code=400, detail="无法通过 Cookie 确认网易云账号,请重新登录")
uid = require_id(profile["userId"], "账号信息")
data = await request_data(client.likelist(uid=uid, cookie=cookie), "喜欢列表")
ids = [require_id(value, "喜欢列表") for value in require_list(data.get("ids"), "喜欢列表")]
page_offset = max(0, offset) if limit > 0 else 0
page_ids = ids[page_offset:page_offset + limit] if limit > 0 else ids
chunks = [page_ids[start:start + DETAIL_BATCH_SIZE] for start in range(0, len(page_ids), DETAIL_BATCH_SIZE)]
batches = await asyncio.gather(*(fetch_song_batch(client, ids=chunk, cookie=cookie) for chunk in chunks))
added_times = await fetch_added_times(client, uid=uid, cookie=cookie) if page_ids else {}
by_id = {str(song["id"]): song for batch in batches for song in batch}
songs = [
{**by_id[identifier], **({"added_at": added_times[identifier]} if identifier in added_times else {})}
for identifier in page_ids if identifier in by_id
]
return {
**data, "songs": songs, "total": len(ids), "offset": page_offset, "limit": max(0, limit),
"has_more": limit > 0 and page_offset + limit < len(ids),
}
35 changes: 35 additions & 0 deletions docs/qa/pr35.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# PR #35 验收记录

核验日期:2026-11-19。范围:本地源码、隔离浏览器和 PR CI;未修改生产、灾备或真实网易云账号。

## 回归覆盖

- 后端校验完整收藏的分批详情、时间戳、原始顺序、外部 API 分页和空收藏;HTTP、业务码、非 JSON 及无效时间戳失败显式返回错误,不产生假完整结果。
- 前端覆盖旧版 200 首分页缓存升级、完整缓存复用、强制刷新、不完整响应拒绝、退出账号及刷新后显示数量重置。
- 搜索覆盖歌名、歌手与专辑,排序先于显示截取,触底阈值保留 120px。

## 浏览器功能与视觉验证

使用本机 Chrome 的隔离会话,接口数据由测试路由提供:450 首歌曲、20 台服务器;所有名称、Cookie 和点歌请求均为测试数据。没有连接真实 TeamSpeak 或调用真实网易云服务。

| 场景 | 检查结果 |
| --- | --- |
| 旧缓存升级 | 旧首屏缓存被替换,初始显示 200 首 |
| 自动追加 | 滚动后依次显示 400、450 首 |
| 完整搜索 | 可查到第 450 首的歌手、第 449 首的专辑;无匹配时显示明确空结果 |
| 排序与刷新 | 添加时间倒序、名称顺序和原顺序均正确;刷新重置为 200 首 |
| 请求失败 | 刷新时注入收藏时间 HTTP 500,页面显示明确错误 |
| 歌曲操作 | 加入队列、立即播放的测试请求正确;本地收藏可添加后取消 |
| 服务器浮层 | 20 项可滚动;方向键、End、Enter、Escape、外部点击及焦点返回已检查 |
| 服务器隔离 | 切换到第二台服务器并进入喜欢页,显示未配置 Cookie,不继承第一台凭证 |
| 响应式与主题 | 1440px、390px、320px;浅色/夜间模式,未见新控件横向溢出或歌曲操作按钮被裁切 |

验收同时修正了窄屏操作列与刷新按钮可访问名称,以及 Vue scoped 样式中 `:global()` 的完整选择器范围。浏览器会话和临时开发服务均已关闭。

## 截图

截图为上述测试数据,已实际打开检查:

- [桌面端](../screenshots/likes-search-sort-autoload-selector/desktop.png)
- [手机服务器浮层](../screenshots/likes-search-sort-autoload-selector/mobile.png)
- [320px 夜间排序菜单](../screenshots/likes-search-sort-autoload-selector/mobile-dark.png)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading