Import page in the web UI, worker service and import monitoring
- New Import page: upload an export (with upload progress) or, when the server has a Last.fm API key, import straight from a Last.fm username; jobs list with live progress, counts, errors and cancelling - docker compose runs the import worker from the API image; the API image no longer sets PROMETHEUS_MULTIPROC_DIR (gunicorn.conf.py does, and other commands must not inherit multiprocess mode) - Prometheus scrapes the worker; Usage dashboard gains an Imports row; ImportWorkerDown and ImportJobsWaiting alerts - README and .env.example document imports and LASTFM_API_KEY Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
eebd7b8730
commit
e40a074a64
12 files changed
+754
-3
No files matched your search
@@ -779,3 +779,68 @@ input {
|
||||
transition: width 1s linear;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Import --------------------------------------------------------------- */
|
||||
.import-sources {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
|
||||
gap: 2rem 3rem;
|
||||
margin-bottom: 3rem;
|
||||
}
|
||||
|
||||
.import-sources section + section {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.import-sources h2 {
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.import-sources .muted {
|
||||
margin-bottom: 1.1rem;
|
||||
}
|
||||
|
||||
.stacked-form .button {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.field input[type="file"] {
|
||||
padding: 0.45rem;
|
||||
}
|
||||
|
||||
.bar {
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: var(--bar);
|
||||
overflow: hidden;
|
||||
margin: 0.6rem 0;
|
||||
}
|
||||
|
||||
.bar-fill {
|
||||
height: 100%;
|
||||
width: 0;
|
||||
background: var(--slate);
|
||||
}
|
||||
|
||||
.upload-progress {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.import-status {
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
|
||||
.import-running .bar-fill {
|
||||
background: var(--ok);
|
||||
}
|
||||
|
||||
.import-date {
|
||||
font-size: var(--step--1);
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.bar-fill {
|
||||
transition: width 0.4s ease-out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Import · Scrobbler</title>
|
||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<script src="config.js"></script>
|
||||
<script type="module" src="js/import.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header" id="site-header"></header>
|
||||
<main id="main">
|
||||
<h1 class="page-title">Import history</h1>
|
||||
<p class="lede">Bring in your Last.fm history. Plays that are already here are skipped, so importing the same history twice is safe.</p>
|
||||
<div id="messages"></div>
|
||||
<div class="import-sources">
|
||||
<section aria-labelledby="file-title">
|
||||
<h2 id="file-title">From an export file</h2>
|
||||
<p class="muted">A CSV from lastfm-to-csv, any CSV with artist, track and date columns, or a JSON export of your scrobbles. Gzipped files work too.</p>
|
||||
<form id="file-form" class="stacked-form">
|
||||
<div class="field">
|
||||
<label for="file">Export file</label>
|
||||
<input id="file" name="file" type="file" accept=".csv,.tsv,.txt,.json,.gz" required>
|
||||
<span class="hint" id="file-limit"></span>
|
||||
</div>
|
||||
<div class="upload-progress" id="upload-progress" hidden>
|
||||
<div class="bar" aria-hidden="true"><div class="bar-fill"></div></div>
|
||||
<span class="muted" role="status"></span>
|
||||
</div>
|
||||
<button class="button" type="submit">Upload and import</button>
|
||||
</form>
|
||||
</section>
|
||||
<section aria-labelledby="lastfm-title" id="lastfm-section" hidden>
|
||||
<h2 id="lastfm-title">Straight from Last.fm</h2>
|
||||
<p class="muted">Copies the public scrobble history of a Last.fm account. Large histories take a few minutes; you can leave this page while it runs.</p>
|
||||
<form id="lastfm-form" class="stacked-form">
|
||||
<div class="field">
|
||||
<label for="lastfm-username">Last.fm username</label>
|
||||
<input id="lastfm-username" name="username" required maxlength="64" autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<button class="button" type="submit">Import from Last.fm</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
<section aria-labelledby="jobs-title">
|
||||
<h2 id="jobs-title" class="section-head">Your imports</h2>
|
||||
<ul class="rows" id="jobs"></ul>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -87,3 +87,46 @@ export function describeError(error) {
|
||||
}
|
||||
return error.message;
|
||||
}
|
||||
|
||||
// Multipart upload with progress (fetch can't report upload progress).
|
||||
export function upload(path, formData, onProgress) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", `${apiBase}/api/v1${path}`);
|
||||
const token = getToken();
|
||||
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
|
||||
xhr.upload.addEventListener("progress", (event) => {
|
||||
if (event.lengthComputable) onProgress?.(event.loaded / event.total);
|
||||
});
|
||||
xhr.addEventListener("error", () =>
|
||||
reject(new ApiError(0, "network", `Can't reach the Scrobbler API at ${apiBase}. Check that it's running.`)),
|
||||
);
|
||||
xhr.addEventListener("load", () => {
|
||||
let data = null;
|
||||
try {
|
||||
data = JSON.parse(xhr.responseText);
|
||||
} catch {
|
||||
// Not JSON (e.g. a proxy's error page)
|
||||
}
|
||||
if (xhr.status === 401) {
|
||||
setToken(null);
|
||||
redirectToLogin();
|
||||
return;
|
||||
}
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve(data);
|
||||
return;
|
||||
}
|
||||
const error = data?.error ?? {};
|
||||
reject(
|
||||
new ApiError(
|
||||
xhr.status,
|
||||
error.code ?? "error",
|
||||
error.message ?? (xhr.status === 413 ? "That file is too large." : `Upload failed (${xhr.status}).`),
|
||||
error.details,
|
||||
),
|
||||
);
|
||||
});
|
||||
xhr.send(formData);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { api, describeError, upload } from "./api.js";
|
||||
import { errorBox, formatDate, h, num, replace, timeAgo } from "./dom.js";
|
||||
import { signedInPage } from "./layout.js";
|
||||
|
||||
const POLL_MS = 2000;
|
||||
// Declared before the top-level awaits below, which render jobs straight away.
|
||||
const STATUS_TEXT = {
|
||||
pending: "Waiting to start",
|
||||
running: "Importing",
|
||||
completed: "Finished",
|
||||
failed: "Failed",
|
||||
cancelled: "Cancelled",
|
||||
};
|
||||
const messages = document.getElementById("messages");
|
||||
const jobsList = document.getElementById("jobs");
|
||||
const fileForm = document.getElementById("file-form");
|
||||
const lastfmForm = document.getElementById("lastfm-form");
|
||||
const progress = document.getElementById("upload-progress");
|
||||
|
||||
let pollTimer;
|
||||
|
||||
await signedInPage("import.html");
|
||||
try {
|
||||
const options = await api("/imports/options");
|
||||
document.getElementById("file-limit").textContent = `Up to ${formatBytes(options.max_upload_bytes)}.`;
|
||||
document.getElementById("lastfm-section").hidden = !options.sources.includes("lastfm");
|
||||
} catch (error) {
|
||||
replace(messages, errorBox(error.message));
|
||||
}
|
||||
await refresh();
|
||||
|
||||
fileForm.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const file = fileForm.elements.file.files[0];
|
||||
if (!file) return;
|
||||
const button = fileForm.querySelector("button");
|
||||
const fill = progress.querySelector(".bar-fill");
|
||||
const status = progress.querySelector("[role=status]");
|
||||
button.disabled = true;
|
||||
progress.hidden = false;
|
||||
replace(messages);
|
||||
try {
|
||||
const data = new FormData();
|
||||
data.append("file", file);
|
||||
await upload("/imports/file", data, (fraction) => {
|
||||
fill.style.width = `${Math.round(fraction * 100)}%`;
|
||||
status.textContent = fraction < 1 ? `Uploading ${Math.round(fraction * 100)}%` : "Starting the import";
|
||||
});
|
||||
fileForm.reset();
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
replace(messages, errorBox(describeError(error)));
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
progress.hidden = true;
|
||||
fill.style.width = "0";
|
||||
}
|
||||
});
|
||||
|
||||
lastfmForm.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const button = lastfmForm.querySelector("button");
|
||||
button.disabled = true;
|
||||
replace(messages);
|
||||
try {
|
||||
await api("/imports/lastfm", { method: "POST", body: { username: lastfmForm.elements.username.value.trim() } });
|
||||
lastfmForm.reset();
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
replace(messages, errorBox(describeError(error)));
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function refresh() {
|
||||
clearTimeout(pollTimer);
|
||||
let jobs;
|
||||
try {
|
||||
jobs = await api("/imports");
|
||||
} catch (error) {
|
||||
replace(jobsList, h("li", {}, errorBox(error.message)));
|
||||
return;
|
||||
}
|
||||
if (!jobs.length) {
|
||||
replace(jobsList, h("li", { class: "empty" }, "Nothing imported yet."));
|
||||
return;
|
||||
}
|
||||
replace(jobsList, jobs.map(jobRow));
|
||||
if (jobs.some((job) => job.status === "pending" || job.status === "running")) {
|
||||
pollTimer = setTimeout(refresh, POLL_MS);
|
||||
}
|
||||
}
|
||||
|
||||
function jobRow(job) {
|
||||
const title = job.source === "lastfm" ? `Last.fm: ${job.lastfm_username}` : job.filename;
|
||||
const active = job.status === "pending" || job.status === "running";
|
||||
const fraction = job.total ? Math.min(1, job.processed / job.total) : 0;
|
||||
const when = job.finished_at ?? job.started_at ?? job.created_at;
|
||||
|
||||
const counts = [
|
||||
`${num(job.imported)} added`,
|
||||
job.duplicates ? `${num(job.duplicates)} already in your history` : null,
|
||||
job.skipped ? `${num(job.skipped)} skipped` : null,
|
||||
].filter(Boolean);
|
||||
|
||||
return h(
|
||||
"li",
|
||||
{ class: `import-job import-${job.status}` },
|
||||
h(
|
||||
"div",
|
||||
{ class: "row-head" },
|
||||
h("span", { class: "row-title" }, title),
|
||||
active
|
||||
? h(
|
||||
"button",
|
||||
{ type: "button", class: "button button-quiet", onclick: () => cancel(job) },
|
||||
"Cancel import",
|
||||
)
|
||||
: null,
|
||||
),
|
||||
h(
|
||||
"p",
|
||||
{ class: "import-status" },
|
||||
h("strong", {}, STATUS_TEXT[job.status] ?? job.status),
|
||||
` ${timeAgo(when)}`,
|
||||
job.status === "running" && job.total ? `, ${num(job.processed)} of ${num(job.total)}` : "",
|
||||
),
|
||||
active
|
||||
? h(
|
||||
"div",
|
||||
{
|
||||
class: "bar",
|
||||
role: "progressbar",
|
||||
"aria-valuemin": 0,
|
||||
"aria-valuemax": 100,
|
||||
"aria-valuenow": Math.round(fraction * 100),
|
||||
"aria-label": `Progress of ${title}`,
|
||||
},
|
||||
h("div", { class: "bar-fill", style: `width: ${fraction * 100}%` }),
|
||||
)
|
||||
: null,
|
||||
job.status === "pending" && Date.now() - new Date(job.created_at) > 60_000
|
||||
? h("p", { class: "muted" }, "Still waiting? The import worker may not be running on the server.")
|
||||
: null,
|
||||
job.processed || job.status === "completed" ? h("p", { class: "muted" }, counts.join(", ")) : null,
|
||||
job.error ? h("p", { class: "notice notice-error" }, job.error) : null,
|
||||
h("p", { class: "muted import-date" }, `Started ${formatDate(job.created_at)}`),
|
||||
);
|
||||
}
|
||||
|
||||
async function cancel(job) {
|
||||
try {
|
||||
await api(`/imports/${job.id}/cancel`, { method: "POST" });
|
||||
} catch (error) {
|
||||
replace(messages, errorBox(error.message));
|
||||
}
|
||||
await refresh();
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
const mb = bytes / (1024 * 1024);
|
||||
return mb >= 1 ? `${num(Math.round(mb))} MB` : `${num(Math.round(bytes / 1024))} KB`;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ const NAV = [
|
||||
["history.html", "History"],
|
||||
["apps.html", "Apps"],
|
||||
["sessions.html", "Sessions"],
|
||||
["import.html", "Import"],
|
||||
];
|
||||
|
||||
// Renders the header and returns the signed-in user (redirecting if there isn't one).
|
||||
|
||||
Reference in new issue
Block a user