From 93e12cfc72da72dfdc1a5e76a1e6374438133e5d Mon Sep 17 00:00:00 2001 From: jude Date: Sun, 22 Nov 2026 09:45:52 +0000 Subject: [PATCH] Create and delete genre mixes from the web UI - Add a form to create a cluster mix rule: shown on first visit when there are no rules, and from a + in the sidebar for another Listenbrainz user. Backed by POST /api/discover/rules, which validates each setting and allows one rule per Listenbrainz user. - Add deleting a user's mixes from a bin in the sidebar, optionally also deleting the mixes' playlists from Subsonic. Backed by DELETE /api/discover/rules/?delete_playlists=true. - Stop showing the previous user's mix while a new user's mixes build. - Remove the per-account Listenbrainz token: LB Radio now always uses listenbrainz.token from the config. A migration drops the token columns from app_user, and PUT /api/auth/account/listenbrainz is gone. Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 +- ...de39ef9883b134c4f1ad97d55ad7c9bead982.json | 16 -- ...2fbe2c542e7c81ddf28f91b60d112a7a9e95b.json | 22 ++ ...20cc6e52f5c7492dbd3aeb6bbf90a7795cca9.json | 22 ++ ...19b8a225ef01ac92825065860cb868b04cbd9.json | 20 -- ...834d0a41c153ceba338b00ff52f3e1ae39fe4.json | 34 --- ...85d85a36795f49980e1fac023e12c610e4fef.json | 22 ++ README.md | 31 ++- discover/src/AccountView.tsx | 103 +-------- discover/src/App.tsx | 105 ++++++--- discover/src/Auth.tsx | 1 - discover/src/DeleteMixesView.tsx | 92 ++++++++ discover/src/NewMixesView.tsx | 202 ++++++++++++++++++ discover/src/api.ts | 16 +- discover/src/styles.css | 88 ++++++-- etc/playlistd/playlistd.toml | 2 +- ...120000_drop_account_listenbrainz_token.sql | 4 + src/auth.rs | 71 +----- src/daemon/cluster_mixes.rs | 2 +- src/discover.rs | 4 +- src/listenbrainz.rs | 35 +-- src/tracked.rs | 2 +- src/web.rs | 149 ++++++++++++- 23 files changed, 701 insertions(+), 344 deletions(-) delete mode 100644 .sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json create mode 100644 .sqlx/query-28192c8717a3cb6654c3868c43f2fbe2c542e7c81ddf28f91b60d112a7a9e95b.json create mode 100644 .sqlx/query-5b3c5bc84a46ee28e84803d183820cc6e52f5c7492dbd3aeb6bbf90a7795cca9.json delete mode 100644 .sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json delete mode 100644 .sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json create mode 100644 .sqlx/query-b1284c3dd34ac0f15791efd36f985d85a36795f49980e1fac023e12c610e4fef.json create mode 100644 discover/src/DeleteMixesView.tsx create mode 100644 discover/src/NewMixesView.tsx create mode 100644 migrations/20261122120000_drop_account_listenbrainz_token.sql diff --git a/.env.example b/.env.example index 8b97e2f..8857ce0 100644 --- a/.env.example +++ b/.env.example @@ -10,7 +10,7 @@ SUBSONIC_PASSWORD= POSTGRES_PASSWORD= # Optional: your Listenbrainz user token (listenbrainz.org/settings), to find new songs for each -# genre mix with LB Radio. You can also save it to your account in the web UI, which takes priority. +# genre mix with LB Radio. LISTENBRAINZ_TOKEN= # Where to serve playlistd. The first visit to the web UI creates the login, and anyone who gets diff --git a/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json b/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json deleted file mode 100644 index f88b3ec..0000000 --- a/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE \"app_user\" SET listenbrainz_token = $1, listenbrainz_user = $2 WHERE id = $3", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Varchar", - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982" -} diff --git a/.sqlx/query-28192c8717a3cb6654c3868c43f2fbe2c542e7c81ddf28f91b60d112a7a9e95b.json b/.sqlx/query-28192c8717a3cb6654c3868c43f2fbe2c542e7c81ddf28f91b60d112a7a9e95b.json new file mode 100644 index 0000000..73cb1bf --- /dev/null +++ b/.sqlx/query-28192c8717a3cb6654c3868c43f2fbe2c542e7c81ddf28f91b60d112a7a9e95b.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT playlist_id FROM \"cluster_mix_playlist\" WHERE rule_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "playlist_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "28192c8717a3cb6654c3868c43f2fbe2c542e7c81ddf28f91b60d112a7a9e95b" +} diff --git a/.sqlx/query-5b3c5bc84a46ee28e84803d183820cc6e52f5c7492dbd3aeb6bbf90a7795cca9.json b/.sqlx/query-5b3c5bc84a46ee28e84803d183820cc6e52f5c7492dbd3aeb6bbf90a7795cca9.json new file mode 100644 index 0000000..ce9a5c4 --- /dev/null +++ b/.sqlx/query-5b3c5bc84a46ee28e84803d183820cc6e52f5c7492dbd3aeb6bbf90a7795cca9.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT username FROM \"app_user\" WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "5b3c5bc84a46ee28e84803d183820cc6e52f5c7492dbd3aeb6bbf90a7795cca9" +} diff --git a/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json b/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json deleted file mode 100644 index 57a8942..0000000 --- a/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT listenbrainz_token AS \"token!\" FROM \"app_user\"\n WHERE listenbrainz_token IS NOT NULL\n ORDER BY created_at\n LIMIT 1\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "token!", - "type_info": "Text" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - true - ] - }, - "hash": "a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9" -} diff --git a/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json b/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json deleted file mode 100644 index 63c13a3..0000000 --- a/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT username, listenbrainz_user, listenbrainz_token IS NOT NULL AS \"has_listenbrainz_token!\"\n FROM \"app_user\" WHERE id = $1\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "username", - "type_info": "Varchar" - }, - { - "ordinal": 1, - "name": "listenbrainz_user", - "type_info": "Varchar" - }, - { - "ordinal": 2, - "name": "has_listenbrainz_token!", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - false, - true, - null - ] - }, - "hash": "a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4" -} diff --git a/.sqlx/query-b1284c3dd34ac0f15791efd36f985d85a36795f49980e1fac023e12c610e4fef.json b/.sqlx/query-b1284c3dd34ac0f15791efd36f985d85a36795f49980e1fac023e12c610e4fef.json new file mode 100644 index 0000000..74a9bba --- /dev/null +++ b/.sqlx/query-b1284c3dd34ac0f15791efd36f985d85a36795f49980e1fac023e12c610e4fef.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM \"cluster_mix_rule\" WHERE id = $1 RETURNING tracking_user", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "tracking_user", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "b1284c3dd34ac0f15791efd36f985d85a36795f49980e1fac023e12c610e4fef" +} diff --git a/README.md b/README.md index dc3b0a4..242d585 100644 --- a/README.md +++ b/README.md @@ -92,8 +92,9 @@ from it is logged too. Each of these will work best when your music library is well organised with Musicbrainz metadata. -Tracked playlists, recurring playlists and genre mixes can all be managed from the web UI (see -[Discover UI](#discover-ui)), under "Tracked playlists". The SQL below does the same by hand. +Tracked playlists and recurring playlists can be managed from the web UI (see +[Discover UI](#discover-ui)), under "Tracked playlists", and genre mixes are created there too. The +SQL below does the same by hand. ### Tracked playlist @@ -138,10 +139,19 @@ Mixes are rebuilt every `refresh_hours`. On a rebuild, existing mix playlists ar new cluster with the most similar genres (and renamed), new playlists are created for new clusters, and playlists for clusters that no longer appear are deleted. -Create a rule through the API (after logging in, see [Logging in](#logging-in)): +Create a rule from the web UI: the first time you open it, it asks for your Listenbrainz user and +how to build the mixes. To add mixes for another Listenbrainz user, use the + next to the current +one in the sidebar. Each Listenbrainz user can have one rule. + +To stop making a user's mixes, use the bin next to their name in the sidebar. This deletes the rule +with its mixes and suggestions (liked ones too), and, unless you untick it, the mixes' playlists in +Subsonic. (Mixes are regrouped on every rebuild, so there's no deleting a single mix: it would just +come back.) + +Or through the API (after logging in, see [Logging in](#logging-in)): ```sh -curl -b cookies -X POST localhost:8000/api/playlist/mix -H 'Content-Type: application/json' \ +curl -b cookies -X POST localhost:8000/api/discover/rules -H 'Content-Type: application/json' \ -d '{"tracking_user": "jellywx", "months": 3, "playlist_size": 50}' ``` @@ -172,8 +182,10 @@ your library yet. Each time the mixes are rebuilt, playlistd also looks for new songs for each mix: * your Listenbrainz recommendations, keeping only recordings you've never listened to, and -* if a Listenbrainz token is saved to your account (or `listenbrainz.token` is set), an LB Radio - playlist for each mix's top genres. +* if `listenbrainz.token` (or `LISTENBRAINZ_TOKEN`) is set to a Listenbrainz user token, an LB + Radio playlist for each mix's top genres. Find your token at + [listenbrainz.org/settings](https://listenbrainz.org/settings/). It's used for every mix, whichever + Listenbrainz user it's for. Every candidate's MusicBrainz genres are compared with each mix's, and it's suggested in the mix it fits best (if it fits well enough), skipping songs already in your library. @@ -214,10 +226,6 @@ will set it up again: DELETE FROM app_user; ``` -Under the account page in the UI (your username, in the sidebar), you can save your Listenbrainz -user token to your account. It's checked with Listenbrainz first, and is then used instead of -`listenbrainz.token` from the config. - To use the API from a script, log in with a cookie jar and pass it with each request: ```sh @@ -236,7 +244,6 @@ under `/api/auth`: | `POST /login` | Log in (`username`, `password`) | | `POST /logout` | Log out | | `GET /account` | The logged in account | -| `PUT /account/listenbrainz` | Save a Listenbrainz `token` to the account (empty removes it) | ### Endpoints @@ -245,6 +252,8 @@ The UI uses these endpoints under `/api/discover`: | Endpoint | Purpose | |--------------------------------|------------------------------------------------------| | `GET /rules` | Cluster mix rules | +| `POST /rules` | Create a cluster mix rule (`tracking_user`, plus any of the columns above) | +| `DELETE /rules/?delete_playlists=true` | Delete a rule, its mixes and suggestions, optionally deleting the playlists from Subsonic | | `GET /rules//mixes` | A rule's mixes | | `GET /mixes/` | A mix's library songs and new song suggestions | | `GET /rules//liked` | Liked suggestions | diff --git a/discover/src/AccountView.tsx b/discover/src/AccountView.tsx index 350a36c..5ae46d4 100644 --- a/discover/src/AccountView.tsx +++ b/discover/src/AccountView.tsx @@ -1,44 +1,12 @@ -import { FormEvent, useState } from "react"; +import { useState } from "react"; import { Account, authApi } from "./api"; -import * as Icon from "./icons"; -export function AccountView(props: { - account: Account; - onChange: (account: Account) => void; - onLogout: () => void; - onToast: (message: string) => void; -}) { +export function AccountView(props: { account: Account; onLogout: () => void }) { const { account } = props; - const [token, setToken] = useState(""); - const [busy, setBusy] = useState<"save" | "remove" | "logout" | null>(null); - const [error, setError] = useState(null); - - const saveToken = async (value: string) => { - setBusy(value ? "save" : "remove"); - setError(null); - try { - const updated = await authApi.setListenbrainzToken(value); - props.onChange(updated); - setToken(""); - props.onToast( - updated.listenbrainz_user - ? `Saved the token for ${updated.listenbrainz_user}` - : "Removed the Listenbrainz token", - ); - } catch (e) { - setError((e as Error).message); - } finally { - setBusy(null); - } - }; - - const submit = (e: FormEvent) => { - e.preventDefault(); - void saveToken(token.trim()); - }; + const [busy, setBusy] = useState(false); const logout = async () => { - setBusy("logout"); + setBusy(true); try { await authApi.logout(); } catch { @@ -54,73 +22,14 @@ export function AccountView(props: {

{account.username}

-
-
-
-

Listenbrainz token

-

- Lets playlistd find new songs for each mix's genres with LB Radio, on top of your - recommendations. Find yours at{" "} - - listenbrainz.org/settings - - . New songs are picked up the next time your mixes are rebuilt. -

-
-
- -

- {account.has_listenbrainz_token ? ( - <> -

- -
- - {error &&

{error}

} -
- {account.has_listenbrainz_token && ( - - )} - -
-
-
-

Session

Logged in as {account.username} in this browser.

-
diff --git a/discover/src/App.tsx b/discover/src/App.tsx index a359c48..9a75543 100644 --- a/discover/src/App.tsx +++ b/discover/src/App.tsx @@ -5,14 +5,16 @@ import { MixView, hue } from "./MixView"; import { LikedView } from "./LikedView"; import { TrackedView } from "./TrackedView"; import { AccountView } from "./AccountView"; +import { NewMixesView } from "./NewMixesView"; +import { DeleteMixesView } from "./DeleteMixesView"; import { PlayerBar } from "./PlayerBar"; import * as Icon from "./icons"; -type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" } | { view: "account" }; +type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" } | { view: "account" } | { view: "new-mixes" } | { view: "delete-mixes" }; function parseHash(): Route { const [, view, id] = window.location.hash.split("/"); - if (view === "liked" || view === "tracked" || view === "account") return { view }; + if (view === "liked" || view === "tracked" || view === "account" || view === "new-mixes" || view === "delete-mixes") return { view }; return { view: "mix", id: id || undefined }; } @@ -28,7 +30,6 @@ function storedRule() { export function App(props: { account: Account; - onAccountChange: (account: Account) => void; onLogout: () => void; }) { const [rules, setRules] = useState(null); @@ -140,6 +141,42 @@ export function App(props: { ); }; + const selectRule = (id: string) => { + setRuleId(id); + setMixes(null); + setLiked([]); + try { + localStorage.setItem("discover.rule", id); + } catch { + /* not essential */ + } + window.location.hash = ""; + }; + + const onRuleCreated = (created: Rule) => { + setRules((rs) => [...(rs ?? []), created]); + selectRule(created.id); + setToast({ message: `Building mixes for ${created.tracking_user}. This takes a minute or two.` }); + }; + + const onRuleDeleted = (deleted: Rule, playlistsDeleted: boolean) => { + const remaining = rules?.filter((r) => r.id !== deleted.id) ?? []; + setRules(remaining); + setDetail(null); + if (remaining.length) { + selectRule(remaining[0].id); + } else { + setMixes(null); + setLiked([]); + window.location.hash = ""; + } + setToast({ + message: playlistsDeleted + ? `Deleted the mixes for ${deleted.tracking_user}` + : `Deleted the mixes for ${deleted.tracking_user}. Their playlists stay in Subsonic.`, + }); + }; + const rebuild = () => { if (!rule) return; api.rebuild(rule.id).then(() => { @@ -160,16 +197,7 @@ export function App(props: { className="rule-select" value={rule?.id} aria-label="Listenbrainz user" - onChange={(e) => { - setRuleId(e.target.value); - setMixes(null); - try { - localStorage.setItem("discover.rule", e.target.value); - } catch { - /* not essential */ - } - window.location.hash = ""; - }} + onChange={(e) => selectRule(e.target.value)} > {rules.map((r) => )} @@ -177,9 +205,19 @@ export function App(props: { {rule && (

{rule.tracking_user} · last {rule.months} months - + + + + + + + + +

)}
    @@ -217,28 +255,35 @@ export function App(props: {
    {error &&
    {error}
    } - {(route.view === "mix" || route.view === "liked") && rules && rules.length === 0 && ( -
    -

    No mix rules yet

    -

    Create one, and playlistd will cluster your listens into genre mixes:

    -
    {`curl -c cookies -X POST ${location.origin}/api/auth/login -H 'Content-Type: application/json' \\\n  -d '{"username": "${props.account.username}", "password": "…"}'\ncurl -b cookies -X POST ${location.origin}/api/playlist/mix -H 'Content-Type: application/json' \\\n  -d '{"tracking_user": "your-listenbrainz-name"}'`}
    -
    - )} {(route.view === "mix" || route.view === "liked") && pending && mixes?.length === 0 && (
    Building mixes from your recent listens…
    )} - {route.view === "account" ? ( - setToast({ message })} + {route.view === "new-mixes" || ((route.view === "mix" || route.view === "liked") && rules?.length === 0) ? ( + (window.location.hash = "")} + onCreated={onRuleCreated} /> + ) : route.view === "delete-mixes" ? ( + rule && ( + (window.location.hash = "")} + onDeleted={onRuleDeleted} + /> + ) + ) : route.view === "account" ? ( + ) : route.view === "tracked" ? ( setToast({ message })} /> ) : route.view === "liked" ? ( - ) : detail ? ( + ) : detail && detail.id === mixId ? ( ) : ( mixId &&
    Loading…
    diff --git a/discover/src/Auth.tsx b/discover/src/Auth.tsx index 2adcbae..cc7add3 100644 --- a/discover/src/Auth.tsx +++ b/discover/src/Auth.tsx @@ -64,7 +64,6 @@ export function AuthGate() { return ( setState({ kind: "ready", account })} onLogout={() => setState({ kind: "login" })} /> ); diff --git a/discover/src/DeleteMixesView.tsx b/discover/src/DeleteMixesView.tsx new file mode 100644 index 0000000..e18b54e --- /dev/null +++ b/discover/src/DeleteMixesView.tsx @@ -0,0 +1,92 @@ +import { useState } from "react"; +import { api, MixSummary, mixTitle, Rule } from "./api"; +import * as Icon from "./icons"; + +/** Confirm deleting a cluster mix rule, and with it all of its mixes */ +export function DeleteMixesView(props: { + rule: Rule; + mixes: MixSummary[] | null; + likedCount: number; + onCancel: () => void; + onDeleted: (rule: Rule, playlistsDeleted: boolean) => void; +}) { + const { rule, mixes } = props; + const [deletePlaylists, setDeletePlaylists] = useState(true); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const remove = async () => { + setBusy(true); + setError(null); + try { + await api.deleteRule(rule.id, deletePlaylists); + props.onDeleted(rule, deletePlaylists); + } catch (e) { + setError((e as Error).message); + setBusy(false); + } + }; + + const count = mixes?.length ?? 0; + const playlists = count === 1 ? "playlist" : `${count} playlists`; + + return ( +
    +
    +

    Discover

    +

    Delete mixes for {rule.tracking_user}?

    +

    + playlistd stops building genre mixes for {rule.tracking_user}. You can set them up again later, but + they'll start from scratch. +

    +
    + +
    +
    +
    +

    Mixes

    +

    + {mixes === null + ? "Loading…" + : count === 0 + ? "No mixes have been built yet." + : `${count} ${count === 1 ? "mix" : "mixes"}, each a playlist in Subsonic.`} +

    +
    +
    + + {count > 0 && ( +
      + {mixes!.map((m) =>
    • {m.name ?? mixTitle(m)}
    • )} +
    + )} + +
    + {count > 0 && ( + + )} + {count > 0 && !deletePlaylists && ( +

    The {playlists} stay in Subsonic as they are now, and won't be updated.

    + )} + {props.likedCount > 0 && ( +

    + Your {props.likedCount} liked new{" "} + {props.likedCount === 1 ? "song is" : "songs are"} deleted too, along with the rest of the + suggestions. +

    + )} + {error &&

    {error}

    } +
    + + +
    +
    +
    +
    + ); +} diff --git a/discover/src/NewMixesView.tsx b/discover/src/NewMixesView.tsx new file mode 100644 index 0000000..a783a64 --- /dev/null +++ b/discover/src/NewMixesView.tsx @@ -0,0 +1,202 @@ +import { FormEvent, useState } from "react"; +import { api, NewRule, Rule } from "./api"; +import * as Icon from "./icons"; + +const HISTORY: [number, string][] = [ + [1, "Last month"], + [3, "Last 3 months"], + [6, "Last 6 months"], + [12, "Last year"], +]; + +const REFRESH: [number, string][] = [ + [6, "Every 6 hours"], + [12, "Every 12 hours"], + [24, "Every day"], + [72, "Every 3 days"], + [168, "Every week"], +]; + +/** Create a cluster mix rule: genre mixes for a Listenbrainz user */ +export function NewMixesView(props: { + /** No rules exist yet, so this is the first thing the user sees */ + first: boolean; + onCancel: () => void; + onCreated: (rule: Rule) => void; +}) { + const [rule, setRule] = useState({ + tracking_user: "", + months: 3, + playlist_size: 50, + cluster_count: null, + familiar_ratio: 0.3, + discovery_count: 15, + name_template: "Mix: {label}", + refresh_hours: 24, + }); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const set = (change: Partial) => setRule((r) => ({ ...r, ...change })); + + const templateError = rule.name_template.includes("{label}") + ? null + : "Include {label}, so each mix gets its own name"; + + const submit = async (e: FormEvent) => { + e.preventDefault(); + setBusy(true); + setError(null); + try { + props.onCreated(await api.createRule({ ...rule, tracking_user: rule.tracking_user.trim() })); + } catch (err) { + setError((err as Error).message); + setBusy(false); + } + }; + + return ( +
    +
    +

    Discover

    +

    {props.first ? "Set up your mixes" : "New mixes"}

    +

    + playlistd groups what you've listened to recently by genre, and keeps a Subsonic playlist for + each group: songs you love, songs from your library you haven't played lately, and new songs + to try. +

    +
    + +
    +
    +
    +

    Mixes

    +

    The first build takes a minute or two. After that, mixes are rebuilt on a schedule.

    +
    +
    + +
    +
    + + + + + +
    + + set({ familiar_ratio: Number(e.target.value) })} + aria-describedby="familiar-help" + /> +
    + +
    + +
      +
    • Songs per mix, from your library.
    • +
    • Songs you know: the share of each mix taken from what you've played recently. The rest are songs from your library in the same genres.
    • +
    • New songs not in your library to suggest for each mix, to listen to here.
    • +
    + +
    + More options +
    +
    + + set({ name_template: e.target.value })} + spellCheck={false} + aria-describedby="mix-template-help" + aria-invalid={!!templateError} + /> + + {templateError ? ( + {templateError} + ) : ( + <> + {"{label}"} becomes the mix's top genres, e.g.{" "} + {rule.name_template.replace("{label}", "Shoegaze / Dream Pop")} + + )} + +
    + +
    +
    + + {error &&

    {error}

    } +
    + {!props.first && } + +
    +
    +
    +
    + ); +} diff --git a/discover/src/api.ts b/discover/src/api.ts index d7cc81c..3b4d93e 100644 --- a/discover/src/api.ts +++ b/discover/src/api.ts @@ -2,13 +2,20 @@ export type Rule = { id: string; tracking_user: string; months: number; + /** null: chosen automatically */ + cluster_count: number | null; playlist_size: number; discovery_count: number; /** Share of a mix made of songs the user already knows */ familiar_ratio: number; + /** `{label}` becomes the mix's top genres */ + name_template: string; + refresh_hours: number; last_run: string | null; }; +export type NewRule = Omit; + export type MixSummary = { id: string; playlist_id: string; @@ -75,6 +82,10 @@ const json = (method: string, body: unknown): RequestInit => ({ export const api = { rules: () => request("/rules"), + createRule: (rule: NewRule) => request("/rules", json("POST", rule)), + /** Deletes the rule's mixes and suggestions, and optionally their playlists in Subsonic */ + deleteRule: (id: string, deletePlaylists: boolean) => + request(`/rules/${id}?delete_playlists=${deletePlaylists}`, { method: "DELETE" }), mixes: (ruleId: string) => request(`/rules/${ruleId}/mixes`), mix: (mixId: string) => request(`/mixes/${mixId}`), liked: (ruleId: string) => request(`/rules/${ruleId}/liked`), @@ -161,9 +172,6 @@ export const trackedApi = { export type Account = { username: string; - /** The Listenbrainz user the saved token belongs to */ - listenbrainz_user: string | null; - has_listenbrainz_token: boolean; }; export type AuthStatus = { @@ -179,6 +187,4 @@ export const authApi = { setup: (username: string, password: string) => auth("/setup", json("POST", { username, password })), login: (username: string, password: string) => auth("/login", json("POST", { username, password })), logout: () => auth("/logout", { method: "POST" }), - /** An empty token removes the saved one */ - setListenbrainzToken: (token: string) => auth("/account/listenbrainz", json("PUT", { token })), }; diff --git a/discover/src/styles.css b/discover/src/styles.css index c45c47f..9689bfa 100644 --- a/discover/src/styles.css +++ b/discover/src/styles.css @@ -136,6 +136,11 @@ a { font-size: 0.85rem; } +.rule-actions { + display: flex; + gap: 2px; +} + .mix-list { list-style: none; margin: 0; @@ -1005,6 +1010,69 @@ h2 { color: var(--accent-text); } +.field output { + margin-left: 4px; + color: var(--muted); + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.field input[type="range"] { + min-height: 38px; + padding: 0; + border: 0; + background: none; + accent-color: var(--accent); +} + +.field input[aria-invalid="true"] { + border-color: var(--youtube); +} + +.field-help { + display: grid; + gap: 3px; + margin: -2px 0 0; + padding: 0; + list-style: none; +} + +.advanced summary { + width: fit-content; + color: var(--muted); + font-size: 0.88rem; + font-weight: 600; + cursor: pointer; +} + +.advanced[open] summary { + margin-bottom: 12px; +} + +.advanced .form-grid { + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1.2fr); +} + +.delete-list { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0 0 14px; + padding: 0; + list-style: none; +} + +.delete-list li { + padding: 3px 10px; + border: 1px solid var(--border); + border-radius: 999px; + font-size: 0.85rem; +} + +.confirm .hint svg { + vertical-align: -2px; +} + /* ---------- login & account ---------- */ .auth-page { @@ -1053,26 +1121,6 @@ h2 { color: var(--muted); } -.token-status { - display: flex; - align-items: center; - gap: 8px; - margin: 0 0 4px; - font-size: 0.92rem; -} - -.status-dot { - flex: none; - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--muted); -} - -.status-dot.ok { - background: var(--library); -} - .hint a { color: var(--accent); } diff --git a/etc/playlistd/playlistd.toml b/etc/playlistd/playlistd.toml index cf4a0b3..2a2b6a3 100644 --- a/etc/playlistd/playlistd.toml +++ b/etc/playlistd/playlistd.toml @@ -22,7 +22,7 @@ url = "postgres:///navidrome-playlists" [listenbrainz] # Your Listenbrainz user token (listenbrainz.org/settings). Optional: lets the discover UI # find new songs for each mix's genres with LB Radio, on top of your recommendations. -# A token saved to your account in the web UI takes priority over this one +# Used for every mix, whichever Listenbrainz user it's for # token = "" [discover] diff --git a/migrations/20261122120000_drop_account_listenbrainz_token.sql b/migrations/20261122120000_drop_account_listenbrainz_token.sql new file mode 100644 index 0000000..bdab3a3 --- /dev/null +++ b/migrations/20261122120000_drop_account_listenbrainz_token.sql @@ -0,0 +1,4 @@ +-- The Listenbrainz token now only comes from the config (`listenbrainz.token`) +ALTER TABLE "app_user" + DROP COLUMN listenbrainz_token, + DROP COLUMN listenbrainz_user; diff --git a/src/auth.rs b/src/auth.rs index 0599a30..5cdf2c0 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -4,7 +4,6 @@ //! request needs a session cookie from logging in. Passwords are hashed with Argon2id, and only a //! SHA-256 hash of each session token is stored, so the database alone can't be used to log in. -use crate::listenbrainz; use argon2::password_hash::{ rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString, }; @@ -14,7 +13,7 @@ use rocket::http::{Cookie, CookieJar, SameSite, Status}; use rocket::request::{FromRequest, Outcome}; use rocket::response::status::Custom; use rocket::serde::json::Json; -use rocket::{catch, get, post, put, routes, Request, Route, State}; +use rocket::{catch, get, post, routes, Request, Route, State}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use sqlx::postgres::PgPool; @@ -27,14 +26,7 @@ const MIN_PASSWORD: usize = 8; const MAX_USERNAME: usize = 64; pub fn routes() -> Vec { - routes![ - status, - setup, - login, - logout, - account, - set_listenbrainz_token - ] + routes![status, setup, login, logout, account] } #[derive(Serialize)] @@ -185,18 +177,12 @@ async fn start_session( #[derive(Serialize)] struct Account { username: String, - /// The Listenbrainz user the saved token belongs to. The token itself is never sent back. - listenbrainz_user: Option, - has_listenbrainz_token: bool, } async fn load_account(pool: &PgPool, id: Uuid) -> Result>> { sqlx::query_as!( Account, - r#" - SELECT username, listenbrainz_user, listenbrainz_token IS NOT NULL AS "has_listenbrainz_token!" - FROM "app_user" WHERE id = $1 - "#, + r#"SELECT username FROM "app_user" WHERE id = $1"#, id ) .fetch_one(pool) @@ -343,54 +329,3 @@ async fn logout( async fn account(pool: &State, user: User) -> ApiResult { load_account(pool.inner(), user.id).await.map(Json) } - -#[derive(Deserialize)] -struct ListenbrainzToken { - /// Empty or missing removes the saved token - token: Option, -} - -/// Save a Listenbrainz user token to the account, after checking it with Listenbrainz -#[put("/account/listenbrainz", data = "")] -async fn set_listenbrainz_token( - pool: &State, - user: User, - body: Json, -) -> ApiResult { - let token = body - .token - .as_deref() - .map(str::trim) - .filter(|t| !t.is_empty()); - - let listenbrainz_user = match token { - Some(token) => match listenbrainz::validate_token(token).await { - Ok(Some(name)) => Some(name), - Ok(None) => { - return Err(error( - Status::UnprocessableEntity, - "Listenbrainz says that token isn't valid", - )) - } - Err(e) => { - log::warn!("Could not check Listenbrainz token: {}", e); - return Err(error( - Status::BadGateway, - "Couldn't reach Listenbrainz to check the token", - )); - } - }, - None => None, - }; - - sqlx::query!( - r#"UPDATE "app_user" SET listenbrainz_token = $1, listenbrainz_user = $2 WHERE id = $3"#, - token, - listenbrainz_user, - user.id - ) - .execute(pool.inner()) - .await - .map_err(db_error)?; - load_account(pool.inner(), user.id).await.map(Json) -} diff --git a/src/daemon/cluster_mixes.rs b/src/daemon/cluster_mixes.rs index cd3cf45..140d880 100644 --- a/src/daemon/cluster_mixes.rs +++ b/src/daemon/cluster_mixes.rs @@ -318,7 +318,7 @@ async fn save_suggestions( recently_played, &exclude, rule.discovery_count.max(0) as usize, - listenbrainz::token(database).await, + listenbrainz::token(), ) .await?; diff --git a/src/discover.rs b/src/discover.rs index 0eb03a5..7a08ac6 100644 --- a/src/discover.rs +++ b/src/discover.rs @@ -1,8 +1,8 @@ //! Find songs that aren't in the library to suggest alongside each mix. //! //! Candidates come from Listenbrainz's collaborative filtering recommendations -//! for the user (filtered to recordings they've never listened to) and, if a -//! Listenbrainz token is saved to the account (or configured), an LB Radio prompt built from each mix's +//! for the user (filtered to recordings they've never listened to) and, if +//! `listenbrainz.token` is configured, an LB Radio prompt built from each mix's //! top genres. Every candidate's MusicBrainz genres are compared with each //! mix's genre profile (cosine similarity) and it's assigned to the mix it fits //! best. Songs already in the library, or played recently, are skipped. diff --git a/src/listenbrainz.rs b/src/listenbrainz.rs index 6325456..0c679db 100644 --- a/src/listenbrainz.rs +++ b/src/listenbrainz.rs @@ -471,24 +471,8 @@ pub async fn recommendations( .mbids) } -/// The user token needed by some endpoints (e.g. LB Radio): the one saved to the account in the -/// web UI, or otherwise `listenbrainz.token` from the config -pub async fn token(database: &sqlx::PgPool) -> Option { - match sqlx::query_scalar!( - r#" - SELECT listenbrainz_token AS "token!" FROM "app_user" - WHERE listenbrainz_token IS NOT NULL - ORDER BY created_at - LIMIT 1 - "# - ) - .fetch_optional(database) - .await - { - Ok(Some(token)) => return Some(token), - Ok(None) => {} - Err(e) => log::warn!("Could not load the account's Listenbrainz token: {}", e), - } +/// The user token needed by some endpoints (e.g. LB Radio): `listenbrainz.token` from the config +pub fn token() -> Option { crate::CONFIG .get()? .get::("listenbrainz.token") @@ -496,21 +480,6 @@ pub async fn token(database: &sqlx::PgPool) -> Option { .filter(|t| !t.is_empty()) } -#[derive(Deserialize)] -struct ValidateTokenResponse { - valid: bool, - user_name: Option, -} - -/// The name of the Listenbrainz user a token belongs to, or `None` if it isn't valid -pub async fn validate_token(token: &str) -> Result, reqwest::Error> { - let request = reqwest::Client::new() - .get(format!("{}/validate-token", BASE)) - .header(reqwest::header::AUTHORIZATION, format!("Token {}", token)); - let response = send_json::(request).await?; - Ok(response.user_name.filter(|_| response.valid)) -} - #[derive(Deserialize)] struct RadioResponse { payload: RadioPayload, diff --git a/src/tracked.rs b/src/tracked.rs index 8993a6a..f779d1e 100644 --- a/src/tracked.rs +++ b/src/tracked.rs @@ -41,7 +41,7 @@ pub struct ApiError { type ApiResult = Result, Custom>>; -fn fail(status: Status, message: impl Into) -> Custom> { +pub(crate) fn fail(status: Status, message: impl Into) -> Custom> { Custom( status, Json(ApiError { diff --git a/src/web.rs b/src/web.rs index dcd8f2a..3e486f8 100644 --- a/src/web.rs +++ b/src/web.rs @@ -2,16 +2,18 @@ //! from Subsonic or YouTube. use crate::auth::User; -use crate::models::{ClusterMixRule, MixSuggestion}; +use crate::models::{ClusterMixRule, MixSuggestion, PartialClusterMixRule}; use crate::subsonic::Subsonic; use crate::track::Track; +use crate::tracked::{fail, ApiError}; use crate::youtube::YouTube; use futures_util::TryStreamExt; use rocket::http::Status; use rocket::request::{FromRequest, Outcome}; +use rocket::response::status::Custom; use rocket::response::{self, Responder}; use rocket::serde::json::Json; -use rocket::{get, post, put, routes, Request, Response, Route, State}; +use rocket::{delete, get, post, put, routes, Request, Response, Route, State}; use serde::{Deserialize, Serialize}; use sqlx::postgres::PgPool; use std::convert::Infallible; @@ -20,7 +22,19 @@ use tokio_util::io::StreamReader; use uuid::Uuid; pub fn routes() -> Vec { - routes![rules, mixes, mix, liked, set_status, rebuild, stream, cover, youtube] + routes![ + rules, + create_rule, + delete_rule, + mixes, + mix, + liked, + set_status, + rebuild, + stream, + cover, + youtube + ] } type ApiResult = Result, Status>; @@ -47,6 +61,135 @@ async fn rules(_user: User, pool: &State) -> ApiResult Result<(), Custom>> { + let invalid = |message: &str| Err(fail(Status::UnprocessableEntity, message)); + let out_of = |value: Option, range: std::ops::RangeInclusive| { + value.is_some_and(|v| !range.contains(&v)) + }; + + if rule.tracking_user.trim().is_empty() { + return invalid("Enter a Listenbrainz user"); + } + if out_of(rule.months, 1..=24) { + return invalid("Cluster between 1 and 24 months of listens"); + } + if out_of(rule.cluster_count, 1..=20) { + return invalid("Make between 1 and 20 mixes, or choose them automatically"); + } + if out_of(rule.playlist_size, 1..=500) { + return invalid("Mixes can have between 1 and 500 songs"); + } + if rule + .familiar_ratio + .is_some_and(|r| !(0.0..=1.0).contains(&r)) + { + return invalid("The share of songs you know must be between 0% and 100%"); + } + if out_of(rule.discovery_count, 0..=100) { + return invalid("Suggest between 0 and 100 new songs per mix"); + } + if out_of(rule.refresh_hours, 1..=24 * 30) { + return invalid("Rebuild the mixes between every hour and every 30 days"); + } + if let Some(template) = &rule.name_template { + if !template.contains("{label}") { + return invalid("The name needs {label}, so each mix gets its own name"); + } + } + Ok(()) +} + +/// Create a mix rule. Its mixes are built on the next daemon tick. +#[post("/rules", data = "")] +async fn create_rule( + _user: User, + rule: Json, + pool: &State, +) -> Result, Custom>> { + let database_error = |e: sqlx::Error| { + log::error!("Database error: {}", e); + fail(Status::InternalServerError, "Database error") + }; + + let mut rule = rule.into_inner(); + rule.tracking_user = rule.tracking_user.trim().to_string(); + rule.name_template = rule + .name_template + .map(|t| t.trim().to_string()) + .filter(|t| !t.is_empty()); + validate_rule(&rule)?; + + // the UI picks mixes by Listenbrainz user, so one rule each + let existing = ClusterMixRule::all(pool.inner()) + .await + .map_err(database_error)?; + if existing + .iter() + .any(|r| r.tracking_user.eq_ignore_ascii_case(&rule.tracking_user)) + { + return Err(fail( + Status::Conflict, + format!("There are already mixes for {}", rule.tracking_user), + )); + } + + let created = rule.record(pool.inner()).await.map_err(database_error)?; + log::info!( + "Created mix rule {} for {}", + created.id, + created.tracking_user + ); + Ok(Json(created)) +} + +/// Delete a mix rule along with its mixes and suggestions (liked ones too), optionally deleting +/// the mixes' playlists from Subsonic as well +#[delete("/rules/?")] +async fn delete_rule( + _user: User, + id: &str, + delete_playlists: Option, + pool: &State, + media_client: &State>, +) -> Result>> { + let database_error = |e: sqlx::Error| { + log::error!("Database error: {}", e); + fail(Status::InternalServerError, "Database error") + }; + let id = parse_id(id).map_err(|_| fail(Status::NotFound, "Not found"))?; + + let mut transaction = pool.begin().await.map_err(database_error)?; + // the rule's playlists go with it (ON DELETE CASCADE), so note them first + let playlist_ids = sqlx::query_scalar!( + r#"SELECT playlist_id FROM "cluster_mix_playlist" WHERE rule_id = $1"#, + id + ) + .fetch_all(&mut *transaction) + .await + .map_err(database_error)?; + let tracking_user = sqlx::query_scalar!( + r#"DELETE FROM "cluster_mix_rule" WHERE id = $1 RETURNING tracking_user"#, + id + ) + .fetch_optional(&mut *transaction) + .await + .map_err(database_error)? + .ok_or_else(|| fail(Status::NotFound, "Not found"))?; + transaction.commit().await.map_err(database_error)?; + + log::info!("Deleted mix rule {} for {}", id, tracking_user); + if delete_playlists.unwrap_or(false) { + for playlist_id in playlist_ids { + // it may already be gone from Subsonic + if let Err(e) = media_client.delete_playlist(&playlist_id).await { + log::warn!("Could not delete playlist {}: {}", playlist_id, e); + } + } + } + Ok(Status::NoContent) +} + #[derive(Serialize)] struct MixSummary { id: Uuid,