Add UI for managing tracked playlists

A "Tracked playlists" page in the web UI lists, creates, edits, refreshes
and removes tracked playlists, and manages the rules that create a new
tracked playlist each period.

- New /api/tracked routes. Input is validated with readable errors,
  including name templates, which made the create daemon panic when they
  had an invalid % code.
- New playlists can be created in Subsonic or picked from existing ones.
  Genre mix playlists can't be tracked, since two daemons would fight
  over their songs.
- "Refresh" updates a playlist straight away, and the page shows when
  some of the top songs couldn't be found in the library.
- Removing a playlist can also delete it from Subsonic.
- Rule names preview live as you type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p
This commit is contained in:
Claude committed 2026-11-13 19:59:09 +00:00
1 parent 2dd8621568
commit e176ddac6c
10 files changed
+1536 -10

No files matched your search

+16
View File
@@ -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/<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 |
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/<id>` | Change size, user or period; rename with `name` |
| `DELETE /playlists/<id>?delete_playlist=true` | Stop tracking, optionally deleting the playlist |
| `POST /playlists/<id>/refresh` | Update a playlist's songs now |
| `GET /subsonic-playlists` | Playlists that can be tracked |
| `GET`/`POST /rules`, `PUT`/`DELETE /rules/<id>` | Recurring playlist rules |
| `GET /preview-name?template=` | What a name template produces today |
+15 -5
View File
@@ -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 && <span className="count">{liked.length}</span>}
</a>
</li>
<li className="manage-link">
<a href="#/tracked" className={route.view === "tracked" ? "selected" : ""} style={{ ["--hue" as string]: 220 }}>
<span className="mix-dot heart" aria-hidden="true"><Icon.ListMusic size={14} /></span>
<span className="mix-name">Tracked playlists</span>
</a>
</li>
</ul>
</nav>
<main className="content">
{error && <div className="notice error">{error}</div>}
{rules && rules.length === 0 && (
{route.view !== "tracked" && 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 && (
{route.view !== "tracked" && pending && mixes?.length === 0 && (
<div className="notice"><span className="spinner" /> Building mixes from your recent listens…</div>
)}
{route.view === "liked" ? (
{route.view === "tracked" ? (
<TrackedView defaultUser={rule?.tracking_user} onToast={(message) => setToast({ message })} />
) : route.view === "liked" ? (
<LikedView liked={liked} player={player} onStatus={onStatus} />
) : detail ? (
<MixView mix={detail} knownRatio={rule?.familiar_ratio ?? 0.3} player={player} onStatus={onStatus} />
+522
View File
@@ -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<TrackedPlaylist[] | null>(null);
const [rules, setRules] = useState<TrackedRule[] | null>(null);
const [error, setError] = useState<string | null>(null);
// "new-playlist", "new-rule", or the id of the item being edited
const [editing, setEditing] = useState<string | null>(null);
const [confirming, setConfirming] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState<Set<string>>(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 = <T extends { id: string }>(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 (
<article className="manage">
<header className="manage-header">
<p className="eyebrow">Manage</p>
<h1>Tracked playlists</h1>
<p className="mix-counts">
Subsonic playlists kept up to date with your top songs on Listenbrainz.
</p>
</header>
{error && <div className="notice error" role="alert">{error}</div>}
<section className="panel" aria-labelledby="tracked-heading">
<div className="panel-header">
<div>
<h2 id="tracked-heading"><Icon.ListMusic size={17} /> Playlists</h2>
<p className="hint">Refreshed automatically every few minutes.</p>
</div>
{editing !== "new-playlist" && (
<button className="btn primary" onClick={() => setEditing("new-playlist")}>
<Icon.Plus size={16} /> New playlist
</button>
)}
</div>
{editing === "new-playlist" && (
<PlaylistForm
users={users}
initial={{ playlist_size: 50, tracking_user: suggestedUser, tracking_type: "month" }}
onCancel={() => setEditing(null)}
onSaved={(p) => {
setPlaylists((ps) => replace(ps, p));
setEditing(null);
onToast(`Tracking “${p.name}”. Refreshing it now…`);
void refresh(p);
}}
/>
)}
{playlists === null ? (
<p className="empty"><span className="spinner" /> Loading…</p>
) : playlists.length === 0 && editing !== "new-playlist" ? (
<p className="empty">No tracked playlists yet. Create one to keep, say, your top 50 of the last month in Subsonic.</p>
) : (
<ul className="items">
{playlists.map((p) =>
editing === p.id ? (
<li key={p.id} className="item editing">
<PlaylistForm
users={users}
initial={p}
onCancel={() => setEditing(null)}
onSaved={(updated) => {
setPlaylists((ps) => replace(ps, updated));
setEditing(null);
onToast("Saved. Refresh to apply the changes now.");
}}
/>
</li>
) : (
<Item
key={p.id}
icon={p.name ? <Icon.ListMusic size={20} /> : <Icon.Warning size={20} />}
title={p.name ?? <span className="warning-text">Missing from Subsonic</span>}
subtitle={describe(p)}
aside={
p.song_count === null ? undefined : p.song_count > 0 && p.song_count < p.playlist_size ? (
<span title="Some of the top songs aren't in your library">
{p.song_count} of {p.playlist_size} found
</span>
) : (
`${p.song_count} songs`
)
}
actions={
<>
<button className="btn" onClick={() => refresh(p)} disabled={refreshing.has(p.id) || !p.name}>
{refreshing.has(p.id) ? <span className="spinner" /> : <Icon.Refresh size={15} />} Refresh
</button>
<button className="btn" onClick={() => setEditing(p.id)} aria-label={`Edit ${p.name ?? "playlist"}`}>
<Icon.Pencil size={15} /> Edit
</button>
<button className="btn icon-only" onClick={() => setConfirming(p.id)} aria-label={`Stop tracking ${p.name ?? "playlist"}`} title="Stop tracking">
<Icon.Trash size={15} />
</button>
</>
}
confirm={
confirming === p.id && (
<RemovePlaylist
playlist={p}
onCancel={() => 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.");
}}
/>
)
}
/>
),
)}
</ul>
)}
</section>
<section className="panel" aria-labelledby="rules-heading">
<div className="panel-header">
<div>
<h2 id="rules-heading"><Icon.Calendar size={17} /> Recurring playlists</h2>
<p className="hint">Start a new tracked playlist whenever the name changes, e.g. each year or month.</p>
</div>
{editing !== "new-rule" && (
<button className="btn primary" onClick={() => setEditing("new-rule")}>
<Icon.Plus size={16} /> New rule
</button>
)}
</div>
{editing === "new-rule" && (
<RuleForm
users={users}
initial={{ name_template: "%Y - Top 100", playlist_size: 100, tracking_user: suggestedUser, tracking_type: "this_year" }}
onCancel={() => 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 ? (
<p className="empty"><span className="spinner" /> Loading…</p>
) : rules.length === 0 && editing !== "new-rule" ? (
<p className="empty">No recurring playlists. A rule like “%Y - Top 100” makes a new top 100 every year.</p>
) : (
<ul className="items">
{rules.map((r) =>
editing === r.id ? (
<li key={r.id} className="item editing">
<RuleForm
users={users}
initial={r}
onCancel={() => setEditing(null)}
onSaved={(updated) => {
setRules((rs) => replace(rs, updated));
setEditing(null);
onToast("Saved. Applies to playlists the rule makes from now on.");
}}
/>
</li>
) : (
<Item
key={r.id}
icon={<Icon.Calendar size={20} />}
title={<code className="template">{r.name_template}</code>}
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={
<>
<button className="btn" onClick={() => setEditing(r.id)} aria-label={`Edit rule ${r.name_template}`}>
<Icon.Pencil size={15} /> Edit
</button>
<button className="btn icon-only" onClick={() => setConfirming(r.id)} aria-label={`Delete rule ${r.name_template}`} title="Delete rule">
<Icon.Trash size={15} />
</button>
</>
}
confirm={
confirming === r.id && (
<Confirm
message="Delete this rule? Playlists it already made keep being tracked."
action="Delete rule"
onCancel={() => setConfirming(null)}
onConfirm={async () => {
await trackedApi.removeRule(r.id);
setRules((rs) => rs?.filter((x) => x.id !== r.id) ?? null);
setConfirming(null);
}}
/>
)
}
/>
),
)}
</ul>
)}
</section>
</article>
);
}
function Item(props: { icon: ReactNode; title: ReactNode; subtitle: string; aside?: ReactNode; actions: ReactNode; confirm?: ReactNode }) {
return (
<li className="item">
<div className="item-row">
<div className="item-icon" aria-hidden="true">{props.icon}</div>
<div className="item-text">
<div className="item-title">{props.title}</div>
<div className="item-sub">{props.subtitle}</div>
</div>
{props.aside && <div className="item-aside">{props.aside}</div>}
<div className="item-actions">{props.actions}</div>
</div>
{props.confirm}
</li>
);
}
function Confirm(props: { message: ReactNode; action: string; onCancel: () => void; onConfirm: () => Promise<void>; children?: ReactNode }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<div className="confirm" role="alertdialog" aria-label={props.action}>
<p>{props.message}</p>
{props.children}
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
<button className="btn" onClick={props.onCancel} autoFocus>Cancel</button>
<button
className="btn danger"
disabled={busy}
onClick={async () => {
setBusy(true);
setError(null);
try {
await props.onConfirm();
} catch (e) {
setError((e as Error).message);
setBusy(false);
}
}}
>
{busy && <span className="spinner" />} {props.action}
</button>
</div>
</div>
);
}
function RemovePlaylist(props: { playlist: TrackedPlaylist; onCancel: () => void; onRemoved: (deleted: boolean) => void }) {
const [alsoDelete, setAlsoDelete] = useState(false);
return (
<Confirm
message={<>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 && (
<label className="checkbox">
<input type="checkbox" checked={alsoDelete} onChange={(e) => setAlsoDelete(e.target.checked)} />
Also delete the playlist from Subsonic
</label>
)}
</Confirm>
);
}
/** Fields shared by playlists and rules */
function TrackingFields({ value, onChange, users }: { value: Tracking; onChange: (t: Tracking) => void; users: string[] }) {
return (
<>
<label className="field">
<span>Listenbrainz user</span>
<input
required
list="lb-users"
value={value.tracking_user}
onChange={(e) => onChange({ ...value, tracking_user: e.target.value })}
autoComplete="off"
spellCheck={false}
/>
<datalist id="lb-users">{users.map((u) => <option key={u} value={u} />)}</datalist>
</label>
<label className="field">
<span>Top songs from</span>
<select value={value.tracking_type} onChange={(e) => onChange({ ...value, tracking_type: e.target.value })}>
{PERIODS.map(([v, label]) => <option key={v} value={v}>{label}</option>)}
</select>
</label>
<label className="field narrow">
<span>Songs</span>
<input
type="number"
required
min={1}
max={1000}
value={value.playlist_size}
onChange={(e) => onChange({ ...value, playlist_size: Number(e.target.value) })}
/>
</label>
</>
);
}
function useSubmit<T>(save: () => Promise<T>, onSaved: (t: T) => void) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(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<TrackedPlaylist>;
users: string[];
onCancel: () => void;
onSaved: (p: TrackedPlaylist) => void;
}) {
const creating = !props.initial.id;
const [tracking, setTracking] = useState<Tracking>({
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<SubsonicPlaylist[] | null>(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 (
<form className="form" onSubmit={submit} aria-label={creating ? "New tracked playlist" : "Edit tracked playlist"}>
{creating && (
<div className="segmented" role="radiogroup" aria-label="Playlist">
<button type="button" role="radio" aria-checked={mode === "new"} onClick={() => setMode("new")}>New playlist</button>
<button type="button" role="radio" aria-checked={mode === "existing"} onClick={() => setMode("existing")}>Existing playlist</button>
</div>
)}
<div className="form-grid">
{creating && mode === "existing" ? (
<div className="field wide">
<label htmlFor="existing-playlist">Subsonic playlist</label>
<select id="existing-playlist" required value={existingId} onChange={(e) => setExistingId(e.target.value)}
disabled={!subsonic} aria-describedby="existing-help">
<option value="">{subsonic === null ? "Loading…" : available.length ? "Choose a playlist" : "No untracked playlists"}</option>
{available.map((p) => <option key={p.id} value={p.id}>{p.name} ({p.song_count} songs)</option>)}
</select>
<small className="hint" id="existing-help">Its songs will be replaced with your top songs.</small>
</div>
) : (
(creating || props.initial.name) && (
<label className="field wide">
<span>Name</span>
<input required={creating} value={name} onChange={(e) => setName(e.target.value)} placeholder="Top songs this month" />
</label>
)
)}
<TrackingFields value={tracking} onChange={setTracking} users={props.users} />
</div>
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
<button type="button" className="btn" onClick={props.onCancel}>Cancel</button>
<button type="submit" className="btn primary" disabled={busy}>
{busy && <span className="spinner light" />} {creating ? "Create" : "Save"}
</button>
</div>
</form>
);
}
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<Tracking>({
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 (
<form className="form" onSubmit={submit} aria-label={creating ? "New recurring playlist" : "Edit recurring playlist"}>
<div className="form-grid">
<div className="field wide">
<label htmlFor="rule-template">Name</label>
<input id="rule-template" required value={template} onChange={(e) => setTemplate(e.target.value)} spellCheck={false}
aria-describedby="template-help" className="mono" />
<small className="hint" id="template-help" aria-live="polite">
{preview.error ? (
<span className="warning-text">{preview.error}</span>
) : preview.name ? (
<>Today this makes <strong>{preview.name}</strong>. </>
) : null}
Use <code>%Y</code> for the year, <code>%B</code> the month, <code>%m</code> its number, <code>%V</code> the week. A new playlist starts whenever the name changes.
</small>
</div>
<TrackingFields value={tracking} onChange={setTracking} users={props.users} />
</div>
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
<button type="button" className="btn" onClick={props.onCancel}>Cancel</button>
<button type="submit" className="btn primary" disabled={busy || !!preview.error}>
{busy && <span className="spinner light" />} {creating ? "Create" : "Save"}
</button>
</div>
</form>
);
}
+73 -4
View File
@@ -49,14 +49,22 @@ export type MixDetail = MixSummary & {
suggestions: Suggestion[];
};
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(`/api/discover${path}`, init);
async function request<T>(path: string, init?: RequestInit, base = "/api/discover"): Promise<T> {
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<Rule[]>("/rules"),
mixes: (ruleId: string) => request<MixSummary[]>(`/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 = <T>(path: string, init?: RequestInit) => request<T>(path, init, "/api/tracked");
export const trackedApi = {
playlists: () => tracked<TrackedPlaylist[]>("/playlists"),
create: (body: Tracking & { name?: string; playlist_id?: string }) =>
tracked<TrackedPlaylist>("/playlists", json("POST", body)),
update: (id: string, body: Tracking & { name?: string }) =>
tracked<TrackedPlaylist>(`/playlists/${id}`, json("PUT", body)),
remove: (id: string, deletePlaylist: boolean) =>
tracked<void>(`/playlists/${id}?delete_playlist=${deletePlaylist}`, { method: "DELETE" }),
refresh: (id: string) => tracked<TrackedPlaylist>(`/playlists/${id}/refresh`, { method: "POST" }),
subsonicPlaylists: () => tracked<SubsonicPlaylist[]>("/subsonic-playlists"),
rules: () => tracked<TrackedRule[]>("/rules"),
createRule: (body: Tracking & { name_template: string }) => tracked<TrackedRule>("/rules", json("POST", body)),
updateRule: (id: string, body: Tracking & { name_template: string }) =>
tracked<TrackedRule>(`/rules/${id}`, json("PUT", body)),
removeRule: (id: string) => tracked<void>(`/rules/${id}`, { method: "DELETE" }),
previewName: (template: string) =>
tracked<{ name: string }>(`/preview-name?template=${encodeURIComponent(template)}`),
};
+6
View File
@@ -14,3 +14,9 @@ export const Refresh = ({ size }: P) => svg(<><path d="M20 11a8 8 0 1 0-2.3 5.7"
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);
export const Plus = ({ size }: P) => svg(<path d="M12 5v14M5 12h14" />, size);
export const Pencil = ({ size }: P) => svg(<><path d="M4 20h4L19 9l-4-4L4 16z" /><path d="M13.5 6.5l4 4" /></>, size);
export const Trash = ({ size }: P) => svg(<><path d="M4 7h16" /><path d="M9 7V4h6v3" /><path d="M6 7l1 13h10l1-13" /></>, size);
export const ListMusic = ({ size }: P) => svg(<><path d="M4 6h11M4 11h11M4 16h7" /><circle cx="17" cy="17" r="2.5" /><path d="M19.5 17V8l2-1" /></>, size);
export const Calendar = ({ size }: P) => svg(<><rect x="4" y="5" width="16" height="15" rx="2" /><path d="M4 10h16M9 3v4M15 3v4" /></>, size);
export const Warning = ({ size }: P) => svg(<><path d="M12 4l9 16H3z" /><path d="M12 10v4M12 17v.5" /></>, size);
+312
View File
@@ -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;
+1 -1
View File
@@ -59,7 +59,7 @@ pub async fn update_playlists_daemon(
}
}
async fn update_playlist(
pub async fn update_playlist(
media_client: impl AsRef<Subsonic>,
playlist: TrackedPlaylist,
) -> Result<(), Box<dyn std::error::Error>> {
+2
View File
@@ -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<dyn std::error::Error>> {
.manage(database)
.manage(youtube)
.mount("/api/discover", web::routes())
.mount("/api/tracked", tracked::routes())
.mount(
"/api/playlist",
routes![
+20
View File
@@ -43,6 +43,17 @@ struct GetPlaylistResponse {
type CreatePlaylistResponse = GetPlaylistResponse;
#[derive(Deserialize)]
struct GetPlaylistsResponse {
playlists: PlaylistList,
}
#[derive(Deserialize)]
struct PlaylistList {
#[serde(default)]
playlist: Vec<Playlist>,
}
#[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<Vec<Playlist>, SubsonicError> {
Ok(self
.request::<GetPlaylistsResponse>("getPlaylists", &[])
.await?
.playlists
.playlist)
}
/// All genres in the library
pub async fn get_genres(&self) -> Result<Vec<Genre>, SubsonicError> {
Ok(self
+569
View File
@@ -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<Route> {
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<T> = Result<Json<T>, Custom<Json<ApiError>>>;
fn fail(status: Status, message: impl Into<String>) -> Custom<Json<ApiError>> {
Custom(
status,
Json(ApiError {
error: message.into(),
}),
)
}
fn db_error(e: sqlx::Error) -> Custom<Json<ApiError>> {
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<Json<ApiError>> {
println!("Subsonic error: {:?}", e);
fail(Status::BadGateway, "Couldn't reach Subsonic")
}
fn parse_id(id: &str) -> Result<Uuid, Custom<Json<ApiError>>> {
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<Json<ApiError>>> {
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<String, Custom<Json<ApiError>>> {
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<String>,
/// Name in Subsonic; None if the playlist no longer exists there
name: Option<String>,
song_count: Option<usize>,
playlist_size: i32,
tracking_user: String,
tracking_type: String,
}
async fn view(
media_client: &Subsonic,
rows: Vec<TrackedPlaylist>,
) -> Result<Vec<TrackedPlaylistView>, Custom<Json<ApiError>>> {
let subsonic: HashMap<String, (String, usize)> = 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<PgPool>,
media_client: &State<Arc<Subsonic>>,
) -> ApiResult<Vec<TrackedPlaylistView>> {
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<String>,
/// ...or create a new one with this name
name: Option<String>,
#[serde(flatten)]
tracking: Tracking,
}
#[post("/playlists", data = "<body>")]
async fn create_playlist(
body: Json<NewTrackedPlaylist>,
pool: &State<PgPool>,
media_client: &State<Arc<Subsonic>>,
) -> ApiResult<TrackedPlaylistView> {
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<String>,
#[serde(flatten)]
tracking: Tracking,
}
#[put("/playlists/<id>", data = "<body>")]
async fn update_tracked_playlist(
id: &str,
body: Json<TrackedPlaylistUpdate>,
pool: &State<PgPool>,
media_client: &State<Arc<Subsonic>>,
) -> ApiResult<TrackedPlaylistView> {
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/<id>?<delete_playlist>")]
async fn delete_tracked_playlist(
id: &str,
delete_playlist: Option<bool>,
pool: &State<PgPool>,
media_client: &State<Arc<Subsonic>>,
) -> Result<Status, Custom<Json<ApiError>>> {
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/<id>/refresh")]
async fn refresh(
id: &str,
pool: &State<PgPool>,
media_client: &State<Arc<Subsonic>>,
) -> ApiResult<TrackedPlaylistView> {
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<Vec<String>, Custom<Json<ApiError>>> {
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<PgPool>,
media_client: &State<Arc<Subsonic>>,
) -> ApiResult<Vec<SubsonicPlaylist>> {
let tracked: Vec<String> = 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<SubsonicPlaylist> = 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<String>,
}
fn rule_view(rule: CreateTrackedPlaylist) -> RuleView {
RuleView {
current_name: format_template(&rule.name_template).ok(),
rule,
}
}
#[get("/rules")]
async fn rules(pool: &State<PgPool>) -> ApiResult<Vec<RuleView>> {
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 = "<body>")]
async fn create_rule(body: Json<RuleBody>, pool: &State<PgPool>) -> ApiResult<RuleView> {
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/<id>", data = "<body>")]
async fn update_rule(id: &str, body: Json<RuleBody>, pool: &State<PgPool>) -> ApiResult<RuleView> {
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/<id>")]
async fn delete_rule(id: &str, pool: &State<PgPool>) -> Result<Status, Custom<Json<ApiError>>> {
let result = sqlx::query!(
r#"DELETE FROM "create_tracked_playlist" WHERE id = $1"#,
parse_id(id)?
)
.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?<template>")]
async fn preview_name(template: &str) -> ApiResult<NamePreview> {
Ok(Json(NamePreview {
name: format_template(template)?,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validates_templates() {
assert!(format_template("%Y - Top 100").is_ok());
assert!(format_template("100%% hits").is_ok());
assert!(format_template("Top %Q").is_err());
assert!(format_template("50% off").is_err());
assert!(format_template(" ").is_err());
}
#[test]
fn validates_tracking() {
let ok = Tracking {
playlist_size: 50,
tracking_user: "jellywx".into(),
tracking_type: "this_year".into(),
};
assert!(ok.validate().is_ok());
for bad in [
Tracking {
playlist_size: 0,
..clone(&ok)
},
Tracking {
tracking_user: " ".into(),
..clone(&ok)
},
Tracking {
tracking_type: "fortnight".into(),
..clone(&ok)
},
] {
assert!(bad.validate().is_err());
}
}
fn clone(t: &Tracking) -> Tracking {
Tracking {
playlist_size: t.playlist_size,
tracking_user: t.tracking_user.clone(),
tracking_type: t.tracking_type.clone(),
}
}
}