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: Google Takeout Location History importer + shared timeline import seam (#2160)

Adam Eivya8ecbc30e221
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7dc84e8312..d2ee67e669 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -152,4 +152,6 @@
- **[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 Google Takeout Location History → `place.visit` events, on the shared import seam.** The `/timeline` page gains a collapsible "Import Google location history" panel alongside the Spotify one: upload the Takeout "Location History (Timeline)" ZIP (or a single `Semantic Location History` JSON) → preview parsed visit/place counts + date-range + top places → confirm, and every place visit lands as an idempotent `place.visit` event (source `location`) via the existing `recordEvents()` infra (dedupe on place identity + visit start, so re-imports and overlapping exports never double-count). Both export vintages parse: classic server-side Timeline (`timelineObjects[].placeVisit` with E7 coords and ISO or epoch-ms durations) and the 2024+ on-device export (`semanticSegments[].visit.topCandidate` with `latLng` strings). Travel/activity segments carry no "where was I" signal and are dropped; the raw `Records.json` GPS dump is deliberately skipped. The two importers now share ONE seam: a generic `ActivityImportPanel` (pick → preview → confirm, stale-response-guarded) that Spotify + location wrap thinly, one `importHandler` route factory on `/api/timeline`, and one `importFile` client wrapper — so the remaining sources are small follow-ups. (`server/services/takeoutLocationImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/{ActivityImportPanel,TakeoutLocationImportPanel,SpotifyImportPanel}.jsx`, `client/src/pages/Timeline.jsx`)
+
- **[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/ActivityImportPanel.jsx b/client/src/components/timeline/ActivityImportPanel.jsx
new file mode 100644
index 0000000000..a942171bff
--- /dev/null
+++ b/client/src/components/timeline/ActivityImportPanel.jsx
@@ -0,0 +1,156 @@
+import { useState, useRef } from 'react';
+import { Upload, Loader2, CheckCircle2 } from 'lucide-react';
+import toast from '../ui/Toast';
+
+// Shared bulk-backfill importer panel for the timeline (#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.
+//
+// Source-specific bits are props so each source (Spotify, Takeout location, …)
+// is a thin wrapper around this one seam:
+// icon — lucide icon component for the toggle header
+// title — header label ("Import Spotify history")
+// noun — the record noun, singular ("play", "visit") for button/toasts
+// help — JSX help text (where to get the export)
+// importFn — (file, { preview, silent }) => Promise<result>
+// renderPreview— (summary) => JSX for the preview details block
+export default function ActivityImportPanel({ icon: Icon, title, noun, help, importFn, renderPreview, 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);
+ // Monotonic request id — a response only applies if it's still the latest
+ // request, so swapping the file mid-flight can't let a stale response land on
+ // the new selection.
+ const reqIdRef = useRef(0);
+
+ const reset = () => { reqIdRef.current += 1; setFile(null); setPreview(null); setResult(null); };
+
+ const pickFile = (e) => {
+ const next = e.target.files?.[0] || null;
+ reqIdRef.current += 1; // invalidate any in-flight response for the old file
+ setFile(next);
+ setPreview(null);
+ setResult(null);
+ };
+
+ const runPreview = () => {
+ if (!file || busy) return;
+ const rid = ++reqIdRef.current;
+ setBusy(true);
+ setResult(null);
+ importFn(file, { preview: true, silent: true })
+ .then((res) => {
+ if (rid !== reqIdRef.current) return;
+ setPreview(res);
+ if (!res.mapped) toast.error(`No ${noun} records found in that file.`);
+ })
+ .catch((err) => { if (rid === reqIdRef.current) toast.error(`Preview failed: ${err.message}`); })
+ .finally(() => { if (rid === reqIdRef.current) setBusy(false); });
+ };
+
+ const runImport = () => {
+ if (!file || busy) return;
+ const rid = ++reqIdRef.current;
+ setBusy(true);
+ importFn(file, { preview: false, silent: true })
+ .then((res) => {
+ if (rid !== reqIdRef.current) return;
+ setResult(res);
+ toast.success(`Imported ${res.recorded} ${noun}(s) (${res.skipped} already present).`);
+ if (res.recorded > 0) onImported?.();
+ })
+ .catch((err) => { if (rid === reqIdRef.current) toast.error(`Import failed: ${err.message}`); })
+ .finally(() => { if (rid === reqIdRef.current) setBusy(false); });
+ };
+
+ 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}
+ >
+ <Icon size={16} className="text-port-accent" />
+ <span className="font-medium">{title}</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">{help}</p>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <label className={`inline-flex items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm text-gray-200 ${busy ? 'cursor-not-allowed opacity-40' : 'cursor-pointer 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} disabled={busy} 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} {noun}{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>
+ {renderPreview(preview.summary)}
+ </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 {noun}(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>
+ );
+}
+
+// Shared preview helper: render a date range like "1/2/2023 — 4/5/2024" (or a
+// single date when from === to), or null when either bound is missing.
+export function dateRangeLabel(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}`;
+}
diff --git a/client/src/components/timeline/SpotifyImportPanel.jsx b/client/src/components/timeline/SpotifyImportPanel.jsx
index dc2fc41812..ff48ff56a9 100644
--- a/client/src/components/timeline/SpotifyImportPanel.jsx
+++ b/client/src/components/timeline/SpotifyImportPanel.jsx
@@ -1,163 +1,42 @@
-import { useState, useRef } from 'react';
-import { Music, Upload, Loader2, CheckCircle2 } from 'lucide-react';
+import { Music } from 'lucide-react';
import * as api from '../../services/api';
-import toast from '../ui/Toast';
import { formatDurationSec } from '../../utils/formatters';
+import ActivityImportPanel, { dateRangeLabel } from './ActivityImportPanel';
-// 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.
+// Bulk-backfill importer for Spotify "Extended streaming history" exports (#2160),
+// built on the shared ActivityImportPanel seam.
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);
- // Monotonic request id — a response only applies if it's still the latest
- // request, so swapping the file mid-flight can't let a stale response land on
- // the new selection.
- const reqIdRef = useRef(0);
-
- const reset = () => { reqIdRef.current += 1; setFile(null); setPreview(null); setResult(null); };
-
- const pickFile = (e) => {
- const next = e.target.files?.[0] || null;
- reqIdRef.current += 1; // invalidate any in-flight response for the old file
- setFile(next);
- setPreview(null);
- setResult(null);
- };
-
- const runPreview = () => {
- if (!file || busy) return;
- const rid = ++reqIdRef.current;
- setBusy(true);
- setResult(null);
- api.importSpotifyHistory(file, { preview: true, silent: true })
- .then((res) => {
- if (rid !== reqIdRef.current) return;
- setPreview(res);
- if (!res.mapped) toast.error('No listening records found in that file.');
- })
- .catch((err) => { if (rid === reqIdRef.current) toast.error(`Preview failed: ${err.message}`); })
- .finally(() => { if (rid === reqIdRef.current) setBusy(false); });
- };
-
- const runImport = () => {
- if (!file || busy) return;
- const rid = ++reqIdRef.current;
- setBusy(true);
- api.importSpotifyHistory(file, { preview: false, silent: true })
- .then((res) => {
- if (rid !== reqIdRef.current) return;
- setResult(res);
- toast.success(`Imported ${res.recorded} play(s) (${res.skipped} already present).`);
- if (res.recorded > 0) onImported?.();
- })
- .catch((err) => { if (rid === reqIdRef.current) toast.error(`Import failed: ${err.message}`); })
- .finally(() => { if (rid === reqIdRef.current) 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 items-center gap-2 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm text-gray-200 ${busy ? 'cursor-not-allowed opacity-40' : 'cursor-pointer 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} disabled={busy} 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>
+ <ActivityImportPanel
+ icon={Music}
+ title="Import Spotify history"
+ noun="play"
+ importFn={api.importSpotifyHistory}
+ onImported={onImported}
+ help={(
+ <>
+ 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.
+ </>
+ )}
+ renderPreview={(summary) => (
+ <>
+ <div>{summary.plays} play(s) across {summary.uniqueTracks} unique track(s)</div>
+ {dateRangeLabel(summary.from, summary.to) && (
+ <div>Range: {dateRangeLabel(summary.from, summary.to)}</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>
+ {summary.totalMs > 0 && (
+ <div>Total listening: {formatDurationSec(Math.round(summary.totalMs / 1000))}</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>
+ {summary.topArtists?.length > 0 && (
+ <div className="mt-1 truncate">
+ Top: {summary.topArtists.slice(0, 5).map((a) => a.name).join(', ')}
</div>
)}
- </div>
+ </>
)}
- </div>
+ />
);
}
diff --git a/client/src/components/timeline/TakeoutLocationImportPanel.jsx b/client/src/components/timeline/TakeoutLocationImportPanel.jsx
new file mode 100644
index 0000000000..3bdd7c36e4
--- /dev/null
+++ b/client/src/components/timeline/TakeoutLocationImportPanel.jsx
@@ -0,0 +1,39 @@
+import { MapPin } from 'lucide-react';
+import * as api from '../../services/api';
+import ActivityImportPanel, { dateRangeLabel } from './ActivityImportPanel';
+
+// Bulk-backfill importer for Google Takeout "Location History (Timeline)"
+// exports (#2160) → place.visit events, built on the shared ActivityImportPanel
+// seam.
+export default function TakeoutLocationImportPanel({ onImported }) {
+ return (
+ <ActivityImportPanel
+ icon={MapPin}
+ title="Import Google location history"
+ noun="visit"
+ importFn={api.importTakeoutLocationHistory}
+ onImported={onImported}
+ help={(
+ <>
+ Request <span className="text-gray-300">Location History (Timeline)</span> from
+ Google Takeout (takeout.google.com), then upload the ZIP (or a single
+ <span className="font-mono"> Semantic Location History</span> JSON) here. Only place
+ visits are imported — travel segments are skipped. Re-imports are safe.
+ </>
+ )}
+ renderPreview={(summary) => (
+ <>
+ <div>{summary.visits} visit(s) across {summary.uniquePlaces} unique place(s)</div>
+ {dateRangeLabel(summary.from, summary.to) && (
+ <div>Range: {dateRangeLabel(summary.from, summary.to)}</div>
+ )}
+ {summary.topPlaces?.length > 0 && (
+ <div className="mt-1 truncate">
+ Top: {summary.topPlaces.slice(0, 5).map((p) => p.name).join(', ')}
+ </div>
+ )}
+ </>
+ )}
+ />
+ );
+}
diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsx
index 0d39c6768c..1c5b6313be 100644
--- a/client/src/pages/Timeline.jsx
+++ b/client/src/pages/Timeline.jsx
@@ -2,10 +2,11 @@ import { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
CalendarClock, ChevronLeft, ChevronRight, Mail, MailOpen, Send,
- CalendarDays, Music, Play, MessageSquare, Activity,
+ CalendarDays, Music, Play, MessageSquare, Activity, MapPin,
} from 'lucide-react';
import PageHeader from '../components/PageHeader';
import SpotifyImportPanel from '../components/timeline/SpotifyImportPanel';
+import TakeoutLocationImportPanel from '../components/timeline/TakeoutLocationImportPanel';
import * as api from '../services/api';
import toast from '../components/ui/Toast';
import { formatClockTime, formatDurationSec } from '../utils/formatters';
@@ -37,12 +38,14 @@ const SOURCE_ICON = {
signal: MessageSquare,
spotify: Music,
youtube: Play,
+ location: MapPin,
};
function kindIcon(kind, source) {
if (kind === 'message.sent') return Send;
if (kind === 'message.received') return MailOpen;
if (kind === 'calendar.event') return CalendarDays;
+ if (kind === 'place.visit') return MapPin;
return SOURCE_ICON[source] || Activity;
}
@@ -50,7 +53,8 @@ function KindBadge({ kind }) {
const label = kind === 'message.sent' ? 'Sent'
: kind === 'message.received' ? 'Received'
: kind === 'calendar.event' ? 'Event'
- : kind;
+ : kind === 'place.visit' ? 'Visit'
+ : kind;
return (
<span className="rounded bg-port-bg px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-gray-400">
{label}
@@ -202,6 +206,7 @@ export default function Timeline() {
</div>
<SpotifyImportPanel onImported={() => setReloadKey((k) => k + 1)} />
+ <TakeoutLocationImportPanel onImported={() => setReloadKey((k) => k + 1)} />
<Histogram histogram={histogram} />
diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.js
index 90769b09a7..1d29443e4a 100644
--- a/client/src/services/apiTimeline.js
+++ b/client/src/services/apiTimeline.js
@@ -21,13 +21,22 @@ export const getTimelineEvents = (options = {}) => {
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 } = {}) => {
+// Bulk-backfill importers (#2160). Upload an export file (ZIP or single 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.
+const importFile = (path, 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 });
+ return request(path, { method: 'POST', body: formData, ...options });
};
+
+// Spotify extended-history export (dedupe on played-at + track).
+export const importSpotifyHistory = (file, options = {}) =>
+ importFile('/timeline/import/spotify', file, options);
+
+// Google Takeout "Location History (Timeline)" semantic place visits (dedupe on
+// visit-start + place identity).
+export const importTakeoutLocationHistory = (file, options = {}) =>
+ importFile('/timeline/import/takeout-location', file, options);
diff --git a/server/routes/timeline.js b/server/routes/timeline.js
index 8e93b5b7fa..edda35b529 100644
--- a/server/routes/timeline.js
+++ b/server/routes/timeline.js
@@ -7,21 +7,26 @@ 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';
+import { importTakeoutLocationHistory } from '../services/takeoutLocationImport.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', {
+// Bulk-export uploads (Spotify extended history, Google Takeout location
+// history) are ZIPs of JSON arrays bounded by the account lifetime — 200MB
+// comfortably covers years of history. Both accept the same ZIP-or-JSON shape.
+const zipOrJsonUpload = (label) => 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' }));
+ cb(new ServerError(`Only ${label} export ZIP or JSON files are accepted`, { status: 400, code: 'BAD_REQUEST' }));
},
});
+const uploadSpotify = zipOrJsonUpload('Spotify');
+const uploadTakeoutLocation = zipOrJsonUpload('Google Takeout location');
+
// `preview` (a multipart text field, so it arrives as a string) toggles a
// parse-only dry run — count what would be imported without writing. Only map
// the recognized true/false tokens; any other string is left as-is so Zod
@@ -65,22 +70,30 @@ 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) => {
+// Shared handler for the bulk-backfill importers (#2160). Each accepts a ZIP or
+// single JSON via multipart upload; `preview=true` parses + summarizes without
+// writing; a real import is idempotent (dedupe key per source), so re-imports
+// are safe. The uploaded temp file is ALWAYS unlinked, success or not, and BOTH
+// validation and the import run inside the cleanup chain so a rejected `preview`
+// value still unlinks the already-staged temp upload.
+const importHandler = (importFn) => asyncHandler(async (req, res) => {
const file = req.file;
if (!file?.path) throw new ServerError('No file uploaded', { status: 400, code: 'BAD_REQUEST' });
- // Wrap BOTH validation and the import in the cleanup chain — a rejected
- // `preview` value must still unlink the already-staged temp upload.
const run = async () => {
const { preview } = validateRequest(importBodySchema, req.body);
- return importSpotifyHistory(file, { dryRun: preview });
+ return importFn(file, { dryRun: preview });
};
const result = await run().finally(() => unlink(file.path).catch(() => {}));
res.json(result);
-}));
+});
+
+// POST /api/timeline/import/spotify — bulk-backfill Spotify extended streaming
+// history (dedupe on played-at + track).
+router.post('/import/spotify', uploadSpotify, importHandler(importSpotifyHistory));
+
+// POST /api/timeline/import/takeout-location — bulk-backfill Google Takeout
+// "Location History (Timeline)" semantic place visits → place.visit events
+// (dedupe on visit-start + place identity).
+router.post('/import/takeout-location', uploadTakeoutLocation, importHandler(importTakeoutLocationHistory));
export default router;
diff --git a/server/routes/timeline.test.js b/server/routes/timeline.test.js
index b8eb6683da..838bb29a21 100644
--- a/server/routes/timeline.test.js
+++ b/server/routes/timeline.test.js
@@ -16,12 +16,24 @@ vi.mock('../services/spotifyImport.js', () => ({
})),
}));
+vi.mock('../services/takeoutLocationImport.js', () => ({
+ importTakeoutLocationHistory: vi.fn(async (file, opts) => ({
+ dryRun: Boolean(opts?.dryRun),
+ parsed: 2,
+ mapped: 2,
+ recorded: opts?.dryRun ? 0 : 2,
+ skipped: opts?.dryRun ? 0 : 0,
+ summary: { visits: 2, uniquePlaces: 2, from: null, to: null, topPlaces: [] },
+ })),
+}));
+
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 { importTakeoutLocationHistory } from '../services/takeoutLocationImport.js';
import timelineRoutes from './timeline.js';
function makeApp() {
@@ -131,4 +143,46 @@ describe('timeline import routes', () => {
expect(r.status).toBe(400);
expect(importSpotifyHistory).not.toHaveBeenCalled();
});
+
+ it('POST /import/takeout-location parses the upload and calls the importer', async () => {
+ const { boundary, body } = multipart(
+ { preview: 'false' },
+ { filename: '2021_MARCH.json', contentType: 'application/json', content: '{}' },
+ );
+ const r = await request(app).post('/api/timeline/import/takeout-location')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(body);
+ expect(r.status).toBe(200);
+ expect(r.body.recorded).toBe(2);
+ expect(importTakeoutLocationHistory).toHaveBeenCalledWith(
+ expect.objectContaining({ originalname: '2021_MARCH.json' }),
+ { dryRun: false },
+ );
+ });
+
+ it('takeout-location honors preview=true as a dry run', async () => {
+ const { boundary, body } = multipart(
+ { preview: 'true' },
+ { filename: 'export.zip', contentType: 'application/zip', content: 'PK...' },
+ );
+ const r = await request(app).post('/api/timeline/import/takeout-location')
+ .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(importTakeoutLocationHistory).toHaveBeenCalledWith(expect.anything(), { dryRun: true });
+ });
+
+ it('takeout-location 400s on an unrecognized preview token', async () => {
+ const { boundary, body } = multipart(
+ { preview: 'maybe' },
+ { filename: 'x.json', contentType: 'application/json', content: '{}' },
+ );
+ const r = await request(app).post('/api/timeline/import/takeout-location')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(body);
+ expect(r.status).toBe(400);
+ expect(importTakeoutLocationHistory).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/takeoutLocationImport.js b/server/services/takeoutLocationImport.js
new file mode 100644
index 0000000000..445d85787a
--- /dev/null
+++ b/server/services/takeoutLocationImport.js
@@ -0,0 +1,337 @@
+/**
+ * Google Takeout Location History importer (#2160) — bulk historical backfill
+ * into the human-activity timeline.
+ *
+ * Google's "Location History (Timeline)" Takeout export contains, per month, a
+ * `Semantic Location History/YYYY/YYYY_MONTH.json` file describing where you
+ * were. Two shapes exist across export vintages:
+ *
+ * - Classic semantic history (server-side Timeline, pre-2024): a top-level
+ * `{ timelineObjects: [{ placeVisit: { location, duration }, ... }] }`. Each
+ * `placeVisit` carries `location.{ name, address, placeId, latitudeE7,
+ * longitudeE7, semanticType }` and `duration.{ startTimestamp, endTimestamp }`
+ * (older files use epoch-ms `startTimestampMs` / `endTimestampMs`).
+ * - On-device Timeline export (2024+): a top-level `{ semanticSegments: [{
+ * startTime, endTime, visit: { topCandidate: { placeId, semanticType,
+ * placeLocation: { latLng } } } }] }`, where `latLng` is a
+ * `"37.4°, -122.0°"` (or `"geo:lat,lng"`) string.
+ *
+ * We map every place VISIT (not travel/activity segments) to a `place.visit`
+ * activity event under source `location`. Travel segments carry no
+ * autobiographical "where was I" signal at the granularity the timeline cares
+ * about, so they're dropped.
+ *
+ * Idempotent: every candidate carries a stable `dedupeKey` (place identity +
+ * visit start instant), so re-importing the same export — or an overlapping
+ * newer one — 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 Takeout visit timestamp to a UTC ISO string, or null if unparseable.
+// Classic files use ISO-8601 with a `Z` (`startTimestamp`); older classic files
+// use an epoch-ms string (`startTimestampMs`); on-device files use ISO with an
+// offset. A bare all-digits value is treated as epoch milliseconds.
+export function resolveTakeoutInstant(value) {
+ if (value === null || value === undefined) return null;
+ const s = String(value).trim();
+ if (!s) return null;
+ if (/^\d+$/.test(s)) {
+ const d = new Date(Number(s));
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+ }
+ const d = new Date(s);
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+}
+
+// Round a coordinate to ~6 decimal places (≈0.1m) for a stable dedupe fallback
+// and compact metadata; returns null for non-finite input.
+function roundCoord(n) {
+ return Number.isFinite(n) ? Math.round(n * 1e6) / 1e6 : null;
+}
+
+// Resolve a { lat, lng } pair from the several shapes Takeout uses:
+// - E7 integers: `latitudeE7` / `longitudeE7` (degrees × 1e7)
+// - a `latLng` string: "37.421°, -122.084°" or "geo:37.421,-122.084"
+// Returns { lat, lng } (rounded) or null when neither yields two finite numbers.
+export function resolveLatLng({ latitudeE7, longitudeE7, latLng } = {}) {
+ if (Number.isFinite(latitudeE7) && Number.isFinite(longitudeE7)) {
+ return { lat: roundCoord(latitudeE7 / 1e7), lng: roundCoord(longitudeE7 / 1e7) };
+ }
+ if (typeof latLng === 'string' && latLng.trim()) {
+ const nums = latLng.replace(/geo:/i, '').match(/-?\d+(?:\.\d+)?/g);
+ if (nums && nums.length >= 2) {
+ const lat = roundCoord(Number(nums[0]));
+ const lng = roundCoord(Number(nums[1]));
+ if (lat !== null && lng !== null) return { lat, lng };
+ }
+ }
+ return null;
+}
+
+// Human-readable label for a place. Google semantic types come through as
+// `TYPE_HOME` / `TYPE_WORK` / `HOME` / `INFERRED_WORK` etc. — normalize the
+// common ones to a friendly word; pass anything else through title-cased.
+export function friendlySemanticType(type) {
+ if (!type) return null;
+ const norm = String(type).replace(/^TYPE_/, '').replace(/^INFERRED_/, '').trim().toUpperCase();
+ if (!norm || norm === 'UNKNOWN') return null;
+ const map = { HOME: 'Home', WORK: 'Work', SEARCHED_ADDRESS: 'Searched address' };
+ if (map[norm]) return map[norm];
+ return norm
+ .toLowerCase()
+ .split(/[_\s]+/)
+ .filter(Boolean)
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
+ .join(' ');
+}
+
+// Map ONE normalized visit intermediate to an activity candidate, or null if it
+// lacks a usable start instant. Shared by both export shapes.
+// visit = { startTime, endTime, name, address, placeId, lat, lng, semanticType }
+export function visitToCandidate(visit) {
+ if (!visit || typeof visit !== 'object') return null;
+ const happenedAt = resolveTakeoutInstant(visit.startTime);
+ if (!happenedAt) return null;
+ const endAt = resolveTakeoutInstant(visit.endTime);
+
+ const friendly = friendlySemanticType(visit.semanticType);
+ const title = visit.name || visit.address || friendly || 'Place visit';
+
+ const durationS = endAt
+ ? Math.max(0, Math.round((new Date(endAt).getTime() - new Date(happenedAt).getTime()) / 1000))
+ : null;
+
+ // Dedupe on the visit start + place identity. Prefer the Google placeId; fall
+ // back to rounded lat/lng, then to the title, so two *different* places don't
+ // collapse into one visit when a placeId is absent (on-device exports omit it
+ // for un-geocoded stops).
+ const identity = visit.placeId
+ || (visit.lat !== null && visit.lat !== undefined && visit.lng !== null && visit.lng !== undefined
+ ? `${visit.lat},${visit.lng}`
+ : null)
+ || title;
+ const dedupeKey = `location:${identity}:${happenedAt}`;
+
+ // Summary keeps a short human line (address, else the friendly type) — never a
+ // full record. Drop the address when it's identical to the title to avoid "X — X".
+ const summaryText = visit.address && visit.address !== title ? visit.address : friendly;
+
+ return {
+ source: 'location',
+ kind: 'place.visit',
+ happenedAt,
+ durationS: durationS && durationS > 0 ? durationS : null,
+ title,
+ summary: summaryText ? shortSummary(summaryText) : null,
+ dedupeKey,
+ metadata: {
+ placeId: visit.placeId || null,
+ address: visit.address || null,
+ semanticType: visit.semanticType || null,
+ lat: visit.lat ?? null,
+ lng: visit.lng ?? null,
+ endTime: endAt,
+ },
+ };
+}
+
+// Extract normalized visit intermediates from ONE classic `placeVisit` object.
+function normalizeClassicPlaceVisit(placeVisit) {
+ if (!placeVisit || typeof placeVisit !== 'object') return null;
+ const loc = placeVisit.location || {};
+ const dur = placeVisit.duration || {};
+ const { lat, lng } = resolveLatLng({
+ latitudeE7: Number(loc.latitudeE7),
+ longitudeE7: Number(loc.longitudeE7),
+ }) || {};
+ return {
+ startTime: dur.startTimestamp ?? dur.startTimestampMs ?? null,
+ endTime: dur.endTimestamp ?? dur.endTimestampMs ?? null,
+ name: loc.name || null,
+ address: loc.address || null,
+ placeId: loc.placeId || null,
+ semanticType: loc.semanticType || null,
+ lat: lat ?? null,
+ lng: lng ?? null,
+ };
+}
+
+// Extract normalized visit intermediates from ONE on-device `semanticSegments`
+// entry that carries a `visit` (skips activity/travel segments → null).
+function normalizeSegmentVisit(segment) {
+ if (!segment || typeof segment !== 'object' || !segment.visit) return null;
+ const cand = segment.visit.topCandidate || {};
+ const { lat, lng } = resolveLatLng({ latLng: cand.placeLocation?.latLng }) || {};
+ return {
+ startTime: segment.startTime ?? null,
+ endTime: segment.endTime ?? null,
+ name: cand.name || null,
+ address: cand.address || null,
+ placeId: cand.placeId || null,
+ semanticType: cand.semanticType || null,
+ lat: lat ?? null,
+ lng: lng ?? null,
+ };
+}
+
+// Turn ONE parsed Takeout file object into normalized visit intermediates,
+// handling both export shapes and a bare `placeVisit`/`visit` array. Non-visit
+// entries (travel segments) are dropped.
+export function extractVisits(parsed) {
+ if (!parsed || typeof parsed !== 'object') return [];
+ const out = [];
+ if (Array.isArray(parsed.timelineObjects)) {
+ for (const obj of parsed.timelineObjects) {
+ if (obj?.placeVisit) {
+ const v = normalizeClassicPlaceVisit(obj.placeVisit);
+ if (v) out.push(v);
+ }
+ }
+ }
+ if (Array.isArray(parsed.semanticSegments)) {
+ for (const seg of parsed.semanticSegments) {
+ const v = normalizeSegmentVisit(seg);
+ if (v) out.push(v);
+ }
+ }
+ return out;
+}
+
+// Map a batch of visit intermediates to candidates, dropping the unmappable ones.
+export function takeoutLocationCandidates(visits = []) {
+ if (!Array.isArray(visits)) return [];
+ return visits.map(visitToCandidate).filter(Boolean);
+}
+
+// Summarize a candidate batch for the import preview: date range, visit count,
+// unique places, and the most-visited place labels. Pure over candidates.
+export function summarizeLocationCandidates(candidates = []) {
+ const list = Array.isArray(candidates) ? candidates : [];
+ let earliest = null;
+ let latest = null;
+ const places = new Set();
+ const placeCounts = 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 key = c.metadata?.placeId || c.title;
+ places.add(key);
+ placeCounts.set(c.title, (placeCounts.get(c.title) || 0) + 1);
+ }
+ const topPlaces = [...placeCounts.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 10)
+ .map(([name, count]) => ({ name, count }));
+ return {
+ visits: list.length,
+ uniquePlaces: places.size,
+ from: earliest,
+ to: latest,
+ topPlaces,
+ };
+}
+
+// Parse the text of a single Takeout location JSON file into a parsed object.
+// Throws only on malformed JSON; `extractVisits` handles the shape dispatch.
+export function parseTakeoutJsonText(text) {
+ return JSON.parse(text);
+}
+
+// ---------------------------------------------------------------------------
+// File ingestion (ZIP or single JSON) → visit intermediates.
+// ---------------------------------------------------------------------------
+
+const isZip = (file) =>
+ file?.mimetype === 'application/zip' ||
+ file?.mimetype === 'application/x-zip-compressed' ||
+ /\.zip$/i.test(file?.originalname || '');
+
+// A semantic-location-history JSON member inside the Takeout ZIP. Google names
+// per-month files `2021_JANUARY.json` under a `Semantic Location History/YYYY/`
+// folder; the on-device export ships a single `location-history.json` /
+// `Timeline.json`. We deliberately DON'T match `Records.json` (raw GPS points —
+// enormous, no place visits) or other Takeout JSON.
+const isLocationJsonEntry = (entryPath) => {
+ const path = String(entryPath || '');
+ if (!/\.json$/i.test(path)) return false;
+ if (/(?:^|\/)Records\.json$/i.test(path)) return false;
+ return (
+ /Semantic Location History\//i.test(path) ||
+ /(?:^|\/)\d{4}_[A-Z]+\.json$/i.test(path) ||
+ /(?:^|\/)(?:location-history|Timeline)\.json$/i.test(path)
+ );
+};
+
+// Extract and concatenate the visit intermediates from every location-history
+// JSON member of the Takeout ZIP. Non-matching entries are drained and ignored.
+async function readVisitsFromZip(filePath) {
+ const visits = [];
+ const reads = [];
+ await new Promise((resolve, reject) => {
+ let settled = false;
+ const src = createReadStream(filePath);
+ const parser = parseZip();
+ const settle = (fn) => (...args) => {
+ if (settled) return;
+ settled = true;
+ // On failure, tear down the read + parse pipeline so a large upload with an
+ // early error (bad JSON member, corrupt ZIP) doesn't keep reading to EOF.
+ if (fn === reject) { src.destroy(); parser.destroy?.(); }
+ fn(...args);
+ };
+ src.on('error', settle(reject));
+ src
+ .pipe(parser)
+ .on('entry', (entry) => {
+ if (isLocationJsonEntry(entry.path)) {
+ reads.push(
+ collectZipEntry(entry)
+ .then((buf) => {
+ for (const v of extractVisits(parseTakeoutJsonText(buf.toString('utf-8')))) visits.push(v);
+ })
+ .catch(settle(reject)),
+ );
+ } else {
+ entry.autodrain();
+ }
+ })
+ .on('close', () => Promise.all(reads).then(settle(resolve)).catch(settle(reject)))
+ .on('error', settle(reject));
+ });
+ return visits;
+}
+
+// Read visit intermediates from an uploaded file (ZIP export or single JSON).
+export async function readTakeoutVisits(file) {
+ if (!file?.path) return [];
+ if (isZip(file)) return readVisitsFromZip(file.path);
+ const text = await readFile(file.path, 'utf-8');
+ return extractVisits(parseTakeoutJsonText(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 importTakeoutLocationHistory(file, { dryRun = false } = {}) {
+ const visits = await readTakeoutVisits(file);
+ const candidates = takeoutLocationCandidates(visits);
+ const summary = summarizeLocationCandidates(candidates);
+ if (dryRun) {
+ console.log(`📍 Takeout location import preview: ${candidates.length} visit(s) from ${visits.length} record(s)`);
+ return { dryRun: true, parsed: visits.length, mapped: candidates.length, recorded: 0, skipped: 0, summary };
+ }
+ const { recorded, skipped } = await recordEvents(candidates);
+ console.log(`📍 Takeout location import: ${recorded} new visit(s) recorded, ${skipped} duplicate/invalid (from ${visits.length} record(s))`);
+ return { dryRun: false, parsed: visits.length, mapped: candidates.length, recorded, skipped, summary };
+}
diff --git a/server/services/takeoutLocationImport.test.js b/server/services/takeoutLocationImport.test.js
new file mode 100644
index 0000000000..263d902918
--- /dev/null
+++ b/server/services/takeoutLocationImport.test.js
@@ -0,0 +1,235 @@
+import { describe, it, expect } from 'vitest';
+import {
+ resolveTakeoutInstant,
+ resolveLatLng,
+ friendlySemanticType,
+ visitToCandidate,
+ extractVisits,
+ takeoutLocationCandidates,
+ summarizeLocationCandidates,
+ parseTakeoutJsonText,
+} from './takeoutLocationImport.js';
+
+// A classic semantic-location-history file (server-side Timeline, pre-2024).
+const classicFile = {
+ timelineObjects: [
+ {
+ placeVisit: {
+ location: {
+ name: 'Blue Bottle Coffee',
+ address: '66 Mint St, San Francisco, CA',
+ placeId: 'ChIJ-blue-bottle',
+ latitudeE7: 377834990,
+ longitudeE7: -1224019870,
+ semanticType: 'TYPE_SEARCHED_ADDRESS',
+ },
+ duration: { startTimestamp: '2021-03-01T15:00:00Z', endTimestamp: '2021-03-01T16:30:00Z' },
+ },
+ },
+ // A travel/activity segment — must be dropped (no placeVisit).
+ { activitySegment: { distance: 1200 } },
+ {
+ placeVisit: {
+ location: { name: 'Home', placeId: 'ChIJ-home', semanticType: 'TYPE_HOME' },
+ // older classic files: epoch-ms strings
+ duration: { startTimestampMs: '1614624300000', endTimestampMs: '1614640000000' },
+ },
+ },
+ ],
+};
+
+// An on-device Timeline export (2024+).
+const onDeviceFile = {
+ semanticSegments: [
+ {
+ startTime: '2024-06-15T09:00:00.000-07:00',
+ endTime: '2024-06-15T10:15:00.000-07:00',
+ visit: {
+ topCandidate: {
+ placeId: 'ChIJ-work',
+ semanticType: 'INFERRED_WORK',
+ placeLocation: { latLng: '37.4220°, -122.0840°' },
+ },
+ },
+ },
+ // A travel segment — no `visit`, must be dropped.
+ { startTime: '2024-06-15T10:15:00-07:00', endTime: '2024-06-15T10:30:00-07:00', activity: { distanceMeters: 900 } },
+ ],
+};
+
+describe('resolveTakeoutInstant', () => {
+ it('passes ISO-8601 timestamps through (with offset)', () => {
+ expect(resolveTakeoutInstant('2024-06-15T09:00:00.000-07:00')).toBe('2024-06-15T16:00:00.000Z');
+ });
+ it('passes UTC ISO through', () => {
+ expect(resolveTakeoutInstant('2021-03-01T15:00:00Z')).toBe('2021-03-01T15:00:00.000Z');
+ });
+ it('treats all-digit strings as epoch milliseconds', () => {
+ expect(resolveTakeoutInstant('1614624300000')).toBe('2021-03-01T18:45:00.000Z');
+ });
+ it('returns null for empty/unparseable/nullish values', () => {
+ expect(resolveTakeoutInstant('')).toBeNull();
+ expect(resolveTakeoutInstant(null)).toBeNull();
+ expect(resolveTakeoutInstant(undefined)).toBeNull();
+ expect(resolveTakeoutInstant('not a date')).toBeNull();
+ });
+});
+
+describe('resolveLatLng', () => {
+ it('converts E7 integers to rounded degrees', () => {
+ expect(resolveLatLng({ latitudeE7: 377834990, longitudeE7: -1224019870 }))
+ .toEqual({ lat: 37.783499, lng: -122.401987 });
+ });
+ it('parses a degree-symbol latLng string', () => {
+ expect(resolveLatLng({ latLng: '37.4220°, -122.0840°' })).toEqual({ lat: 37.422, lng: -122.084 });
+ });
+ it('parses a geo: latLng string', () => {
+ expect(resolveLatLng({ latLng: 'geo:37.422,-122.084' })).toEqual({ lat: 37.422, lng: -122.084 });
+ });
+ it('returns null when neither shape yields two coords', () => {
+ expect(resolveLatLng({})).toBeNull();
+ expect(resolveLatLng({ latLng: 'nope' })).toBeNull();
+ expect(resolveLatLng({ latitudeE7: 100 })).toBeNull();
+ });
+});
+
+describe('friendlySemanticType', () => {
+ it('maps common Google types to friendly words', () => {
+ expect(friendlySemanticType('TYPE_HOME')).toBe('Home');
+ expect(friendlySemanticType('INFERRED_WORK')).toBe('Work');
+ expect(friendlySemanticType('TYPE_SEARCHED_ADDRESS')).toBe('Searched address');
+ });
+ it('title-cases unknown types', () => {
+ expect(friendlySemanticType('TYPE_GYM')).toBe('Gym');
+ });
+ it('drops empty/unknown', () => {
+ expect(friendlySemanticType(null)).toBeNull();
+ expect(friendlySemanticType('UNKNOWN')).toBeNull();
+ expect(friendlySemanticType('TYPE_UNKNOWN')).toBeNull();
+ });
+});
+
+describe('extractVisits', () => {
+ it('extracts classic placeVisit entries and drops travel segments', () => {
+ const visits = extractVisits(classicFile);
+ expect(visits).toHaveLength(2);
+ expect(visits[0]).toMatchObject({
+ name: 'Blue Bottle Coffee',
+ placeId: 'ChIJ-blue-bottle',
+ startTime: '2021-03-01T15:00:00Z',
+ lat: 37.783499,
+ lng: -122.401987,
+ });
+ // second visit uses epoch-ms duration keys
+ expect(visits[1]).toMatchObject({ name: 'Home', startTime: '1614624300000' });
+ });
+
+ it('extracts on-device semanticSegments visits and drops non-visit segments', () => {
+ const visits = extractVisits(onDeviceFile);
+ expect(visits).toHaveLength(1);
+ expect(visits[0]).toMatchObject({
+ placeId: 'ChIJ-work',
+ semanticType: 'INFERRED_WORK',
+ lat: 37.422,
+ lng: -122.084,
+ });
+ });
+
+ it('returns [] for junk / missing arrays', () => {
+ expect(extractVisits(null)).toEqual([]);
+ expect(extractVisits({})).toEqual([]);
+ expect(extractVisits(42)).toEqual([]);
+ });
+});
+
+describe('visitToCandidate', () => {
+ it('maps a classic visit to a place.visit candidate with duration', () => {
+ const [visit] = extractVisits(classicFile);
+ const c = visitToCandidate(visit);
+ expect(c).toMatchObject({
+ source: 'location',
+ kind: 'place.visit',
+ happenedAt: '2021-03-01T15:00:00.000Z',
+ durationS: 90 * 60,
+ title: 'Blue Bottle Coffee',
+ });
+ expect(c.summary).toBe('66 Mint St, San Francisco, CA');
+ expect(c.metadata).toMatchObject({ placeId: 'ChIJ-blue-bottle', lat: 37.783499, lng: -122.401987 });
+ });
+
+ it('falls back to friendly semantic type for the title when no name/address', () => {
+ const c = visitToCandidate({ startTime: '2021-01-01T00:00:00Z', semanticType: 'TYPE_HOME', placeId: 'p' });
+ expect(c.title).toBe('Home');
+ });
+
+ it('builds a stable dedupe key from placeId + visit start', () => {
+ const [visit] = extractVisits(classicFile);
+ const a = visitToCandidate(visit);
+ const b = visitToCandidate({ ...visit });
+ expect(a.dedupeKey).toBe(b.dedupeKey);
+ expect(a.dedupeKey).toBe('location:ChIJ-blue-bottle:2021-03-01T15:00:00.000Z');
+ });
+
+ it('uses rounded lat/lng as the dedupe fallback when placeId is absent (no title-only collapse)', () => {
+ const base = { startTime: '2021-01-01T12:00:00Z', name: 'Cafe' };
+ const a = visitToCandidate({ ...base, lat: 1.1, lng: 2.2 });
+ const b = visitToCandidate({ ...base, lat: 3.3, lng: 4.4 });
+ // Same title + same instant, different coords — must NOT share a dedupe key.
+ expect(a.dedupeKey).not.toBe(b.dedupeKey);
+ expect(a.dedupeKey).toContain('1.1,2.2');
+ });
+
+ it('leaves durationS null when there is no end time', () => {
+ const c = visitToCandidate({ startTime: '2021-01-01T00:00:00Z', name: 'X' });
+ expect(c.durationS).toBeNull();
+ });
+
+ it('drops visits with no usable start instant', () => {
+ expect(visitToCandidate({ name: 'X' })).toBeNull();
+ expect(visitToCandidate(null)).toBeNull();
+ });
+});
+
+describe('takeoutLocationCandidates', () => {
+ it('maps a batch and filters unmappable rows', () => {
+ const out = takeoutLocationCandidates([...extractVisits(classicFile), { name: 'no-start' }]);
+ expect(out).toHaveLength(2);
+ expect(out.every((c) => c.source === 'location' && c.kind === 'place.visit')).toBe(true);
+ });
+ it('returns [] for non-arrays', () => {
+ expect(takeoutLocationCandidates(null)).toEqual([]);
+ expect(takeoutLocationCandidates({})).toEqual([]);
+ });
+});
+
+describe('summarizeLocationCandidates', () => {
+ it('computes range, visit count, unique places, and top places', () => {
+ const candidates = takeoutLocationCandidates([
+ ...extractVisits(classicFile),
+ ...extractVisits(onDeviceFile),
+ // a second Blue Bottle visit (same placeId, later day)
+ { startTime: '2021-03-05T15:00:00Z', name: 'Blue Bottle Coffee', placeId: 'ChIJ-blue-bottle' },
+ ]);
+ const s = summarizeLocationCandidates(candidates);
+ expect(s.visits).toBe(4);
+ expect(s.uniquePlaces).toBe(3); // blue-bottle (x2), home, work
+ expect(s.from).toBe('2021-03-01T15:00:00.000Z');
+ expect(s.to).toBe('2024-06-15T16:00:00.000Z');
+ expect(s.topPlaces[0]).toEqual({ name: 'Blue Bottle Coffee', count: 2 });
+ });
+
+ it('handles an empty batch', () => {
+ const s = summarizeLocationCandidates([]);
+ expect(s).toMatchObject({ visits: 0, uniquePlaces: 0, from: null, to: null });
+ expect(s.topPlaces).toEqual([]);
+ });
+});
+
+describe('parseTakeoutJsonText', () => {
+ it('parses a classic file', () => {
+ expect(parseTakeoutJsonText(JSON.stringify(classicFile)).timelineObjects).toHaveLength(3);
+ });
+ it('throws on malformed JSON', () => {
+ expect(() => parseTakeoutJsonText('{not json')).toThrow();
+ });
+});