diff --git a/README.md b/README.md index 00771da..0b4c050 100644 --- a/README.md +++ b/README.md @@ -381,6 +381,12 @@ QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 → 设置 `QQ_MUSIC_MANAGED_SESSION=0` 并重启可关闭自动续期。机器人继续使用当前的 QQ 播放 Cookie,并从 `cookies/qq.json` 兼容读取旧部署的 Cookie。 +### 每用户音乐账号 + +管理员可在设置中开启「每个成员使用自己的音乐账号」,默认关闭。成员可扫码绑定自己的网易云,也可接受管理员分配的网易云、QQ 音乐、酷狗或 B 站账号。网页搜索、歌单和推荐默认优先使用自己的绑定,其次使用分配账号,最后使用机器人共享账号。成员也可在「我的音乐账号」中主动选择共享账号。房间播歌使用机器人共享账号。 + +从共享账号导入时,账号池保存当前 Cookie 的副本。共享账号续期或更换后,管理员可在账号池中更新该条目的 Cookie。 + ### WebUI 页面说明 | 页面 | 功能 | diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index 184c5a6..e55ce5e 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -396,6 +396,20 @@ const resolveAndPlay = BotInstance.prototype.resolveAndPlay as ( this: unknown, song: any, ) => Promise; + +it("re-resolves an active web FM account before fetching more songs", async () => { + const old = { platform: "netease", getCookie: () => "old", getPersonalFm: vi.fn(async () => []) }; + const shared = { platform: "netease", getCookie: () => "shared", getPersonalFm: vi.fn(async () => []) }; + const context = { + isFmMode: true, + fmProvider: old, + resolveFmProvider: () => shared, + logger: { error: vi.fn() }, + }; + await (BotInstance.prototype as unknown as { refillFm(): Promise }).refillFm.call(context); + expect(old.getPersonalFm).not.toHaveBeenCalled(); + expect(shared.getPersonalFm).toHaveBeenCalledOnce(); +}); const setupPlayerEvents = (BotInstance.prototype as any).setupPlayerEvents as ( this: unknown, ) => void; diff --git a/src/bot/instance.ts b/src/bot/instance.ts index b2412cb..c0d89e8 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -9,6 +9,7 @@ import { import { AudioPlayer } from "../audio/player.js"; import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js"; import type { MusicProvider, Platform, Song } from "../music/provider.js"; +import { musicRequestError } from "../music/request-error.js"; import { parseCommand, canRunCommand, @@ -198,6 +199,7 @@ export class BotInstance extends EventEmitter { private profileManager: BotProfileManager; private isFmMode = false; private fmProvider: MusicProvider | null = null; + private resolveFmProvider?: () => MusicProvider; private fmRequesterName: string | undefined; /** Results of the most recent !search, for "#N" selection (issue #90). */ private lastSearchResults: Song[] = []; @@ -980,6 +982,7 @@ export class BotInstance extends EventEmitter { private disableFmMode(): void { this.isFmMode = false; this.fmProvider = null; + this.resolveFmProvider = undefined; this.fmRequesterName = undefined; } @@ -1807,7 +1810,11 @@ export class BotInstance extends EventEmitter { return this.startFm(this.getProvider(cmd.flags), requesterName); } - async startFm(provider: MusicProvider = this.neteaseProvider, requesterName?: string): Promise { + async startFm( + provider: MusicProvider = this.neteaseProvider, + requesterName?: string, + resolveProvider?: () => MusicProvider, + ): Promise { // Match the !fm chat-command guard: refuse before mutating the queue when // offline, so the web /fm route can't wipe the queue + flip into FM mode // while nothing can actually play. @@ -1829,6 +1836,7 @@ export class BotInstance extends EventEmitter { this.queue.setMode(PlayMode.Random); this.isFmMode = true; this.fmProvider = provider; + this.resolveFmProvider = resolveProvider; this.fmRequesterName = requesterName?.trim() || undefined; this.player.resetFailures(); @@ -1874,17 +1882,23 @@ export class BotInstance extends EventEmitter { } private async refillFm(): Promise { - const provider = this.fmProvider; - if (!this.isFmMode || !provider?.getPersonalFm) return; + if (!this.isFmMode || !this.fmProvider) return; + const resolveProvider = this.resolveFmProvider; try { + const current = this.fmProvider; + const resolved = resolveProvider?.() ?? current; + // Keep a provider's FM cursor while its login remains unchanged. + const provider = resolved !== current && resolved.getCookie() !== current.getCookie() ? resolved : current; + this.fmProvider = provider; + if (!provider.getPersonalFm) return; const songs = await provider.getPersonalFm(); - if (songs.length === 0) return; + if (!this.isFmMode || this.fmProvider !== provider || this.resolveFmProvider !== resolveProvider || songs.length === 0) return; for (const song of songs) { this.queue.add(this.withRequester({ ...song, platform: provider.platform }, this.fmRequesterName)); } this.logger.debug({ count: songs.length, platform: provider.platform }, "FM queue refilled"); } catch (err) { - this.logger.error({ err }, "Failed to refill FM queue"); + this.logger.error({ err: musicRequestError(err) }, "Failed to refill FM queue"); } } @@ -2037,6 +2051,7 @@ export class BotInstance extends EventEmitter { if (st.isFmMode && st.fmPlatform) { this.isFmMode = true; this.fmProvider = this.getProviderFor(st.fmPlatform as Platform); + this.resolveFmProvider = undefined; } const current = this.queue.current(); if (current) { diff --git a/src/data/config.ts b/src/data/config.ts index 898a5bc..a84df34 100755 --- a/src/data/config.ts +++ b/src/data/config.ts @@ -130,6 +130,13 @@ export interface BotConfig { * persisted/restored until an operator opts in. */ savedQueuesEnabled: boolean; + /** + * Per-user music accounts (admin-controlled, default false). When on, a web + * user who linked their own platform account (Settings → 我的音乐账号) reads + * search results, playlists and recommendations through their linked account + * or an account assigned by an admin. Room playback uses the shared account. + */ + perUserMusicAccounts: boolean; /** * When true, a single-song immediate !play (chat) / play-song (web) inserts * after the current track and jumps to it instead of clearing the queue, so @@ -191,6 +198,7 @@ export function getDefaultConfig(): BotConfig { idleTimeoutMinutes: 0, localAudioEnabled: true, savedQueuesEnabled: false, + perUserMusicAccounts: false, playKeepsQueue: false, publicUrl: "", trustProxy: false, @@ -394,6 +402,9 @@ export function loadConfig(path: string): BotConfig { // them (`"yes"`, `1`, `null` → false; only a literal `true` enables). const savedQueuesEnabled = partial.savedQueuesEnabled === true; const playKeepsQueue = partial.playKeepsQueue === true; + // Same strict-coercion rule: a legacy config without the key, or a + // hand-edited `"yes"`/`1`, must never turn account isolation on by accident. + const perUserMusicAccounts = partial.perUserMusicAccounts === true; // Voice ducking is opt-in and the retained-volume percentage is consumed // directly by the audio path. Only a plain-object block with correctly @@ -456,6 +467,7 @@ export function loadConfig(path: string): BotConfig { audioQuality, enabledProviders, savedQueuesEnabled, + perUserMusicAccounts, playKeepsQueue, voiceDucking, defaultPlatform: defaultPlatformPref, diff --git a/src/data/database.ts b/src/data/database.ts index 9285685..55f3dac 100644 --- a/src/data/database.ts +++ b/src/data/database.ts @@ -1,4 +1,5 @@ import Database from "better-sqlite3"; +import { randomUUID } from "node:crypto"; import { CAPABILITIES, BOTS_ALL } from "./permissions.js"; import { GUEST_USER_ID, GUEST_USERNAME } from "./users.js"; import type { QueuedSong } from "../audio/queue.js"; @@ -126,6 +127,54 @@ export interface FavoritePlaylist { createdAt: string; } +/** + * A music-platform login the ADMIN owns and may hand out to members + * (`perUserMusicAccounts`, #164 follow-up). + * + * Two separate tables, on purpose: + * - `music_accounts` = the pool. Only the admin writes it. + * - `music_account_grants` = "member X may use account Y". + * + * Keeping grants out of `user_music_cookies` is what makes "self-linked beats + * admin-granted" possible: a member scanning their own QR code must not + * silently overwrite (or be overwritten by) an account the admin assigned, and + * unlinking on the member side must never revoke what the admin granted. + * + * `cookie` is server-side only — the API layer masks it before answering. + */ +export interface MusicAccount { + id: string; + platform: string; + /** Admin-facing name ("网易云-主号"). Members see this instead of a nickname. */ + label: string; + cookie: string; + /** Who provided the login; null = imported from the bot's shared login. */ + ownerId: string | null; + /** 0 = any number of grantees, 1 = exclusive (one member at a time). */ + capacity: number; + enabled: boolean; + createdAt: string; + updatedAt: string; +} + +/** One row of `music_account_grants`, joined with display fields for the UI. */ +export interface MusicAccountGrant { + userId: string; + username: string; + platform: string; + accountId: string; + accountLabel: string; + grantedBy: string; + grantedAt: string; +} + +/** An account resolved FOR a user: what provider-scope needs to build a view. */ +export interface GrantedMusicAccount { + accountId: string; + label: string; + cookie: string; +} + export interface BotDatabase { db: Database.Database; addPlayHistory(entry: PlayHistoryEntry): void; @@ -152,6 +201,54 @@ export interface BotDatabase { getUserMusicCookie(userId: string, platform: string): string | null; setUserMusicCookie(userId: string, platform: string, cookie: string): void; deleteUserMusicCookie(userId: string, platform: string): boolean; + /** null when the member never chose; callers treat that as "prefer own". */ + getUserMusicPreference(userId: string, platform: string): { preferShared: boolean } | null; + setUserMusicPreference(userId: string, platform: string, preferShared: boolean): void; + // Admin-owned account pool + assignments (#164 follow-up). + listMusicAccounts(platform?: string): MusicAccount[]; + getMusicAccount(id: string): MusicAccount | null; + createMusicAccount(input: { + platform: string; + label: string; + cookie: string; + ownerId?: string | null; + capacity?: number; + enabled?: boolean; + }): MusicAccount; + /** + * Partial update; false when the id does not exist or the capacity is too low. + * + * `platform` is intentionally NOT patchable: grants are keyed by + * (userId, platform) while pointing at `accountId`, so moving an account to + * another platform would silently orphan every existing assignment (the + * grant would still say "netease" while the account says "qq"). Re-create the + * account instead — that path preserves the invariant. + */ + updateMusicAccount( + id: string, + patch: Partial>, + ): boolean; + /** Removes the account AND every grant pointing at it (FK cascade). */ + deleteMusicAccount(id: string): boolean; + countMusicAccountGrants(accountId: string): number; + listMusicAccountGrants(accountId: string): MusicAccountGrant[]; + /** Every grant, grouped for the admin overview page. */ + listAllMusicAccountGrants(): MusicAccountGrant[]; + /** + * Assign `accountId` to `userId`, enforcing enabled/capacity in ONE + * transaction so two concurrent assignments cannot both pass the capacity + * check and overshoot an exclusive account. + */ + assignMusicAccount( + userId: string, + accountId: string, + grantedBy: string, + ): + | { ok: true; replacedAccountId: string | null } + | { ok: false; reason: "not_found" | "disabled" | "exclusive" | "full" }; + deleteMusicAccountGrant(userId: string, platform: string, accountId: string): boolean; + /** The account an admin assigned to `userId`, or null. Disabled accounts are skipped. */ + getGrantedMusicAccount(userId: string, platform: string): GrantedMusicAccount | null; // Saved queues (Feature 1) — upsert by (ownerId, name), capped. saveQueue(ownerId: string, name: string, songs: StoredSong[]): SavedQueue; listSavedQueues(ownerId: string, includeShared: boolean): SavedQueueMeta[]; @@ -362,6 +459,52 @@ function initTables(db: Database.Database): void { PRIMARY KEY (userId, platform), FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE ); + + -- Which login a member wants to use for a platform (#164 follow-up). + -- preferShared = 1 means "ignore my own / assigned account and play + -- through the bot's shared login", which is how someone whose own account + -- has no membership still gets to play paid tracks. Default 0 keeps the + -- privacy-first behaviour (own account wins). + CREATE TABLE IF NOT EXISTS user_music_prefs ( + userId TEXT NOT NULL, + platform TEXT NOT NULL, + preferShared INTEGER NOT NULL DEFAULT 0, + updatedAt TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (userId, platform), + FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE + ); + + -- Admin-owned music logins that can be handed out to members (#164 + -- follow-up). Separate from user_music_cookies so a member's own QR login + -- and an admin's assignment never overwrite each other. + CREATE TABLE IF NOT EXISTS music_accounts ( + id TEXT PRIMARY KEY, + platform TEXT NOT NULL, + label TEXT NOT NULL, + cookie TEXT NOT NULL, + ownerId TEXT, + capacity INTEGER NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1, + createdAt TEXT NOT NULL DEFAULT (datetime('now')), + updatedAt TEXT NOT NULL DEFAULT (datetime('now')) + ); + CREATE INDEX IF NOT EXISTS idx_music_accounts_platform ON music_accounts(platform); + + -- "member X may use account Y". PK (userId, platform) = at most one + -- assigned account per platform per member; assigning another replaces it. + -- accountId cascade keeps a deleted account from leaving dangling grants. + CREATE TABLE IF NOT EXISTS music_account_grants ( + userId TEXT NOT NULL, + platform TEXT NOT NULL, + accountId TEXT NOT NULL, + grantedBy TEXT NOT NULL, + grantedAt TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (userId, platform), + FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (accountId) REFERENCES music_accounts(id) ON DELETE CASCADE + ); + CREATE INDEX IF NOT EXISTS idx_music_account_grants_accountId + ON music_account_grants(accountId); `); } @@ -502,6 +645,128 @@ export function createDatabase(dbPath: string): BotDatabase { `DELETE FROM user_music_cookies WHERE userId = ? AND platform = ?`, ); + const selectUserMusicPref = db.prepare( + `SELECT preferShared FROM user_music_prefs WHERE userId = ? AND platform = ?`, + ); + const upsertUserMusicPref = db.prepare(` + INSERT INTO user_music_prefs (userId, platform, preferShared) VALUES (?, ?, ?) + ON CONFLICT(userId, platform) DO UPDATE SET preferShared = excluded.preferShared, updatedAt = datetime('now') + `); + + // ---- Admin-owned account pool (#164 follow-up) ------------------------- + const MUSIC_ACCOUNT_GRANT_SELECT = ` + SELECT g.userId, COALESCE(u.username, g.userId) AS username, g.platform, + g.accountId, a.label AS accountLabel, g.grantedBy, g.grantedAt + FROM music_account_grants g + JOIN music_accounts a ON a.id = g.accountId + LEFT JOIN users u ON u.id = g.userId`; + + const selectMusicAccount = db.prepare(`SELECT * FROM music_accounts WHERE id = ?`); + const selectMusicAccountsAll = db.prepare( + `SELECT * FROM music_accounts ORDER BY platform ASC, createdAt ASC`, + ); + const selectMusicAccountsByPlatform = db.prepare( + `SELECT * FROM music_accounts WHERE platform = ? ORDER BY createdAt ASC`, + ); + const insertMusicAccount = db.prepare(` + INSERT INTO music_accounts (id, platform, label, cookie, ownerId, capacity, enabled) + VALUES (@id, @platform, @label, @cookie, @ownerId, @capacity, @enabled) + `); + const updateMusicAccountStmt = db.prepare(` + UPDATE music_accounts + SET platform = @platform, label = @label, cookie = @cookie, + capacity = @capacity, enabled = @enabled, updatedAt = datetime('now') + WHERE id = @id + AND (@capacity = 0 OR @capacity >= ( + SELECT COUNT(*) FROM music_account_grants WHERE accountId = @id + )) + `); + const deleteMusicAccountStmt = db.prepare(`DELETE FROM music_accounts WHERE id = ?`); + const countGrantsByAccount = db.prepare( + `SELECT COUNT(*) AS c FROM music_account_grants WHERE accountId = ?`, + ); + const selectGrantsByAccount = db.prepare( + `${MUSIC_ACCOUNT_GRANT_SELECT} WHERE g.accountId = ? ORDER BY username ASC`, + ); + const selectGrantsAll = db.prepare( + `${MUSIC_ACCOUNT_GRANT_SELECT} ORDER BY g.platform ASC, username ASC`, + ); + const upsertGrantStmt = db.prepare(` + INSERT INTO music_account_grants (userId, platform, accountId, grantedBy) + VALUES (?, ?, ?, ?) + ON CONFLICT(userId, platform) DO UPDATE SET + accountId = excluded.accountId, + grantedBy = excluded.grantedBy, + grantedAt = datetime('now') + `); + const deleteGrantStmt = db.prepare( + `DELETE FROM music_account_grants WHERE userId = ? AND platform = ? AND accountId = ?`, + ); + // A disabled account is invisible to the resolver, so switching it off is an + // instant, reversible rollback for everyone holding it (shared login returns). + const selectGrantedAccount = db.prepare(` + SELECT a.id AS accountId, a.label, a.cookie + FROM music_account_grants g + JOIN music_accounts a ON a.id = g.accountId + WHERE g.userId = ? AND g.platform = ? AND a.enabled = 1 + `); + + const rowToMusicAccount = (r: Record): MusicAccount => ({ + id: String(r.id), + platform: String(r.platform), + label: String(r.label), + cookie: String(r.cookie), + ownerId: r.ownerId === null || r.ownerId === undefined ? null : String(r.ownerId), + capacity: Number(r.capacity ?? 0), + enabled: Number(r.enabled ?? 1) === 1, + createdAt: String(r.createdAt ?? ""), + updatedAt: String(r.updatedAt ?? ""), + }); + + const selectGrantForUser = db.prepare( + `SELECT accountId FROM music_account_grants WHERE userId = ? AND platform = ?`, + ); + + /** Row → object lookup shared by the read/update paths (no `this` reliance). */ + const getAccountById = (id: string): MusicAccount | null => { + const row = selectMusicAccount.get(id) as Record | undefined; + return row ? rowToMusicAccount(row) : null; + }; + + /** + * Capacity check + grant write in ONE transaction. Reading the holder count + * outside the write would let two admins assigning simultaneously both pass + * the check and overshoot an exclusive account. + */ + const assignMusicAccountTx = db.transaction( + ( + userId: string, + accountId: string, + grantedBy: string, + ): + | { ok: true; replacedAccountId: string | null } + | { ok: false; reason: "not_found" | "disabled" | "exclusive" | "full" } => { + const row = selectMusicAccount.get(accountId) as Record | undefined; + if (!row) return { ok: false, reason: "not_found" }; + const account = rowToMusicAccount(row); + if (!account.enabled) return { ok: false, reason: "disabled" }; + + const existing = selectGrantForUser.get(userId, account.platform) as + | { accountId: string } + | undefined; + // Re-assigning the SAME account is a no-op, not a capacity conflict. + if (existing?.accountId === account.id) return { ok: true, replacedAccountId: null }; + const replacedAccountId = existing ? existing.accountId : null; + + const { c } = countGrantsByAccount.get(account.id) as { c: number }; + if (account.capacity === 1 && c >= 1) return { ok: false, reason: "exclusive" }; + if (account.capacity > 1 && c >= account.capacity) return { ok: false, reason: "full" }; + + upsertGrantStmt.run(userId, account.platform, account.id, grantedBy); + return { ok: true, replacedAccountId }; + }, + ); + // A corrupt/hand-edited songs blob must never throw into a route or the // restore path — degrade to an empty list instead. const parseSongs = (raw: string): StoredSong[] => { @@ -712,6 +977,98 @@ export function createDatabase(dbPath: string): BotDatabase { return deleteUserMusicCookieStmt.run(userId, platform).changes > 0; }, + getUserMusicPreference(userId, platform) { + const row = selectUserMusicPref.get(userId, platform) as + | { preferShared: number } + | undefined; + if (!row) return null; + return { preferShared: Number(row.preferShared) === 1 }; + }, + + setUserMusicPreference(userId, platform, preferShared) { + upsertUserMusicPref.run(userId, platform, preferShared ? 1 : 0); + }, + + listMusicAccounts(platform) { + const rows = platform + ? (selectMusicAccountsByPlatform.all(platform) as Record[]) + : (selectMusicAccountsAll.all() as Record[]); + return rows.map(rowToMusicAccount); + }, + + getMusicAccount(id) { + return getAccountById(id); + }, + + createMusicAccount(input) { + const id = randomUUID(); + insertMusicAccount.run({ + id, + platform: input.platform, + label: input.label, + cookie: input.cookie, + ownerId: input.ownerId ?? null, + // Clamped so a negative capacity can never slip through and make the + // "exclusive" check behave like "unlimited". + capacity: Math.max(0, Math.trunc(input.capacity ?? 0)), + enabled: input.enabled === false ? 0 : 1, + }); + // No `this` hop: the factory's returned object can be destructured without + // losing the lookup. + return getAccountById(id)!; + }, + + updateMusicAccount(id, patch) { + const current = getAccountById(id); + if (!current) return false; + return updateMusicAccountStmt.run({ + id, + // Platform is immutable (see the interface doc): existing grants are + // keyed by the OLD platform and would be orphaned by a move. + platform: current.platform, + label: patch.label ?? current.label, + cookie: patch.cookie ?? current.cookie, + capacity: + patch.capacity === undefined + ? current.capacity + : Math.max(0, Math.trunc(patch.capacity)), + enabled: (patch.enabled ?? current.enabled) ? 1 : 0, + }).changes > 0; + }, + + deleteMusicAccount(id) { + return deleteMusicAccountStmt.run(id).changes > 0; + }, + + countMusicAccountGrants(accountId) { + const row = countGrantsByAccount.get(accountId) as { c: number } | undefined; + return row?.c ?? 0; + }, + + listMusicAccountGrants(accountId) { + return selectGrantsByAccount.all(accountId) as MusicAccountGrant[]; + }, + + listAllMusicAccountGrants() { + return selectGrantsAll.all() as MusicAccountGrant[]; + }, + + assignMusicAccount(userId, accountId, grantedBy) { + return assignMusicAccountTx(userId, accountId, grantedBy); + }, + + deleteMusicAccountGrant(userId, platform, accountId) { + return deleteGrantStmt.run(userId, platform, accountId).changes > 0; + }, + + getGrantedMusicAccount(userId, platform) { + const row = selectGrantedAccount.get(userId, platform) as + | { accountId: string; label: string; cookie: string } + | undefined; + if (!row || !row.cookie.trim()) return null; + return { accountId: row.accountId, label: row.label, cookie: row.cookie }; + }, + saveQueue(ownerId, name, songs) { if (songs.length > MAX_QUEUE_SONGS) { throw new Error(`保存失败:歌曲数量超过上限 ${MAX_QUEUE_SONGS}`); diff --git a/src/music/bilibili.ts b/src/music/bilibili.ts index e77d542..6cf7c6f 100644 --- a/src/music/bilibili.ts +++ b/src/music/bilibili.ts @@ -465,6 +465,27 @@ export class BiliBiliProvider implements MusicProvider { this.cookie = normalizeCookie(cookie); } + /** + * A view of the same provider logged in as another account (#164 follow-up): + * a web user's own B站 login instead of the bot's shared one. Mirrors + * NeteaseProvider.withCookie so the web layer can treat every platform the + * same way. + * + * The anonymous buvid3 identity and the WBI signing key are carried over — + * both are account-independent caches, and re-fetching them per request would + * add two extra round-trips to every search. + */ + withCookie(cookie: string): BiliBiliProvider { + const view = new BiliBiliProvider(); + view.quality = this.quality; + view.buvidCookie = this.buvidCookie; + view.buvidInitialized = this.buvidInitialized; + view.wbiMixinKey = this.wbiMixinKey; + view.wbiKeyFetchedAt = this.wbiKeyFetchedAt; + view.setCookie(cookie); + return view; + } + getCookie(): string { return this.cookie; } diff --git a/src/music/kugou.ts b/src/music/kugou.ts index 52e3781..d793744 100644 --- a/src/music/kugou.ts +++ b/src/music/kugou.ts @@ -471,6 +471,27 @@ export class KugouProvider implements MusicProvider { return this.quality; } + /** + * A view of the same provider logged in as another account (#164 follow-up): + * a web user's own 酷狗 login instead of the bot's shared one. + * + * Kugou signs every request with the device identity (guid/mid) and binds the + * session token to it, so the view MUST reuse this instance's device instead + * of generating a fresh one — otherwise the installed cookie is rejected as + * coming from an unknown device. + */ + withCookie(cookie: string): KugouProvider { + const view = new KugouProvider(); + view.guid = this.guid; + view.mid = this.mid; + // Share the in-flight dfid registration: it is device-scoped, not account- + // scoped, and sharing avoids a duplicate /register/dev per request. + view.dfidPromise = this.dfidPromise; + view.quality = this.quality; + view.setCookie(cookie); + return view; + } + // --- Shared signed request pipeline (mirrors util/request.js) -------------- private async request(opts: { method: "GET" | "POST"; diff --git a/src/music/provider.ts b/src/music/provider.ts index ba9990c..7aa81f5 100644 --- a/src/music/provider.ts +++ b/src/music/provider.ts @@ -134,6 +134,14 @@ export interface MusicProvider { setCookie(cookie: string): void; getCookie(): string; getAuthStatus(): Promise; + /** + * A view of this same provider logged in as another account, without + * disturbing the shared instance. Implemented by the sources that support + * per-account logins — NetEase since #164, QQ / Kugou / Bilibili following in + * the #164 follow-up. The rest simply omit it and the web layer falls back to + * the shared login (see web/api/provider-scope.ts). + */ + withCookie?(cookie: string): MusicProvider; getPersonalFm?(): Promise; getDailyRecommendSongs?(): Promise; getUserPlaylists?(): Promise; diff --git a/src/music/qq.ts b/src/music/qq.ts index 327879f..5a8aefd 100644 --- a/src/music/qq.ts +++ b/src/music/qq.ts @@ -838,6 +838,20 @@ export class QQMusicProvider implements MusicProvider { this.radarPage = 1; } + /** + * A view of the same provider logged in as another account (#164 follow-up): + * a web user's own QQ 音乐 login instead of the bot's shared one. + * + * The per-user view points at the SAME API server (`this.api.defaults.baseURL`) + * — only the cookie differs, so the shared login keeps its own instance. + */ + withCookie(cookie: string): QQMusicProvider { + const view = new QQMusicProvider(this.api.defaults.baseURL ?? ""); + view.quality = this.quality; + view.setCookie(cookie); + return view; + } + getCookie(): string { return this.cookie; } diff --git a/src/music/request-error.ts b/src/music/request-error.ts new file mode 100644 index 0000000..6ee1819 --- /dev/null +++ b/src/music/request-error.ts @@ -0,0 +1,10 @@ +import { isAxiosError } from "axios"; + +/** Axios errors can include music-account cookies in the message or config. */ +export function musicRequestError(error: unknown): Error { + if (isAxiosError(error)) { + const status = error.response?.status; + return new Error(typeof status === "number" ? `Music service request failed (HTTP ${status})` : "Music service request failed"); + } + return error instanceof Error ? error : new Error("Music service request failed"); +} diff --git a/src/web/api/auth.ts b/src/web/api/auth.ts index d75fbc5..e590f05 100644 --- a/src/web/api/auth.ts +++ b/src/web/api/auth.ts @@ -3,12 +3,15 @@ import type { ParamsDictionary } from "express-serve-static-core"; import type { MusicProvider } from "../../music/provider.js"; import type { QQMusicProvider } from "../../music/qq.js"; import { normalizeCookie } from "../../music/cookie-normalize.js"; +import { musicRequestError } from "../../music/request-error.js"; import { YouTubeProvider } from "../../music/youtube.js"; import type { CookieStore } from "../../music/auth.js"; import type { Logger } from "../../logger.js"; import type { BotConfig, JellyfinConfig } from "../../data/config.js"; +import type { BotDatabase } from "../../data/database.js"; import { requirePermission } from "../middleware/requirePermission.js"; import { requireNotGuest } from "../middleware/requireNotGuest.js"; +import { resolveMusicCookie } from "./provider-scope.js"; export function createAuthRouter( neteaseProvider: MusicProvider, @@ -19,7 +22,10 @@ export function createAuthRouter( kugouProvider?: MusicProvider, spotifyProvider?: MusicProvider, jellyfinProvider?: MusicProvider, - config?: BotConfig + config?: BotConfig, + // Per-user music accounts (#164 follow-up). Omitted by unit-test routers → + // every caller keeps seeing the bot's shared login status. + database?: BotDatabase, ): Router { const router = Router(); const qqSession = qqProvider.managedSession; @@ -40,13 +46,56 @@ export function createAuthRouter( try { const platform = req.query.platform as string; const provider = getProvider(platform); + // Per-user accounts (#164 follow-up). Two different questions, two + // different answers: + // + // /api/auth/status → "is the BOT's shared login alive?" This is the + // admin console (Settings → 音乐平台), so an + // admin always gets the shared status even if + // they linked or were assigned a personal one. + // /api/me/music/status → "which account does THIS user actually play + // through?" (personal-music.ts) — that one does + // report the personal/granted view. + // + // For a non-admin the shared nickname/avatar must never be returned: that + // is exactly the leak this feature exists to close, so they get + // loggedIn:false instead until they have an account of their own. + const user = (req as { user?: { id?: string; role?: string } }).user; + // A platform without per-account login support (spotify / jellyfin / + // youtube) keeps reporting the shared status for everyone: the toggle only + // governs sources that can actually build a per-user view. + const perUser = + config?.perUserMusicAccounts === true && + user?.role !== "admin" && + typeof provider.withCookie === "function"; + + if (perUser) { + const own = resolveMusicCookie(req, provider.platform, { database, config }); + if (own && typeof provider.withCookie === "function") { + const view = provider.withCookie(own.cookie); + const status = await view.getAuthStatus(); + res.json({ + platform: provider.platform, + personal: true, + source: own.source, + // Admin-facing name for an assigned account; absent for self-linked. + label: own.label, + ...status, + }); + return; + } + res.json({ platform: provider.platform, loggedIn: false, personal: true, source: "none" }); + return; + } + const status = await provider.getAuthStatus(); logger.debug({ platform, loggedIn: status.loggedIn }, "Auth status check"); const renewal = platform === "qq" ? qqSession?.getStatus() : undefined; - res.json({ platform: provider.platform, ...status, ...renewal }); + res.json({ platform: provider.platform, source: "shared", ...status, ...renewal }); } catch (err) { - logger.error({ err }, "Auth status check failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "Auth status check failed"); + res.status(500).json({ error: error.message }); } }); diff --git a/src/web/api/bot.test.ts b/src/web/api/bot.test.ts index dd111dd..bfc5f22 100644 --- a/src/web/api/bot.test.ts +++ b/src/web/api/bot.test.ts @@ -677,12 +677,12 @@ describe("bot router /settings jellyfin block + enabledProviders", () => { rmSync(tmpDir, { recursive: true, force: true }); }); - function mountBot(): express.Express { + function mountBot(user: unknown = { role: "admin" }): express.Express { const fakeManager = { getAllBots: () => [] } as unknown as BotManager; const avatarStore = createAvatarStore(tmpDir); const app = express(); app.use(express.json()); - app.use((req, _res, next) => { (req as { user?: unknown }).user = { role: "admin" }; next(); }); + app.use((req, _res, next) => { (req as { user?: unknown }).user = user; next(); }); app.use( "/api/bot", createBotRouter( @@ -694,6 +694,14 @@ describe("bot router /settings jellyfin block + enabledProviders", () => { return app; } + it("reserves the music-account policy toggle for administrators", async () => { + const member = mountBot({ role: "member", capabilities: new Set(["bot.manage"]) }); + await request(member).post("/api/bot/settings").send({ perUserMusicAccounts: true }).expect(403); + expect(config.perUserMusicAccounts).toBe(false); + await request(mountBot()).post("/api/bot/settings").send({ perUserMusicAccounts: true }).expect(200); + expect(config.perUserMusicAccounts).toBe(true); + }); + it("GET /settings exposes a masked jellyfin block (no password/apiKey echo)", async () => { config.jellyfin.serverUrl = "https://jf.example.com"; config.jellyfin.password = "secret"; diff --git a/src/web/api/bot.ts b/src/web/api/bot.ts index 043a578..e6f48ce 100755 --- a/src/web/api/bot.ts +++ b/src/web/api/bot.ts @@ -74,6 +74,7 @@ export function createBotRouter( voiceDucking: config.voiceDucking, localAudioEnabled: config.localAudioEnabled, savedQueuesEnabled: config.savedQueuesEnabled, + perUserMusicAccounts: config.perUserMusicAccounts === true, playKeepsQueue: config.playKeepsQueue, adminGroups: config.adminGroups ?? [], guestMode: config.guestMode, @@ -94,6 +95,7 @@ export function createBotRouter( voiceDucking, guestMode, adminGroups, + perUserMusicAccounts, } = req.body; const hasIdle = idleTimeoutMinutes !== undefined; @@ -104,10 +106,16 @@ export function createBotRouter( const hasAutoPause = typeof autoPauseOnEmpty === "boolean"; const hasLocalAudioEnabled = typeof localAudioEnabled === "boolean"; + const hasPerUserMusicAccounts = typeof perUserMusicAccounts === "boolean"; + if (hasPerUserMusicAccounts && req.user?.role !== "admin") { + res.status(403).json({ error: "forbidden" }); + return; + } if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes; if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty; if (hasLocalAudioEnabled) config.localAudioEnabled = localAudioEnabled; + if (hasPerUserMusicAccounts) config.perUserMusicAccounts = perUserMusicAccounts; // Voice ducking is a partial settings block. Merge only known, strictly // valid fields so malformed JSON cannot replace the object or inject NaN / @@ -282,6 +290,7 @@ export function createBotRouter( voiceDucking: config.voiceDucking, localAudioEnabled: config.localAudioEnabled, savedQueuesEnabled: config.savedQueuesEnabled, + perUserMusicAccounts: config.perUserMusicAccounts === true, playKeepsQueue: config.playKeepsQueue, adminGroups: config.adminGroups ?? [], guestMode: config.guestMode, diff --git a/src/web/api/music-accounts.test.ts b/src/web/api/music-accounts.test.ts new file mode 100644 index 0000000..ade21b9 --- /dev/null +++ b/src/web/api/music-accounts.test.ts @@ -0,0 +1,273 @@ +import { describe, it, expect, vi } from "vitest"; +import express from "express"; +import request from "supertest"; +import pino from "pino"; +import { createDatabase } from "../../data/database.js"; +import { createUserStore } from "../../data/users.js"; +import { createMusicAccountsRouter } from "./music-accounts.js"; + +function mount(opts: { cookieStore?: { save: any; load: any }; providers?: Record } = {}) { + const db = createDatabase(":memory:"); + const insert = db.db.prepare( + "INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)", + ); + insert.run("u1", "alice", "x", 0, 0, "member"); + insert.run("u2", "bob", "x", 0, 0, "member"); + insert.run("u3", "carol", "x", 0, 0, "member"); + insert.run("u4", "root2", "x", 0, 0, "admin"); + + const users = createUserStore(db.db); + const providers = opts.providers ?? { + netease: { + platform: "netease", + withCookie: vi.fn(() => ({ getAuthStatus: async () => ({ loggedIn: true, nickname: "主号" }) })), + }, + }; + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + (req as any).user = { id: "admin", username: "admin", role: "admin" }; + next(); + }); + app.use( + "/api/music-accounts", + createMusicAccountsRouter(db, users, providers as any, pino({ level: "silent" }), opts.cookieStore as any), + ); + return { app, db, providers }; +} + +const SECRET = "MUSIC_U=abcdefghijklmnopqrstuvwxyz0123456789"; + +async function seed(app: express.Express, over: Record = {}) { + const res = await request(app) + .post("/api/music-accounts") + .send({ platform: "netease", label: "主号", cookie: SECRET, ...over }); + return res; +} + +describe("admin music account pool", () => { + it("creates an account and never echoes the cookie", async () => { + const { app } = mount(); + const res = await seed(app); + expect(res.status).toBe(201); + expect(res.body.label).toBe("主号"); + expect(res.body.capacity).toBe(0); + expect(res.body.enabled).toBe(true); + expect(JSON.stringify(res.body)).not.toContain(SECRET); + expect(res.body.cookiePreview).toContain("…"); + }); + + it("rejects an unknown platform and a missing cookie", async () => { + const { app } = mount(); + expect((await seed(app, { platform: "deezer" })).status).toBe(400); + expect((await seed(app, { cookie: "" })).status).toBe(400); + expect((await seed(app, { label: "" })).status).toBe(400); + }); + + it("lists accounts with their holders and the assignable users", async () => { + const { app } = mount(); + const created = await seed(app); + await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" }); + + const res = await request(app).get("/api/music-accounts"); + expect(res.status).toBe(200); + expect(res.body.accounts).toHaveLength(1); + expect(res.body.accounts[0].granteeCount).toBe(1); + expect(res.body.accounts[0].grantees[0]).toMatchObject({ userId: "u1", username: "alice" }); + // Guests are excluded from the dropdown by UserStore.listUsers(). + expect(res.body.users.map((u: any) => u.username)).toEqual(["alice", "bob", "carol", "root2"]); + expect(JSON.stringify(res.body)).not.toContain(SECRET); + }); + + it("toggles enabled and capacity", async () => { + const { app } = mount(); + const created = await seed(app); + const res = await request(app) + .patch(`/api/music-accounts/${created.body.id}`) + .send({ enabled: false, capacity: 1, label: "备用" }); + expect(res.body).toEqual(expect.objectContaining({ enabled: false, capacity: 1, label: "备用" })); + }); + + it("enforces exclusive capacity (capacity = 1)", async () => { + const { app } = mount(); + const created = await seed(app, { capacity: 1 }); + const id = created.body.id; + + expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200); + const second = await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u2" }); + expect(second.status).toBe(409); + expect(second.body.error).toBe("account_exclusive"); + expect(second.body.holders).toEqual([{ userId: "u1", username: "alice" }]); + + // Re-assigning the SAME user is idempotent, not a conflict. + expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200); + }); + + it("enforces a numeric capacity", async () => { + const { app } = mount(); + const created = await seed(app, { capacity: 2 }); + const id = created.body.id; + expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200); + expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u2" })).status).toBe(200); + const third = await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u3" }); + expect(third.status).toBe(409); + expect(third.body.error).toBe("account_full"); + }); + + it("allows unlimited grantees when capacity is 0", async () => { + const { app } = mount(); + const created = await seed(app); + for (const userId of ["u1", "u2", "u3", "u4"]) { + expect( + (await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId })).status, + ).toBe(200); + } + // An admin can be a grantee too — "assigning an admin out" is allowed. + const list = await request(app).get("/api/music-accounts"); + expect(list.body.accounts[0].grantees.map((g: any) => g.username).sort()).toEqual([ + "alice", "bob", "carol", "root2", + ]); + }); + + it("refuses an assignment to a missing user", async () => { + const { app } = mount(); + const created = await seed(app); + expect( + (await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "nope" })).status, + ).toBe(404); + }); + + it("refuses an assignment from a disabled account", async () => { + const { app } = mount(); + const created = await seed(app, { enabled: false }); + const res = await request(app) + .post(`/api/music-accounts/${created.body.id}/assign`) + .send({ userId: "u1" }); + expect(res.status).toBe(409); + expect(res.body.error).toBe("account_disabled"); + }); + + it("replaces the previous assignment for the same platform", async () => { + const { app, db } = mount(); + const first = await seed(app, { label: "一号" }); + const second = await seed(app, { label: "二号" }); + await request(app).post(`/api/music-accounts/${first.body.id}/assign`).send({ userId: "u1" }); + const res = await request(app) + .post(`/api/music-accounts/${second.body.id}/assign`) + .send({ userId: "u1" }); + expect(res.body.replacedAccountId).toBe(first.body.id); + + // PK (userId, platform) keeps it to one assigned login per platform. + const grants = db.listAllMusicAccountGrants().filter((g) => g.userId === "u1"); + expect(grants).toHaveLength(1); + expect(grants[0].accountId).toBe(second.body.id); + }); + + it("revokes a single assignment", async () => { + const { app, db } = mount(); + const created = await seed(app); + await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" }); + const res = await request(app).delete(`/api/music-accounts/${created.body.id}/assign/u1`); + expect(res.body).toEqual({ ok: true, removed: true }); + expect(db.getGrantedMusicAccount("u1", "netease")).toBeNull(); + }); + + it("preserves a replacement assignment when an old assignment is revoked", async () => { + const { app, db } = mount(); + const first = await seed(app, { label: "一号" }); + const second = await seed(app, { label: "二号" }); + for (const account of [first, second]) { + await request(app).post(`/api/music-accounts/${account.body.id}/assign`).send({ userId: "u1" }).expect(200); + } + const res = await request(app).delete(`/api/music-accounts/${first.body.id}/assign/u1`).expect(200); + expect(res.body.removed).toBe(false); + expect(db.getGrantedMusicAccount("u1", "netease")?.accountId).toBe(second.body.id); + }); + + it("does not lower the capacity below the current number of assignees", async () => { + const { app, db } = mount(); + const id = (await seed(app)).body.id; + for (const userId of ["u1", "u2"]) { + await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId }).expect(200); + } + await request(app).patch(`/api/music-accounts/${id}`).send({ capacity: 1 }).expect(409); + expect(db.getMusicAccount(id)?.capacity).toBe(0); + }); + + // Deleting the account must not leave grants pointing at a dead row. + it("cascades grantees when the account is deleted", async () => { + const { app, db } = mount(); + const created = await seed(app); + await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" }); + expect((await request(app).delete(`/api/music-accounts/${created.body.id}`)).status).toBe(200); + expect(db.listMusicAccounts()).toHaveLength(0); + expect(db.getGrantedMusicAccount("u1", "netease")).toBeNull(); + }); + + it("probes the login and reports unsupported platforms", async () => { + const { app } = mount(); + const created = await seed(app); + const ok = await request(app).post(`/api/music-accounts/${created.body.id}/probe`); + expect(ok.body).toEqual({ ok: true, loggedIn: true, nickname: "主号" }); + + // kugou without a withCookie implementation → 501, not a crash. + const kugou = await seed(app, { platform: "kugou", label: "酷狗" }); + expect(kugou.status).toBe(201); + expect((await request(app).post(`/api/music-accounts/${kugou.body.id}/probe`)).status).toBe(501); + }); + + it("imports the shared login into the pool", async () => { + const cookieStore = { + save: vi.fn(), + load: vi.fn(() => "MUSIC_U=shared"), + }; + const { app } = mount({ cookieStore }); + const res = await request(app) + .post("/api/music-accounts/import-shared") + .send({ platform: "netease", label: "从共享导入" }); + expect(res.status).toBe(201); + expect(res.body.label).toBe("从共享导入"); + expect(cookieStore.load).toHaveBeenCalledWith("netease"); + }); + + it("409s import-shared when the bot has no shared login", async () => { + const cookieStore = { save: vi.fn(), load: vi.fn(() => "") }; + const { app } = mount({ cookieStore }); + const res = await request(app) + .post("/api/music-accounts/import-shared") + .send({ platform: "netease" }); + expect(res.status).toBe(409); + expect(res.body.error).toBe("no_shared_login"); + }); + + it("imports the running QQ cookie instead of the stale file copy", async () => { + const cookieStore = { save: vi.fn(), load: vi.fn(() => "uin=999; qm_keyst=stale") }; + const qq = { + platform: "qq", + withCookie: vi.fn(), + // 托管会话轮换后,内存里已经是新 cookie,qq.json 还是旧的 + getCookie: () => "uin=1; qm_keyst=rotated", + }; + const { app, db } = mount({ cookieStore, providers: { qq } }); + const res = await request(app) + .post("/api/music-accounts/import-shared") + .send({ platform: "qq", label: "QQ 主号" }); + expect(res.status).toBe(201); + expect(db.listMusicAccounts()[0]?.cookie).toBe("uin=1; qm_keyst=rotated"); + expect(cookieStore.load).not.toHaveBeenCalled(); + // cookie 不出服务器:响应里不能出现完整值 + expect(JSON.stringify(res.body)).not.toContain("rotated"); + }); + + it("409s a QQ import when the running provider has no login", async () => { + const cookieStore = { save: vi.fn(), load: vi.fn(() => "uin=999; qm_keyst=stale") }; + const qq = { platform: "qq", withCookie: vi.fn(), getCookie: () => "" }; + const { app, db } = mount({ cookieStore, providers: { qq } }); + const res = await request(app) + .post("/api/music-accounts/import-shared") + .send({ platform: "qq" }); + expect(res.status).toBe(409); + expect(res.body.error).toBe("no_shared_login"); + expect(db.listMusicAccounts()).toHaveLength(0); + }); +}); diff --git a/src/web/api/music-accounts.ts b/src/web/api/music-accounts.ts new file mode 100644 index 0000000..31ba285 --- /dev/null +++ b/src/web/api/music-accounts.ts @@ -0,0 +1,360 @@ +import { Router } from "express"; +import type { BotDatabase, MusicAccount } from "../../data/database.js"; +import type { MusicProvider } from "../../music/provider.js"; +import type { CookieStore } from "../../music/auth.js"; +import type { UserStore } from "../../data/users.js"; +import type { Logger } from "../../logger.js"; +import { PERSONAL_MUSIC_PLATFORMS } from "./personal-music.js"; + +/** + * Admin console for the music-account pool (#164 follow-up). + * + * Why a pool instead of "everyone links their own account": + * - Most members do not own a paid NetEase/QQ/Kugou login, and the bot's + * shared account is usually the ADMIN's. Handing the shared login to some + * members while giving others their own is exactly the "mixed" case this + * feature has to support. + * - So the admin keeps a pool of logins (`music_accounts`) and assigns one to + * a member (`music_account_grants`). Assignment is per platform, and a + * member can hold at most one assigned account per platform. + * + * The controls that stop assignments from turning into a mess: + * 1. OWN BEATS ASSIGNED. A member who linked their own account ignores the + * assignment entirely (see provider-scope.ts). Assigning never overrides + * a member's own login. + * 2. CAPACITY. `capacity = 1` means exclusive: the API refuses to hand the + * same login to a second member (409). `capacity = 0` means unlimited + * (fine for a throwaway account, NOT for one whose recommendations you + * care about — every grantee writes to that account's history). + * 3. ENABLED FLAG. Disabling an account is an instant, reversible rollback: + * every grantee falls back to their own login / the shared login without + * the grants being deleted. + * 4. DELETE CASCADES. Removing an account deletes its grants in the same + * transaction (FK ON DELETE CASCADE), so no member is left pointing at a + * row that no longer exists. + * 5. COOKIES NEVER LEAVE THE SERVER. Every response carries a masked + * preview only; the full value is only ever written, never read back. + * + * The whole router is admin-only (requireAdmin at the mount point): a member + * with `bot.manage` still must not see what other people are assigned. + */ +export function createMusicAccountsRouter( + database: BotDatabase, + users: UserStore, + providers: Partial>, + logger: Logger, + cookieStore?: CookieStore, +): Router { + const router = Router(); + + const knownPlatforms = new Set(PERSONAL_MUSIC_PLATFORMS); + + /** + * Cookies are bearer credentials: showing one in full once is enough to take + * the account over. The console only ever needs to tell two logins apart. + */ + const maskCookie = (cookie: string): string => { + if (!cookie) return ""; + if (cookie.length <= 16) return "••••••"; + return `${cookie.slice(0, 6)}…${cookie.slice(-4)} (${cookie.length} 字符)`; + }; + + const toWire = (a: MusicAccount) => { + const holders = database.listMusicAccountGrants(a.id); + return { + id: a.id, + platform: a.platform, + label: a.label, + cookiePreview: maskCookie(a.cookie), + ownerId: a.ownerId, + capacity: a.capacity, + enabled: a.enabled, + createdAt: a.createdAt, + updatedAt: a.updatedAt, + // The UI needs the count to grey out "assign" on an exclusive account. + granteeCount: holders.length, + grantees: holders.map((g) => ({ + userId: g.userId, + username: g.username, + grantedAt: g.grantedAt, + })), + // A platform without withCookie stores the cookie but cannot build a + // per-account view yet — surfaced so the admin is not left guessing. + playbackSupported: typeof providers[a.platform]?.withCookie === "function", + }; + }; + + const isPlatform = (v: unknown): v is (typeof PERSONAL_MUSIC_PLATFORMS)[number] => + typeof v === "string" && knownPlatforms.has(v); + + const nonEmpty = (v: unknown, max: number): v is string => + typeof v === "string" && v.trim().length > 0 && v.length <= max; + + const validCapacity = (value: unknown): value is number | undefined => + value === undefined || (typeof value === "number" && Number.isSafeInteger(value) && value >= 0); + + /** Every real (non-guest) user, for the assign dropdown. */ + const assignableUsers = () => + users.listUsers().map((u) => ({ id: u.id, username: u.username, role: u.role })); + + router.get("/", (_req, res) => { + const accounts = database.listMusicAccounts().map(toWire); + res.json({ + accounts, + users: assignableUsers(), + platforms: [...PERSONAL_MUSIC_PLATFORMS].map((p) => ({ + platform: p, + // Only platforms that implement withCookie can actually play back a + // per-user login; the rest accept a paste but fall back to shared. + playbackSupported: typeof providers[p]?.withCookie === "function", + })), + }); + }); + + router.post("/", (req, res) => { + const { platform, label, cookie, capacity, ownerId, enabled } = req.body ?? {}; + if (!isPlatform(platform)) { + res.status(400).json({ error: "unsupported platform" }); + return; + } + if (!nonEmpty(label, 64)) { + res.status(400).json({ error: "label is required (max 64 chars)" }); + return; + } + if (!nonEmpty(cookie, 8192)) { + res.status(400).json({ error: "cookie is required" }); + return; + } + if (!validCapacity(capacity)) { + res.status(400).json({ error: "capacity must be a non-negative integer" }); + return; + } + if (ownerId !== undefined && ownerId !== null && typeof ownerId !== "string") { + res.status(400).json({ error: "ownerId must be a string or null" }); + return; + } + if (enabled !== undefined && typeof enabled !== "boolean") { + res.status(400).json({ error: "enabled must be a boolean" }); + return; + } + const created = database.createMusicAccount({ + platform, + label: label.trim(), + cookie: cookie.trim(), + ownerId: ownerId ?? null, + capacity, + // Creating a disabled account is allowed: it lets the admin stage a + // cookie before handing it out. + enabled: enabled !== false, + }); + logger.info({ accountId: created.id, platform, label: created.label }, "Music account added"); + res.status(201).json(toWire(created)); + }); + + router.patch("/:id", (req, res) => { + const account = database.getMusicAccount(req.params.id); + if (!account) { + res.status(404).json({ error: "not found" }); + return; + } + const { label, cookie, capacity, enabled } = req.body ?? {}; + if (label !== undefined && !nonEmpty(label, 64)) { + res.status(400).json({ error: "invalid label" }); + return; + } + if (cookie !== undefined && !nonEmpty(cookie, 8192)) { + res.status(400).json({ error: "invalid cookie" }); + return; + } + if (!validCapacity(capacity)) { + res.status(400).json({ error: "capacity must be a non-negative integer" }); + return; + } + if (enabled !== undefined && typeof enabled !== "boolean") { + res.status(400).json({ error: "enabled must be a boolean" }); + return; + } + // Replacing the cookie invalidates any device-bound session (Kugou binds + // the token to guid/mid) — the existing grants keep pointing at the row, + // so the admin only has to paste a fresh cookie to fix everyone at once. + const updated = database.updateMusicAccount(account.id, { + label: label === undefined ? undefined : label.trim(), + cookie: cookie === undefined ? undefined : cookie.trim(), + capacity, + enabled, + }); + if (!updated) { + res.status(409).json({ error: "capacity_below_existing_grants" }); + return; + } + logger.info( + { accountId: account.id, enabled: enabled ?? account.enabled }, + "Music account updated", + ); + res.json(toWire(database.getMusicAccount(account.id)!)); + }); + + router.delete("/:id", (req, res) => { + const account = database.getMusicAccount(req.params.id); + if (!account) { + res.status(404).json({ error: "not found" }); + return; + } + // FK ON DELETE CASCADE removes the grants with it, so no member is left + // pointing at a deleted row. `changes` on the parent is what we report. + const deleted = database.deleteMusicAccount(account.id); + logger.info( + { accountId: account.id, platform: account.platform, deleted }, + "Music account removed", + ); + res.json({ ok: deleted, revokedGrants: true }); + }); + + /** + * Assign an account to a user (member OR another admin — an admin can be a + * grantee too, they are just not forced onto the shared login). + */ + router.post("/:id/assign", (req, res) => { + const account = database.getMusicAccount(req.params.id); + if (!account) { + res.status(404).json({ error: "not_found" }); + return; + } + const { userId } = req.body ?? {}; + if (typeof userId !== "string" || !userId) { + res.status(400).json({ error: "userId is required" }); + return; + } + const target = users.findById(userId); + if (!target || target.role === "guest") { + res.status(404).json({ error: "user not found" }); + return; + } + + // Enabled + capacity are enforced inside a single transaction in the data + // layer, so two concurrent assignments cannot both slip past the check. + const result = database.assignMusicAccount(userId, account.id, req.user!.id); + if (!result.ok) { + if (result.reason === "not_found") { + res.status(404).json({ error: "not_found" }); + return; + } + if (result.reason === "disabled") { + res.status(409).json({ error: "account_disabled" }); + return; + } + const holders = database.listMusicAccountGrants(account.id).map((h) => ({ + userId: h.userId, + username: h.username, + })); + if (result.reason === "exclusive") { + res.status(409).json({ error: "account_exclusive", holders }); + return; + } + res.status(409).json({ error: "account_full", capacity: account.capacity, holders }); + return; + } + + logger.info( + { accountId: account.id, userId, replacedAccountId: result.replacedAccountId }, + "Music account assigned", + ); + res.json({ + ok: true, + userId, + username: target.username, + accountId: account.id, + platform: account.platform, + replacedAccountId: result.replacedAccountId, + }); + }); + + router.delete("/:id/assign/:userId", (req, res) => { + const account = database.getMusicAccount(req.params.id); + if (!account) { + res.status(404).json({ error: "not found" }); + return; + } + const removed = database.deleteMusicAccountGrant(req.params.userId, account.platform, account.id); + logger.info( + { accountId: account.id, userId: req.params.userId, removed }, + "Music account assignment revoked", + ); + res.json({ ok: true, removed }); + }); + + /** Live check: is this cookie still logged in? */ + router.post("/:id/probe", async (req, res) => { + const account = database.getMusicAccount(req.params.id); + if (!account) { + res.status(404).json({ error: "not found" }); + return; + } + const provider = providers[account.platform]; + if (!provider || typeof provider.withCookie !== "function") { + res.status(501).json({ error: "playback not supported for this platform" }); + return; + } + try { + const status = await provider.withCookie(account.cookie).getAuthStatus(); + res.json({ ok: true, ...status }); + } catch { + logger.warn({ accountId: account.id }, "Music account probe failed"); + res.status(502).json({ error: "music_account_probe_failed", loggedIn: false }); + } + }); + + /** + * Seed the pool with the login the bot already uses, so an admin who scanned + * the shared account can hand it to selected members without re-scanning. + */ + router.post("/import-shared", (req, res) => { + const { platform, label, capacity } = req.body ?? {}; + // QQ 的共享登录以"运行中的 provider"为准:登录写的是它内存里的 cookie, + // qq.json 只是落盘副本。托管会话轮换凭据之后文件就旧了(#188), + // 从这里导入会把一个过期 cookie 塞进账号池。 + const sharedQq = platform === "qq" ? providers.qq : undefined; + if (!sharedQq && !cookieStore) { + res.status(501).json({ error: "cookie store unavailable" }); + return; + } + if (!isPlatform(platform)) { + res.status(400).json({ error: "unsupported platform" }); + return; + } + if (!validCapacity(capacity)) { + res.status(400).json({ error: "capacity must be a non-negative integer" }); + return; + } + // 没有 qq provider(例如单测只挂了 netease)时仍然回落到 cookie store, + // 所以这个改动对已有平台零影响。 + let cookie: string | undefined; + if (sharedQq) { + try { + cookie = sharedQq.getCookie(); + } catch { + // Provider 还没建立登录态时抛错等价于「没有可导入的登录」 + cookie = ""; + } + } else { + cookie = cookieStore?.load(platform); + } + if (!cookie || !cookie.trim()) { + res.status(409).json({ error: "no_shared_login", platform }); + return; + } + const created = database.createMusicAccount({ + platform, + label: nonEmpty(label, 64) ? label.trim() : `${platform} 共享账号`, + cookie: cookie.trim(), + // ownerId stays null: this login was provided by the bot, not a person. + ownerId: null, + capacity, + enabled: true, + }); + logger.info({ accountId: created.id, platform }, "Shared login imported into pool"); + res.status(201).json(toWire(created)); + }); + + return router; +} diff --git a/src/web/api/music.test.ts b/src/web/api/music.test.ts index 73b8dbd..715825f 100644 --- a/src/web/api/music.test.ts +++ b/src/web/api/music.test.ts @@ -3,6 +3,7 @@ import express from "express"; import cookieParser from "cookie-parser"; import request from "supertest"; import pino from "pino"; +import { AxiosError } from "axios"; import { mkdtempSync, rmSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -58,6 +59,18 @@ describe("music router GET /search offset pagination", () => { expect(res.status).toBe(200); expect(netease.search).toHaveBeenCalledWith("hello", 20, 0); }); + + it("keeps provider request credentials out of search errors", async () => { + const logger = pino({ level: "silent" }); + const logError = vi.spyOn(logger, "error"); + const privateCookie = "MUSIC_U=test-private-session"; + vi.mocked(netease.search).mockRejectedValueOnce(new AxiosError(`Provider request failed: ${privateCookie}`)); + const route = express(); + route.use("/api/music", createMusicRouter(netease, fakeProvider("qq"), fakeProvider("bilibili"), logger)); + const res = await request(route).get("/api/music/search?q=test").expect(500); + expect(res.text).not.toContain(privateCookie); + expect(JSON.stringify(logError.mock.calls)).not.toContain(privateCookie); + }); }); describe("music router provider gating (enabledProviders) + jellyfin endpoints", () => { diff --git a/src/web/api/music.ts b/src/web/api/music.ts index 470f4f0..bd710c4 100644 --- a/src/web/api/music.ts +++ b/src/web/api/music.ts @@ -1,11 +1,14 @@ -import express, { Router, type Response } from "express"; +import express, { Router, type Request, type Response } from "express"; import type { MusicProvider, Song, Album, SearchResult } from "../../music/provider.js"; +import { musicRequestError } from "../../music/request-error.js"; import { YouTubeProvider } from "../../music/youtube.js"; import type { Logger } from "../../logger.js"; import { isProviderEnabled, defaultPlatform, saveConfig, type BotConfig } from "../../data/config.js"; +import type { BotDatabase } from "../../data/database.js"; import { requirePermission } from "../middleware/requirePermission.js"; import { requireNotGuest } from "../middleware/requireNotGuest.js"; import { authorize } from "../middleware/authorize.js"; +import { resolveProviderForRequest } from "./provider-scope.js"; /** * Body cap for a local upload. express.raw buffers the whole body in memory, @@ -70,6 +73,10 @@ export function createMusicRouter( // When set (alongside config), a quality change is persisted to config.json so // it survives a restart (#125). Omitted by unit-test routers → no persistence. configPath?: string, + // Per-user music accounts (#164 follow-up): when config.perUserMusicAccounts + // is on, a request carrying a linked account reads through that account + // instead of the bot's shared login. Omitted by unit-test routers → shared. + database?: BotDatabase, ): Router { const router = Router(); const youtubeProvider: MusicProvider = new YouTubeProvider(); @@ -95,14 +102,25 @@ export function createMusicRouter( * return immediately. Without a config (unit-test routers), everything * stays enabled. */ - function resolveProvider(platform: unknown, res: Response): MusicProvider | null { + function resolveProvider( + platform: unknown, + res: Response, + req?: Request, + ): MusicProvider | null { const requested = typeof platform === "string" && platform ? platform : undefined; const target = requested ?? (config ? defaultPlatform(config) : "netease"); if (config && !isProviderEnabled(config, target)) { res.status(400).json({ error: `音源未启用:${target} (provider disabled)` }); return null; } - return getProvider(target); + // Per-user accounts: with the feature on, a user who linked their own + // account reads search/playlists/lyrics/artists through THAT + // login instead of the bot's shared one, so members stop seeing the + // admin's library. Everyone else keeps the shared provider unchanged. + return resolveProviderForRequest(req, target, getProvider(target), { + database, + config, + }); } router.post( @@ -164,7 +182,7 @@ export function createMusicRouter( res.json({ songs: [], playlists: [], albums: [] }); return; } - const provider = resolveProvider(platform, res); + const provider = resolveProvider(platform, res, req); if (!provider) return; // Server-side pagination: offset lets the web load past the first page. // Clamp to >= 0 so a bad/negative value falls back to the first page. @@ -176,8 +194,9 @@ export function createMusicRouter( ); res.json(result); } catch (err) { - logger.error({ err }, "Search failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "Search failed"); + res.status(500).json({ error: error.message }); } }); @@ -199,13 +218,24 @@ export function createMusicRouter( // enabled — a self-hosted library match is almost always the wanted one. const enabled = (p: string) => !config || isProviderEnabled(config, p); const none: SearchResult = { songs: [], albums: [], playlists: [] }; + // Unified search hits every source at once, so each one has to be scoped + // individually — otherwise a member with their own linked account would + // still get the admin's results merged in from the other platforms. + // Local audio and Jellyfin have no per-account login, so they stay shared. + const scope = { database, config }; + const nProvider = resolveProviderForRequest(req, "netease", neteaseProvider, scope); + const qProvider = resolveProviderForRequest(req, "qq", qqProvider, scope); + const bProvider = resolveProviderForRequest(req, "bilibili", bilibiliProvider, scope); + const kProvider = kugouProvider + ? resolveProviderForRequest(req, "kugou", kugouProvider, scope) + : kugouProvider; const [jellyfinResult, neteaseResult, qqResult, bilibiliResult, localResult, kugouResult] = await Promise.allSettled([ jellyfinProvider && enabled("jellyfin") ? jellyfinProvider.search(q as string, parsedLimit) : Promise.resolve(none), - enabled("netease") ? neteaseProvider.search(q as string, parsedLimit) : Promise.resolve(none), - enabled("qq") ? qqProvider.search(q as string, parsedLimit) : Promise.resolve(none), - enabled("bilibili") ? bilibiliProvider.search(q as string, parsedLimit) : Promise.resolve(none), + enabled("netease") ? nProvider.search(q as string, parsedLimit) : Promise.resolve(none), + enabled("qq") ? qProvider.search(q as string, parsedLimit) : Promise.resolve(none), + enabled("bilibili") ? bProvider.search(q as string, parsedLimit) : Promise.resolve(none), localProvider && isLocalAudioEnabled() ? localProvider.search(q as string, parsedLimit) : Promise.resolve(none), - kugouProvider && enabled("kugou") ? kugouProvider.search(q as string, parsedLimit) : Promise.resolve(none), + kProvider && enabled("kugou") ? kProvider.search(q as string, parsedLimit) : Promise.resolve(none), ]); const songs = [ @@ -235,8 +265,9 @@ export function createMusicRouter( res.json({ songs, albums, playlists, artists }); } catch (err) { - logger.error({ err }, "Unified search failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "Unified search failed"); + res.status(500).json({ error: error.message }); } }); @@ -246,7 +277,7 @@ export function createMusicRouter( res.status(403).json({ error: "本地音频播放已关闭" }); return; } - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; const song = await provider.getSongDetail(req.params.id); if (!song) { @@ -255,57 +286,57 @@ export function createMusicRouter( } res.json(song); } catch (err) { - res.status(500).json({ error: (err as Error).message }); + res.status(500).json({ error: musicRequestError(err).message }); } }); router.get("/playlist/:id", async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; const songs = await provider.getPlaylistSongs(req.params.id); res.json({ songs }); } catch (err) { - res.status(500).json({ error: (err as Error).message }); + res.status(500).json({ error: musicRequestError(err).message }); } }); router.get("/recommend/playlists", async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; const playlists = await provider.getRecommendPlaylists(); res.json({ playlists }); } catch (err) { - res.status(500).json({ error: (err as Error).message }); + res.status(500).json({ error: musicRequestError(err).message }); } }); router.get("/album/:id", async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; const songs = await provider.getAlbumSongs(req.params.id); res.json({ songs }); } catch (err) { - res.status(500).json({ error: (err as Error).message }); + res.status(500).json({ error: musicRequestError(err).message }); } }); router.get("/lyrics/:id", async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; const lyrics = await provider.getLyrics(req.params.id); res.json({ lyrics }); } catch (err) { - res.status(500).json({ error: (err as Error).message }); + res.status(500).json({ error: musicRequestError(err).message }); } }); router.get("/artist/:id", async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; if (!provider.getArtistDetail) { res.status(501).json({ error: "Not supported by this provider" }); @@ -329,13 +360,13 @@ export function createMusicRouter( } res.json({ artist, songs, albums }); } catch (err) { - res.status(500).json({ error: (err as Error).message }); + res.status(500).json({ error: musicRequestError(err).message }); } }); router.get("/recommend/songs", requireNotGuest, async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; if (!provider.getDailyRecommendSongs) { res.status(501).json({ error: "Not supported by this provider" }); @@ -344,14 +375,15 @@ export function createMusicRouter( const songs = await provider.getDailyRecommendSongs(); res.json({ songs }); } catch (err) { - logger.error({ err }, "Get daily recommend songs failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "Get daily recommend songs failed"); + res.status(500).json({ error: error.message }); } }); router.get("/personal/fm", requireNotGuest, async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; if (!provider.getPersonalFm) { res.status(501).json({ error: "Not supported by this provider" }); @@ -360,14 +392,15 @@ export function createMusicRouter( const songs = await provider.getPersonalFm(); res.json({ songs }); } catch (err) { - logger.error({ err }, "Get personal FM failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "Get personal FM failed"); + res.status(500).json({ error: error.message }); } }); router.get("/user/playlists", requireNotGuest, async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; if (!provider.getUserPlaylists) { res.status(501).json({ error: "Not supported by this provider" }); @@ -376,14 +409,15 @@ export function createMusicRouter( const playlists = await provider.getUserPlaylists(); res.json({ playlists }); } catch (err) { - logger.error({ err }, "Get user playlists failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "Get user playlists failed"); + res.status(500).json({ error: error.message }); } }); router.get("/playlist/:id/detail", async (req, res) => { try { - const provider = resolveProvider(req.query.platform, res); + const provider = resolveProvider(req.query.platform, res, req); if (!provider) return; if (!provider.getPlaylistDetail) { res.status(501).json({ error: "Not supported by this provider" }); @@ -396,8 +430,9 @@ export function createMusicRouter( } res.json({ playlist: detail }); } catch (err) { - logger.error({ err }, "Get playlist detail failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "Get playlist detail failed"); + res.status(500).json({ error: error.message }); } }); diff --git a/src/web/api/personal-music.test.ts b/src/web/api/personal-music.test.ts index 8faf1ad..b6295ad 100644 --- a/src/web/api/personal-music.test.ts +++ b/src/web/api/personal-music.test.ts @@ -6,7 +6,10 @@ import { createDatabase } from "../../data/database.js"; import { createPersonalMusicRouter } from "./personal-music.js"; import { createPlayerRouter } from "./player.js"; -function mount() { +function mount(opts: { + config?: { perUserMusicAccounts?: boolean }; + extraProviders?: Record; +} = {}) { const db = createDatabase(":memory:"); db.db .prepare("INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)") @@ -27,16 +30,38 @@ function mount() { (req as any).user = { id: "u1", username: "alice", role: "member" }; next(); }); - app.use("/api/me/music", createPersonalMusicRouter(db, provider, pino({ level: "silent" }))); + app.use( + "/api/me/music", + createPersonalMusicRouter( + db, + { netease: provider, ...(opts.extraProviders as object) }, + pino({ level: "silent" }), + opts.config, + ), + ); return { app, db, provider, personalView }; } +/** Seed an admin-owned account and assign it to u1. */ +function assignAccount(db: ReturnType, label = "网易云-主号") { + const account = db.createMusicAccount({ + platform: "netease", + label, + cookie: "MUSIC_U=granted", + }); + db.assignMusicAccount("u1", account.id, "admin"); + return account; +} + describe("personal music account router (#164)", () => { it("reports not linked until the user logs in", async () => { const { app } = mount(); const res = await request(app).get("/api/me/music/netease/status"); expect(res.status).toBe(200); - expect(res.body).toEqual({ linked: false, loggedIn: false }); + expect(res.body).toEqual({ + linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true, + preferShared: false, featureEnabled: false, + }); }); it("creates a QR code", async () => { @@ -64,7 +89,16 @@ describe("personal music account router (#164)", () => { const { app, db, provider } = mount(); db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice"); const res = await request(app).get("/api/me/music/netease/status"); - expect(res.body).toEqual({ linked: true, loggedIn: true, nickname: "Alice163" }); + expect(res.body).toEqual({ + linked: true, + source: "personal", + canUnlink: true, + supportsQrLogin: true, + preferShared: false, + featureEnabled: false, + loggedIn: true, + nickname: "Alice163", + }); expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=alice"); }); @@ -74,6 +108,62 @@ describe("personal music account router (#164)", () => { expect((await request(app).delete("/api/me/music/netease")).status).toBe(200); expect(db.getUserMusicCookie("u1", "netease")).toBeNull(); }); + + // 404 for a platform this build does not expose — keeps the param route from + // silently answering "not linked" for a typo'd URL. + it("404s an unknown platform", async () => { + const { app } = mount(); + expect((await request(app).get("/api/me/music/deezer/status")).status).toBe(404); + }); + + // qq/kugou/bilibili ship withCookie but not pollQrLogin yet: linking is 501, + // while an admin-assigned account still works (see below). + it("501s QR login on a platform without per-user polling", async () => { + const { app } = mount({ extraProviders: { qq: { platform: "qq", withCookie: vi.fn() } } }); + expect((await request(app).post("/api/me/music/qq/qrcode")).status).toBe(501); + }); + + describe("admin-assigned account", () => { + it("reports source=granted with the admin's label and forbids unlinking", async () => { + const { app, db, provider } = mount({ config: { perUserMusicAccounts: true } }); + assignAccount(db); + const res = await request(app).get("/api/me/music/netease/status"); + expect(res.body).toEqual({ + linked: true, + source: "granted", + label: "网易云-主号", + canUnlink: false, + supportsQrLogin: true, + preferShared: false, + featureEnabled: true, + loggedIn: true, + nickname: "Alice163", + }); + expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=granted"); + }); + + it("is invisible while the admin toggle is off", async () => { + const { app, db } = mount({ config: { perUserMusicAccounts: false } }); + assignAccount(db); + const res = await request(app).get("/api/me/music/netease/status"); + expect(res.body).toEqual({ + linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true, + preferShared: false, featureEnabled: false, + }); + }); + + // Unlinking on the member side must never revoke what the admin granted: + // the two live in separate tables on purpose. + it("survives a member unlink and is reported as the fallback", async () => { + const { app, db } = mount({ config: { perUserMusicAccounts: true } }); + assignAccount(db); + db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice"); + const res = await request(app).delete("/api/me/music/netease"); + expect(res.body).toEqual({ ok: true, removed: true, fallback: "granted" }); + expect(db.getUserMusicCookie("u1", "netease")).toBeNull(); + expect(db.getGrantedMusicAccount("u1", "netease")?.cookie).toBe("MUSIC_U=granted"); + }); + }); }); describe("web FM uses the caller's linked NetEase account (#164)", () => { @@ -123,3 +213,73 @@ describe("web FM uses the caller's linked NetEase account (#164)", () => { expect(bot.startFm.mock.calls[0][0]).toBe(qq); }); }); + +// --------------------------------------------------------------------------- +// "Play through the shared account" preference (#164 follow-up) +// +// The case this exists for: the member's own NetEase login has no VIP, the +// admin's does. The preference is per-platform and per-user, and it must not +// touch either stored login. +// --------------------------------------------------------------------------- +describe("personal music — shared-account preference", () => { + const ON = { config: { perUserMusicAccounts: true } }; + + it("defaults to the member's own account", async () => { + const { app } = mount(ON); + const res = await request(app).get("/api/me/music/netease/preference"); + expect(res.status).toBe(200); + expect(res.body).toEqual({ platform: "netease", preferShared: false }); + }); + + it("stores the choice and reports it back", async () => { + const { app } = mount(ON); + const put = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + expect(put.status).toBe(200); + expect(put.body).toEqual({ platform: "netease", preferShared: true }); + + const get = await request(app).get("/api/me/music/netease/preference"); + expect(get.body.preferShared).toBe(true); + }); + + it("keeps the choice per platform", async () => { + const { app } = mount({ + ...ON, + extraProviders: { qq: { platform: "qq", withCookie: () => ({ getAuthStatus: async () => ({ loggedIn: true }) }) } }, + }); + await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + const qq = await request(app).get("/api/me/music/qq/preference"); + expect(qq.body.preferShared).toBe(false); + }); + + it("does not touch the stored login", async () => { + const { app, db } = mount(ON); + db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine"); + await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + + expect(db.getUserMusicCookie("u1", "netease")).toBe("MUSIC_U=mine"); + expect(db.getUserMusicPreference("u1", "netease")).toEqual({ preferShared: true }); + }); + + it("surfaces the choice on the status payload the UI already reads", async () => { + const { app, db } = mount(ON); + db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine"); + await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + + const res = await request(app).get("/api/me/music/netease/status"); + expect(res.body.preferShared).toBe(true); + expect(res.body.featureEnabled).toBe(true); + }); + + it("rejects a non-boolean", async () => { + const { app } = mount(ON); + const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: "yes" }); + expect(res.status).toBe(400); + }); + + it("refuses when the admin has the feature off", async () => { + const { app } = mount({ config: { perUserMusicAccounts: false } }); + const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + expect(res.status).toBe(409); + expect(res.body.error).toBe("per_user_accounts_disabled"); + }); +}); diff --git a/src/web/api/personal-music.ts b/src/web/api/personal-music.ts index dfc3007..a3125fd 100644 --- a/src/web/api/personal-music.ts +++ b/src/web/api/personal-music.ts @@ -2,6 +2,7 @@ import { Router } from "express"; import type { BotDatabase } from "../../data/database.js"; import type { MusicProvider, QrCodeResult } from "../../music/provider.js"; import type { Logger } from "../../logger.js"; +import { perUserMusicEnabled, type MusicScopeDeps } from "./provider-scope.js"; /** * A provider that can log a web user into their OWN account without touching @@ -17,56 +18,165 @@ export function supportsPersonalLogin( provider: MusicProvider | undefined, ): provider is MusicProvider & PersonalLoginProvider { const p = provider as Partial | undefined; - return typeof p?.pollQrLogin === "function" && typeof p.withCookie === "function"; + return typeof p?.pollQrLogin === "function" && typeof p?.withCookie === "function"; } +/** Platforms a member can link an account for. Kept in sync with the providers map. */ +export const PERSONAL_MUSIC_PLATFORMS = ["netease", "qq", "kugou", "bilibili"] as const; + /** - * The caller's own NetEase account, used for their personal FM instead of the - * bot's shared login (#164). Every route acts on req.user only; the cookie is - * stored server-side and never sent back to the browser. + * A web user's own music account (#164), generalised to every platform that + * implements `withCookie` (#164 follow-up). + * + * Three states are reported, and the member UI needs all three: + * - `personal`: the caller scanned their own QR code. They may unlink it. + * - `granted` : an ADMIN assigned one of the pool accounts to them. It cannot + * be unlinked from here — only the admin can take it back — + * which is why `canUnlink` is part of the payload instead of + * the UI guessing from `linked`. + * - `none` : nothing linked; playback falls back to the bot's shared login. + * + * The cookie is stored server-side and never sent back to the browser; the + * `label` of an assigned account is what the member sees instead of a nickname. */ export function createPersonalMusicRouter( database: BotDatabase, - neteaseProvider: MusicProvider, + providers: Partial>, logger: Logger, + config?: MusicScopeDeps["config"], ): Router { const router = Router(); - const platform = "netease"; - router.use((_req, res, next) => { - if (!supportsPersonalLogin(neteaseProvider)) { - res.status(501).json({ error: "Personal login not supported" }); + const providerFor = (platform: string): MusicProvider | undefined => providers[platform]; + + /** 404 for platforms this build does not expose at all. */ + router.param("platform", (req, res, next, platform: string) => { + if (!providerFor(platform)) { + res.status(404).json({ error: `Unknown platform: ${platform}` }); return; } next(); }); - const provider = neteaseProvider as MusicProvider & PersonalLoginProvider; - router.get("/netease/status", async (req, res) => { - const cookie = database.getUserMusicCookie(req.user!.id, platform); - if (!cookie) { - res.json({ linked: false, loggedIn: false }); + /** Read the account state for one platform: own first, then admin-assigned. */ + const describeAccount = ( + userId: string, + platform: string, + ): { source: "personal" | "granted" | "none"; cookie: string | null; label?: string; canUnlink: boolean } => { + const own = database.getUserMusicCookie(userId, platform); + if (own && own.trim()) { + return { source: "personal", cookie: own, canUnlink: true }; + } + // An assignment only exists because the admin turned the feature on, so it + // stops applying the moment the toggle goes off (same rule as playback). + if (perUserMusicEnabled({ database, config })) { + const granted = database.getGrantedMusicAccount(userId, platform); + if (granted) { + return { source: "granted", cookie: granted.cookie, label: granted.label, canUnlink: false }; + } + } + return { source: "none", cookie: null, canUnlink: false }; + }; + + router.get("/:platform/status", async (req, res) => { + const platform = req.params.platform; + const provider = providerFor(platform)!; + const account = describeAccount(req.user!.id, platform); + // Lets the member UI hide "扫码绑定" on platforms that only accept an + // admin-assigned account (qq / kugou / bilibili today). + const supportsQrLogin = supportsPersonalLogin(provider); + // The member's explicit "play through the shared login" choice, so the UI + // can render the radio without a second round-trip. + const preferShared = + database.getUserMusicPreference(req.user!.id, platform)?.preferShared === true; + // The choice only exists while the admin has per-user accounts on; with it + // off everyone is already on the shared login and the radio is meaningless. + const featureEnabled = perUserMusicEnabled({ database, config }); + + if (!account.cookie) { + res.json({ + linked: false, + loggedIn: false, + source: "none", + canUnlink: false, + supportsQrLogin, + preferShared, + featureEnabled, + }); + return; + } + if (typeof provider.withCookie !== "function") { + // Account stored but this platform cannot build a per-account view yet. + res.json({ + linked: true, + loggedIn: false, + source: account.source, + label: account.label, + canUnlink: account.canUnlink, + supportsQrLogin, + preferShared, + featureEnabled, + unsupported: true, + }); return; } try { - const status = await provider.withCookie(cookie).getAuthStatus(); - res.json({ linked: true, ...status }); - } catch (err) { - logger.warn({ err }, "Personal NetEase status check failed"); - res.json({ linked: true, loggedIn: false }); + const status = await provider.withCookie(account.cookie).getAuthStatus(); + res.json({ + linked: true, + source: account.source, + label: account.label, + canUnlink: account.canUnlink, + supportsQrLogin, + preferShared, + featureEnabled, + ...status, + }); + } catch { + logger.warn({ platform, source: account.source }, "Personal music status check failed"); + res.json({ + linked: true, + loggedIn: false, + source: account.source, + label: account.label, + canUnlink: account.canUnlink, + supportsQrLogin, + preferShared, + featureEnabled, + }); } }); - router.post("/netease/qrcode", async (_req, res) => { + router.post("/:platform/qrcode", async (req, res) => { + const platform = req.params.platform; + const provider = providerFor(platform)!; + if (!supportsPersonalLogin(provider)) { + // Only NetEase ships "poll and hand back the cookie" today. The other + // platforms can still receive an admin-assigned account. + res.status(501).json({ + error: "Personal QR login is not implemented for this platform yet", + platform, + }); + return; + } try { res.json(await provider.getQrCode()); } catch (err) { - logger.error({ err }, "Personal NetEase QR generation failed"); + logger.error({ err, platform }, "Personal music QR generation failed"); res.status(500).json({ error: (err as Error).message }); } }); - router.get("/netease/qrcode/status", async (req, res) => { + router.get("/:platform/qrcode/status", async (req, res) => { + const platform = req.params.platform; + const provider = providerFor(platform)!; + if (!supportsPersonalLogin(provider)) { + res.status(501).json({ + error: "Personal QR login is not implemented for this platform yet", + platform, + }); + return; + } const key = req.query.key; if (typeof key !== "string" || !key) { res.status(400).json({ error: "key is required" }); @@ -80,15 +190,62 @@ export function createPersonalMusicRouter( } res.json({ status }); } catch (err) { - logger.error({ err }, "Personal NetEase QR status check failed"); + logger.error({ err, platform }, "Personal music QR status check failed"); res.status(500).json({ error: (err as Error).message }); } }); - router.delete("/netease", (req, res) => { - database.deleteUserMusicCookie(req.user!.id, platform); - logger.info({ userId: req.user!.id, platform }, "Personal music account unlinked"); - res.json({ ok: true }); + router.delete("/:platform", (req, res) => { + const platform = req.params.platform; + const userId = req.user!.id; + // Only the member's OWN login is removed. An admin-assigned account lives + // in a different table and must stay put — otherwise a member could revoke + // (or accidentally destroy) what the admin handed them. + const removed = database.deleteUserMusicCookie(userId, platform); + if (removed) { + logger.info({ userId, platform }, "Personal music account unlinked"); + } + const remaining = describeAccount(userId, platform); + res.json({ + ok: true, + removed, + // What playback falls back to now — the member UI shows the right hint. + fallback: remaining.source === "granted" ? "granted" : "shared", + }); + }); + + /** + * Which login this member plays through. + * + * `preferShared: true` = ignore my own (and any assigned) account and use the + * bot's shared login — the admin's, usually the one with a membership. It is + * the answer to "my NetEase account has no VIP, the admin's does, and I want + * the paid track". Nothing is deleted: flipping it back restores the personal + * account exactly as it was. + */ + router.put("/:platform/preference", (req, res) => { + const platform = req.params.platform; + const { preferShared } = req.body ?? {}; + if (typeof preferShared !== "boolean") { + res.status(400).json({ error: "preferShared must be a boolean" }); + return; + } + // With the feature off there is nothing to choose between — everything + // already runs on the shared login. Refuse instead of storing a value that + // would silently do nothing. + if (!perUserMusicEnabled({ database, config })) { + res.status(409).json({ error: "per_user_accounts_disabled" }); + return; + } + database.setUserMusicPreference(req.user!.id, platform, preferShared); + logger.info({ userId: req.user!.id, platform, preferShared }, "Music account preference set"); + res.json({ platform, preferShared }); + }); + + router.get("/:platform/preference", (req, res) => { + const platform = req.params.platform; + const pref = database.getUserMusicPreference(req.user!.id, platform); + res.json({ platform, preferShared: pref?.preferShared === true }); }); return router; diff --git a/src/web/api/player.ts b/src/web/api/player.ts index ef6f948..79ece27 100644 --- a/src/web/api/player.ts +++ b/src/web/api/player.ts @@ -1,12 +1,13 @@ -import { Router } from "express"; +import { Router, type Request } from "express"; import type { BotManager } from "../../bot/manager.js"; import type { BotDatabase } from "../../data/database.js"; import type { MusicProvider, Song, ArtistSongPage } from "../../music/provider.js"; +import { musicRequestError } from "../../music/request-error.js"; import type { Logger } from "../../logger.js"; import { parseCommand } from "../../bot/commands.js"; import { requireBotAccess } from "../middleware/requirePermission.js"; import { authorize } from "../middleware/authorize.js"; -import { supportsPersonalLogin } from "./personal-music.js"; +import { resolveProviderForRequest } from "./provider-scope.js"; /** Hard cap on how many tracks one "播放全部" request may queue — a safety net * against a pathological catalogue (and against an upstream paging bug). */ @@ -46,9 +47,39 @@ export function createPlayerRouter( neteaseProvider?: MusicProvider, qqProvider?: MusicProvider, bilibiliProvider?: MusicProvider, + // Per-user music accounts (#164 follow-up). Omitted by unit-test routers → + // the feature reads as off and every request uses the shared login. + config?: { perUserMusicAccounts?: boolean }, ): Router { const router = Router(); + /** Platform names the bot resolves as-is; anything else means NetEase. */ + const PASSTHROUGH = new Set(["bilibili", "qq", "youtube", "local", "kugou", "jellyfin"]); + const sharedProviderFor = (bot: any, platform: unknown): MusicProvider => + bot.getProviderFor(PASSTHROUGH.has(platform as string) ? platform : "netease"); + + /** + * The provider this request should read from. With per-user accounts enabled, + * a caller who linked their own account gets a view built from THEIR cookie; + * otherwise the bot's shared provider comes back untouched. + */ + const scopedProvider = (req: Request, bot: any, platform: unknown): MusicProvider => { + const shared = sharedProviderFor(bot, platform); + return resolveProviderForRequest(req, shared.platform, shared, { database, config }); + }; + + /** + * Personal FM predates the admin toggle (#164), so a linked account has always + * driven it. `alwaysPersonal` keeps that guarantee while the toggle is off; + * with the toggle on, FM simply inherits the same account as everything else. + */ + const fmProvider = (req: Pick, bot: any, platform: unknown): MusicProvider => { + const shared = sharedProviderFor(bot, platform); + return resolveProviderForRequest(req, shared.platform, shared, { database, config }, { + alwaysPersonal: true, + }); + }; + // Access check runs BEFORE the existence/resolver check so a member who is // not allowed a bot always gets a uniform 403 — whether or not the bot // exists — instead of a 404 that would leak which bot IDs are real. @@ -156,20 +187,11 @@ export function createPlayerRouter( rejectDisabledLocalAudio(res); return; } - let provider = bot.getProviderFor( - platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin" - ? platform - : "netease" - ); - // A signed-in user who linked their own NetEase account gets FM from - // THEIR taste, not the bot's shared login (#164). Songs still resolve - // through the shared provider when played. - const user = (req as any).user; - if (provider.platform === "netease" && user && user.role !== "guest" && database) { - const cookie = database.getUserMusicCookie(user.id, "netease"); - if (cookie && supportsPersonalLogin(provider)) provider = provider.withCookie(cookie); - } - const message = await bot.startFm(provider, requesterName(req)); + // Resolve FM recommendations with the caller's account. The bot resolves + // each queued track's playback URL using the shared account. + const scope = { user: req.user }; + const resolveFmProvider = () => fmProvider(scope, bot, platform); + const message = await bot.startFm(resolveFmProvider(), requesterName(req), resolveFmProvider); res.json({ ok: !message.startsWith("No FM songs") && @@ -178,7 +200,7 @@ export function createPlayerRouter( message, }); } catch (err) { - res.status(500).json({ error: (err as Error).message }); + res.status(500).json({ error: musicRequestError(err).message }); } }); @@ -340,11 +362,7 @@ export function createPlayerRouter( } // Use the bot's own provider lookup — it already knows about youtube, // which the router's constructor params did not. - const provider = bot.getProviderFor( - platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin" - ? platform - : "netease" - ); + const provider = scopedProvider(req, bot, platform); // Stop current playback bot.getPlayer().stop(); @@ -419,8 +437,9 @@ export function createPlayerRouter( res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` }); } } catch (err) { - logger.error({ err }, "Play playlist failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "Play playlist failed"); + res.status(500).json({ error: error.message }); } }); @@ -433,11 +452,7 @@ export function createPlayerRouter( rejectDisabledLocalAudio(res); return; } - const provider = bot.getProviderFor( - platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin" - ? platform - : "netease" - ); + const provider = scopedProvider(req, bot, platform); // Stop current playback bot.getPlayer().stop(); @@ -497,8 +512,9 @@ export function createPlayerRouter( res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` }); } } catch (err) { - logger.error({ err }, "play-album failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "play-album failed"); + res.status(500).json({ error: error.message }); } }); @@ -518,11 +534,7 @@ export function createPlayerRouter( rejectDisabledLocalAudio(res); return; } - const provider = bot.getProviderFor( - platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin" - ? platform - : "netease" - ); + const provider = scopedProvider(req, bot, platform); if (typeof provider.getArtistSongs !== "function") { res.status(501).json({ error: "Not supported by this provider" }); return; @@ -590,8 +602,9 @@ export function createPlayerRouter( }); res.json(body); } catch (err) { - logger.error({ err }, "play-artist failed"); - res.status(500).json({ error: (err as Error).message }); + const error = musicRequestError(err); + logger.error({ err: error }, "play-artist failed"); + res.status(500).json({ error: error.message }); } }); @@ -754,11 +767,7 @@ export function createPlayerRouter( rejectDisabledLocalAudio(res); return; } - const provider = bot.getProviderFor( - platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin" - ? platform - : "netease" - ); + const provider = scopedProvider(req, bot, platform); const song = await provider.getSongDetail(songId); if (!song) { @@ -777,7 +786,7 @@ export function createPlayerRouter( res.json({ message: `Added: ${song.name} - ${song.artist} (position ${queue.size()})` }); } catch (err) { - res.status(500).json({ error: (err as Error).message }); + res.status(500).json({ error: musicRequestError(err).message }); } }); diff --git a/src/web/api/provider-scope.test.ts b/src/web/api/provider-scope.test.ts new file mode 100644 index 0000000..c57865e --- /dev/null +++ b/src/web/api/provider-scope.test.ts @@ -0,0 +1,460 @@ +import { describe, expect, it } from "vitest"; +import type { Request } from "express"; +import type { BotDatabase, GrantedMusicAccount } from "../../data/database.js"; +import type { MusicProvider } from "../../music/provider.js"; +import { + grantedAccountFor, + perUserMusicEnabled, + personalCookieFor, + resolveMusicCookie, + resolveProviderForRequest, +} from "./provider-scope.js"; + +/** Minimal provider stand-in: only `platform` and an optional `withCookie` are + * consulted by the scope resolver. */ +function fakeProvider(opts: { + platform?: string; + withCookie?: (cookie: string) => MusicProvider; +} = {}): MusicProvider { + const p: Partial = { platform: (opts.platform ?? "netease") as MusicProvider["platform"] }; + if (opts.withCookie) p.withCookie = opts.withCookie; + return p as MusicProvider; +} + +/** + * `own` is the member's self-linked cookie, `granted` an admin assignment. + * Both default to null so a test only states the state it cares about. + */ +function fakeDb( + own: string | null, + granted: GrantedMusicAccount | null = null, + preferShared = false, +): BotDatabase { + return { + getUserMusicCookie: () => own, + getGrantedMusicAccount: () => granted, + getUserMusicPreference: () => + preferShared ? { preferShared: true } : null, + } as unknown as BotDatabase; +} + +function fakeReq(user?: { id: string; role: string }): Request { + return { user } as unknown as Request; +} + +const GRANTED: GrantedMusicAccount = { + accountId: "acc-1", + label: "网易云-主号", + cookie: "MUSIC_U=shared-with-member", +}; + +describe("provider-scope", () => { + it("is off unless config explicitly enables it", () => { + expect(perUserMusicEnabled({})).toBe(false); + expect(perUserMusicEnabled({ config: {} })).toBe(false); + expect(perUserMusicEnabled({ config: { perUserMusicAccounts: false } })).toBe(false); + expect(perUserMusicEnabled({ config: { perUserMusicAccounts: true } })).toBe(true); + }); + + it("returns the shared provider when the feature is off", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, { + database: fakeDb("MUSIC_U=abc"), + config: { perUserMusicAccounts: false }, + }); + expect(scoped).toBe(shared); + }); + + it("returns the shared provider for guests even with a linked cookie", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest(fakeReq({ id: "g1", role: "guest" }), "netease", shared, { + database: fakeDb("MUSIC_U=abc"), + config: { perUserMusicAccounts: true }, + }); + expect(scoped).toBe(shared); + }); + + it("falls back to the shared provider when the user has no linked cookie", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, { + database: fakeDb(null), + config: { perUserMusicAccounts: true }, + }); + expect(scoped).toBe(shared); + }); + + it("falls back to the shared provider when the source has no per-account login", () => { + const shared = fakeProvider({ platform: "local" }); + const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "local", shared, { + database: fakeDb("cookie"), + config: { perUserMusicAccounts: true }, + }); + expect(scoped).toBe(shared); + }); + + it("returns an account-scoped view when enabled, member, and linked", () => { + const personal = fakeProvider(); + let seen = ""; + const shared = fakeProvider({ + withCookie: (cookie) => { + seen = cookie; + return personal; + }, + }); + const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, { + database: fakeDb("MUSIC_U=abc"), + config: { perUserMusicAccounts: true }, + }); + expect(scoped).toBe(personal); + expect(seen).toBe("MUSIC_U=abc"); + }); + + it("degrades to the shared provider when withCookie throws", () => { + const shared = fakeProvider({ + withCookie: () => { + throw new Error("bad cookie"); + }, + }); + const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, { + database: fakeDb("broken"), + config: { perUserMusicAccounts: true }, + }); + expect(scoped).toBe(shared); + }); + + it("treats a blank stored cookie as unlinked", () => { + expect( + personalCookieFor(fakeReq({ id: "u1", role: "member" }), "netease", { + database: fakeDb(" "), + config: { perUserMusicAccounts: true }, + }), + ).toBeNull(); + }); + + it("ignores requests with no authenticated user", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + expect( + resolveProviderForRequest(undefined, "netease", shared, { + database: fakeDb("MUSIC_U=abc"), + config: { perUserMusicAccounts: true }, + }), + ).toBe(shared); + }); + + // Personal FM shipped before the admin toggle existed (#164). A linked account + // has always driven it, so `alwaysPersonal` must keep working with the flag off + // — otherwise turning the feature off would silently regress that release. + it("still uses the linked account for personal FM while the toggle is off", () => { + const personal = fakeProvider(); + const shared = fakeProvider({ withCookie: () => personal }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { database: fakeDb("MUSIC_U=abc"), config: { perUserMusicAccounts: false } }, + { alwaysPersonal: true }, + ); + expect(scoped).toBe(personal); + }); + + it("keeps guests on the shared provider even for personal FM", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "g1", role: "guest" }), + "netease", + shared, + { database: fakeDb("MUSIC_U=abc"), config: { perUserMusicAccounts: true } }, + { alwaysPersonal: true }, + ); + expect(scoped).toBe(shared); + }); + + // --------------------------------------------------------------------- + // Admin-assigned accounts (#164 follow-up) + // --------------------------------------------------------------------- + describe("admin-assigned accounts", () => { + it("resolves an assigned account when the member linked nothing themselves", () => { + const assigned = fakeProvider(); + let seen = ""; + const shared = fakeProvider({ + withCookie: (cookie) => { + seen = cookie; + return assigned; + }, + }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } }, + ); + expect(scoped).toBe(assigned); + expect(seen).toBe(GRANTED.cookie); + }); + + // Own-beats-assigned: linking your own account must never be silently + // overridden by whatever the admin handed out earlier. + it("prefers the member's own login over an assigned one", () => { + const ownView = fakeProvider(); + const grantedView = fakeProvider(); + let seen = ""; + const shared = fakeProvider({ + withCookie: (cookie) => { + seen = cookie; + return cookie === "MUSIC_U=own" ? ownView : grantedView; + }, + }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { database: fakeDb("MUSIC_U=own", GRANTED), config: { perUserMusicAccounts: true } }, + ); + expect(scoped).toBe(ownView); + expect(seen).toBe("MUSIC_U=own"); + }); + + // An assignment only exists because the admin turned the feature on, so it + // must stop applying the moment they turn it off — otherwise "disable" + // would leave members reading the admin's account. + it("ignores assignments while the toggle is off", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + expect( + grantedAccountFor(fakeReq({ id: "u1", role: "member" }), "netease", { + database: fakeDb(null, GRANTED), + config: { perUserMusicAccounts: false }, + }), + ).toBeNull(); + expect( + resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, { + database: fakeDb(null, GRANTED), + config: { perUserMusicAccounts: false }, + }), + ).toBe(shared); + }); + + it("never hands an assignment to a guest", () => { + expect( + grantedAccountFor(fakeReq({ id: "guest", role: "guest" }), "netease", { + database: fakeDb(null, GRANTED), + config: { perUserMusicAccounts: true }, + }), + ).toBeNull(); + }); + + it("reports the source and label so the UI can say 由管理员分配", () => { + const resolved = resolveMusicCookie( + fakeReq({ id: "u1", role: "member" }), + "netease", + { database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } }, + ); + expect(resolved).toEqual({ + source: "granted", + cookie: GRANTED.cookie, + label: "网易云-主号", + accountId: "acc-1", + }); + }); + + it("reports source=personal for a self-linked account", () => { + const resolved = resolveMusicCookie( + fakeReq({ id: "u1", role: "member" }), + "netease", + { database: fakeDb("MUSIC_U=own", GRANTED), config: { perUserMusicAccounts: true } }, + ); + expect(resolved).toEqual({ source: "personal", cookie: "MUSIC_U=own" }); + }); + + it("returns null when neither source applies", () => { + expect( + resolveMusicCookie(fakeReq({ id: "u1", role: "member" }), "netease", { + database: fakeDb(null, null), + config: { perUserMusicAccounts: true }, + }), + ).toBeNull(); + }); + + it("degrades to the shared provider when an assigned cookie is broken", () => { + const shared = fakeProvider({ + withCookie: () => { + throw new Error("bad assigned cookie"); + }, + }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } }, + ); + expect(scoped).toBe(shared); + }); + + // Personal FM keeps the #164 guarantee for the member's OWN login; an + // assignment is not a #164 artefact and must not ride along. + it("does not use an assignment for personal FM while the toggle is off", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: false } }, + { alwaysPersonal: true }, + ); + expect(scoped).toBe(shared); + }); + }); +}); + + +// --------------------------------------------------------------------------- +// "Play through the shared account" preference +// +// The real case: the member's own NetEase login has no VIP, the admin's does. +// Switching to shared must override BOTH their own link and any assignment — +// it is an explicit instruction, not a fallback. +// --------------------------------------------------------------------------- +describe("provider-scope — shared-account preference", () => { + it("ignores the member's own cookie when they chose the shared login", () => { + const resolved = resolveMusicCookie( + fakeReq({ id: "u1", role: "member" }), + "netease", + { + database: fakeDb("MUSIC_U=mine", null, true), + config: { perUserMusicAccounts: true }, + }, + ); + expect(resolved).toBeNull(); + }); + + it("also overrides an admin assignment", () => { + const resolved = resolveMusicCookie( + fakeReq({ id: "u1", role: "member" }), + "netease", + { + database: fakeDb(null, GRANTED, true), + config: { perUserMusicAccounts: true }, + }, + ); + expect(resolved).toBeNull(); + }); + + it("outranks alwaysPersonal, so personal FM follows the choice too", () => { + const resolved = resolveMusicCookie( + fakeReq({ id: "u1", role: "member" }), + "netease", + { + database: fakeDb("MUSIC_U=mine", null, true), + config: { perUserMusicAccounts: true }, + }, + { alwaysPersonal: true }, + ); + expect(resolved).toBeNull(); + }); + + it("hands the untouched shared provider back", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { + database: fakeDb("MUSIC_U=mine", null, true), + config: { perUserMusicAccounts: true }, + }, + ); + expect(scoped).toBe(shared); + }); + + it("is ignored while the admin has the feature off", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { + database: fakeDb("MUSIC_U=mine", null, true), + config: { perUserMusicAccounts: false }, + }, + ); + expect(scoped).toBe(shared); + }); +}); + +// --------------------------------------------------------------------------- +// Automatic playback fallback +// +// Same scenario, minus an explicit choice: keep the member's own account for +// search / playlists, but when THIS track cannot be resolved on it, try the +// shared login instead of greying the track out. +// --------------------------------------------------------------------------- +describe("provider-scope — playback falls back to the shared login", () => { + function view( + getSongUrl: (songId: string, quality?: string) => Promise<{ url: string } | null>, + ): MusicProvider { + return { platform: "netease", getSongUrl } as unknown as MusicProvider; + } + + function scopeWith( + personal: MusicProvider, + sharedUrl: () => Promise<{ url: string } | null>, + options: { fallbackToShared?: boolean } = {}, + ) { + const shared = view(sharedUrl); + (shared as Partial).withCookie = () => personal; + return resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { + database: fakeDb("MUSIC_U=mine"), + config: { perUserMusicAccounts: true }, + }, + options, + ); + } + + it("uses the shared login when the personal account returns no url", async () => { + const scoped = scopeWith(view(async () => null), async () => ({ url: "https://shared/x.mp3" })); + expect((await scoped.getSongUrl("1"))?.url).toBe("https://shared/x.mp3"); + }); + + it("uses the shared login when the personal account throws", async () => { + const scoped = scopeWith( + view(async () => { + throw new Error("no membership"); + }), + async () => ({ url: "https://shared/x.mp3" }), + ); + expect((await scoped.getSongUrl("1"))?.url).toBe("https://shared/x.mp3"); + }); + + it("keeps the personal result when it works", async () => { + const scoped = scopeWith( + view(async () => ({ url: "https://mine/x.mp3" })), + async () => ({ url: "https://shared/x.mp3" }), + ); + expect((await scoped.getSongUrl("1"))?.url).toBe("https://mine/x.mp3"); + }); + + it("can be switched off so playback stays on the member's account", async () => { + const scoped = scopeWith( + view(async () => null), + async () => ({ url: "https://shared/x.mp3" }), + { fallbackToShared: false }, + ); + expect(await scoped.getSongUrl("1")).toBeNull(); + }); + + it("leaves the shared instance itself untouched", async () => { + const shared = view(async () => ({ url: "https://shared/x.mp3" })); + (shared as Partial).withCookie = () => view(async () => null); + resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { database: fakeDb("MUSIC_U=mine"), config: { perUserMusicAccounts: true } }, + ); + // Calling the shared provider directly must still hit its own implementation. + expect((await shared.getSongUrl("1"))?.url).toBe("https://shared/x.mp3"); + }); +}); diff --git a/src/web/api/provider-scope.ts b/src/web/api/provider-scope.ts new file mode 100644 index 0000000..b61a62d --- /dev/null +++ b/src/web/api/provider-scope.ts @@ -0,0 +1,225 @@ +import type { Request } from "express"; +import type { BotDatabase, GrantedMusicAccount } from "../../data/database.js"; +import type { MusicProvider } from "../../music/provider.js"; + +/** + * Resolves which music provider a WEB request should read from (#164 follow-up). + * + * The bot keeps one shared login per platform (data/cookies/.json). + * Before this module, a web user could only replace the SHARED login's taste for + * their own private FM — every search, playlist and playback URL still came from + * the admin's account, so members saw the admin's library. + * + * With `perUserMusicAccounts` enabled, the resolution order is: + * + * 1. the caller's OWN linked account (`user_music_cookies`, scanned by them) + * 2. an account an admin ASSIGNED (`music_account_grants`, admin-owned) + * 3. the bot's shared login (always the fallback) + * + * Own-beats-assigned is deliberate: someone who linked their own account keeps + * it even if an admin later hands them a pool account, and unlinking on the + * member side can never revoke an admin's assignment (different table). + * + * Everything falls back to the shared instance when: + * - the admin left the feature off (the default — zero behaviour change), + * - the caller is a guest (guests share one anonymous identity and cannot link + * an account; /api/me/music already rejects them), + * - the caller has no linked and no assigned account for that platform, + * - the assigned account was disabled by the admin (instant rollback), or + * - the platform has no per-account login implemented (`withCookie` absent). + * + * The cookie never reaches the browser: it is read from the database here and + * only ever lives inside the provider view. + */ +export interface MusicScopeDeps { + /** Omitted by unit-test routers → personal accounts are simply unavailable. */ + database?: BotDatabase; + /** Omitted by unit-test routers → treated as "feature off". */ + config?: { perUserMusicAccounts?: boolean }; +} + +interface ScopedUser { + id?: string; + role?: string; +} + +type ScopeRequest = Pick; + +/** Whether per-user music accounts are switched on for this router instance. */ +export function perUserMusicEnabled(deps: MusicScopeDeps): boolean { + return deps.config?.perUserMusicAccounts === true; +} + +/** + * The caller, when they may hold a per-user account at all. Guests never + * qualify: they all map to one anonymous identity, so a linked or assigned + * account would leak across every guest on the instance. + */ +function scopedUser(req: ScopeRequest | undefined): ScopedUser | null { + if (!req) return null; + const user = (req as { user?: ScopedUser }).user; + if (!user?.id || user.role === "guest") return null; + return user; +} + +/** + * The caller's own cookie for `platform`, or null when personal accounts do not + * apply to this request. + * + * `alwaysPersonal` keeps the pre-existing #164 behaviour for personal FM: that + * feature shipped BEFORE the admin toggle existed, so a linked account must keep + * driving someone's private FM even while the toggle is off. Turning the toggle + * on only widens the scope to search/playlists/playback URLs. + */ +export function personalCookieFor( + req: ScopeRequest | undefined, + platform: string, + deps: MusicScopeDeps, + alwaysPersonal = false, +): string | null { + if (!alwaysPersonal && !perUserMusicEnabled(deps)) return null; + const user = scopedUser(req); + if (!user || !deps.database) return null; + const cookie = deps.database.getUserMusicCookie(user.id!, platform); + return cookie && cookie.trim() ? cookie : null; +} + +/** + * The admin-assigned account for this caller, or null. + * + * Unlike `personalCookieFor` this has NO `alwaysPersonal` escape hatch: an + * assignment only exists because the admin turned the feature on, so turning it + * off must hand everyone back to the shared login immediately. Doing otherwise + * would leave members reading an admin's account after the admin "disabled" + * the feature. + */ +export function grantedAccountFor( + req: ScopeRequest | undefined, + platform: string, + deps: MusicScopeDeps, +): GrantedMusicAccount | null { + if (!perUserMusicEnabled(deps)) return null; + const user = scopedUser(req); + if (!user || !deps.database) return null; + return deps.database.getGrantedMusicAccount(user.id!, platform); +} + +/** + * Whether the member explicitly asked to play through the shared login. + * + * This exists for one concrete case: their own account has no membership, the + * admin's does, and they would rather hear the paid tracks than their own + * recommendations. Choosing it overrides BOTH their own link and any admin + * assignment — it is an explicit instruction, not a fallback. + */ +export function preferSharedFor( + req: ScopeRequest | undefined, + platform: string, + deps: MusicScopeDeps, +): boolean { + if (!perUserMusicEnabled(deps)) return false; + const user = scopedUser(req); + if (!user || !deps.database) return false; + return deps.database.getUserMusicPreference(user.id!, platform)?.preferShared === true; +} + +/** Where the cookie driving this request came from. */ +export interface ResolvedMusicCookie { + source: "personal" | "granted"; + cookie: string; + /** Admin-facing name of an assigned account; undefined for self-linked ones. */ + label?: string; + /** Set for `source: "granted"` so callers can show "由管理员分配". */ + accountId?: string; +} + +/** + * The single place that decides "which login does this request use". + * Returns null when the shared login applies. + */ +export function resolveMusicCookie( + req: ScopeRequest | undefined, + platform: string, + deps: MusicScopeDeps, + options: { alwaysPersonal?: boolean } = {}, +): ResolvedMusicCookie | null { + // An explicit "use the shared account" outranks everything, including the + // `alwaysPersonal` escape hatch: someone who chose membership over their own + // recommendations wants the shared login for FM too. + if (preferSharedFor(req, platform, deps)) return null; + const own = personalCookieFor(req, platform, deps, options.alwaysPersonal); + if (own) return { source: "personal", cookie: own }; + const granted = grantedAccountFor(req, platform, deps); + if (granted) { + return { + source: "granted", + cookie: granted.cookie, + label: granted.label, + accountId: granted.accountId, + }; + } + return null; +} + +/** + * Give `view` a single-shot fallback to the shared login when its own playback + * attempt comes up empty. + * + * The case this exists for: the member's own account is real but has no + * membership, so `/song/url/v1` answers `url: null` (or 400 for the paid track) + * while the admin's account plays it fine. Without this the member has to go + * into settings and switch manually before every such track. + * + * Only `getSongUrl` is wrapped — search, playlists and FM stay on the member's + * own account, which is the whole point of per-user logins. The wrapper keeps + * the shared instance untouched, so nothing leaks between callers. + */ +function withSharedPlaybackFallback(view: MusicProvider, shared: MusicProvider): MusicProvider { + // Guard for partial implementations (and for test doubles): without both + // sides resolvable there is nothing to fall back to. + if (typeof view.getSongUrl !== "function" || typeof shared.getSongUrl !== "function") { + return view; + } + const ownResolve = view.getSongUrl.bind(view); + view.getSongUrl = async (songId: string, quality?: string) => { + try { + const result = await ownResolve(songId, quality); + if (result?.url) return result; + } catch { + // A failure on the personal side (no membership, -460, expired cookie) + // is not a reason for this track to go grey — try the shared login. + } + return shared.getSongUrl(songId, quality); + }; + return view; +} + +/** + * Wrap `shared` in a per-account view when the request carries a usable login; + * otherwise return `shared` untouched. + * + * A provider whose `withCookie` throws (malformed/persisted cookie) degrades to + * the shared login rather than failing the request — a bad stored cookie must + * not break search/playback for that user. + */ +export function resolveProviderForRequest( + req: ScopeRequest | undefined, + platform: string, + shared: MusicProvider, + deps: MusicScopeDeps, + options: { alwaysPersonal?: boolean; fallbackToShared?: boolean } = {}, +): MusicProvider { + const resolved = resolveMusicCookie(req, platform, deps, options); + if (!resolved) return shared; + if (typeof shared.withCookie !== "function") return shared; + let view: MusicProvider; + try { + view = shared.withCookie(resolved.cookie); + } catch { + return shared; + } + // On by default: the common complaint is "my account has no membership, the + // admin's does". Set false to keep playback strictly on the member's account. + if (options.fallbackToShared === false) return view; + return withSharedPlaybackFallback(view, shared); +} diff --git a/src/web/server.ts b/src/web/server.ts index 6dadb43..77875ab 100755 --- a/src/web/server.ts +++ b/src/web/server.ts @@ -20,6 +20,7 @@ import { createAuditStore } from "../data/audit.js"; import { createAuditRouter } from "./api/audit.js"; import { createFavoritesRouter } from "./api/favorites.js"; import { createPersonalMusicRouter } from "./api/personal-music.js"; +import { createMusicAccountsRouter } from "./api/music-accounts.js"; import { createSavedQueuesRouter } from "./api/saved-queues.js"; import { createSpotifyRouter } from "./api/spotify.js"; import { createApiKeysRouter } from "./api/api-keys.js"; @@ -170,15 +171,16 @@ export function createWebServer(options: WebServerOptions): WebServer { ); app.use( "/api/music", - createMusicRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.localProvider, options.config, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.configPath) + createMusicRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.localProvider, options.config, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.configPath, options.database) ); app.use("/api/player", createPlayerRouter( options.botManager, logger, options.database, options.neteaseProvider, options.qqProvider, options.bilibiliProvider, + options.config, )); app.use( "/api/auth", - createAuthRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.cookieStore, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.config) + createAuthRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.cookieStore, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.config, options.database) ); if (options.spotifyOAuth) { app.use( @@ -207,12 +209,41 @@ export function createWebServer(options: WebServerOptions): WebServer { ); } app.use("/api/favorites", requireNotGuest, createFavoritesRouter(options.database, logger)); - // The caller's own NetEase login for their personal FM (#164). Guests share - // one anonymous identity, so they cannot link an account. + // The caller's own music login, per platform (#164 + #164 follow-up). Guests + // share one anonymous identity, so they cannot link an account. app.use( "/api/me/music", requireNotGuest, - createPersonalMusicRouter(options.database, options.neteaseProvider, logger), + createPersonalMusicRouter( + options.database, + { + netease: options.neteaseProvider, + qq: options.qqProvider, + kugou: options.kugouProvider, + bilibili: options.bilibiliProvider, + }, + logger, + options.config, + ), + ); + // Admin-only pool of music logins + per-member assignments (#164 follow-up). + // Mounted on requireAdmin, NOT bot.manage: members must never see which + // account was handed to whom. + app.use( + "/api/music-accounts", + requireAdmin, + createMusicAccountsRouter( + options.database, + users, + { + netease: options.neteaseProvider, + qq: options.qqProvider, + kugou: options.kugouProvider, + bilibili: options.bilibiliProvider, + }, + logger, + options.cookieStore, + ), ); // Saved queues (Feature 1, #119). Members + admins only (requireNotGuest); // the router itself 403s every route unless savedQueuesEnabled is on. diff --git a/web/src/components/MusicAccountPool.vue b/web/src/components/MusicAccountPool.vue new file mode 100644 index 0000000..d71d82f --- /dev/null +++ b/web/src/components/MusicAccountPool.vue @@ -0,0 +1,553 @@ + + + + + diff --git a/web/src/components/PersonalMusicAccount.vue b/web/src/components/PersonalMusicAccount.vue new file mode 100644 index 0000000..f28c1d6 --- /dev/null +++ b/web/src/components/PersonalMusicAccount.vue @@ -0,0 +1,552 @@ + + + + + diff --git a/web/src/components/PersonalNeteaseAccount.vue b/web/src/components/PersonalNeteaseAccount.vue deleted file mode 100644 index 9fb3eec..0000000 --- a/web/src/components/PersonalNeteaseAccount.vue +++ /dev/null @@ -1,261 +0,0 @@ - - - - - diff --git a/web/src/views/Settings.vue b/web/src/views/Settings.vue index 168d4be..e4c0f45 100755 --- a/web/src/views/Settings.vue +++ b/web/src/views/Settings.vue @@ -116,7 +116,10 @@

{{ ownPwError }}

{{ ownPwSuccess }}

- + @@ -973,6 +976,29 @@ @change="savePlayKeepsQueue" /> + + + + + +
+
音乐账号分配
+
添加管理员拥有的账号,分配给指定成员(也可以分配给其他管理员)。成员自己绑定的账号优先;未绑定的人使用分配给自己的账号;都没有时回到机器人的共享账号。这些账号同样只作用于网页端,房间里的播放始终用共享账号。
+ +
@@ -1311,7 +1337,8 @@ import axios from 'axios'; import AvatarUpload from '../components/AvatarUpload.vue'; import CustomAvatarRow from '../components/CustomAvatarRow.vue'; import AccentColorPicker from '../components/AccentColorPicker.vue'; -import PersonalNeteaseAccount from '../components/PersonalNeteaseAccount.vue'; +import PersonalMusicAccount from '../components/PersonalMusicAccount.vue'; +import MusicAccountPool from '../components/MusicAccountPool.vue'; import QRCode from 'qrcode'; import { usePlayerStore } from '../stores/player.js'; import { useSession } from '../composables/useSession.js'; @@ -1452,6 +1479,11 @@ function providerOn(p: string): boolean { return enabledProviders.value.length === 0 || enabledProviders.value.includes(p); } +// Sources the member can hold a personal account for. Only enabled ones are +// offered — /api/me/music serves a fixed set regardless of config. +const PERSONAL_PLATFORMS = ['netease', 'qq', 'kugou', 'bilibili'] as const; +const personalPlatforms = computed(() => PERSONAL_PLATFORMS.filter((p) => providerOn(p))); + // --- Default music source (issue #126) --- // Chinese labels for the gateable providers, shown in the default-source select. const PROVIDER_LABELS: Record = { @@ -1846,6 +1878,8 @@ const localAudioEnabled = ref(true); // Saved-queues + play-keeps-queue toggles (#119), both default OFF. const savedQueuesEnabled = ref(false); const playKeepsQueue = ref(false); +// Per-user music accounts (#164 follow-up). Admin toggle, default OFF. +const perUserMusicAccounts = ref(false); function normalizeVoiceDuckingVolume(): number { const raw = voiceDuckingVolumePercent.value as number | string; @@ -1886,6 +1920,7 @@ async function loadIdleTimeout() { localAudioEnabled.value = res.data.localAudioEnabled ?? true; savedQueuesEnabled.value = res.data.savedQueuesEnabled ?? false; playKeepsQueue.value = res.data.playKeepsQueue ?? false; + perUserMusicAccounts.value = res.data.perUserMusicAccounts ?? false; store.savedQueuesEnabled = savedQueuesEnabled.value; applyGuestModeFromServer(res.data.guestMode); applyAdminGroupsFromServer(res.data.adminGroups); @@ -1964,6 +1999,15 @@ async function savePlayKeepsQueue() { } catch { /* ignore */ } } +async function savePerUserMusicAccounts() { + try { + const res = await axios.post('/api/bot/settings', { + perUserMusicAccounts: perUserMusicAccounts.value, + }); + perUserMusicAccounts.value = res.data.perUserMusicAccounts ?? perUserMusicAccounts.value; + } catch { /* ignore */ } +} + // --- Spotify (Connect) settings (§8) --- // NOTE: This card's status comes ONLY from /api/spotify/status (playback OAuth // `authorized`). It is deliberately NOT wired to the player store's @@ -3404,6 +3448,26 @@ onUnmounted(() => { line-height: 1.5; } +// --- Music account pool (admin) --- +.pool-wrap { + margin-top: 8px; + padding-top: 12px; + border-top: 1px dashed var(--border-color); +} + +.pool-title { + font-size: 13px; + font-weight: 600; + margin-bottom: 4px; +} + +.pool-hint { + font-size: 12px; + color: var(--text-tertiary); + line-height: 1.5; + margin-bottom: 8px; +} + .empty-hint { font-size: 13px; color: var(--text-tertiary);