Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: Spotify bulk-history importer + shared import seam (#2160)

Adam Eivya0b9f791e263
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 52fafcbdba..33fd013461 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -148,3 +148,5 @@
- **[issue-1929] Creative Director scene-0 render no longer races its seeded reference frame.** When first-pass gen is on (#1867), the treatment handler enqueues a fire-and-forget image-gen job per scene to seed `scene.sourceImageFile`; but `advanceAfterSceneSettled` fired the instant the treatment task settled and called `runSceneRender` for the lowest-order pending scene, which reads `sourceImageFile` synchronously — so scene-0 almost always rendered text-to-video before its just-queued seed frame landed, silently degrading the establishing shot. The "find next pending scene" branch now checks whether `project.generateFirstPass && !scene.sourceImageFile` and a `creativeDirector`-tagged image job for that scene is still queued/running on the media-job queue; if so it defers the render, re-firing `advanceAfterSceneSettled` once the seed job settles (with a short bounded poll for the scene-image hook to file `sourceImageFile`, since both handlers run off the same `completed` event). If the seed job fails/cancels the scene renders text-to-video exactly as the fire-and-forget contract always allowed. A 5-minute backstop timer force-proceeds if the seed job never emits a terminal event (worker crash / queue stall / restart that drops the in-memory job), so a stuck seed can't wedge the scene in `pending` forever; the backstopped re-advance renders the scene directly (via a `skipSeedDeferSceneId` gate) instead of re-arming a fresh defer on the same stalled job, and the settle listener matches by scene tag so a duplicate/re-queued seed job for the same scene wakes it too. Later scenes are unaffected (they already have a multi-minute buffer). (`server/services/creativeDirector/completionHook.js`)
- **[issue-2175] Generation-side character framework + structure doctrine (CWQE Phase 10 remainder).** Following the worldbuilding-doctrine slice (#2219), the character-generation and structure-planning prompts now teach the craft up front. The character bible gains the Ghost → Wound → Lie → Want → Need chain (with interlock checks: state the Lie in one sentence; the Need/Truth is its direct opposite; the Ghost causally explains the Lie), a declared arc type (positive/negative/flat), the Three Sliders (proactivity/likability/competence 1–10, rule: HIGH on ≥2 or one-with-growth; all-low = boring, all-high = Mary Sue), and a secrets list — all OPTIONAL so pre-#2175 records round-trip unchanged (`server/lib/storyBible.js` sanitizer + Zod-shape parity via the existing `canonArrayField` sanitize-on-write, client mirror in `client/src/lib/bibleLimits.js`, character-sheet UI in `CharacterDetailEditor.jsx` with `htmlFor`/`id` pairing, and no-clobber merge in `universeCharacterExpand.js` for the AI-expand path). The `character.consistency` / `arc.*` editorial checks now receive the authored Lie/Want/Need/arc-type when present (via `canonCharacterTraitsSummary`) so they reconcile plan-vs-delivery instead of inferring both. Structure prompts gain lean doctrine: `pipeline-season-episodes.md` a try-fail mandate (60%+ of middle episodes end "Yes, but"/"No, and"), beat rules (Catalyst external; Break Into Two a protagonist choice; All Is Lost includes a death — literal or of a hope/relationship/identity) and an active-climax rule; `pipeline-arc-overview.md` MICE-style thread nesting (threads close in reverse order of opening; name the opening/closing thread per season). Shipped-template edits ship to existing installs via hash-keyed migrations 171/172/173 (with the drift-cross-sync of prior owners 003/005/019/027/166). Remaining Phase 10 items (Le Guin style doctrine into the style-guide flow) stay tracked on #2175.
+
+- **[issue-2160] Bulk-history importer for Spotify extended streaming history + shared import seam.** The `/timeline` page gains a collapsible "Import Spotify history" panel: upload the privacy-download ZIP (or a single `Streaming_History_Audio_*.json`) → preview parsed counts/date-range/top-artists → confirm, and every play lands as an idempotent `media.listen` event via the existing `recordEvents()` infra (dedupe on track-uri + played-at, so re-imports and overlapping exports never double-count). Both the modern extended-history shape (`ts`/`ms_played`/`master_metadata_*`) and the legacy `StreamingHistory*.json` shape (`endTime`/`artistName`/`trackName`/`msPlayed`) are parsed; legacy offset-less UTC timestamps are anchored to UTC so a server west of UTC can't shift the listen into the wrong day. The route reuses the streaming `multipart.js` parser + `zipStream.js` (no new deps; the JSON parser is hand-written), Zod-validates the `preview` flag, and always unlinks the temp upload. This is one slice of the larger backfill issue. (`server/services/spotifyImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/SpotifyImportPanel.jsx`, `client/src/pages/Timeline.jsx`)
diff --git a/client/src/components/timeline/SpotifyImportPanel.jsx b/client/src/components/timeline/SpotifyImportPanel.jsx
new file mode 100644
index 0000000000..9bfab13dcd
--- /dev/null
+++ b/client/src/components/timeline/SpotifyImportPanel.jsx
@@ -0,0 +1,154 @@
+import { useState } from 'react';
+import { Music, Upload, Loader2, CheckCircle2 } from 'lucide-react';
+import * as api from '../../services/api';
+import toast from '../ui/Toast';
+import { formatDurationSec } from '../../utils/formatters';
+
+// Bulk-backfill importer for Spotify "Extended streaming history" exports (#2160).
+// Two-step flow: pick a file → preview (parse-only, no write) → confirm import.
+// The import is idempotent server-side, so re-importing the same or overlapping
+// export never double-counts. Collapsed by default so it stays out of the way of
+// the day timeline; `onImported` lets the page refresh once new events land.
+export default function SpotifyImportPanel({ onImported }) {
+ const [open, setOpen] = useState(false);
+ const [file, setFile] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const [preview, setPreview] = useState(null);
+ const [result, setResult] = useState(null);
+
+ const reset = () => { setFile(null); setPreview(null); setResult(null); };
+
+ const pickFile = (e) => {
+ const next = e.target.files?.[0] || null;
+ setFile(next);
+ setPreview(null);
+ setResult(null);
+ };
+
+ const runPreview = () => {
+ if (!file) return;
+ setBusy(true);
+ setResult(null);
+ api.importSpotifyHistory(file, { preview: true, silent: true })
+ .then((res) => {
+ setPreview(res);
+ if (!res.mapped) toast.error('No listening records found in that file.');
+ })
+ .catch((err) => toast.error(`Preview failed: ${err.message}`))
+ .finally(() => setBusy(false));
+ };
+
+ const runImport = () => {
+ if (!file) return;
+ setBusy(true);
+ api.importSpotifyHistory(file, { preview: false, silent: true })
+ .then((res) => {
+ setResult(res);
+ toast.success(`Imported ${res.recorded} play(s) (${res.skipped} already present).`);
+ if (res.recorded > 0) onImported?.();
+ })
+ .catch((err) => toast.error(`Import failed: ${err.message}`))
+ .finally(() => setBusy(false));
+ };
+
+ const dateRange = (from, to) => {
+ if (!from || !to) return null;
+ const f = new Date(from).toLocaleDateString();
+ const t = new Date(to).toLocaleDateString();
+ return f === t ? f : `${f} — ${t}`;
+ };
+
+ return (
+ <div className="rounded border border-port-border bg-port-card">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center gap-2 px-3 py-2 text-left text-sm text-gray-300 hover:text-gray-100"
+ aria-expanded={open}
+ >
+ <Music size={16} className="text-port-accent" />
+ <span className="font-medium">Import Spotify history</span>
+ <span className="ml-auto text-xs text-gray-500">{open ? 'Hide' : 'Backfill'}</span>
+ </button>
+
+ {open && (
+ <div className="flex flex-col gap-3 border-t border-port-border p-3">
+ <p className="text-xs text-gray-500">
+ Request your <span className="text-gray-300">Extended streaming history</span> from
+ Spotify (Account → Privacy), then upload the ZIP (or a single
+ <span className="font-mono"> Streaming_History_Audio_*.json</span>) here. Re-imports are safe —
+ already-recorded plays are skipped.
+ </p>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="inline-flex cursor-pointer items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm text-gray-200 hover:border-port-accent">
+ <Upload size={14} />
+ <span>{file ? 'Change file' : 'Choose file'}</span>
+ <input type="file" accept=".zip,.json,application/zip,application/json" onChange={pickFile} className="hidden" />
+ </label>
+ {file && <span className="truncate text-xs text-gray-400">{file.name}</span>}
+ </div>
+
+ {file && !result && (
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={runPreview}
+ disabled={busy}
+ className="inline-flex items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm hover:border-port-accent disabled:opacity-40"
+ >
+ {busy && !preview ? <Loader2 size={14} className="animate-spin" /> : null}
+ Preview
+ </button>
+ {preview && preview.mapped > 0 && (
+ <button
+ type="button"
+ onClick={runImport}
+ disabled={busy}
+ className="inline-flex items-center gap-2 rounded bg-port-accent px-3 py-1.5 text-sm font-medium text-white hover:opacity-90 disabled:opacity-40"
+ >
+ {busy && preview ? <Loader2 size={14} className="animate-spin" /> : null}
+ Import {preview.mapped} play{preview.mapped === 1 ? '' : 's'}
+ </button>
+ )}
+ </div>
+ )}
+
+ {preview && !result && (
+ <div className="rounded border border-port-border bg-port-bg p-3 text-xs text-gray-400">
+ <div className="mb-1 font-medium text-gray-300">Preview</div>
+ <div>{preview.mapped} play(s) across {preview.summary.uniqueTracks} unique track(s)</div>
+ {dateRange(preview.summary.from, preview.summary.to) && (
+ <div>Range: {dateRange(preview.summary.from, preview.summary.to)}</div>
+ )}
+ {preview.summary.totalMs > 0 && (
+ <div>Total listening: {formatDurationSec(Math.round(preview.summary.totalMs / 1000))}</div>
+ )}
+ {preview.summary.topArtists?.length > 0 && (
+ <div className="mt-1 truncate">
+ Top: {preview.summary.topArtists.slice(0, 5).map((a) => a.name).join(', ')}
+ </div>
+ )}
+ </div>
+ )}
+
+ {result && (
+ <div className="rounded border border-port-success/40 bg-port-bg p-3 text-xs text-gray-300">
+ <div className="mb-1 flex items-center gap-2 font-medium text-port-success">
+ <CheckCircle2 size={14} /> Import complete
+ </div>
+ <div>{result.recorded} new play(s) recorded, {result.skipped} already present.</div>
+ <button
+ type="button"
+ onClick={reset}
+ className="mt-2 rounded border border-port-border px-2 py-1 text-gray-300 hover:border-port-accent"
+ >
+ Import another
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsx
index c99a5007ee..0d39c6768c 100644
--- a/client/src/pages/Timeline.jsx
+++ b/client/src/pages/Timeline.jsx
@@ -5,6 +5,7 @@ import {
CalendarDays, Music, Play, MessageSquare, Activity,
} from 'lucide-react';
import PageHeader from '../components/PageHeader';
+import SpotifyImportPanel from '../components/timeline/SpotifyImportPanel';
import * as api from '../services/api';
import toast from '../components/ui/Toast';
import { formatClockTime, formatDurationSec } from '../utils/formatters';
@@ -123,6 +124,8 @@ export default function Timeline() {
const [day, setDay] = useState(null);
const [loading, setLoading] = useState(true);
+ // Bumped after a bulk import lands so the current day view re-fetches.
+ const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
let active = true;
@@ -132,7 +135,7 @@ export default function Timeline() {
.catch((err) => { if (active) { setDay(null); toast.error(`Failed to load timeline: ${err.message}`); } })
.finally(() => { if (active) setLoading(false); });
return () => { active = false; };
- }, [urlDate]);
+ }, [urlDate, reloadKey]);
// Browser-local fallbacks cover only the loading/error window before the
// server response supplies the authoritative `date` and `today`.
@@ -198,6 +201,8 @@ export default function Timeline() {
<div className="text-sm text-gray-400">{dayLabel}</div>
</div>
+ <SpotifyImportPanel onImported={() => setReloadKey((k) => k + 1)} />
+
<Histogram histogram={histogram} />
<div className="flex flex-wrap gap-2 text-xs text-gray-400">
diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.js
index f4087de4fd..90769b09a7 100644
--- a/client/src/services/apiTimeline.js
+++ b/client/src/services/apiTimeline.js
@@ -20,3 +20,14 @@ export const getTimelineEvents = (options = {}) => {
const qs = params.toString();
return request(`/timeline/events${qs ? `?${qs}` : ''}`, { silent: options.silent });
};
+
+// Bulk-backfill importer (#2160). Upload a Spotify extended-history export (ZIP
+// or a single history JSON). `preview: true` returns parse-only counts + a
+// summary without writing; a real import is idempotent so re-imports are safe.
+// request() detects the FormData body and lets the browser set the boundary.
+export const importSpotifyHistory = (file, { preview = false, ...options } = {}) => {
+ const formData = new FormData();
+ formData.append('file', file);
+ formData.append('preview', preview ? 'true' : 'false');
+ return request('/timeline/import/spotify', { method: 'POST', body: formData, ...options });
+};
diff --git a/server/routes/timeline.js b/server/routes/timeline.js
index ace3507a29..92e54d8621 100644
--- a/server/routes/timeline.js
+++ b/server/routes/timeline.js
@@ -1,12 +1,36 @@
import { Router } from 'express';
import { z } from 'zod';
+import { unlink } from 'fs/promises';
-import { asyncHandler } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
+import { uploadSingle } from '../lib/multipart.js';
import * as humanActivity from '../services/humanActivity.js';
+import { importSpotifyHistory } from '../services/spotifyImport.js';
const router = Router();
+// Spotify extended-history exports (a ZIP of JSON arrays) are bounded by the
+// account lifetime — 200MB comfortably covers years of listening.
+const uploadSpotify = uploadSingle('file', {
+ limits: { fileSize: 200 * 1024 * 1024 },
+ fileFilter: (req, file, cb) => {
+ const ok = /\.(zip|json)$/i.test(file.originalname)
+ || ['application/zip', 'application/x-zip-compressed', 'application/json', 'text/json'].includes(file.mimetype);
+ if (ok) return cb(null, true);
+ cb(new ServerError('Only Spotify export ZIP or JSON files are accepted', { status: 400, code: 'BAD_REQUEST' }));
+ },
+});
+
+// `preview` (a multipart text field, so it arrives as a string) toggles a
+// parse-only dry run — count what would be imported without writing.
+const importBodySchema = z.object({
+ preview: z.preprocess(
+ (v) => (typeof v === 'string' ? v === 'true' || v === '1' : v),
+ z.boolean().optional().default(false),
+ ),
+});
+
const dayQuerySchema = z.object({
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
});
@@ -36,4 +60,18 @@ router.get('/events', asyncHandler(async (req, res) => {
res.json({ events });
}));
+// POST /api/timeline/import/spotify — bulk-backfill Spotify extended streaming
+// history (#2160). Accepts the privacy-download ZIP or a single history JSON via
+// multipart upload. `preview=true` parses + summarizes without writing; a real
+// import is idempotent (dedupe on played-at + track), so re-imports are safe.
+// The uploaded temp file is always unlinked, whether the import succeeds or not.
+router.post('/import/spotify', uploadSpotify, asyncHandler(async (req, res) => {
+ const { preview } = validateRequest(importBodySchema, req.body);
+ const file = req.file;
+ if (!file?.path) throw new ServerError('No file uploaded', { status: 400, code: 'BAD_REQUEST' });
+ const result = await importSpotifyHistory(file, { dryRun: preview })
+ .finally(() => unlink(file.path).catch(() => {}));
+ res.json(result);
+}));
+
export default router;
diff --git a/server/routes/timeline.test.js b/server/routes/timeline.test.js
new file mode 100644
index 0000000000..dce6ced018
--- /dev/null
+++ b/server/routes/timeline.test.js
@@ -0,0 +1,122 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// The importer service is exercised via its own unit suite; here we only assert
+// the route wiring: multipart parse → validation → service call → temp cleanup.
+vi.mock('../services/spotifyImport.js', () => ({
+ importSpotifyHistory: vi.fn(async (file, opts) => ({
+ dryRun: Boolean(opts?.dryRun),
+ parsed: 3,
+ mapped: 2,
+ recorded: opts?.dryRun ? 0 : 2,
+ skipped: opts?.dryRun ? 0 : 1,
+ summary: { plays: 2, uniqueTracks: 2, totalMs: 1000, from: null, to: null, topArtists: [] },
+ })),
+}));
+
+vi.mock('../services/humanActivity.js', () => ({
+ getDaySummary: vi.fn(async () => ({ date: '2026-07-07', events: [] })),
+ listEvents: vi.fn(async () => []),
+}));
+
+import { importSpotifyHistory } from '../services/spotifyImport.js';
+import timelineRoutes from './timeline.js';
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/timeline', timelineRoutes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+// Build a minimal multipart/form-data body with one file part + optional fields.
+function multipart(fields, file) {
+ const boundary = '----portostest' + Math.random().toString(16).slice(2);
+ const parts = [];
+ for (const [name, value] of Object.entries(fields || {})) {
+ parts.push(Buffer.from(
+ `--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`,
+ ));
+ }
+ if (file) {
+ parts.push(Buffer.from(
+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${file.filename}"\r\n` +
+ `Content-Type: ${file.contentType}\r\n\r\n`,
+ ));
+ parts.push(Buffer.from(file.content));
+ parts.push(Buffer.from('\r\n'));
+ }
+ parts.push(Buffer.from(`--${boundary}--\r\n`));
+ return { boundary, body: Buffer.concat(parts) };
+}
+
+describe('timeline import routes', () => {
+ let app;
+ beforeEach(() => { app = makeApp(); vi.clearAllMocks(); });
+
+ it('POST /import/spotify parses the upload and calls the importer (real import)', async () => {
+ const { boundary, body } = multipart(
+ { preview: 'false' },
+ { filename: 'history.json', contentType: 'application/json', content: '[]' },
+ );
+ const r = await request(app).post('/api/timeline/import/spotify')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(body);
+ expect(r.status).toBe(200);
+ expect(r.body.recorded).toBe(2);
+ expect(importSpotifyHistory).toHaveBeenCalledWith(
+ expect.objectContaining({ originalname: 'history.json' }),
+ { dryRun: false },
+ );
+ });
+
+ it('honors preview=true as a dry run', async () => {
+ const { boundary, body } = multipart(
+ { preview: 'true' },
+ { filename: 'history.json', contentType: 'application/json', content: '[]' },
+ );
+ const r = await request(app).post('/api/timeline/import/spotify')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(body);
+ expect(r.status).toBe(200);
+ expect(r.body.dryRun).toBe(true);
+ expect(r.body.recorded).toBe(0);
+ expect(importSpotifyHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true });
+ });
+
+ it('defaults preview to false when the field is absent', async () => {
+ const { boundary, body } = multipart(
+ {},
+ { filename: 'export.zip', contentType: 'application/zip', content: 'PK...' },
+ );
+ const r = await request(app).post('/api/timeline/import/spotify')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(body);
+ expect(r.status).toBe(200);
+ expect(importSpotifyHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: false });
+ });
+
+ it('rejects a disallowed file type with 400', async () => {
+ const { boundary, body } = multipart(
+ {},
+ { filename: 'notes.txt', contentType: 'text/plain', content: 'hi' },
+ );
+ const r = await request(app).post('/api/timeline/import/spotify')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(body);
+ expect(r.status).toBe(400);
+ expect(importSpotifyHistory).not.toHaveBeenCalled();
+ });
+
+ it('400s when no file part is present', async () => {
+ const { boundary, body } = multipart({ preview: 'false' }, null);
+ const r = await request(app).post('/api/timeline/import/spotify')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(body);
+ expect(r.status).toBe(400);
+ expect(importSpotifyHistory).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/spotifyImport.js b/server/services/spotifyImport.js
new file mode 100644
index 0000000000..082e3ccb76
--- /dev/null
+++ b/server/services/spotifyImport.js
@@ -0,0 +1,237 @@
+/**
+ * Spotify extended-streaming-history importer (#2160) — bulk historical backfill
+ * into the human-activity timeline.
+ *
+ * Spotify's privacy download ("Extended streaming history") ships a ZIP whose
+ * `Streaming_History_Audio_*.json` files are arrays of per-play records covering
+ * the full account lifetime — far more than the 50-track window the Web API
+ * exposes (which the live sync in Phase 3 polls). This importer takes that export
+ * (either the raw ZIP or an individual JSON array) and maps every play into a
+ * `media.listen` activity event.
+ *
+ * Two export shapes are supported:
+ * - Extended history (2023+): `{ ts, ms_played, master_metadata_track_name,
+ * master_metadata_album_artist_name, master_metadata_album_album_name,
+ * spotify_track_uri, episode_name, ... }`
+ * - Legacy "Account data" `StreamingHistory*.json`: `{ endTime, artistName,
+ * trackName, msPlayed }` (endTime is UTC "YYYY-MM-DD HH:MM").
+ *
+ * Idempotent: every candidate carries a stable `dedupeKey` (track uri + ISO
+ * timestamp), so re-importing the same export — or an overlapping newer export —
+ * is a no-op via `recordEvents`'s `ON CONFLICT DO NOTHING`. No AI-provider calls;
+ * parsing is deterministic and LLM-free.
+ */
+import { createReadStream } from 'fs';
+import { readFile } from 'fs/promises';
+import { parseZip, collectZipEntry } from '../lib/zipStream.js';
+import { shortSummary, recordEvents } from './humanActivity.js';
+
+// ---------------------------------------------------------------------------
+// Pure helpers (exported for unit tests — no DB, no filesystem, no side effects).
+// ---------------------------------------------------------------------------
+
+// Resolve a Spotify play timestamp to a UTC ISO string, or null if unparseable.
+// Extended history uses ISO-8601 with a `Z` (`ts`); legacy StreamingHistory uses
+// a space-separated UTC wall clock without an offset ("2022-01-01 15:30") — we
+// append the missing `:00Z` so it's interpreted as UTC, not server-OS-local.
+export function resolveSpotifyInstant(value) {
+ if (!value) return null;
+ const s = String(value).trim();
+ const legacy = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2})$/.exec(s);
+ const iso = legacy ? `${legacy[1]}T${legacy[2]}:00Z` : s;
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+}
+
+// Turn a `spotify:track:ID` / `spotify:episode:ID` URI into an open.spotify.com
+// link; pass through anything that's already an http(s) URL; else null.
+export function spotifyUriToUrl(uri) {
+ if (!uri) return null;
+ const s = String(uri).trim();
+ if (/^https?:\/\//i.test(s)) return s;
+ const m = /^spotify:(track|episode|album|artist):([A-Za-z0-9]+)$/.exec(s);
+ return m ? `https://open.spotify.com/${m[1]}/${m[2]}` : null;
+}
+
+// Map ONE raw Spotify play record to an activity candidate, or null if it lacks a
+// usable timestamp or a track/episode name (bare ms_played records with null
+// metadata — local files, ads — carry no autobiographical signal).
+export function spotifyRecordToCandidate(record) {
+ if (!record || typeof record !== 'object') return null;
+ const happenedAt = resolveSpotifyInstant(record.ts ?? record.endTime);
+ if (!happenedAt) return null;
+
+ const trackName = record.master_metadata_track_name ?? record.trackName ?? null;
+ const artist = record.master_metadata_album_artist_name ?? record.artistName ?? null;
+ const album = record.master_metadata_album_album_name ?? null;
+ const episodeName = record.episode_name ?? null;
+ const showName = record.episode_show_name ?? null;
+ const title = trackName || episodeName;
+ if (!title) return null;
+
+ const isEpisode = !trackName && Boolean(episodeName);
+ const uri = record.spotify_track_uri ?? record.spotify_episode_uri ?? null;
+ const msRaw = record.ms_played ?? record.msPlayed;
+ const ms = Number(msRaw);
+ const durationS = Number.isFinite(ms) && ms > 0 ? Math.round(ms / 1000) : null;
+
+ // Dedupe on the play instant + track identity. Two plays of the same track at
+ // the exact same second are indistinguishable in the export, so collapsing
+ // them is correct (and matches the design's "played_at + track id" contract).
+ const identity = uri || title;
+ const dedupeKey = `spotify:${identity}:${happenedAt}`;
+
+ const summaryParts = isEpisode
+ ? [showName].filter(Boolean)
+ : [artist, album].filter(Boolean);
+
+ return {
+ source: 'spotify',
+ kind: 'media.listen',
+ happenedAt,
+ durationS,
+ title,
+ summary: shortSummary(summaryParts.join(' — ')),
+ url: spotifyUriToUrl(uri),
+ dedupeKey,
+ metadata: {
+ artist: artist || null,
+ album: album || null,
+ trackUri: uri,
+ type: isEpisode ? 'episode' : 'track',
+ showName: isEpisode ? showName || null : null,
+ platform: record.platform ?? null,
+ reasonStart: record.reason_start ?? null,
+ reasonEnd: record.reason_end ?? null,
+ shuffle: typeof record.shuffle === 'boolean' ? record.shuffle : null,
+ skipped: typeof record.skipped === 'boolean' ? record.skipped : null,
+ msPlayed: Number.isFinite(ms) ? ms : null,
+ },
+ };
+}
+
+// Map a batch of raw records to candidates, dropping the unmappable ones.
+export function spotifyActivityCandidates(records = []) {
+ if (!Array.isArray(records)) return [];
+ return records.map(spotifyRecordToCandidate).filter(Boolean);
+}
+
+// Summarize a candidate batch for the import preview: date range, listen time,
+// unique track count, and the top artists by play count. Pure over candidates.
+export function summarizeSpotifyCandidates(candidates = []) {
+ const list = Array.isArray(candidates) ? candidates : [];
+ let earliest = null;
+ let latest = null;
+ let totalMs = 0;
+ const uris = new Set();
+ const artistCounts = new Map();
+ for (const c of list) {
+ if (c.happenedAt) {
+ if (!earliest || c.happenedAt < earliest) earliest = c.happenedAt;
+ if (!latest || c.happenedAt > latest) latest = c.happenedAt;
+ }
+ const ms = c.metadata?.msPlayed;
+ if (Number.isFinite(ms)) totalMs += ms;
+ uris.add(c.metadata?.trackUri || c.title);
+ const artist = c.metadata?.artist;
+ if (artist) artistCounts.set(artist, (artistCounts.get(artist) || 0) + 1);
+ }
+ const topArtists = [...artistCounts.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 10)
+ .map(([name, count]) => ({ name, count }));
+ return {
+ plays: list.length,
+ uniqueTracks: uris.size,
+ totalMs,
+ from: earliest,
+ to: latest,
+ topArtists,
+ };
+}
+
+// Parse the text of a single Spotify history JSON file into a record array.
+// Tolerates a top-level array (the normal shape) and a `{ items: [...] }`
+// wrapper; anything else yields []. Throws only on malformed JSON.
+export function parseSpotifyJsonText(text) {
+ const parsed = JSON.parse(text);
+ if (Array.isArray(parsed)) return parsed;
+ if (Array.isArray(parsed?.items)) return parsed.items;
+ return [];
+}
+
+// ---------------------------------------------------------------------------
+// File ingestion (ZIP or single JSON) → records.
+// ---------------------------------------------------------------------------
+
+const isZip = (file) =>
+ file?.mimetype === 'application/zip' ||
+ file?.mimetype === 'application/x-zip-compressed' ||
+ /\.zip$/i.test(file?.originalname || '');
+
+// A streaming-history JSON member inside the export ZIP. Spotify names them
+// `Streaming_History_Audio_2023_1.json` (extended) or `StreamingHistory0.json`
+// (legacy), sometimes under a `Spotify Extended Streaming History/` folder.
+const isHistoryJsonEntry = (entryPath) =>
+ /(?:^|\/)(?:Streaming_History_Audio|StreamingHistory)[^/]*\.json$/i.test(entryPath);
+
+// Extract and concatenate the play records from every streaming-history JSON
+// member of the export ZIP. Non-history entries are drained and ignored.
+async function readRecordsFromZip(filePath) {
+ const records = [];
+ const reads = [];
+ await new Promise((resolve, reject) => {
+ let settled = false;
+ const settle = (fn) => (...args) => {
+ if (settled) return;
+ settled = true;
+ fn(...args);
+ };
+ const src = createReadStream(filePath);
+ const parser = parseZip();
+ src.on('error', settle(reject));
+ src
+ .pipe(parser)
+ .on('entry', (entry) => {
+ if (isHistoryJsonEntry(entry.path)) {
+ reads.push(
+ collectZipEntry(entry)
+ .then((buf) => {
+ for (const r of parseSpotifyJsonText(buf.toString('utf-8'))) records.push(r);
+ })
+ .catch(settle(reject)),
+ );
+ } else {
+ entry.autodrain();
+ }
+ })
+ .on('close', () => Promise.all(reads).then(settle(resolve)).catch(settle(reject)))
+ .on('error', settle(reject));
+ });
+ return records;
+}
+
+// Read raw play records from an uploaded file (ZIP export or single JSON array).
+export async function readSpotifyRecords(file) {
+ if (!file?.path) return [];
+ if (isZip(file)) return readRecordsFromZip(file.path);
+ const text = await readFile(file.path, 'utf-8');
+ return parseSpotifyJsonText(text);
+}
+
+// End-to-end import seam: read the file → map → (preview | record). Returns
+// counts + a preview summary. `dryRun` parses and summarizes WITHOUT writing so
+// the UI can show the user what will be imported before they commit. Because
+// `recordEvents` is idempotent, committing (or re-committing) is always safe.
+export async function importSpotifyHistory(file, { dryRun = false } = {}) {
+ const records = await readSpotifyRecords(file);
+ const candidates = spotifyActivityCandidates(records);
+ const summary = summarizeSpotifyCandidates(candidates);
+ if (dryRun) {
+ console.log(`🎧 Spotify import preview: ${candidates.length} play(s) from ${records.length} record(s)`);
+ return { dryRun: true, parsed: records.length, mapped: candidates.length, recorded: 0, skipped: 0, summary };
+ }
+ const { recorded, skipped } = await recordEvents(candidates);
+ console.log(`🎧 Spotify import: ${recorded} new play(s) recorded, ${skipped} duplicate/invalid (from ${records.length} record(s))`);
+ return { dryRun: false, parsed: records.length, mapped: candidates.length, recorded, skipped, summary };
+}
diff --git a/server/services/spotifyImport.test.js b/server/services/spotifyImport.test.js
new file mode 100644
index 0000000000..ae3ff6640b
--- /dev/null
+++ b/server/services/spotifyImport.test.js
@@ -0,0 +1,174 @@
+import { describe, it, expect } from 'vitest';
+import {
+ resolveSpotifyInstant,
+ spotifyUriToUrl,
+ spotifyRecordToCandidate,
+ spotifyActivityCandidates,
+ summarizeSpotifyCandidates,
+ parseSpotifyJsonText,
+} from './spotifyImport.js';
+
+// A representative extended-history record (Spotify's 2023+ export shape).
+const extendedRecord = {
+ ts: '2023-05-01T18:30:00Z',
+ ms_played: 210000,
+ master_metadata_track_name: 'Idioteque',
+ master_metadata_album_artist_name: 'Radiohead',
+ master_metadata_album_album_name: 'Kid A',
+ spotify_track_uri: 'spotify:track:2gjHtqrEnMBmD3lBWJUp2P',
+ platform: 'osx',
+ reason_start: 'trackdone',
+ reason_end: 'trackdone',
+ shuffle: false,
+ skipped: false,
+};
+
+// The older "Account data" StreamingHistory shape.
+const legacyRecord = {
+ endTime: '2022-01-15 09:05',
+ artistName: 'Boards of Canada',
+ trackName: 'Roygbiv',
+ msPlayed: 132000,
+};
+
+describe('resolveSpotifyInstant', () => {
+ it('passes ISO-8601 UTC timestamps straight through', () => {
+ expect(resolveSpotifyInstant('2023-05-01T18:30:00Z')).toBe('2023-05-01T18:30:00.000Z');
+ });
+
+ it('interprets legacy space-separated timestamps as UTC (not OS-local)', () => {
+ // Appending :00Z is what prevents a server west of UTC from shifting the day.
+ expect(resolveSpotifyInstant('2022-01-15 09:05')).toBe('2022-01-15T09:05:00.000Z');
+ });
+
+ it('returns null for empty/unparseable values', () => {
+ expect(resolveSpotifyInstant('')).toBeNull();
+ expect(resolveSpotifyInstant(null)).toBeNull();
+ expect(resolveSpotifyInstant('not a date')).toBeNull();
+ });
+});
+
+describe('spotifyUriToUrl', () => {
+ it('converts a track URI to an open.spotify.com link', () => {
+ expect(spotifyUriToUrl('spotify:track:abc123')).toBe('https://open.spotify.com/track/abc123');
+ });
+ it('converts episode URIs too', () => {
+ expect(spotifyUriToUrl('spotify:episode:xyz')).toBe('https://open.spotify.com/episode/xyz');
+ });
+ it('passes through http(s) URLs and rejects junk', () => {
+ expect(spotifyUriToUrl('https://open.spotify.com/track/x')).toBe('https://open.spotify.com/track/x');
+ expect(spotifyUriToUrl('garbage')).toBeNull();
+ expect(spotifyUriToUrl(null)).toBeNull();
+ });
+});
+
+describe('spotifyRecordToCandidate', () => {
+ it('maps an extended-history record to a media.listen candidate', () => {
+ const c = spotifyRecordToCandidate(extendedRecord);
+ expect(c).toMatchObject({
+ source: 'spotify',
+ kind: 'media.listen',
+ happenedAt: '2023-05-01T18:30:00.000Z',
+ durationS: 210,
+ title: 'Idioteque',
+ url: 'https://open.spotify.com/track/2gjHtqrEnMBmD3lBWJUp2P',
+ });
+ expect(c.summary).toBe('Radiohead — Kid A');
+ expect(c.metadata).toMatchObject({ artist: 'Radiohead', album: 'Kid A', type: 'track' });
+ });
+
+ it('maps a legacy StreamingHistory record', () => {
+ const c = spotifyRecordToCandidate(legacyRecord);
+ expect(c).toMatchObject({
+ source: 'spotify',
+ kind: 'media.listen',
+ happenedAt: '2022-01-15T09:05:00.000Z',
+ durationS: 132,
+ title: 'Roygbiv',
+ });
+ expect(c.summary).toBe('Boards of Canada');
+ });
+
+ it('builds a stable dedupe key from track uri + instant', () => {
+ const c1 = spotifyRecordToCandidate(extendedRecord);
+ const c2 = spotifyRecordToCandidate({ ...extendedRecord });
+ expect(c1.dedupeKey).toBe(c2.dedupeKey);
+ expect(c1.dedupeKey).toBe('spotify:spotify:track:2gjHtqrEnMBmD3lBWJUp2P:2023-05-01T18:30:00.000Z');
+ });
+
+ it('classifies podcast episodes and uses the show name as summary', () => {
+ const c = spotifyRecordToCandidate({
+ ts: '2023-06-01T12:00:00Z',
+ ms_played: 1800000,
+ episode_name: 'The One About Testing',
+ episode_show_name: 'Dev Talk',
+ spotify_episode_uri: 'spotify:episode:ep1',
+ });
+ expect(c.title).toBe('The One About Testing');
+ expect(c.summary).toBe('Dev Talk');
+ expect(c.metadata.type).toBe('episode');
+ expect(c.metadata.showName).toBe('Dev Talk');
+ });
+
+ it('drops records with no timestamp or no title', () => {
+ expect(spotifyRecordToCandidate({ ms_played: 1000 })).toBeNull();
+ expect(spotifyRecordToCandidate({ ts: '2023-01-01T00:00:00Z', ms_played: 1000 })).toBeNull();
+ expect(spotifyRecordToCandidate(null)).toBeNull();
+ });
+
+ it('leaves durationS null for missing/zero playtime', () => {
+ const c = spotifyRecordToCandidate({ ts: '2023-01-01T00:00:00Z', master_metadata_track_name: 'X' });
+ expect(c.durationS).toBeNull();
+ });
+});
+
+describe('spotifyActivityCandidates', () => {
+ it('maps a batch and filters unmappable rows', () => {
+ const out = spotifyActivityCandidates([extendedRecord, { ms_played: 5 }, legacyRecord]);
+ expect(out).toHaveLength(2);
+ expect(out.every((c) => c.source === 'spotify')).toBe(true);
+ });
+ it('returns [] for non-arrays', () => {
+ expect(spotifyActivityCandidates(null)).toEqual([]);
+ expect(spotifyActivityCandidates({})).toEqual([]);
+ });
+});
+
+describe('summarizeSpotifyCandidates', () => {
+ it('computes range, listen time, unique tracks, and top artists', () => {
+ const candidates = spotifyActivityCandidates([
+ extendedRecord,
+ legacyRecord,
+ { ...extendedRecord, ts: '2023-05-02T10:00:00Z' }, // second Radiohead play
+ ]);
+ const s = summarizeSpotifyCandidates(candidates);
+ expect(s.plays).toBe(3);
+ expect(s.uniqueTracks).toBe(2); // Idioteque (x2, same uri) + Roygbiv
+ expect(s.from).toBe('2022-01-15T09:05:00.000Z');
+ expect(s.to).toBe('2023-05-02T10:00:00.000Z');
+ expect(s.totalMs).toBe(210000 + 132000 + 210000);
+ expect(s.topArtists[0]).toEqual({ name: 'Radiohead', count: 2 });
+ });
+
+ it('handles an empty batch', () => {
+ const s = summarizeSpotifyCandidates([]);
+ expect(s).toMatchObject({ plays: 0, uniqueTracks: 0, totalMs: 0, from: null, to: null });
+ expect(s.topArtists).toEqual([]);
+ });
+});
+
+describe('parseSpotifyJsonText', () => {
+ it('parses a top-level array', () => {
+ expect(parseSpotifyJsonText(JSON.stringify([extendedRecord]))).toHaveLength(1);
+ });
+ it('unwraps an { items: [...] } shape', () => {
+ expect(parseSpotifyJsonText(JSON.stringify({ items: [extendedRecord] }))).toHaveLength(1);
+ });
+ it('returns [] for a non-array/object shape', () => {
+ expect(parseSpotifyJsonText('42')).toEqual([]);
+ expect(parseSpotifyJsonText('{"foo":1}')).toEqual([]);
+ });
+ it('throws on malformed JSON', () => {
+ expect(() => parseSpotifyJsonText('{not json')).toThrow();
+ });
+});