diff --git a/README.md b/README.md index ab934e8..ce6374a 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,9 @@ The package is written to `target/debian/`. Each of these will work best when your music library is well organised with Musicbrainz metadata. +Tracked playlists, recurring playlists and genre mixes can all be managed from the web UI (see +[Discover UI](#discover-ui)), under "Tracked playlists". The SQL below does the same by hand. + ### Tracked playlist A tracked playlist is a single Subsonic playlist that tracks data from Listenbrainz. For example, @@ -160,3 +163,16 @@ The UI uses these endpoints under `/api/discover`: | `GET /stream/` | Stream a library song from Subsonic | | `GET /cover/` | Library cover art from Subsonic | | `GET /youtube/` | Stream a suggested song from YouTube | + +and these under `/api/tracked` for tracked playlists: + +| Endpoint | Purpose | +|-----------------------------------|------------------------------------------------------------| +| `GET /playlists` | Tracked playlists, with their names and song counts | +| `POST /playlists` | Track an existing playlist (`playlist_id`) or a new one (`name`) | +| `PUT /playlists/` | Change size, user or period; rename with `name` | +| `DELETE /playlists/?delete_playlist=true` | Stop tracking, optionally deleting the playlist | +| `POST /playlists//refresh` | Update a playlist's songs now | +| `GET /subsonic-playlists` | Playlists that can be tracked | +| `GET`/`POST /rules`, `PUT`/`DELETE /rules/` | Recurring playlist rules | +| `GET /preview-name?template=` | What a name template produces today | diff --git a/discover/src/App.tsx b/discover/src/App.tsx index 735b9b0..ca9268e 100644 --- a/discover/src/App.tsx +++ b/discover/src/App.tsx @@ -3,14 +3,16 @@ import { api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatu import { usePlayer } from "./usePlayer"; import { MixView, hue } from "./MixView"; import { LikedView } from "./LikedView"; +import { TrackedView } from "./TrackedView"; import { PlayerBar } from "./PlayerBar"; import * as Icon from "./icons"; -type Route = { view: "mix"; id?: string } | { view: "liked" }; +type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" }; function parseHash(): Route { const [, view, id] = window.location.hash.split("/"); - return view === "liked" ? { view: "liked" } : { view: "mix", id: id || undefined }; + if (view === "liked" || view === "tracked") return { view }; + return { view: "mix", id: id || undefined }; } type Toast = { message: string; undo?: () => void }; @@ -193,22 +195,30 @@ export function App() { {liked.length > 0 && {liked.length}} +
  • + + + Tracked playlists + +
  • {error &&
    {error}
    } - {rules && rules.length === 0 && ( + {route.view !== "tracked" && rules && rules.length === 0 && (

    No mix rules yet

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

    {`curl -X POST /api/playlist/mix -H 'Content-Type: application/json' \\\n  -d '{"tracking_user": "your-listenbrainz-name"}'`}
    )} - {pending && mixes?.length === 0 && ( + {route.view !== "tracked" && pending && mixes?.length === 0 && (
    Building mixes from your recent listens…
    )} - {route.view === "liked" ? ( + {route.view === "tracked" ? ( + setToast({ message })} /> + ) : route.view === "liked" ? ( ) : detail ? ( diff --git a/discover/src/TrackedView.tsx b/discover/src/TrackedView.tsx new file mode 100644 index 0000000..29d5225 --- /dev/null +++ b/discover/src/TrackedView.tsx @@ -0,0 +1,522 @@ +import { FormEvent, ReactNode, useCallback, useEffect, useMemo, useState } from "react"; +import { + PERIODS, + periodLabel, + SubsonicPlaylist, + TrackedPlaylist, + TrackedRule, + trackedApi, + Tracking, +} from "./api"; +import * as Icon from "./icons"; + +type Props = { + /** Listenbrainz user to suggest for new playlists */ + defaultUser?: string; + onToast: (message: string) => void; +}; + +const describe = (t: Tracking) => `Top ${t.playlist_size} · ${periodLabel(t.tracking_type)} · ${t.tracking_user}`; + +export function TrackedView({ defaultUser, onToast }: Props) { + const [playlists, setPlaylists] = useState(null); + const [rules, setRules] = useState(null); + const [error, setError] = useState(null); + // "new-playlist", "new-rule", or the id of the item being edited + const [editing, setEditing] = useState(null); + const [confirming, setConfirming] = useState(null); + const [refreshing, setRefreshing] = useState>(new Set()); + + const load = useCallback(() => { + trackedApi.playlists().then(setPlaylists, (e) => setError(e.message)); + trackedApi.rules().then(setRules, (e) => setError(e.message)); + }, []); + useEffect(load, [load]); + + const users = useMemo(() => { + const all = [defaultUser, ...(playlists ?? []).map((p) => p.tracking_user), ...(rules ?? []).map((r) => r.tracking_user)]; + return [...new Set(all.filter((u): u is string => !!u))]; + }, [defaultUser, playlists, rules]); + const suggestedUser = users[0] ?? ""; + + const replace = (items: T[] | null, item: T) => + items?.some((i) => i.id === item.id) ? items.map((i) => (i.id === item.id ? item : i)) : [...(items ?? []), item]; + + const refresh = async (p: TrackedPlaylist) => { + setRefreshing((s) => new Set(s).add(p.id)); + try { + const updated = await trackedApi.refresh(p.id); + setPlaylists((ps) => replace(ps, updated)); + const found = updated.song_count ?? 0; + onToast( + found < updated.playlist_size + ? `Updated “${updated.name ?? "playlist"}”: ${found} of the top ${updated.playlist_size} are in your library` + : `Updated “${updated.name ?? "playlist"}” with ${found} songs`, + ); + } catch (e) { + onToast((e as Error).message); + } finally { + setRefreshing((s) => { + const next = new Set(s); + next.delete(p.id); + return next; + }); + } + }; + + return ( +
    +
    +

    Manage

    +

    Tracked playlists

    +

    + Subsonic playlists kept up to date with your top songs on Listenbrainz. +

    +
    + {error &&
    {error}
    } + +
    +
    +
    +

    Playlists

    +

    Refreshed automatically every few minutes.

    +
    + {editing !== "new-playlist" && ( + + )} +
    + + {editing === "new-playlist" && ( + setEditing(null)} + onSaved={(p) => { + setPlaylists((ps) => replace(ps, p)); + setEditing(null); + onToast(`Tracking “${p.name}”. Refreshing it now…`); + void refresh(p); + }} + /> + )} + + {playlists === null ? ( +

    Loading…

    + ) : playlists.length === 0 && editing !== "new-playlist" ? ( +

    No tracked playlists yet. Create one to keep, say, your top 50 of the last month in Subsonic.

    + ) : ( +
      + {playlists.map((p) => + editing === p.id ? ( +
    • + setEditing(null)} + onSaved={(updated) => { + setPlaylists((ps) => replace(ps, updated)); + setEditing(null); + onToast("Saved. Refresh to apply the changes now."); + }} + /> +
    • + ) : ( + : } + title={p.name ?? Missing from Subsonic} + subtitle={describe(p)} + aside={ + p.song_count === null ? undefined : p.song_count > 0 && p.song_count < p.playlist_size ? ( + + {p.song_count} of {p.playlist_size} found + + ) : ( + `${p.song_count} songs` + ) + } + actions={ + <> + + + + + } + confirm={ + confirming === p.id && ( + setConfirming(null)} + onRemoved={(deleted) => { + setPlaylists((ps) => ps?.filter((x) => x.id !== p.id) ?? null); + setConfirming(null); + onToast(deleted ? "Playlist deleted" : "Stopped tracking. The playlist stays in Subsonic."); + }} + /> + ) + } + /> + ), + )} +
    + )} +
    + +
    +
    +
    +

    Recurring playlists

    +

    Start a new tracked playlist whenever the name changes, e.g. each year or month.

    +
    + {editing !== "new-rule" && ( + + )} +
    + + {editing === "new-rule" && ( + setEditing(null)} + onSaved={(r) => { + setRules((rs) => replace(rs, r)); + setEditing(null); + onToast(`“${r.current_name}” will be created within a few minutes`); + // the daemon creates the playlist; show it once it's there + window.setTimeout(load, 15000); + }} + /> + )} + + {rules === null ? ( +

    Loading…

    + ) : rules.length === 0 && editing !== "new-rule" ? ( +

    No recurring playlists. A rule like “%Y - Top 100” makes a new top 100 every year.

    + ) : ( +
      + {rules.map((r) => + editing === r.id ? ( +
    • + setEditing(null)} + onSaved={(updated) => { + setRules((rs) => replace(rs, updated)); + setEditing(null); + onToast("Saved. Applies to playlists the rule makes from now on."); + }} + /> +
    • + ) : ( + } + title={{r.name_template}} + subtitle={describe(r)} + aside={ + r.last_name && r.last_name === r.current_name + ? <>Current: {r.last_name} + : r.current_name ? <>Next: {r.current_name} : undefined + } + actions={ + <> + + + + } + confirm={ + confirming === r.id && ( + setConfirming(null)} + onConfirm={async () => { + await trackedApi.removeRule(r.id); + setRules((rs) => rs?.filter((x) => x.id !== r.id) ?? null); + setConfirming(null); + }} + /> + ) + } + /> + ), + )} +
    + )} +
    +
    + ); +} + +function Item(props: { icon: ReactNode; title: ReactNode; subtitle: string; aside?: ReactNode; actions: ReactNode; confirm?: ReactNode }) { + return ( +
  • +
    + +
    +
    {props.title}
    +
    {props.subtitle}
    +
    + {props.aside &&
    {props.aside}
    } +
    {props.actions}
    +
    + {props.confirm} +
  • + ); +} + +function Confirm(props: { message: ReactNode; action: string; onCancel: () => void; onConfirm: () => Promise; children?: ReactNode }) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + return ( +
    +

    {props.message}

    + {props.children} + {error &&

    {error}

    } +
    + + +
    +
    + ); +} + +function RemovePlaylist(props: { playlist: TrackedPlaylist; onCancel: () => void; onRemoved: (deleted: boolean) => void }) { + const [alsoDelete, setAlsoDelete] = useState(false); + return ( + Stop updating “{props.playlist.name ?? "this playlist"}”?} + action={alsoDelete ? "Delete playlist" : "Stop tracking"} + onCancel={props.onCancel} + onConfirm={async () => { + await trackedApi.remove(props.playlist.id, alsoDelete); + props.onRemoved(alsoDelete); + }} + > + {props.playlist.name && ( + + )} + + ); +} + +/** Fields shared by playlists and rules */ +function TrackingFields({ value, onChange, users }: { value: Tracking; onChange: (t: Tracking) => void; users: string[] }) { + return ( + <> + + + + + ); +} + +function useSubmit(save: () => Promise, onSaved: (t: T) => void) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const submit = async (e: FormEvent) => { + e.preventDefault(); + setBusy(true); + setError(null); + try { + onSaved(await save()); + } catch (err) { + setError((err as Error).message); + setBusy(false); + } + }; + return { busy, error, submit }; +} + +function PlaylistForm(props: { + initial: Tracking & Partial; + users: string[]; + onCancel: () => void; + onSaved: (p: TrackedPlaylist) => void; +}) { + const creating = !props.initial.id; + const [tracking, setTracking] = useState({ + playlist_size: props.initial.playlist_size, + tracking_user: props.initial.tracking_user, + tracking_type: props.initial.tracking_type, + }); + const [mode, setMode] = useState<"new" | "existing">("new"); + const [name, setName] = useState(props.initial.name ?? ""); + const [existingId, setExistingId] = useState(""); + const [subsonic, setSubsonic] = useState(null); + + useEffect(() => { + if (creating && mode === "existing" && subsonic === null) { + trackedApi.subsonicPlaylists().then(setSubsonic, () => setSubsonic([])); + } + }, [creating, mode, subsonic]); + const available = subsonic?.filter((p) => !p.tracked) ?? []; + + const { busy, error, submit } = useSubmit( + () => + creating + ? trackedApi.create(mode === "new" ? { ...tracking, name } : { ...tracking, playlist_id: existingId }) + : trackedApi.update(props.initial.id!, { ...tracking, name: name || undefined }), + props.onSaved, + ); + + return ( +
    + {creating && ( +
    + + +
    + )} +
    + {creating && mode === "existing" ? ( +
    + + + Its songs will be replaced with your top songs. +
    + ) : ( + (creating || props.initial.name) && ( + + ) + )} + +
    + {error &&

    {error}

    } +
    + + +
    +
    + ); +} + +function RuleForm(props: { + initial: Tracking & { name_template: string; id?: string }; + users: string[]; + onCancel: () => void; + onSaved: (r: TrackedRule) => void; +}) { + const creating = !props.initial.id; + const [tracking, setTracking] = useState({ + playlist_size: props.initial.playlist_size, + tracking_user: props.initial.tracking_user, + tracking_type: props.initial.tracking_type, + }); + const [template, setTemplate] = useState(props.initial.name_template); + const [preview, setPreview] = useState<{ name?: string; error?: string }>({}); + + useEffect(() => { + const t = window.setTimeout(() => { + trackedApi.previewName(template).then( + ({ name }) => setPreview({ name }), + (e) => setPreview({ error: e.message }), + ); + }, 250); + return () => window.clearTimeout(t); + }, [template]); + + const { busy, error, submit } = useSubmit( + () => + creating + ? trackedApi.createRule({ ...tracking, name_template: template }) + : trackedApi.updateRule(props.initial.id!, { ...tracking, name_template: template }), + props.onSaved, + ); + + return ( +
    +
    +
    + + setTemplate(e.target.value)} spellCheck={false} + aria-describedby="template-help" className="mono" /> + + {preview.error ? ( + {preview.error} + ) : preview.name ? ( + <>Today this makes {preview.name}. + ) : null} + Use %Y for the year, %B the month, %m its number, %V the week. A new playlist starts whenever the name changes. + +
    + +
    + {error &&

    {error}

    } +
    + + +
    +
    + ); +} diff --git a/discover/src/api.ts b/discover/src/api.ts index c6db338..ccd6270 100644 --- a/discover/src/api.ts +++ b/discover/src/api.ts @@ -49,14 +49,22 @@ export type MixDetail = MixSummary & { suggestions: Suggestion[]; }; -async function request(path: string, init?: RequestInit): Promise { - const response = await fetch(`/api/discover${path}`, init); +async function request(path: string, init?: RequestInit, base = "/api/discover"): Promise { + const response = await fetch(`${base}${path}`, init); if (!response.ok) { - throw new Error(`${response.status} ${response.statusText}`); + // the API explains what went wrong where it can + const body = await response.json().catch(() => null); + throw new Error(body?.error ?? `${response.status} ${response.statusText}`); } - return response.json(); + return response.status === 204 ? (undefined as T) : response.json(); } +const json = (method: string, body: unknown): RequestInit => ({ + method, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), +}); + export const api = { rules: () => request("/rules"), mixes: (ruleId: string) => request(`/rules/${ruleId}/mixes`), @@ -80,3 +88,64 @@ export const youtubeUrl = (suggestionId: string) => `/api/discover/youtube/${sug /** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */ export const mixTitle = (mix: MixSummary) => (mix.name ?? mix.tags.join(" / ")).replace(/^mix:\s*/i, ""); + +// ---------- tracked playlists ---------- + +export const PERIODS: [string, string][] = [ + ["this_week", "This week so far"], + ["this_month", "This month so far"], + ["this_year", "This year so far"], + ["week", "Last week"], + ["month", "Last month"], + ["quarter", "Last quarter"], + ["half_yearly", "Last six months"], + ["year", "Last year"], + ["all_time", "All time"], +]; + +export const periodLabel = (period: string) => + PERIODS.find(([value]) => value === period)?.[1] ?? period; + +export type Tracking = { + playlist_size: number; + tracking_user: string; + tracking_type: string; +}; + +export type TrackedPlaylist = Tracking & { + id: string; + playlist_id: string | null; + /** null when the playlist no longer exists in Subsonic */ + name: string | null; + song_count: number | null; +}; + +export type TrackedRule = Tracking & { + id: string; + name_template: string; + last_name: string | null; + current_name: string | null; +}; + +export type SubsonicPlaylist = { id: string; name: string; song_count: number; tracked: boolean }; + +const tracked = (path: string, init?: RequestInit) => request(path, init, "/api/tracked"); + +export const trackedApi = { + playlists: () => tracked("/playlists"), + create: (body: Tracking & { name?: string; playlist_id?: string }) => + tracked("/playlists", json("POST", body)), + update: (id: string, body: Tracking & { name?: string }) => + tracked(`/playlists/${id}`, json("PUT", body)), + remove: (id: string, deletePlaylist: boolean) => + tracked(`/playlists/${id}?delete_playlist=${deletePlaylist}`, { method: "DELETE" }), + refresh: (id: string) => tracked(`/playlists/${id}/refresh`, { method: "POST" }), + subsonicPlaylists: () => tracked("/subsonic-playlists"), + rules: () => tracked("/rules"), + createRule: (body: Tracking & { name_template: string }) => tracked("/rules", json("POST", body)), + updateRule: (id: string, body: Tracking & { name_template: string }) => + tracked(`/rules/${id}`, json("PUT", body)), + removeRule: (id: string) => tracked(`/rules/${id}`, { method: "DELETE" }), + previewName: (template: string) => + tracked<{ name: string }>(`/preview-name?template=${encodeURIComponent(template)}`), +}; diff --git a/discover/src/icons.tsx b/discover/src/icons.tsx index 72ae65e..03a0756 100644 --- a/discover/src/icons.tsx +++ b/discover/src/icons.tsx @@ -14,3 +14,9 @@ export const Refresh = ({ size }: P) => svg(<> svg(, size); export const Library = ({ size }: P) => svg(<>, size); export const Shuffle = ({ size }: P) => svg(<>, size); +export const Plus = ({ size }: P) => svg(, size); +export const Pencil = ({ size }: P) => svg(<>, size); +export const Trash = ({ size }: P) => svg(<>, size); +export const ListMusic = ({ size }: P) => svg(<>, size); +export const Calendar = ({ size }: P) => svg(<>, size); +export const Warning = ({ size }: P) => svg(<>, size); diff --git a/discover/src/styles.css b/discover/src/styles.css index 739fd6d..0f53006 100644 --- a/discover/src/styles.css +++ b/discover/src/styles.css @@ -729,6 +729,282 @@ h2 { cursor: pointer; } +/* ---------- tracked playlists ---------- */ + +.manage { + max-width: 980px; +} + +.manage-header { + margin-bottom: 24px; +} + +.manage-link { + margin-top: 2px; +} + +.manage-link .mix-dot { + color: var(--muted); +} + +.panel { + padding: 18px 20px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.panel + .panel { + margin-top: 20px; +} + +.panel-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 12px; +} + +.panel-header h2 { + margin: 0 0 2px; +} + +.hint { + margin: 0; + color: var(--muted); + font-size: 0.85rem; +} + +.hint code, +.template { + padding: 1px 5px; + border-radius: 4px; + background: var(--surface-2); + font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + font-size: 0.85em; +} + +.template { + font-size: 0.95em; +} + +.items { + margin: 0; + padding: 0; + list-style: none; +} + +.item { + border-top: 1px solid var(--border); +} + +.item-row { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) auto auto; + align-items: center; + gap: 14px; + padding: 12px 0; +} + +.item-icon { + display: grid; + place-items: center; + width: 40px; + height: 40px; + border-radius: 10px; + background: var(--surface-2); + color: var(--muted); +} + +.item-title { + overflow: hidden; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +.item-sub, +.item-aside { + color: var(--muted); + font-size: 0.88rem; +} + +.item-aside { + white-space: nowrap; +} + +.item-actions { + display: flex; + gap: 6px; +} + +.warning-text { + color: var(--youtube); +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 34px; + padding: 6px 12px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); + font-size: 0.88rem; + font-weight: 600; + white-space: nowrap; + cursor: pointer; +} + +.btn:hover:not(:disabled) { + background: var(--surface-2); +} + +.btn:disabled { + opacity: 0.55; + cursor: default; +} + +.btn.icon-only { + width: 34px; + padding: 0; + color: var(--muted); +} + +.btn.primary { + border-color: transparent; + background: var(--accent); + color: var(--accent-text); +} + +.btn.primary:hover:not(:disabled) { + background: color-mix(in srgb, var(--accent) 88%, var(--text)); +} + +.btn.danger { + border-color: transparent; + background: var(--youtube); + color: #fff; +} + +.btn .spinner { + width: 14px; + height: 14px; +} + +.form, +.confirm { + display: flex; + flex-direction: column; + gap: 14px; + margin: 4px 0 16px; + padding: 16px; + border-radius: 10px; + background: var(--surface-2); +} + +.item.editing .form { + margin: 12px 0; +} + +.confirm { + margin-top: 0; +} + +.confirm p { + margin: 0; +} + +.form-grid { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1.2fr) 100px; + gap: 12px; +} + +.field { + display: flex; + flex-direction: column; + gap: 5px; + min-width: 0; +} + +.field.wide { + grid-column: 1 / -1; +} + +.field > span, +.field > label { + font-size: 0.82rem; + font-weight: 600; +} + +.field input, +.field select { + width: 100%; + min-height: 38px; + padding: 7px 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); +} + +.field input.mono { + font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; +} + +.checkbox { + display: flex; + align-items: center; + gap: 8px; + font-size: 0.92rem; +} + +.checkbox input { + width: 16px; + height: 16px; + accent-color: var(--youtube); +} + +.form-error { + margin: 0; + color: var(--youtube); + font-size: 0.9rem; +} + +.form-actions { + display: flex; + justify-content: flex-end; + gap: 8px; +} + +.segmented { + display: inline-flex; + align-self: flex-start; + padding: 3px; + border-radius: 9px; + background: var(--surface); + border: 1px solid var(--border); +} + +.segmented button { + padding: 5px 12px; + border: 0; + border-radius: 6px; + background: none; + color: var(--muted); + font-size: 0.88rem; + font-weight: 600; + cursor: pointer; +} + +.segmented button[aria-checked="true"] { + background: var(--accent); + color: var(--accent-text); +} + /* ---------- small screens ---------- */ @media (max-width: 800px) { @@ -805,6 +1081,42 @@ h2 { display: none; } + .panel { + padding: 14px; + } + + .panel-header { + flex-direction: column; + } + + .item-row { + grid-template-columns: 36px minmax(0, 1fr); + gap: 4px 12px; + } + + .item-icon { + width: 36px; + height: 36px; + } + + .item-aside, + .item-actions { + grid-column: 2; + } + + .item-actions { + flex-wrap: wrap; + margin-top: 6px; + } + + .form-grid { + grid-template-columns: minmax(0, 1fr) 90px; + } + + .form-grid .field:not(.wide):not(.narrow) { + grid-column: 1 / -1; + } + .player { grid-template-columns: minmax(0, 1fr) auto; height: auto; diff --git a/src/daemon/update_playlists.rs b/src/daemon/update_playlists.rs index c4f052c..0ec32dc 100644 --- a/src/daemon/update_playlists.rs +++ b/src/daemon/update_playlists.rs @@ -59,7 +59,7 @@ pub async fn update_playlists_daemon( } } -async fn update_playlist( +pub async fn update_playlist( media_client: impl AsRef, playlist: TrackedPlaylist, ) -> Result<(), Box> { diff --git a/src/main.rs b/src/main.rs index fce4aa3..8237cd2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod models; mod playlist; mod subsonic; mod track; +mod tracked; mod web; mod youtube; @@ -87,6 +88,7 @@ async fn main() -> Result<(), Box> { .manage(database) .manage(youtube) .mount("/api/discover", web::routes()) + .mount("/api/tracked", tracked::routes()) .mount( "/api/playlist", routes![ diff --git a/src/subsonic.rs b/src/subsonic.rs index 25c0ef8..cf0d070 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -43,6 +43,17 @@ struct GetPlaylistResponse { type CreatePlaylistResponse = GetPlaylistResponse; +#[derive(Deserialize)] +struct GetPlaylistsResponse { + playlists: PlaylistList, +} + +#[derive(Deserialize)] +struct PlaylistList { + #[serde(default)] + playlist: Vec, +} + #[derive(Deserialize)] struct GetGenresResponse { genres: GenreList, @@ -287,6 +298,15 @@ impl Subsonic { request.send().await.map_err(SubsonicError::Reqwest) } + /// All of the user's playlists, without their songs + pub async fn get_playlists(&self) -> Result, SubsonicError> { + Ok(self + .request::("getPlaylists", &[]) + .await? + .playlists + .playlist) + } + /// All genres in the library pub async fn get_genres(&self) -> Result, SubsonicError> { Ok(self diff --git a/src/tracked.rs b/src/tracked.rs new file mode 100644 index 0000000..662840b --- /dev/null +++ b/src/tracked.rs @@ -0,0 +1,569 @@ +//! API for managing tracked playlists (Subsonic playlists kept up to date with a Listenbrainz +//! user's top songs) and the rules that create them on a schedule. + +use crate::daemon::update_playlists::update_playlist; +use crate::listenbrainz::StatsRange; +use crate::models::{CreateTrackedPlaylist, TrackedPlaylist}; +use crate::subsonic::Subsonic; +use chrono::format::{Item, StrftimeItems}; +use chrono::Local; +use rocket::http::Status; +use rocket::response::status::Custom; +use rocket::serde::json::Json; +use rocket::{delete, get, post, put, routes, Route, State}; +use serde::{Deserialize, Serialize}; +use sqlx::postgres::PgPool; +use std::collections::HashMap; +use std::sync::Arc; +use uuid::Uuid; + +pub fn routes() -> Vec { + routes![ + playlists, + create_playlist, + update_tracked_playlist, + delete_tracked_playlist, + refresh, + subsonic_playlists, + rules, + create_rule, + update_rule, + delete_rule, + preview_name + ] +} + +#[derive(Serialize)] +pub struct ApiError { + error: String, +} + +type ApiResult = Result, Custom>>; + +fn fail(status: Status, message: impl Into) -> Custom> { + Custom( + status, + Json(ApiError { + error: message.into(), + }), + ) +} + +fn db_error(e: sqlx::Error) -> Custom> { + match e { + sqlx::Error::RowNotFound => fail(Status::NotFound, "Not found"), + e => { + println!("Database error: {:?}", e); + fail(Status::InternalServerError, "Database error") + } + } +} + +fn subsonic_error(e: impl std::fmt::Debug) -> Custom> { + println!("Subsonic error: {:?}", e); + fail(Status::BadGateway, "Couldn't reach Subsonic") +} + +fn parse_id(id: &str) -> Result>> { + Uuid::parse_str(id).map_err(|_| fail(Status::NotFound, "Not found")) +} + +/// Settings shared by tracked playlists and rules +#[derive(Deserialize)] +struct Tracking { + playlist_size: i32, + tracking_user: String, + tracking_type: String, +} + +impl Tracking { + fn validate(&self) -> Result<(), Custom>> { + if !(1..=1000).contains(&self.playlist_size) { + return Err(fail( + Status::UnprocessableEntity, + "Size must be between 1 and 1000", + )); + } + if self.tracking_user.trim().is_empty() { + return Err(fail( + Status::UnprocessableEntity, + "Enter a Listenbrainz user", + )); + } + if StatsRange::from_param(&self.tracking_type).is_none() { + return Err(fail(Status::UnprocessableEntity, "Unknown time period")); + } + Ok(()) + } +} + +/// Format a playlist name template, or explain why it's invalid +fn format_template(template: &str) -> Result>> { + if template.trim().is_empty() { + return Err(fail(Status::UnprocessableEntity, "Enter a name")); + } + // chrono panics when displaying a format with invalid specifiers + if StrftimeItems::new(template).any(|item| matches!(item, Item::Error)) { + return Err(fail( + Status::UnprocessableEntity, + "The name has an invalid % code (use %% for a literal %)", + )); + } + Ok(Local::now().format(template).to_string()) +} + +// --------------------------------------------------------------------------- +// Tracked playlists +// --------------------------------------------------------------------------- + +#[derive(Serialize)] +struct TrackedPlaylistView { + id: Uuid, + playlist_id: Option, + /// Name in Subsonic; None if the playlist no longer exists there + name: Option, + song_count: Option, + playlist_size: i32, + tracking_user: String, + tracking_type: String, +} + +async fn view( + media_client: &Subsonic, + rows: Vec, +) -> Result, Custom>> { + let subsonic: HashMap = media_client + .get_playlists() + .await + .map_err(subsonic_error)? + .into_iter() + .map(|p| (p.id, (p.name, p.song_count))) + .collect(); + + Ok(rows + .into_iter() + .map(|row| { + let found = row.playlist_id.as_ref().and_then(|id| subsonic.get(id)); + TrackedPlaylistView { + id: row.id, + name: found.map(|(name, _)| name.clone()), + song_count: found.map(|(_, count)| *count), + playlist_id: row.playlist_id, + playlist_size: row.playlist_size, + tracking_user: row.tracking_user, + tracking_type: row.tracking_type, + } + }) + .collect()) +} + +#[get("/playlists")] +async fn playlists( + pool: &State, + media_client: &State>, +) -> ApiResult> { + let mut rows = TrackedPlaylist::all(pool.inner()).await.map_err(db_error)?; + rows.sort_by(|a, b| a.tracking_user.cmp(&b.tracking_user)); + let mut out = view(media_client, rows).await?; + out.sort_by(|a, b| { + a.name + .as_deref() + .unwrap_or("") + .to_lowercase() + .cmp(&b.name.as_deref().unwrap_or("").to_lowercase()) + }); + Ok(Json(out)) +} + +#[derive(Deserialize)] +struct NewTrackedPlaylist { + /// Track this existing Subsonic playlist... + playlist_id: Option, + /// ...or create a new one with this name + name: Option, + #[serde(flatten)] + tracking: Tracking, +} + +#[post("/playlists", data = "")] +async fn create_playlist( + body: Json, + pool: &State, + media_client: &State>, +) -> ApiResult { + body.tracking.validate()?; + + let playlist_id = match (&body.playlist_id, body.name.as_deref().map(str::trim)) { + (Some(id), _) => { + media_client + .get_playlist(id) + .await + .map_err(|_| fail(Status::UnprocessableEntity, "That playlist doesn't exist"))?; + let tracked = sqlx::query_scalar!( + r#"SELECT COUNT(*) AS "count!" FROM "tracked_playlist" WHERE playlist_id = $1"#, + id + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + if tracked > 0 { + return Err(fail( + Status::Conflict, + "That playlist is already being tracked", + )); + } + if mix_playlist_ids(pool.inner()).await?.contains(id) { + return Err(fail( + Status::Conflict, + "That's a genre mix, which playlistd already keeps up to date", + )); + } + id.clone() + } + (None, Some(name)) if !name.is_empty() => { + media_client + .create_playlist(name) + .await + .map_err(subsonic_error)? + .id + } + _ => { + return Err(fail( + Status::UnprocessableEntity, + "Choose a playlist or enter a name", + )) + } + }; + + let id = Uuid::new_v4(); + sqlx::query!( + r#" + INSERT INTO "tracked_playlist" (id, playlist_id, playlist_size, tracking_user, tracking_type) + VALUES ($1, $2, $3, $4, $5) + "#, + id, + playlist_id, + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +#[derive(Deserialize)] +struct TrackedPlaylistUpdate { + /// Rename the playlist in Subsonic + name: Option, + #[serde(flatten)] + tracking: Tracking, +} + +#[put("/playlists/", data = "")] +async fn update_tracked_playlist( + id: &str, + body: Json, + pool: &State, + media_client: &State>, +) -> ApiResult { + let id = parse_id(id)?; + body.tracking.validate()?; + + let row = sqlx::query_as!( + TrackedPlaylist, + r#" + UPDATE "tracked_playlist" SET playlist_size = $1, tracking_user = $2, tracking_type = $3 + WHERE id = $4 + RETURNING * + "#, + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + id, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + if let (Some(name), Some(playlist_id)) = (body.name.as_deref().map(str::trim), &row.playlist_id) + { + if !name.is_empty() { + media_client + .rename_playlist(playlist_id, name) + .await + .map_err(subsonic_error)?; + } + } + + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +/// Stop tracking a playlist, optionally deleting it from Subsonic too +#[delete("/playlists/?")] +async fn delete_tracked_playlist( + id: &str, + delete_playlist: Option, + pool: &State, + media_client: &State>, +) -> Result>> { + let row = sqlx::query_as!( + TrackedPlaylist, + r#"DELETE FROM "tracked_playlist" WHERE id = $1 RETURNING *"#, + parse_id(id)? + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + if delete_playlist.unwrap_or(false) { + if let Some(playlist_id) = row.playlist_id { + // it may already be gone from Subsonic + if let Err(e) = media_client.delete_playlist(&playlist_id).await { + println!("Could not delete playlist {}: {:?}", playlist_id, e); + } + } + } + Ok(Status::NoContent) +} + +/// Update a tracked playlist's songs now, rather than on the next daemon tick +#[post("/playlists//refresh")] +async fn refresh( + id: &str, + pool: &State, + media_client: &State>, +) -> ApiResult { + let id = parse_id(id)?; + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + + let result = update_playlist(media_client.inner().clone(), row) + .await + .map_err(|e| e.to_string()); + if let Err(e) = result { + return Err(fail( + Status::BadGateway, + format!("Couldn't update the playlist: {}", e), + )); + } + + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +#[derive(Serialize)] +struct SubsonicPlaylist { + id: String, + name: String, + song_count: usize, + tracked: bool, +} + +/// Playlists maintained as genre mixes, which mustn't also be tracked +async fn mix_playlist_ids(pool: &PgPool) -> Result, Custom>> { + sqlx::query_scalar!(r#"SELECT playlist_id FROM "cluster_mix_playlist""#) + .fetch_all(pool) + .await + .map_err(db_error) +} + +/// Subsonic playlists that could be tracked (genre mixes are left out) +#[get("/subsonic-playlists")] +async fn subsonic_playlists( + pool: &State, + media_client: &State>, +) -> ApiResult> { + let tracked: Vec = TrackedPlaylist::all(pool.inner()) + .await + .map_err(db_error)? + .into_iter() + .filter_map(|p| p.playlist_id) + .collect(); + let mixes = mix_playlist_ids(pool.inner()).await?; + let mut out: Vec = media_client + .get_playlists() + .await + .map_err(subsonic_error)? + .into_iter() + .filter(|p| !mixes.contains(&p.id)) + .map(|p| SubsonicPlaylist { + tracked: tracked.contains(&p.id), + id: p.id, + name: p.name, + song_count: p.song_count, + }) + .collect(); + out.sort_by_key(|p| p.name.to_lowercase()); + Ok(Json(out)) +} + +// --------------------------------------------------------------------------- +// Rules +// --------------------------------------------------------------------------- + +#[derive(Serialize)] +struct RuleView { + #[serde(flatten)] + rule: CreateTrackedPlaylist, + /// The name the rule's next playlist will have, if it differs from the last one + current_name: Option, +} + +fn rule_view(rule: CreateTrackedPlaylist) -> RuleView { + RuleView { + current_name: format_template(&rule.name_template).ok(), + rule, + } +} + +#[get("/rules")] +async fn rules(pool: &State) -> ApiResult> { + let mut rules = CreateTrackedPlaylist::all(pool.inner()) + .await + .map_err(db_error)?; + rules.sort_by(|a, b| a.name_template.cmp(&b.name_template)); + Ok(Json(rules.into_iter().map(rule_view).collect())) +} + +#[derive(Deserialize)] +struct RuleBody { + name_template: String, + #[serde(flatten)] + tracking: Tracking, +} + +#[post("/rules", data = "")] +async fn create_rule(body: Json, pool: &State) -> ApiResult { + body.tracking.validate()?; + format_template(&body.name_template)?; + + let rule = sqlx::query_as!( + CreateTrackedPlaylist, + r#" + INSERT INTO "create_tracked_playlist" (id, name_template, playlist_size, tracking_user, tracking_type) + VALUES ($1, $2, $3, $4, $5) + RETURNING * + "#, + Uuid::new_v4(), + body.name_template.trim(), + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + Ok(Json(rule_view(rule))) +} + +/// Changes apply to playlists the rule creates from now on +#[put("/rules/", data = "")] +async fn update_rule(id: &str, body: Json, pool: &State) -> ApiResult { + body.tracking.validate()?; + format_template(&body.name_template)?; + + let rule = sqlx::query_as!( + CreateTrackedPlaylist, + r#" + UPDATE "create_tracked_playlist" + SET name_template = $1, playlist_size = $2, tracking_user = $3, tracking_type = $4 + WHERE id = $5 + RETURNING * + "#, + body.name_template.trim(), + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + parse_id(id)?, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + Ok(Json(rule_view(rule))) +} + +/// Delete a rule. Playlists it already created keep being tracked. +#[delete("/rules/")] +async fn delete_rule(id: &str, pool: &State) -> Result>> { + let result = sqlx::query!( + r#"DELETE FROM "create_tracked_playlist" WHERE id = $1"#, + parse_id(id)? + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + if result.rows_affected() == 0 { + return Err(fail(Status::NotFound, "Not found")); + } + Ok(Status::NoContent) +} + +#[derive(Serialize)] +struct NamePreview { + name: String, +} + +/// What a name template produces today +#[get("/preview-name?