mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 03:12:51 +08:00
feat(music): per-user music accounts with an admin-owned account pool
Every member saw the admin's library: the bot keeps one shared login per platform (data/cookies/<platform>.json) and search, playlists and playback URLs all read through it. #164 added a personal NetEase login, but only for 私人FM — the rest still came from the shared account. On top of that, most members do not own a paid login, so "everyone links their own" is not enough: the admin has to be able to hand out accounts. What this adds, behind one admin switch (`perUserMusicAccounts`, default off): - One login per request, resolved in this order: the caller's OWN linked account, then an account an admin ASSIGNED, then the bot's shared login. - An admin-owned pool (`music_accounts`) plus per-member assignments (`music_account_grants`, PK userId+platform = one per platform). Assignments are capacity-checked inside a transaction, so an exclusive account cannot be handed to two members by two concurrent clicks. `enabled = 0` is an instant rollback of every grant without deleting them. - Own-beats-assigned, and the two live in separate tables: a member scanning their own QR code never overwrites an admin's assignment, and unlinking on the member side never revokes what the admin granted. - QQ / Kugou / Bilibili now implement `withCookie`, so all four sources can be isolated. Only NetEase exposes QR self-linking (it is the only one with `pollQrLogin`); the rest accept an assigned account, which is the workflow that actually matters for members without a paid login. - `/api/music-accounts` is admin-only (`requireAdmin`, not `bot.manage`): members must never see which account was handed to whom. Cookies are masked in every response. Switch off = no behaviour change at all, except 私人FM keeps the #164 behaviour through `alwaysPersonal`.
This commit is contained in:
1 parent
17008ae52e
commit
61c24cc219
20 files changed
+2568
-114
No files matched your search
@@ -130,6 +130,16 @@ 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, daily recommendations and playback URLs from
|
||||
* THAT account instead of the bot's shared login — so a member stops seeing
|
||||
* the admin's library. When off (or when the user has no linked account, or
|
||||
* the source has no per-account login) everything falls back to the shared
|
||||
* login, which is exactly the pre-existing behaviour.
|
||||
*/
|
||||
perUserMusicAccounts: boolean;
|
||||
/**
|
||||
* When true, a single-song immediate !play (chat) / play-song (web) inserts
|
||||
* after the current track and jumps to it instead of clearing the queue, so
|
||||
@@ -191,6 +201,7 @@ export function getDefaultConfig(): BotConfig {
|
||||
idleTimeoutMinutes: 0,
|
||||
localAudioEnabled: true,
|
||||
savedQueuesEnabled: false,
|
||||
perUserMusicAccounts: false,
|
||||
playKeepsQueue: false,
|
||||
publicUrl: "",
|
||||
trustProxy: false,
|
||||
@@ -394,6 +405,9 @@ export function loadConfig(path: string): BotConfig {
|
||||
// them (`"yes"`, `1`, `null` → false; only a literal `true` enables).
|
||||
const savedQueuesEnabled = partial.savedQueuesEnabled === true;
|
||||
const playKeepsQueue = partial.playKeepsQueue === true;
|
||||
// Same strict-coercion rule: a legacy config without the key, or a
|
||||
// hand-edited `"yes"`/`1`, must never turn account isolation on by accident.
|
||||
const perUserMusicAccounts = partial.perUserMusicAccounts === true;
|
||||
|
||||
// Voice ducking is opt-in and the retained-volume percentage is consumed
|
||||
// directly by the audio path. Only a plain-object block with correctly
|
||||
@@ -456,6 +470,7 @@ export function loadConfig(path: string): BotConfig {
|
||||
audioQuality,
|
||||
enabledProviders,
|
||||
savedQueuesEnabled,
|
||||
perUserMusicAccounts,
|
||||
playKeepsQueue,
|
||||
voiceDucking,
|
||||
defaultPlatform: defaultPlatformPref,
|
||||
|
||||
@@ -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,51 @@ export interface BotDatabase {
|
||||
getUserMusicCookie(userId: string, platform: string): string | null;
|
||||
setUserMusicCookie(userId: string, platform: string, cookie: string): void;
|
||||
deleteUserMusicCookie(userId: string, platform: string): boolean;
|
||||
// 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.
|
||||
*
|
||||
* `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): 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 +452,38 @@ function initTables(db: Database.Database): void {
|
||||
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 +620,117 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
`DELETE FROM user_music_cookies WHERE userId = ? AND platform = ?`,
|
||||
);
|
||||
|
||||
// ---- 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
|
||||
`);
|
||||
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 = ?`,
|
||||
);
|
||||
// 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 +925,87 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
return deleteUserMusicCookieStmt.run(userId, platform).changes > 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;
|
||||
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,
|
||||
});
|
||||
return true;
|
||||
},
|
||||
|
||||
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) {
|
||||
return deleteGrantStmt.run(userId, platform).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}`);
|
||||
|
||||
@@ -464,6 +464,27 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
this.cookie = 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;
|
||||
}
|
||||
|
||||
@@ -468,6 +468,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";
|
||||
|
||||
@@ -134,6 +134,14 @@ export interface MusicProvider {
|
||||
setCookie(cookie: string): void;
|
||||
getCookie(): string;
|
||||
getAuthStatus(): Promise<AuthStatus>;
|
||||
/**
|
||||
* 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[]>;
|
||||
|
||||
@@ -824,6 +824,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;
|
||||
}
|
||||
|
||||
+49
-2
@@ -4,8 +4,10 @@ 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,
|
||||
@@ -16,7 +18,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();
|
||||
// YouTube is auth-less; we only use this instance so /auth/status can
|
||||
@@ -36,9 +41,51 @@ 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, status }, "Auth status check");
|
||||
res.json({ platform: provider.platform, ...status });
|
||||
res.json({ platform: provider.platform, source: "shared", ...status });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Auth status check failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
|
||||
@@ -74,6 +74,7 @@ export function createBotRouter(
|
||||
voiceDucking: config.voiceDucking,
|
||||
localAudioEnabled: config.localAudioEnabled,
|
||||
savedQueuesEnabled: config.savedQueuesEnabled,
|
||||
perUserMusicAccounts: config.perUserMusicAccounts === true,
|
||||
playKeepsQueue: config.playKeepsQueue,
|
||||
adminGroups: config.adminGroups ?? [],
|
||||
guestMode: config.guestMode,
|
||||
@@ -94,6 +95,7 @@ export function createBotRouter(
|
||||
voiceDucking,
|
||||
guestMode,
|
||||
adminGroups,
|
||||
perUserMusicAccounts,
|
||||
} = req.body;
|
||||
|
||||
const hasIdle = idleTimeoutMinutes !== undefined;
|
||||
@@ -104,10 +106,14 @@ export function createBotRouter(
|
||||
|
||||
const hasAutoPause = typeof autoPauseOnEmpty === "boolean";
|
||||
const hasLocalAudioEnabled = typeof localAudioEnabled === "boolean";
|
||||
// Per-user music accounts: admin-only toggle (this route already requires
|
||||
// bot.manage). Strictly boolean — anything else leaves the value alone.
|
||||
const hasPerUserMusicAccounts = typeof perUserMusicAccounts === "boolean";
|
||||
|
||||
if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes;
|
||||
if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty;
|
||||
if (hasLocalAudioEnabled) config.localAudioEnabled = localAudioEnabled;
|
||||
if (hasPerUserMusicAccounts) config.perUserMusicAccounts = perUserMusicAccounts;
|
||||
|
||||
// Voice ducking is a partial settings block. Merge only known, strictly
|
||||
// valid fields so malformed JSON cannot replace the object or inject NaN /
|
||||
@@ -282,6 +288,7 @@ export function createBotRouter(
|
||||
voiceDucking: config.voiceDucking,
|
||||
localAudioEnabled: config.localAudioEnabled,
|
||||
savedQueuesEnabled: config.savedQueuesEnabled,
|
||||
perUserMusicAccounts: config.perUserMusicAccounts === true,
|
||||
playKeepsQueue: config.playKeepsQueue,
|
||||
adminGroups: config.adminGroups ?? [],
|
||||
guestMode: config.guestMode,
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
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();
|
||||
});
|
||||
|
||||
// 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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,337 @@
|
||||
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 string =>
|
||||
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;
|
||||
|
||||
/** 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 (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative number" });
|
||||
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 (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative number" });
|
||||
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.
|
||||
database.updateMusicAccount(account.id, {
|
||||
label: label === undefined ? undefined : label.trim(),
|
||||
cookie: cookie === undefined ? undefined : cookie.trim(),
|
||||
capacity,
|
||||
enabled,
|
||||
});
|
||||
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);
|
||||
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 (err) {
|
||||
logger.warn({ err, accountId: account.id }, "Music account probe failed");
|
||||
res.status(502).json({ error: (err as Error).message, 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) => {
|
||||
if (!cookieStore) {
|
||||
res.status(501).json({ error: "cookie store unavailable" });
|
||||
return;
|
||||
}
|
||||
const { platform, label, capacity } = req.body ?? {};
|
||||
if (!isPlatform(platform)) {
|
||||
res.status(400).json({ error: "unsupported platform" });
|
||||
return;
|
||||
}
|
||||
if (capacity !== undefined && (typeof capacity !== "number" || capacity < 0)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative number" });
|
||||
return;
|
||||
}
|
||||
const cookie = cookieStore.load(platform as Parameters<CookieStore["load"]>[0]);
|
||||
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;
|
||||
}
|
||||
+46
-18
@@ -1,11 +1,13 @@
|
||||
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 { 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 +72,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 +101,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/playback 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 +181,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.
|
||||
@@ -199,13 +216,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 = [
|
||||
@@ -246,7 +274,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) {
|
||||
@@ -261,7 +289,7 @@ export function createMusicRouter(
|
||||
|
||||
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 });
|
||||
@@ -272,7 +300,7 @@ export function createMusicRouter(
|
||||
|
||||
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 });
|
||||
@@ -283,7 +311,7 @@ export function createMusicRouter(
|
||||
|
||||
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 });
|
||||
@@ -294,7 +322,7 @@ export function createMusicRouter(
|
||||
|
||||
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 });
|
||||
@@ -305,7 +333,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
@@ -335,7 +363,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
@@ -351,7 +379,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
@@ -367,7 +395,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
@@ -383,7 +411,7 @@ export function createMusicRouter(
|
||||
|
||||
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" });
|
||||
|
||||
@@ -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,37 @@ 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,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a QR code", async () => {
|
||||
@@ -64,7 +88,14 @@ 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,
|
||||
loggedIn: true,
|
||||
nickname: "Alice163",
|
||||
});
|
||||
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=alice");
|
||||
});
|
||||
|
||||
@@ -74,6 +105,59 @@ 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,
|
||||
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,
|
||||
});
|
||||
});
|
||||
|
||||
// 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)", () => {
|
||||
|
||||
+134
-26
@@ -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,150 @@ 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);
|
||||
|
||||
if (!account.cookie) {
|
||||
res.json({
|
||||
linked: false,
|
||||
loggedIn: false,
|
||||
source: "none",
|
||||
canUnlink: false,
|
||||
supportsQrLogin,
|
||||
});
|
||||
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,
|
||||
unsupported: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await provider.withCookie(cookie).getAuthStatus();
|
||||
res.json({ linked: true, ...status });
|
||||
const status = await provider.withCookie(account.cookie).getAuthStatus();
|
||||
res.json({
|
||||
linked: true,
|
||||
source: account.source,
|
||||
label: account.label,
|
||||
canUnlink: account.canUnlink,
|
||||
supportsQrLogin,
|
||||
...status,
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn({ err }, "Personal NetEase status check failed");
|
||||
res.json({ linked: true, loggedIn: false });
|
||||
logger.warn({ err, 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,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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 +175,28 @@ 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",
|
||||
});
|
||||
});
|
||||
|
||||
return router;
|
||||
|
||||
+41
-35
@@ -1,4 +1,4 @@
|
||||
import { Router } from "express";
|
||||
import { Router, type Request } from "express";
|
||||
import type { BotManager } from "../../bot/manager.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import type { MusicProvider, Song, ArtistSongPage } from "../../music/provider.js";
|
||||
@@ -6,7 +6,7 @@ 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). */
|
||||
@@ -41,9 +41,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: Request, 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.
|
||||
@@ -151,19 +181,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);
|
||||
}
|
||||
// A caller who linked their own account gets FM from THEIR taste instead
|
||||
// of the bot's shared login (#164). With per-user accounts enabled the
|
||||
// same account now also resolves playback, so VIP/high-quality tracks
|
||||
// come from that account rather than the admin's.
|
||||
const provider = fmProvider(req, bot, platform);
|
||||
const message = await bot.startFm(provider, requesterName(req));
|
||||
res.json({
|
||||
ok:
|
||||
@@ -335,11 +357,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,11 +446,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();
|
||||
@@ -513,11 +527,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;
|
||||
@@ -749,11 +759,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) {
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
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): BotDatabase {
|
||||
return {
|
||||
getUserMusicCookie: () => own,
|
||||
getGrantedMusicAccount: () => granted,
|
||||
} 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/** 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: Request | undefined, deps: MusicScopeDeps): 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: Request | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
alwaysPersonal = false,
|
||||
): string | null {
|
||||
if (!alwaysPersonal && !perUserMusicEnabled(deps)) return null;
|
||||
const user = scopedUser(req, deps);
|
||||
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: Request | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
): GrantedMusicAccount | null {
|
||||
if (!perUserMusicEnabled(deps)) return null;
|
||||
const user = scopedUser(req, deps);
|
||||
if (!user || !deps.database) return null;
|
||||
return deps.database.getGrantedMusicAccount(user.id!, platform);
|
||||
}
|
||||
|
||||
/** 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: Request | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
options: { alwaysPersonal?: boolean } = {},
|
||||
): ResolvedMusicCookie | 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: Request | undefined,
|
||||
platform: string,
|
||||
shared: MusicProvider,
|
||||
deps: MusicScopeDeps,
|
||||
options: { alwaysPersonal?: boolean } = {},
|
||||
): MusicProvider {
|
||||
const resolved = resolveMusicCookie(req, platform, deps, options);
|
||||
if (!resolved) return shared;
|
||||
if (typeof shared.withCookie !== "function") return shared;
|
||||
try {
|
||||
return shared.withCookie(resolved.cookie);
|
||||
} catch {
|
||||
return shared;
|
||||
}
|
||||
}
|
||||
+36
-5
@@ -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.
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
<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('');
|
||||
const draft = reactive({ platform: 'netease', label: '', cookie: '', capacity: 0 });
|
||||
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 = 0;
|
||||
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>
|
||||
+134
-22
@@ -1,30 +1,67 @@
|
||||
<template>
|
||||
<!-- The signed-in user's own NetEase account, used for THEIR 私人FM instead
|
||||
of the bot's shared login (#164). -->
|
||||
<!-- 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:radio" class="account-icon" />
|
||||
<Icon icon="mdi:account-music" 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>
|
||||
<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>未绑定 — 私人FM使用机器人的共享账号</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">
|
||||
绑定后,你在网页端开启的网易云私人FM会按你自己的口味推荐;其他人不受影响。
|
||||
仅保存在服务器上,不会显示给任何人。
|
||||
<template v-if="status.source === 'granted'">
|
||||
这个账号是管理员分配给你的,搜索、歌单、每日推荐和播放都会用它。想换成自己的账号,直接扫码绑定即可 — 自己的账号优先。
|
||||
</template>
|
||||
<template v-else-if="status.supportsQrLogin">
|
||||
绑定后,{{ PLATFORM_LABEL[current] ?? current }}的搜索、歌单、每日推荐和播放地址都按你自己的账号获取,
|
||||
看不到管理员的歌单和收藏。仅保存在服务器上,不会显示给任何人。
|
||||
</template>
|
||||
<template v-else>
|
||||
该平台暂不支持在网页端自助绑定,需要账号请联系管理员分配。
|
||||
</template>
|
||||
</p>
|
||||
|
||||
<div class="login-methods">
|
||||
<button class="login-btn" :disabled="qr.loading" @click="startQrLogin">
|
||||
<button
|
||||
v-if="status.supportsQrLogin"
|
||||
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">
|
||||
<!-- 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>
|
||||
@@ -38,7 +75,7 @@
|
||||
<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扫码
|
||||
<Icon icon="mdi:cellphone" /> 请使用{{ PLATFORM_LABEL[current] ?? '' }}APP扫码
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'scanned'">
|
||||
<Icon icon="mdi:check" /> 已扫码,请在手机上确认
|
||||
@@ -57,14 +94,32 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, reactive, ref } from 'vue';
|
||||
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
const BASE = '/api/me/music/netease';
|
||||
const props = withDefaults(defineProps<{ platforms?: string[] }>(), {
|
||||
platforms: () => ['netease'],
|
||||
});
|
||||
|
||||
const status = reactive({ linked: false, loggedIn: false, nickname: '' });
|
||||
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,
|
||||
});
|
||||
const qr = reactive({
|
||||
loading: false,
|
||||
dataUrl: '',
|
||||
@@ -74,6 +129,8 @@ const qr = reactive({
|
||||
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;
|
||||
@@ -81,15 +138,34 @@ function stopPolling() {
|
||||
|
||||
async function refreshStatus() {
|
||||
try {
|
||||
const res = await axios.get(`${BASE}/status`);
|
||||
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);
|
||||
} 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 = '';
|
||||
@@ -97,7 +173,7 @@ async function startQrLogin() {
|
||||
qr.dataUrl = '';
|
||||
qr.status = 'waiting';
|
||||
try {
|
||||
const res = await axios.post(`${BASE}/qrcode`);
|
||||
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.
|
||||
@@ -108,7 +184,10 @@ async function startQrLogin() {
|
||||
}));
|
||||
pollTimer = setInterval(pollQrStatus, 2000);
|
||||
} catch (err: any) {
|
||||
error.value = err?.response?.data?.error ?? '二维码生成失败';
|
||||
const code = err?.response?.status;
|
||||
error.value = code === 501
|
||||
? '该平台暂不支持自助绑定,请联系管理员分配账号'
|
||||
: (err?.response?.data?.error ?? '二维码生成失败');
|
||||
} finally {
|
||||
qr.loading = false;
|
||||
}
|
||||
@@ -117,7 +196,7 @@ async function startQrLogin() {
|
||||
async function pollQrStatus() {
|
||||
if (!qr.key) return;
|
||||
try {
|
||||
const res = await axios.get(`${BASE}/qrcode/status`, { params: { key: qr.key } });
|
||||
const res = await axios.get(`${base()}/qrcode/status`, { params: { key: qr.key } });
|
||||
qr.status = res.data.status;
|
||||
if (qr.status === 'confirmed') {
|
||||
stopPolling();
|
||||
@@ -133,15 +212,25 @@ async function pollQrStatus() {
|
||||
async function unlink() {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(BASE);
|
||||
stopPolling();
|
||||
qr.dataUrl = '';
|
||||
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>
|
||||
@@ -174,6 +263,29 @@ onUnmounted(stopPolling);
|
||||
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 {
|
||||
@@ -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 -->
|
||||
@@ -967,6 +970,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">添加管理员拥有的账号,分配给指定成员(也可以分配给其他管理员)。成员自己绑定的账号优先;未绑定的人使用分配给自己的账号;都没有时回到机器人的共享账号。</div>
|
||||
<MusicAccountPool />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Guest Mode (admin only) -->
|
||||
@@ -1305,7 +1331,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';
|
||||
@@ -1431,6 +1458,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> = {
|
||||
@@ -1825,6 +1857,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;
|
||||
@@ -1865,6 +1899,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);
|
||||
@@ -1943,6 +1978,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
|
||||
@@ -3383,6 +3427,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);
|
||||
|
||||
Reference in new issue
Block a user