-
Notifications
You must be signed in to change notification settings - Fork 569
Expand file tree
/
Copy pathApp.jsx
More file actions
1257 lines (1175 loc) · 43.7 KB
/
Copy pathApp.jsx
File metadata and controls
1257 lines (1175 loc) · 43.7 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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
useState,
useEffect,
useCallback,
useMemo,
useRef,
lazy,
Suspense,
} from "react";
import ErrorBoundary from "./components/ErrorBoundary";
import KeyboardShortcutsModal from "./components/KeyboardShortcutsModal";
import WindowTitlebar from "./components/WindowTitlebar";
import { storage, secureStorage, STORAGE_KEYS } from "./utils/storage";
import { applyAccentColor } from "./utils/appearance";
import { collectBackupData } from "./utils/backup";
import { tmdbFetch, setApiErrorHandlers } from "./utils/api";
import { clearAppCaches } from "./utils/storage";
import Sidebar from "./components/Sidebar";
import SearchModal from "./components/SearchModal";
import SetupScreen from "./components/SetupScreen";
import CloseConfirmModal from "./components/CloseConfirmModal";
import UpdateModal from "./components/UpdateModal";
// Lazy-loaded pages: each chunk is only downloaded when the user first visits
const HomePage = lazy(() => import("./pages/HomePage"));
const MoviePage = lazy(() => import("./pages/MoviePage"));
const TVPage = lazy(() => import("./pages/TVPage"));
const LibraryPage = lazy(() => import("./pages/LibraryPage"));
const SettingsPage = lazy(() => import("./pages/SettingsPage"));
const DownloadsPage = lazy(() => import("./pages/DownloadsPage"));
import { checkForUpdates } from "./utils/updates";
export default function App() {
// apiKey loaded async from secure storage (OS keychain)
const [apiKey, setApiKey] = useState(null);
const [apiKeyLoaded, setApiKeyLoaded] = useState(false);
const [skipped, setSkipped] = useState(false);
const [apiKeyStatus, setApiKeyStatus] = useState("checking"); // 'checking' | 'ok' | 'invalid_token' | 'unreachable'
const [page, setPage] = useState(() => storage.get("startPage") || "home");
const [selected, setSelected] = useState(null);
const [showSearch, setShowSearch] = useState(false);
const [librarySort, setLibrarySort] = useState(
() => storage.get(STORAGE_KEYS.LIBRARY_SORT) || "manual",
);
const [showShortcuts, setShowShortcuts] = useState(false);
const [platform, setPlatform] = useState(null);
// Navigation history stack for Ctrl+Z back navigation
const [navStack, setNavStack] = useState([]);
const [saved, setSaved] = useState(() => storage.get("saved") || {});
// Separate order array for drag-and-drop reordering
const [savedOrder, setSavedOrder] = useState(
() => storage.get("savedOrder") || null,
);
const [progress, setProgress] = useState(() => storage.get("progress") || {});
const [history, setHistory] = useState(() => storage.get("history") || []);
const [watched, setWatched] = useState(() => storage.get("watched") || {});
const [toast, setToast] = useState(null);
const [updateBanner, setUpdateBanner] = useState(null);
const [showUpdateModal, setShowUpdateModal] = useState(false);
// null | "checking" | { entries: object[] } | "none"
const [episodeCheckStatus, setEpisodeCheckStatus] = useState(null);
const episodeDismissTimerRef = useRef(null);
const [trending, setTrending] = useState([]);
const [trendingTV, setTrendingTV] = useState([]);
const [loadingHome, setLoadingHome] = useState(false);
const [offline, setOffline] = useState(() => !navigator.onLine);
// ── Scheduled backup: run on startup if due ─────────────────────────────────
useEffect(() => {
if (!window.electron?.onScheduledBackupRequested) return;
const handler = window.electron.onScheduledBackupRequested(async () => {
try {
const settings = await window.electron.getScheduledBackupSettings();
if (!settings?.enabled || !settings?.path) return;
const data = collectBackupData();
await window.electron.performScheduledBackup({ data, settings });
} catch {
// silently ignore errors on scheduled backup
}
});
return () => window.electron.offScheduledBackupRequested(handler);
}, []);
// ── Post-update cache flush ───────────────────────────────────────────────
// On every start, compare the running version against the last-seen version.
// If they differ the app was just updated -> clear all caches to prevent problems
useEffect(() => {
if (!window.electron?.getAppVersion) return;
window.electron.getAppVersion().then((version) => {
const lastVersion = localStorage.getItem("streambert_lastVersion");
if (lastVersion && lastVersion !== version) {
clearAppCaches();
}
localStorage.setItem("streambert_lastVersion", version);
});
}, []);
// ── Startup update check ─────────────────────────────────────────────────
useEffect(() => {
if (!storage.get("autoCheckUpdates")) return;
checkForUpdates()
.then((r) => {
if (r.hasUpdate) setUpdateBanner(r);
})
.catch(() => {}); // silently ignore network errors on startup
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// ── Startup: new-episode notification check ──────────────────────────────
// Only runs once the API key has been loaded from secure storage (i.e. the
// app is fully started and past the setup screen). Shows an in-app status
// pill while checking, then either a result card or a brief "nothing new" message.
useEffect(() => {
if (!apiKeyLoaded) return;
const notifyPref = storage.get(STORAGE_KEYS.NOTIFY_NEW_EPISODE);
if (notifyPref === false || notifyPref === 0) return;
let cancelled = false;
async function checkNewEpisodes() {
// Small grace period so the UI has fully painted before we start
await new Promise((r) => setTimeout(r, 1200));
if (cancelled) return;
if (!apiKey || cancelled) return;
const tvSeries = Object.values(saved).filter(
(item) => item && item.media_type === "tv" && item.id,
);
if (!tvSeries.length) return;
// Only re-check entries older than 12 h
const cache = storage.get(STORAGE_KEYS.EPISODE_RELEASE_CACHE) || {};
const now = Date.now();
const CACHE_TTL = 12 * 60 * 60 * 1000;
const toCheck = tvSeries.filter(
(s) => !cache[s.id] || now - (cache[s.id].checkedAt || 0) > CACHE_TTL,
);
if (!toCheck.length) {
setEpisodeCheckStatus("none");
episodeDismissTimerRef.current = setTimeout(() => {
if (!cancelled) setEpisodeCheckStatus(null);
}, 2000);
return;
}
// Only show loading pill when there's actually something to check
setEpisodeCheckStatus("checking");
const BATCH = 3;
// Each entry: { title, season, id, seriesItem }
const newEpisodeEntries = [];
for (let i = 0; i < toCheck.length && !cancelled; i += BATCH) {
const batch = toCheck.slice(i, i + BATCH);
await Promise.all(
batch.map(async (series) => {
try {
const data = await tmdbFetch(`/tv/${series.id}`, apiKey);
if (cancelled) return;
const prev = cache[series.id] || {};
const lastEp = data.last_episode_to_air;
const lastDate = lastEp?.air_date || null;
const isFirstCheck = !prev.checkedAt;
// Parse air_date strings as local midnight to avoid UTC offset issues
const parseLocalDate = (d) => {
if (!d) return null;
const [y, m, day] = d.split("-").map(Number);
return new Date(y, m - 1, day);
};
const todayLocal = new Date();
todayLocal.setHours(0, 0, 0, 0);
const sevenDaysAgo = new Date(todayLocal);
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
if (isFirstCheck) {
// First time: notify if latest episode aired in last 7 days
const lastParsed = parseLocalDate(lastDate);
if (lastParsed && lastParsed >= sevenDaysAgo) {
newEpisodeEntries.push({
title:
series.title ||
series.name ||
data.name ||
"Unknown series",
season: lastEp?.season_number ?? null,
id: series.id,
seriesItem: series,
});
}
} else {
// Subsequent checks: notify when last_episode_to_air changed
// (new episode aired) compared to what we cached.
// Migration: old cache entries only have nextEpDate, not lastEpDate.
// In that case treat as first check to avoid false positives.
const prevLastDate = prev.lastEpDate ?? null;
const isMigratingOldCache =
prev.checkedAt && prevLastDate === null;
if (isMigratingOldCache) {
// Just update the cache with lastEpDat
} else {
const lastParsed = parseLocalDate(lastDate);
const prevParsed = parseLocalDate(prevLastDate);
const isNewEpisode =
lastDate &&
lastDate !== prevLastDate &&
lastParsed &&
lastParsed >= sevenDaysAgo &&
(!prevParsed || lastParsed > prevParsed);
if (isNewEpisode) {
newEpisodeEntries.push({
title:
series.title ||
series.name ||
data.name ||
"Unknown series",
season: lastEp?.season_number ?? null,
id: series.id,
seriesItem: series,
});
}
}
}
cache[series.id] = {
lastEpDate: lastDate,
// keep nextEpDate for reference but don't use it for detection
nextEpDate: data.next_episode_to_air?.air_date || null,
checkedAt: now,
};
} catch {}
}),
);
if (i + BATCH < toCheck.length && !cancelled) {
await new Promise((r) => setTimeout(r, 400));
}
}
if (cancelled) return;
storage.set(STORAGE_KEYS.EPISODE_RELEASE_CACHE, cache);
if (newEpisodeEntries.length === 0) {
setEpisodeCheckStatus("none");
// Auto-dismiss after 2 s
episodeDismissTimerRef.current = setTimeout(() => {
if (!cancelled) setEpisodeCheckStatus(null);
}, 2000);
return;
}
// Show in-app result card
setEpisodeCheckStatus({ entries: newEpisodeEntries });
// Also fire OS notification
if (window.electron?.showNotification) {
const names = newEpisodeEntries.map((e) => e.title);
const body =
names.length === 1
? `${names[0]} has a new episode.`
: `${names.slice(0, 3).join(", ")}${
names.length > 3 ? ` and ${names.length - 3} more` : ""
} have new episodes.`;
window.electron.showNotification({
title: "New episodes available",
body,
silent: false,
});
}
}
checkNewEpisodes().catch(() => {
if (!cancelled) setEpisodeCheckStatus(null);
});
return () => {
cancelled = true;
clearTimeout(episodeDismissTimerRef.current);
};
}, [apiKeyLoaded]);
// ── Downloads state ──────────────────────────────────────────────────────
const [downloads, setDownloads] = useState([]);
const [highlightDownload, setHighlightDownload] = useState(null);
const [closeConfirm, setCloseConfirm] = useState(null); // { count }
// ── Load API key from secure storage on startup ──
useEffect(() => {
let mounted = true;
secureStorage.get("apikey").then((val) => {
if (!mounted) return;
setApiKey(val || null);
setApiKeyLoaded(true);
});
return () => {
mounted = false;
};
}, []);
// ── Detect platform for Windows titlebar ──────────────────────────────────
useEffect(() => {
if (!window.electron?.getPlatform) return;
let mounted = true;
window.electron.getPlatform().then((p) => {
if (!mounted) return;
setPlatform(p);
if (p === "win32" || p === "linux") {
document.documentElement.setAttribute("data-win-titlebar", "1");
}
});
return () => {
mounted = false;
};
}, []);
// Listen for close confirmation request from main process
useEffect(() => {
if (!window.electron) return;
const handler = window.electron.onConfirmClose((data) =>
setCloseConfirm(data),
);
return () => window.electron.offConfirmClose(handler);
}, []);
// ── Register global API error handlers ──────────────────────────────────
// Fire on any tmdbFetch call that returns 401/403 or network failure
useEffect(() => {
setApiErrorHandlers(
() => setApiKeyStatus("invalid_token"), // 401 / 403
() => setApiKeyStatus("unreachable"), // network failure
);
}, []);
// ── Validate stored API key on startup ───────────────────────────────────
useEffect(() => {
if (!apiKey) {
setApiKeyStatus("ok");
return;
}
setApiKeyStatus("checking");
const controller = new AbortController();
fetch("https://api.themoviedb.org/3/configuration", {
headers: { Authorization: `Bearer ${apiKey}` },
signal: controller.signal,
})
.then((res) => {
if (res.status === 401 || res.status === 403)
setApiKeyStatus("invalid_token");
else setApiKeyStatus("ok");
})
.catch((err) => {
if (err.name === "AbortError") return;
setApiKeyStatus("unreachable");
});
return () => controller.abort();
}, [apiKey]);
// Load persisted downloads on startup + immediately prune missing files
useEffect(() => {
if (!window.electron) return;
let mounted = true;
window.electron.getDownloads().then(async (list) => {
if (!mounted || !Array.isArray(list)) return;
const pruned = [...list];
const toRemove = new Set();
await Promise.all(
pruned.map(async (d) => {
if (d.status !== "completed" || !d.filePath) return;
const exists = await window.electron.fileExists(d.filePath);
if (!exists) {
// File gone, remove from registry silently
window.electron.deleteDownload({ id: d.id, filePath: null });
toRemove.add(d.id);
return;
}
// Prune subtitle paths that no longer exist
if (
d.subtitlePaths?.length > 0 &&
window.electron.pruneSubtitlePaths
) {
const res = await window.electron.pruneSubtitlePaths(d.id);
if (res?.ok) d.subtitlePaths = res.subtitlePaths;
}
}),
);
if (mounted) setDownloads(pruned.filter((d) => !toRemove.has(d.id)));
});
return () => {
mounted = false;
};
}, []);
// Listen for live progress events from main process
useEffect(() => {
if (!window.electron) return;
const handler = window.electron.onDownloadProgress((update) => {
// ── Desktop notification ──────────────────────
if (
update.status === "completed" &&
storage.get(STORAGE_KEYS.NOTIFY_DOWNLOAD_COMPLETE) !== false &&
window.electron.showNotification
) {
window.electron.showNotification({
title: "Download complete",
body: update.name || "Your download has finished.",
silent: false,
});
}
setDownloads((prev) => {
const idx = prev.findIndex((d) => d.id === update.id);
if (idx === -1) {
// Unknown id: either the entry was deleted (stale event after SIGKILL)
// or a genuine race on first event.
if (!update.name) return prev;
return [update, ...prev];
}
const updated = [...prev];
updated[idx] = { ...updated[idx], ...update };
return updated;
});
});
return () => window.electron.offDownloadProgress(handler);
}, []);
const handleDownloadStarted = useCallback((newEntry) => {
setDownloads((prev) => {
// Guard: if a progress event already added this id (race), just update it
const idx = prev.findIndex((d) => d.id === newEntry.id);
if (idx !== -1) {
const updated = [...prev];
updated[idx] = { ...updated[idx], ...newEntry };
return updated;
}
return [newEntry, ...prev];
});
}, []);
const handleDeleteDownload = useCallback((id) => {
setDownloads((prev) => prev.filter((d) => d.id !== id));
}, []);
// Active download count for sidebar badge
const activeDownloadCount = useMemo(
() => downloads.filter((d) => d.status === "downloading").length,
[downloads],
);
// ── Trending, single shared fetch fn avoids code duplication ────────────
// Results are cached in localStorage for 30 min to avoid redundant API calls
// and to keep trending data out of RAM between restarts.
const fetchTrending = useCallback(() => {
if (!apiKey) return;
const cached = storage.get("trendingCache");
const CACHE_TTL = 30 * 60 * 1000; // 30 minutes
if (cached && cached.ts && Date.now() - cached.ts < CACHE_TTL) {
setTrending(cached.movies || []);
setTrendingTV(cached.tv || []);
return;
}
setLoadingHome(true);
Promise.all([
tmdbFetch("/trending/movie/week", apiKey),
tmdbFetch("/trending/tv/week", apiKey),
])
.then(([m, t]) => {
const movies = m.results || [];
const tv = t.results || [];
setTrending(movies);
setTrendingTV(tv);
storage.set("trendingCache", { movies, tv, ts: Date.now() });
})
.catch(() => {})
.finally(() => setLoadingHome(false));
}, [apiKey]);
useEffect(() => {
fetchTrending();
}, [fetchTrending]);
const retryHome = useCallback(() => {
if (offline) return;
fetchTrending();
}, [offline, fetchTrending]);
// ── Sync librarySort when changed from Settings ───────────────────────────
useEffect(() => {
const handler = (e) => setLibrarySort(e.detail);
window.addEventListener("streambert:library-sort-changed", handler);
return () =>
window.removeEventListener("streambert:library-sort-changed", handler);
}, []);
useEffect(() => {
// Accent colour
const accent = storage.get(STORAGE_KEYS.ACCENT_COLOR) || "red";
applyAccentColor(accent);
// Font size
const font = storage.get(STORAGE_KEYS.FONT_SIZE) || "normal";
const zoomMap = { sm: 0.85, normal: 1, lg: 1.15 };
const factor = zoomMap[font] ?? 1;
if (window.electron?.setZoomFactor) window.electron.setZoomFactor(factor);
// Compact mode
const compact = !!storage.get(STORAGE_KEYS.COMPACT_MODE);
document.body.classList.toggle("compact-mode", compact);
// Reduce animations
const noAnim = !!storage.get(STORAGE_KEYS.REDUCE_ANIMATIONS);
document.body.classList.toggle("no-anim", noAnim);
}, []);
useEffect(() => {
const goOnline = () => setOffline(false);
const goOffline = () => setOffline(true);
window.addEventListener("online", goOnline);
window.addEventListener("offline", goOffline);
return () => {
window.removeEventListener("online", goOnline);
window.removeEventListener("offline", goOffline);
};
}, []);
// ── Navigation ────────────────────────────────────────────────────────────
// Refs so navigate/navigateBack never need page/selected as deps
const pageRef = useRef(page);
const selectedRef = useRef(selected);
useEffect(() => {
pageRef.current = page;
}, [page]);
useEffect(() => {
selectedRef.current = selected;
}, [selected]);
const navigateBack = useCallback(() => {
setNavStack((prev) => {
if (prev.length === 0) return prev;
const last = prev[prev.length - 1];
setPage(last.page);
setSelected(last.selected);
if (typeof gc === "function") {
requestIdleCallback(() => gc(), { timeout: 2000 });
}
return prev.slice(0, -1);
});
}, []);
const navigate = useCallback((pg, data = null) => {
setNavStack((prev) => [
...prev,
{ page: pageRef.current, selected: selectedRef.current },
]);
setSelected(data);
setPage(pg);
setShowSearch(false);
// After navigating away, the previous page's component unmounts
if (typeof gc === "function") {
requestIdleCallback(() => gc(), { timeout: 2000 });
}
}, []);
// ── Keyboard shortcuts ────────────────────────────────────────────────────
useEffect(() => {
const handler = (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === "f") {
e.preventDefault();
setShowSearch(true);
}
if (e.key === "Escape") {
setShowSearch(false);
setShowShortcuts(false);
}
if (e.key === "?" && !e.ctrlKey && !e.metaKey) {
const tag = (e.target?.tagName || "").toUpperCase();
if (tag !== "INPUT" && tag !== "TEXTAREA") {
e.preventDefault();
setShowShortcuts((v) => !v);
}
}
// Ctrl+Z / Cmd+Z → navigate back
if ((e.metaKey || e.ctrlKey) && e.key === "z" && !e.shiftKey) {
e.preventDefault();
navigateBack();
}
if ((e.metaKey || e.ctrlKey) && e.key === "r") {
e.preventDefault();
window.location.reload();
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [navigateBack]);
// ── Helpers ───────────────────────────────────────────────────────────────
const toastTimerRef = useRef(null);
const showToast = useCallback((msg) => {
if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
setToast(msg);
toastTimerRef.current = setTimeout(() => setToast(null), 2500);
}, []);
const getMediaType = useCallback(
(item) => item.media_type || (item.first_air_date ? "tv" : "movie"),
[],
);
const handleSelectResult = useCallback(
(item) => {
navigate(item.media_type === "tv" ? "tv" : "movie", item);
},
[navigate],
);
const saveApiKey = useCallback((key) => {
secureStorage.set("apikey", key);
setApiKey(key);
}, []);
const changeApiKey = useCallback(() => {
secureStorage.set("apikey", "");
setApiKey(null);
setApiKeyLoaded(true);
setSkipped(false);
}, []);
// Ref so toggleSave never needs `saved` as a dep (avoids recreation on every save)
const savedRef = useRef(saved);
useEffect(() => {
savedRef.current = saved;
}, [saved]);
const toggleSave = useCallback(
(item) => {
const mt = getMediaType(item);
const id = `${mt}_${item.id}`;
const currentSaved = savedRef.current;
const isRemoving = !!currentSaved[id];
const next = { ...currentSaved };
if (isRemoving) {
delete next[id];
showToast("Removed from watchlist");
setSavedOrder((prev) => {
const currentOrder = prev || Object.keys(currentSaved);
const newOrder = currentOrder.filter((k) => k !== id);
storage.set("savedOrder", newOrder);
return newOrder;
});
} else {
next[id] = {
id: item.id,
title: item.title || item.name,
poster_path: item.poster_path,
media_type: mt,
vote_average: item.vote_average,
year: (item.release_date || item.first_air_date || "").slice(0, 4),
};
showToast("Added to watchlist");
setSavedOrder((prev) => {
const currentOrder = prev || Object.keys(currentSaved);
const newOrder = [...currentOrder, id];
storage.set("savedOrder", newOrder);
return newOrder;
});
}
setSaved(next);
storage.set("saved", next);
},
[showToast, getMediaType],
);
const isSaved = useCallback(
(item) => {
const id = `${getMediaType(item)}_${item.id}`;
return !!saved[id];
},
[saved, getMediaType],
);
const addHistory = useCallback((item) => {
// Respect the "disable watch history" setting
const historyEnabled = storage.get(STORAGE_KEYS.HISTORY_ENABLED);
if (historyEnabled === 0 || historyEnabled === false) return;
const entry = {
id: item.id,
title: item.title || item.name,
poster_path: item.poster_path,
media_type: getMediaType(item),
watchedAt: Date.now(),
// Store as numbers so the progress key always matches exactly
season: item.season != null ? Number(item.season) : null,
episode: item.episode != null ? Number(item.episode) : null,
episodeName: item.episodeName || null,
};
// Functional update - never reads stale history from closure
setHistory((prev) => {
const filtered = prev.filter(
(h) => !(h.id === entry.id && h.media_type === entry.media_type),
);
const next = [entry, ...filtered].slice(0, 50);
storage.set("history", next);
return next;
});
}, []); // no deps needed
const saveProgress = useCallback((key, pct) => {
// Functional update - without this, TVPage's setInterval keeps spreading
// the progress object from when the interval was created, overwriting
// saves from other episodes (classic stale closure bug).
setProgress((prev) => {
if (prev[key] === pct) return prev; // no change - skip write
const next = { ...prev, [key]: pct };
storage.set("progress", next);
return next;
});
}, []); // no deps needed
const markWatched = useCallback((key) => {
setWatched((prev) => {
const next = { ...prev, [key]: true };
storage.set("watched", next);
return next;
});
}, []);
const markUnwatched = useCallback((key) => {
setWatched((prev) => {
const next = { ...prev };
delete next[key];
storage.set("watched", next);
return next;
});
}, []);
// Memoized, avoids re-filtering on every download-progress event
// Pre-compute progress keys for history items once; only re-runs when history changes.
const historyWithKeys = useMemo(
() =>
history
.filter((h) => {
if (h.media_type === "tv" && (h.season == null || h.episode == null))
return false;
return true;
})
.map((h) => ({
...h,
_pk:
h.media_type === "movie"
? `movie_${h.id}`
: `tv_${h.id}_s${h.season}e${h.episode}`,
})),
[history],
);
// Filter by progress/watched
const inProgress = useMemo(
() =>
historyWithKeys.filter((h) => {
if (watched[h._pk]) return false;
const pct = progress[h._pk];
return pct != null && pct > 2 && pct < 98;
}),
[historyWithKeys, progress, watched],
);
// Memoized, avoids re-mapping on every download-progress event
const savedList = useMemo(() => {
const orderedKeys = savedOrder
? savedOrder.filter((k) => saved[k])
: Object.keys(saved);
const list = orderedKeys.map((k) => saved[k]).filter(Boolean);
if (librarySort === "title")
return [...list].sort((a, b) =>
(a.title || "").localeCompare(b.title || ""),
);
if (librarySort === "rating")
return [...list].sort(
(a, b) => (b.vote_average || 0) - (a.vote_average || 0),
);
if (librarySort === "year")
return [...list].sort((a, b) =>
(b.year || "").localeCompare(a.year || ""),
);
return list;
}, [saved, savedOrder, librarySort]);
const handleReorderSaved = useCallback((newOrder) => {
setSavedOrder(newOrder);
storage.set("savedOrder", newOrder);
}, []);
// Stable handler
const handleGoToDownloads = useCallback(
(id) => {
setHighlightDownload(id || null);
navigate("downloads");
},
[navigate],
);
if (!apiKeyLoaded) return null; // wait for secure storage to resolve
if (!apiKey && !skipped)
return <SetupScreen onSave={saveApiKey} onSkip={() => setSkipped(true)} />;
const hasCustomTitlebar = platform === "win32" || platform === "linux";
return (
<ErrorBoundary>
{hasCustomTitlebar && <WindowTitlebar />}
<div>
<Sidebar
page={page}
onNavigate={navigate}
onSearch={() => setShowSearch(true)}
savedList={savedList}
activeDownloads={activeDownloadCount}
onReorderSaved={handleReorderSaved}
onRemoveSaved={toggleSave}
canGoBack={navStack.length > 0}
onBack={navigateBack}
onShowShortcuts={() => setShowShortcuts(true)}
/>
<div className="main">
{/* ── API key status banner ── */}
{/* Suspense boundary: lazy page chunks are fetched on first visit */}
{apiKeyStatus === "invalid_token" && (
<div className="api-status-banner api-status-error">
<span>
⚠ Your TMDB token is invalid, not set or has been revoked.
Movies and shows won't load.
</span>
<button className="api-status-btn" onClick={changeApiKey}>
Update Token
</button>
</div>
)}
{apiKeyStatus === "unreachable" && (
<div className="api-status-banner api-status-warn">
<span>
⚠ Cannot reach TMDB, check your internet connection. Content may
not load.
</span>
<button
className="api-status-btn"
onClick={() =>
setApiKeyStatus("checking") || window.location.reload()
}
>
Retry
</button>
</div>
)}
<Suspense
fallback={
<div
style={{
color: "var(--text2)",
padding: 48,
textAlign: "center",
fontSize: 15,
}}
>
Laden…
</div>
}
>
{page === "home" && (
<HomePage
trending={trending}
trendingTV={trendingTV}
loading={loadingHome}
onSelect={handleSelectResult}
progress={progress}
inProgress={inProgress}
offline={offline}
onRetry={retryHome}
watched={watched}
onMarkWatched={markWatched}
onMarkUnwatched={markUnwatched}
history={history}
apiKey={apiKey}
/>
)}
{page === "movie" && selected && (
<MoviePage
item={selected}
apiKey={apiKey}
onSave={() => toggleSave(selected)}
isSaved={isSaved(selected)}
onHistory={addHistory}
progress={progress}
saveProgress={saveProgress}
onBack={() => navigate("home")}
onSettings={(section) =>
navigate("settings", { section: section || null })
}
onDownloadStarted={handleDownloadStarted}
watched={watched}
onMarkWatched={markWatched}
onMarkUnwatched={markUnwatched}
downloads={downloads}
onGoToDownloads={handleGoToDownloads}
onSelect={handleSelectResult}
/>
)}
{page === "tv" && selected && (
<TVPage
item={selected}
apiKey={apiKey}
onSave={() => toggleSave(selected)}
isSaved={isSaved(selected)}
onHistory={addHistory}
progress={progress}
saveProgress={saveProgress}
onBack={() => navigate("home")}
onSettings={(section) =>
navigate("settings", { section: section || null })
}
onDownloadStarted={handleDownloadStarted}
watched={watched}
onMarkWatched={markWatched}
onMarkUnwatched={markUnwatched}
downloads={downloads}
onGoToDownloads={handleGoToDownloads}
/>
)}
{page === "history" && (
<LibraryPage
history={history}
inProgress={inProgress}
saved={savedList}
progress={progress}
onSelect={handleSelectResult}
watched={watched}
onMarkWatched={markWatched}
onMarkUnwatched={markUnwatched}
/>
)}
{page === "settings" && (
<SettingsPage
apiKey={apiKey}
onChangeApiKey={changeApiKey}
initialSection={selected?.section}
/>
)}
{page === "downloads" && (
<DownloadsPage
downloads={downloads}
onDeleteDownload={handleDeleteDownload}
onHistory={addHistory}
onSaveProgress={saveProgress}
progress={progress}
watched={watched}
onMarkWatched={markWatched}
onMarkUnwatched={markUnwatched}
highlightId={highlightDownload}
onClearHighlight={() => setHighlightDownload(null)}
onSelect={handleSelectResult}
onSettings={(section) =>
navigate("settings", { section: section || null })
}
onUpdateDownload={(id, updates) =>
setDownloads((prev) =>
prev.map((d) => (d.id === id ? { ...d, ...updates } : d)),
)
}
/>
)}
</Suspense>
</div>
{showSearch && (
<SearchModal
apiKey={apiKey}
onSelect={handleSelectResult}
onClose={() => setShowSearch(false)}
offline={offline}
/>
)}
{updateBanner && (
<div
style={{
position: "fixed",
top: hasCustomTitlebar ? 32 : 0,
left: 0,
right: 0,
zIndex: 9999,
background: "rgba(229,9,20,0.92)",
backdropFilter: "blur(8px)",
display: "flex",