Add discover UI with new song suggestions
Each mix rebuild now also finds songs that aren't in the library: the user's Listenbrainz recommendations they've never played, plus an LB Radio prompt per mix when a Listenbrainz token is configured. Each candidate goes to the mix whose genre profile it fits best and is skipped if it's already in the library or was played recently. discover/ is a new React app to listen to the mixes: library songs stream from Subsonic and suggested songs are found on YouTube with yt-dlp, both proxied through playlistd with Range support for seeking. Suggestions can be liked (kept in a "Liked new songs" list) or hidden. - discover: candidate gathering, genre fit scoring, library filtering - web: /api/discover routes, Subsonic/YouTube streaming proxy - youtube: yt-dlp search (skipping hour-long results) and audio URLs - mix tags now hold library genre names, for display in the UI - config: listenbrainz.token, discover.ui, discover.ytdlp, discover.format Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p
This commit is contained in:
32 files changed
+4628
-36
No files matched your search
Generated
+29
@@ -664,6 +664,17 @@ version = "0.3.30"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1"
|
checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures-macro"
|
||||||
|
version = "0.3.30"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "futures-sink"
|
name = "futures-sink"
|
||||||
version = "0.3.30"
|
version = "0.3.30"
|
||||||
@@ -685,6 +696,7 @@ dependencies = [
|
|||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
"futures-io",
|
"futures-io",
|
||||||
|
"futures-macro",
|
||||||
"futures-sink",
|
"futures-sink",
|
||||||
"futures-task",
|
"futures-task",
|
||||||
"memchr",
|
"memchr",
|
||||||
@@ -1467,6 +1479,7 @@ version = "0.2.6"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
"config",
|
"config",
|
||||||
|
"futures-util",
|
||||||
"log",
|
"log",
|
||||||
"md5",
|
"md5",
|
||||||
"rand",
|
"rand",
|
||||||
@@ -1477,6 +1490,7 @@ dependencies = [
|
|||||||
"sqlx",
|
"sqlx",
|
||||||
"thiserror 2.0.17",
|
"thiserror 2.0.17",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1658,10 +1672,12 @@ dependencies = [
|
|||||||
"system-configuration",
|
"system-configuration",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-native-tls",
|
"tokio-native-tls",
|
||||||
|
"tokio-util",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
"url",
|
"url",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
"wasm-bindgen-futures",
|
"wasm-bindgen-futures",
|
||||||
|
"wasm-streams",
|
||||||
"web-sys",
|
"web-sys",
|
||||||
"winreg",
|
"winreg",
|
||||||
]
|
]
|
||||||
@@ -2847,6 +2863,19 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasm-streams"
|
||||||
|
version = "0.4.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4e072d4e72f700fb3443d8fe94a39315df013eef1104903cdb0a2abd322bbecd"
|
||||||
|
dependencies = [
|
||||||
|
"futures-util",
|
||||||
|
"js-sys",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"wasm-bindgen-futures",
|
||||||
|
"web-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "web-sys"
|
name = "web-sys"
|
||||||
version = "0.3.69"
|
version = "0.3.69"
|
||||||
|
|||||||
+3
-1
@@ -10,7 +10,7 @@ description = "Subsonic playlist daemon"
|
|||||||
rocket = { version = "0.5.0", features = ["json"] }
|
rocket = { version = "0.5.0", features = ["json"] }
|
||||||
tokio = { version = "1.0", features = ["full"] }
|
tokio = { version = "1.0", features = ["full"] }
|
||||||
sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "uuid", "chrono"] }
|
sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "uuid", "chrono"] }
|
||||||
reqwest = { version = "0.11", features = ["json"] }
|
reqwest = { version = "0.11", features = ["json", "stream"] }
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
uuid = { version = "1.7", features = ["v4", "serde"] }
|
uuid = { version = "1.7", features = ["v4", "serde"] }
|
||||||
md5 = "0.8.0"
|
md5 = "0.8.0"
|
||||||
@@ -20,6 +20,8 @@ log = "0.4.21"
|
|||||||
chrono = { version = "0.4.38", features = ["serde"] }
|
chrono = { version = "0.4.38", features = ["serde"] }
|
||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
futures-util = "0.3"
|
||||||
|
tokio-util = { version = "0.7", features = ["io"] }
|
||||||
|
|
||||||
[package.metadata.deb]
|
[package.metadata.deb]
|
||||||
depends = "$auto"
|
depends = "$auto"
|
||||||
|
|||||||
@@ -109,5 +109,50 @@ VALUES (gen_random_uuid(), 'jellywx', 3, 50);
|
|||||||
| `familiar_ratio` | 0.3 | Share of each mix taken from recently played tracks |
|
| `familiar_ratio` | 0.3 | Share of each mix taken from recently played tracks |
|
||||||
| `name_template` | `Mix: {label}` | Playlist name; `{label}` becomes the mix's top genres |
|
| `name_template` | `Mix: {label}` | Playlist name; `{label}` becomes the mix's top genres |
|
||||||
| `refresh_hours` | 24 | How often to rebuild the mixes |
|
| `refresh_hours` | 24 | How often to rebuild the mixes |
|
||||||
|
| `discovery_count`| 15 | New songs (not in your library) to suggest per mix |
|
||||||
|
|
||||||
Set `last_run` to `NULL` to rebuild a rule's mixes on the next daemon tick.
|
Set `last_run` to `NULL` to rebuild a rule's mixes on the next daemon tick.
|
||||||
|
|
||||||
|
### Discover UI
|
||||||
|
|
||||||
|
`discover/` is a React app for listening to the genre mixes, alongside new songs that aren't in
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
In the UI, songs from your library stream from Subsonic. New songs are found on YouTube with
|
||||||
|
[yt-dlp](https://github.com/yt-dlp/yt-dlp) and streamed through playlistd, so yt-dlp needs to be
|
||||||
|
installed on the server (keep it up to date: YouTube changes often break older versions). You can
|
||||||
|
like a new song to keep it in "Liked new songs", or hide it so it isn't suggested again.
|
||||||
|
|
||||||
|
Build it with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd discover
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
and set `discover.ui` (or `DISCOVER_UI`) to the `discover/dist` directory to serve it from
|
||||||
|
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`).
|
||||||
|
|
||||||
|
The UI uses these endpoints under `/api/discover`:
|
||||||
|
|
||||||
|
| Endpoint | Purpose |
|
||||||
|
|--------------------------------|------------------------------------------------------|
|
||||||
|
| `GET /rules` | Cluster mix rules |
|
||||||
|
| `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 |
|
||||||
|
| `PUT /suggestions/<id>` | Set a suggestion's status (`new`, `liked`, `dismissed`) |
|
||||||
|
| `POST /rules/<id>/rebuild` | Rebuild a rule's mixes on the next daemon tick |
|
||||||
|
| `GET /stream/<song id>` | Stream a library song from Subsonic |
|
||||||
|
| `GET /cover/<cover art id>` | Library cover art from Subsonic |
|
||||||
|
| `GET /youtube/<suggestion id>` | Stream a suggested song from YouTube |
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<meta name="color-scheme" content="light dark" />
|
||||||
|
<title>Discover</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1757
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"name": "playlistd-discover",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc --noEmit && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "18.3.1",
|
||||||
|
"react-dom": "18.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.9.0",
|
||||||
|
"@types/react": "18.3.12",
|
||||||
|
"@types/react-dom": "18.3.1",
|
||||||
|
"@vitejs/plugin-react": "4.3.3",
|
||||||
|
"typescript": "5.6.3",
|
||||||
|
"vite": "5.4.10"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatus } from "./api";
|
||||||
|
import { usePlayer } from "./usePlayer";
|
||||||
|
import { MixView, hue } from "./MixView";
|
||||||
|
import { LikedView } from "./LikedView";
|
||||||
|
import { PlayerBar } from "./PlayerBar";
|
||||||
|
import * as Icon from "./icons";
|
||||||
|
|
||||||
|
type Route = { view: "mix"; id?: string } | { view: "liked" };
|
||||||
|
|
||||||
|
function parseHash(): Route {
|
||||||
|
const [, view, id] = window.location.hash.split("/");
|
||||||
|
return view === "liked" ? { view: "liked" } : { view: "mix", id: id || undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
type Toast = { message: string; undo?: () => void };
|
||||||
|
|
||||||
|
function storedRule() {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem("discover.rule");
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function App() {
|
||||||
|
const [rules, setRules] = useState<Rule[] | null>(null);
|
||||||
|
const [ruleId, setRuleId] = useState<string | null>(storedRule);
|
||||||
|
const [mixes, setMixes] = useState<MixSummary[] | null>(null);
|
||||||
|
const [detail, setDetail] = useState<MixDetail | null>(null);
|
||||||
|
const [liked, setLiked] = useState<Suggestion[]>([]);
|
||||||
|
const [route, setRoute] = useState<Route>(parseHash);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [toast, setToast] = useState<Toast | null>(null);
|
||||||
|
|
||||||
|
const player = usePlayer((item) => setToast({ message: `Couldn't play “${item.title}”` }));
|
||||||
|
const rule = rules?.find((r) => r.id === ruleId) ?? rules?.[0];
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onHash = () => setRoute(parseHash());
|
||||||
|
window.addEventListener("hashchange", onHash);
|
||||||
|
return () => window.removeEventListener("hashchange", onHash);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!toast) return;
|
||||||
|
const t = window.setTimeout(() => setToast(null), toast.undo ? 6000 : 3500);
|
||||||
|
return () => window.clearTimeout(t);
|
||||||
|
}, [toast]);
|
||||||
|
|
||||||
|
const loadRules = useCallback(() => {
|
||||||
|
api.rules().then(setRules, (e) => setError(`Couldn't reach playlistd (${e.message})`));
|
||||||
|
}, []);
|
||||||
|
useEffect(loadRules, [loadRules]);
|
||||||
|
|
||||||
|
const loadMixes = useCallback(() => {
|
||||||
|
if (!rule) return;
|
||||||
|
api.mixes(rule.id).then(setMixes, (e) => setError(e.message));
|
||||||
|
api.liked(rule.id).then(setLiked, () => undefined);
|
||||||
|
}, [rule?.id]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
useEffect(loadMixes, [loadMixes]);
|
||||||
|
|
||||||
|
// mixes are built by the daemon; check back while they're pending
|
||||||
|
const pending = !!rule && (!rule.last_run || mixes?.length === 0);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pending) return;
|
||||||
|
const t = window.setInterval(() => {
|
||||||
|
loadRules();
|
||||||
|
loadMixes();
|
||||||
|
}, 10000);
|
||||||
|
return () => window.clearInterval(t);
|
||||||
|
}, [pending, loadRules, loadMixes]);
|
||||||
|
|
||||||
|
const mixId = route.view === "mix" ? route.id ?? mixes?.[0]?.id : undefined;
|
||||||
|
const loadDetail = useCallback(
|
||||||
|
(quiet = false) => {
|
||||||
|
if (!mixId) return;
|
||||||
|
if (!quiet) setDetail((d) => (d?.id === mixId ? d : null));
|
||||||
|
api.mix(mixId).then(setDetail, (e) => !quiet && setError(`Couldn't load mix (${e.message})`));
|
||||||
|
},
|
||||||
|
[mixId],
|
||||||
|
);
|
||||||
|
useEffect(() => loadDetail(), [loadDetail]);
|
||||||
|
|
||||||
|
// pick up YouTube links once a new song has been found and starts playing
|
||||||
|
useEffect(() => {
|
||||||
|
if (player.status === "playing" && player.current?.source === "youtube") {
|
||||||
|
loadDetail(true);
|
||||||
|
if (rule) api.liked(rule.id).then(setLiked, () => undefined);
|
||||||
|
}
|
||||||
|
}, [player.status, player.current?.key]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
const updateLocal = (id: string, status: SuggestionStatus, previous?: Suggestion) => {
|
||||||
|
setDetail((d) => {
|
||||||
|
if (!d) return d;
|
||||||
|
const suggestions =
|
||||||
|
status === "dismissed"
|
||||||
|
? d.suggestions.filter((s) => s.id !== id)
|
||||||
|
: d.suggestions.some((s) => s.id === id)
|
||||||
|
? d.suggestions.map((s) => (s.id === id ? { ...s, status } : s))
|
||||||
|
: previous && previous.mix_id === d.id
|
||||||
|
? [...d.suggestions, { ...previous, status }].sort((a, b) => b.score - a.score)
|
||||||
|
: d.suggestions;
|
||||||
|
return { ...d, suggestions };
|
||||||
|
});
|
||||||
|
setLiked((l) => {
|
||||||
|
const without = l.filter((s) => s.id !== id);
|
||||||
|
const item = previous ?? l.find((s) => s.id === id);
|
||||||
|
return status === "liked" && item ? [{ ...item, status }, ...without] : without;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const onStatus = (s: Suggestion, status: SuggestionStatus) => {
|
||||||
|
updateLocal(s.id, status, s);
|
||||||
|
api.setStatus(s.id, status).then(
|
||||||
|
() => {
|
||||||
|
loadMixes();
|
||||||
|
if (status === "dismissed") {
|
||||||
|
setToast({
|
||||||
|
message: `Hid “${s.title}”`,
|
||||||
|
undo: () => {
|
||||||
|
updateLocal(s.id, s.status, s);
|
||||||
|
api.setStatus(s.id, s.status).then(loadMixes);
|
||||||
|
setToast(null);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
updateLocal(s.id, s.status, s);
|
||||||
|
setToast({ message: "Couldn't save that, try again" });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const rebuild = () => {
|
||||||
|
if (!rule) return;
|
||||||
|
api.rebuild(rule.id).then(() => {
|
||||||
|
setToast({ message: "Rebuilding mixes. This takes a minute or two." });
|
||||||
|
loadRules();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`app ${player.current ? "with-player" : ""}`}>
|
||||||
|
<nav className="sidebar" aria-label="Mixes">
|
||||||
|
<div className="brand">
|
||||||
|
<span className="brand-mark"><Icon.Sparkle size={16} /></span>
|
||||||
|
Discover
|
||||||
|
</div>
|
||||||
|
{rules && rules.length > 1 && (
|
||||||
|
<select
|
||||||
|
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 = "";
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{rules.map((r) => <option key={r.id} value={r.id}>{r.tracking_user}</option>)}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
{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>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<ul className="mix-list">
|
||||||
|
{mixes?.map((m) => (
|
||||||
|
<li key={m.id}>
|
||||||
|
<a href={`#/mix/${m.id}`} className={mixId === m.id ? "selected" : ""}
|
||||||
|
style={{ ["--hue" as string]: hue(m.tags.join()) }}>
|
||||||
|
<span className="mix-dot" aria-hidden="true" />
|
||||||
|
<span className="mix-name">{mixTitle(m)}</span>
|
||||||
|
{m.new_count > 0 && <span className="count" title={`${m.new_count} new songs`}>{m.new_count}</span>}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
<li className="liked-link">
|
||||||
|
<a href="#/liked" className={route.view === "liked" ? "selected" : ""} style={{ ["--hue" as string]: 340 }}>
|
||||||
|
<span className="mix-dot heart" aria-hidden="true"><Icon.Heart size={12} filled /></span>
|
||||||
|
<span className="mix-name">Liked new songs</span>
|
||||||
|
{liked.length > 0 && <span className="count">{liked.length}</span>}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<main className="content">
|
||||||
|
{error && <div className="notice error">{error}</div>}
|
||||||
|
{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>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{pending && mixes?.length === 0 && (
|
||||||
|
<div className="notice"><span className="spinner" /> Building mixes from your recent listens…</div>
|
||||||
|
)}
|
||||||
|
{route.view === "liked" ? (
|
||||||
|
<LikedView liked={liked} player={player} onStatus={onStatus} />
|
||||||
|
) : detail ? (
|
||||||
|
<MixView mix={detail} player={player} onStatus={onStatus} />
|
||||||
|
) : (
|
||||||
|
mixId && <div className="notice"><span className="spinner" /> Loading…</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<PlayerBar player={player} />
|
||||||
|
|
||||||
|
{toast && (
|
||||||
|
<div className="toast" role="status">
|
||||||
|
{toast.message}
|
||||||
|
{toast.undo && <button onClick={toast.undo}>Undo</button>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import { Suggestion, SuggestionStatus } from "./api";
|
||||||
|
import { fromSuggestion } from "./queue";
|
||||||
|
import { Player } from "./usePlayer";
|
||||||
|
import { TrackRow } from "./TrackRow";
|
||||||
|
import { SuggestionActions } from "./MixView";
|
||||||
|
import * as Icon from "./icons";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
liked: Suggestion[];
|
||||||
|
player: Player;
|
||||||
|
onStatus: (s: Suggestion, status: SuggestionStatus) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function LikedView({ liked, player, onStatus }: Props) {
|
||||||
|
const items = useMemo(() => liked.map(fromSuggestion), [liked]);
|
||||||
|
return (
|
||||||
|
<article className="mix liked-view" style={{ ["--hue" as string]: 340 }}>
|
||||||
|
<header className="mix-header">
|
||||||
|
<div className="mix-art" aria-hidden="true"><Icon.Heart size={56} filled /></div>
|
||||||
|
<div className="mix-info">
|
||||||
|
<p className="eyebrow">Collection</p>
|
||||||
|
<h1>Liked new songs</h1>
|
||||||
|
<p className="mix-counts">Songs you liked that aren't in your library yet: a shopping list.</p>
|
||||||
|
<div className="mix-buttons">
|
||||||
|
<button className="primary" onClick={() => player.playAt(items, 0)} disabled={!items.length}>
|
||||||
|
<Icon.Play size={16} /> Play all
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<section>
|
||||||
|
{items.length === 0 ? (
|
||||||
|
<p className="empty">Nothing yet. Tap the heart on a new song to keep it here.</p>
|
||||||
|
) : (
|
||||||
|
<ol className="tracks">
|
||||||
|
{liked.map((s, i) => (
|
||||||
|
<TrackRow key={s.id} item={items[i]} number={i + 1} active={player.current?.key === items[i].key}
|
||||||
|
status={player.status} onPlay={() => player.playAt(items, i)}
|
||||||
|
actions={<SuggestionActions s={s} onStatus={onStatus} />} />
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import { MixDetail, mixTitle, Suggestion, SuggestionStatus } from "./api";
|
||||||
|
import { fromSong, fromSuggestion, interleave, QueueItem } from "./queue";
|
||||||
|
import { Player } from "./usePlayer";
|
||||||
|
import { TrackRow } from "./TrackRow";
|
||||||
|
import * as Icon from "./icons";
|
||||||
|
|
||||||
|
export function hue(text: string) {
|
||||||
|
let h = 0;
|
||||||
|
for (const c of text) h = (h * 31 + c.charCodeAt(0)) % 360;
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SuggestionActions({ s, onStatus }: { s: Suggestion; onStatus: (s: Suggestion, status: SuggestionStatus) => void }) {
|
||||||
|
const liked = s.status === "liked";
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button className={`icon-button ${liked ? "liked" : ""}`} onClick={() => onStatus(s, liked ? "new" : "liked")}
|
||||||
|
aria-label={liked ? "Unlike" : "Like"} aria-pressed={liked} title={liked ? "Unlike" : "Like"}>
|
||||||
|
<Icon.Heart filled={liked} />
|
||||||
|
</button>
|
||||||
|
{s.youtube_id ? (
|
||||||
|
<a className="icon-button" href={`https://www.youtube.com/watch?v=${s.youtube_id}`} target="_blank" rel="noreferrer"
|
||||||
|
aria-label="Open on YouTube" title="Open on YouTube"><Icon.External /></a>
|
||||||
|
) : (
|
||||||
|
<a className="icon-button" href={`https://musicbrainz.org/recording/${s.recording_mbid}`} target="_blank" rel="noreferrer"
|
||||||
|
aria-label="Open on MusicBrainz" title="Open on MusicBrainz"><Icon.External /></a>
|
||||||
|
)}
|
||||||
|
{s.status !== "liked" && (
|
||||||
|
<button className="icon-button" onClick={() => onStatus(s, "dismissed")} aria-label="Not for me" title="Not for me">
|
||||||
|
<Icon.Close />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
mix: MixDetail;
|
||||||
|
player: Player;
|
||||||
|
onStatus: (s: Suggestion, status: SuggestionStatus) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function MixView({ mix, player, onStatus }: Props) {
|
||||||
|
const fresh = useMemo(() => mix.suggestions.map(fromSuggestion), [mix.suggestions]);
|
||||||
|
const library = useMemo(() => mix.songs.map(fromSong), [mix.songs]);
|
||||||
|
// clicking a row plays through everything shown, new songs first
|
||||||
|
const all = useMemo(() => [...fresh, ...library], [fresh, library]);
|
||||||
|
const title = mixTitle(mix);
|
||||||
|
const h = hue(mix.tags.join());
|
||||||
|
|
||||||
|
const play = (items: QueueItem[], at = 0) => items.length && player.playAt(items, at);
|
||||||
|
const isActive = (item: QueueItem) => player.current?.key === item.key;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<article className="mix" style={{ ["--hue" as string]: h }}>
|
||||||
|
<header className="mix-header">
|
||||||
|
<div className="mix-art" aria-hidden="true">
|
||||||
|
<span>{title.split(" / ")[0]}</span>
|
||||||
|
</div>
|
||||||
|
<div className="mix-info">
|
||||||
|
<p className="eyebrow">Mix</p>
|
||||||
|
<h1>{title}</h1>
|
||||||
|
<ul className="tags">
|
||||||
|
{mix.tags.map((t) => <li key={t}>{t}</li>)}
|
||||||
|
</ul>
|
||||||
|
<p className="mix-counts">
|
||||||
|
{mix.songs.length} from your library · {mix.suggestions.length} new
|
||||||
|
</p>
|
||||||
|
<div className="mix-buttons">
|
||||||
|
<button className="primary" onClick={() => play(interleave(library, fresh))} disabled={!all.length}>
|
||||||
|
<Icon.Shuffle size={16} /> Play mix
|
||||||
|
</button>
|
||||||
|
<button onClick={() => play(fresh)} disabled={!fresh.length}>
|
||||||
|
<Icon.Sparkle size={16} /> Only new songs
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section aria-labelledby="new-heading">
|
||||||
|
<h2 id="new-heading"><Icon.Sparkle size={16} /> New for you</h2>
|
||||||
|
{fresh.length === 0 ? (
|
||||||
|
<p className="empty">No new songs for this mix yet. They're found when the mixes are rebuilt.</p>
|
||||||
|
) : (
|
||||||
|
<ol className="tracks">
|
||||||
|
{mix.suggestions.map((s, i) => (
|
||||||
|
<TrackRow
|
||||||
|
key={s.id}
|
||||||
|
item={fresh[i]}
|
||||||
|
number={i + 1}
|
||||||
|
active={isActive(fresh[i])}
|
||||||
|
status={player.status}
|
||||||
|
onPlay={() => play(all, i)}
|
||||||
|
meta={<span className="match" title="How well its genres fit this mix">{Math.round(s.score * 100)}% match</span>}
|
||||||
|
actions={<SuggestionActions s={s} onStatus={onStatus} />}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section aria-labelledby="library-heading">
|
||||||
|
<h2 id="library-heading"><Icon.Library size={16} /> From your library</h2>
|
||||||
|
<ol className="tracks">
|
||||||
|
{mix.songs.map((song, i) => (
|
||||||
|
<TrackRow
|
||||||
|
key={song.id}
|
||||||
|
item={library[i]}
|
||||||
|
number={i + 1}
|
||||||
|
active={isActive(library[i])}
|
||||||
|
status={player.status}
|
||||||
|
onPlay={() => play(all, fresh.length + i)}
|
||||||
|
duration={song.duration}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { Player } from "./usePlayer";
|
||||||
|
import { Cover, formatTime } from "./TrackRow";
|
||||||
|
import * as Icon from "./icons";
|
||||||
|
|
||||||
|
export function PlayerBar({ player }: { player: Player }) {
|
||||||
|
const { current, status, time, duration } = player;
|
||||||
|
if (!current) return null;
|
||||||
|
const label =
|
||||||
|
status === "loading"
|
||||||
|
? current.source === "youtube" ? "Finding on YouTube…" : "Loading…"
|
||||||
|
: status === "error" ? "Couldn't play this one, skipping" : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<footer className="player" aria-label="Player">
|
||||||
|
<div className="player-track">
|
||||||
|
<Cover src={current.cover} label={current.title} size={52} />
|
||||||
|
<div className="track-text">
|
||||||
|
<div className="track-title">{current.title}</div>
|
||||||
|
<div className="track-sub">{current.artist}</div>
|
||||||
|
</div>
|
||||||
|
<span className={`badge ${current.source}`}>
|
||||||
|
{current.source === "youtube" ? "YouTube" : "Library"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="player-main">
|
||||||
|
<div className="player-buttons">
|
||||||
|
<button className="icon-button" onClick={player.previous} aria-label="Previous"><Icon.Prev /></button>
|
||||||
|
<button className="play-button" onClick={player.toggle} aria-label={status === "playing" ? "Pause" : "Play"}>
|
||||||
|
{status === "loading" ? <span className="spinner light" /> : status === "playing" ? <Icon.Pause size={20} /> : <Icon.Play size={20} />}
|
||||||
|
</button>
|
||||||
|
<button className="icon-button" onClick={player.next} aria-label="Next"><Icon.Next /></button>
|
||||||
|
</div>
|
||||||
|
<div className="player-progress">
|
||||||
|
<span>{formatTime(time) || "0:00"}</span>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={0}
|
||||||
|
max={duration || 1}
|
||||||
|
step={0.5}
|
||||||
|
value={Math.min(time, duration || 1)}
|
||||||
|
disabled={!duration}
|
||||||
|
onChange={(e) => player.seek(Number(e.target.value))}
|
||||||
|
aria-label="Seek"
|
||||||
|
style={{ ["--progress" as string]: `${duration ? (time / duration) * 100 : 0}%` }}
|
||||||
|
/>
|
||||||
|
<span>{formatTime(duration)}</span>
|
||||||
|
</div>
|
||||||
|
{label && <div className={`player-status ${status}`}>{label}</div>}
|
||||||
|
</div>
|
||||||
|
<div className="player-queue">
|
||||||
|
{player.index + 1} / {player.queue.length}
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { ReactNode } from "react";
|
||||||
|
import { QueueItem } from "./queue";
|
||||||
|
import { PlayerStatus } from "./usePlayer";
|
||||||
|
import * as Icon from "./icons";
|
||||||
|
|
||||||
|
export function formatTime(seconds?: number) {
|
||||||
|
if (!seconds || !Number.isFinite(seconds)) return "";
|
||||||
|
const s = Math.floor(seconds);
|
||||||
|
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Cover({ src, label, size = 44 }: { src?: string | null; label: string; size?: number }) {
|
||||||
|
return (
|
||||||
|
<div className="cover" style={{ width: size, height: size }} aria-hidden="true">
|
||||||
|
<span>{label.slice(0, 1).toUpperCase()}</span>
|
||||||
|
{src && <img src={src} alt="" loading="lazy" onError={(e) => (e.currentTarget.style.display = "none")} />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
item: QueueItem;
|
||||||
|
number: number;
|
||||||
|
active: boolean;
|
||||||
|
status: PlayerStatus;
|
||||||
|
onPlay: () => void;
|
||||||
|
meta?: ReactNode;
|
||||||
|
actions?: ReactNode;
|
||||||
|
duration?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function TrackRow({ item, number, active, status, onPlay, meta, actions, duration }: Props) {
|
||||||
|
const loading = active && status === "loading";
|
||||||
|
const playing = active && status === "playing";
|
||||||
|
return (
|
||||||
|
<li className={`track ${active ? "active" : ""}`}>
|
||||||
|
<button className="track-play" onClick={onPlay} aria-label={`Play ${item.title} by ${item.artist}`}>
|
||||||
|
<span className="track-number">{number}</span>
|
||||||
|
<span className="track-icon">
|
||||||
|
{loading ? <span className="spinner" /> : playing ? <span className="bars"><i /><i /><i /></span> : <Icon.Play size={14} />}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<Cover src={item.cover} label={item.title} />
|
||||||
|
<div className="track-text">
|
||||||
|
<div className="track-title">{item.title}</div>
|
||||||
|
<div className="track-sub">
|
||||||
|
{item.artist}
|
||||||
|
{item.album && <span className="track-album"> · {item.album}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{meta && <div className="track-meta">{meta}</div>}
|
||||||
|
<div className="track-duration">{formatTime(duration)}</div>
|
||||||
|
{actions && <div className="track-actions">{actions}</div>}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
export type Rule = {
|
||||||
|
id: string;
|
||||||
|
tracking_user: string;
|
||||||
|
months: number;
|
||||||
|
playlist_size: number;
|
||||||
|
discovery_count: number;
|
||||||
|
last_run: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type MixSummary = {
|
||||||
|
id: string;
|
||||||
|
playlist_id: string;
|
||||||
|
name: string | null;
|
||||||
|
tags: string[];
|
||||||
|
position: number;
|
||||||
|
new_count: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Song = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
artist: string;
|
||||||
|
album: string;
|
||||||
|
duration?: number;
|
||||||
|
coverArt?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SuggestionStatus = "new" | "liked" | "dismissed";
|
||||||
|
|
||||||
|
export type Suggestion = {
|
||||||
|
id: string;
|
||||||
|
mix_id: string | null;
|
||||||
|
recording_mbid: string;
|
||||||
|
title: string;
|
||||||
|
artist: string;
|
||||||
|
release: string | null;
|
||||||
|
cover_url: string | null;
|
||||||
|
score: number;
|
||||||
|
status: SuggestionStatus;
|
||||||
|
youtube_id: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type MixDetail = MixSummary & { songs: Song[]; suggestions: Suggestion[] };
|
||||||
|
|
||||||
|
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
|
const response = await fetch(`/api/discover${path}`, init);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`${response.status} ${response.statusText}`);
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
rules: () => request<Rule[]>("/rules"),
|
||||||
|
mixes: (ruleId: string) => request<MixSummary[]>(`/rules/${ruleId}/mixes`),
|
||||||
|
mix: (mixId: string) => request<MixDetail>(`/mixes/${mixId}`),
|
||||||
|
liked: (ruleId: string) => request<Suggestion[]>(`/rules/${ruleId}/liked`),
|
||||||
|
setStatus: (id: string, status: SuggestionStatus) =>
|
||||||
|
request<Suggestion>(`/suggestions/${id}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ status }),
|
||||||
|
}),
|
||||||
|
rebuild: (ruleId: string) =>
|
||||||
|
fetch(`/api/discover/rules/${ruleId}/rebuild`, { method: "POST" }),
|
||||||
|
};
|
||||||
|
|
||||||
|
export const coverUrl = (coverArt: string, size = 120) =>
|
||||||
|
`/api/discover/cover/${encodeURIComponent(coverArt)}?size=${size}`;
|
||||||
|
export const streamUrl = (songId: string) => `/api/discover/stream/${encodeURIComponent(songId)}`;
|
||||||
|
export const youtubeUrl = (suggestionId: string) => `/api/discover/youtube/${suggestionId}`;
|
||||||
|
|
||||||
|
/** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */
|
||||||
|
export const mixTitle = (mix: MixSummary) =>
|
||||||
|
(mix.name ?? mix.tags.join(" / ")).replace(/^mix:\s*/i, "");
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
type P = { size?: number };
|
||||||
|
const svg = (path: JSX.Element, size = 18) => (
|
||||||
|
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}
|
||||||
|
strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{path}</svg>
|
||||||
|
);
|
||||||
|
export const Play = ({ size }: P) => svg(<path d="M7 4.5v15l12-7.5z" fill="currentColor" stroke="none" />, size);
|
||||||
|
export const Pause = ({ size }: P) => svg(<><rect x="6" y="5" width="4" height="14" rx="1" fill="currentColor" stroke="none" /><rect x="14" y="5" width="4" height="14" rx="1" fill="currentColor" stroke="none" /></>, size);
|
||||||
|
export const Next = ({ size }: P) => svg(<><path d="M5 5v14l10-7z" fill="currentColor" stroke="none" /><path d="M18 5v14" /></>, size);
|
||||||
|
export const Prev = ({ size }: P) => svg(<><path d="M19 5v14L9 12z" fill="currentColor" stroke="none" /><path d="M6 5v14" /></>, size);
|
||||||
|
export const Heart = ({ size, filled }: P & { filled?: boolean }) => svg(<path d="M12 20s-7-4.4-9.2-8.6C1.2 8.3 3 4.5 6.6 4.5c2.1 0 3.6 1.2 5.4 3.2 1.8-2 3.3-3.2 5.4-3.2 3.6 0 5.4 3.8 3.8 6.9C19 15.6 12 20 12 20z" fill={filled ? "currentColor" : "none"} />, size);
|
||||||
|
export const Close = ({ size }: P) => svg(<path d="M6 6l12 12M18 6L6 18" />, size);
|
||||||
|
export const External = ({ size }: P) => svg(<><path d="M14 4h6v6" /><path d="M20 4l-9 9" /><path d="M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5" /></>, size);
|
||||||
|
export const Refresh = ({ size }: P) => svg(<><path d="M20 11a8 8 0 1 0-2.3 5.7" /><path d="M20 4v7h-7" /></>, size);
|
||||||
|
export const Sparkle = ({ size }: P) => svg(<path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z" fill="currentColor" stroke="none" />, size);
|
||||||
|
export const Library = ({ size }: P) => svg(<><path d="M4 4v16M9 4v16" /><path d="M14 5l5 14" /></>, size);
|
||||||
|
export const Shuffle = ({ size }: P) => svg(<><path d="M4 7h3c4 0 6 10 10 10h3" /><path d="M4 17h3c1.6 0 2.8-1.6 3.9-3.6M13.1 9.6C14.2 8 15.4 7 17 7h3" /><path d="M18 4l3 3-3 3M18 14l3 3-3 3" /></>, size);
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import { App } from "./App";
|
||||||
|
import "./styles.css";
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
);
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { coverUrl, Song, streamUrl, Suggestion, youtubeUrl } from "./api";
|
||||||
|
|
||||||
|
export type QueueItem = {
|
||||||
|
key: string;
|
||||||
|
source: "library" | "youtube";
|
||||||
|
src: string;
|
||||||
|
title: string;
|
||||||
|
artist: string;
|
||||||
|
album?: string | null;
|
||||||
|
cover?: string | null;
|
||||||
|
suggestionId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const fromSong = (song: Song): QueueItem => ({
|
||||||
|
key: `song:${song.id}`,
|
||||||
|
source: "library",
|
||||||
|
src: streamUrl(song.id),
|
||||||
|
title: song.title,
|
||||||
|
artist: song.artist,
|
||||||
|
album: song.album,
|
||||||
|
cover: song.coverArt ? coverUrl(song.coverArt, 300) : null,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const fromSuggestion = (s: Suggestion): QueueItem => ({
|
||||||
|
key: `suggestion:${s.id}`,
|
||||||
|
source: "youtube",
|
||||||
|
src: youtubeUrl(s.id),
|
||||||
|
title: s.title,
|
||||||
|
artist: s.artist,
|
||||||
|
album: s.release,
|
||||||
|
cover: s.cover_url,
|
||||||
|
suggestionId: s.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Spread new songs evenly through the library songs */
|
||||||
|
export function interleave(library: QueueItem[], fresh: QueueItem[]): QueueItem[] {
|
||||||
|
if (fresh.length === 0) return library;
|
||||||
|
const out: QueueItem[] = [];
|
||||||
|
const every = Math.max(1, Math.round((library.length + fresh.length) / fresh.length));
|
||||||
|
let l = 0;
|
||||||
|
let f = 0;
|
||||||
|
for (let i = 0; l < library.length || f < fresh.length; i++) {
|
||||||
|
const takeFresh = (i % every === every - 1 && f < fresh.length) || l >= library.length;
|
||||||
|
out.push(takeFresh ? fresh[f++] : library[l++]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,824 @@
|
|||||||
|
:root {
|
||||||
|
--bg: #f6f5f2;
|
||||||
|
--surface: #ffffff;
|
||||||
|
--surface-2: #efede8;
|
||||||
|
--border: #e2dfd8;
|
||||||
|
--text: #1d1b18;
|
||||||
|
--muted: #6d675e;
|
||||||
|
--accent: #5b3df5;
|
||||||
|
--accent-text: #ffffff;
|
||||||
|
--youtube: #d4351c;
|
||||||
|
--library: #2f7d4f;
|
||||||
|
--heart: #e0245e;
|
||||||
|
--shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 6%);
|
||||||
|
--art-l: 62%;
|
||||||
|
--art-s: 70%;
|
||||||
|
--radius: 12px;
|
||||||
|
font-family: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1.45;
|
||||||
|
color: var(--text);
|
||||||
|
background: var(--bg);
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
--bg: #121214;
|
||||||
|
--surface: #1b1b1f;
|
||||||
|
--surface-2: #26262b;
|
||||||
|
--border: #2e2e34;
|
||||||
|
--text: #f1f0ee;
|
||||||
|
--muted: #a09d98;
|
||||||
|
--accent: #8b74ff;
|
||||||
|
--accent-text: #120d26;
|
||||||
|
--youtube: #ff6b52;
|
||||||
|
--library: #5fcf8d;
|
||||||
|
--heart: #ff5c8a;
|
||||||
|
--shadow: 0 1px 2px rgb(0 0 0 / 30%), 0 8px 24px rgb(0 0 0 / 30%);
|
||||||
|
--art-l: 45%;
|
||||||
|
--art-s: 55%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
button,
|
||||||
|
select,
|
||||||
|
input {
|
||||||
|
font: inherit;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
:focus-visible {
|
||||||
|
outline: 2px solid var(--accent);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- layout ---------- */
|
||||||
|
|
||||||
|
.app {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 272px minmax(0, 1fr);
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
height: 100vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 20px 12px;
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
.with-player .sidebar {
|
||||||
|
height: calc(100vh - 84px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
padding: 28px clamp(16px, 4vw, 48px) 48px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.with-player .content {
|
||||||
|
padding-bottom: 120px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 0 10px 16px;
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 1.15rem;
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-mark {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rule-select {
|
||||||
|
width: calc(100% - 20px);
|
||||||
|
margin: 0 10px 8px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--surface-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rule-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin: 0 0 8px;
|
||||||
|
padding: 0 4px 0 10px;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-list a {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border-radius: 8px;
|
||||||
|
text-decoration: none;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-list a:hover {
|
||||||
|
background: var(--surface-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-list a.selected {
|
||||||
|
background: hsl(var(--hue) var(--art-s) var(--art-l) / 18%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-dot {
|
||||||
|
flex: none;
|
||||||
|
width: 12px;
|
||||||
|
height: 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: linear-gradient(135deg, hsl(var(--hue) var(--art-s) var(--art-l)), hsl(calc(var(--hue) + 40) var(--art-s) calc(var(--art-l) - 12%)));
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-dot.heart {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
background: none;
|
||||||
|
color: var(--heart);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-name {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
font-size: 0.93rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.count {
|
||||||
|
flex: none;
|
||||||
|
min-width: 22px;
|
||||||
|
padding: 1px 7px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-text);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 600;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.liked-link {
|
||||||
|
margin-top: 10px;
|
||||||
|
padding-top: 10px;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- mix header ---------- */
|
||||||
|
|
||||||
|
.mix-header {
|
||||||
|
display: flex;
|
||||||
|
gap: 28px;
|
||||||
|
align-items: flex-end;
|
||||||
|
margin-bottom: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-art {
|
||||||
|
flex: none;
|
||||||
|
display: grid;
|
||||||
|
place-items: end start;
|
||||||
|
width: 200px;
|
||||||
|
height: 200px;
|
||||||
|
padding: 18px;
|
||||||
|
border-radius: 16px;
|
||||||
|
background:
|
||||||
|
radial-gradient(circle at 80% 15%, hsl(calc(var(--hue) + 60) 90% 75% / 70%), transparent 55%),
|
||||||
|
linear-gradient(135deg, hsl(var(--hue) var(--art-s) var(--art-l)), hsl(calc(var(--hue) + 40) var(--art-s) calc(var(--art-l) - 18%)));
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
font-weight: 800;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
line-height: 1.1;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
text-shadow: 0 1px 8px rgb(0 0 0 / 25%);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.liked-view .mix-art {
|
||||||
|
place-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-info {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.eyebrow {
|
||||||
|
margin: 0 0 4px;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.78rem;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0 0 12px;
|
||||||
|
font-size: clamp(1.6rem, 3.4vw, 2.6rem);
|
||||||
|
line-height: 1.1;
|
||||||
|
letter-spacing: -0.025em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tags {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
margin: 0 0 12px;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tags li {
|
||||||
|
padding: 2px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: hsl(var(--hue) var(--art-s) var(--art-l) / 16%);
|
||||||
|
font-size: 0.82rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-counts {
|
||||||
|
margin: 0 0 16px;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-buttons {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-buttons button {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 9px 16px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--surface);
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-buttons button.primary {
|
||||||
|
border-color: transparent;
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-buttons button:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- track lists ---------- */
|
||||||
|
|
||||||
|
section + section {
|
||||||
|
margin-top: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin: 0 0 8px;
|
||||||
|
font-size: 1.05rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tracks {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 36px 44px minmax(0, 1fr) auto auto auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track:hover,
|
||||||
|
.track.active {
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
.track.active {
|
||||||
|
box-shadow: inset 3px 0 0 var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-play {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: none;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-icon {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track:hover .track-number,
|
||||||
|
.track.active .track-number {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track:hover .track-icon,
|
||||||
|
.track.active .track-icon,
|
||||||
|
.track-play:focus-visible .track-icon {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-play:focus-visible .track-number {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-number {
|
||||||
|
color: var(--muted);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cover {
|
||||||
|
position: relative;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--surface-2);
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cover img {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-text {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-title,
|
||||||
|
.track-sub {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-title {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track.active .track-title {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-sub {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.88rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.match {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.82rem;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-duration {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-button {
|
||||||
|
display: inline-grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 34px;
|
||||||
|
height: 34px;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: none;
|
||||||
|
color: var(--muted);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-button.small {
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-button:hover {
|
||||||
|
background: var(--surface-2);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-button.liked {
|
||||||
|
color: var(--heart);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- player ---------- */
|
||||||
|
|
||||||
|
.player {
|
||||||
|
position: fixed;
|
||||||
|
inset: auto 0 0 0;
|
||||||
|
z-index: 10;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr) minmax(0, 1fr);
|
||||||
|
align-items: center;
|
||||||
|
gap: 20px;
|
||||||
|
height: 84px;
|
||||||
|
padding: 0 20px;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
background: color-mix(in srgb, var(--surface) 92%, transparent);
|
||||||
|
backdrop-filter: blur(12px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-track {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
flex: none;
|
||||||
|
padding: 1px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid currentColor;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge.youtube {
|
||||||
|
color: var(--youtube);
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge.library {
|
||||||
|
color: var(--library);
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-main {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-buttons {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.play-button {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--text);
|
||||||
|
color: var(--bg);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-progress {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
width: 100%;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-progress span {
|
||||||
|
width: 38px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-progress input {
|
||||||
|
flex: 1;
|
||||||
|
height: 4px;
|
||||||
|
appearance: none;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: linear-gradient(to right, var(--accent) var(--progress), var(--border) var(--progress));
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-progress input::-webkit-slider-thumb {
|
||||||
|
appearance: none;
|
||||||
|
width: 12px;
|
||||||
|
height: 12px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-progress input::-moz-range-thumb {
|
||||||
|
width: 12px;
|
||||||
|
height: 12px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-status {
|
||||||
|
position: absolute;
|
||||||
|
top: -26px;
|
||||||
|
padding: 2px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--surface-2);
|
||||||
|
font-size: 0.78rem;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-status.error {
|
||||||
|
color: var(--youtube);
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-queue {
|
||||||
|
justify-self: end;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- feedback ---------- */
|
||||||
|
|
||||||
|
.spinner {
|
||||||
|
display: inline-block;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
border: 2px solid var(--border);
|
||||||
|
border-top-color: var(--accent);
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: spin 0.8s linear infinite;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner.light {
|
||||||
|
border-color: color-mix(in srgb, var(--bg) 35%, transparent);
|
||||||
|
border-top-color: var(--bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.bars {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
gap: 2px;
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bars i {
|
||||||
|
width: 3px;
|
||||||
|
background: var(--accent);
|
||||||
|
animation: bar 0.9s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bars i:nth-child(2) {
|
||||||
|
animation-delay: -0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bars i:nth-child(3) {
|
||||||
|
animation-delay: -0.6s;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes bar {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
height: 30%;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.bars i,
|
||||||
|
.spinner {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.notice {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
padding: 16px 20px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
.notice.error {
|
||||||
|
border-color: var(--youtube);
|
||||||
|
color: var(--youtube);
|
||||||
|
}
|
||||||
|
|
||||||
|
.notice pre {
|
||||||
|
overflow-x: auto;
|
||||||
|
margin: 0;
|
||||||
|
padding: 12px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--surface-2);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast {
|
||||||
|
position: fixed;
|
||||||
|
left: 50%;
|
||||||
|
bottom: 104px;
|
||||||
|
z-index: 20;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
max-width: calc(100vw - 32px);
|
||||||
|
padding: 10px 16px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--text);
|
||||||
|
color: var(--bg);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
transform: translateX(-50%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.app:not(.with-player) .toast {
|
||||||
|
bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast button {
|
||||||
|
border: 0;
|
||||||
|
background: none;
|
||||||
|
color: var(--accent);
|
||||||
|
font-weight: 700;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- small screens ---------- */
|
||||||
|
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.app {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar,
|
||||||
|
.with-player .sidebar {
|
||||||
|
position: static;
|
||||||
|
height: auto;
|
||||||
|
padding: 14px 16px 10px;
|
||||||
|
border-right: 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand {
|
||||||
|
padding: 0 0 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rule-info {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-list {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin: 0 -16px;
|
||||||
|
padding: 0 16px 4px;
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-list a {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 6px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-name {
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
.liked-link {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
padding: 20px 16px 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-header {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mix-art {
|
||||||
|
width: 100%;
|
||||||
|
height: 140px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track {
|
||||||
|
grid-template-columns: 32px 40px minmax(0, 1fr) auto;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 6px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.track-meta,
|
||||||
|
.track-duration,
|
||||||
|
.track-album {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player {
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
height: auto;
|
||||||
|
padding: 10px 16px;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-main {
|
||||||
|
flex-direction: row-reverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-progress,
|
||||||
|
.player-queue,
|
||||||
|
.player .badge {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.player-status {
|
||||||
|
right: 0;
|
||||||
|
top: -38px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.with-player .content {
|
||||||
|
padding-bottom: 110px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import { QueueItem } from "./queue";
|
||||||
|
|
||||||
|
export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error";
|
||||||
|
|
||||||
|
export type Player = ReturnType<typeof usePlayer>;
|
||||||
|
|
||||||
|
export function usePlayer(onError: (item: QueueItem) => void) {
|
||||||
|
const audio = useRef<HTMLAudioElement | null>(null);
|
||||||
|
if (audio.current === null && typeof Audio !== "undefined") {
|
||||||
|
audio.current = new Audio();
|
||||||
|
audio.current.preload = "auto";
|
||||||
|
}
|
||||||
|
|
||||||
|
const [queue, setQueue] = useState<QueueItem[]>([]);
|
||||||
|
const [index, setIndex] = useState(-1);
|
||||||
|
const [status, setStatus] = useState<PlayerStatus>("idle");
|
||||||
|
const [time, setTime] = useState(0);
|
||||||
|
const [duration, setDuration] = useState(0);
|
||||||
|
const current = index >= 0 ? queue[index] : undefined;
|
||||||
|
|
||||||
|
// keep the latest values for the audio element's event handlers
|
||||||
|
const state = useRef({ queue, index, onError });
|
||||||
|
state.current = { queue, index, onError };
|
||||||
|
|
||||||
|
const playAt = useCallback((items: QueueItem[], at: number) => {
|
||||||
|
setQueue(items);
|
||||||
|
setIndex(at);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const next = useCallback(() => {
|
||||||
|
const { queue, index } = state.current;
|
||||||
|
if (index + 1 < queue.length) setIndex(index + 1);
|
||||||
|
else {
|
||||||
|
audio.current?.pause();
|
||||||
|
setStatus("paused");
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const previous = useCallback(() => {
|
||||||
|
const el = audio.current;
|
||||||
|
if (el && el.currentTime > 3) el.currentTime = 0;
|
||||||
|
else setIndex((i) => Math.max(0, i - 1));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const toggle = useCallback(() => {
|
||||||
|
const el = audio.current;
|
||||||
|
if (!el || !state.current.queue.length) return;
|
||||||
|
if (el.paused) void el.play().catch(() => undefined);
|
||||||
|
else el.pause();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const seek = useCallback((seconds: number) => {
|
||||||
|
if (!audio.current) return;
|
||||||
|
audio.current.currentTime = seconds;
|
||||||
|
// update now, or the controlled slider snaps back and its change event seeks back too
|
||||||
|
setTime(seconds);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// load the current item
|
||||||
|
useEffect(() => {
|
||||||
|
const el = audio.current;
|
||||||
|
if (!el || !current) return;
|
||||||
|
setTime(0);
|
||||||
|
setDuration(0);
|
||||||
|
setStatus("loading");
|
||||||
|
el.src = current.src;
|
||||||
|
void el.play().catch(() => undefined);
|
||||||
|
}, [current?.key]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = audio.current;
|
||||||
|
if (!el) return;
|
||||||
|
let errorTimer: number | undefined;
|
||||||
|
const handlers: Record<string, () => void> = {
|
||||||
|
playing: () => setStatus("playing"),
|
||||||
|
pause: () => setStatus((s) => (s === "error" ? s : "paused")),
|
||||||
|
waiting: () => setStatus("loading"),
|
||||||
|
timeupdate: () => setTime(el.currentTime),
|
||||||
|
durationchange: () => setDuration(Number.isFinite(el.duration) ? el.duration : 0),
|
||||||
|
ended: () => next(),
|
||||||
|
error: () => {
|
||||||
|
if (!el.src) return;
|
||||||
|
setStatus("error");
|
||||||
|
const { queue, index, onError } = state.current;
|
||||||
|
if (queue[index]) onError(queue[index]);
|
||||||
|
errorTimer = window.setTimeout(next, 1500);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
for (const [event, handler] of Object.entries(handlers)) el.addEventListener(event, handler);
|
||||||
|
return () => {
|
||||||
|
window.clearTimeout(errorTimer);
|
||||||
|
for (const [event, handler] of Object.entries(handlers)) el.removeEventListener(event, handler);
|
||||||
|
};
|
||||||
|
}, [next]);
|
||||||
|
|
||||||
|
// OS media controls and keyboard
|
||||||
|
useEffect(() => {
|
||||||
|
if (!("mediaSession" in navigator) || !current) return;
|
||||||
|
navigator.mediaSession.metadata = new MediaMetadata({
|
||||||
|
title: current.title,
|
||||||
|
artist: current.artist,
|
||||||
|
album: current.album ?? undefined,
|
||||||
|
artwork: current.cover ? [{ src: current.cover }] : [],
|
||||||
|
});
|
||||||
|
navigator.mediaSession.setActionHandler("play", toggle);
|
||||||
|
navigator.mediaSession.setActionHandler("pause", toggle);
|
||||||
|
navigator.mediaSession.setActionHandler("nexttrack", next);
|
||||||
|
navigator.mediaSession.setActionHandler("previoustrack", previous);
|
||||||
|
}, [current, toggle, next, previous]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
const target = e.target as HTMLElement;
|
||||||
|
if (e.code !== "Space" || ["INPUT", "TEXTAREA", "BUTTON"].includes(target.tagName)) return;
|
||||||
|
e.preventDefault();
|
||||||
|
toggle();
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [toggle]);
|
||||||
|
|
||||||
|
return { queue, index, current, status, time, duration, playAt, next, previous, toggle, seek };
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true
|
||||||
|
},
|
||||||
|
"include": ["src", "vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
|
||||||
|
// During development, API requests go to playlistd (PLAYLISTD_URL, default localhost:8000)
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
proxy: {
|
||||||
|
"/api": process.env.PLAYLISTD_URL ?? "http://localhost:8000",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -13,3 +13,17 @@ interval = 240
|
|||||||
[database]
|
[database]
|
||||||
# URL of database to use
|
# URL of database to use
|
||||||
url = "postgres:///navidrome-playlists"
|
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
|
||||||
|
# token = ""
|
||||||
|
|
||||||
|
[discover]
|
||||||
|
# Directory with the built discover UI (discover/dist) to serve at /
|
||||||
|
# ui = "/usr/share/playlistd/discover"
|
||||||
|
# yt-dlp binary used to play suggested songs that aren't in your library
|
||||||
|
# ytdlp = "yt-dlp"
|
||||||
|
# Format to ask Subsonic to stream in ("raw" = no transcoding), e.g. "mp3" if your
|
||||||
|
# library has files browsers can't play
|
||||||
|
# format = "raw"
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
ALTER TABLE "cluster_mix_rule"
|
||||||
|
ADD COLUMN discovery_count INT NOT NULL DEFAULT 15; -- New songs to suggest per mix
|
||||||
|
|
||||||
|
ALTER TABLE "cluster_mix_playlist"
|
||||||
|
ADD COLUMN name VARCHAR(250), -- Name of the playlist in subsonic
|
||||||
|
ADD COLUMN position INT NOT NULL DEFAULT 0; -- Order of the mix, most listened first
|
||||||
|
|
||||||
|
-- Songs not in the library, recommended by Listenbrainz and matched to a mix by genre
|
||||||
|
CREATE TABLE "mix_suggestion"
|
||||||
|
(
|
||||||
|
id UUID NOT NULL PRIMARY KEY,
|
||||||
|
rule_id UUID NOT NULL REFERENCES "cluster_mix_rule" (id) ON DELETE CASCADE,
|
||||||
|
mix_id UUID REFERENCES "cluster_mix_playlist" (id) ON DELETE SET NULL,
|
||||||
|
recording_mbid VARCHAR(36) NOT NULL,
|
||||||
|
title VARCHAR(500) NOT NULL,
|
||||||
|
artist VARCHAR(500) NOT NULL,
|
||||||
|
release VARCHAR(500),
|
||||||
|
cover_url TEXT,
|
||||||
|
score DOUBLE PRECISION NOT NULL,
|
||||||
|
status VARCHAR(16) NOT NULL DEFAULT 'new', -- new, liked or dismissed
|
||||||
|
youtube_id VARCHAR(32), -- Cached YouTube match
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (rule_id, recording_mbid)
|
||||||
|
);
|
||||||
+106
-13
@@ -1,4 +1,5 @@
|
|||||||
use crate::cluster::{self, ClusterOptions, Play};
|
use crate::cluster::{self, ClusterOptions, Play};
|
||||||
|
use crate::discover::{self, MixTarget};
|
||||||
use crate::listenbrainz;
|
use crate::listenbrainz;
|
||||||
use crate::mix::{self, ListenedTrack, MixOptions, RecentlyPlayed};
|
use crate::mix::{self, ListenedTrack, MixOptions, RecentlyPlayed};
|
||||||
use crate::models::{ClusterMixPlaylist, ClusterMixRule};
|
use crate::models::{ClusterMixPlaylist, ClusterMixRule};
|
||||||
@@ -8,7 +9,7 @@ use chrono::Utc;
|
|||||||
use rand::rngs::StdRng;
|
use rand::rngs::StdRng;
|
||||||
use rand::SeedableRng;
|
use rand::SeedableRng;
|
||||||
use sqlx::postgres::PgPool;
|
use sqlx::postgres::PgPool;
|
||||||
use std::collections::HashMap;
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::time::{interval, MissedTickBehavior};
|
use tokio::time::{interval, MissedTickBehavior};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
@@ -142,7 +143,7 @@ pub async fn build_mixes(
|
|||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
Some(mix) => mixes.push(mix),
|
Some(mix) => mixes.push((mix, cluster)),
|
||||||
None => println!(
|
None => println!(
|
||||||
"No library genres match cluster {:?}",
|
"No library genres match cluster {:?}",
|
||||||
cluster
|
cluster
|
||||||
@@ -157,7 +158,7 @@ pub async fn build_mixes(
|
|||||||
|
|
||||||
// two clusters can share their top genres
|
// two clusters can share their top genres
|
||||||
let mut seen_labels: HashMap<String, usize> = HashMap::new();
|
let mut seen_labels: HashMap<String, usize> = HashMap::new();
|
||||||
for mix in &mut mixes {
|
for (mix, _) in &mut mixes {
|
||||||
let n = seen_labels.entry(mix.label.clone()).or_default();
|
let n = seen_labels.entry(mix.label.clone()).or_default();
|
||||||
*n += 1;
|
*n += 1;
|
||||||
if *n > 1 {
|
if *n > 1 {
|
||||||
@@ -176,12 +177,17 @@ pub async fn build_mixes(
|
|||||||
|
|
||||||
let pairs = mix::match_mixes(
|
let pairs = mix::match_mixes(
|
||||||
&existing.iter().map(|p| p.tags.clone()).collect::<Vec<_>>(),
|
&existing.iter().map(|p| p.tags.clone()).collect::<Vec<_>>(),
|
||||||
&mixes.iter().map(|m| m.tags.clone()).collect::<Vec<_>>(),
|
&mixes
|
||||||
|
.iter()
|
||||||
|
.map(|(m, _)| m.tags.clone())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
);
|
);
|
||||||
let old_for_new: HashMap<usize, usize> = pairs.iter().map(|&(o, n)| (n, o)).collect();
|
let old_for_new: HashMap<usize, usize> = pairs.iter().map(|&(o, n)| (n, o)).collect();
|
||||||
|
|
||||||
for (n, mix) in mixes.iter().enumerate() {
|
let mut targets = vec![];
|
||||||
|
for (n, (mix, cluster)) in mixes.iter().enumerate() {
|
||||||
let name = rule.name_template.replace("{label}", &mix.label);
|
let name = rule.name_template.replace("{label}", &mix.label);
|
||||||
|
let position = n as i32;
|
||||||
|
|
||||||
let reused = match old_for_new.get(&n).map(|&o| &existing[o]) {
|
let reused = match old_for_new.get(&n).map(|&o| &existing[o]) {
|
||||||
// the playlist may have been deleted by hand since the last run
|
// the playlist may have been deleted by hand since the last run
|
||||||
@@ -190,13 +196,15 @@ pub async fn build_mixes(
|
|||||||
.rename_playlist(&old.playlist_id, &name)
|
.rename_playlist(&old.playlist_id, &name)
|
||||||
.await?;
|
.await?;
|
||||||
sqlx::query!(
|
sqlx::query!(
|
||||||
r#"UPDATE "cluster_mix_playlist" SET tags = $1 WHERE id = $2"#,
|
r#"UPDATE "cluster_mix_playlist" SET tags = $1, name = $2, position = $3 WHERE id = $4"#,
|
||||||
&mix.tags,
|
&mix.tags,
|
||||||
|
name,
|
||||||
|
position,
|
||||||
old.id
|
old.id
|
||||||
)
|
)
|
||||||
.execute(database)
|
.execute(database)
|
||||||
.await?;
|
.await?;
|
||||||
Some(old.playlist_id.clone())
|
Some((old.id, old.playlist_id.clone()))
|
||||||
}
|
}
|
||||||
Some(old) => {
|
Some(old) => {
|
||||||
sqlx::query!(
|
sqlx::query!(
|
||||||
@@ -210,25 +218,32 @@ pub async fn build_mixes(
|
|||||||
None => None,
|
None => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let playlist_id = match reused {
|
let (mix_id, playlist_id) = match reused {
|
||||||
Some(id) => id,
|
Some(ids) => ids,
|
||||||
None => {
|
None => {
|
||||||
let playlist = media_client.create_playlist(&name).await?;
|
let playlist = media_client.create_playlist(&name).await?;
|
||||||
|
let mix_id = Uuid::new_v4();
|
||||||
sqlx::query!(
|
sqlx::query!(
|
||||||
r#"
|
r#"
|
||||||
INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags)
|
INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags, name, position)
|
||||||
VALUES ($1, $2, $3, $4)
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
"#,
|
"#,
|
||||||
Uuid::new_v4(),
|
mix_id,
|
||||||
rule.id,
|
rule.id,
|
||||||
playlist.id,
|
playlist.id,
|
||||||
&mix.tags,
|
&mix.tags,
|
||||||
|
name,
|
||||||
|
position,
|
||||||
)
|
)
|
||||||
.execute(database)
|
.execute(database)
|
||||||
.await?;
|
.await?;
|
||||||
playlist.id
|
(mix_id, playlist.id)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
targets.push(MixTarget {
|
||||||
|
mix_id,
|
||||||
|
profile: cluster.profile.clone(),
|
||||||
|
});
|
||||||
|
|
||||||
media_client
|
media_client
|
||||||
.replace_playlist_songs(&playlist_id, mix.song_ids.clone())
|
.replace_playlist_songs(&playlist_id, mix.song_ids.clone())
|
||||||
@@ -252,6 +267,17 @@ pub async fn build_mixes(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- songs that aren't in the library ----
|
||||||
|
// a failure here shouldn't stop the mixes from being marked as built
|
||||||
|
if let Err(e) =
|
||||||
|
save_suggestions(media_client, &rule, &targets, &recently_played, database).await
|
||||||
|
{
|
||||||
|
println!(
|
||||||
|
"Could not find new songs for {}: {:?}",
|
||||||
|
rule.tracking_user, e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
sqlx::query!(
|
sqlx::query!(
|
||||||
r#"UPDATE "cluster_mix_rule" SET last_run = NOW() WHERE id = $1"#,
|
r#"UPDATE "cluster_mix_rule" SET last_run = NOW() WHERE id = $1"#,
|
||||||
rule.id
|
rule.id
|
||||||
@@ -261,3 +287,70 @@ pub async fn build_mixes(
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn save_suggestions(
|
||||||
|
media_client: &Subsonic,
|
||||||
|
rule: &ClusterMixRule,
|
||||||
|
targets: &[MixTarget],
|
||||||
|
recently_played: &RecentlyPlayed,
|
||||||
|
database: &PgPool,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
// liked and dismissed suggestions stay as they are
|
||||||
|
let exclude: HashSet<String> = sqlx::query_scalar!(
|
||||||
|
r#"SELECT recording_mbid FROM "mix_suggestion" WHERE rule_id = $1 AND status <> 'new'"#,
|
||||||
|
rule.id
|
||||||
|
)
|
||||||
|
.fetch_all(database)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let suggestions = discover::suggest(
|
||||||
|
media_client,
|
||||||
|
&rule.tracking_user,
|
||||||
|
targets,
|
||||||
|
recently_played,
|
||||||
|
&exclude,
|
||||||
|
rule.discovery_count.max(0) as usize,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
for s in &suggestions {
|
||||||
|
sqlx::query!(
|
||||||
|
r#"
|
||||||
|
INSERT INTO "mix_suggestion" (id, rule_id, mix_id, recording_mbid, title, artist, release, cover_url, score)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||||
|
ON CONFLICT (rule_id, recording_mbid) DO UPDATE
|
||||||
|
SET mix_id = EXCLUDED.mix_id, score = EXCLUDED.score, title = EXCLUDED.title,
|
||||||
|
artist = EXCLUDED.artist, release = EXCLUDED.release, cover_url = EXCLUDED.cover_url
|
||||||
|
"#,
|
||||||
|
Uuid::new_v4(),
|
||||||
|
rule.id,
|
||||||
|
s.mix_id,
|
||||||
|
s.mbid,
|
||||||
|
s.info.title,
|
||||||
|
s.info.artist,
|
||||||
|
s.info.release,
|
||||||
|
s.info.cover_url,
|
||||||
|
s.score,
|
||||||
|
)
|
||||||
|
.execute(database)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// drop untouched suggestions from previous runs
|
||||||
|
let kept: Vec<String> = suggestions.iter().map(|s| s.mbid.clone()).collect();
|
||||||
|
sqlx::query!(
|
||||||
|
r#"
|
||||||
|
DELETE FROM "mix_suggestion"
|
||||||
|
WHERE rule_id = $1 AND status = 'new' AND NOT (recording_mbid = ANY($2))
|
||||||
|
"#,
|
||||||
|
rule.id,
|
||||||
|
&kept,
|
||||||
|
)
|
||||||
|
.execute(database)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
println!(" {} new songs suggested", suggestions.len());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
+210
@@ -0,0 +1,210 @@
|
|||||||
|
//! 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 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.
|
||||||
|
|
||||||
|
use crate::listenbrainz::{self, RecordingInfo};
|
||||||
|
use crate::mix::{name_key, normalize, RecentlyPlayed};
|
||||||
|
use crate::subsonic::Subsonic;
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// Candidates must fit a mix at least this well (cosine similarity of genres)
|
||||||
|
const MIN_FIT: f64 = 0.2;
|
||||||
|
/// Most suggestions per artist in one mix
|
||||||
|
const PER_ARTIST: usize = 2;
|
||||||
|
/// Recommendations to request from Listenbrainz
|
||||||
|
const RECOMMENDATIONS: usize = 1000;
|
||||||
|
/// Genres per LB Radio prompt
|
||||||
|
const RADIO_GENRES: usize = 3;
|
||||||
|
|
||||||
|
pub struct MixTarget {
|
||||||
|
pub mix_id: Uuid,
|
||||||
|
/// The mix's genres (as in the cluster profile, best first) and their weights
|
||||||
|
pub profile: Vec<(String, f64)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Suggestion {
|
||||||
|
pub mix_id: Uuid,
|
||||||
|
pub mbid: String,
|
||||||
|
pub info: RecordingInfo,
|
||||||
|
pub score: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cosine similarity between a recording's genres and a mix profile
|
||||||
|
fn fit(genres: &HashMap<String, f64>, profile: &HashMap<String, f64>, profile_norm: f64) -> f64 {
|
||||||
|
let (mut dot, mut norm) = (0.0, 0.0);
|
||||||
|
for (genre, w) in genres {
|
||||||
|
norm += w * w;
|
||||||
|
if let Some(p) = profile.get(&normalize(genre)) {
|
||||||
|
dot += w * p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if norm == 0.0 || profile_norm == 0.0 {
|
||||||
|
0.0
|
||||||
|
} else {
|
||||||
|
dot / (norm.sqrt() * profile_norm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn suggest(
|
||||||
|
client: &Subsonic,
|
||||||
|
user: &str,
|
||||||
|
targets: &[MixTarget],
|
||||||
|
recently_played: &RecentlyPlayed,
|
||||||
|
// recordings that already have a suggestion the user acted on
|
||||||
|
exclude: &HashSet<String>,
|
||||||
|
per_mix: usize,
|
||||||
|
) -> Result<Vec<Suggestion>, Box<dyn std::error::Error>> {
|
||||||
|
if targets.is_empty() || per_mix == 0 {
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- candidates ----
|
||||||
|
let mut candidates: Vec<String> = listenbrainz::recommendations(user, RECOMMENDATIONS)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|r| r.latest_listened_at.is_none())
|
||||||
|
.map(|r| r.recording_mbid)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if let Some(token) = listenbrainz::token() {
|
||||||
|
for target in targets {
|
||||||
|
let genres: Vec<&str> = target
|
||||||
|
.profile
|
||||||
|
.iter()
|
||||||
|
.take(RADIO_GENRES)
|
||||||
|
.map(|(g, _)| g.as_str())
|
||||||
|
.collect();
|
||||||
|
// LB Radio prompts can't contain these
|
||||||
|
if genres.iter().any(|g| g.contains([',', '(', ')', ':'])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let prompt = format!("tag:({})::or", genres.join(", "));
|
||||||
|
match listenbrainz::radio(&prompt, "medium", &token).await {
|
||||||
|
Ok(mbids) => candidates.extend(mbids),
|
||||||
|
Err(e) => println!("LB Radio failed for {}: {:?}", prompt, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
candidates.retain(|m| !exclude.contains(m) && seen.insert(m.clone()));
|
||||||
|
let metadata = listenbrainz::recording_metadata(&candidates).await?;
|
||||||
|
|
||||||
|
// ---- assign each candidate to the mix it fits best ----
|
||||||
|
let profiles: Vec<(HashMap<String, f64>, f64)> = targets
|
||||||
|
.iter()
|
||||||
|
.map(|t| {
|
||||||
|
let mut p: HashMap<String, f64> = HashMap::new();
|
||||||
|
for (genre, w) in &t.profile {
|
||||||
|
*p.entry(normalize(genre)).or_default() += w;
|
||||||
|
}
|
||||||
|
let norm = p.values().map(|w| w * w).sum::<f64>().sqrt();
|
||||||
|
(p, norm)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut per_target: Vec<Vec<(f64, &String, &RecordingInfo)>> = vec![vec![]; targets.len()];
|
||||||
|
for (mbid, info) in &metadata {
|
||||||
|
if info.title.is_empty()
|
||||||
|
|| recently_played.contains_recording(Some(mbid), &info.artist, &info.title)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let best = profiles
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, (p, n))| (i, fit(&info.genres, p, *n)))
|
||||||
|
.max_by(|a, b| a.1.total_cmp(&b.1));
|
||||||
|
if let Some((i, score)) = best {
|
||||||
|
if score >= MIN_FIT {
|
||||||
|
per_target[i].push((score, mbid, info));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- pick the best per mix, skipping songs already in the library ----
|
||||||
|
let mut suggestions = vec![];
|
||||||
|
let mut seen_names: HashSet<String> = HashSet::new();
|
||||||
|
for (target, mut found) in targets.iter().zip(per_target) {
|
||||||
|
found.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(b.1)));
|
||||||
|
let mut artists: HashMap<String, usize> = HashMap::new();
|
||||||
|
let mut taken = 0;
|
||||||
|
|
||||||
|
for (score, mbid, info) in found {
|
||||||
|
if taken >= per_mix {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let artist_count = artists.entry(normalize(&info.artist)).or_default();
|
||||||
|
if *artist_count >= PER_ARTIST
|
||||||
|
|| seen_names.contains(&name_key(&info.artist, &info.title))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if in_library(client, mbid, info).await? {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
*artist_count += 1;
|
||||||
|
taken += 1;
|
||||||
|
seen_names.insert(name_key(&info.artist, &info.title));
|
||||||
|
suggestions.push(Suggestion {
|
||||||
|
mix_id: target.mix_id,
|
||||||
|
mbid: mbid.clone(),
|
||||||
|
info: RecordingInfo {
|
||||||
|
title: info.title.clone(),
|
||||||
|
artist: info.artist.clone(),
|
||||||
|
release: info.release.clone(),
|
||||||
|
cover_url: info.cover_url.clone(),
|
||||||
|
genres: HashMap::new(),
|
||||||
|
},
|
||||||
|
score,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(suggestions)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn in_library(
|
||||||
|
client: &Subsonic,
|
||||||
|
mbid: &str,
|
||||||
|
info: &RecordingInfo,
|
||||||
|
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||||
|
if !client.song_search(mbid.to_string()).await?.is_empty() {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
let key = name_key(&info.artist, &info.title);
|
||||||
|
Ok(client
|
||||||
|
.song_search(format!("{} {}", info.title, info.artist))
|
||||||
|
.await?
|
||||||
|
.iter()
|
||||||
|
.any(|s| name_key(&s.artist, &s.title) == key))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fit_prefers_matching_genres() {
|
||||||
|
let profile: HashMap<String, f64> =
|
||||||
|
[("mathcore".to_string(), 2.0), ("mathrock".to_string(), 1.0)].into();
|
||||||
|
let norm = 5f64.sqrt();
|
||||||
|
let math: HashMap<String, f64> = [
|
||||||
|
("Mathcore".to_string(), 1.0),
|
||||||
|
("math rock".to_string(), 1.0),
|
||||||
|
]
|
||||||
|
.into();
|
||||||
|
let folk: HashMap<String, f64> = [("folk".to_string(), 1.0)].into();
|
||||||
|
|
||||||
|
assert!(fit(&math, &profile, norm) > 0.9);
|
||||||
|
assert_eq!(fit(&folk, &profile, norm), 0.0);
|
||||||
|
assert_eq!(fit(&HashMap::new(), &profile, norm), 0.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
+176
-8
@@ -239,10 +239,32 @@ pub async fn listens_since(user: impl Display, min_ts: i64) -> Result<Vec<Listen
|
|||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
#[derive(Deserialize, Default)]
|
||||||
struct RecordingMetadata {
|
struct RecordingMetadata {
|
||||||
|
#[serde(default)]
|
||||||
|
recording: Option<Named>,
|
||||||
|
#[serde(default)]
|
||||||
|
artist: Option<Named>,
|
||||||
|
#[serde(default)]
|
||||||
|
release: Option<Release>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
tag: Option<RecordingTags>,
|
tag: Option<RecordingTags>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct Named {
|
||||||
|
#[serde(default)]
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct Release {
|
||||||
|
#[serde(default)]
|
||||||
|
name: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
caa_id: Option<i64>,
|
||||||
|
#[serde(default)]
|
||||||
|
caa_release_mbid: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
#[derive(Deserialize, Default)]
|
||||||
struct RecordingTags {
|
struct RecordingTags {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -263,11 +285,21 @@ struct Tag {
|
|||||||
genre_mbid: Option<String>,
|
genre_mbid: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Weighted MusicBrainz genres for each recording, combining the recording's own genres (most
|
pub struct RecordingInfo {
|
||||||
/// specific) with those of its release group and artists (broadest). Names are lowercased.
|
pub title: String,
|
||||||
pub async fn recording_tags(
|
pub artist: String,
|
||||||
|
pub release: Option<String>,
|
||||||
|
/// Front cover from the Cover Art Archive, if there is one
|
||||||
|
pub cover_url: Option<String>,
|
||||||
|
/// Weighted MusicBrainz genres, combining the recording's own genres (most specific) with
|
||||||
|
/// those of its release group and artists (broadest). Names are lowercased.
|
||||||
|
pub genres: HashMap<String, f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Names, cover art and genres of recordings
|
||||||
|
pub async fn recording_metadata(
|
||||||
mbids: &[String],
|
mbids: &[String],
|
||||||
) -> Result<HashMap<String, HashMap<String, f64>>, reqwest::Error> {
|
) -> Result<HashMap<String, RecordingInfo>, reqwest::Error> {
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let mut out = HashMap::new();
|
let mut out = HashMap::new();
|
||||||
|
|
||||||
@@ -282,8 +314,8 @@ pub async fn recording_tags(
|
|||||||
let metadata = send_json::<HashMap<String, RecordingMetadata>>(request).await?;
|
let metadata = send_json::<HashMap<String, RecordingMetadata>>(request).await?;
|
||||||
|
|
||||||
for (mbid, recording) in metadata {
|
for (mbid, recording) in metadata {
|
||||||
let mut weights: HashMap<String, f64> = HashMap::new();
|
let mut genres: HashMap<String, f64> = HashMap::new();
|
||||||
if let Some(tags) = recording.tag {
|
if let Some(tags) = &recording.tag {
|
||||||
for (source, weight) in [
|
for (source, weight) in [
|
||||||
(&tags.recording, 3.0),
|
(&tags.recording, 3.0),
|
||||||
(&tags.release_group, 2.0),
|
(&tags.release_group, 2.0),
|
||||||
@@ -292,15 +324,151 @@ pub async fn recording_tags(
|
|||||||
for tag in source.iter().filter(|t| t.genre_mbid.is_some()) {
|
for tag in source.iter().filter(|t| t.genre_mbid.is_some()) {
|
||||||
let name = tag.tag.trim().to_lowercase();
|
let name = tag.tag.trim().to_lowercase();
|
||||||
if !name.is_empty() {
|
if !name.is_empty() {
|
||||||
*weights.entry(name).or_default() +=
|
*genres.entry(name).or_default() +=
|
||||||
weight * (1.0 + tag.count.unwrap_or(1).max(1) as f64).ln();
|
weight * (1.0 + tag.count.unwrap_or(1).max(1) as f64).ln();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
out.insert(mbid, weights);
|
let release = recording.release.unwrap_or_default();
|
||||||
|
let cover_url = match (release.caa_id, &release.caa_release_mbid) {
|
||||||
|
(Some(id), Some(release_mbid)) => Some(format!(
|
||||||
|
"https://coverartarchive.org/release/{}/{}-250.jpg",
|
||||||
|
release_mbid, id
|
||||||
|
)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
out.insert(
|
||||||
|
mbid,
|
||||||
|
RecordingInfo {
|
||||||
|
title: recording.recording.unwrap_or_default().name,
|
||||||
|
artist: recording.artist.unwrap_or_default().name,
|
||||||
|
release: release.name,
|
||||||
|
cover_url,
|
||||||
|
genres,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Weighted MusicBrainz genres for each recording; see [`RecordingInfo::genres`]
|
||||||
|
pub async fn recording_tags(
|
||||||
|
mbids: &[String],
|
||||||
|
) -> Result<HashMap<String, HashMap<String, f64>>, reqwest::Error> {
|
||||||
|
Ok(recording_metadata(mbids)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(|(mbid, info)| (mbid, info.genres))
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct RecommendationsResponse {
|
||||||
|
payload: RecommendationsPayload,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct RecommendationsPayload {
|
||||||
|
#[serde(default)]
|
||||||
|
mbids: Vec<Recommendation>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone)]
|
||||||
|
pub struct Recommendation {
|
||||||
|
pub recording_mbid: String,
|
||||||
|
/// Set if the user has ever listened to the recording
|
||||||
|
#[serde(default)]
|
||||||
|
pub latest_listened_at: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Listenbrainz's collaborative filtering recording recommendations for a user
|
||||||
|
pub async fn recommendations(
|
||||||
|
user: impl Display,
|
||||||
|
count: usize,
|
||||||
|
) -> Result<Vec<Recommendation>, reqwest::Error> {
|
||||||
|
let response = reqwest::Client::new()
|
||||||
|
.get(format!(
|
||||||
|
"{}/cf/recommendation/user/{}/recording",
|
||||||
|
BASE, user
|
||||||
|
))
|
||||||
|
.query(&[("count", count)])
|
||||||
|
.header(reqwest::header::USER_AGENT, USER_AGENT)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.error_for_status()?;
|
||||||
|
|
||||||
|
// 204 when there are no recommendations for the user (yet)
|
||||||
|
if response.status() == reqwest::StatusCode::NO_CONTENT {
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
Ok(response
|
||||||
|
.json::<RecommendationsResponse>()
|
||||||
|
.await?
|
||||||
|
.payload
|
||||||
|
.mbids)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user token from the config, needed by some endpoints (e.g. LB Radio)
|
||||||
|
pub fn token() -> Option<String> {
|
||||||
|
crate::CONFIG
|
||||||
|
.get()?
|
||||||
|
.get::<String>("listenbrainz.token")
|
||||||
|
.ok()
|
||||||
|
.filter(|t| !t.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct RadioResponse {
|
||||||
|
payload: RadioPayload,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct RadioPayload {
|
||||||
|
jspf: Jspf,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Jspf {
|
||||||
|
playlist: JspfPlaylist,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct JspfPlaylist {
|
||||||
|
#[serde(default)]
|
||||||
|
track: Vec<JspfTrack>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct JspfTrack {
|
||||||
|
#[serde(default)]
|
||||||
|
identifier: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recording MBIDs from an LB Radio prompt, e.g. `tag:(mathcore, math rock)::or`.
|
||||||
|
/// `mode` is "easy", "medium" or "hard" (more obscure). Needs a user token.
|
||||||
|
pub async fn radio(prompt: &str, mode: &str, token: &str) -> Result<Vec<String>, reqwest::Error> {
|
||||||
|
let request = reqwest::Client::new()
|
||||||
|
.get(format!("{}/explore/lb-radio", BASE))
|
||||||
|
.query(&[("prompt", prompt), ("mode", mode)])
|
||||||
|
.header(reqwest::header::AUTHORIZATION, format!("Token {}", token));
|
||||||
|
|
||||||
|
Ok(send_json::<RadioResponse>(request)
|
||||||
|
.await?
|
||||||
|
.payload
|
||||||
|
.jspf
|
||||||
|
.playlist
|
||||||
|
.track
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|t| t.identifier)
|
||||||
|
.filter_map(|id| {
|
||||||
|
id.rsplit('/')
|
||||||
|
.next()
|
||||||
|
.filter(|m| m.len() == 36)
|
||||||
|
.map(str::to_string)
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
+22
-4
@@ -1,11 +1,14 @@
|
|||||||
mod cluster;
|
mod cluster;
|
||||||
mod daemon;
|
mod daemon;
|
||||||
|
mod discover;
|
||||||
mod listenbrainz;
|
mod listenbrainz;
|
||||||
mod mix;
|
mod mix;
|
||||||
mod models;
|
mod models;
|
||||||
mod playlist;
|
mod playlist;
|
||||||
mod subsonic;
|
mod subsonic;
|
||||||
mod track;
|
mod track;
|
||||||
|
mod web;
|
||||||
|
mod youtube;
|
||||||
|
|
||||||
use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon};
|
use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon};
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
@@ -71,9 +74,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
rocket::build()
|
let youtube = youtube::YouTube::new(
|
||||||
|
CONFIG
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.get::<String>("discover.ytdlp")
|
||||||
|
.unwrap_or_else(|_| "yt-dlp".to_string()),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut server = rocket::build()
|
||||||
.manage(media_client)
|
.manage(media_client)
|
||||||
.manage(database)
|
.manage(database)
|
||||||
|
.manage(youtube)
|
||||||
|
.mount("/api/discover", web::routes())
|
||||||
.mount(
|
.mount(
|
||||||
"/api/playlist",
|
"/api/playlist",
|
||||||
routes![
|
routes![
|
||||||
@@ -84,9 +97,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
create_cluster_mix_rule,
|
create_cluster_mix_rule,
|
||||||
all_cluster_mix_rules,
|
all_cluster_mix_rules,
|
||||||
],
|
],
|
||||||
)
|
);
|
||||||
.launch()
|
|
||||||
.await?;
|
// the discover UI's built files (discover/dist)
|
||||||
|
if let Ok(ui) = CONFIG.get().unwrap().get::<String>("discover.ui") {
|
||||||
|
server = server.mount("/", rocket::fs::FileServer::from(ui));
|
||||||
|
}
|
||||||
|
|
||||||
|
server.launch().await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-8
@@ -27,7 +27,7 @@ pub struct MixOptions {
|
|||||||
|
|
||||||
pub struct Mix {
|
pub struct Mix {
|
||||||
pub label: String,
|
pub label: String,
|
||||||
/// Normalised genres describing the mix, best first
|
/// Library genres describing the mix, best first
|
||||||
pub tags: Vec<String>,
|
pub tags: Vec<String>,
|
||||||
pub song_ids: Vec<String>,
|
pub song_ids: Vec<String>,
|
||||||
}
|
}
|
||||||
@@ -67,10 +67,12 @@ impl RecentlyPlayed {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn contains(&self, song: &Track) -> bool {
|
fn contains(&self, song: &Track) -> bool {
|
||||||
song.music_brainz_id
|
self.contains_recording(song.music_brainz_id.as_deref(), &song.artist, &song.title)
|
||||||
.as_ref()
|
}
|
||||||
.is_some_and(|m| self.mbids.contains(m))
|
|
||||||
|| self.names.contains(&name_key(&song.artist, &song.title))
|
pub fn contains_recording(&self, mbid: Option<&str>, artist: &str, title: &str) -> bool {
|
||||||
|
mbid.is_some_and(|m| self.mbids.contains(m))
|
||||||
|
|| self.names.contains(&name_key(artist, title))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,7 +251,11 @@ pub async fn build_mix(
|
|||||||
|
|
||||||
Ok(Some(Mix {
|
Ok(Some(Mix {
|
||||||
label,
|
label,
|
||||||
tags: matched.iter().take(5).map(|(k, _)| k.clone()).collect(),
|
tags: matched
|
||||||
|
.iter()
|
||||||
|
.take(5)
|
||||||
|
.map(|(k, _)| library_genres[k].clone())
|
||||||
|
.collect(),
|
||||||
song_ids: chosen.into_iter().map(|s| s.id).collect(),
|
song_ids: chosen.into_iter().map(|s| s.id).collect(),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@@ -260,8 +266,8 @@ pub fn match_mixes(old: &[Vec<String>], new: &[Vec<String>]) -> Vec<(usize, usiz
|
|||||||
let mut pairs: Vec<(f64, usize, usize)> = vec![];
|
let mut pairs: Vec<(f64, usize, usize)> = vec![];
|
||||||
for (i, a) in old.iter().enumerate() {
|
for (i, a) in old.iter().enumerate() {
|
||||||
for (j, b) in new.iter().enumerate() {
|
for (j, b) in new.iter().enumerate() {
|
||||||
let a: HashSet<_> = a.iter().collect();
|
let a: HashSet<String> = a.iter().map(|t| normalize(t)).collect();
|
||||||
let b: HashSet<_> = b.iter().collect();
|
let b: HashSet<String> = b.iter().map(|t| normalize(t)).collect();
|
||||||
let union = a.union(&b).count();
|
let union = a.union(&b).count();
|
||||||
let jaccard = if union == 0 {
|
let jaccard = if union == 0 {
|
||||||
0.0
|
0.0
|
||||||
|
|||||||
+23
-2
@@ -142,6 +142,7 @@ pub struct PartialClusterMixRule {
|
|||||||
pub familiar_ratio: Option<f64>,
|
pub familiar_ratio: Option<f64>,
|
||||||
pub name_template: Option<String>,
|
pub name_template: Option<String>,
|
||||||
pub refresh_hours: Option<i32>,
|
pub refresh_hours: Option<i32>,
|
||||||
|
pub discovery_count: Option<i32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialClusterMixRule {
|
impl PartialClusterMixRule {
|
||||||
@@ -154,8 +155,8 @@ impl PartialClusterMixRule {
|
|||||||
sqlx::query!(
|
sqlx::query!(
|
||||||
r#"
|
r#"
|
||||||
INSERT INTO "cluster_mix_rule"
|
INSERT INTO "cluster_mix_rule"
|
||||||
(id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours)
|
(id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours, discovery_count)
|
||||||
VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24))
|
VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24), COALESCE($9, 15))
|
||||||
"#,
|
"#,
|
||||||
uuid,
|
uuid,
|
||||||
self.tracking_user,
|
self.tracking_user,
|
||||||
@@ -165,6 +166,7 @@ impl PartialClusterMixRule {
|
|||||||
self.familiar_ratio,
|
self.familiar_ratio,
|
||||||
self.name_template,
|
self.name_template,
|
||||||
self.refresh_hours,
|
self.refresh_hours,
|
||||||
|
self.discovery_count,
|
||||||
)
|
)
|
||||||
.execute(pool)
|
.execute(pool)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -184,6 +186,7 @@ pub struct ClusterMixRule {
|
|||||||
pub name_template: String,
|
pub name_template: String,
|
||||||
pub refresh_hours: i32,
|
pub refresh_hours: i32,
|
||||||
pub last_run: Option<DateTime<Utc>>,
|
pub last_run: Option<DateTime<Utc>>,
|
||||||
|
pub discovery_count: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ClusterMixRule {
|
impl ClusterMixRule {
|
||||||
@@ -226,4 +229,22 @@ pub struct ClusterMixPlaylist {
|
|||||||
pub rule_id: Uuid,
|
pub rule_id: Uuid,
|
||||||
pub playlist_id: String,
|
pub playlist_id: String,
|
||||||
pub tags: Vec<String>,
|
pub tags: Vec<String>,
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub position: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct MixSuggestion {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub rule_id: Uuid,
|
||||||
|
pub mix_id: Option<Uuid>,
|
||||||
|
pub recording_mbid: String,
|
||||||
|
pub title: String,
|
||||||
|
pub artist: String,
|
||||||
|
pub release: Option<String>,
|
||||||
|
pub cover_url: Option<String>,
|
||||||
|
pub score: f64,
|
||||||
|
pub status: String,
|
||||||
|
pub youtube_id: Option<String>,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
@@ -266,6 +266,27 @@ impl Subsonic {
|
|||||||
serde_json::from_value(response).map_err(SubsonicError::Json)
|
serde_json::from_value(response).map_err(SubsonicError::Json)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Request a binary endpoint (e.g. `stream`, `getCoverArt`) and hand back the raw response,
|
||||||
|
/// forwarding an HTTP Range header if given
|
||||||
|
pub async fn raw(
|
||||||
|
&self,
|
||||||
|
endpoint: &str,
|
||||||
|
params: &[(&'static str, String)],
|
||||||
|
range: Option<&str>,
|
||||||
|
) -> Result<reqwest::Response, SubsonicError> {
|
||||||
|
let mut query = self.base_params();
|
||||||
|
query.extend_from_slice(params);
|
||||||
|
|
||||||
|
let mut request = self
|
||||||
|
.client
|
||||||
|
.get(format!("{}/{}", self.base, endpoint))
|
||||||
|
.query(&query);
|
||||||
|
if let Some(range) = range {
|
||||||
|
request = request.header(reqwest::header::RANGE, range);
|
||||||
|
}
|
||||||
|
request.send().await.map_err(SubsonicError::Reqwest)
|
||||||
|
}
|
||||||
|
|
||||||
/// All genres in the library
|
/// All genres in the library
|
||||||
pub async fn get_genres(&self) -> Result<Vec<Genre>, SubsonicError> {
|
pub async fn get_genres(&self) -> Result<Vec<Genre>, SubsonicError> {
|
||||||
Ok(self
|
Ok(self
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ pub struct Track {
|
|||||||
pub genres: Vec<ItemGenre>,
|
pub genres: Vec<ItemGenre>,
|
||||||
#[serde(rename = "musicBrainzId", default)]
|
#[serde(rename = "musicBrainzId", default)]
|
||||||
pub music_brainz_id: Option<String>,
|
pub music_brainz_id: Option<String>,
|
||||||
|
/// Seconds
|
||||||
|
#[serde(default)]
|
||||||
|
pub duration: Option<u64>,
|
||||||
|
#[serde(rename = "coverArt", default)]
|
||||||
|
pub cover_art: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||||
|
|||||||
+375
@@ -0,0 +1,375 @@
|
|||||||
|
//! API for the discover UI: mixes, suggested songs, and audio/cover streaming
|
||||||
|
//! from Subsonic or YouTube.
|
||||||
|
|
||||||
|
use crate::models::{ClusterMixRule, MixSuggestion};
|
||||||
|
use crate::subsonic::Subsonic;
|
||||||
|
use crate::track::Track;
|
||||||
|
use crate::youtube::YouTube;
|
||||||
|
use futures_util::TryStreamExt;
|
||||||
|
use rocket::http::Status;
|
||||||
|
use rocket::request::{FromRequest, Outcome};
|
||||||
|
use rocket::response::{self, Responder};
|
||||||
|
use rocket::serde::json::Json;
|
||||||
|
use rocket::{get, post, put, routes, Request, Response, Route, State};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sqlx::postgres::PgPool;
|
||||||
|
use std::convert::Infallible;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio_util::io::StreamReader;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub fn routes() -> Vec<Route> {
|
||||||
|
routes![rules, mixes, mix, liked, set_status, rebuild, stream, cover, youtube]
|
||||||
|
}
|
||||||
|
|
||||||
|
type ApiResult<T> = Result<Json<T>, Status>;
|
||||||
|
|
||||||
|
fn db_error(e: sqlx::Error) -> Status {
|
||||||
|
match e {
|
||||||
|
sqlx::Error::RowNotFound => Status::NotFound,
|
||||||
|
e => {
|
||||||
|
println!("Database error: {:?}", e);
|
||||||
|
Status::InternalServerError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_id(id: &str) -> Result<Uuid, Status> {
|
||||||
|
Uuid::parse_str(id).map_err(|_| Status::NotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/rules")]
|
||||||
|
async fn rules(pool: &State<PgPool>) -> ApiResult<Vec<ClusterMixRule>> {
|
||||||
|
ClusterMixRule::all(pool.inner())
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(db_error)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct MixSummary {
|
||||||
|
id: Uuid,
|
||||||
|
playlist_id: String,
|
||||||
|
name: Option<String>,
|
||||||
|
tags: Vec<String>,
|
||||||
|
position: i32,
|
||||||
|
new_count: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/rules/<id>/mixes")]
|
||||||
|
async fn mixes(id: &str, pool: &State<PgPool>) -> ApiResult<Vec<MixSummary>> {
|
||||||
|
sqlx::query_as!(
|
||||||
|
MixSummary,
|
||||||
|
r#"
|
||||||
|
SELECT p.id, p.playlist_id, p.name, p.tags, p.position,
|
||||||
|
COUNT(s.id) FILTER (WHERE s.status = 'new') AS "new_count!"
|
||||||
|
FROM "cluster_mix_playlist" p
|
||||||
|
LEFT JOIN "mix_suggestion" s ON s.mix_id = p.id
|
||||||
|
WHERE p.rule_id = $1
|
||||||
|
GROUP BY p.id
|
||||||
|
ORDER BY p.position
|
||||||
|
"#,
|
||||||
|
parse_id(id)?
|
||||||
|
)
|
||||||
|
.fetch_all(pool.inner())
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(db_error)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct MixDetail {
|
||||||
|
#[serde(flatten)]
|
||||||
|
summary: MixSummary,
|
||||||
|
songs: Vec<Track>,
|
||||||
|
suggestions: Vec<MixSuggestion>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/mixes/<id>")]
|
||||||
|
async fn mix(
|
||||||
|
id: &str,
|
||||||
|
pool: &State<PgPool>,
|
||||||
|
media_client: &State<Arc<Subsonic>>,
|
||||||
|
) -> ApiResult<MixDetail> {
|
||||||
|
let id = parse_id(id)?;
|
||||||
|
let summary = sqlx::query_as!(
|
||||||
|
MixSummary,
|
||||||
|
r#"
|
||||||
|
SELECT p.id, p.playlist_id, p.name, p.tags, p.position,
|
||||||
|
COUNT(s.id) FILTER (WHERE s.status = 'new') AS "new_count!"
|
||||||
|
FROM "cluster_mix_playlist" p
|
||||||
|
LEFT JOIN "mix_suggestion" s ON s.mix_id = p.id
|
||||||
|
WHERE p.id = $1
|
||||||
|
GROUP BY p.id
|
||||||
|
"#,
|
||||||
|
id
|
||||||
|
)
|
||||||
|
.fetch_one(pool.inner())
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
|
||||||
|
let songs = media_client
|
||||||
|
.get_playlist(&summary.playlist_id)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
println!("Could not load playlist {}: {:?}", summary.playlist_id, e);
|
||||||
|
Status::BadGateway
|
||||||
|
})?
|
||||||
|
.entry;
|
||||||
|
|
||||||
|
let suggestions = sqlx::query_as!(
|
||||||
|
MixSuggestion,
|
||||||
|
r#"
|
||||||
|
SELECT * FROM "mix_suggestion"
|
||||||
|
WHERE mix_id = $1 AND status <> 'dismissed'
|
||||||
|
ORDER BY score DESC
|
||||||
|
"#,
|
||||||
|
id
|
||||||
|
)
|
||||||
|
.fetch_all(pool.inner())
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
|
||||||
|
Ok(Json(MixDetail {
|
||||||
|
summary,
|
||||||
|
songs,
|
||||||
|
suggestions,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/rules/<id>/liked")]
|
||||||
|
async fn liked(id: &str, pool: &State<PgPool>) -> ApiResult<Vec<MixSuggestion>> {
|
||||||
|
sqlx::query_as!(
|
||||||
|
MixSuggestion,
|
||||||
|
r#"
|
||||||
|
SELECT * FROM "mix_suggestion"
|
||||||
|
WHERE rule_id = $1 AND status = 'liked'
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
"#,
|
||||||
|
parse_id(id)?
|
||||||
|
)
|
||||||
|
.fetch_all(pool.inner())
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(db_error)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct StatusUpdate {
|
||||||
|
status: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like, dismiss, or reset a suggestion
|
||||||
|
#[put("/suggestions/<id>", data = "<update>")]
|
||||||
|
async fn set_status(
|
||||||
|
id: &str,
|
||||||
|
update: Json<StatusUpdate>,
|
||||||
|
pool: &State<PgPool>,
|
||||||
|
) -> ApiResult<MixSuggestion> {
|
||||||
|
if !["new", "liked", "dismissed"].contains(&update.status.as_str()) {
|
||||||
|
return Err(Status::UnprocessableEntity);
|
||||||
|
}
|
||||||
|
sqlx::query_as!(
|
||||||
|
MixSuggestion,
|
||||||
|
r#"UPDATE "mix_suggestion" SET status = $1 WHERE id = $2 RETURNING *"#,
|
||||||
|
update.status,
|
||||||
|
parse_id(id)?
|
||||||
|
)
|
||||||
|
.fetch_one(pool.inner())
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(db_error)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebuild a rule's mixes on the next daemon tick
|
||||||
|
#[post("/rules/<id>/rebuild")]
|
||||||
|
async fn rebuild(id: &str, pool: &State<PgPool>) -> Status {
|
||||||
|
let Ok(id) = parse_id(id) else {
|
||||||
|
return Status::NotFound;
|
||||||
|
};
|
||||||
|
match sqlx::query!(
|
||||||
|
r#"UPDATE "cluster_mix_rule" SET last_run = NULL WHERE id = $1"#,
|
||||||
|
id
|
||||||
|
)
|
||||||
|
.execute(pool.inner())
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(r) if r.rows_affected() > 0 => Status::Accepted,
|
||||||
|
Ok(_) => Status::NotFound,
|
||||||
|
Err(e) => db_error(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The request's Range header, so audio can be seeked
|
||||||
|
pub struct Range(Option<String>);
|
||||||
|
|
||||||
|
#[rocket::async_trait]
|
||||||
|
impl<'r> FromRequest<'r> for Range {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
||||||
|
Outcome::Success(Range(
|
||||||
|
request.headers().get_one("Range").map(str::to_string),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stream an upstream response through, keeping the headers a media element needs
|
||||||
|
pub struct Proxied(reqwest::Response);
|
||||||
|
|
||||||
|
impl<'r> Responder<'r, 'static> for Proxied {
|
||||||
|
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
|
||||||
|
let upstream = self.0;
|
||||||
|
let mut response = Response::build();
|
||||||
|
response.status(Status::new(upstream.status().as_u16()));
|
||||||
|
for name in [
|
||||||
|
"content-type",
|
||||||
|
"content-range",
|
||||||
|
"accept-ranges",
|
||||||
|
"cache-control",
|
||||||
|
"last-modified",
|
||||||
|
"etag",
|
||||||
|
] {
|
||||||
|
if let Some(value) = upstream.headers().get(name).and_then(|v| v.to_str().ok()) {
|
||||||
|
response.raw_header(name, value.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let size = upstream.content_length();
|
||||||
|
let body = StreamReader::new(upstream.bytes_stream().map_err(std::io::Error::other));
|
||||||
|
match size {
|
||||||
|
// a known length lets browsers show durations and seek
|
||||||
|
Some(size) => response.sized_body(size as usize, LengthReader(body)),
|
||||||
|
None => response.streamed_body(body),
|
||||||
|
};
|
||||||
|
response.ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rocket only accepts a known body length for seekable bodies, but never seeks one whose size
|
||||||
|
/// is given up front. This satisfies the trait for a plain stream.
|
||||||
|
struct LengthReader<R>(R);
|
||||||
|
|
||||||
|
impl<R: tokio::io::AsyncRead + Unpin> tokio::io::AsyncRead for LengthReader<R> {
|
||||||
|
fn poll_read(
|
||||||
|
mut self: std::pin::Pin<&mut Self>,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
buf: &mut tokio::io::ReadBuf<'_>,
|
||||||
|
) -> std::task::Poll<std::io::Result<()>> {
|
||||||
|
std::pin::Pin::new(&mut self.0).poll_read(cx, buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<R: Unpin> tokio::io::AsyncSeek for LengthReader<R> {
|
||||||
|
fn start_seek(self: std::pin::Pin<&mut Self>, _: std::io::SeekFrom) -> std::io::Result<()> {
|
||||||
|
Err(std::io::Error::other("streamed body can't be seeked"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_complete(
|
||||||
|
self: std::pin::Pin<&mut Self>,
|
||||||
|
_: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<std::io::Result<u64>> {
|
||||||
|
std::task::Poll::Ready(Err(std::io::Error::other("streamed body can't be seeked")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stream a song from Subsonic
|
||||||
|
#[get("/stream/<id>")]
|
||||||
|
async fn stream(
|
||||||
|
id: &str,
|
||||||
|
range: Range,
|
||||||
|
media_client: &State<Arc<Subsonic>>,
|
||||||
|
) -> Result<Proxied, Status> {
|
||||||
|
let format = crate::CONFIG
|
||||||
|
.get()
|
||||||
|
.and_then(|c| c.get::<String>("discover.format").ok())
|
||||||
|
.unwrap_or_else(|| "raw".to_string());
|
||||||
|
media_client
|
||||||
|
.raw(
|
||||||
|
"stream",
|
||||||
|
&[("id", id.to_string()), ("format", format)],
|
||||||
|
range.0.as_deref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(Proxied)
|
||||||
|
.map_err(|_| Status::BadGateway)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cover art from Subsonic
|
||||||
|
#[get("/cover/<id>?<size>")]
|
||||||
|
async fn cover(
|
||||||
|
id: &str,
|
||||||
|
size: Option<u32>,
|
||||||
|
media_client: &State<Arc<Subsonic>>,
|
||||||
|
) -> Result<Proxied, Status> {
|
||||||
|
media_client
|
||||||
|
.raw(
|
||||||
|
"getCoverArt",
|
||||||
|
&[
|
||||||
|
("id", id.to_string()),
|
||||||
|
("size", size.unwrap_or(300).to_string()),
|
||||||
|
],
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(Proxied)
|
||||||
|
.map_err(|_| Status::BadGateway)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find a suggested song on YouTube and stream its audio
|
||||||
|
#[get("/youtube/<id>")]
|
||||||
|
async fn youtube(
|
||||||
|
id: &str,
|
||||||
|
range: Range,
|
||||||
|
pool: &State<PgPool>,
|
||||||
|
youtube: &State<YouTube>,
|
||||||
|
) -> Result<Proxied, Status> {
|
||||||
|
let suggestion = sqlx::query_as!(
|
||||||
|
MixSuggestion,
|
||||||
|
r#"SELECT * FROM "mix_suggestion" WHERE id = $1"#,
|
||||||
|
parse_id(id)?
|
||||||
|
)
|
||||||
|
.fetch_one(pool.inner())
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
|
||||||
|
let video_id = match suggestion.youtube_id {
|
||||||
|
Some(video_id) => video_id,
|
||||||
|
None => {
|
||||||
|
let video_id = youtube
|
||||||
|
.search(&suggestion.artist, &suggestion.title)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
println!("YouTube search failed: {}", e);
|
||||||
|
Status::BadGateway
|
||||||
|
})?
|
||||||
|
.ok_or(Status::NotFound)?;
|
||||||
|
sqlx::query!(
|
||||||
|
r#"UPDATE "mix_suggestion" SET youtube_id = $1 WHERE id = $2"#,
|
||||||
|
video_id,
|
||||||
|
suggestion.id
|
||||||
|
)
|
||||||
|
.execute(pool.inner())
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
video_id
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// a cached URL may have expired; fetch a fresh one once
|
||||||
|
for refresh in [false, true] {
|
||||||
|
let url = youtube.audio_url(&video_id, refresh).await.map_err(|e| {
|
||||||
|
println!("Could not get audio for {}: {}", video_id, e);
|
||||||
|
Status::BadGateway
|
||||||
|
})?;
|
||||||
|
let mut request = youtube.client.get(url);
|
||||||
|
if let Some(range) = &range.0 {
|
||||||
|
request = request.header(reqwest::header::RANGE, range);
|
||||||
|
}
|
||||||
|
let response = request.send().await.map_err(|_| Status::BadGateway)?;
|
||||||
|
if !refresh && matches!(response.status().as_u16(), 403 | 404 | 410) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return Ok(Proxied(response));
|
||||||
|
}
|
||||||
|
Err(Status::BadGateway)
|
||||||
|
}
|
||||||
+133
@@ -0,0 +1,133 @@
|
|||||||
|
//! Find and stream songs from YouTube with yt-dlp.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::process::Stdio;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
use thiserror::Error;
|
||||||
|
use tokio::process::Command;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
|
/// Search results longer than this are probably full albums or mixes
|
||||||
|
const MAX_DURATION_SECS: f64 = 15.0 * 60.0;
|
||||||
|
/// YouTube's media URLs expire after about 6 hours
|
||||||
|
const URL_TTL: Duration = Duration::from_secs(60 * 60);
|
||||||
|
const SEARCH_RESULTS: usize = 5;
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum YouTubeError {
|
||||||
|
#[error("couldn't run yt-dlp: {0}")]
|
||||||
|
Spawn(#[from] std::io::Error),
|
||||||
|
#[error("yt-dlp failed: {0}")]
|
||||||
|
Failed(String),
|
||||||
|
#[error("invalid video id")]
|
||||||
|
InvalidId,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct YouTube {
|
||||||
|
binary: String,
|
||||||
|
urls: Mutex<HashMap<String, (String, Instant)>>,
|
||||||
|
pub client: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn valid_video_id(id: &str) -> bool {
|
||||||
|
id.len() == 11
|
||||||
|
&& id
|
||||||
|
.chars()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||||
|
}
|
||||||
|
|
||||||
|
impl YouTube {
|
||||||
|
pub fn new(binary: String) -> Self {
|
||||||
|
Self {
|
||||||
|
binary,
|
||||||
|
urls: Mutex::new(HashMap::new()),
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(&self, args: &[&str]) -> Result<String, YouTubeError> {
|
||||||
|
let output = Command::new(&self.binary)
|
||||||
|
.args(["--no-warnings", "--no-playlist", "--ignore-config"])
|
||||||
|
.args(args)
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.kill_on_drop(true)
|
||||||
|
.output()
|
||||||
|
.await?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return Err(YouTubeError::Failed(
|
||||||
|
String::from_utf8_lossy(&output.stderr).trim().to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ID of the best matching video for a song, skipping very long videos
|
||||||
|
pub async fn search(&self, artist: &str, title: &str) -> Result<Option<String>, YouTubeError> {
|
||||||
|
let query = format!("ytsearch{}:{} - {}", SEARCH_RESULTS, artist, title);
|
||||||
|
let output = self
|
||||||
|
.run(&["--flat-playlist", "--print", "%(id)s\t%(duration)s", &query])
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let results: Vec<(&str, Option<f64>)> = output
|
||||||
|
.lines()
|
||||||
|
.filter_map(|line| {
|
||||||
|
let (id, duration) = line.split_once('\t')?;
|
||||||
|
valid_video_id(id).then(|| (id, duration.trim().parse::<f64>().ok()))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(results
|
||||||
|
.iter()
|
||||||
|
.find(|(_, d)| d.is_some_and(|d| d <= MAX_DURATION_SECS))
|
||||||
|
.or(results.first())
|
||||||
|
.map(|(id, _)| id.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A direct URL to the video's audio, preferring m4a since every browser can play it
|
||||||
|
pub async fn audio_url(&self, video_id: &str, refresh: bool) -> Result<String, YouTubeError> {
|
||||||
|
if !valid_video_id(video_id) {
|
||||||
|
return Err(YouTubeError::InvalidId);
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let urls = self.urls.lock().await;
|
||||||
|
if let Some((url, fetched)) = urls.get(video_id) {
|
||||||
|
if !refresh && fetched.elapsed() < URL_TTL {
|
||||||
|
return Ok(url.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let output = self
|
||||||
|
.run(&[
|
||||||
|
"-f",
|
||||||
|
"bestaudio[ext=m4a]/bestaudio",
|
||||||
|
"--get-url",
|
||||||
|
&format!("https://www.youtube.com/watch?v={}", video_id),
|
||||||
|
])
|
||||||
|
.await?;
|
||||||
|
let url = output
|
||||||
|
.lines()
|
||||||
|
.next()
|
||||||
|
.filter(|l| l.starts_with("http"))
|
||||||
|
.ok_or_else(|| YouTubeError::Failed("no audio URL".to_string()))?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let mut urls = self.urls.lock().await;
|
||||||
|
urls.retain(|_, (_, fetched)| fetched.elapsed() < URL_TTL);
|
||||||
|
urls.insert(video_id.to_string(), (url.clone(), Instant::now()));
|
||||||
|
Ok(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validates_video_ids() {
|
||||||
|
assert!(valid_video_id("dQw4w9WgXcQ"));
|
||||||
|
assert!(valid_video_id("a-b_c123456"));
|
||||||
|
assert!(!valid_video_id("--exec=rm -"));
|
||||||
|
assert!(!valid_video_id("short"));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user