-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnewtab.js
More file actions
584 lines (528 loc) · 18.8 KB
/
Copy pathnewtab.js
File metadata and controls
584 lines (528 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
import {
getConfig,
isConfigured,
randomAssets,
onThisDay,
viewUrl,
ping,
} from "../lib/immich.js";
const VERSION_TAG = "diag-v3";
const $ = (id) => document.getElementById(id);
function fmtClock(d) {
return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", hour12: false });
}
function fmtDate(d) {
return d.toLocaleDateString([], { weekday: "long", month: "long", day: "numeric" });
}
function tickClock() {
$("clock").textContent = fmtClock(new Date());
}
setInterval(tickClock, 1000);
tickClock();
async function loadThumbViaBg(assetId, size = "preview") {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ type: "thumb", assetId, size }, (res) => {
if (chrome.runtime.lastError) return reject(new Error(chrome.runtime.lastError.message));
if (!res?.ok) return reject(new Error(res?.error || `status ${res?.status}`));
const blob = new Blob([new Uint8Array(res.data)], { type: res.contentType || "image/jpeg" });
resolve(URL.createObjectURL(blob));
});
});
}
function showToast(msg, link) {
const t = $("toast");
t.replaceChildren();
t.appendChild(document.createTextNode(msg));
if (link) {
const a = document.createElement("a");
a.href = "#";
a.textContent = link.label;
a.addEventListener("click", (e) => { e.preventDefault(); link.onClick(); });
t.appendChild(a);
}
t.hidden = false;
}
let rotateTimer;
// ---- Background-image cache --------------------------------------------
//
// Pre-fetches the next few random previews into the browser's Cache API
// so each new-tab open can paint the background instantly instead of
// waiting on the network. Strategy:
//
// - On every new-tab open: try to pop one entry from the queue and
// display it immediately. Then asynchronously top up the queue back
// to BG_MAX_QUEUED so the next open is also instant.
// - The queue lives in chrome.storage.local (small JSON: assetId, asset
// metadata, cachedAt). Image bytes go into the Cache API which is
// designed for blob storage and managed by the browser.
// - Each consume removes the displayed entry, so a user never sees the
// same cached image twice in a row.
// - Stale entries (>24h) are evicted on init. New ones are only kept
// up to BG_MAX_QUEUED. Worst-case disk usage: ~1.5 MB (3 × ~500 KB
// preview JPEGs).
const BG_CACHE_NAME = "immich-newtab-bg-v1";
const BG_META_KEY = "newtabBgCache";
const BG_MAX_QUEUED = 3;
const BG_STALE_MS = 24 * 60 * 60 * 1000; // 24 hours
// MUST match background.js's newtabBgCacheKey(). Cache API rejects
// chrome-extension:// scheme, so we use a deliberately-non-resolving
// .invalid URL as a string key — both contexts have to agree on it.
function bgCacheKey(assetId) {
return `https://immich-companion.invalid/newtab-bg/${assetId}`;
}
async function getBgMeta() {
try {
const r = await chrome.storage.local.get(BG_META_KEY);
const m = r?.[BG_META_KEY];
return m && Array.isArray(m.queue) ? m : { queue: [] };
} catch {
return { queue: [] };
}
}
async function setBgMeta(meta) {
try { await chrome.storage.local.set({ [BG_META_KEY]: meta }); } catch {}
}
// Take one entry off the queue + Cache, return its asset metadata + blob.
// Returns null if the queue is empty or the cache is out of sync.
async function consumeCachedBg() {
// Run storage.get and caches.open in parallel — they're independent.
// Saves ~10-30 ms vs awaiting them serially.
const [meta, cache] = await Promise.all([
getBgMeta(),
caches.open(BG_CACHE_NAME).catch(() => null),
]);
if (!meta.queue.length || !cache) return null;
while (meta.queue.length) {
const entry = meta.queue.shift();
const key = bgCacheKey(entry.assetId);
let response;
try { response = await cache.match(key); } catch {}
if (response) {
try { await cache.delete(key); } catch {}
await setBgMeta(meta);
try {
return { asset: entry.asset, blob: await response.blob() };
} catch {
// unreadable response — try the next entry
}
}
}
await setBgMeta(meta);
return null;
}
// Ask the background service worker to top up the cache. Fire-and-forget
// — must NOT happen on the new-tab page itself, because new tabs unload
// the moment the user types a URL or clicks a result and any in-flight
// fetch/storage write gets killed mid-flight. The SW persists across the
// document closing.
function requestPrecacheTopUp() {
try {
chrome.runtime.sendMessage({ type: "newtab-precache" }).catch(() => {});
} catch {}
}
// Drop entries older than BG_STALE_MS. Called once at init.
async function evictStaleBg() {
const meta = await getBgMeta();
if (!meta.queue.length) return;
const now = Date.now();
const fresh = [];
let evicted = 0;
let cache;
try { cache = await caches.open(BG_CACHE_NAME); } catch { return; }
for (const entry of meta.queue) {
if (!entry.cachedAt || (now - entry.cachedAt) > BG_STALE_MS) {
try { await cache.delete(bgCacheKey(entry.assetId)); } catch {}
evicted++;
} else {
fresh.push(entry);
}
}
if (evicted > 0) {
meta.queue = fresh;
await setBgMeta(meta);
}
}
// Tracks whether we've painted at least one background. The first paint
// of the page goes straight to opacity:1 with no fade — fade-in adds 600ms
// of perceived load time, which makes the new tab feel slow even when
// the image came from cache. Auto-rotate cycles still get the fade
// because there it's actually a nice transition between two visible
// photos rather than from blank → photo.
let _firstPaintDone = false;
// Renders the asset's preview as the new-tab background and populates the
// metadata corner. Shared by both the cached-hit and live-fetch paths.
function renderNewtabBackground(asset, blobUrl, cfg) {
const bg = $("bg");
if (!_firstPaintDone) {
// First paint: instant. Skip the opacity dance entirely.
bg.style.transition = "none";
bg.style.backgroundImage = `url("${blobUrl}")`;
bg.style.opacity = "1";
// Force a reflow before re-enabling transitions so the next rotation
// animates rather than snapping.
void bg.offsetHeight;
bg.style.transition = "";
_firstPaintDone = true;
} else {
// Auto-rotate: keep the smooth fade between visible photos.
bg.style.opacity = "0";
setTimeout(() => {
bg.style.backgroundImage = `url("${blobUrl}")`;
bg.style.opacity = "1";
}, 50);
}
const exif = asset.exifInfo || {};
const date = exif.dateTimeOriginal || asset.fileCreatedAt;
// Include the state/region so e.g. "Boulder, Colorado, United States"
// renders instead of "Boulder, United States". Immich populates this
// from EXIF GPS reverse-geocoding into exifInfo.state.
const place = [exif.city, exif.state, exif.country].filter(Boolean).join(", ");
const meta = $("meta");
meta.replaceChildren();
const dateEl = document.createElement("div");
dateEl.textContent = fmtDate(new Date());
dateEl.style.fontWeight = "500";
meta.appendChild(dateEl);
if (date || place) {
const sub = document.createElement("div");
const parts = [];
if (date) parts.push(new Date(date).toLocaleDateString());
if (place) parts.push(place);
sub.textContent = parts.join(" · ");
sub.style.opacity = "0.85";
meta.appendChild(sub);
}
if (cfg.newtabShowMetadata !== false) {
const lines = buildExifLines(exif);
for (const line of lines) {
const el = document.createElement("div");
el.className = "meta-detail";
el.textContent = line;
meta.appendChild(el);
}
}
const link = document.createElement("a");
link.href = viewUrl(cfg.serverUrl, asset.id);
link.textContent = "Open in Immich →";
link.target = "_blank";
link.rel = "noopener";
meta.appendChild(link);
}
async function pickAndRender(cfg) {
// Cached path — instant, no network involved at all.
const cached = await consumeCachedBg();
if (cached) {
const blobUrl = URL.createObjectURL(cached.blob);
renderNewtabBackground(cached.asset, blobUrl, cfg);
// Refill the cache for the next new-tab open. Fire-and-forget so we
// don't block the displayed page.
requestPrecacheTopUp();
return;
}
// Cache miss — fall back to the original live-fetch path.
const items = await randomAssets({
count: 1,
albumId: cfg.newtabAlbumId || "",
favoritesOnly: cfg.newtabFavoritesOnly === true,
});
const asset = Array.isArray(items) ? items[0] : items?.assets?.items?.[0];
if (!asset) {
if (cfg.newtabFavoritesOnly) {
showToast("No favorites match — try unfavoriting fewer photos or turning off the favorites filter.", {
label: "Open settings",
onClick: () => chrome.runtime.openOptionsPage(),
});
} else if (cfg.newtabAlbumId) {
showToast("Selected album has no photos.", {
label: "Change album",
onClick: () => chrome.runtime.openOptionsPage(),
});
}
return;
}
// /search/random is lightweight — Immich often returns a thin asset
// record without exifInfo. Fetch the full asset detail so the photo
// metadata block in the corner has something to show.
if (cfg.newtabShowMetadata !== false) {
const exif = asset.exifInfo;
const sparse = !exif || Object.keys(exif).length === 0 ||
(!exif.make && !exif.model && !exif.iso && !exif.fNumber);
if (sparse) {
try {
const detail = await fetchAssetDetail(cfg, asset.id);
if (detail) Object.assign(asset, detail);
} catch {}
}
}
const url = await loadThumbViaBg(asset.id, "preview");
renderNewtabBackground(asset, url, cfg);
// Pre-cache for next time even on the cache-miss path. After a cold
// start, every subsequent new tab is instant.
requestPrecacheTopUp();
}
async function fetchAssetDetail(cfg, assetId) {
const res = await fetch(`${cfg.serverUrl}/api/assets/${assetId}`, {
headers: { "x-api-key": cfg.apiKey },
});
if (!res.ok) return null;
return res.json();
}
function buildExifLines(exif) {
const lines = [];
// Camera + lens
const cam = [exif.make, exif.model].filter(Boolean).join(" ").trim();
if (cam) lines.push(cam);
if (exif.lensModel && exif.lensModel !== cam) lines.push(exif.lensModel);
// Exposure
const settings = [];
if (exif.iso) settings.push(`ISO ${exif.iso}`);
if (exif.fNumber) settings.push(`f/${exif.fNumber}`);
if (exif.exposureTime) settings.push(`${exif.exposureTime}s`);
if (exif.focalLength) settings.push(`${Math.round(exif.focalLength)}mm`);
if (settings.length) lines.push(settings.join(" · "));
// Dimensions + file size
const dimsParts = [];
if (exif.exifImageWidth && exif.exifImageHeight) {
dimsParts.push(`${exif.exifImageWidth} × ${exif.exifImageHeight}`);
} else if (exif.imageWidth && exif.imageHeight) {
dimsParts.push(`${exif.imageWidth} × ${exif.imageHeight}`);
}
if (exif.fileSizeInByte) dimsParts.push(formatBytes(exif.fileSizeInByte));
if (dimsParts.length) lines.push(dimsParts.join(" · "));
return lines;
}
function formatBytes(n) {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`;
return `${(n / 1024 / 1024 / 1024).toFixed(2)} GB`;
}
// Same heuristic as the popup: timeouts, generic network errors, 5xx server
// responses. Triggers the dedicated overlay instead of a tiny pill toast.
function isConnectionError(e) {
if (!e) return false;
if (e.name === "AbortError") return true;
if (e instanceof TypeError) return true;
const m = e.message || "";
if (/timed out|unreachable/i.test(m)) return true;
if (/Failed to fetch|NetworkError|net::ERR_/i.test(m)) return true;
if (/failed: 5\d\d/.test(m)) return true;
return false;
}
function showConnectionErrorOverlay(cfg, error) {
const overlay = $("connError");
if (!overlay) return;
$("connErrorDetail").textContent = error?.message || "Unknown error.";
let host = "";
try { if (cfg?.serverUrl) host = new URL(cfg.serverUrl).host; } catch {}
$("connErrorHost").textContent = host;
$("connErrorHost").hidden = !host;
overlay.hidden = false;
}
function hideConnectionErrorOverlay() {
const overlay = $("connError");
if (overlay) overlay.hidden = true;
}
async function loadBackground(cfg) {
try {
await pickAndRender(cfg);
hideConnectionErrorOverlay();
} catch (e) {
if (isConnectionError(e)) {
showConnectionErrorOverlay(cfg, e);
} else {
showToast(`Background failed: ${e.message}`, {
label: "Settings",
onClick: () => chrome.runtime.openOptionsPage(),
});
}
}
if (cfg.newtabRotateSeconds && cfg.newtabRotateSeconds > 0) {
clearInterval(rotateTimer);
rotateTimer = setInterval(() => {
pickAndRender(cfg)
.then(hideConnectionErrorOverlay)
.catch((e) => {
if (isConnectionError(e)) showConnectionErrorOverlay(cfg, e);
});
}, cfg.newtabRotateSeconds * 1000);
}
}
async function loadOnThisDayStrip(cfg) {
try {
const groups = await onThisDay(new Date(), cfg.newtabAlbumId || "", cfg.newtabFavoritesOnly === true);
if (!groups.length) return;
const strip = $("otd-strip");
strip.replaceChildren();
let count = 0;
for (const g of groups) {
const yearsAgo = new Date().getFullYear() - g.year;
for (const a of g.items.slice(0, 6)) {
if (count++ > 30) break;
const link = document.createElement("a");
link.href = viewUrl(cfg.serverUrl, a.id);
link.target = "_blank";
link.rel = "noopener";
link.title = `${yearsAgo} year${yearsAgo === 1 ? "" : "s"} ago`;
const img = document.createElement("img");
img.alt = "";
img.loading = "lazy";
const badge = document.createElement("div");
badge.className = "badge";
badge.textContent = `${yearsAgo}y`;
link.appendChild(img);
link.appendChild(badge);
strip.appendChild(link);
loadThumbViaBg(a.id, "thumbnail").then((u) => (img.src = u)).catch(() => {});
}
}
if (strip.children.length) $("otd").hidden = false;
} catch {
// silent
}
}
function renderMinimal(cfg) {
// If the user set an explicit fallback URL, honor it. Otherwise show
// the minimal clock-only page. Browsers don't let an extension that
// declares chrome_url_overrides.newtab release the new tab back to the
// browser without being uninstalled — there's nothing we can do about
// that from inside the extension. The Settings page now spells this
// out in the toggle's description so the limitation is visible.
if (cfg.newtabFallbackUrl) {
location.replace(cfg.newtabFallbackUrl);
return;
}
document.body.classList.add("minimal");
}
function diagRow(parent, label, status, detail) {
const r = document.createElement("div");
r.className = "diag-row";
const tag = document.createElement("span");
tag.className = `tag ${status}`;
tag.textContent = status === "ok" ? "✓" : status === "err" ? "✗" : "·";
const lbl = document.createElement("strong");
lbl.textContent = label;
const det = document.createElement("span");
det.className = "detail";
det.textContent = " " + (detail || "");
r.appendChild(tag);
r.appendChild(lbl);
r.appendChild(det);
parent.appendChild(r);
return r;
}
async function showSetupOverlay(reason) {
$("setup").hidden = false;
const diag = $("diag");
diag.replaceChildren();
// Always show a build marker so the user can confirm they're on the latest code.
const marker = document.createElement("div");
marker.className = "diag-marker";
marker.textContent = `build: ${VERSION_TAG} · loaded ${new Date().toLocaleTimeString()}`;
diag.appendChild(marker);
// Anything below this line might fail; protect it.
try {
diagRow(diag, "reason", "err", reason);
let raw = {};
let cfg = {};
try {
raw = await chrome.storage.sync.get(null);
} catch (e) {
diagRow(diag, "storage.sync.get", "err", e.message);
}
try {
cfg = await getConfig();
} catch (e) {
diagRow(diag, "getConfig", "err", e.message);
}
const sUrl = (cfg.serverUrl || raw.serverUrl || "").trim();
const sKey = (cfg.apiKey || raw.apiKey || "").trim();
diagRow(diag, "serverUrl", sUrl ? "ok" : "err", sUrl || "(empty)");
diagRow(
diag,
"apiKey",
sKey ? "ok" : "err",
sKey ? `${sKey.slice(0, 4)}…${sKey.slice(-4)} (${sKey.length} chars)` : "(empty)",
);
diagRow(
diag,
"sync keys",
Object.keys(raw).length ? "ok" : "err",
Object.keys(raw).join(", ") || "(none)",
);
// Also peek at storage.local in case Chrome sync is paused/disabled.
try {
const local = await chrome.storage.local.get(null);
diagRow(
diag,
"local keys",
"",
Object.keys(local).join(", ") || "(none)",
);
} catch {}
if (sUrl && sKey) {
try {
await ping();
diagRow(diag, "ping", "ok", "200 — reloading…");
setTimeout(() => location.reload(), 600);
} catch (e) {
diagRow(diag, "ping", "err", e.message);
}
}
} catch (e) {
const r = document.createElement("div");
r.className = "diag-row";
r.style.color = "#ff6b6b";
r.textContent = `diag crash: ${e.message}`;
diag.appendChild(r);
}
}
async function init() {
let cfg;
try {
cfg = await getConfig();
} catch (e) {
return showSetupOverlay(`getConfig threw: ${e.message}`);
}
if (cfg.theme === "dark" || cfg.theme === "light") {
document.documentElement.setAttribute("data-theme", cfg.theme);
}
if (cfg.featureNewtab === false) {
renderMinimal(cfg);
return;
}
if (!isConfigured(cfg)) {
await showSetupOverlay(
!cfg.serverUrl && !cfg.apiKey
? "Server URL and API key are both empty in chrome.storage.sync."
: !cfg.serverUrl
? "Server URL is empty."
: "API key is empty.",
);
return;
}
// Prune any cached entries older than 24h before the rest of the
// pipeline runs. Cheap (a single chrome.storage read + a Cache.delete
// per stale entry) and only writes if anything actually evicted.
evictStaleBg().catch(() => {});
const tasks = [];
if (cfg.newtabBackground !== false) tasks.push(loadBackground(cfg));
if (cfg.newtabOnThisDay !== false) tasks.push(loadOnThisDayStrip(cfg));
await Promise.all(tasks);
}
$("openSettings").addEventListener("click", () => chrome.runtime.openOptionsPage());
$("recheck").addEventListener("click", () => location.reload());
// Connection-error overlay actions
$("connErrorRetry")?.addEventListener("click", () => {
hideConnectionErrorOverlay();
location.reload();
});
$("connErrorSettings")?.addEventListener("click", () => chrome.runtime.openOptionsPage());
chrome.storage.onChanged.addListener((_changes, area) => {
if (area !== "sync") return;
location.reload();
});
init().catch((e) => {
console.error("[immich-companion] init failed:", e);
showSetupOverlay(`init crashed: ${e.message}`).catch(() => {});
});