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/<id>?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 <noreply@anthropic.com>
This commit is contained in:
judeandClaude Opus 5.5 committed 2026-11-22 09:45:52 +00:00
1 parent f5cb5076ca
commit 93e12cfc72
23 files changed
+701 -344

No files matched your search

+1 -1
View File
@@ -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
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
+20 -11
View File
@@ -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/<id>?delete_playlists=true` | Delete a rule, its mixes and suggestions, optionally deleting the playlists from Subsonic |
| `GET /rules/<id>/mixes` | A rule's mixes |
| `GET /mixes/<id>` | A mix's library songs and new song suggestions |
| `GET /rules/<id>/liked` | Liked suggestions |
+6 -97
View File
@@ -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<string | null>(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: {
<h1>{account.username}</h1>
</header>
<section className="panel" aria-labelledby="lb-heading">
<div className="panel-header">
<div>
<h2 id="lb-heading">Listenbrainz token</h2>
<p className="hint">
Lets playlistd find new songs for each mix's genres with LB Radio, on top of your
recommendations. Find yours at{" "}
<a href="https://listenbrainz.org/settings/" target="_blank" rel="noreferrer">
listenbrainz.org/settings <Icon.External size={12} />
</a>
. New songs are picked up the next time your mixes are rebuilt.
</p>
</div>
</div>
<p className="token-status">
{account.has_listenbrainz_token ? (
<>
<span className="status-dot ok" aria-hidden="true" />
Saved, for Listenbrainz user <strong>{account.listenbrainz_user}</strong>
</>
) : (
<>
<span className="status-dot" aria-hidden="true" />
No token saved
</>
)}
</p>
<form className="form" onSubmit={submit} aria-label="Listenbrainz token">
<label className="field">
<span>{account.has_listenbrainz_token ? "Replace token" : "Token"}</span>
<input
className="mono"
type="password"
required
value={token}
onChange={(e) => setToken(e.target.value)}
autoComplete="off"
spellCheck={false}
placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
/>
</label>
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
{account.has_listenbrainz_token && (
<button type="button" className="btn" disabled={!!busy} onClick={() => saveToken("")}>
{busy === "remove" && <span className="spinner" />}
Remove token
</button>
)}
<button type="submit" className="btn primary" disabled={!!busy || !token.trim()}>
{busy === "save" && <span className="spinner light" />}
{busy === "save" ? "Checking…" : "Save token"}
</button>
</div>
</form>
</section>
<section className="panel" aria-labelledby="session-heading">
<div className="panel-header">
<div>
<h2 id="session-heading">Session</h2>
<p className="hint">Logged in as {account.username} in this browser.</p>
</div>
<button className="btn" onClick={logout} disabled={!!busy}>
{busy === "logout" && <span className="spinner" />}
<button className="btn" onClick={logout} disabled={busy}>
{busy && <span className="spinner" />}
Log out
</button>
</div>
+75 -30
View File
@@ -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<Rule[] | null>(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) => <option key={r.id} value={r.id}>{r.tracking_user}</option>)}
</select>
@@ -177,9 +205,19 @@ export function App(props: {
{rule && (
<p className="rule-info">
{rule.tracking_user} · last {rule.months} months
<button className="icon-button small" onClick={rebuild} title="Rebuild mixes" aria-label="Rebuild mixes">
<Icon.Refresh size={15} />
</button>
<span className="rule-actions">
<button className="icon-button small" onClick={rebuild} title="Rebuild mixes" aria-label="Rebuild mixes">
<Icon.Refresh size={15} />
</button>
<a href="#/new-mixes" className="icon-button small" title="Mixes for another Listenbrainz user"
aria-label="New mixes for another Listenbrainz user">
<Icon.Plus size={15} />
</a>
<a href="#/delete-mixes" className="icon-button small" title={`Delete the mixes for ${rule.tracking_user}`}
aria-label={`Delete the mixes for ${rule.tracking_user}`}>
<Icon.Trash size={15} />
</a>
</span>
</p>
)}
<ul className="mix-list">
@@ -217,28 +255,35 @@ export function App(props: {
<main className="content">
{error && <div className="notice error">{error}</div>}
{(route.view === "mix" || route.view === "liked") && rules && rules.length === 0 && (
<div className="notice">
<h1>No mix rules yet</h1>
<p>Create one, and playlistd will cluster your listens into genre mixes:</p>
<pre>{`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"}'`}</pre>
</div>
)}
{(route.view === "mix" || route.view === "liked") && pending && mixes?.length === 0 && (
<div className="notice"><span className="spinner" /> Building mixes from your recent listens…</div>
)}
{route.view === "account" ? (
<AccountView
account={props.account}
onChange={props.onAccountChange}
onLogout={props.onLogout}
onToast={(message) => setToast({ message })}
{route.view === "new-mixes" || ((route.view === "mix" || route.view === "liked") && rules?.length === 0) ? (
<NewMixesView
// remount when switching between the first-run and "another user" forms
key={rules?.length ? "another" : "first"}
first={rules?.length === 0}
onCancel={() => (window.location.hash = "")}
onCreated={onRuleCreated}
/>
) : route.view === "delete-mixes" ? (
rule && (
<DeleteMixesView
key={rule.id}
rule={rule}
mixes={mixes}
likedCount={liked.length}
onCancel={() => (window.location.hash = "")}
onDeleted={onRuleDeleted}
/>
)
) : route.view === "account" ? (
<AccountView account={props.account} onLogout={props.onLogout} />
) : route.view === "tracked" ? (
<TrackedView defaultUser={rule?.tracking_user} onToast={(message) => setToast({ message })} />
) : route.view === "liked" ? (
<LikedView liked={liked} player={player} onStatus={onStatus} />
) : detail ? (
) : detail && detail.id === mixId ? (
<MixView mix={detail} knownRatio={rule?.familiar_ratio ?? 0.3} player={player} onStatus={onStatus} />
) : (
mixId && <div className="notice"><span className="spinner" /> Loading…</div>
-1
View File
@@ -64,7 +64,6 @@ export function AuthGate() {
return (
<App
account={state.account}
onAccountChange={(account) => setState({ kind: "ready", account })}
onLogout={() => setState({ kind: "login" })}
/>
);
+92
View File
@@ -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<string | null>(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 (
<article className="manage">
<header className="manage-header">
<p className="eyebrow">Discover</p>
<h1>Delete mixes for {rule.tracking_user}?</h1>
<p className="mix-counts">
playlistd stops building genre mixes for {rule.tracking_user}. You can set them up again later, but
they'll start from scratch.
</p>
</header>
<section className="panel" aria-labelledby="delete-mixes-heading">
<div className="panel-header">
<div>
<h2 id="delete-mixes-heading"><Icon.Trash size={17} /> Mixes</h2>
<p className="hint">
{mixes === null
? "Loading…"
: count === 0
? "No mixes have been built yet."
: `${count} ${count === 1 ? "mix" : "mixes"}, each a playlist in Subsonic.`}
</p>
</div>
</div>
{count > 0 && (
<ul className="delete-list">
{mixes!.map((m) => <li key={m.id}>{m.name ?? mixTitle(m)}</li>)}
</ul>
)}
<div className="confirm" role="alertdialog" aria-labelledby="delete-mixes-heading">
{count > 0 && (
<label className="checkbox">
<input type="checkbox" checked={deletePlaylists} onChange={(e) => setDeletePlaylists(e.target.checked)} />
Also delete the {playlists} from Subsonic
</label>
)}
{count > 0 && !deletePlaylists && (
<p className="hint">The {playlists} stay in Subsonic as they are now, and won't be updated.</p>
)}
{props.likedCount > 0 && (
<p className="hint">
<Icon.Warning size={13} /> Your {props.likedCount} liked new{" "}
{props.likedCount === 1 ? "song is" : "songs are"} deleted too, along with the rest of the
suggestions.
</p>
)}
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
<button className="btn" onClick={props.onCancel} autoFocus>Cancel</button>
<button className="btn danger" onClick={remove} disabled={busy || mixes === null}>
{busy ? <span className="spinner light" /> : <Icon.Trash size={15} />} Delete mixes
</button>
</div>
</div>
</section>
</article>
);
}
+202
View File
@@ -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<NewRule>({
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<string | null>(null);
const set = (change: Partial<NewRule>) => 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 (
<article className="manage">
<header className="manage-header">
<p className="eyebrow">Discover</p>
<h1>{props.first ? "Set up your mixes" : "New mixes"}</h1>
<p className="mix-counts">
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.
</p>
</header>
<section className="panel" aria-labelledby="new-mixes-heading">
<div className="panel-header">
<div>
<h2 id="new-mixes-heading"><Icon.Sparkle size={17} /> Mixes</h2>
<p className="hint">The first build takes a minute or two. After that, mixes are rebuilt on a schedule.</p>
</div>
</div>
<form className="form" onSubmit={submit} aria-label="New mixes">
<div className="form-grid">
<label className="field">
<span>Listenbrainz user</span>
<input
required
value={rule.tracking_user}
onChange={(e) => set({ tracking_user: e.target.value })}
autoComplete="off"
spellCheck={false}
autoFocus
/>
</label>
<label className="field">
<span>Listens from</span>
<select value={rule.months} onChange={(e) => set({ months: Number(e.target.value) })}>
{HISTORY.map(([v, label]) => <option key={v} value={v}>{label}</option>)}
</select>
</label>
<label className="field narrow">
<span>Songs</span>
<input
type="number"
required
min={1}
max={500}
value={rule.playlist_size}
onChange={(e) => set({ playlist_size: Number(e.target.value) })}
aria-describedby="songs-help"
/>
</label>
<label className="field">
<span>Number of mixes</span>
<select
value={rule.cluster_count ?? ""}
onChange={(e) => set({ cluster_count: e.target.value ? Number(e.target.value) : null })}
>
<option value="">Automatic</option>
{Array.from({ length: 11 }, (_, i) => i + 2).map((n) => (
<option key={n} value={n}>{n}</option>
))}
</select>
</label>
<div className="field">
<label htmlFor="familiar-ratio">
Songs you know <output htmlFor="familiar-ratio">{Math.round(rule.familiar_ratio * 100)}%</output>
</label>
<input
id="familiar-ratio"
type="range"
min={0}
max={1}
step={0.05}
value={rule.familiar_ratio}
onChange={(e) => set({ familiar_ratio: Number(e.target.value) })}
aria-describedby="familiar-help"
/>
</div>
<label className="field narrow">
<span>New songs</span>
<input
type="number"
required
min={0}
max={100}
value={rule.discovery_count}
onChange={(e) => set({ discovery_count: Number(e.target.value) })}
aria-describedby="new-help"
/>
</label>
</div>
<ul className="field-help hint">
<li id="songs-help"><strong>Songs</strong> per mix, from your library.</li>
<li id="familiar-help"><strong>Songs you know</strong>: the share of each mix taken from what you've played recently. The rest are songs from your library in the same genres.</li>
<li id="new-help"><strong>New songs</strong> not in your library to suggest for each mix, to listen to here.</li>
</ul>
<details className="advanced">
<summary>More options</summary>
<div className="form-grid">
<div className="field">
<label htmlFor="mix-template">Playlist name</label>
<input
id="mix-template"
className="mono"
required
value={rule.name_template}
onChange={(e) => set({ name_template: e.target.value })}
spellCheck={false}
aria-describedby="mix-template-help"
aria-invalid={!!templateError}
/>
<small className="hint" id="mix-template-help" aria-live="polite">
{templateError ? (
<span className="warning-text">{templateError}</span>
) : (
<>
<code>{"{label}"}</code> becomes the mix's top genres, e.g.{" "}
<strong>{rule.name_template.replace("{label}", "Shoegaze / Dream Pop")}</strong>
</>
)}
</small>
</div>
<label className="field">
<span>Rebuild</span>
<select value={rule.refresh_hours} onChange={(e) => set({ refresh_hours: Number(e.target.value) })}>
{REFRESH.map(([v, label]) => <option key={v} value={v}>{label}</option>)}
</select>
</label>
</div>
</details>
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
{!props.first && <button type="button" className="btn" onClick={props.onCancel}>Cancel</button>}
<button type="submit" className="btn primary" disabled={busy || !!templateError}>
{busy ? <span className="spinner light" /> : <Icon.Plus size={16} />} Create mixes
</button>
</div>
</form>
</section>
</article>
);
}
+11 -5
View File
@@ -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<Rule, "id" | "last_run">;
export type MixSummary = {
id: string;
playlist_id: string;
@@ -75,6 +82,10 @@ const json = (method: string, body: unknown): RequestInit => ({
export const api = {
rules: () => request<Rule[]>("/rules"),
createRule: (rule: NewRule) => request<Rule>("/rules", json("POST", rule)),
/** Deletes the rule's mixes and suggestions, and optionally their playlists in Subsonic */
deleteRule: (id: string, deletePlaylists: boolean) =>
request<void>(`/rules/${id}?delete_playlists=${deletePlaylists}`, { method: "DELETE" }),
mixes: (ruleId: string) => request<MixSummary[]>(`/rules/${ruleId}/mixes`),
mix: (mixId: string) => request<MixDetail>(`/mixes/${mixId}`),
liked: (ruleId: string) => request<Suggestion[]>(`/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<Account>("/setup", json("POST", { username, password })),
login: (username: string, password: string) => auth<Account>("/login", json("POST", { username, password })),
logout: () => auth<void>("/logout", { method: "POST" }),
/** An empty token removes the saved one */
setListenbrainzToken: (token: string) => auth<Account>("/account/listenbrainz", json("PUT", { token })),
};
+68 -20
View File
@@ -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);
}
+1 -1
View File
@@ -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]
@@ -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;
+3 -68
View File
@@ -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<Route> {
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<String>,
has_listenbrainz_token: bool,
}
async fn load_account(pool: &PgPool, id: Uuid) -> Result<Account, Custom<Json<ApiError>>> {
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<PgPool>, user: User) -> ApiResult<Account> {
load_account(pool.inner(), user.id).await.map(Json)
}
#[derive(Deserialize)]
struct ListenbrainzToken {
/// Empty or missing removes the saved token
token: Option<String>,
}
/// Save a Listenbrainz user token to the account, after checking it with Listenbrainz
#[put("/account/listenbrainz", data = "<body>")]
async fn set_listenbrainz_token(
pool: &State<PgPool>,
user: User,
body: Json<ListenbrainzToken>,
) -> ApiResult<Account> {
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)
}
+1 -1
View File
@@ -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?;
+2 -2
View File
@@ -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.
+2 -33
View File
@@ -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<String> {
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<String> {
crate::CONFIG
.get()?
.get::<String>("listenbrainz.token")
@@ -496,21 +480,6 @@ pub async fn token(database: &sqlx::PgPool) -> Option<String> {
.filter(|t| !t.is_empty())
}
#[derive(Deserialize)]
struct ValidateTokenResponse {
valid: bool,
user_name: Option<String>,
}
/// 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<Option<String>, reqwest::Error> {
let request = reqwest::Client::new()
.get(format!("{}/validate-token", BASE))
.header(reqwest::header::AUTHORIZATION, format!("Token {}", token));
let response = send_json::<ValidateTokenResponse>(request).await?;
Ok(response.user_name.filter(|_| response.valid))
}
#[derive(Deserialize)]
struct RadioResponse {
payload: RadioPayload,
+1 -1
View File
@@ -41,7 +41,7 @@ pub struct ApiError {
type ApiResult<T> = Result<Json<T>, Custom<Json<ApiError>>>;
fn fail(status: Status, message: impl Into<String>) -> Custom<Json<ApiError>> {
pub(crate) fn fail(status: Status, message: impl Into<String>) -> Custom<Json<ApiError>> {
Custom(
status,
Json(ApiError {
+146 -3
View File
@@ -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<Route> {
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<T> = Result<Json<T>, Status>;
@@ -47,6 +61,135 @@ async fn rules(_user: User, pool: &State<PgPool>) -> ApiResult<Vec<ClusterMixRul
.map_err(db_error)
}
/// Check a new rule's settings, explaining what's wrong where they're out of range
fn validate_rule(rule: &PartialClusterMixRule) -> Result<(), Custom<Json<ApiError>>> {
let invalid = |message: &str| Err(fail(Status::UnprocessableEntity, message));
let out_of = |value: Option<i32>, range: std::ops::RangeInclusive<i32>| {
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 = "<rule>")]
async fn create_rule(
_user: User,
rule: Json<PartialClusterMixRule>,
pool: &State<PgPool>,
) -> Result<Json<ClusterMixRule>, Custom<Json<ApiError>>> {
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/<id>?<delete_playlists>")]
async fn delete_rule(
_user: User,
id: &str,
delete_playlists: Option<bool>,
pool: &State<PgPool>,
media_client: &State<Arc<Subsonic>>,
) -> Result<Status, Custom<Json<ApiError>>> {
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,