-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathhome-page.svelte
More file actions
475 lines (412 loc) · 12.5 KB
/
Copy pathhome-page.svelte
File metadata and controls
475 lines (412 loc) · 12.5 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
<script lang="ts">
import * as api from '$lib/index';
import ProgressBar from '$lib/components/elements/progress-bar.svelte';
import { slideshowStore } from '$lib/stores/slideshow.store';
import { clientIdentifierStore, authSecretStore, assetBacklogStore, assetHistoryStore, displayingAssetsStore, clearPersistedStore } from '$lib/stores/persist.store';
import { onDestroy, onMount, setContext } from 'svelte';
import OverlayControls from '../elements/overlay-controls.svelte';
import ImageComponent from '../elements/image-component.svelte';
import { configStore } from '$lib/stores/config.store';
import ErrorElement from '../elements/error-element.svelte';
import Clock from '../elements/clock.svelte';
import Appointments from '../elements/appointments.svelte';
import LoadingElement from '../elements/LoadingElement.svelte';
import { page } from '$app/state';
import { ProgressBarLocation, ProgressBarStatus } from '../elements/progress-bar.types';
interface ImagesState {
images: [string, api.AssetResponseDto, api.AlbumResponseDto[]][];
error: boolean;
loaded: boolean;
split: boolean;
hasBday: boolean;
}
api.init();
// TODO: make this configurable?
const PRELOAD_IMAGES = 5;
let assetHistory: api.AssetResponseDto[] = [];
let assetBacklog: api.AssetResponseDto[] = [];
// persist helpers - save to localStorage if enabled
function persistBacklog() {
if ($configStore.clientPersistAssetQueue) {
assetBacklogStore.set(assetBacklog);
}
}
function persistHistory() {
if ($configStore.clientPersistAssetHistory) {
assetHistoryStore.set(assetHistory);
}
}
function persistDisplaying() {
if ($configStore.clientPersistAssetQueue) {
displayingAssetsStore.set(displayingAssets);
}
}
async function showAssets(assets: api.AssetResponseDto[]) {
displayingAssets = assets;
persistDisplaying();
updateImagePromises();
imagesState = await loadImages(assets);
}
let displayingAssets: api.AssetResponseDto[] = $state() as api.AssetResponseDto[];
const { restartProgress, stopProgress, instantTransition } = slideshowStore;
let progressBarStatus: ProgressBarStatus = $state(ProgressBarStatus.Playing);
let progressBar: ProgressBar = $state() as ProgressBar;
let error: boolean = $state(false);
let infoVisible: boolean = $state(false);
let authError: boolean = $state(false);
let errorMessage: string = $state() as string;
let imagesState: ImagesState = $state({
images: [],
error: false,
loaded: false,
split: false,
hasBday: false
});
let imagePromisesDict: Record<
string,
Promise<[string, api.AssetResponseDto, api.AlbumResponseDto[]]>
> = {};
let unsubscribeRestart: () => void;
let unsubscribeStop: () => void;
let cursorVisible = $state(true);
let timeoutId: number;
const clientIdentifier = page.url.searchParams.get('client');
const authsecret = page.url.searchParams.get('authsecret');
if (clientIdentifier && clientIdentifier != $clientIdentifierStore) {
clientIdentifierStore.set(clientIdentifier);
}
if (authsecret && authsecret != $authSecretStore) {
authSecretStore.set(authsecret);
api.init();
}
const hideCursor = () => {
cursorVisible = false;
};
setContext('close', provideClose);
async function provideClose() {
infoVisible = false;
await progressBar.play();
}
const showCursor = () => {
cursorVisible = true;
clearTimeout(timeoutId);
timeoutId = setTimeout(hideCursor, 2000);
};
async function updateImagePromises() {
for (let asset of displayingAssets) {
if (!(asset.id in imagePromisesDict)) {
imagePromisesDict[asset.id] = loadImage(asset);
}
}
for (let i = 0; i < PRELOAD_IMAGES; i++) {
if (i >= assetBacklog.length) {
break;
}
if (!(assetBacklog[i].id in imagePromisesDict)) {
imagePromisesDict[assetBacklog[i].id] = loadImage(assetBacklog[i]);
}
}
// originally just deleted displayingAssets after they were no longer needed
// but this is more bulletproof to edge cases I think
for (let key in imagePromisesDict) {
if (
!(
displayingAssets.find((item) => item.id == key) ||
assetBacklog.find((item) => item.id == key)
)
) {
delete imagePromisesDict[key];
}
}
}
async function loadAssets() {
try {
let assetRequest = await api.getAsset({ clientIdentifier: $clientIdentifierStore });
if (assetRequest.status != 200) {
if (assetRequest.status == 401) {
authError = true;
}
error = true;
return;
}
error = false;
assetBacklog = assetRequest.data;
persistBacklog();
} catch {
error = true;
}
}
const handleDone = async (previous: boolean = false, instant: boolean = false) => {
progressBar.restart(false);
$instantTransition = instant;
if (previous) await getPreviousAssets();
else await getNextAssets();
progressBar.play();
};
async function getNextAssets() {
if (!assetBacklog || assetBacklog.length < 1) {
await loadAssets();
}
if (!error && assetBacklog.length == 0) {
error = true;
errorMessage = 'No assets were found! Check your configuration.';
return;
}
let next: api.AssetResponseDto[];
if (
$configStore.layout?.trim().toLowerCase() == 'splitview' &&
assetBacklog.length > 1 &&
isHorizontal(assetBacklog[0]) &&
isHorizontal(assetBacklog[1])
) {
next = assetBacklog.splice(0, 2);
} else {
next = assetBacklog.splice(0, 1);
}
assetBacklog = [...assetBacklog];
persistBacklog();
if (displayingAssets) {
// Push to History
assetHistory.push(...displayingAssets);
}
// History max 250 Items
if (assetHistory.length > 250) {
assetHistory = assetHistory.splice(assetHistory.length - 250, 250);
}
persistHistory();
await showAssets(next);
}
async function getPreviousAssets() {
if (!assetHistory || assetHistory.length < 1) {
return;
}
let next: api.AssetResponseDto[];
if (
$configStore.layout?.trim().toLowerCase() == 'splitview' &&
assetHistory.length > 1 &&
isHorizontal(assetHistory[assetHistory.length - 1]) &&
isHorizontal(assetHistory[assetHistory.length - 2])
) {
next = assetHistory.splice(assetHistory.length - 2, 2);
} else {
next = assetHistory.splice(assetHistory.length - 1, 1);
}
assetHistory = [...assetHistory];
persistHistory();
// Unshift to Backlog
if (displayingAssets) {
assetBacklog.unshift(...displayingAssets);
}
assetBacklog = [...assetBacklog];
persistBacklog();
await showAssets(next);
}
function isHorizontal(asset: api.AssetResponseDto) {
const isFlipped = (orientation: number) => [5, 6, 7, 8].includes(orientation);
let imageHeight = asset.exifInfo?.exifImageHeight ?? 0;
let imageWidth = asset.exifInfo?.exifImageWidth ?? 0;
if (isFlipped(Number(asset.exifInfo?.orientation ?? 0))) {
[imageHeight, imageWidth] = [imageWidth, imageHeight];
}
return imageHeight > imageWidth; // or imageHeight > imageWidth * 1.25;
}
function hasBirthday(assets: api.AssetResponseDto[]) {
let today = new Date();
let hasBday: boolean = false;
for (let asset of assets) {
for (let person of asset.people ?? new Array()) {
let birthdate = new Date(person.birthDate ?? '');
if (birthdate.getDate() === today.getDate() && birthdate.getMonth() === today.getMonth()) {
hasBday = true;
break;
}
}
if (hasBday) break;
}
return hasBday;
}
async function loadImages(assets: api.AssetResponseDto[]) {
let newImages = [];
try {
for (let asset of assets) {
let img = await imagePromisesDict[asset.id];
newImages.push(img);
}
return {
images: newImages,
error: false,
loaded: true,
split: assets.length == 2,
hasBday: hasBirthday(assets)
};
} catch {
return {
images: [],
error: true,
loaded: false,
split: false,
hasBday: false
};
}
}
async function loadImage(assetResponse: api.AssetResponseDto) {
let req = await api.getImage(assetResponse.id, { clientIdentifier: $clientIdentifierStore });
let album: api.AlbumResponseDto[] | null = null;
if ($configStore.showAlbumName) {
let albumReq = await api.getAlbumInfo(assetResponse.id, {
clientIdentifier: $clientIdentifierStore
});
album = albumReq.data;
}
if (req.status != 200 || ($configStore.showAlbumName && album == null)) {
return ['', assetResponse, []] as [string, api.AssetResponseDto, api.AlbumResponseDto[]];
}
// if the people array is already populated, there is no need to call the API again
if ($configStore.showPeopleDesc && (assetResponse.people ?? []).length == 0) {
let assetInfoRequest = await api.getAssetInfo(assetResponse.id, {
clientIdentifier: $clientIdentifierStore
});
assetResponse.people = assetInfoRequest.data.people;
// assetResponse.exifInfo = assetInfoRequest.data.exifInfo;
}
return [getImageUrl(req.data), assetResponse, album] as [
string,
api.AssetResponseDto,
api.AlbumResponseDto[]
];
}
function getImageUrl(image: Blob) {
return URL.createObjectURL(image);
}
onMount(() => {
window.addEventListener('mousemove', showCursor);
window.addEventListener('click', showCursor);
if ($configStore.primaryColor) {
document.documentElement.style.setProperty('--primary-color', $configStore.primaryColor);
}
if ($configStore.secondaryColor) {
document.documentElement.style.setProperty('--secondary-color', $configStore.secondaryColor);
}
if ($configStore.baseFontSize) {
document.documentElement.style.fontSize = $configStore.baseFontSize;
}
// load or clear persisted asset queue and displaying assets
let restoredDisplaying = false;
if ($configStore.clientPersistAssetQueue) {
const storedBacklog = $assetBacklogStore as api.AssetResponseDto[];
if (storedBacklog && storedBacklog.length > 0) {
assetBacklog = storedBacklog;
}
const storedDisplaying = $displayingAssetsStore as api.AssetResponseDto[];
if (storedDisplaying && storedDisplaying.length > 0) {
displayingAssets = storedDisplaying;
restoredDisplaying = true;
}
} else {
clearPersistedStore('assetBacklog');
clearPersistedStore('displayingAssets');
}
// load or clear persisted asset history
if ($configStore.clientPersistAssetHistory) {
const stored = $assetHistoryStore as api.AssetResponseDto[];
if (stored && stored.length > 0) {
assetHistory = stored;
}
} else {
clearPersistedStore('assetHistory');
}
unsubscribeRestart = restartProgress.subscribe((value) => {
if (value) {
progressBar.restart(value);
}
});
unsubscribeStop = stopProgress.subscribe((value) => {
if (value) {
progressBar.restart(false);
}
});
if (restoredDisplaying) {
showAssets(displayingAssets);
} else {
getNextAssets();
}
return () => {
window.removeEventListener('mousemove', showCursor);
window.removeEventListener('click', showCursor);
};
});
onDestroy(() => {
if (unsubscribeRestart) {
unsubscribeRestart();
}
if (unsubscribeStop) {
unsubscribeStop();
}
});
</script>
<section class="fixed grid h-dvh-safe w-screen bg-black" class:cursor-none={!cursorVisible}>
{#if error}
<ErrorElement {authError} message={errorMessage} />
{:else if displayingAssets}
<div class="absolute h-screen w-screen">
<ImageComponent
showLocation={$configStore.showImageLocation}
interval={$configStore.interval}
showPhotoDate={$configStore.showPhotoDate}
showImageDesc={$configStore.showImageDesc}
showPeopleDesc={$configStore.showPeopleDesc}
showAlbumName={$configStore.showAlbumName}
{...imagesState}
imageFill={$configStore.imageFill}
imageZoom={$configStore.imageZoom}
imagePan={$configStore.imagePan}
bind:showInfo={infoVisible}
/>
</div>
{#if $configStore.showClock}
<Clock />
{/if}
<Appointments />
<OverlayControls
next={async () => {
await handleDone(false, true);
infoVisible = false;
}}
back={async () => {
await handleDone(true, true);
infoVisible = false;
}}
pause={async () => {
infoVisible = false;
if (progressBarStatus == ProgressBarStatus.Paused) {
await progressBar.play();
} else {
await progressBar.pause();
}
}}
showInfo={async () => {
if (infoVisible) {
infoVisible = false;
await progressBar.play();
} else {
infoVisible = true;
await progressBar.pause();
}
}}
bind:status={progressBarStatus}
bind:infoVisible
overlayVisible={cursorVisible}
/>
<ProgressBar
autoplay
duration={$configStore.interval}
hidden={!$configStore.showProgressBar}
location={ProgressBarLocation.Bottom}
bind:this={progressBar}
bind:status={progressBarStatus}
onDone={handleDone}
/>
{:else}
<LoadingElement />
{/if}
</section>