Merge the reviewed music-account changes into playback retry

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 17:02:20 +08:00
commit d34e249f8a
27 files changed
+3567 -392

No files matched your search

+6
View File
@@ -355,6 +355,12 @@ QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 →
设置 `QQ_MUSIC_MANAGED_SESSION=0` 并重启可关闭自动续期。机器人继续使用当前的 QQ 播放 Cookie,并从 `cookies/qq.json` 兼容读取旧部署的 Cookie。
### 每用户音乐账号
管理员可在设置中开启「每个成员使用自己的音乐账号」,默认关闭。成员可扫码绑定自己的网易云,也可接受管理员分配的网易云、QQ 音乐、酷狗或 B 站账号。网页搜索、歌单和推荐默认优先使用自己的绑定,其次使用分配账号,最后使用机器人共享账号。成员也可在「我的音乐账号」中主动选择共享账号。房间播歌使用机器人共享账号。
从共享账号导入时,账号池保存当前 Cookie 的副本。共享账号续期或更换后,管理员可在账号池中更新该条目的 Cookie。
### WebUI 页面说明
| 页面 | 功能 |
+14
View File
@@ -396,6 +396,20 @@ const resolveAndPlay = BotInstance.prototype.resolveAndPlay as (
this: unknown,
song: any,
) => Promise<boolean>;
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<void> }).refillFm.call(context);
expect(old.getPersonalFm).not.toHaveBeenCalled();
expect(shared.getPersonalFm).toHaveBeenCalledOnce();
});
const setupPlayerEvents = (BotInstance.prototype as any).setupPlayerEvents as (
this: unknown,
) => void;
+21 -7
View File
@@ -9,9 +9,9 @@ import {
import { AudioPlayer } from "../audio/player.js";
import { resolveUrlWithRetry } from "./url-retry.js";
import { RISK_CONTROL_CODE, RiskControlError, toPlayFailure } from "../music/provider.js";
import type { PlayFailure } from "../music/provider.js";
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
import type { MusicProvider, Platform, Song, SongUrlResult } from "../music/provider.js";
import type { MusicProvider, Platform, PlayFailure, Song, SongUrlResult } from "../music/provider.js";
import { musicRequestError } from "../music/request-error.js";
import {
parseCommand,
canRunCommand,
@@ -201,6 +201,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[] = [];
@@ -984,6 +985,7 @@ export class BotInstance extends EventEmitter {
private disableFmMode(): void {
this.isFmMode = false;
this.fmProvider = null;
this.resolveFmProvider = undefined;
this.fmRequesterName = undefined;
}
@@ -1879,7 +1881,11 @@ export class BotInstance extends EventEmitter {
return this.startFm(this.getProvider(cmd.flags), requesterName);
}
async startFm(provider: MusicProvider = this.neteaseProvider, requesterName?: string): Promise<string> {
async startFm(
provider: MusicProvider = this.neteaseProvider,
requesterName?: string,
resolveProvider?: () => MusicProvider,
): Promise<string> {
// 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.
@@ -1901,6 +1907,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();
@@ -1946,17 +1953,23 @@ export class BotInstance extends EventEmitter {
}
private async refillFm(): Promise<void> {
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");
}
}
@@ -2109,6 +2122,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) {
+12
View File
@@ -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
@@ -204,6 +211,7 @@ export function getDefaultConfig(): BotConfig {
idleTimeoutMinutes: 0,
localAudioEnabled: true,
savedQueuesEnabled: false,
perUserMusicAccounts: false,
playKeepsQueue: false,
// Two extra attempts: enough to ride out a transient NetEase hiccup without
// making a genuinely unlicensed track feel stuck (~1s of backoff total).
@@ -410,6 +418,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;
// Play-URL retry budget. Anything non-numeric (legacy config, `"3"`,
// `null`) falls back to the default instead of disabling the retry, because
@@ -482,6 +493,7 @@ export function loadConfig(path: string): BotConfig {
audioQuality,
enabledProviders,
savedQueuesEnabled,
perUserMusicAccounts,
playKeepsQueue,
playUrlRetries,
voiceDucking,
+357
View File
@@ -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;
@@ -148,6 +197,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<Pick<MusicAccount, "label" | "cookie" | "capacity" | "enabled">>,
): 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[];
@@ -358,6 +455,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);
`);
}
@@ -494,6 +637,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<string, unknown>): 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<string, unknown> | 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<string, unknown> | 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[] => {
@@ -688,6 +953,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<string, unknown>[])
: (selectMusicAccountsAll.all() as Record<string, unknown>[]);
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}`);
+21
View File
@@ -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;
}
+21
View File
@@ -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";
+8
View File
@@ -217,6 +217,14 @@ export interface MusicProvider {
* local files, Jellyfin) omit this and the caller keeps its single attempt.
*/
getFallbackQualities?(): string[];
/**
* 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<Song[]>;
getDailyRecommendSongs?(): Promise<Song[]>;
getUserPlaylists?(): Promise<Playlist[]>;
+14
View File
@@ -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;
}
+10
View File
@@ -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");
}
+53 -4
View File
@@ -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 });
}
});
+10 -2
View File
@@ -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";
+10
View File
@@ -74,6 +74,7 @@ export function createBotRouter(
voiceDucking: config.voiceDucking,
localAudioEnabled: config.localAudioEnabled,
savedQueuesEnabled: config.savedQueuesEnabled,
perUserMusicAccounts: config.perUserMusicAccounts === true,
playKeepsQueue: config.playKeepsQueue,
// Silent re-resolve budget for a track whose URL came back empty.
playUrlRetries: config.playUrlRetries ?? 0,
@@ -97,6 +98,7 @@ export function createBotRouter(
guestMode,
adminGroups,
playUrlRetries,
perUserMusicAccounts,
} = req.body;
const hasIdle = idleTimeoutMinutes !== undefined;
@@ -121,10 +123,17 @@ export function createBotRouter(
return;
}
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 (hasPlayUrlRetries) config.playUrlRetries = playUrlRetries;
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 /
@@ -299,6 +308,7 @@ export function createBotRouter(
voiceDucking: config.voiceDucking,
localAudioEnabled: config.localAudioEnabled,
savedQueuesEnabled: config.savedQueuesEnabled,
perUserMusicAccounts: config.perUserMusicAccounts === true,
playKeepsQueue: config.playKeepsQueue,
// Silent re-resolve budget for a track whose URL came back empty.
playUrlRetries: config.playUrlRetries ?? 0,
+273
View File
@@ -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<string, any> } = {}) {
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<string, unknown> = {}) {
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);
});
});
+360
View File
@@ -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<Record<string, MusicProvider>>,
logger: Logger,
cookieStore?: CookieStore,
): Router {
const router = Router();
const knownPlatforms = new Set<string>(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;
}
+13
View File
@@ -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", () => {
+71 -36
View File
@@ -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 });
}
});
+164 -4
View File
@@ -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<string, unknown>;
} = {}) {
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<typeof createDatabase>, 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");
});
});
+184 -27
View File
@@ -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<PersonalLoginProvider> | 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<Record<string, MusicProvider>>,
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;
+53 -44
View File
@@ -1,14 +1,15 @@
import { Router } from "express";
import { Router, type Request } from "express";
import type { BotInstance } from "../../bot/instance.js";
import type { QueuedSong } from "../../audio/queue.js";
import type { BotManager } from "../../bot/manager.js";
import type { BotDatabase } from "../../data/database.js";
import type { MusicProvider, Song, ArtistSongPage, PlayFailure } 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). */
@@ -43,9 +44,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<Request, "user">, 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.
@@ -168,20 +199,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") &&
@@ -190,7 +212,7 @@ export function createPlayerRouter(
message,
});
} catch (err) {
res.status(500).json({ error: (err as Error).message });
res.status(500).json({ error: musicRequestError(err).message });
}
});
@@ -352,11 +374,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();
@@ -428,8 +446,9 @@ export function createPlayerRouter(
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
} 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 });
}
});
@@ -442,11 +461,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();
@@ -503,8 +518,9 @@ export function createPlayerRouter(
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
} 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 });
}
});
@@ -524,11 +540,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;
@@ -595,8 +607,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 });
}
});
@@ -762,11 +775,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) {
@@ -785,7 +794,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 });
}
});
+460
View File
@@ -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<MusicProvider> = { 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<MusicProvider>).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<MusicProvider>).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");
});
});
+225
View File
@@ -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/<platform>.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<Request, "user">;
/** 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);
}
+36 -5
View File
@@ -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.
+553
View File
@@ -0,0 +1,553 @@
<template>
<!-- Admin console for the music-account pool (#164 follow-up).
One row per login the admin owns; each row can be handed to members (or
to another admin). See src/web/api/music-accounts.ts for the rules. -->
<div class="pool">
<p class="hint">
这里存放管理员拥有的音乐账号,可以逐个分配给成员。成员自己扫码绑定的账号优先级更高,
管理员分配的账号只在他们没绑定自己的账号时生效。播放地址、搜索、歌单都会按被分配的账号获取。
</p>
<!-- Create -->
<div class="create-row">
<select v-model="draft.platform" class="field">
<option v-for="p in platforms" :key="p.platform" :value="p.platform">
{{ PLATFORM_LABEL[p.platform] ?? p.platform }}
{{ p.playbackSupported ? '' : '(暂不支持按账号播放)' }}
</option>
</select>
<input v-model="draft.label" class="field" placeholder="名称,如 网易云-主号" maxlength="64" />
<input
v-model.number="draft.capacity"
class="field field-narrow"
type="number"
min="0"
title="0 = 可分配给多人;1 = 独占,只能给一个人"
placeholder="人数上限"
/>
<button class="btn primary" :disabled="creating" @click="create">
<Icon icon="mdi:plus" /> 添加账号
</button>
<button class="btn" :disabled="creating" @click="importShared">
<Icon icon="mdi:download" /> 从共享账号导入
</button>
</div>
<textarea
v-model="draft.cookie"
class="field cookie-input"
rows="2"
placeholder="粘贴该账号的 Cookie(仅保存在服务器,列表里只显示掩码)"
></textarea>
<p v-if="error" class="error">{{ error }}</p>
<!-- List -->
<div v-if="accounts.length === 0" class="empty">还没有添加任何账号</div>
<div v-for="a in accounts" :key="a.id" class="account" :class="{ disabled: !a.enabled }">
<div class="account-head">
<div class="account-title">
<span class="badge">{{ PLATFORM_LABEL[a.platform] ?? a.platform }}</span>
<span class="label">{{ a.label }}</span>
<span v-if="a.capacity === 1" class="tag exclusive">独占</span>
<span v-else-if="a.capacity > 1" class="tag">最多 {{ a.capacity }} 人</span>
<span v-else class="tag">不限人数</span>
<span v-if="!a.playbackSupported" class="tag warn">该平台暂不支持按账号播放</span>
</div>
<div class="account-actions">
<button class="btn tiny" @click="probe(a)">
<Icon icon="mdi:shield-check" /> 检测
</button>
<label class="switch" :title="a.enabled ? '已启用' : '已停用'">
<input type="checkbox" :checked="a.enabled" @change="toggleEnabled(a)" />
<span class="slider"></span>
</label>
<button class="btn tiny danger" @click="remove(a)">
<Icon icon="mdi:trash-can-outline" />
</button>
</div>
</div>
<div class="account-meta">
<span class="mono">{{ a.cookiePreview }}</span>
<span v-if="probeResult[a.id]" class="probe" :class="{ ok: probeResult[a.id]!.loggedIn }">
{{ probeResult[a.id]!.loggedIn ? `登录有效${probeResult[a.id]!.nickname ? ':' + probeResult[a.id]!.nickname : ''}` : '登录已失效' }}
</span>
</div>
<div class="grantees">
<span class="grantees-label">已分配:</span>
<span v-if="a.grantees.length === 0" class="muted">无</span>
<span v-for="g in a.grantees" :key="g.userId" class="chip">
{{ g.username }}
<button class="chip-x" title="收回" @click="revoke(a, g.userId)">×</button>
</span>
<select
class="field field-narrow assign-select"
:value="''"
:disabled="assignable(a).length === 0"
@change="onAssign(a, $event)"
>
<option value="">{{ assignable(a).length === 0 ? '已满额' : '+ 分配给…' }}</option>
<option v-for="u in assignable(a)" :key="u.id" :value="u.id">
{{ u.username }}{{ u.role === 'admin' ? '(管理员)' : '' }}
</option>
</select>
</div>
<div class="cookie-edit">
<input
v-model="cookieDraft[a.id]"
class="field"
type="password"
placeholder="更新 Cookie(登录失效时用)"
/>
<button class="btn tiny" :disabled="!cookieDraft[a.id]" @click="updateCookie(a)">
保存
</button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { Icon } from '@iconify/vue';
import axios from 'axios';
interface Grantee { userId: string; username: string; grantedAt: string }
interface PoolAccount {
id: string;
platform: string;
label: string;
cookiePreview: string;
capacity: number;
enabled: boolean;
playbackSupported: boolean;
granteeCount: number;
grantees: Grantee[];
}
interface AssignableUser { id: string; username: string; role: string }
const PLATFORM_LABEL: Record<string, string> = {
netease: '网易云',
qq: 'QQ音乐',
kugou: '酷狗',
bilibili: 'B站',
};
const accounts = ref<PoolAccount[]>([]);
const users = ref<AssignableUser[]>([]);
const platforms = ref<Array<{ platform: string; playbackSupported: boolean }>>([]);
const creating = ref(false);
const error = ref('');
// Default to exclusive: sharing one login between members mixes their
// playback history and recommendations, which is almost never intended.
const draft = reactive({ platform: 'netease', label: '', cookie: '', capacity: 1 });
const cookieDraft = reactive<Record<string, string>>({});
const probeResult = ref<Record<string, { loggedIn: boolean; nickname?: string } | undefined>>({});
const assignable = (a: PoolAccount) => {
const held = new Set(a.grantees.map((g) => g.userId));
// An exclusive account that already has a holder offers nobody: the API would
// answer 409 anyway, so don't dangle options that cannot work.
if (a.capacity === 1 && a.granteeCount >= 1) return [];
if (a.capacity > 1 && a.granteeCount >= a.capacity) return [];
return users.value.filter((u) => !held.has(u.id));
};
const errText = (err: any, fallback: string) => {
const e = err?.response?.data?.error;
if (e === 'account_exclusive') return '该账号是独占的,请先收回其他成员';
if (e === 'account_full') return '该账号已分配满额';
if (e === 'account_disabled') return '该账号已停用';
if (e === 'no_shared_login') return '机器人还没有登录该平台的共享账号';
return e ?? fallback;
};
async function load() {
try {
const res = await axios.get('/api/music-accounts');
accounts.value = res.data.accounts ?? [];
users.value = res.data.users ?? [];
platforms.value = res.data.platforms ?? [];
if (!platforms.value.some((p) => p.platform === draft.platform)) {
draft.platform = platforms.value[0]?.platform ?? 'netease';
}
} catch (err) {
error.value = errText(err, '加载失败');
}
}
async function create() {
error.value = '';
if (!draft.label.trim() || !draft.cookie.trim()) {
error.value = '名称和 Cookie 都要填';
return;
}
creating.value = true;
try {
await axios.post('/api/music-accounts', {
platform: draft.platform,
label: draft.label.trim(),
cookie: draft.cookie.trim(),
capacity: Number(draft.capacity) || 0,
});
draft.label = '';
draft.cookie = '';
draft.capacity = 1;
await load();
} catch (err) {
error.value = errText(err, '添加失败');
} finally {
creating.value = false;
}
}
async function importShared() {
error.value = '';
creating.value = true;
try {
await axios.post('/api/music-accounts/import-shared', {
platform: draft.platform,
label: `${PLATFORM_LABEL[draft.platform] ?? draft.platform} 共享账号`,
capacity: Number(draft.capacity) || 0,
});
await load();
} catch (err) {
error.value = errText(err, '导入失败');
} finally {
creating.value = false;
}
}
async function toggleEnabled(a: PoolAccount) {
error.value = '';
try {
await axios.patch(`/api/music-accounts/${a.id}`, { enabled: !a.enabled });
await load();
} catch (err) {
error.value = errText(err, '操作失败');
}
}
async function updateCookie(a: PoolAccount) {
error.value = '';
try {
await axios.patch(`/api/music-accounts/${a.id}`, { cookie: cookieDraft[a.id] });
cookieDraft[a.id] = '';
await load();
} catch (err) {
error.value = errText(err, '保存失败');
}
}
async function remove(a: PoolAccount) {
if (!confirm(`删除「${a.label}」?已分配给成员的记录会一起收回。`)) return;
error.value = '';
try {
await axios.delete(`/api/music-accounts/${a.id}`);
await load();
} catch (err) {
error.value = errText(err, '删除失败');
}
}
async function onAssign(a: PoolAccount, ev: Event) {
const select = ev.target as HTMLSelectElement;
const userId = select.value;
select.value = '';
if (!userId) return;
error.value = '';
try {
await axios.post(`/api/music-accounts/${a.id}/assign`, { userId });
await load();
} catch (err) {
error.value = errText(err, '分配失败');
}
}
async function revoke(a: PoolAccount, userId: string) {
error.value = '';
try {
await axios.delete(`/api/music-accounts/${a.id}/assign/${userId}`);
await load();
} catch (err) {
error.value = errText(err, '收回失败');
}
}
async function probe(a: PoolAccount) {
error.value = '';
try {
const res = await axios.post(`/api/music-accounts/${a.id}/probe`);
probeResult.value[a.id] = { loggedIn: Boolean(res.data.loggedIn), nickname: res.data.nickname };
} catch (err) {
probeResult.value[a.id] = { loggedIn: false };
error.value = errText(err, '检测失败');
}
}
onMounted(load);
</script>
<style lang="scss" scoped>
.pool {
margin-top: 12px;
}
.hint {
font-size: 12px;
color: var(--text-tertiary);
line-height: 1.6;
margin: 0 0 12px;
}
.create-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 8px;
}
.field {
padding: 7px 10px;
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
color: inherit;
font-size: 13px;
min-width: 0;
&:focus {
outline: none;
border-color: var(--color-primary);
}
}
.field-narrow {
width: 96px;
}
.cookie-input {
width: 100%;
resize: vertical;
font-family: var(--font-mono, monospace);
margin-bottom: 8px;
}
.btn {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 7px 14px;
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
font-size: 13px;
color: inherit;
cursor: pointer;
transition: all var(--transition-fast);
&:hover:not(:disabled) {
border-color: var(--color-primary);
color: var(--color-primary);
}
&:disabled {
opacity: 0.55;
cursor: default;
}
&.primary {
border-color: var(--color-primary);
color: var(--color-primary);
}
&.tiny {
padding: 4px 8px;
font-size: 12px;
}
&.danger:hover {
border-color: #e26a6a;
color: #e26a6a;
}
}
.empty {
padding: 16px;
font-size: 13px;
color: var(--text-tertiary);
text-align: center;
}
.account {
padding: 12px 14px;
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
margin-bottom: 10px;
background: var(--hover-bg);
&.disabled {
opacity: 0.6;
}
}
.account-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.account-title {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.badge {
font-size: 11px;
padding: 2px 7px;
border-radius: 10px;
background: var(--bg-card);
border: 1px solid var(--border-color);
color: var(--text-secondary);
}
.label {
font-weight: 600;
font-size: 14px;
}
.tag {
font-size: 11px;
color: var(--text-tertiary);
&.exclusive {
color: var(--color-primary);
}
&.warn {
color: #d19a3a;
}
}
.account-actions {
display: flex;
align-items: center;
gap: 8px;
}
.account-meta {
display: flex;
align-items: center;
gap: 10px;
margin-top: 6px;
font-size: 12px;
color: var(--text-tertiary);
flex-wrap: wrap;
}
.mono {
font-family: var(--font-mono, monospace);
}
.probe {
color: #e26a6a;
&.ok {
color: var(--color-online);
}
}
.grantees {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
margin-top: 10px;
}
.grantees-label {
font-size: 12px;
color: var(--text-tertiary);
}
.muted {
font-size: 12px;
color: var(--text-tertiary);
}
.chip {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 2px 8px;
font-size: 12px;
border-radius: 10px;
background: var(--bg-card);
border: 1px solid var(--border-color);
}
.chip-x {
border: none;
background: none;
color: var(--text-tertiary);
cursor: pointer;
font-size: 13px;
line-height: 1;
padding: 0 0 0 2px;
&:hover {
color: #e26a6a;
}
}
.assign-select {
margin-left: auto;
}
.cookie-edit {
display: flex;
gap: 8px;
margin-top: 10px;
.field {
flex: 1;
}
}
.switch {
position: relative;
display: inline-block;
width: 34px;
height: 18px;
input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
inset: 0;
background: var(--border-color);
border-radius: 9px;
cursor: pointer;
transition: background var(--transition-fast);
}
.slider::before {
content: '';
position: absolute;
width: 14px;
height: 14px;
left: 2px;
top: 2px;
background: #fff;
border-radius: 50%;
transition: transform var(--transition-fast);
}
input:checked + .slider {
background: var(--color-primary);
}
input:checked + .slider::before {
transform: translateX(16px);
}
}
.error {
margin: 6px 0;
font-size: 12px;
color: #e26a6a;
}
</style>
+552
View File
@@ -0,0 +1,552 @@
<template>
<!-- The signed-in user's own music accounts (#164 + #164 follow-up).
Two ways an account can apply to this user:
- 自己扫码绑定 (source = personal) → they may unlink it
- 管理员分配 (source = granted) → only the admin can revoke it
Everything is read from /api/me/music/<platform>/status; the cookie never
reaches the browser. -->
<div class="account-card">
<div class="account-header">
<Icon icon="mdi:account-music" class="account-icon" />
<div class="account-info">
<div class="account-name">我的音乐账号</div>
<div class="account-status" :class="{ logged: status.loggedIn, granted: status.source === 'granted' }">
<template v-if="status.source === 'granted'">
由管理员分配:{{ status.label || '已分配的账号' }}
<template v-if="status.loggedIn && status.nickname">({{ status.nickname }})</template>
<template v-else-if="!status.loggedIn">,但登录已失效,请联系管理员</template>
</template>
<template v-else-if="status.loggedIn">已绑定:{{ status.nickname }}</template>
<template v-else-if="status.linked">已绑定,但登录已失效,请重新扫码</template>
<template v-else>未绑定 — 使用机器人的共享账号</template>
</div>
</div>
</div>
<!-- Platform switch: only the sources this instance has enabled. -->
<div v-if="platforms.length > 1" class="platform-tabs">
<button
v-for="p in platforms"
:key="p"
class="platform-tab"
:class="{ active: p === current }"
@click="selectPlatform(p)"
>
{{ PLATFORM_LABEL[p] ?? p }}
</button>
</div>
<p class="hint">
<template v-if="status.source === 'granted'">
网页搜索、歌单和每日推荐默认使用管理员分配的账号。自己的绑定优先。
</template>
<template v-else-if="status.supportsQrLogin">
管理员开启每用户独立账号后,可使用你绑定的{{ PLATFORM_LABEL[current] ?? current }}账号查看网页搜索、歌单和推荐。登录凭据保存在服务器。
</template>
<template v-else>
该平台暂不支持在网页端自助绑定,需要账号请联系管理员分配。
</template>
</p>
<!-- 网页用哪个账号。只有真的持有个人/分配账号、且管理员开了这个功能时
才有得选;否则本来就走共享账号。 -->
<div
v-if="status.featureEnabled && status.linked"
class="account-choice"
role="radiogroup"
aria-label="网页端使用哪个账号"
>
<div class="account-choice-title">网页端使用哪个账号</div>
<div
class="account-choice-option"
:class="{ active: !status.preferShared }"
role="radio"
:aria-checked="!status.preferShared"
tabindex="0"
@click="setPreference(false)"
@keydown.enter.prevent="setPreference(false)"
@keydown.space.prevent="setPreference(false)"
>
<span class="account-choice-dot" :class="{ on: !status.preferShared }" />
<span class="account-choice-text">
<strong>我的账号</strong>
<em>
{{ status.source === 'granted' ? '管理员分配的账号' : '我扫码绑定的账号' }}
</em>
</span>
</div>
<div
class="account-choice-option"
:class="{ active: status.preferShared }"
role="radio"
:aria-checked="status.preferShared"
tabindex="0"
@click="setPreference(true)"
@keydown.enter.prevent="setPreference(true)"
@keydown.space.prevent="setPreference(true)"
>
<span class="account-choice-dot" :class="{ on: status.preferShared }" />
<span class="account-choice-text">
<strong>共享账号(管理员的)</strong>
<em>查看共享账号的歌单和推荐</em>
</span>
</div>
<div class="account-choice-note">
这个选择影响网页端的搜索、歌单和推荐。房间播歌使用机器人共享账号。
</div>
</div>
<div class="login-methods">
<button
v-if="status.supportsQrLogin"
class="login-btn"
:disabled="qr.loading"
@click="startQrLogin"
>
<Icon icon="mdi:qrcode" />
{{ status.linked ? '重新扫码绑定' : '扫码绑定' }}
</button>
<!-- Only the user's OWN login can be removed here; an admin-granted one
is managed from Settings → 音乐账号分配. -->
<button v-if="status.canUnlink" class="login-btn" @click="unlink">
<Icon icon="mdi:link-off" />
解除绑定
</button>
</div>
<div v-if="qr.loading" class="qr-loading">
<Icon icon="mdi:loading" class="spin" />
生成二维码中...
</div>
<div v-else-if="qr.dataUrl" class="qr-wrap">
<img :src="qr.dataUrl" class="qr-image" alt="QR Code" />
<div class="qr-status" :class="qr.status">
<template v-if="qr.status === 'waiting'">
<Icon icon="mdi:cellphone" /> 请使用{{ PLATFORM_LABEL[current] ?? '' }}APP扫码
</template>
<template v-else-if="qr.status === 'scanned'">
<Icon icon="mdi:check" /> 已扫码,请在手机上确认
</template>
<template v-else-if="qr.status === 'confirmed'">
<Icon icon="mdi:check-circle" /> 绑定成功!
</template>
<template v-else-if="qr.status === 'expired'">
<Icon icon="mdi:refresh" /> 二维码已过期
<button class="btn-link" @click="startQrLogin">重新生成</button>
</template>
</div>
</div>
<p v-if="error" class="error">{{ error }}</p>
</div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { Icon } from '@iconify/vue';
import axios from 'axios';
import QRCode from 'qrcode';
const props = withDefaults(defineProps<{ platforms?: string[] }>(), {
platforms: () => ['netease'],
});
const PLATFORM_LABEL: Record<string, string> = {
netease: '网易云',
qq: 'QQ音乐',
kugou: '酷狗',
bilibili: 'B站',
};
const current = ref(props.platforms[0] ?? 'netease');
const status = reactive({
linked: false,
loggedIn: false,
nickname: '',
label: '',
source: 'none' as 'none' | 'personal' | 'granted',
canUnlink: false,
supportsQrLogin: false,
preferShared: false,
featureEnabled: false,
});
const qr = reactive({
loading: false,
dataUrl: '',
key: '',
status: 'waiting' as 'waiting' | 'scanned' | 'confirmed' | 'expired',
});
const error = ref('');
let pollTimer: ReturnType<typeof setInterval> | null = null;
const base = () => `/api/me/music/${current.value}`;
function stopPolling() {
if (pollTimer) clearInterval(pollTimer);
pollTimer = null;
}
async function refreshStatus() {
try {
const res = await axios.get(`${base()}/status`);
status.linked = Boolean(res.data?.linked);
status.loggedIn = Boolean(res.data?.loggedIn);
status.nickname = res.data?.nickname ?? '';
status.label = res.data?.label ?? '';
status.source = res.data?.source ?? 'none';
status.canUnlink = Boolean(res.data?.canUnlink);
status.supportsQrLogin = Boolean(res.data?.supportsQrLogin);
status.preferShared = Boolean(res.data?.preferShared);
status.featureEnabled = Boolean(res.data?.featureEnabled);
} catch {
// Leave the last known state
}
}
function resetQr() {
stopPolling();
qr.dataUrl = '';
qr.key = '';
qr.status = 'waiting';
}
function selectPlatform(p: string) {
if (p === current.value) return;
current.value = p;
error.value = '';
resetQr();
void refreshStatus();
}
async function startQrLogin() {
stopPolling();
error.value = '';
qr.loading = true;
qr.dataUrl = '';
qr.status = 'waiting';
try {
const res = await axios.post(`${base()}/qrcode`);
const { qrUrl, qrImg, key } = res.data;
qr.key = key;
// Dark-on-light only: many in-app scanners can't read an inverted code.
qr.dataUrl = qrImg || (await QRCode.toDataURL(qrUrl, {
width: 200,
margin: 2,
color: { dark: '#000000', light: '#ffffff' },
}));
pollTimer = setInterval(pollQrStatus, 2000);
} catch (err: any) {
const code = err?.response?.status;
error.value = code === 501
? '该平台暂不支持自助绑定,请联系管理员分配账号'
: (err?.response?.data?.error ?? '二维码生成失败');
} finally {
qr.loading = false;
}
}
async function pollQrStatus() {
if (!qr.key) return;
try {
const res = await axios.get(`${base()}/qrcode/status`, { params: { key: qr.key } });
qr.status = res.data.status;
if (qr.status === 'confirmed') {
stopPolling();
await refreshStatus();
} else if (qr.status === 'expired') {
stopPolling();
}
} catch {
// Ignore poll errors
}
}
/**
* Switch which login playback uses.
*
* `true` = the bot's shared account (usually the admin's, usually the one with
* a membership), `false` = my own / the assigned one. Nothing is unlinked, so
* switching back restores the personal account exactly as it was.
*/
async function setPreference(preferShared: boolean) {
if (preferShared === status.preferShared) return;
error.value = '';
const previous = status.preferShared;
status.preferShared = preferShared; // optimistic — the radio must feel instant
try {
await axios.put(`${base()}/preference`, { preferShared });
} catch (err: any) {
status.preferShared = previous;
const code = err?.response?.status;
error.value =
code === 409
? '管理员未开启「每用户独立账号」,暂时无法切换'
: (err?.response?.data?.error ?? '切换失败');
}
}
async function unlink() {
error.value = '';
try {
await axios.delete(base());
resetQr();
await refreshStatus();
} catch (err: any) {
error.value = err?.response?.data?.error ?? '解除绑定失败';
}
}
// Settings can render before the provider list is known; follow it if it changes.
watch(
() => props.platforms,
(list) => {
if (list.length > 0 && !list.includes(current.value)) {
current.value = list[0];
void refreshStatus();
}
},
);
onMounted(refreshStatus);
onUnmounted(stopPolling);
</script>
<style lang="scss" scoped>
.account-card {
margin-top: 16px;
padding: 20px;
background: var(--hover-bg);
border-radius: var(--radius-md);
}
.account-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 12px;
}
.account-icon {
font-size: 28px;
color: var(--color-primary);
}
.account-name {
font-weight: 600;
}
.account-status {
font-size: 12px;
color: var(--text-tertiary);
&.logged { color: var(--color-online); }
&.granted { color: var(--text-secondary); }
}
.platform-tabs {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 10px;
}
.platform-tab {
padding: 5px 12px;
font-size: 12px;
border-radius: 14px;
border: 1px solid var(--border-color);
background: var(--bg-card);
color: var(--text-secondary);
cursor: pointer;
transition: all var(--transition-fast);
&.active {
border-color: var(--color-primary);
color: var(--color-primary);
}
}
.hint {
font-size: 12px;
color: var(--text-tertiary);
margin: 0 0 12px;
line-height: 1.5;
}
.account-choice {
margin: 12px 0 16px;
padding: 12px;
border: 1px solid var(--border-color, rgba(128, 128, 128, 0.2));
border-radius: var(--radius-sm, 8px);
}
.account-choice-title {
font-size: 13px;
font-weight: 600;
margin-bottom: 8px;
color: var(--text-primary);
}
.account-choice-option {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 8px 10px;
border-radius: var(--radius-sm, 8px);
cursor: pointer;
transition: background-color 0.15s ease;
& + & {
margin-top: 4px;
}
&:hover {
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.08));
}
&.active {
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.1));
}
&:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
}
.account-choice-dot {
flex: 0 0 auto;
width: 16px;
height: 16px;
margin-top: 2px;
border-radius: 50%;
border: 2px solid var(--text-secondary, #888);
position: relative;
&.on {
border-color: var(--color-primary);
&::after {
content: '';
position: absolute;
inset: 2px;
border-radius: 50%;
background: var(--color-primary);
}
}
}
.account-choice-text {
display: flex;
flex-direction: column;
gap: 2px;
font-size: 13px;
line-height: 1.45;
strong {
font-weight: 600;
color: var(--text-primary);
}
em {
font-style: normal;
color: var(--text-secondary);
font-size: 12px;
}
}
/* Scope disclaimer: the radio above governs the web player only. Members were
reading "共享账号" as "房间里也用这个" — which is true, but for the opposite
reason, so it needs saying. */
.account-choice-note {
margin-top: 8px;
padding-top: 8px;
border-top: 1px dashed var(--border-color, rgba(128, 128, 128, 0.2));
font-size: 12px;
line-height: 1.5;
color: var(--text-secondary);
code {
font-size: 11px;
padding: 1px 4px;
border-radius: 3px;
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.12));
}
}
.login-methods {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 16px;
}
.login-btn {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 16px;
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
font-size: 13px;
font-weight: 500;
color: inherit;
cursor: pointer;
transition: all var(--transition-fast);
&:hover:not(:disabled) { border-color: var(--color-primary); color: var(--color-primary); }
&:disabled { opacity: 0.6; cursor: default; }
}
.qr-loading {
display: flex;
align-items: center;
gap: 8px;
color: var(--text-secondary);
}
.qr-wrap {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
}
.qr-image {
width: 200px;
height: 200px;
border-radius: var(--radius-md);
border: 2px solid var(--border-color);
}
.qr-status {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--text-secondary);
&.confirmed { color: var(--color-online); }
}
.btn-link {
background: none;
border: none;
color: var(--color-primary);
cursor: pointer;
padding: 0;
}
.error {
margin-top: 8px;
font-size: 12px;
color: #e26a6a;
}
.spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
@@ -1,261 +0,0 @@
<template>
<!-- The signed-in user's own NetEase account, used for THEIR 私人FM instead
of the bot's shared login (#164). -->
<div class="account-card">
<div class="account-header">
<Icon icon="mdi:radio" class="account-icon" />
<div class="account-info">
<div class="account-name">我的网易云账号(私人FM)</div>
<div class="account-status" :class="{ logged: status.loggedIn }">
<template v-if="status.loggedIn">已绑定: {{ status.nickname }}</template>
<template v-else-if="status.linked">已绑定,但登录已失效,请重新扫码</template>
<template v-else>未绑定 — 私人FM使用机器人的共享账号</template>
</div>
</div>
</div>
<p class="hint">
绑定后,你在网页端开启的网易云私人FM会按你自己的口味推荐;其他人不受影响。
仅保存在服务器上,不会显示给任何人。
</p>
<div class="login-methods">
<button class="login-btn" :disabled="qr.loading" @click="startQrLogin">
<Icon icon="mdi:qrcode" />
{{ status.linked ? '重新扫码绑定' : '扫码绑定' }}
</button>
<button v-if="status.linked" class="login-btn" @click="unlink">
<Icon icon="mdi:link-off" />
解除绑定
</button>
</div>
<div v-if="qr.loading" class="qr-loading">
<Icon icon="mdi:loading" class="spin" />
生成二维码中...
</div>
<div v-else-if="qr.dataUrl" class="qr-wrap">
<img :src="qr.dataUrl" class="qr-image" alt="QR Code" />
<div class="qr-status" :class="qr.status">
<template v-if="qr.status === 'waiting'">
<Icon icon="mdi:cellphone" /> 请使用网易云音乐APP扫码
</template>
<template v-else-if="qr.status === 'scanned'">
<Icon icon="mdi:check" /> 已扫码,请在手机上确认
</template>
<template v-else-if="qr.status === 'confirmed'">
<Icon icon="mdi:check-circle" /> 绑定成功!
</template>
<template v-else-if="qr.status === 'expired'">
<Icon icon="mdi:refresh" /> 二维码已过期
<button class="btn-link" @click="startQrLogin">重新生成</button>
</template>
</div>
</div>
<p v-if="error" class="error">{{ error }}</p>
</div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { Icon } from '@iconify/vue';
import axios from 'axios';
import QRCode from 'qrcode';
const BASE = '/api/me/music/netease';
const status = reactive({ linked: false, loggedIn: false, nickname: '' });
const qr = reactive({
loading: false,
dataUrl: '',
key: '',
status: 'waiting' as 'waiting' | 'scanned' | 'confirmed' | 'expired',
});
const error = ref('');
let pollTimer: ReturnType<typeof setInterval> | null = null;
function stopPolling() {
if (pollTimer) clearInterval(pollTimer);
pollTimer = null;
}
async function refreshStatus() {
try {
const res = await axios.get(`${BASE}/status`);
status.linked = Boolean(res.data?.linked);
status.loggedIn = Boolean(res.data?.loggedIn);
status.nickname = res.data?.nickname ?? '';
} catch {
// Leave the last known state
}
}
async function startQrLogin() {
stopPolling();
error.value = '';
qr.loading = true;
qr.dataUrl = '';
qr.status = 'waiting';
try {
const res = await axios.post(`${BASE}/qrcode`);
const { qrUrl, qrImg, key } = res.data;
qr.key = key;
// Dark-on-light only: many in-app scanners can't read an inverted code.
qr.dataUrl = qrImg || (await QRCode.toDataURL(qrUrl, {
width: 200,
margin: 2,
color: { dark: '#000000', light: '#ffffff' },
}));
pollTimer = setInterval(pollQrStatus, 2000);
} catch (err: any) {
error.value = err?.response?.data?.error ?? '二维码生成失败';
} finally {
qr.loading = false;
}
}
async function pollQrStatus() {
if (!qr.key) return;
try {
const res = await axios.get(`${BASE}/qrcode/status`, { params: { key: qr.key } });
qr.status = res.data.status;
if (qr.status === 'confirmed') {
stopPolling();
await refreshStatus();
} else if (qr.status === 'expired') {
stopPolling();
}
} catch {
// Ignore poll errors
}
}
async function unlink() {
error.value = '';
try {
await axios.delete(BASE);
stopPolling();
qr.dataUrl = '';
await refreshStatus();
} catch (err: any) {
error.value = err?.response?.data?.error ?? '解除绑定失败';
}
}
onMounted(refreshStatus);
onUnmounted(stopPolling);
</script>
<style lang="scss" scoped>
.account-card {
margin-top: 16px;
padding: 20px;
background: var(--hover-bg);
border-radius: var(--radius-md);
}
.account-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 12px;
}
.account-icon {
font-size: 28px;
color: var(--color-primary);
}
.account-name {
font-weight: 600;
}
.account-status {
font-size: 12px;
color: var(--text-tertiary);
&.logged { color: var(--color-online); }
}
.hint {
font-size: 12px;
color: var(--text-tertiary);
margin: 0 0 12px;
line-height: 1.5;
}
.login-methods {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 16px;
}
.login-btn {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 16px;
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
font-size: 13px;
font-weight: 500;
color: inherit;
cursor: pointer;
transition: all var(--transition-fast);
&:hover:not(:disabled) { border-color: var(--color-primary); color: var(--color-primary); }
&:disabled { opacity: 0.6; cursor: default; }
}
.qr-loading {
display: flex;
align-items: center;
gap: 8px;
color: var(--text-secondary);
}
.qr-wrap {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
}
.qr-image {
width: 200px;
height: 200px;
border-radius: var(--radius-md);
border: 2px solid var(--border-color);
}
.qr-status {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--text-secondary);
&.confirmed { color: var(--color-online); }
}
.btn-link {
background: none;
border: none;
color: var(--color-primary);
cursor: pointer;
padding: 0;
}
.error {
margin-top: 8px;
font-size: 12px;
color: #e26a6a;
}
.spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
+66 -2
View File
@@ -116,7 +116,10 @@
</form>
<p v-if="ownPwError" class="user-error">{{ ownPwError }}</p>
<p v-if="ownPwSuccess" class="user-success">{{ ownPwSuccess }}</p>
<PersonalNeteaseAccount v-if="providerOn('netease') && !session.isGuest.value" />
<PersonalMusicAccount
v-if="!session.isGuest.value && personalPlatforms.length > 0"
:platforms="personalPlatforms"
/>
</section>
<!-- Bot Management (create/edit/delete/start-stop) requires bot.manage -->
@@ -973,6 +976,29 @@
@change="savePlayKeepsQueue"
/>
</label>
<!-- Admin-only: per-user music accounts. Off by default so an existing
deployment keeps sharing one login with everyone. -->
<label v-if="session.isAdmin.value" class="profile-toggle behavior-toggle">
<div class="profile-toggle-text">
<div class="profile-toggle-label">每个成员使用自己的音乐账号</div>
<div class="profile-toggle-hint">开启后,成员可用自己绑定或管理员分配的账号访问网页搜索、歌单和推荐。仅网易云支持成员扫码绑定。没有专属账号时使用机器人共享账号。房间播歌始终使用共享账号。</div>
</div>
<input
v-model="perUserMusicAccounts"
type="checkbox"
class="profile-toggle-switch"
@change="savePerUserMusicAccounts"
/>
</label>
<!-- Admin-only: the pool of logins that can be handed to members. Only
meaningful while the toggle above is on. -->
<div v-if="session.isAdmin.value && perUserMusicAccounts" class="pool-wrap">
<div class="pool-title">音乐账号分配</div>
<div class="pool-hint">添加管理员拥有的账号,分配给指定成员(也可以分配给其他管理员)。成员自己绑定的账号优先;未绑定的人使用分配给自己的账号;都没有时回到机器人的共享账号。这些账号同样只作用于<strong>网页端</strong>,房间里的播放始终用共享账号。</div>
<MusicAccountPool />
</div>
</section>
<!-- Guest Mode (admin only) -->
@@ -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<string, string> = {
@@ -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);