From d3eb6f2107065c0303fd79ce2f5c0c95d564d619 Mon Sep 17 00:00:00 2001 From: jiayuLian Date: Sun, 8 Nov 2026 18:10:08 +0800 Subject: [PATCH] feat(music): let a member choose the shared login when their own has no VIP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The order was hardcoded: own account → assigned account → shared. That is the right default (privacy first), but it leaves one common case stuck: a member's own NetEase login is real but has no membership, while the admin's does. They linked their account, so playback keeps using theirs, and every paid track fails — with no way to say "just use the admin's for playback". Two things now: 1. An explicit choice — `user_music_prefs` (userId + platform), exposed as GET/PUT `/api/me/music/:platform/preference` and a radio in the account card. `preferShared: true` outranks EVERYTHING, including `alwaysPersonal` (someone who chose membership over their own recommendations wants the shared login for FM too). It stores a flag, not a cookie — flipping it back restores the personal account untouched. 2. An automatic fallback for people who never touch the switch. Only `getSongUrl` is wrapped: if the personal account returns `url: null` or throws, the same track is retried once on the shared login. Search, playlists and FM stay on the member's own account — that is the point of per-user logins, and widening the fallback would leak their library back to the admin's. Details: - The fallback lives in `resolveProviderForRequest`, so every playback entry point (web click, chat !play, auto-advance, playlists) gets it by construction, and the shared instance is never mutated. - `fallbackToShared: false` is available for callers that must stay strictly on the member's account; the default is on, because "my account has no VIP" is the complaint that produced this feature. - The status payload now carries `preferShared` and `featureEnabled`, so the UI can render the radio without a second round-trip and hide it when the admin has the feature off (PUT answers 409 in that case). 13 new tests: preference overrides own + assigned + alwaysPersonal, feature-off ignored, GET/PUT round-trip, per-platform isolation, stored cookie untouched, non-boolean rejected, 409 when disabled; fallback on null, on throw, keeps the personal result when it works, can be disabled, leaves the shared instance untouched. --- src/data/database.ts | 37 +++++ src/web/api/personal-music.test.ts | 76 +++++++++ src/web/api/personal-music.ts | 49 ++++++ src/web/api/provider-scope.test.ts | 162 +++++++++++++++++++- src/web/api/provider-scope.ts | 65 +++++++- web/src/components/PersonalMusicAccount.vue | 158 +++++++++++++++++++ 6 files changed, 544 insertions(+), 3 deletions(-) diff --git a/src/data/database.ts b/src/data/database.ts index 8a9205f..3a5f493 100644 --- a/src/data/database.ts +++ b/src/data/database.ts @@ -197,6 +197,9 @@ export interface BotDatabase { getUserMusicCookie(userId: string, platform: string): string | null; setUserMusicCookie(userId: string, platform: string, cookie: string): void; deleteUserMusicCookie(userId: string, platform: string): boolean; + /** null when the member never chose; callers treat that as "prefer own". */ + getUserMusicPreference(userId: string, platform: string): { preferShared: boolean } | null; + setUserMusicPreference(userId: string, platform: string, preferShared: boolean): void; // Admin-owned account pool + assignments (#164 follow-up). listMusicAccounts(platform?: string): MusicAccount[]; getMusicAccount(id: string): MusicAccount | null; @@ -453,6 +456,20 @@ function initTables(db: Database.Database): void { FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE ); + -- Which login a member wants to use for a platform (#164 follow-up). + -- preferShared = 1 means "ignore my own / assigned account and play + -- through the bot's shared login", which is how someone whose own account + -- has no membership still gets to play paid tracks. Default 0 keeps the + -- privacy-first behaviour (own account wins). + CREATE TABLE IF NOT EXISTS user_music_prefs ( + userId TEXT NOT NULL, + platform TEXT NOT NULL, + preferShared INTEGER NOT NULL DEFAULT 0, + updatedAt TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (userId, platform), + FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE + ); + -- Admin-owned music logins that can be handed out to members (#164 -- follow-up). Separate from user_music_cookies so a member's own QR login -- and an admin's assignment never overwrite each other. @@ -620,6 +637,14 @@ export function createDatabase(dbPath: string): BotDatabase { `DELETE FROM user_music_cookies WHERE userId = ? AND platform = ?`, ); + const selectUserMusicPref = db.prepare( + `SELECT preferShared FROM user_music_prefs WHERE userId = ? AND platform = ?`, + ); + const upsertUserMusicPref = db.prepare(` + INSERT INTO user_music_prefs (userId, platform, preferShared) VALUES (?, ?, ?) + ON CONFLICT(userId, platform) DO UPDATE SET preferShared = excluded.preferShared, updatedAt = datetime('now') + `); + // ---- Admin-owned account pool (#164 follow-up) ------------------------- const MUSIC_ACCOUNT_GRANT_SELECT = ` SELECT g.userId, COALESCE(u.username, g.userId) AS username, g.platform, @@ -925,6 +950,18 @@ export function createDatabase(dbPath: string): BotDatabase { return deleteUserMusicCookieStmt.run(userId, platform).changes > 0; }, + getUserMusicPreference(userId, platform) { + const row = selectUserMusicPref.get(userId, platform) as + | { preferShared: number } + | undefined; + if (!row) return null; + return { preferShared: Number(row.preferShared) === 1 }; + }, + + setUserMusicPreference(userId, platform, preferShared) { + upsertUserMusicPref.run(userId, platform, preferShared ? 1 : 0); + }, + listMusicAccounts(platform) { const rows = platform ? (selectMusicAccountsByPlatform.all(platform) as Record[]) diff --git a/src/web/api/personal-music.test.ts b/src/web/api/personal-music.test.ts index 1f2f34a..b6295ad 100644 --- a/src/web/api/personal-music.test.ts +++ b/src/web/api/personal-music.test.ts @@ -60,6 +60,7 @@ describe("personal music account router (#164)", () => { expect(res.status).toBe(200); expect(res.body).toEqual({ linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true, + preferShared: false, featureEnabled: false, }); }); @@ -93,6 +94,8 @@ describe("personal music account router (#164)", () => { source: "personal", canUnlink: true, supportsQrLogin: true, + preferShared: false, + featureEnabled: false, loggedIn: true, nickname: "Alice163", }); @@ -131,6 +134,8 @@ describe("personal music account router (#164)", () => { label: "网易云-主号", canUnlink: false, supportsQrLogin: true, + preferShared: false, + featureEnabled: true, loggedIn: true, nickname: "Alice163", }); @@ -143,6 +148,7 @@ describe("personal music account router (#164)", () => { const res = await request(app).get("/api/me/music/netease/status"); expect(res.body).toEqual({ linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true, + preferShared: false, featureEnabled: false, }); }); @@ -207,3 +213,73 @@ describe("web FM uses the caller's linked NetEase account (#164)", () => { expect(bot.startFm.mock.calls[0][0]).toBe(qq); }); }); + +// --------------------------------------------------------------------------- +// "Play through the shared account" preference (#164 follow-up) +// +// The case this exists for: the member's own NetEase login has no VIP, the +// admin's does. The preference is per-platform and per-user, and it must not +// touch either stored login. +// --------------------------------------------------------------------------- +describe("personal music — shared-account preference", () => { + const ON = { config: { perUserMusicAccounts: true } }; + + it("defaults to the member's own account", async () => { + const { app } = mount(ON); + const res = await request(app).get("/api/me/music/netease/preference"); + expect(res.status).toBe(200); + expect(res.body).toEqual({ platform: "netease", preferShared: false }); + }); + + it("stores the choice and reports it back", async () => { + const { app } = mount(ON); + const put = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + expect(put.status).toBe(200); + expect(put.body).toEqual({ platform: "netease", preferShared: true }); + + const get = await request(app).get("/api/me/music/netease/preference"); + expect(get.body.preferShared).toBe(true); + }); + + it("keeps the choice per platform", async () => { + const { app } = mount({ + ...ON, + extraProviders: { qq: { platform: "qq", withCookie: () => ({ getAuthStatus: async () => ({ loggedIn: true }) }) } }, + }); + await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + const qq = await request(app).get("/api/me/music/qq/preference"); + expect(qq.body.preferShared).toBe(false); + }); + + it("does not touch the stored login", async () => { + const { app, db } = mount(ON); + db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine"); + await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + + expect(db.getUserMusicCookie("u1", "netease")).toBe("MUSIC_U=mine"); + expect(db.getUserMusicPreference("u1", "netease")).toEqual({ preferShared: true }); + }); + + it("surfaces the choice on the status payload the UI already reads", async () => { + const { app, db } = mount(ON); + db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine"); + await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + + const res = await request(app).get("/api/me/music/netease/status"); + expect(res.body.preferShared).toBe(true); + expect(res.body.featureEnabled).toBe(true); + }); + + it("rejects a non-boolean", async () => { + const { app } = mount(ON); + const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: "yes" }); + expect(res.status).toBe(400); + }); + + it("refuses when the admin has the feature off", async () => { + const { app } = mount({ config: { perUserMusicAccounts: false } }); + const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true }); + expect(res.status).toBe(409); + expect(res.body.error).toBe("per_user_accounts_disabled"); + }); +}); diff --git a/src/web/api/personal-music.ts b/src/web/api/personal-music.ts index eb971a0..68c3e7b 100644 --- a/src/web/api/personal-music.ts +++ b/src/web/api/personal-music.ts @@ -85,6 +85,13 @@ export function createPersonalMusicRouter( // Lets the member UI hide "扫码绑定" on platforms that only accept an // admin-assigned account (qq / kugou / bilibili today). const supportsQrLogin = supportsPersonalLogin(provider); + // The member's explicit "play through the shared login" choice, so the UI + // can render the radio without a second round-trip. + const preferShared = + database.getUserMusicPreference(req.user!.id, platform)?.preferShared === true; + // The choice only exists while the admin has per-user accounts on; with it + // off everyone is already on the shared login and the radio is meaningless. + const featureEnabled = perUserMusicEnabled({ database, config }); if (!account.cookie) { res.json({ @@ -93,6 +100,8 @@ export function createPersonalMusicRouter( source: "none", canUnlink: false, supportsQrLogin, + preferShared, + featureEnabled, }); return; } @@ -105,6 +114,8 @@ export function createPersonalMusicRouter( label: account.label, canUnlink: account.canUnlink, supportsQrLogin, + preferShared, + featureEnabled, unsupported: true, }); return; @@ -117,6 +128,8 @@ export function createPersonalMusicRouter( label: account.label, canUnlink: account.canUnlink, supportsQrLogin, + preferShared, + featureEnabled, ...status, }); } catch (err) { @@ -128,6 +141,8 @@ export function createPersonalMusicRouter( label: account.label, canUnlink: account.canUnlink, supportsQrLogin, + preferShared, + featureEnabled, }); } }); @@ -199,5 +214,39 @@ export function createPersonalMusicRouter( }); }); + /** + * Which login this member plays through. + * + * `preferShared: true` = ignore my own (and any assigned) account and use the + * bot's shared login — the admin's, usually the one with a membership. It is + * the answer to "my NetEase account has no VIP, the admin's does, and I want + * the paid track". Nothing is deleted: flipping it back restores the personal + * account exactly as it was. + */ + router.put("/:platform/preference", (req, res) => { + const platform = req.params.platform; + const { preferShared } = req.body ?? {}; + if (typeof preferShared !== "boolean") { + res.status(400).json({ error: "preferShared must be a boolean" }); + return; + } + // With the feature off there is nothing to choose between — everything + // already runs on the shared login. Refuse instead of storing a value that + // would silently do nothing. + if (!perUserMusicEnabled({ database, config })) { + res.status(409).json({ error: "per_user_accounts_disabled" }); + return; + } + database.setUserMusicPreference(req.user!.id, platform, preferShared); + logger.info({ userId: req.user!.id, platform, preferShared }, "Music account preference set"); + res.json({ platform, preferShared }); + }); + + router.get("/:platform/preference", (req, res) => { + const platform = req.params.platform; + const pref = database.getUserMusicPreference(req.user!.id, platform); + res.json({ platform, preferShared: pref?.preferShared === true }); + }); + return router; } diff --git a/src/web/api/provider-scope.test.ts b/src/web/api/provider-scope.test.ts index 52b6afa..c57865e 100644 --- a/src/web/api/provider-scope.test.ts +++ b/src/web/api/provider-scope.test.ts @@ -25,10 +25,16 @@ function fakeProvider(opts: { * `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 { +function fakeDb( + own: string | null, + granted: GrantedMusicAccount | null = null, + preferShared = false, +): BotDatabase { return { getUserMusicCookie: () => own, getGrantedMusicAccount: () => granted, + getUserMusicPreference: () => + preferShared ? { preferShared: true } : null, } as unknown as BotDatabase; } @@ -298,3 +304,157 @@ describe("provider-scope", () => { }); }); }); + + +// --------------------------------------------------------------------------- +// "Play through the shared account" preference +// +// The real case: the member's own NetEase login has no VIP, the admin's does. +// Switching to shared must override BOTH their own link and any assignment — +// it is an explicit instruction, not a fallback. +// --------------------------------------------------------------------------- +describe("provider-scope — shared-account preference", () => { + it("ignores the member's own cookie when they chose the shared login", () => { + const resolved = resolveMusicCookie( + fakeReq({ id: "u1", role: "member" }), + "netease", + { + database: fakeDb("MUSIC_U=mine", null, true), + config: { perUserMusicAccounts: true }, + }, + ); + expect(resolved).toBeNull(); + }); + + it("also overrides an admin assignment", () => { + const resolved = resolveMusicCookie( + fakeReq({ id: "u1", role: "member" }), + "netease", + { + database: fakeDb(null, GRANTED, true), + config: { perUserMusicAccounts: true }, + }, + ); + expect(resolved).toBeNull(); + }); + + it("outranks alwaysPersonal, so personal FM follows the choice too", () => { + const resolved = resolveMusicCookie( + fakeReq({ id: "u1", role: "member" }), + "netease", + { + database: fakeDb("MUSIC_U=mine", null, true), + config: { perUserMusicAccounts: true }, + }, + { alwaysPersonal: true }, + ); + expect(resolved).toBeNull(); + }); + + it("hands the untouched shared provider back", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { + database: fakeDb("MUSIC_U=mine", null, true), + config: { perUserMusicAccounts: true }, + }, + ); + expect(scoped).toBe(shared); + }); + + it("is ignored while the admin has the feature off", () => { + const shared = fakeProvider({ withCookie: () => fakeProvider() }); + const scoped = resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { + database: fakeDb("MUSIC_U=mine", null, true), + config: { perUserMusicAccounts: false }, + }, + ); + expect(scoped).toBe(shared); + }); +}); + +// --------------------------------------------------------------------------- +// Automatic playback fallback +// +// Same scenario, minus an explicit choice: keep the member's own account for +// search / playlists, but when THIS track cannot be resolved on it, try the +// shared login instead of greying the track out. +// --------------------------------------------------------------------------- +describe("provider-scope — playback falls back to the shared login", () => { + function view( + getSongUrl: (songId: string, quality?: string) => Promise<{ url: string } | null>, + ): MusicProvider { + return { platform: "netease", getSongUrl } as unknown as MusicProvider; + } + + function scopeWith( + personal: MusicProvider, + sharedUrl: () => Promise<{ url: string } | null>, + options: { fallbackToShared?: boolean } = {}, + ) { + const shared = view(sharedUrl); + (shared as Partial).withCookie = () => personal; + return resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { + database: fakeDb("MUSIC_U=mine"), + config: { perUserMusicAccounts: true }, + }, + options, + ); + } + + it("uses the shared login when the personal account returns no url", async () => { + const scoped = scopeWith(view(async () => null), async () => ({ url: "https://shared/x.mp3" })); + expect((await scoped.getSongUrl("1"))?.url).toBe("https://shared/x.mp3"); + }); + + it("uses the shared login when the personal account throws", async () => { + const scoped = scopeWith( + view(async () => { + throw new Error("no membership"); + }), + async () => ({ url: "https://shared/x.mp3" }), + ); + expect((await scoped.getSongUrl("1"))?.url).toBe("https://shared/x.mp3"); + }); + + it("keeps the personal result when it works", async () => { + const scoped = scopeWith( + view(async () => ({ url: "https://mine/x.mp3" })), + async () => ({ url: "https://shared/x.mp3" }), + ); + expect((await scoped.getSongUrl("1"))?.url).toBe("https://mine/x.mp3"); + }); + + it("can be switched off so playback stays on the member's account", async () => { + const scoped = scopeWith( + view(async () => null), + async () => ({ url: "https://shared/x.mp3" }), + { fallbackToShared: false }, + ); + expect(await scoped.getSongUrl("1")).toBeNull(); + }); + + it("leaves the shared instance itself untouched", async () => { + const shared = view(async () => ({ url: "https://shared/x.mp3" })); + (shared as Partial).withCookie = () => view(async () => null); + resolveProviderForRequest( + fakeReq({ id: "u1", role: "member" }), + "netease", + shared, + { database: fakeDb("MUSIC_U=mine"), config: { perUserMusicAccounts: true } }, + ); + // Calling the shared provider directly must still hit its own implementation. + expect((await shared.getSongUrl("1"))?.url).toBe("https://shared/x.mp3"); + }); +}); diff --git a/src/web/api/provider-scope.ts b/src/web/api/provider-scope.ts index cfaa80a..d43ad95 100644 --- a/src/web/api/provider-scope.ts +++ b/src/web/api/provider-scope.ts @@ -102,6 +102,25 @@ export function grantedAccountFor( return deps.database.getGrantedMusicAccount(user.id!, platform); } +/** + * Whether the member explicitly asked to play through the shared login. + * + * This exists for one concrete case: their own account has no membership, the + * admin's does, and they would rather hear the paid tracks than their own + * recommendations. Choosing it overrides BOTH their own link and any admin + * assignment — it is an explicit instruction, not a fallback. + */ +export function preferSharedFor( + req: Request | undefined, + platform: string, + deps: MusicScopeDeps, +): boolean { + if (!perUserMusicEnabled(deps)) return false; + const user = scopedUser(req, deps); + if (!user || !deps.database) return false; + return deps.database.getUserMusicPreference(user.id!, platform)?.preferShared === true; +} + /** Where the cookie driving this request came from. */ export interface ResolvedMusicCookie { source: "personal" | "granted"; @@ -122,6 +141,10 @@ export function resolveMusicCookie( deps: MusicScopeDeps, options: { alwaysPersonal?: boolean } = {}, ): ResolvedMusicCookie | null { + // An explicit "use the shared account" outranks everything, including the + // `alwaysPersonal` escape hatch: someone who chose membership over their own + // recommendations wants the shared login for FM too. + if (preferSharedFor(req, platform, deps)) return null; const own = personalCookieFor(req, platform, deps, options.alwaysPersonal); if (own) return { source: "personal", cookie: own }; const granted = grantedAccountFor(req, platform, deps); @@ -136,6 +159,39 @@ export function resolveMusicCookie( return null; } +/** + * Give `view` a single-shot fallback to the shared login when its own playback + * attempt comes up empty. + * + * The case this exists for: the member's own account is real but has no + * membership, so `/song/url/v1` answers `url: null` (or 400 for the paid track) + * while the admin's account plays it fine. Without this the member has to go + * into settings and switch manually before every such track. + * + * Only `getSongUrl` is wrapped — search, playlists and FM stay on the member's + * own account, which is the whole point of per-user logins. The wrapper keeps + * the shared instance untouched, so nothing leaks between callers. + */ +function withSharedPlaybackFallback(view: MusicProvider, shared: MusicProvider): MusicProvider { + // Guard for partial implementations (and for test doubles): without both + // sides resolvable there is nothing to fall back to. + if (typeof view.getSongUrl !== "function" || typeof shared.getSongUrl !== "function") { + return view; + } + const ownResolve = view.getSongUrl.bind(view); + view.getSongUrl = async (songId: string, quality?: string) => { + try { + const result = await ownResolve(songId, quality); + if (result?.url) return result; + } catch { + // A failure on the personal side (no membership, -460, expired cookie) + // is not a reason for this track to go grey — try the shared login. + } + return shared.getSongUrl(songId, quality); + }; + return view; +} + /** * Wrap `shared` in a per-account view when the request carries a usable login; * otherwise return `shared` untouched. @@ -149,14 +205,19 @@ export function resolveProviderForRequest( platform: string, shared: MusicProvider, deps: MusicScopeDeps, - options: { alwaysPersonal?: boolean } = {}, + options: { alwaysPersonal?: boolean; fallbackToShared?: boolean } = {}, ): MusicProvider { const resolved = resolveMusicCookie(req, platform, deps, options); if (!resolved) return shared; if (typeof shared.withCookie !== "function") return shared; + let view: MusicProvider; try { - return shared.withCookie(resolved.cookie); + view = shared.withCookie(resolved.cookie); } catch { return shared; } + // On by default: the common complaint is "my account has no membership, the + // admin's does". Set false to keep playback strictly on the member's account. + if (options.fallbackToShared === false) return view; + return withSharedPlaybackFallback(view, shared); } diff --git a/web/src/components/PersonalMusicAccount.vue b/web/src/components/PersonalMusicAccount.vue index ebf3e32..b5cc921 100644 --- a/web/src/components/PersonalMusicAccount.vue +++ b/web/src/components/PersonalMusicAccount.vue @@ -49,6 +49,54 @@

+ + +