mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-10-02 21:12:49 +08:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8861f39ecc | ||
|
|
6d5755ced7 | ||
|
|
997bb17ceb | ||
|
|
ea6501ea81 | ||
|
|
1d2da33d3c | ||
|
|
0e68e287b7 | ||
|
|
ecdb2d253e | ||
|
|
8860347bfe | ||
|
|
beb99f1d8e | ||
|
|
63f1ced2bc | ||
|
|
fa6013d22e | ||
|
|
6b60792277 | ||
|
|
c562fe05b0 | ||
|
|
9efa818bbb | ||
|
|
d757e69bf4 | ||
|
|
8cccf2ed24 | ||
|
|
f6b82b8e21 | ||
|
|
51d7ce61bd | ||
|
|
20f4cfacea | ||
|
|
7d9081efc1 | ||
|
|
a2453784c1 |
No files matched your search
@@ -19,8 +19,6 @@
|
||||
"Read(//tmp/**)"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(git push * main)",
|
||||
"Bash(git push * master)",
|
||||
"Bash(git push --force *)",
|
||||
"Bash(rm -rf /)"
|
||||
]
|
||||
|
||||
@@ -253,6 +253,7 @@ sudo systemctl start tsmusicbot
|
||||
| `!stop` | 停止播放并清空队列 |
|
||||
| `!vol <0-100>` | 设置音量 |
|
||||
| `!queue` | 查看播放队列 |
|
||||
| `!remove <位置>` | 从队列中删除指定位置的歌曲(位置从 1 开始,见 `!queue`) |
|
||||
| `!mode <seq\|loop\|random\|rloop>` | 切换播放模式 |
|
||||
| `!playlist <歌单名或ID>` | 加载歌单(支持名称模糊搜索和 ID) |
|
||||
| `!playlist -q <歌单名>` | 从 QQ 音乐搜索并加载歌单 |
|
||||
|
||||
+8
-1
@@ -279,8 +279,12 @@ export class AudioPlayer extends EventEmitter {
|
||||
this.emit("error", err);
|
||||
});
|
||||
|
||||
// Mark playing but DO NOT start the frame loop here — the loop's
|
||||
// "no ffmpeg + empty buffer → trackEnd" branch would fire on the very
|
||||
// first tick, before the PowerShell download even completes. The
|
||||
// frame loop is started inside spawnFfmpegFromFile() once ffmpeg is
|
||||
// alive and producing PCM.
|
||||
this.state = "playing";
|
||||
this.startFrameLoop();
|
||||
}
|
||||
|
||||
private spawnFfmpegFromFile(tempFile: string, seekSeconds: number, sessionId: number): void {
|
||||
@@ -329,6 +333,9 @@ export class AudioPlayer extends EventEmitter {
|
||||
this.emit("error", err);
|
||||
}
|
||||
});
|
||||
|
||||
// Now that ffmpeg is producing PCM, run the frame loop.
|
||||
this.startFrameLoop();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
|
||||
+27
-4
@@ -22,6 +22,7 @@ export class PlayQueue {
|
||||
private mode: PlayMode = PlayMode.Sequential;
|
||||
private playedIndices = new Set<number>();
|
||||
private history: number[] = [];
|
||||
private forwardStack: number[] = [];
|
||||
private static readonly HISTORY_LIMIT = 50;
|
||||
|
||||
private pushHistory(idx: number): void {
|
||||
@@ -100,12 +101,14 @@ export class PlayQueue {
|
||||
this.currentIndex = -1;
|
||||
this.playedIndices.clear();
|
||||
this.history = [];
|
||||
this.forwardStack = [];
|
||||
}
|
||||
|
||||
play(): QueuedSong | null {
|
||||
if (this.songs.length === 0) return null;
|
||||
this.playedIndices.clear();
|
||||
this.history = [];
|
||||
this.forwardStack = [];
|
||||
this.currentIndex = 0;
|
||||
this.playedIndices.add(0);
|
||||
return this.songs[0];
|
||||
@@ -118,6 +121,7 @@ export class PlayQueue {
|
||||
// shuffle from this point. History tracking is independent and
|
||||
// unaffected by this clear.
|
||||
this.playedIndices.clear();
|
||||
this.forwardStack = [];
|
||||
this.currentIndex = index;
|
||||
this.playedIndices.add(index);
|
||||
return this.songs[index];
|
||||
@@ -139,7 +143,20 @@ export class PlayQueue {
|
||||
this.currentIndex = (this.currentIndex + 1) % this.songs.length;
|
||||
return this.songs[this.currentIndex];
|
||||
}
|
||||
case PlayMode.Random: {
|
||||
case PlayMode.Random:
|
||||
case PlayMode.RandomLoop: {
|
||||
// 优先回到前进栈记录的位置(prev 退回的歌)
|
||||
if (this.forwardStack.length > 0) {
|
||||
const target = this.forwardStack.pop()!;
|
||||
if (target !== this.currentIndex) {
|
||||
this.pushHistory(this.currentIndex);
|
||||
this.currentIndex = target;
|
||||
this.playedIndices.add(target);
|
||||
return this.songs[target];
|
||||
}
|
||||
}
|
||||
// 前进栈为空,走纯随机逻辑
|
||||
if (this.mode === PlayMode.Random) {
|
||||
const unplayed: number[] = [];
|
||||
for (let i = 0; i < this.songs.length; i++) {
|
||||
if (!this.playedIndices.has(i)) unplayed.push(i);
|
||||
@@ -151,8 +168,7 @@ export class PlayQueue {
|
||||
this.currentIndex = nextIndex;
|
||||
this.playedIndices.add(nextIndex);
|
||||
return this.songs[nextIndex];
|
||||
}
|
||||
case PlayMode.RandomLoop: {
|
||||
} else {
|
||||
if (this.songs.length === 1) {
|
||||
this.pushHistory(this.currentIndex);
|
||||
this.currentIndex = 0;
|
||||
@@ -168,17 +184,23 @@ export class PlayQueue {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
prev(): QueuedSong | null {
|
||||
if (this.songs.length === 0) return null;
|
||||
|
||||
// 记录当前位置到前进栈,供 next 优先返回
|
||||
if (this.currentIndex >= 0 && this.forwardStack.length < PlayQueue.HISTORY_LIMIT) {
|
||||
this.forwardStack.push(this.currentIndex);
|
||||
}
|
||||
|
||||
// Preferred: pop from the back-stack so prev means "the song I
|
||||
// actually played before this one," not "the previous array slot."
|
||||
while (this.history.length > 0) {
|
||||
const idx = this.history.pop()!;
|
||||
if (idx >= 0 && idx < this.songs.length) {
|
||||
this.currentIndex = idx;
|
||||
this.playedIndices.add(idx);
|
||||
this.playedIndices = new Set([...this.history, this.currentIndex]);
|
||||
return this.songs[idx];
|
||||
}
|
||||
// Stale entry (song removed) — keep popping.
|
||||
@@ -227,6 +249,7 @@ export class PlayQueue {
|
||||
this.mode = mode;
|
||||
this.playedIndices.clear();
|
||||
this.history = [];
|
||||
this.forwardStack = [];
|
||||
if (this.currentIndex >= 0) {
|
||||
this.playedIndices.add(this.currentIndex);
|
||||
}
|
||||
|
||||
+21
-2
@@ -638,9 +638,27 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
private async cmdAlbum(cmd: ParsedCommand): Promise<string> {
|
||||
if (!cmd.args) return "Usage: !album <album ID>";
|
||||
if (!cmd.args) return "Usage: !album <album name or ID>";
|
||||
const provider = this.getProvider(cmd.flags);
|
||||
const songs = await provider.getAlbumSongs(cmd.args);
|
||||
|
||||
const id = this.extractId(cmd.args);
|
||||
const isNumericId = /^\d+$/.test(cmd.args.trim());
|
||||
|
||||
let albumId: string;
|
||||
|
||||
if (isNumericId || id !== cmd.args) {
|
||||
// Input is a numeric ID or URL containing an ID — use directly
|
||||
albumId = id;
|
||||
} else {
|
||||
// Name-based search
|
||||
const result = await provider.search(cmd.args);
|
||||
const albums = result.albums ?? [];
|
||||
if (albums.length === 0)
|
||||
return `No albums found for: ${cmd.args}`;
|
||||
albumId = albums[0].id;
|
||||
}
|
||||
|
||||
const songs = await provider.getAlbumSongs(albumId);
|
||||
if (songs.length === 0) return "Album is empty or not found";
|
||||
|
||||
this.queue.clear();
|
||||
@@ -778,6 +796,7 @@ export class BotInstance extends EventEmitter {
|
||||
`${p}stop — Stop and clear queue`,
|
||||
`${p}vol <0-100> — Set volume`,
|
||||
`${p}queue — Show queue`,
|
||||
`${p}remove <pos> — Remove song at position (see ${p}queue)`,
|
||||
`${p}mode <seq|loop|random|rloop> — Play mode`,
|
||||
`${p}playlist <name or id> — Load playlist by name or ID`,
|
||||
`${p}playlist -q <name or id> — Load playlist from QQ Music`,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { parseLyrics } from "./netease.js";
|
||||
import { parseLyrics, mapNeteaseAlbums } from "./netease.js";
|
||||
|
||||
describe("NetEase adapter", () => {
|
||||
it("parses LRC format lyrics", () => {
|
||||
@@ -28,4 +28,32 @@ describe("NetEase adapter", () => {
|
||||
expect(lines[0].text).toBe("Hello world");
|
||||
expect(lines[0].translation).toBe("你好世界");
|
||||
});
|
||||
|
||||
it("mapNeteaseAlbums maps raw cloudsearch albums to Album shape", () => {
|
||||
const raw = [
|
||||
{
|
||||
id: 42,
|
||||
name: "Album A",
|
||||
picUrl: "https://x/p.jpg",
|
||||
artists: [{ name: "Artist X" }, { name: "Featured Y" }],
|
||||
size: 12,
|
||||
},
|
||||
{
|
||||
id: 99,
|
||||
name: "Album B",
|
||||
picUrl: "",
|
||||
artists: [],
|
||||
},
|
||||
];
|
||||
expect(mapNeteaseAlbums(raw)).toEqual([
|
||||
{ id: "42", name: "Album A", artist: "Artist X / Featured Y", coverUrl: "https://x/p.jpg", songCount: 12, platform: "netease" },
|
||||
{ id: "99", name: "Album B", artist: "", coverUrl: "", songCount: 0, platform: "netease" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("mapNeteaseAlbums returns [] for empty/null input", () => {
|
||||
expect(mapNeteaseAlbums([])).toEqual([]);
|
||||
expect(mapNeteaseAlbums(null as any)).toEqual([]);
|
||||
expect(mapNeteaseAlbums(undefined as any)).toEqual([]);
|
||||
});
|
||||
});
|
||||
+21
-3
@@ -8,6 +8,7 @@ import type {
|
||||
SearchResult,
|
||||
QrCodeResult,
|
||||
AuthStatus,
|
||||
Album,
|
||||
} from "./provider.js";
|
||||
|
||||
export function parseLyrics(lrc: string, tlyric?: string): LyricLine[] {
|
||||
@@ -55,6 +56,18 @@ export function parseLyrics(lrc: string, tlyric?: string): LyricLine[] {
|
||||
return lines.sort((a, b) => a.time - b.time);
|
||||
}
|
||||
|
||||
export function mapNeteaseAlbums(raw: any[] | null | undefined): Album[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.map((a) => ({
|
||||
id: String(a.id),
|
||||
name: a.name ?? "",
|
||||
artist: (a.artists ?? []).map((x: any) => x.name).join(" / "),
|
||||
coverUrl: a.picUrl ?? "",
|
||||
songCount: a.size ?? 0,
|
||||
platform: "netease",
|
||||
}));
|
||||
}
|
||||
|
||||
// NetEase quality levels: standard(128k) higher(192k) exhigh(320k) lossless(flac) hires(hi-res) jyeffect jymaster
|
||||
export const NETEASE_QUALITY_LEVELS = [
|
||||
{ value: "standard", label: "标准 (128kbps)", bitrate: 128 },
|
||||
@@ -91,7 +104,7 @@ export class NeteaseProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
async search(query: string, limit = 20): Promise<SearchResult> {
|
||||
const [songRes, playlistRes] = await Promise.all([
|
||||
const [songRes, playlistRes, albumRes] = await Promise.all([
|
||||
this.api.get("/cloudsearch", {
|
||||
params: { keywords: query, type: 1, limit, ...this.cookieParams },
|
||||
}),
|
||||
@@ -99,10 +112,13 @@ export class NeteaseProvider implements MusicProvider {
|
||||
params: {
|
||||
keywords: query,
|
||||
type: 1000,
|
||||
limit: 5,
|
||||
limit: 10,
|
||||
...this.cookieParams,
|
||||
},
|
||||
}),
|
||||
this.api.get("/cloudsearch", {
|
||||
params: { keywords: query, type: 10, limit: 10, ...this.cookieParams },
|
||||
}),
|
||||
]);
|
||||
|
||||
const songs: Song[] = (songRes.data?.result?.songs ?? []).map(
|
||||
@@ -127,7 +143,9 @@ export class NeteaseProvider implements MusicProvider {
|
||||
platform: "netease",
|
||||
}));
|
||||
|
||||
return { songs, playlists, albums: [] };
|
||||
const albums = mapNeteaseAlbums(albumRes.data?.result?.albums);
|
||||
|
||||
return { songs, playlists, albums };
|
||||
}
|
||||
|
||||
async getSongUrl(songId: string, quality?: string): Promise<string | null> {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mapQqAlbums } from "./qq.js";
|
||||
|
||||
describe("QQ adapter", () => {
|
||||
it("mapQqAlbums maps albumMID-style raw entries", () => {
|
||||
const raw = [
|
||||
{
|
||||
albumMID: "abc",
|
||||
albumName: "Aero",
|
||||
singerName: "Singer A",
|
||||
},
|
||||
{
|
||||
albumMID: "xyz",
|
||||
albumName: "Beta",
|
||||
singer: [{ name: "Singer B" }, { name: "Singer C" }],
|
||||
},
|
||||
];
|
||||
const out = mapQqAlbums(raw);
|
||||
expect(out).toHaveLength(2);
|
||||
expect(out[0]).toMatchObject({
|
||||
id: "abc",
|
||||
name: "Aero",
|
||||
artist: "Singer A",
|
||||
platform: "qq",
|
||||
});
|
||||
expect(out[0].coverUrl).toContain("T002R300x300M000abc.jpg");
|
||||
expect(out[1].artist).toBe("Singer B / Singer C");
|
||||
expect(out[1].coverUrl).toContain("xyz");
|
||||
});
|
||||
|
||||
it("mapQqAlbums returns [] for empty/null input", () => {
|
||||
expect(mapQqAlbums([])).toEqual([]);
|
||||
expect(mapQqAlbums(null as any)).toEqual([]);
|
||||
expect(mapQqAlbums(undefined as any)).toEqual([]);
|
||||
});
|
||||
|
||||
it("mapQqAlbums falls back to albumPic when no albumMID", () => {
|
||||
const raw = [{ albumName: "C", albumPic: "https://x/p.jpg", singerName: "S" }];
|
||||
const out = mapQqAlbums(raw);
|
||||
expect(out[0].coverUrl).toBe("https://x/p.jpg");
|
||||
expect(out[0].id).toBe("");
|
||||
});
|
||||
});
|
||||
+143
-12
@@ -8,17 +8,29 @@ import type {
|
||||
SearchResult,
|
||||
QrCodeResult,
|
||||
AuthStatus,
|
||||
Album,
|
||||
} from "./provider.js";
|
||||
import { parseLyrics } from "./netease.js";
|
||||
|
||||
// Direct QQ Music API client — bypasses the local API server for search
|
||||
// because @sansenjian/qq-music-api still uses the broken c.y.qq.com endpoint.
|
||||
const qqDirectApi = axios.create({
|
||||
// Primary search client: u.y.qq.com/cgi-bin/musicu.fcg (JSON sub-request
|
||||
// batch). Was broken ca. 2026-05 due to two upstream API changes:
|
||||
// 1. searchid param must NOT be present (causes all lists to be empty)
|
||||
// 2. num_per_page must be >= 10 (lower values return empty)
|
||||
// Both fixes applied per https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/61
|
||||
const qqMusicuApi = axios.create({
|
||||
baseURL: "https://u.y.qq.com",
|
||||
timeout: 10000,
|
||||
headers: { referer: "https://y.qq.com" },
|
||||
});
|
||||
|
||||
// Fallback search client: c.y.qq.com/soso/fcgi-bin/client_search_cp (classic
|
||||
// endpoint, song + album only, no playlist support).
|
||||
const qqSearchApi = axios.create({
|
||||
baseURL: "https://c.y.qq.com",
|
||||
timeout: 10000,
|
||||
headers: { referer: "https://y.qq.com" },
|
||||
});
|
||||
|
||||
// Direct client for c.y.qq.com endpoints (collected playlists / favorites).
|
||||
// The bundled qq-music-api wrapper doesn't expose these endpoints.
|
||||
const qqFavApi = axios.create({
|
||||
@@ -27,6 +39,26 @@ const qqFavApi = axios.create({
|
||||
headers: { referer: "https://y.qq.com/" },
|
||||
});
|
||||
|
||||
export function mapQqAlbums(raw: any[] | null | undefined): Album[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.map((a) => {
|
||||
const id = String(a.albumMID ?? a.mid ?? a.albumID ?? "");
|
||||
const artist = a.singerName
|
||||
?? (Array.isArray(a.singer) ? a.singer.map((s: any) => s.name).join(" / ") : "");
|
||||
const coverUrl = id
|
||||
? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${id}.jpg`
|
||||
: (a.albumPic ?? "");
|
||||
return {
|
||||
id,
|
||||
name: a.albumName ?? a.title ?? "",
|
||||
artist,
|
||||
coverUrl,
|
||||
songCount: a.song_count ?? a.songCount ?? 0,
|
||||
platform: "qq" as const,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function computeGtk(pSkey: string): number {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < pSkey.length; i++) {
|
||||
@@ -61,24 +93,55 @@ export class QQMusicProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
async search(query: string, limit = 20): Promise<SearchResult> {
|
||||
// Primary: u.y.qq.com/cgi-bin/musicu.fcg — supports songs + albums +
|
||||
// playlists. Fixed per https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/issues/61
|
||||
// (removed searchid, num_per_page >= 10, corrected search_type values).
|
||||
const primary = await this.searchViaMusicuFcg(query, limit);
|
||||
if (primary) return primary;
|
||||
|
||||
// Fallback: c.y.qq.com/soso/fcgi-bin/client_search_cp (song + album,
|
||||
// no playlist support). Kept as redundancy.
|
||||
return this.searchViaClientSearchCp(query, limit);
|
||||
}
|
||||
|
||||
/** Primary search via u.y.qq.com/cgi-bin/musicu.fcg.
|
||||
*
|
||||
* Two upstream API changes (2026-05) required fixes:
|
||||
* 1. Omit `searchid` — its presence now causes all lists to be empty.
|
||||
* 2. `num_per_page` >= 10 — lower values return empty.
|
||||
* 3. `search_type: 2` for albums, `3` for playlists (8 was "user"). */
|
||||
private async searchViaMusicuFcg(
|
||||
query: string,
|
||||
limit: number
|
||||
): Promise<SearchResult | null> {
|
||||
try {
|
||||
const numPerPage = Math.max(10, Math.min(limit, 50));
|
||||
const reqData = JSON.stringify({
|
||||
req_0: {
|
||||
module: "music.search.SearchCgiService",
|
||||
method: "DoSearchForQQMusicDesktop",
|
||||
param: {
|
||||
searchid: "1",
|
||||
query,
|
||||
num_per_page: Math.min(limit, 50),
|
||||
param: { query, num_per_page: numPerPage, search_type: 0 },
|
||||
},
|
||||
req_album: {
|
||||
module: "music.search.SearchCgiService",
|
||||
method: "DoSearchForQQMusicDesktop",
|
||||
param: { query, num_per_page: 10, search_type: 2 },
|
||||
},
|
||||
req_playlist: {
|
||||
module: "music.search.SearchCgiService",
|
||||
method: "DoSearchForQQMusicDesktop",
|
||||
param: { query, num_per_page: 10, search_type: 3 },
|
||||
},
|
||||
});
|
||||
const res = await qqDirectApi.get("/cgi-bin/musicu.fcg", {
|
||||
const res = await qqMusicuApi.get("/cgi-bin/musicu.fcg", {
|
||||
params: { format: "json", data: reqData },
|
||||
});
|
||||
const list: any[] =
|
||||
res.data?.req_0?.data?.body?.song?.list ?? [];
|
||||
|
||||
const songs: Song[] = list.map((s: any) => ({
|
||||
const songList: any[] =
|
||||
res.data?.req_0?.data?.body?.song?.list ?? [];
|
||||
if (songList.length === 0) return null;
|
||||
|
||||
const songs: Song[] = songList.map((s: any) => ({
|
||||
id: String(s.mid ?? s.id),
|
||||
name: s.title ?? s.name ?? "",
|
||||
artist: (s.singer ?? []).map((a: any) => a.name).join(" / "),
|
||||
@@ -90,7 +153,75 @@ export class QQMusicProvider implements MusicProvider {
|
||||
platform: "qq",
|
||||
}));
|
||||
|
||||
return { songs, playlists: [], albums: [] };
|
||||
const albumList: any[] = res.data?.req_album?.data?.body?.album?.list ?? [];
|
||||
const albums = mapQqAlbums(albumList);
|
||||
|
||||
const playlistList: any[] = res.data?.req_playlist?.data?.body?.songlist?.list ?? [];
|
||||
const playlists: Playlist[] = playlistList.map((p: any) => ({
|
||||
id: String(p.dissid ?? p.id ?? ""),
|
||||
name: p.dissname ?? p.title ?? "",
|
||||
coverUrl: p.imgurl ?? p.logo ?? "",
|
||||
songCount: p.songnum ?? p.song_count ?? 0,
|
||||
platform: "qq" as const,
|
||||
}));
|
||||
|
||||
return { songs, playlists, albums };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Fallback search via c.y.qq.com/soso/fcgi-bin/client_search_cp */
|
||||
private async searchViaClientSearchCp(
|
||||
query: string,
|
||||
limit: number
|
||||
): Promise<SearchResult> {
|
||||
const songParams = {
|
||||
w: query,
|
||||
format: "json",
|
||||
p: 1,
|
||||
n: Math.min(limit, 50),
|
||||
type: 0,
|
||||
cr: 1,
|
||||
};
|
||||
const albumParams = {
|
||||
w: query,
|
||||
format: "json",
|
||||
p: 1,
|
||||
n: 5,
|
||||
t: 8,
|
||||
cr: 1,
|
||||
};
|
||||
|
||||
const [songRes, albumRes] = await Promise.allSettled([
|
||||
qqSearchApi.get("/soso/fcgi-bin/client_search_cp", { params: songParams }),
|
||||
qqSearchApi.get("/soso/fcgi-bin/client_search_cp", { params: albumParams }),
|
||||
]);
|
||||
|
||||
const songList: any[] =
|
||||
songRes.status === "fulfilled"
|
||||
? (songRes.value.data?.data?.song?.list ?? [])
|
||||
: [];
|
||||
|
||||
const songs: Song[] = songList.map((s: any) => ({
|
||||
id: String(s.songmid ?? s.songid ?? ""),
|
||||
name: s.songname ?? s.name ?? "",
|
||||
artist: (s.singer ?? []).map((a: any) => a.name).join(" / "),
|
||||
album: s.albumname ?? s.album?.name ?? "",
|
||||
duration: s.interval ?? 0,
|
||||
coverUrl: s.albummid
|
||||
? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${s.albummid}.jpg`
|
||||
: "",
|
||||
platform: "qq",
|
||||
}));
|
||||
|
||||
const albumList: any[] =
|
||||
albumRes.status === "fulfilled"
|
||||
? (albumRes.value.data?.data?.album?.list ?? [])
|
||||
: [];
|
||||
const albums = mapQqAlbums(albumList);
|
||||
|
||||
return { songs, playlists: [], albums };
|
||||
}
|
||||
|
||||
async getSongUrl(songId: string, quality?: string): Promise<string | null> {
|
||||
|
||||
+10
-4
@@ -52,14 +52,20 @@ export function createMusicRouter(
|
||||
]);
|
||||
|
||||
const songs = [
|
||||
...(neteaseResult.status === "fulfilled"
|
||||
? neteaseResult.value.songs
|
||||
: []),
|
||||
...(neteaseResult.status === "fulfilled" ? neteaseResult.value.songs : []),
|
||||
...(qqResult.status === "fulfilled" ? qqResult.value.songs : []),
|
||||
...(bilibiliResult.status === "fulfilled" ? bilibiliResult.value.songs : []),
|
||||
];
|
||||
const albums = [
|
||||
...(neteaseResult.status === "fulfilled" ? neteaseResult.value.albums : []),
|
||||
...(qqResult.status === "fulfilled" ? qqResult.value.albums : []),
|
||||
];
|
||||
const playlists = [
|
||||
...(neteaseResult.status === "fulfilled" ? neteaseResult.value.playlists : []),
|
||||
...(qqResult.status === "fulfilled" ? qqResult.value.playlists : []),
|
||||
];
|
||||
|
||||
res.json({ songs });
|
||||
res.json({ songs, albums, playlists });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Unified search failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
|
||||
@@ -313,6 +313,78 @@ export function createPlayerRouter(
|
||||
}
|
||||
});
|
||||
|
||||
// Play an album by ID — mirrors play-playlist but calls getAlbumSongs
|
||||
router.post("/:botId/play-album", async (req, res) => {
|
||||
try {
|
||||
const bot = (req as any).bot;
|
||||
const { albumId, platform } = req.body;
|
||||
const provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
|
||||
// Stop current playback
|
||||
bot.getPlayer().stop();
|
||||
bot.getPlayer().resetFailures();
|
||||
|
||||
const songs = await provider.getAlbumSongs(albumId);
|
||||
if (songs.length === 0) {
|
||||
res.json({ message: "Album is empty" });
|
||||
return;
|
||||
}
|
||||
|
||||
// QQ-specific optimization: batch-resolve playable IDs to avoid
|
||||
// wasting retries on region/copyright-restricted tracks.
|
||||
let queueable: { id: string }[] = songs;
|
||||
const totalCount = songs.length;
|
||||
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
|
||||
if (typeof qqLike.getPlayableSongIds === "function") {
|
||||
const playable = await qqLike.getPlayableSongIds(songs.map((s: { id: string }) => s.id));
|
||||
if (playable !== null) {
|
||||
queueable = songs.filter((s: { id: string }) => playable.has(s.id));
|
||||
}
|
||||
}
|
||||
if (queueable.length === 0) {
|
||||
res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
|
||||
return;
|
||||
}
|
||||
|
||||
const queue = bot.getQueueManager();
|
||||
queue.clear();
|
||||
for (const song of queueable) {
|
||||
queue.add({ ...song, platform: provider.platform });
|
||||
}
|
||||
|
||||
const mode = queue.getMode();
|
||||
let first;
|
||||
if (mode === "random" || mode === "rloop") {
|
||||
const idx = Math.floor(Math.random() * queue.size());
|
||||
first = queue.playAt(idx);
|
||||
} else {
|
||||
first = queue.play();
|
||||
}
|
||||
|
||||
let started = first ? await bot.resolveAndPlay(first) : false;
|
||||
if (first && !started) {
|
||||
started = await bot.playNext(20);
|
||||
}
|
||||
|
||||
const playing = queue.current();
|
||||
const loadedMsg = queueable.length < totalCount
|
||||
? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)`
|
||||
: `已加载 ${queueable.length} 首`;
|
||||
if (started && playing) {
|
||||
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
|
||||
} else {
|
||||
res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` });
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err }, "play-album failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
// Play a single song by ID — resolves URL on demand
|
||||
router.post("/:botId/play-song", async (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -22,6 +22,13 @@ const router = createRouter({
|
||||
path: '/playlist/:id',
|
||||
name: 'playlist',
|
||||
component: () => import('../views/Playlist.vue'),
|
||||
meta: { kind: 'playlist' },
|
||||
},
|
||||
{
|
||||
path: '/album/:id',
|
||||
name: 'album',
|
||||
component: () => import('../views/Playlist.vue'),
|
||||
meta: { kind: 'album' },
|
||||
},
|
||||
{
|
||||
path: '/lyrics',
|
||||
|
||||
@@ -322,6 +322,16 @@ export const usePlayerStore = defineStore('player', {
|
||||
this._syncAfterAction();
|
||||
},
|
||||
|
||||
async playAlbum(albumId: string, platform = 'netease') {
|
||||
if (!this.activeBotId) return;
|
||||
const res = await axios.post(`/api/player/${this.activeBotId}/play-album`, { albumId, platform });
|
||||
if (res.data?.message) {
|
||||
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
|
||||
}
|
||||
this._setTiming(this.activeBotId, { serverElapsed: 0 });
|
||||
this._syncAfterAction();
|
||||
},
|
||||
|
||||
async pause() {
|
||||
if (!this.activeBotId) return;
|
||||
// Freeze elapsed at current interpolated value
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-else class="loading">歌单不存在或加载失败</div>
|
||||
<div v-else class="loading">{{ kind === 'album' ? '专辑' : '歌单' }}不存在或加载失败</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -64,6 +64,8 @@ interface PlaylistDetail {
|
||||
songCount: number;
|
||||
}
|
||||
|
||||
const kind = (route.meta.kind as string) ?? 'playlist'; // 'playlist' | 'album'
|
||||
|
||||
const playlist = ref<PlaylistDetail | null>(null);
|
||||
const songs = ref<Song[]>([]);
|
||||
const loading = ref(true);
|
||||
@@ -71,20 +73,32 @@ const loading = ref(true);
|
||||
async function playAll() {
|
||||
const id = route.params.id as string;
|
||||
const platform = (route.query.platform as string) || 'netease';
|
||||
if (kind === 'album') {
|
||||
await store.playAlbum(id, platform);
|
||||
} else {
|
||||
await store.playPlaylist(id, platform);
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const id = route.params.id as string;
|
||||
const platform = (route.query.platform as string) || 'netease';
|
||||
|
||||
const detailUrl = kind === 'album'
|
||||
? `/api/music/album/${id}/detail`
|
||||
: `/api/music/playlist/${id}/detail`;
|
||||
const songsUrl = kind === 'album'
|
||||
? `/api/music/album/${id}`
|
||||
: `/api/music/playlist/${id}`;
|
||||
|
||||
// allSettled, not Promise.all — if detail 404s but songs is fine
|
||||
// (e.g., a QQ playlist whose detail endpoint flaked but the song
|
||||
// list resolved), we still want to show the songs rather than
|
||||
// the "歌单不存在" empty state.
|
||||
// the "不存在" empty state. For albums, detail always 404s — that
|
||||
// is intentional; the fallback stub below handles it.
|
||||
const [detailRes, songsRes] = await Promise.allSettled([
|
||||
axios.get(`/api/music/playlist/${id}/detail`, { params: { platform } }),
|
||||
axios.get(`/api/music/playlist/${id}`, { params: { platform } }),
|
||||
axios.get(detailUrl, { params: { platform } }),
|
||||
axios.get(songsUrl, { params: { platform } }),
|
||||
]);
|
||||
|
||||
const detail = detailRes.status === 'fulfilled' ? detailRes.value.data?.playlist : null;
|
||||
@@ -93,10 +107,14 @@ onMounted(async () => {
|
||||
if (detail) {
|
||||
playlist.value = detail;
|
||||
} else if (songList.length > 0) {
|
||||
// Fall back to a stub built from the route + first song's cover.
|
||||
// Fall back to a stub built from the route + first song. For albums,
|
||||
// every song's `album` field carries the real album name.
|
||||
const fallbackName = kind === 'album'
|
||||
? (songList[0]?.album || '专辑')
|
||||
: '歌单';
|
||||
playlist.value = {
|
||||
id,
|
||||
name: '歌单',
|
||||
name: fallbackName,
|
||||
description: '',
|
||||
coverUrl: songList[0]?.coverUrl ?? '',
|
||||
songCount: songList.length,
|
||||
@@ -104,7 +122,7 @@ onMounted(async () => {
|
||||
} else {
|
||||
playlist.value = null;
|
||||
if (detailRes.status === 'rejected') {
|
||||
console.error('Failed to load playlist detail:', (detailRes.reason as any)?.response?.status, (detailRes.reason as any)?.message);
|
||||
console.error('Failed to load detail:', (detailRes.reason as any)?.response?.status, (detailRes.reason as any)?.message);
|
||||
}
|
||||
}
|
||||
songs.value = songList;
|
||||
|
||||
+268
-15
@@ -20,9 +20,89 @@
|
||||
|
||||
<div v-if="loading" class="loading">搜索中...</div>
|
||||
|
||||
<div v-else-if="results.length > 0" class="results">
|
||||
<template v-else-if="allSongs.length || allAlbums.length || allPlaylists.length">
|
||||
<div class="source-bar">
|
||||
<button
|
||||
class="source-btn"
|
||||
:class="{ active: selectedSource === 'netease' }"
|
||||
@click="selectedSource = 'netease'"
|
||||
>网易云</button>
|
||||
<button
|
||||
class="source-btn"
|
||||
:class="{ active: selectedSource === 'qq' }"
|
||||
@click="selectedSource = 'qq'"
|
||||
>QQ</button>
|
||||
<button
|
||||
class="source-btn"
|
||||
:class="{ active: selectedSource === 'bilibili' }"
|
||||
@click="selectedSource = 'bilibili'"
|
||||
>B站</button>
|
||||
</div>
|
||||
|
||||
<div class="tab-bar">
|
||||
<button
|
||||
class="tab"
|
||||
:class="{ active: activeTab === 'songs' }"
|
||||
@click="activeTab = 'songs'"
|
||||
>
|
||||
单曲<span class="tab-count">{{ filteredSongs.length }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="selectedSource !== 'bilibili'"
|
||||
class="tab"
|
||||
:class="{ active: activeTab === 'albums' }"
|
||||
@click="activeTab = 'albums'"
|
||||
>
|
||||
专辑<span class="tab-count">{{ filteredAlbums.length }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="selectedSource !== 'bilibili'"
|
||||
class="tab"
|
||||
:class="{ active: activeTab === 'playlists' }"
|
||||
@click="activeTab = 'playlists'"
|
||||
>
|
||||
歌单<span class="tab-count">{{ filteredPlaylists.length }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section v-if="activeTab === 'albums' && filteredAlbums.length" class="result-section">
|
||||
<div class="card-grid">
|
||||
<router-link
|
||||
v-for="al in filteredAlbums"
|
||||
:key="`${al.platform}-${al.id}`"
|
||||
:to="`/album/${al.id}?platform=${al.platform}`"
|
||||
class="card hover-scale"
|
||||
>
|
||||
<CoverArt :url="al.coverUrl" :size="160" :radius="10" :show-shadow="true" />
|
||||
<div class="card-name">
|
||||
{{ al.name }}
|
||||
<span class="platform-badge" :class="badgeClass(al.platform)">{{ badgeLabel(al.platform) }}</span>
|
||||
</div>
|
||||
<div class="card-sub">{{ al.artist }}</div>
|
||||
</router-link>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="activeTab === 'playlists' && filteredPlaylists.length" class="result-section">
|
||||
<div class="card-grid">
|
||||
<router-link
|
||||
v-for="pl in filteredPlaylists"
|
||||
:key="`${pl.platform}-${pl.id}`"
|
||||
:to="`/playlist/${pl.id}?platform=${pl.platform}`"
|
||||
class="card hover-scale"
|
||||
>
|
||||
<CoverArt :url="pl.coverUrl" :size="160" :radius="10" :show-shadow="true" />
|
||||
<div class="card-name">
|
||||
{{ pl.name }}
|
||||
<span class="platform-badge" :class="badgeClass(pl.platform)">{{ badgeLabel(pl.platform) }}</span>
|
||||
</div>
|
||||
</router-link>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="activeTab === 'songs' && filteredSongs.length" class="result-section">
|
||||
<SongCard
|
||||
v-for="(song, i) in results"
|
||||
v-for="(song, i) in filteredSongs"
|
||||
:key="`${song.platform}-${song.id}`"
|
||||
:song="song"
|
||||
:index="i + 1"
|
||||
@@ -31,48 +111,106 @@
|
||||
@playNext="store.playNextSong(song)"
|
||||
@add="store.addSong(song)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<div v-else-if="searched" class="empty">
|
||||
未找到相关结果
|
||||
</div>
|
||||
<div v-else-if="searched" class="empty">未找到相关结果</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { ref, computed, watch, onMounted } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
import { usePlayerStore } from '../stores/player.js';
|
||||
import type { Song } from '../stores/player.js';
|
||||
import SongCard from '../components/SongCard.vue';
|
||||
import CoverArt from '../components/CoverArt.vue';
|
||||
|
||||
const store = usePlayerStore();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const SOURCE_STORAGE_KEY = 'search-source';
|
||||
|
||||
function loadSource(): 'netease' | 'qq' | 'bilibili' {
|
||||
try {
|
||||
const stored = localStorage.getItem(SOURCE_STORAGE_KEY);
|
||||
if (stored === 'netease' || stored === 'qq' || stored === 'bilibili') return stored;
|
||||
} catch { /* localStorage blocked */ }
|
||||
return 'netease';
|
||||
}
|
||||
|
||||
const query = ref((route.query.q as string) || '');
|
||||
import { Song } from '../stores/player.js';
|
||||
const activeTab = ref<'songs' | 'albums' | 'playlists'>('songs');
|
||||
const selectedSource = ref<'netease' | 'qq' | 'bilibili'>(loadSource());
|
||||
|
||||
const results = ref<Song[]>([]);
|
||||
interface Album { id: string; name: string; artist: string; coverUrl: string; songCount?: number; platform: string; }
|
||||
interface Playlist { id: string; name: string; coverUrl: string; songCount?: number; platform: string; }
|
||||
|
||||
const allSongs = ref<Song[]>([]);
|
||||
const allAlbums = ref<Album[]>([]);
|
||||
const allPlaylists = ref<Playlist[]>([]);
|
||||
const loading = ref(false);
|
||||
const searched = ref(false);
|
||||
|
||||
const filteredSongs = computed(() =>
|
||||
allSongs.value.filter((s) => s.platform === selectedSource.value)
|
||||
);
|
||||
|
||||
const filteredAlbums = computed(() =>
|
||||
allAlbums.value.filter((a) => a.platform === selectedSource.value)
|
||||
);
|
||||
|
||||
const filteredPlaylists = computed(() =>
|
||||
allPlaylists.value.filter((p) => p.platform === selectedSource.value)
|
||||
);
|
||||
|
||||
// Persist source preference
|
||||
watch(selectedSource, (src) => {
|
||||
try { localStorage.setItem(SOURCE_STORAGE_KEY, src); } catch { /* ignore */ }
|
||||
});
|
||||
|
||||
// B站 has no albums/playlists — force songs tab when switching to B站
|
||||
watch(selectedSource, (src) => {
|
||||
if (src === 'bilibili' && activeTab.value !== 'songs') {
|
||||
activeTab.value = 'songs';
|
||||
}
|
||||
});
|
||||
|
||||
async function doSearch() {
|
||||
if (!query.value.trim()) return;
|
||||
loading.value = true;
|
||||
searched.value = true;
|
||||
activeTab.value = 'songs';
|
||||
router.replace({ query: { q: query.value } });
|
||||
try {
|
||||
const res = await axios.get('/api/music/search/all', {
|
||||
params: { q: query.value },
|
||||
});
|
||||
results.value = res.data.songs;
|
||||
const res = await axios.get('/api/music/search/all', { params: { q: query.value } });
|
||||
allSongs.value = res.data.songs ?? [];
|
||||
allAlbums.value = res.data.albums ?? [];
|
||||
allPlaylists.value = res.data.playlists ?? [];
|
||||
} catch {
|
||||
results.value = [];
|
||||
allSongs.value = []; allAlbums.value = []; allPlaylists.value = [];
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function badgeLabel(platform: string): string {
|
||||
if (platform === 'qq') return 'QQ';
|
||||
if (platform === 'bilibili') return 'B站';
|
||||
if (platform === 'youtube') return 'YouTube';
|
||||
return '网易云';
|
||||
}
|
||||
|
||||
function badgeClass(platform: string): string {
|
||||
if (platform === 'qq') return 'badge-qq';
|
||||
if (platform === 'bilibili') return 'badge-bilibili';
|
||||
if (platform === 'youtube') return 'badge-youtube';
|
||||
return 'badge-netease';
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (query.value) doSearch();
|
||||
});
|
||||
@@ -141,4 +279,119 @@ onMounted(() => {
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.source-bar {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.source-btn {
|
||||
padding: 5px 16px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
font-weight: var(--fw-semi);
|
||||
color: var(--text-secondary);
|
||||
background: var(--bg-card);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover { color: var(--text-primary); }
|
||||
|
||||
&.active {
|
||||
color: var(--color-primary);
|
||||
background: rgba(51, 94, 234, 0.12);
|
||||
}
|
||||
}
|
||||
|
||||
.tab-bar {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-bottom: 24px;
|
||||
padding: 4px;
|
||||
background: var(--bg-card);
|
||||
border-radius: var(--radius-md);
|
||||
width: fit-content;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 8px 20px;
|
||||
border-radius: calc(var(--radius-md) - 2px);
|
||||
font-size: 14px;
|
||||
font-family: inherit;
|
||||
font-weight: var(--fw-semi);
|
||||
color: var(--text-secondary);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover { color: var(--text-primary); }
|
||||
|
||||
&.active {
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
.tab-count { opacity: 0.85; }
|
||||
}
|
||||
}
|
||||
|
||||
.tab-count {
|
||||
margin-left: 5px;
|
||||
opacity: 0.55;
|
||||
font-weight: var(--fw-regular);
|
||||
font-size: 13px;
|
||||
|
||||
&::before { content: '('; }
|
||||
&::after { content: ')'; }
|
||||
}
|
||||
|
||||
.result-section {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
.card-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 16px 28px;
|
||||
}
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
.card-name { font-size: 14px; line-height: 1.3; max-height: 2.6em; overflow: hidden; }
|
||||
.card-sub { font-size: 12px; opacity: 0.6; }
|
||||
}
|
||||
|
||||
.platform-badge {
|
||||
vertical-align: middle;
|
||||
flex-shrink: 0;
|
||||
font-size: var(--fs-micro);
|
||||
font-weight: var(--fw-semi);
|
||||
padding: 1px 5px;
|
||||
border-radius: var(--radius-xs);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.badge-netease {
|
||||
background: var(--brand-netease-15);
|
||||
color: var(--brand-netease);
|
||||
}
|
||||
|
||||
.badge-qq {
|
||||
background: var(--brand-qq-15);
|
||||
color: var(--brand-qq);
|
||||
}
|
||||
|
||||
.badge-bilibili {
|
||||
background: var(--brand-bilibili-15);
|
||||
color: var(--brand-bilibili);
|
||||
}
|
||||
|
||||
.badge-youtube {
|
||||
background: var(--brand-youtube-12);
|
||||
color: var(--brand-youtube);
|
||||
}
|
||||
</style>
|
||||
@@ -80,6 +80,10 @@
|
||||
<label>服务器密码(可选)</label>
|
||||
<input v-model="editForm.serverPassword" class="input" type="password" placeholder="服务器有密码时填写" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>自定义头像</label>
|
||||
<CustomAvatarRow :bot-id="editingBot" />
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="btn-secondary" @click="editingBot = null">取消</button>
|
||||
<button class="btn-primary" @click="saveEditBot">保存(需重启机器人生效)</button>
|
||||
|
||||
Reference in new issue
Block a user