Require logging in to the web UI and API
The first visit to the UI creates the account from a username and password; after that every API route needs a session cookie from logging in. Accounts are stored in app_user (Argon2id password hashes) and sessions in user_session (SHA-256 token hashes, 30 days). The account page lets the user save a Listenbrainz token, checked with Listenbrainz first. It takes priority over listenbrainz.token from the config for LB Radio suggestions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0767c21a6f
commit
53c1bffa6d
33 files changed
+1249
-39
No files matched your search
+4
-3
@@ -10,11 +10,12 @@ SUBSONIC_PASSWORD=
|
||||
POSTGRES_PASSWORD=
|
||||
|
||||
# Optional: your Listenbrainz user token (listenbrainz.org/settings), to find new songs for each
|
||||
# genre mix with LB Radio
|
||||
# genre mix with LB Radio. You can also save it to your account in the web UI, which takes priority.
|
||||
LISTENBRAINZ_TOKEN=
|
||||
|
||||
# Where to serve playlistd. It has no login, so it only listens on this machine by default; set
|
||||
# PLAYLISTD_BIND=0.0.0.0 to make it reachable from your network.
|
||||
# Where to serve playlistd. The first visit to the web UI creates the login, and anyone who gets
|
||||
# there first can, so it only listens on this machine by default. Once you've created your account,
|
||||
# set PLAYLISTD_BIND=0.0.0.0 to make it reachable from your network.
|
||||
PLAYLISTD_BIND=127.0.0.1
|
||||
PLAYLISTD_PORT=8000
|
||||
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "INSERT INTO \"app_user\" (id, username, password_hash) VALUES ($1, $2, $3)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Varchar",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0"
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n INSERT INTO \"user_session\" (token_hash, user_id, expires_at)\n VALUES ($1, $2, NOW() + make_interval(days => $3))\n ",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Bytea",
|
||||
"Uuid",
|
||||
"Int4"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "DELETE FROM \"user_session\" WHERE expires_at <= NOW()",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": []
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "LOCK TABLE \"app_user\" IN SHARE ROW EXCLUSIVE MODE",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": []
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT user_id FROM \"user_session\" WHERE token_hash = $1 AND expires_at > NOW()",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "user_id",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Bytea"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT EXISTS (SELECT 1 FROM \"app_user\") AS \"e!\"",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "e!",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": []
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3"
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "DELETE FROM \"user_session\" WHERE token_hash = $1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Bytea"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916"
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT id, password_hash FROM \"app_user\" WHERE username = $1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "password_hash",
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b"
|
||||
}
|
||||
Generated
+34
@@ -97,6 +97,18 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"blake2",
|
||||
"cpufeatures",
|
||||
"password-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arraydeque"
|
||||
version = "0.5.1"
|
||||
@@ -220,6 +232,15 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blake2"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -1471,6 +1492,17 @@ dependencies = [
|
||||
"windows-targets 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "password-hash"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"rand_core",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pathdiff"
|
||||
version = "0.2.3"
|
||||
@@ -1603,6 +1635,7 @@ checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"
|
||||
name = "playlistd"
|
||||
version = "0.2.6"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chrono",
|
||||
"config",
|
||||
"env_logger",
|
||||
@@ -1614,6 +1647,7 @@ dependencies = [
|
||||
"rocket",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sqlx",
|
||||
"thiserror 2.0.17",
|
||||
"tokio",
|
||||
|
||||
@@ -23,6 +23,8 @@ rand = "0.8"
|
||||
serde_json = "1.0"
|
||||
futures-util = "0.3"
|
||||
tokio-util = { version = "0.7", features = ["io"] }
|
||||
argon2 = "0.5"
|
||||
sha2 = "0.10"
|
||||
|
||||
[package.metadata.deb]
|
||||
depends = "$auto"
|
||||
|
||||
@@ -32,8 +32,10 @@ cp .env.example .env # then fill in your Subsonic server and a database passw
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
The web UI is then at http://localhost:8000. playlistd has no login, so it only listens on the
|
||||
Docker host by default; set `PLAYLISTD_BIND=0.0.0.0` in `.env` to open it to your network. If your
|
||||
The web UI is then at http://localhost:8000. The first visit asks you to create an account (see
|
||||
[Logging in](#logging-in)), and anyone who reaches it first can, so it only listens on the Docker
|
||||
host by default: create your account, then set `PLAYLISTD_BIND=0.0.0.0` in `.env` to open it to
|
||||
your network. If your
|
||||
Subsonic server runs on the Docker host, use `http://host.docker.internal:4533/rest` as
|
||||
`SUBSONIC_BASE`.
|
||||
|
||||
@@ -136,10 +138,10 @@ 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:
|
||||
Create a rule through the API (after logging in, see [Logging in](#logging-in)):
|
||||
|
||||
```sh
|
||||
curl -X POST localhost:8000/api/playlist/mix -H 'Content-Type: application/json' \
|
||||
curl -b cookies -X POST localhost:8000/api/playlist/mix -H 'Content-Type: application/json' \
|
||||
-d '{"tracking_user": "jellywx", "months": 3, "playlist_size": 50}'
|
||||
```
|
||||
|
||||
@@ -170,7 +172,8 @@ 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 `listenbrainz.token` is set, an LB Radio playlist for each mix's top genres.
|
||||
* if a Listenbrainz token is saved to your account (or `listenbrainz.token` is set), an LB Radio
|
||||
playlist for each mix's top genres.
|
||||
|
||||
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.
|
||||
@@ -197,6 +200,46 @@ and set `discover.ui` (or `DISCOVER_UI`) to the `discover/dist` directory to ser
|
||||
playlistd at `/`. For development, `npm run dev` serves the UI with hot reload and forwards API
|
||||
requests to playlistd on `localhost:8000` (or `PLAYLISTD_URL`).
|
||||
|
||||
### Logging in
|
||||
|
||||
The web UI and every API endpoint need you to log in. There's no default account: the first time
|
||||
anyone opens the UI, it asks for a username and password, and creates the account with them. After
|
||||
that, the UI shows a login page instead, and new accounts can't be created. Passwords are stored as
|
||||
Argon2id hashes in the `app_user` table, and logging in sets a session cookie that lasts 30 days.
|
||||
|
||||
To start over (e.g. if you forget your password), delete the account, and the next visit to the UI
|
||||
will set it up again:
|
||||
|
||||
```sql
|
||||
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
|
||||
curl -c cookies -X POST localhost:8000/api/auth/login -H 'Content-Type: application/json' \
|
||||
-d '{"username": "you", "password": "your password"}'
|
||||
curl -b cookies localhost:8000/api/tracked/playlists
|
||||
```
|
||||
|
||||
Requests without a valid session get `401 {"error": "Log in to continue"}`. These endpoints are
|
||||
under `/api/auth`:
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|------------------------------|---------------------------------------------------------------|
|
||||
| `GET /status` | Whether the account still has to be set up, and who's logged in |
|
||||
| `POST /setup` | Create the account (`username`, `password`), only if there isn't one |
|
||||
| `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
|
||||
|
||||
The UI uses these endpoints under `/api/discover`:
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ services:
|
||||
db:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
# playlistd has no login, so by default it's only reachable from this machine
|
||||
# the first visit creates the login, so by default it's only reachable from this machine
|
||||
- "${PLAYLISTD_BIND:-127.0.0.1}:${PLAYLISTD_PORT:-8000}:8000"
|
||||
environment:
|
||||
DATABASE_URL: postgres://playlistd:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@db/playlistd
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { FormEvent, 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;
|
||||
}) {
|
||||
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 logout = async () => {
|
||||
setBusy("logout");
|
||||
try {
|
||||
await authApi.logout();
|
||||
} catch {
|
||||
// the session is gone from this browser either way
|
||||
}
|
||||
props.onLogout();
|
||||
};
|
||||
|
||||
return (
|
||||
<article className="manage">
|
||||
<header className="manage-header">
|
||||
<p className="eyebrow">Account</p>
|
||||
<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" />}
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
+26
-8
@@ -1,17 +1,18 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatus } from "./api";
|
||||
import { Account, api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatus } from "./api";
|
||||
import { usePlayer } from "./usePlayer";
|
||||
import { MixView, hue } from "./MixView";
|
||||
import { LikedView } from "./LikedView";
|
||||
import { TrackedView } from "./TrackedView";
|
||||
import { AccountView } from "./AccountView";
|
||||
import { PlayerBar } from "./PlayerBar";
|
||||
import * as Icon from "./icons";
|
||||
|
||||
type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" };
|
||||
type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" } | { view: "account" };
|
||||
|
||||
function parseHash(): Route {
|
||||
const [, view, id] = window.location.hash.split("/");
|
||||
if (view === "liked" || view === "tracked") return { view };
|
||||
if (view === "liked" || view === "tracked" || view === "account") return { view };
|
||||
return { view: "mix", id: id || undefined };
|
||||
}
|
||||
|
||||
@@ -25,7 +26,11 @@ function storedRule() {
|
||||
}
|
||||
}
|
||||
|
||||
export function App() {
|
||||
export function App(props: {
|
||||
account: Account;
|
||||
onAccountChange: (account: Account) => void;
|
||||
onLogout: () => void;
|
||||
}) {
|
||||
const [rules, setRules] = useState<Rule[] | null>(null);
|
||||
const [ruleId, setRuleId] = useState<string | null>(storedRule);
|
||||
const [mixes, setMixes] = useState<MixSummary[] | null>(null);
|
||||
@@ -201,22 +206,35 @@ export function App() {
|
||||
<span className="mix-name">Tracked playlists</span>
|
||||
</a>
|
||||
</li>
|
||||
<li className="account-link">
|
||||
<a href="#/account" className={route.view === "account" ? "selected" : ""} style={{ ["--hue" as string]: 220 }}>
|
||||
<span className="mix-dot heart" aria-hidden="true"><Icon.User size={14} /></span>
|
||||
<span className="mix-name">{props.account.username}</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<main className="content">
|
||||
{error && <div className="notice error">{error}</div>}
|
||||
{route.view !== "tracked" && rules && rules.length === 0 && (
|
||||
{(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 -X POST /api/playlist/mix -H 'Content-Type: application/json' \\\n -d '{"tracking_user": "your-listenbrainz-name"}'`}</pre>
|
||||
<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 !== "tracked" && pending && mixes?.length === 0 && (
|
||||
{(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 === "tracked" ? (
|
||||
{route.view === "account" ? (
|
||||
<AccountView
|
||||
account={props.account}
|
||||
onChange={props.onAccountChange}
|
||||
onLogout={props.onLogout}
|
||||
onToast={(message) => setToast({ message })}
|
||||
/>
|
||||
) : route.view === "tracked" ? (
|
||||
<TrackedView defaultUser={rule?.tracking_user} onToast={(message) => setToast({ message })} />
|
||||
) : route.view === "liked" ? (
|
||||
<LikedView liked={liked} player={player} onStatus={onStatus} />
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { FormEvent, useCallback, useEffect, useState } from "react";
|
||||
import { Account, authApi, UNAUTHORIZED_EVENT } from "./api";
|
||||
import { App } from "./App";
|
||||
import * as Icon from "./icons";
|
||||
|
||||
type State =
|
||||
| { kind: "loading" }
|
||||
| { kind: "unreachable"; message: string }
|
||||
| { kind: "setup" }
|
||||
| { kind: "login"; expired?: boolean }
|
||||
| { kind: "ready"; account: Account };
|
||||
|
||||
/** Shows the app once logged in. The first visit creates the account instead. */
|
||||
export function AuthGate() {
|
||||
const [state, setState] = useState<State>({ kind: "loading" });
|
||||
|
||||
const check = useCallback(() => {
|
||||
authApi.status().then(
|
||||
(s) =>
|
||||
setState(
|
||||
s.account
|
||||
? { kind: "ready", account: s.account }
|
||||
: s.setup_required
|
||||
? { kind: "setup" }
|
||||
: { kind: "login" },
|
||||
),
|
||||
(e) => setState({ kind: "unreachable", message: e.message }),
|
||||
);
|
||||
}, []);
|
||||
useEffect(check, [check]);
|
||||
|
||||
// the session ran out (or was logged out elsewhere) while using the app
|
||||
useEffect(() => {
|
||||
const onUnauthorized = () =>
|
||||
setState((s) => (s.kind === "ready" ? { kind: "login", expired: true } : s));
|
||||
window.addEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
|
||||
return () => window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
|
||||
}, []);
|
||||
|
||||
switch (state.kind) {
|
||||
case "loading":
|
||||
return <div className="auth-page"><span className="spinner" aria-label="Loading" /></div>;
|
||||
case "unreachable":
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<div className="notice error" role="alert">
|
||||
Couldn't reach playlistd ({state.message})
|
||||
<button className="btn" onClick={check}>Try again</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
case "setup":
|
||||
case "login":
|
||||
return (
|
||||
<CredentialsForm
|
||||
setup={state.kind === "setup"}
|
||||
expired={state.kind === "login" && state.expired}
|
||||
onDone={(account) => setState({ kind: "ready", account })}
|
||||
// someone else finished setting up first
|
||||
onRecheck={check}
|
||||
/>
|
||||
);
|
||||
case "ready":
|
||||
return (
|
||||
<App
|
||||
account={state.account}
|
||||
onAccountChange={(account) => setState({ kind: "ready", account })}
|
||||
onLogout={() => setState({ kind: "login" })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function CredentialsForm(props: {
|
||||
setup: boolean;
|
||||
expired?: boolean;
|
||||
onDone: (account: Account) => void;
|
||||
onRecheck: () => void;
|
||||
}) {
|
||||
const { setup } = props;
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (setup && password !== confirm) {
|
||||
setError("The passwords don't match");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
props.onDone(setup ? await authApi.setup(username, password) : await authApi.login(username, password));
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
setBusy(false);
|
||||
if (setup) props.onRecheck();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<form className="auth-card" onSubmit={submit} aria-labelledby="auth-heading">
|
||||
<div className="brand">
|
||||
<span className="brand-mark"><Icon.Sparkle size={16} /></span>
|
||||
playlistd
|
||||
</div>
|
||||
<div>
|
||||
<h1 id="auth-heading">{setup ? "Create your account" : "Log in"}</h1>
|
||||
<p className="hint">
|
||||
{setup
|
||||
? "Choose the username and password you'll use to log in to playlistd from now on."
|
||||
: props.expired
|
||||
? "Your session has ended. Log in again to continue."
|
||||
: "Log in to continue."}
|
||||
</p>
|
||||
</div>
|
||||
<label className="field">
|
||||
<span>Username</span>
|
||||
<input
|
||||
required
|
||||
autoFocus
|
||||
maxLength={64}
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
autoComplete="username"
|
||||
autoCapitalize="none"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Password</span>
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
minLength={setup ? 8 : undefined}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete={setup ? "new-password" : "current-password"}
|
||||
/>
|
||||
{setup && <span className="hint">At least 8 characters</span>}
|
||||
</label>
|
||||
{setup && (
|
||||
<label className="field">
|
||||
<span>Confirm password</span>
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{error && <p className="form-error" role="alert">{error}</p>}
|
||||
<button className="btn primary" type="submit" disabled={busy}>
|
||||
{busy && <span className="spinner light" />}
|
||||
{setup ? "Create account" : "Log in"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+36
-3
@@ -49,14 +49,22 @@ export type MixDetail = MixSummary & {
|
||||
suggestions: Suggestion[];
|
||||
};
|
||||
|
||||
/** Fired when the API says the session has ended, so the app can ask to log in again */
|
||||
export const UNAUTHORIZED_EVENT = "playlistd:unauthorized";
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit, base = "/api/discover"): Promise<T> {
|
||||
const response = await fetch(`${base}${path}`, init);
|
||||
if (!response.ok) {
|
||||
// (a failed login is just a wrong password)
|
||||
if (response.status === 401 && `${base}${path}` !== "/api/auth/login") {
|
||||
window.dispatchEvent(new Event(UNAUTHORIZED_EVENT));
|
||||
}
|
||||
// the API explains what went wrong where it can
|
||||
const body = await response.json().catch(() => null);
|
||||
throw new Error(body?.error ?? `${response.status} ${response.statusText}`);
|
||||
}
|
||||
return response.status === 204 ? (undefined as T) : response.json();
|
||||
const text = await response.text();
|
||||
return text ? JSON.parse(text) : (undefined as T);
|
||||
}
|
||||
|
||||
const json = (method: string, body: unknown): RequestInit => ({
|
||||
@@ -76,8 +84,7 @@ export const api = {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ status }),
|
||||
}),
|
||||
rebuild: (ruleId: string) =>
|
||||
fetch(`/api/discover/rules/${ruleId}/rebuild`, { method: "POST" }),
|
||||
rebuild: (ruleId: string) => request<void>(`/rules/${ruleId}/rebuild`, { method: "POST" }),
|
||||
};
|
||||
|
||||
export const coverUrl = (coverArt: string, size = 120) =>
|
||||
@@ -149,3 +156,29 @@ export const trackedApi = {
|
||||
previewName: (template: string) =>
|
||||
tracked<{ name: string }>(`/preview-name?template=${encodeURIComponent(template)}`),
|
||||
};
|
||||
|
||||
// ---------- account ----------
|
||||
|
||||
export type Account = {
|
||||
username: string;
|
||||
/** The Listenbrainz user the saved token belongs to */
|
||||
listenbrainz_user: string | null;
|
||||
has_listenbrainz_token: boolean;
|
||||
};
|
||||
|
||||
export type AuthStatus = {
|
||||
/** No account exists yet: the first visit creates it */
|
||||
setup_required: boolean;
|
||||
account: Account | null;
|
||||
};
|
||||
|
||||
const auth = <T>(path: string, init?: RequestInit) => request<T>(path, init, "/api/auth");
|
||||
|
||||
export const authApi = {
|
||||
status: () => auth<AuthStatus>("/status"),
|
||||
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 })),
|
||||
};
|
||||
@@ -20,3 +20,4 @@ export const Trash = ({ size }: P) => svg(<><path d="M4 7h16" /><path d="M9 7V4h
|
||||
export const ListMusic = ({ size }: P) => svg(<><path d="M4 6h11M4 11h11M4 16h7" /><circle cx="17" cy="17" r="2.5" /><path d="M19.5 17V8l2-1" /></>, size);
|
||||
export const Calendar = ({ size }: P) => svg(<><rect x="4" y="5" width="16" height="15" rx="2" /><path d="M4 10h16M9 3v4M15 3v4" /></>, size);
|
||||
export const Warning = ({ size }: P) => svg(<><path d="M12 4l9 16H3z" /><path d="M12 10v4M12 17v.5" /></>, size);
|
||||
export const User = ({ size }: P) => svg(<><circle cx="12" cy="8" r="4" /><path d="M4 20c1.5-3.5 4.5-5 8-5s6.5 1.5 8 5" /></>, size);
|
||||
@@ -1,10 +1,10 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App";
|
||||
import { AuthGate } from "./Auth";
|
||||
import "./styles.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<AuthGate />
|
||||
</StrictMode>,
|
||||
);
|
||||
+75
-1
@@ -1005,6 +1005,78 @@ h2 {
|
||||
color: var(--accent-text);
|
||||
}
|
||||
|
||||
/* ---------- login & account ---------- */
|
||||
|
||||
.auth-page {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 100vh;
|
||||
padding: 24px 16px;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
max-width: 380px;
|
||||
padding: 28px 24px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.auth-card .brand {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.auth-card h1 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 1.4rem;
|
||||
}
|
||||
|
||||
.auth-card .btn {
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.auth-page .notice {
|
||||
align-items: flex-start;
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
.account-link {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.account-link .mix-dot {
|
||||
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);
|
||||
}
|
||||
|
||||
/* ---------- small screens ---------- */
|
||||
|
||||
@media (max-width: 800px) {
|
||||
@@ -1048,7 +1120,9 @@ h2 {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.liked-link {
|
||||
.liked-link,
|
||||
.manage-link,
|
||||
.account-link {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
|
||||
@@ -94,6 +94,18 @@ export function usePlayer(onError: (item: QueueItem) => void) {
|
||||
};
|
||||
}, [next]);
|
||||
|
||||
// stop playing when the app goes away (e.g. on logging out)
|
||||
useEffect(
|
||||
() => () => {
|
||||
const el = audio.current;
|
||||
if (!el) return;
|
||||
el.pause();
|
||||
el.removeAttribute("src");
|
||||
el.load();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// OS media controls and keyboard
|
||||
useEffect(() => {
|
||||
if (!("mediaSession" in navigator) || !current) return;
|
||||
|
||||
@@ -21,7 +21,8 @@ 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
|
||||
# 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
|
||||
# token = ""
|
||||
|
||||
[discover]
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
-- The account that logs in to the web UI. The first visit to the UI creates it.
|
||||
CREATE TABLE "app_user"
|
||||
(
|
||||
id UUID NOT NULL PRIMARY KEY,
|
||||
username VARCHAR(64) NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL, -- Argon2id, in PHC string format
|
||||
listenbrainz_token TEXT, -- Used for Listenbrainz endpoints that need one (e.g. LB Radio)
|
||||
listenbrainz_user VARCHAR(250), -- The Listenbrainz user the token belongs to
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Logged in browsers. Only a hash of the session token is stored.
|
||||
CREATE TABLE "user_session"
|
||||
(
|
||||
token_hash BYTEA NOT NULL PRIMARY KEY, -- SHA-256 of the token in the session cookie
|
||||
user_id UUID NOT NULL REFERENCES "app_user" (id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX "user_session_expires_at" ON "user_session" (expires_at);
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
//! Login for the web UI and its API.
|
||||
//!
|
||||
//! The first visit to the UI creates the account (there's no default one); after that, every API
|
||||
//! 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,
|
||||
};
|
||||
use argon2::Argon2;
|
||||
use rand::RngCore;
|
||||
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 serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::postgres::PgPool;
|
||||
use std::sync::OnceLock;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const COOKIE: &str = "playlistd_session";
|
||||
const SESSION_DAYS: i64 = 30;
|
||||
const MIN_PASSWORD: usize = 8;
|
||||
const MAX_USERNAME: usize = 64;
|
||||
|
||||
pub fn routes() -> Vec<Route> {
|
||||
routes![
|
||||
status,
|
||||
setup,
|
||||
login,
|
||||
logout,
|
||||
account,
|
||||
set_listenbrainz_token
|
||||
]
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ApiError {
|
||||
error: String,
|
||||
}
|
||||
|
||||
type ApiResult<T> = Result<Json<T>, Custom<Json<ApiError>>>;
|
||||
|
||||
fn error(status: Status, message: impl Into<String>) -> Custom<Json<ApiError>> {
|
||||
Custom(
|
||||
status,
|
||||
Json(ApiError {
|
||||
error: message.into(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn db_error(e: sqlx::Error) -> Custom<Json<ApiError>> {
|
||||
log::error!("Database error: {}", e);
|
||||
error(Status::InternalServerError, "Database error")
|
||||
}
|
||||
|
||||
/// API requests without a valid session get this instead of Rocket's HTML page
|
||||
#[catch(401)]
|
||||
pub fn unauthorized() -> Json<ApiError> {
|
||||
Json(ApiError {
|
||||
error: "Log in to continue".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The logged in user. Add it as a request guard to a route to require logging in: requests
|
||||
/// without a valid session fail with 401.
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for User {
|
||||
type Error = ();
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
||||
let Some(token) = request.cookies().get(COOKIE).map(|c| c.value().to_string()) else {
|
||||
return Outcome::Error((Status::Unauthorized, ()));
|
||||
};
|
||||
let pool = match request.guard::<&State<PgPool>>().await {
|
||||
Outcome::Success(pool) => pool,
|
||||
_ => return Outcome::Error((Status::InternalServerError, ())),
|
||||
};
|
||||
match sqlx::query_scalar!(
|
||||
r#"SELECT user_id FROM "user_session" WHERE token_hash = $1 AND expires_at > NOW()"#,
|
||||
&hash_token(&token)[..]
|
||||
)
|
||||
.fetch_optional(pool.inner())
|
||||
.await
|
||||
{
|
||||
Ok(Some(id)) => Outcome::Success(User { id }),
|
||||
Ok(None) => Outcome::Error((Status::Unauthorized, ())),
|
||||
Err(e) => {
|
||||
log::error!("Database error checking session: {}", e);
|
||||
Outcome::Error((Status::InternalServerError, ()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_token(token: &str) -> Vec<u8> {
|
||||
Sha256::digest(token.as_bytes()).to_vec()
|
||||
}
|
||||
|
||||
/// Argon2 is deliberately slow, so it runs off the async workers
|
||||
async fn hash_password(password: String) -> Result<String, Custom<Json<ApiError>>> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
Argon2::default()
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map(|h| h.to_string())
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.ok_or_else(|| error(Status::InternalServerError, "Couldn't hash the password"))
|
||||
}
|
||||
|
||||
async fn verify_password(password: String, hash: String) -> bool {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
PasswordHash::new(&hash)
|
||||
.map(|parsed| {
|
||||
Argon2::default()
|
||||
.verify_password(password.as_bytes(), &parsed)
|
||||
.is_ok()
|
||||
})
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// A hash to check passwords against when the username doesn't exist, so that a wrong username
|
||||
/// takes as long as a wrong password
|
||||
fn dummy_hash() -> &'static str {
|
||||
static HASH: OnceLock<String> = OnceLock::new();
|
||||
HASH.get_or_init(|| {
|
||||
Argon2::default()
|
||||
.hash_password(b"not a password", &SaltString::generate(&mut OsRng))
|
||||
.map(|h| h.to_string())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Start a session for a user and give the browser its cookie
|
||||
async fn start_session(
|
||||
pool: &PgPool,
|
||||
cookies: &CookieJar<'_>,
|
||||
user_id: Uuid,
|
||||
) -> Result<(), Custom<Json<ApiError>>> {
|
||||
let mut bytes = [0u8; 32];
|
||||
rand::rngs::OsRng.fill_bytes(&mut bytes);
|
||||
let token: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
|
||||
|
||||
sqlx::query!(r#"DELETE FROM "user_session" WHERE expires_at <= NOW()"#)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO "user_session" (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, NOW() + make_interval(days => $3))
|
||||
"#,
|
||||
&hash_token(&token)[..],
|
||||
user_id,
|
||||
SESSION_DAYS as i32
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
|
||||
cookies.add(
|
||||
Cookie::build((COOKIE, token))
|
||||
.path("/")
|
||||
.http_only(true)
|
||||
.same_site(SameSite::Strict)
|
||||
.max_age(rocket::time::Duration::days(SESSION_DAYS)),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[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
|
||||
"#,
|
||||
id
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AuthStatus {
|
||||
/// No account exists yet, so the UI should ask for a username and password to create one
|
||||
setup_required: bool,
|
||||
/// The logged in account, if any
|
||||
account: Option<Account>,
|
||||
}
|
||||
|
||||
#[get("/status")]
|
||||
async fn status(pool: &State<PgPool>, user: Option<User>) -> ApiResult<AuthStatus> {
|
||||
let setup_required =
|
||||
!sqlx::query_scalar!(r#"SELECT EXISTS (SELECT 1 FROM "app_user") AS "e!""#)
|
||||
.fetch_one(pool.inner())
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
let account = match user {
|
||||
Some(user) => Some(load_account(pool.inner(), user.id).await?),
|
||||
None => None,
|
||||
};
|
||||
Ok(Json(AuthStatus {
|
||||
setup_required,
|
||||
account,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Credentials {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
/// Create the account. Only works while there isn't one yet.
|
||||
#[post("/setup", data = "<credentials>")]
|
||||
async fn setup(
|
||||
pool: &State<PgPool>,
|
||||
cookies: &CookieJar<'_>,
|
||||
credentials: Json<Credentials>,
|
||||
) -> ApiResult<Account> {
|
||||
let username = credentials.username.trim().to_string();
|
||||
if username.is_empty() || username.chars().count() > MAX_USERNAME {
|
||||
return Err(error(
|
||||
Status::UnprocessableEntity,
|
||||
format!("Choose a username of 1 to {} characters", MAX_USERNAME),
|
||||
));
|
||||
}
|
||||
if credentials.password.chars().count() < MIN_PASSWORD {
|
||||
return Err(error(
|
||||
Status::UnprocessableEntity,
|
||||
format!("Use a password of at least {} characters", MIN_PASSWORD),
|
||||
));
|
||||
}
|
||||
let password_hash = hash_password(credentials.password.clone()).await?;
|
||||
|
||||
// the lock makes concurrent setups wait, so only the first one creates an account
|
||||
let mut tx = pool.begin().await.map_err(db_error)?;
|
||||
sqlx::query!(r#"LOCK TABLE "app_user" IN SHARE ROW EXCLUSIVE MODE"#)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
let exists = sqlx::query_scalar!(r#"SELECT EXISTS (SELECT 1 FROM "app_user") AS "e!""#)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
if exists {
|
||||
return Err(error(
|
||||
Status::Conflict,
|
||||
"The account has already been set up",
|
||||
));
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query!(
|
||||
r#"INSERT INTO "app_user" (id, username, password_hash) VALUES ($1, $2, $3)"#,
|
||||
id,
|
||||
username,
|
||||
password_hash
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
tx.commit().await.map_err(db_error)?;
|
||||
log::info!("Created account {}", username);
|
||||
|
||||
start_session(pool.inner(), cookies, id).await?;
|
||||
load_account(pool.inner(), id).await.map(Json)
|
||||
}
|
||||
|
||||
#[post("/login", data = "<credentials>")]
|
||||
async fn login(
|
||||
pool: &State<PgPool>,
|
||||
cookies: &CookieJar<'_>,
|
||||
credentials: Json<Credentials>,
|
||||
) -> ApiResult<Account> {
|
||||
let user = sqlx::query!(
|
||||
r#"SELECT id, password_hash FROM "app_user" WHERE username = $1"#,
|
||||
credentials.username.trim()
|
||||
)
|
||||
.fetch_optional(pool.inner())
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
|
||||
let hash = user
|
||||
.as_ref()
|
||||
.map(|u| u.password_hash.clone())
|
||||
.unwrap_or_else(|| dummy_hash().to_string());
|
||||
let valid = verify_password(credentials.password.clone(), hash).await;
|
||||
match user {
|
||||
Some(user) if valid => {
|
||||
start_session(pool.inner(), cookies, user.id).await?;
|
||||
load_account(pool.inner(), user.id).await.map(Json)
|
||||
}
|
||||
_ => {
|
||||
log::warn!("Failed login for {:?}", credentials.username.trim());
|
||||
Err(error(Status::Unauthorized, "Wrong username or password"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/logout")]
|
||||
async fn logout(
|
||||
pool: &State<PgPool>,
|
||||
cookies: &CookieJar<'_>,
|
||||
) -> Result<Status, Custom<Json<ApiError>>> {
|
||||
if let Some(cookie) = cookies.get(COOKIE) {
|
||||
sqlx::query!(
|
||||
r#"DELETE FROM "user_session" WHERE token_hash = $1"#,
|
||||
&hash_token(cookie.value())[..]
|
||||
)
|
||||
.execute(pool.inner())
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
}
|
||||
cookies.remove(Cookie::build(COOKIE).path("/"));
|
||||
Ok(Status::NoContent)
|
||||
}
|
||||
|
||||
#[get("/account")]
|
||||
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)
|
||||
}
|
||||
@@ -318,6 +318,7 @@ async fn save_suggestions(
|
||||
recently_played,
|
||||
&exclude,
|
||||
rule.discovery_count.max(0) as usize,
|
||||
listenbrainz::token(database).await,
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
||||
+4
-2
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! 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 configured, an LB Radio prompt built from each mix's
|
||||
//! Listenbrainz token is saved to the account (or 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.
|
||||
@@ -59,6 +59,8 @@ pub async fn suggest(
|
||||
// recordings that already have a suggestion the user acted on
|
||||
exclude: &HashSet<String>,
|
||||
per_mix: usize,
|
||||
// a Listenbrainz user token, to also ask LB Radio for candidates
|
||||
token: Option<String>,
|
||||
) -> Result<Vec<Suggestion>, Box<dyn std::error::Error>> {
|
||||
if targets.is_empty() || per_mix == 0 {
|
||||
return Ok(vec![]);
|
||||
@@ -72,7 +74,7 @@ pub async fn suggest(
|
||||
.map(|r| r.recording_mbid)
|
||||
.collect();
|
||||
|
||||
if let Some(token) = listenbrainz::token() {
|
||||
if let Some(token) = token {
|
||||
for target in targets {
|
||||
let genres: Vec<&str> = target
|
||||
.profile
|
||||
|
||||
+33
-2
@@ -471,8 +471,24 @@ pub async fn recommendations(
|
||||
.mbids)
|
||||
}
|
||||
|
||||
/// The user token from the config, needed by some endpoints (e.g. LB Radio)
|
||||
pub fn token() -> Option<String> {
|
||||
/// 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),
|
||||
}
|
||||
crate::CONFIG
|
||||
.get()?
|
||||
.get::<String>("listenbrainz.token")
|
||||
@@ -480,6 +496,21 @@ pub fn token() -> 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,
|
||||
|
||||
+10
-2
@@ -1,3 +1,4 @@
|
||||
mod auth;
|
||||
mod cluster;
|
||||
mod daemon;
|
||||
mod discover;
|
||||
@@ -11,6 +12,7 @@ mod tracked;
|
||||
mod web;
|
||||
mod youtube;
|
||||
|
||||
use crate::auth::User;
|
||||
use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon};
|
||||
use crate::models::{
|
||||
ClusterMixRule, CreateTrackedPlaylist, PartialClusterMixRule, PartialCreateTrackedPlaylist,
|
||||
@@ -95,6 +97,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.manage(media_client)
|
||||
.manage(database)
|
||||
.manage(youtube)
|
||||
.mount("/api/auth", auth::routes())
|
||||
.register("/api", rocket::catchers![auth::unauthorized])
|
||||
.mount("/api/discover", web::routes())
|
||||
.mount("/api/tracked", tracked::routes())
|
||||
.mount(
|
||||
@@ -214,6 +218,7 @@ pub struct CreatePlaylist {
|
||||
/// Create a new playlist and attach a tracker
|
||||
#[post("/rule", data = "<create_playlist_rule>")]
|
||||
async fn create_tracking_playlist_rule(
|
||||
_user: User,
|
||||
pool: &State<PgPool>,
|
||||
create_playlist_rule: Json<PartialCreateTrackedPlaylist>,
|
||||
) -> Json<Response<CreateTrackedPlaylist>> {
|
||||
@@ -226,6 +231,7 @@ async fn create_tracking_playlist_rule(
|
||||
/// Create a new playlist and attach a tracker
|
||||
#[post("/create", data = "<create_playlist>")]
|
||||
async fn create_tracking_playlist(
|
||||
_user: User,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
pool: &State<PgPool>,
|
||||
create_playlist: Json<CreatePlaylist>,
|
||||
@@ -257,6 +263,7 @@ async fn create_tracking_playlist(
|
||||
/// Add tracking to an existing playlist
|
||||
#[post("/track", data = "<playlist>")]
|
||||
async fn add_tracking_playlist(
|
||||
_user: User,
|
||||
pool: &State<PgPool>,
|
||||
playlist: Json<PartialTrackedPlaylist>,
|
||||
) -> Json<Response<TrackedPlaylist>> {
|
||||
@@ -268,7 +275,7 @@ async fn add_tracking_playlist(
|
||||
|
||||
/// Get all tracked playlists
|
||||
#[get("/")]
|
||||
async fn all_playlists(pool: &State<PgPool>) -> JsonValue {
|
||||
async fn all_playlists(_user: User, pool: &State<PgPool>) -> JsonValue {
|
||||
match TrackedPlaylist::all(pool.inner()).await {
|
||||
Ok(playlists) => json!(playlists),
|
||||
Err(_) => json!([]),
|
||||
@@ -278,6 +285,7 @@ async fn all_playlists(pool: &State<PgPool>) -> JsonValue {
|
||||
/// Create a rule that maintains genre mixes built from clustering a user's recent listens
|
||||
#[post("/mix", data = "<rule>")]
|
||||
async fn create_cluster_mix_rule(
|
||||
_user: User,
|
||||
pool: &State<PgPool>,
|
||||
rule: Json<PartialClusterMixRule>,
|
||||
) -> Json<Response<ClusterMixRule>> {
|
||||
@@ -289,7 +297,7 @@ async fn create_cluster_mix_rule(
|
||||
|
||||
/// Get all cluster mix rules
|
||||
#[get("/mix")]
|
||||
async fn all_cluster_mix_rules(pool: &State<PgPool>) -> JsonValue {
|
||||
async fn all_cluster_mix_rules(_user: User, pool: &State<PgPool>) -> JsonValue {
|
||||
match ClusterMixRule::all(pool.inner()).await {
|
||||
Ok(rules) => json!(rules),
|
||||
Err(_) => json!([]),
|
||||
|
||||
+25
-5
@@ -1,6 +1,7 @@
|
||||
//! API for managing tracked playlists (Subsonic playlists kept up to date with a Listenbrainz
|
||||
//! user's top songs) and the rules that create them on a schedule.
|
||||
|
||||
use crate::auth::User;
|
||||
use crate::daemon::update_playlists::update_playlist;
|
||||
use crate::listenbrainz::StatsRange;
|
||||
use crate::models::{CreateTrackedPlaylist, TrackedPlaylist};
|
||||
@@ -159,6 +160,7 @@ async fn view(
|
||||
|
||||
#[get("/playlists")]
|
||||
async fn playlists(
|
||||
_user: User,
|
||||
pool: &State<PgPool>,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
) -> ApiResult<Vec<TrackedPlaylistView>> {
|
||||
@@ -187,6 +189,7 @@ struct NewTrackedPlaylist {
|
||||
|
||||
#[post("/playlists", data = "<body>")]
|
||||
async fn create_playlist(
|
||||
_user: User,
|
||||
body: Json<NewTrackedPlaylist>,
|
||||
pool: &State<PgPool>,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
@@ -267,6 +270,7 @@ struct TrackedPlaylistUpdate {
|
||||
|
||||
#[put("/playlists/<id>", data = "<body>")]
|
||||
async fn update_tracked_playlist(
|
||||
_user: User,
|
||||
id: &str,
|
||||
body: Json<TrackedPlaylistUpdate>,
|
||||
pool: &State<PgPool>,
|
||||
@@ -307,6 +311,7 @@ async fn update_tracked_playlist(
|
||||
/// Stop tracking a playlist, optionally deleting it from Subsonic too
|
||||
#[delete("/playlists/<id>?<delete_playlist>")]
|
||||
async fn delete_tracked_playlist(
|
||||
_user: User,
|
||||
id: &str,
|
||||
delete_playlist: Option<bool>,
|
||||
pool: &State<PgPool>,
|
||||
@@ -335,6 +340,7 @@ async fn delete_tracked_playlist(
|
||||
/// Update a tracked playlist's songs now, rather than on the next daemon tick
|
||||
#[post("/playlists/<id>/refresh")]
|
||||
async fn refresh(
|
||||
_user: User,
|
||||
id: &str,
|
||||
pool: &State<PgPool>,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
@@ -379,6 +385,7 @@ async fn mix_playlist_ids(pool: &PgPool) -> Result<Vec<String>, Custom<Json<ApiE
|
||||
/// Subsonic playlists that could be tracked (genre mixes are left out)
|
||||
#[get("/subsonic-playlists")]
|
||||
async fn subsonic_playlists(
|
||||
_user: User,
|
||||
pool: &State<PgPool>,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
) -> ApiResult<Vec<SubsonicPlaylist>> {
|
||||
@@ -426,7 +433,7 @@ fn rule_view(rule: CreateTrackedPlaylist) -> RuleView {
|
||||
}
|
||||
|
||||
#[get("/rules")]
|
||||
async fn rules(pool: &State<PgPool>) -> ApiResult<Vec<RuleView>> {
|
||||
async fn rules(_user: User, pool: &State<PgPool>) -> ApiResult<Vec<RuleView>> {
|
||||
let mut rules = CreateTrackedPlaylist::all(pool.inner())
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
@@ -442,7 +449,11 @@ struct RuleBody {
|
||||
}
|
||||
|
||||
#[post("/rules", data = "<body>")]
|
||||
async fn create_rule(body: Json<RuleBody>, pool: &State<PgPool>) -> ApiResult<RuleView> {
|
||||
async fn create_rule(
|
||||
_user: User,
|
||||
body: Json<RuleBody>,
|
||||
pool: &State<PgPool>,
|
||||
) -> ApiResult<RuleView> {
|
||||
body.tracking.validate()?;
|
||||
format_template(&body.name_template)?;
|
||||
|
||||
@@ -467,7 +478,12 @@ async fn create_rule(body: Json<RuleBody>, pool: &State<PgPool>) -> ApiResult<Ru
|
||||
|
||||
/// Changes apply to playlists the rule creates from now on
|
||||
#[put("/rules/<id>", data = "<body>")]
|
||||
async fn update_rule(id: &str, body: Json<RuleBody>, pool: &State<PgPool>) -> ApiResult<RuleView> {
|
||||
async fn update_rule(
|
||||
_user: User,
|
||||
id: &str,
|
||||
body: Json<RuleBody>,
|
||||
pool: &State<PgPool>,
|
||||
) -> ApiResult<RuleView> {
|
||||
body.tracking.validate()?;
|
||||
format_template(&body.name_template)?;
|
||||
|
||||
@@ -493,7 +509,11 @@ async fn update_rule(id: &str, body: Json<RuleBody>, pool: &State<PgPool>) -> Ap
|
||||
|
||||
/// Delete a rule. Playlists it already created keep being tracked.
|
||||
#[delete("/rules/<id>")]
|
||||
async fn delete_rule(id: &str, pool: &State<PgPool>) -> Result<Status, Custom<Json<ApiError>>> {
|
||||
async fn delete_rule(
|
||||
_user: User,
|
||||
id: &str,
|
||||
pool: &State<PgPool>,
|
||||
) -> Result<Status, Custom<Json<ApiError>>> {
|
||||
let result = sqlx::query!(
|
||||
r#"DELETE FROM "create_tracked_playlist" WHERE id = $1"#,
|
||||
parse_id(id)?
|
||||
@@ -514,7 +534,7 @@ struct NamePreview {
|
||||
|
||||
/// What a name template produces today
|
||||
#[get("/preview-name?<template>")]
|
||||
async fn preview_name(template: &str) -> ApiResult<NamePreview> {
|
||||
async fn preview_name(_user: User, template: &str) -> ApiResult<NamePreview> {
|
||||
Ok(Json(NamePreview {
|
||||
name: format_template(template)?,
|
||||
}))
|
||||
|
||||
+10
-4
@@ -1,6 +1,7 @@
|
||||
//! API for the discover UI: mixes, suggested songs, and audio/cover streaming
|
||||
//! from Subsonic or YouTube.
|
||||
|
||||
use crate::auth::User;
|
||||
use crate::models::{ClusterMixRule, MixSuggestion};
|
||||
use crate::subsonic::Subsonic;
|
||||
use crate::track::Track;
|
||||
@@ -39,7 +40,7 @@ fn parse_id(id: &str) -> Result<Uuid, Status> {
|
||||
}
|
||||
|
||||
#[get("/rules")]
|
||||
async fn rules(pool: &State<PgPool>) -> ApiResult<Vec<ClusterMixRule>> {
|
||||
async fn rules(_user: User, pool: &State<PgPool>) -> ApiResult<Vec<ClusterMixRule>> {
|
||||
ClusterMixRule::all(pool.inner())
|
||||
.await
|
||||
.map(Json)
|
||||
@@ -57,7 +58,7 @@ struct MixSummary {
|
||||
}
|
||||
|
||||
#[get("/rules/<id>/mixes")]
|
||||
async fn mixes(id: &str, pool: &State<PgPool>) -> ApiResult<Vec<MixSummary>> {
|
||||
async fn mixes(_user: User, id: &str, pool: &State<PgPool>) -> ApiResult<Vec<MixSummary>> {
|
||||
sqlx::query_as!(
|
||||
MixSummary,
|
||||
r#"
|
||||
@@ -89,6 +90,7 @@ struct MixDetail {
|
||||
|
||||
#[get("/mixes/<id>")]
|
||||
async fn mix(
|
||||
_user: User,
|
||||
id: &str,
|
||||
pool: &State<PgPool>,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
@@ -149,7 +151,7 @@ async fn mix(
|
||||
}
|
||||
|
||||
#[get("/rules/<id>/liked")]
|
||||
async fn liked(id: &str, pool: &State<PgPool>) -> ApiResult<Vec<MixSuggestion>> {
|
||||
async fn liked(_user: User, id: &str, pool: &State<PgPool>) -> ApiResult<Vec<MixSuggestion>> {
|
||||
sqlx::query_as!(
|
||||
MixSuggestion,
|
||||
r#"
|
||||
@@ -173,6 +175,7 @@ struct StatusUpdate {
|
||||
/// Like, dismiss, or reset a suggestion
|
||||
#[put("/suggestions/<id>", data = "<update>")]
|
||||
async fn set_status(
|
||||
_user: User,
|
||||
id: &str,
|
||||
update: Json<StatusUpdate>,
|
||||
pool: &State<PgPool>,
|
||||
@@ -194,7 +197,7 @@ async fn set_status(
|
||||
|
||||
/// Rebuild a rule's mixes on the next daemon tick
|
||||
#[post("/rules/<id>/rebuild")]
|
||||
async fn rebuild(id: &str, pool: &State<PgPool>) -> Status {
|
||||
async fn rebuild(_user: User, id: &str, pool: &State<PgPool>) -> Status {
|
||||
let Ok(id) = parse_id(id) else {
|
||||
return Status::NotFound;
|
||||
};
|
||||
@@ -286,6 +289,7 @@ impl<R: Unpin> tokio::io::AsyncSeek for LengthReader<R> {
|
||||
/// Stream a song from Subsonic
|
||||
#[get("/stream/<id>")]
|
||||
async fn stream(
|
||||
_user: User,
|
||||
id: &str,
|
||||
range: Range,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
@@ -308,6 +312,7 @@ async fn stream(
|
||||
/// Cover art from Subsonic
|
||||
#[get("/cover/<id>?<size>")]
|
||||
async fn cover(
|
||||
_user: User,
|
||||
id: &str,
|
||||
size: Option<u32>,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
@@ -329,6 +334,7 @@ async fn cover(
|
||||
/// Find a suggested song on YouTube and stream its audio
|
||||
#[get("/youtube/<id>")]
|
||||
async fn youtube(
|
||||
_user: User,
|
||||
id: &str,
|
||||
range: Range,
|
||||
pool: &State<PgPool>,
|
||||
|
||||
Reference in new issue
Block a user