From e40a074a648f3200f82a2fb1efbcfed478605146 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 15:10:15 +0100 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- .env.example | 3 + README.md | 23 +- deploy/grafana/dashboards/usage.json | 359 +++++++++++++++++++++++++++ deploy/prometheus/alerts.yml | 16 ++ deploy/prometheus/prometheus.yml | 4 + docker-compose.yml | 23 +- docker/api.Dockerfile | 3 +- frontend/css/style.css | 65 +++++ frontend/import.html | 53 ++++ frontend/js/api.js | 43 ++++ frontend/js/import.js | 164 ++++++++++++ frontend/js/layout.js | 1 + 12 files changed, 754 insertions(+), 3 deletions(-) create mode 100644 frontend/import.html create mode 100644 frontend/js/import.js diff --git a/.env.example b/.env.example index caea81c..ffd6774 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,9 @@ UI_BASE_URL=http://localhost:8080 # Prometheus metrics are served on a separate port. METRICS_PORT=9100 +# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create). +LASTFM_API_KEY= + # docker compose host ports (defaults shown) API_PORT=5050 UI_PORT=8080 diff --git a/README.md b/README.md index d7d3269..29b5247 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,14 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana - **API** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages. - **Web UI** (`frontend/`): plain HTML, CSS and JavaScript with no build step. Host it anywhere static files can be served. - **Docs**: OpenAPI at `/api/openapi.json`, Swagger UI at `/api/docs` and ReDoc at `/api/redoc`. A copy of the spec is committed at `docs/openapi.json`. +- **Import worker**: `flask imports worker` imports Last.fm history in the background, from export files or straight from Last.fm. - **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules. ## Run it ```sh cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD -docker compose up -d # db, api (:5050), ui (:8080) +docker compose up -d # db, api (:5050), worker, ui (:8080) docker compose --profile monitoring up -d # + Prometheus (:9090), Grafana (:3000) ``` @@ -44,6 +45,9 @@ The images are `pkgs.daubney.dev/scrobbler/scrobbler-api` and `pkgs.daubney.dev/ | `METRICS_PORT` | api | `9100` | Prometheus metrics port (keep it off the public network) | | `WEB_CONCURRENCY` | api | `2` | gunicorn workers | | `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | +| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) | +| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted | +| `IMPORT_WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port | | `API_BASE_URL` | ui image | `http://localhost:5050` | API location, written into `config.js` and the CSP | In `docker compose` the host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, `PROMETHEUS_PORT` and `GRAFANA_PORT`. @@ -73,6 +77,21 @@ Supported methods: Scrobbles are ignored (not rejected) if the artist or track is empty, or if the timestamp is more than 14 days old or more than 5 minutes in the future. Sending the same scrobble again is accepted and stored once, so client retries are safe. +## Importing Last.fm history + +Open **Import** in the web UI. You can import from: + +- **An export file**: + - CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), with no header row and artist, album, track and date columns. + - Any CSV or TSV with a header row naming artist, track and a date or Unix-time column. Comma, semicolon and tab delimiters all work. + - A JSON export of `user.getRecentTracks` pages (such as lastfm.ghan.nl's), a single `recenttracks` response, or a flat list of tracks. + - Files can be gzipped. +- **Last.fm directly**: enter a Last.fm username and the worker pages through that account's public history. This option only appears when the server has `LASTFM_API_KEY` set. + +Imports run in the background in the `worker` service. The page shows progress, and an import can be cancelled. + +Unlike live scrobbles, imports keep plays of any age. They still skip rows with no artist or track, and plays dated in the future. Plays already in your history are skipped, so importing again is safe. + ## Develop ```sh @@ -81,6 +100,7 @@ uv sync uv run flask --app scrobbler db upgrade uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS) python -m http.server 8080 -d frontend # UI +uv run flask --app scrobbler imports worker # process imports uv run pytest # needs TEST_DATABASE_URL (see .env.example) uv run ruff check && uv run ruff format --check ``` @@ -113,6 +133,7 @@ With the `monitoring` profile, Grafana (admin password `GRAFANA_ADMIN_PASSWORD`) Alert rules live in `deploy/prometheus/alerts.yml`: - API down +- import worker down, or imports left waiting - 5xx ratio - p95 latency - authentication-failure spike diff --git a/deploy/grafana/dashboards/usage.json b/deploy/grafana/dashboards/usage.json index 961918b..ffd61d4 100644 --- a/deploy/grafana/dashboards/usage.json +++ b/deploy/grafana/dashboards/usage.json @@ -569,6 +569,365 @@ "w": 12, "h": 8 } + }, + { + "type": "row", + "title": "Imports", + "id": 13, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 32, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "stat", + "title": "Imports waiting", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_import_jobs{status=\"pending\"})", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + }, + { + "color": "orange", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 14, + "gridPos": { + "x": 0, + "y": 33, + "w": 4, + "h": 5 + } + }, + { + "type": "stat", + "title": "Imports running", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_import_jobs{status=\"running\"})", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 15, + "gridPos": { + "x": 4, + "y": 33, + "w": 4, + "h": 5 + } + }, + { + "type": "stat", + "title": "Import worker", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "up{job=\"scrobbler-worker\"}", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + }, + "mappings": [ + { + "type": "value", + "options": { + "0": { + "text": "Down", + "color": "red" + }, + "1": { + "text": "Up", + "color": "green" + } + } + } + ] + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 16, + "gridPos": { + "x": 8, + "y": 33, + "w": 4, + "h": 5 + } + }, + { + "type": "timeseries", + "title": "Import jobs finished", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (status) (increase(scrobbler_imports_total{status!=\"created\"}[$__rate_interval]))", + "legendFormat": "{{status}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 70, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + }, + "drawStyle": "bars" + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 17, + "gridPos": { + "x": 12, + "y": 33, + "w": 12, + "h": 5 + } + }, + { + "type": "timeseries", + "title": "Imported rows / min", + "description": "Rows read from exports or Last.fm: imported, already in the user's history, or skipped.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (source, result) (rate(scrobbler_imported_scrobbles_total[$__rate_interval])) * 60", + "legendFormat": "{{source}} {{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 18, + "gridPos": { + "x": 0, + "y": 38, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Import duration (p95)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, source) (rate(scrobbler_import_duration_seconds_bucket[$__range])))", + "legendFormat": "{{source}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 19, + "gridPos": { + "x": 12, + "y": 38, + "w": 12, + "h": 8 + } } ] } diff --git a/deploy/prometheus/alerts.yml b/deploy/prometheus/alerts.yml index 88e7532..a0c6cd4 100644 --- a/deploy/prometheus/alerts.yml +++ b/deploy/prometheus/alerts.yml @@ -57,6 +57,22 @@ groups: summary: Every pooled database connection is in use description: Workers are running on overflow connections; requests may queue. + - alert: ImportWorkerDown + expr: up{job="scrobbler-worker"} == 0 + for: 5m + labels: {severity: warning} + annotations: + summary: The import worker isn't running + description: History imports will wait until it's back. + + - alert: ImportJobsWaiting + expr: max(scrobbler_import_jobs{status="pending"}) > 0 and max(scrobbler_import_jobs{status="running"}) == 0 + for: 15m + labels: {severity: warning} + annotations: + summary: Imports have been waiting for 15 minutes with nothing running + description: The import worker is probably stopped or stuck. + - alert: PostgresDown expr: pg_up == 0 for: 2m diff --git a/deploy/prometheus/prometheus.yml b/deploy/prometheus/prometheus.yml index d1e3bd8..1257f81 100644 --- a/deploy/prometheus/prometheus.yml +++ b/deploy/prometheus/prometheus.yml @@ -10,6 +10,10 @@ scrape_configs: static_configs: - targets: ["api:9100"] + - job_name: scrobbler-worker + static_configs: + - targets: ["worker:9101"] + - job_name: postgres static_configs: - targets: ["postgres-exporter:9187"] diff --git a/docker-compose.yml b/docker-compose.yml index d4b650c..31dff55 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -# Core services: docker compose up +# Core services: docker compose up (db, api, worker, ui) # With monitoring: docker compose --profile monitoring up # Published images: SCROBBLER_IMAGE_TAG=main docker compose up --no-build name: scrobbler @@ -33,6 +33,7 @@ services: UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080} WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} FORWARDED_ALLOW_IPS: "*" + LASTFM_API_KEY: ${LASTFM_API_KEY:-} ports: - "${API_PORT:-5050}:8000" expose: @@ -41,6 +42,26 @@ services: db: condition: service_healthy + # Processes history imports (uploaded exports and pulls from Last.fm). + worker: + image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local} + build: + context: . + dockerfile: docker/api.Dockerfile + command: ["flask", "--app", "scrobbler", "imports", "worker"] + environment: + DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler + SECRET_KEY: ${SECRET_KEY:-change-me} + LASTFM_API_KEY: ${LASTFM_API_KEY:-} + RUN_MIGRATIONS: "0" # the api service applies them + expose: + - "9101" # metrics: internal network only + healthcheck: + disable: true + depends_on: + api: + condition: service_healthy + ui: image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-ui:${SCROBBLER_IMAGE_TAG:-local} build: diff --git a/docker/api.Dockerfile b/docker/api.Dockerfile index 0db537b..cb3f998 100644 --- a/docker/api.Dockerfile +++ b/docker/api.Dockerfile @@ -15,9 +15,10 @@ RUN useradd --system --uid 10001 --no-create-home scrobbler WORKDIR /app COPY --from=build /app/.venv /app/.venv COPY gunicorn.conf.py docker/api-entrypoint.sh ./ +# PROMETHEUS_MULTIPROC_DIR is set by gunicorn.conf.py for the API only: prometheus_client +# enters multiprocess mode whenever it's set, which other commands (the worker) don't want. ENV PATH=/app/.venv/bin:$PATH \ PYTHONUNBUFFERED=1 \ - PROMETHEUS_MULTIPROC_DIR=/tmp/scrobbler-metrics \ BIND=0.0.0.0:8000 \ METRICS_PORT=9100 \ OPENAPI_DOCS_ENABLED=1 diff --git a/frontend/css/style.css b/frontend/css/style.css index a97748e..be1e45e 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -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; + } +} diff --git a/frontend/import.html b/frontend/import.html new file mode 100644 index 0000000..9673cfd --- /dev/null +++ b/frontend/import.html @@ -0,0 +1,53 @@ + + + + + + Import · Scrobbler + + + + + + + +
+

Import history

+

Bring in your Last.fm history. Plays that are already here are skipped, so importing the same history twice is safe.

+
+
+
+

From an export file

+

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.

+
+
+ + + +
+ + +
+
+ +
+
+

Your imports

+
    +
    +
    + + diff --git a/frontend/js/api.js b/frontend/js/api.js index 079698a..6283117 100644 --- a/frontend/js/api.js +++ b/frontend/js/api.js @@ -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); + }); +} diff --git a/frontend/js/import.js b/frontend/js/import.js new file mode 100644 index 0000000..1cdfc70 --- /dev/null +++ b/frontend/js/import.js @@ -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`; +} diff --git a/frontend/js/layout.js b/frontend/js/layout.js index b6dc9f6..ff2a6e6 100644 --- a/frontend/js/layout.js +++ b/frontend/js/layout.js @@ -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).