BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

app.js 188.5 KiB Download Raw
1/* =========================================================
2 FILE MANAGER — CLIENT SPA
3 =========================================================
4 Architecture:
5 - RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API
6 - Token is stored in localStorage to survive full page refresh
7 - Token is sent as Bearer header on every API call
8 - Fingerprint (derived from navigator info) locks the token to this browser
9 ========================================================= */
10'use strict';
11
12// ───────────────────────────────────────────────────────────────────────────
13// STATE
14// ───────────────────────────────────────────────────────────────────────────
15const STATE = {
16 token: null, // decrypted JWT string
17 username: null,
18 isAdmin: false,
19 permissions: {},
20 roots: [], // [{ label, path }]
21 currentDir: null, // absolute path currently shown (null = roots view)
22 currentRoot: null, // { label, path } of the active root
23 items: [], // current directory listing
24 selectedItem: null, // item object selected in sidebar
25
26 // Ephemeral key pair per session (client-side)
27 clientPrivateKey: null,
28 clientPublicKeyJwk: null,
29
30 // Server public key for encrypting login
31 serverPublicKeyJwk: null,
32
33 // Stable per-browser binding id used in fingerprint derivation
34 clientBindingId: null,
35
36 // Persisted view state
37 restoreDir: null,
38 restoreRootPath: null,
39 lastOperationAt: null,
40
41 // Background refresh state
42 autoRefreshTimer: null,
43 uploadInProgress: false,
44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
45 thumbnailUrls: [],
46 thumbnailObserver: null,
47 folderIconObserver: null,
48
49 // Preview overlay state
50 previewObjectUrl: null,
51 previewCleanup: null,
52 previewDownloadAction: null,
53 previewVideoStreamSessionId: null,
54 previewSourceEl: null, // SVG element that triggered the preview
55 previewClosing: false, // guard to prevent double-close during animation
56 previewExpandState: null, // in-place expanded tile preview state
57 movePicker: null,
58
59 // Sidebar async loading guard to prevent stale updates on rapid selection changes.
60 sidebarLoadId: 0,
61 sidebarAbortController: null,
62
63 // Watched overlays are resolved asynchronously from /files/meta responses.
64 watchedStatusByPath: {},
65 watchedLoadId: 0,
66
67 // Cross-root file search mode (null = regular folder browsing).
68 searchQuery: null,
69
70 // Bust cache when favicon changes.
71 faviconVersion: Date.now(),
72};
73
74const SESSION_KEY = 'filemanager.session.v1';
75const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
76const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
77const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
78const MOBILE_LONG_PRESS_MS = 420;
79const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
80const THUMB_OBSERVER_ROOT_MARGIN = '120px';
81const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.';
82const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings';
83const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({
84 backgroundOpacity: '0',
85 edgeStyle: 'uniform',
86});
87const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
88const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
89let videoJsLoaderPromise = null;
90let threePreviewModulesPromise = null;
91
92// ───────────────────────────────────────────────────────────────────────────
93// CRYPTO HELPERS (Web Crypto API)
94// ───────────────────────────────────────────────────────────────────────────
95
96async function generateClientKeyPair ()
97{
98 if (!hasWebCrypto()) return;
99 const kp = await crypto.subtle.generateKey(
100 { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
101 true,
102 ['encrypt', 'decrypt'],
103 );
104 STATE.clientPrivateKey = kp.privateKey;
105 STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey);
106}
107
108/**
109 * Hybrid-encrypt a JS object using the server's RSA public key.
110 * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.
111 */
112async function hybridEncryptForServer (obj)
113{
114 if (!hasWebCrypto() || !STATE.serverPublicKeyJwk)
115 {
116 return { plaintext: obj };
117 }
118
119 const serverPub = await crypto.subtle.importKey(
120 'jwk', STATE.serverPublicKeyJwk,
121 { name: 'RSA-OAEP', hash: 'SHA-256' },
122 false, ['encrypt'],
123 );
124
125 const plaintext = new TextEncoder().encode(JSON.stringify(obj));
126 const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
127 const iv = crypto.getRandomValues(new Uint8Array(12));
128 const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext);
129
130 // gcmResult = ciphertext || tag (last 16 bytes are auth tag)
131 const gcmBytes = new Uint8Array(gcmResult);
132 const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16);
133 const tag = gcmBytes.slice(gcmBytes.length - 16);
134
135 const rawAes = await crypto.subtle.exportKey('raw', aesKey);
136 const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes);
137
138 return {
139 encryptedKey: b64(encryptedKey),
140 iv: b64(iv),
141 ciphertext: b64(ciphertext),
142 tag: b64(tag),
143 };
144}
145
146/**
147 * Hybrid-decrypt a payload encrypted by the server for us (using our public key).
148 */
149async function hybridDecryptFromServer (payload)
150{
151 if (!payload) return null;
152 if (payload.token) return payload.token;
153 if (!hasWebCrypto()) return null;
154
155 const encryptedKey = unb64(payload.encryptedKey);
156 const iv = unb64(payload.iv);
157 const ciphertext = unb64(payload.ciphertext);
158 const tag = unb64(payload.tag);
159
160 const rawAes = await crypto.subtle.decrypt(
161 { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey,
162 );
163
164 const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']);
165
166 // Recombine ciphertext + tag for AES-GCM
167 const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength);
168 combined.set(new Uint8Array(ciphertext));
169 combined.set(new Uint8Array(tag), ciphertext.byteLength);
170
171 const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined);
172 return new TextDecoder().decode(plain);
173}
174
175// ───────────────────────────────────────────────────────────────────────────
176// UTIL
177// ───────────────────────────────────────────────────────────────────────────
178
179function b64 (buf)
180{
181 return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));
182}
183
184function hasWebCrypto ()
185{
186 return !!(window.crypto && window.crypto.subtle);
187}
188
189function unb64 (str)
190{
191 const binary = atob(str);
192 const buf = new Uint8Array(binary.length);
193 for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);
194 return buf.buffer;
195}
196
197/** Stable browser fingerprint (not stored, derived fresh each load) */
198function getFingerprint ()
199{
200 const binding = getOrCreateClientBindingId();
201 const nav = navigator;
202
203 // Keep this stable: avoid viewport/screen metrics that can change when
204 // devtools opens, orientation changes, or window state changes.
205 return [
206 binding,
207 nav.userAgent || '',
208 nav.language,
209 nav.platform || nav.userAgentData?.platform || '',
210 Intl.DateTimeFormat().resolvedOptions().timeZone,
211 ].join('|');
212}
213
214function randomIdHex (bytes = 16)
215{
216 const arr = new Uint8Array(bytes);
217 if (window.crypto && typeof window.crypto.getRandomValues === 'function')
218 {
219 window.crypto.getRandomValues(arr);
220 } else
221 {
222 for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);
223 }
224 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
225}
226
227function userVideoPrefsKey ()
228{
229 const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous';
230 return VIDEO_PREFS_KEY_PREFIX + name;
231}
232
233function loadUserVideoPrefs ()
234{
235 try
236 {
237 const raw = localStorage.getItem(userVideoPrefsKey());
238 const parsed = raw ? JSON.parse(raw) : {};
239 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
240 return parsed;
241 } catch
242 {
243 return {};
244 }
245}
246
247function saveUserVideoPrefs (patch)
248{
249 try
250 {
251 const current = loadUserVideoPrefs();
252 localStorage.setItem(userVideoPrefsKey(), JSON.stringify({ ...current, ...(patch || {}) }));
253 } catch
254 {
255 // Ignore localStorage failures.
256 }
257}
258
259function buildAuthHeaders ()
260{
261 const headers = {};
262 if (STATE.token)
263 {
264 headers.Authorization = 'Bearer ' + STATE.token;
265 try
266 {
267 const fp = getFingerprint();
268 if (fp) headers['X-Fp'] = fp;
269 } catch
270 {
271 // Continue without a fingerprint header in constrained test/runtime contexts.
272 }
273 }
274 return headers;
275}
276
277function applyUserVideoTextTrackPrefs ()
278{
279 try
280 {
281 // Only override the two requested defaults and leave other settings at Video.js defaults.
282 localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW);
283 } catch
284 {
285 // Ignore localStorage failures.
286 }
287}
288
289function normaliseTrackName (name)
290{
291 return String(name || '').trim().toLowerCase();
292}
293
294function getTrackName (track)
295{
296 if (!track || typeof track !== 'object') return '';
297 const label = String(track.label || '').trim();
298 if (label) return label;
299 const name = String(track.name || '').trim();
300 if (name) return name;
301 const language = String(track.language || '').trim();
302 if (language) return language;
303 const id = String(track.id || '').trim();
304 if (id) return id;
305 return '';
306}
307
308function trackListToArray (trackList)
309{
310 if (!trackList || typeof trackList.length !== 'number') return [];
311 const out = [];
312 for (let i = 0; i < trackList.length; i++)
313 {
314 const track = trackList[i] || (typeof trackList.item === 'function' ? trackList.item(i) : null);
315 if (track) out.push(track);
316 }
317 return out;
318}
319
320function subtitleTracksFromPlayer (player)
321{
322 if (!player || typeof player.textTracks !== 'function') return [];
323 return trackListToArray(player.textTracks()).filter((track) =>
324 {
325 const kind = String(track.kind || '').toLowerCase();
326 return kind === 'subtitles' || kind === 'captions';
327 });
328}
329
330function audioTracksFromPlayer (player)
331{
332 if (!player || typeof player.audioTracks !== 'function') return [];
333 return trackListToArray(player.audioTracks());
334}
335
336function applySavedSubtitleTrack (player, savedName)
337{
338 if (typeof savedName !== 'string') return;
339 const tracks = subtitleTracksFromPlayer(player);
340 if (!tracks.length) return;
341
342 const wanted = normaliseTrackName(savedName);
343 if (!wanted)
344 {
345 for (const track of tracks) track.mode = 'disabled';
346 return;
347 }
348
349 const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted);
350 if (!match) return;
351
352 for (const track of tracks)
353 {
354 track.mode = track === match ? 'showing' : 'disabled';
355 }
356}
357
358function applySavedAudioTrack (player, savedName)
359{
360 if (typeof savedName !== 'string') return;
361 const tracks = audioTracksFromPlayer(player);
362 if (!tracks.length) return;
363
364 const wanted = normaliseTrackName(savedName);
365 if (!wanted) return;
366
367 const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted);
368 if (!match) return;
369
370 for (const track of tracks)
371 {
372 track.enabled = track === match;
373 }
374}
375
376function getSelectedSubtitleTrackName (player)
377{
378 const tracks = subtitleTracksFromPlayer(player);
379 if (!tracks.length) return null;
380 const active = tracks.find((track) => String(track.mode || '').toLowerCase() === 'showing');
381 return active ? getTrackName(active) : '';
382}
383
384function getSelectedAudioTrackName (player)
385{
386 const tracks = audioTracksFromPlayer(player);
387 if (!tracks.length) return null;
388 const active = tracks.find((track) => !!track.enabled);
389 return active ? getTrackName(active) : '';
390}
391
392function bindUserVideoTrackPrefs (player, prefs)
393{
394 const applySavedTracks = () =>
395 {
396 applySavedSubtitleTrack(player, prefs.subtitleTrackName);
397 applySavedAudioTrack(player, prefs.audioTrackName);
398 };
399
400 const captureSelectedTracks = () =>
401 {
402 const subtitleTrackName = getSelectedSubtitleTrackName(player);
403 const audioTrackName = getSelectedAudioTrackName(player);
404 const patch = {};
405
406 if (subtitleTrackName !== null) patch.subtitleTrackName = subtitleTrackName;
407 if (audioTrackName !== null) patch.audioTrackName = audioTrackName;
408
409 if (Object.keys(patch).length) saveUserVideoPrefs(patch);
410 };
411
412 const textTrackList = typeof player.textTracks === 'function' ? player.textTracks() : null;
413 const audioTrackList = typeof player.audioTracks === 'function' ? player.audioTracks() : null;
414 const onTrackListChange = () => captureSelectedTracks();
415
416 if (textTrackList && typeof textTrackList.addEventListener === 'function')
417 {
418 textTrackList.addEventListener('change', onTrackListChange);
419 }
420
421 if (audioTrackList && typeof audioTrackList.addEventListener === 'function')
422 {
423 audioTrackList.addEventListener('change', onTrackListChange);
424 }
425
426 return {
427 applySavedTracks,
428 captureSelectedTracks,
429 detach: () =>
430 {
431 if (textTrackList && typeof textTrackList.removeEventListener === 'function')
432 {
433 textTrackList.removeEventListener('change', onTrackListChange);
434 }
435 if (audioTrackList && typeof audioTrackList.removeEventListener === 'function')
436 {
437 audioTrackList.removeEventListener('change', onTrackListChange);
438 }
439 },
440 };
441}
442
443function bindImageSubtitleOverlay (player, videojs, prefs, session, item)
444{
445 const imageTracks = Array.isArray(session.imageSubtitleTracks)
446 ? session.imageSubtitleTracks.map((track) => ({
447 label: String(track.label || '').trim() || `Subtitle ${Number(track.streamIndex || 0) + 1}`,
448 language: String(track.language || '').trim(),
449 isDefault: !!track.default,
450 streamIndex: Number(track.streamIndex),
451 })).filter((track) => Number.isInteger(track.streamIndex) && track.streamIndex >= 0)
452 : [];
453
454 if (!imageTracks.length) return null;
455
456 const trackByStreamIndex = new Map(imageTracks.map((track) => [track.streamIndex, track]));
457 let selectedStreamIndex = null;
458 let menuOpen = false;
459 let requestToken = 0;
460 let activeBucket = -1;
461 let activeObjectUrl = null;
462 let overlayEl = null;
463 let overlayImgEl = null;
464 let menuEl = null;
465 let buttonEl = null;
466 let trackDisabled = false;
467 let failureNotified = false;
468
469 const closeObjectUrl = () =>
470 {
471 if (activeObjectUrl)
472 {
473 URL.revokeObjectURL(activeObjectUrl);
474 activeObjectUrl = null;
475 }
476 };
477
478 const hideOverlay = () =>
479 {
480 if (overlayEl) overlayEl.style.display = 'none';
481 if (overlayImgEl) overlayImgEl.removeAttribute('src');
482 closeObjectUrl();
483 };
484
485 const updateButtonState = () =>
486 {
487 if (!buttonEl) return;
488 const track = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null;
489 buttonEl.setAttribute('title', track ? `Image subtitles: ${track.label}` : 'Image subtitles');
490 buttonEl.setAttribute('aria-pressed', selectedStreamIndex === null ? 'false' : 'true');
491 };
492
493 const updateMenuState = () =>
494 {
495 if (!menuEl) return;
496 const items = menuEl.querySelectorAll('[data-image-subtitle-stream-index]');
497 for (const itemEl of items)
498 {
499 const value = itemEl.getAttribute('data-image-subtitle-stream-index');
500 const isSelected = value === (selectedStreamIndex === null ? 'off' : String(selectedStreamIndex));
501 itemEl.classList.toggle('is-selected', isSelected);
502 itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false');
503 itemEl.style.background = isSelected ? 'rgba(90, 196, 255, 0.28)' : 'transparent';
504 itemEl.style.fontWeight = isSelected ? '600' : '400';
505 itemEl.style.boxShadow = isSelected ? 'inset 0 0 0 1px rgba(90, 196, 255, 0.55)' : 'none';
506 }
507 };
508
509 const closeMenu = () =>
510 {
511 menuOpen = false;
512 if (menuEl) menuEl.style.display = 'none';
513 };
514
515 const openMenu = () =>
516 {
517 menuOpen = true;
518 if (menuEl)
519 {
520 updateMenuState();
521 menuEl.style.display = 'block';
522 }
523 };
524
525 const toggleMenu = () =>
526 {
527 if (menuOpen) closeMenu();
528 else openMenu();
529 };
530
531 const saveSelection = () =>
532 {
533 const selectedTrack = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null;
534 saveUserVideoPrefs({
535 imageSubtitleTrackStreamIndex: selectedStreamIndex,
536 imageSubtitleTrackName: selectedTrack ? selectedTrack.label : null,
537 });
538 };
539
540 const disableTrack = () =>
541 {
542 trackDisabled = true;
543 selectedStreamIndex = null;
544 activeBucket = -1;
545 hideOverlay();
546 updateButtonState();
547 updateMenuState();
548 saveSelection();
549
550 if (!failureNotified)
551 {
552 failureNotified = true;
553 toast('Image subtitles could not be rendered for this file.', 'err');
554 }
555 };
556
557 const setSelectedStreamIndex = (streamIndex, { persist = true } = {}) =>
558 {
559 const nextStreamIndex = Number.isInteger(streamIndex) ? streamIndex : null;
560 if (nextStreamIndex !== null && !trackByStreamIndex.has(nextStreamIndex)) return;
561
562 trackDisabled = false;
563 failureNotified = false;
564 selectedStreamIndex = nextStreamIndex;
565 activeBucket = -1;
566 hideOverlay();
567 updateButtonState();
568 updateMenuState();
569 if (persist) saveSelection();
570
571 if (selectedStreamIndex !== null)
572 {
573 void refreshFrame(true);
574 }
575 };
576
577 const refreshFrame = async (force = false) =>
578 {
579 if (selectedStreamIndex === null) return;
580 if (!overlayEl || !overlayImgEl) return;
581 if (trackDisabled) return;
582
583 const currentTime = Number(player.currentTime());
584 if (!Number.isFinite(currentTime) || currentTime < 0) return;
585
586 const bucket = Math.floor(currentTime * 4);
587 if (!force && bucket === activeBucket) return;
588 activeBucket = bucket;
589
590 const token = ++requestToken;
591 const headers = buildAuthHeaders();
592 const url = `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${selectedStreamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`;
593
594 try
595 {
596 const res = await fetch(url, {
597 method: 'GET',
598 headers,
599 credentials: 'same-origin',
600 });
601
602 if (token !== requestToken) return;
603
604 if (res.status === 204)
605 {
606 const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase();
607 hideOverlay();
608 if (frameStatus === 'error') disableTrack();
609 return;
610 }
611
612 if (!res.ok)
613 {
614 disableTrack();
615 return;
616 }
617
618 const blob = await res.blob();
619 if (token !== requestToken) return;
620
621 if (!blob || blob.size === 0)
622 {
623 disableTrack();
624 return;
625 }
626
627 closeObjectUrl();
628 activeObjectUrl = URL.createObjectURL(blob);
629 overlayImgEl.src = activeObjectUrl;
630 overlayEl.style.display = 'block';
631 overlayImgEl.style.display = 'block';
632 } catch
633 {
634 if (token === requestToken) disableTrack();
635 }
636 };
637
638 const dispose = () =>
639 {
640 requestToken++;
641 closeMenu();
642 hideOverlay();
643 if (overlayEl) overlayEl.remove();
644 if (menuEl) menuEl.remove();
645 player.imageSubtitleOverlayController = null;
646 buttonEl = null;
647 };
648
649 overlayEl = document.createElement('div');
650 overlayEl.className = 'video-subtitle-overlay';
651 overlayEl.style.position = 'absolute';
652 overlayEl.style.left = '0';
653 overlayEl.style.right = '0';
654 overlayEl.style.bottom = '3rem';
655 overlayEl.style.display = 'none';
656 overlayEl.style.zIndex = '3';
657 overlayEl.style.pointerEvents = 'none';
658 overlayEl.style.textAlign = 'center';
659 overlayEl.style.padding = '0 0.75rem';
660
661 overlayImgEl = document.createElement('img');
662 overlayImgEl.alt = 'Image subtitles';
663 overlayImgEl.style.display = 'none';
664 overlayImgEl.style.maxWidth = '100%';
665 overlayImgEl.style.maxHeight = '35%';
666 overlayImgEl.style.objectFit = 'contain';
667 overlayImgEl.style.filter = 'drop-shadow(0 2px 2px rgba(0, 0, 0, 0.7))';
668 overlayEl.appendChild(overlayImgEl);
669
670 menuEl = document.createElement('div');
671 menuEl.className = 'video-subtitle-overlay-menu';
672 menuEl.style.position = 'absolute';
673 menuEl.style.right = '0.75rem';
674 menuEl.style.bottom = 'calc(3rem + 0.5rem)';
675 menuEl.style.minWidth = '14rem';
676 menuEl.style.maxWidth = '20rem';
677 menuEl.style.background = 'rgba(12, 12, 12, 0.96)';
678 menuEl.style.border = '1px solid rgba(255, 255, 255, 0.15)';
679 menuEl.style.borderRadius = '0.5rem';
680 menuEl.style.boxShadow = '0 12px 28px rgba(0, 0, 0, 0.35)';
681 menuEl.style.padding = '0.35rem';
682 menuEl.style.display = 'none';
683 menuEl.style.zIndex = '4';
684
685 const buildMenuItem = (label, streamIndex, isSelected) =>
686 {
687 const itemEl = document.createElement('button');
688 itemEl.type = 'button';
689 itemEl.className = 'video-subtitle-overlay-menu-item';
690 itemEl.setAttribute('data-image-subtitle-stream-index', streamIndex === null ? 'off' : String(streamIndex));
691 itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false');
692 itemEl.style.display = 'block';
693 itemEl.style.width = '100%';
694 itemEl.style.margin = '0';
695 itemEl.style.padding = '0.5rem 0.75rem';
696 itemEl.style.border = '0';
697 itemEl.style.borderRadius = '0.35rem';
698 itemEl.style.background = isSelected ? 'rgba(255, 255, 255, 0.18)' : 'transparent';
699 itemEl.style.color = '#fff';
700 itemEl.style.textAlign = 'left';
701 itemEl.style.cursor = 'pointer';
702 itemEl.textContent = label;
703 itemEl.addEventListener('click', () =>
704 {
705 setSelectedStreamIndex(streamIndex);
706 closeMenu();
707 });
708 return itemEl;
709 };
710
711 menuEl.appendChild(buildMenuItem('Off', null, false));
712 for (const track of imageTracks)
713 {
714 menuEl.appendChild(buildMenuItem(track.label, track.streamIndex, false));
715 }
716
717 const registerButton = () =>
718 {
719 if (!videojs || typeof videojs.getComponent !== 'function' || typeof videojs.registerComponent !== 'function') return;
720 if (videojs.getComponent('ImageSubtitleButton')) return;
721
722 const Button = videojs.getComponent('Button');
723 class ImageSubtitleButton extends Button
724 {
725 buildCSSClass ()
726 {
727 return `${super.buildCSSClass()} vjs-image-subtitle-button`;
728 }
729
730 createEl ()
731 {
732 const el = super.createEl();
733 el.type = 'button';
734 el.setAttribute('title', 'Image subtitles');
735 el.setAttribute('aria-label', 'Image subtitles');
736 el.innerHTML = '<span aria-hidden="true">IM</span>';
737 return el;
738 }
739
740 handleClick ()
741 {
742 const controller = this.player().imageSubtitleOverlayController;
743 if (controller) controller.toggleMenu();
744 }
745 }
746
747 videojs.registerComponent('ImageSubtitleButton', ImageSubtitleButton);
748 };
749
750 const attachUi = () =>
751 {
752 if (!player.el()) return;
753 registerButton();
754 if (overlayEl.parentElement !== player.el()) player.el().appendChild(overlayEl);
755 if (menuEl.parentElement !== player.el()) player.el().appendChild(menuEl);
756 const controlBar = typeof player.getChild === 'function' ? player.getChild('controlBar') : null;
757 if (controlBar && typeof controlBar.addChild === 'function' && !buttonEl)
758 {
759 const button = controlBar.addChild('ImageSubtitleButton', {});
760 buttonEl = button && typeof button.el === 'function' ? button.el() : null;
761 updateButtonState();
762 }
763 };
764
765 const applySavedTracks = () =>
766 {
767 const savedName = normaliseTrackName(prefs.imageSubtitleTrackName);
768 if (savedName)
769 {
770 const savedByName = imageTracks.find((track) => normaliseTrackName(track.label) === savedName) || null;
771 if (savedByName)
772 {
773 setSelectedStreamIndex(savedByName.streamIndex, { persist: false });
774 return;
775 }
776 }
777
778 const savedIndex = Number(prefs.imageSubtitleTrackStreamIndex);
779 if (Number.isInteger(savedIndex) && trackByStreamIndex.has(savedIndex))
780 {
781 setSelectedStreamIndex(savedIndex, { persist: false });
782 return;
783 }
784
785 const defaultTrack = imageTracks.find((track) => track.isDefault) || null;
786 if (defaultTrack)
787 {
788 setSelectedStreamIndex(defaultTrack.streamIndex, { persist: false });
789 return;
790 }
791
792 setSelectedStreamIndex(null, { persist: false });
793 };
794
795 player.imageSubtitleOverlayController = {
796 toggleMenu,
797 closeMenu,
798 applySavedTracks,
799 captureSelectedTracks: saveSelection,
800 detach: dispose,
801 };
802
803 player.on('timeupdate', () => { void refreshFrame(); });
804 player.on('seeking', () => { void refreshFrame(true); });
805 player.on('play', () => { void refreshFrame(true); });
806 player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });
807 player.on('dispose', dispose);
808 player.ready(() =>
809 {
810 attachUi();
811 updateMenuState();
812 updateButtonState();
813 applySavedTracks();
814 if (menuOpen) openMenu();
815 });
816
817 return player.imageSubtitleOverlayController;
818}
819
820function normaliseVideoDuration (player, durationSeconds)
821{
822 const duration = Number(durationSeconds);
823 if (!player || !Number.isFinite(duration) || duration <= 0) return;
824
825 let originalDuration = null;
826 let durationWasChanged = false;
827 try
828 {
829 originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null;
830 installDurationFallback(player, originalDuration, duration);
831 if (player.__filemanagerDurationApplied) return;
832
833 const current = originalDuration ? Number(originalDuration()) : NaN;
834 const withinTolerance = Number.isFinite(current) && current >= duration * 0.95;
835 console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`);
836 if (withinTolerance)
837 {
838 player.__filemanagerDurationApplied = true;
839 return;
840 }
841
842 if (originalDuration)
843 {
844 durationWasChanged = true;
845 originalDuration(duration);
846 }
847 } catch
848 {
849 // Ignore players that do not support setting duration.
850 }
851
852 try
853 {
854 const updated = originalDuration ? Number(originalDuration()) : NaN;
855 if (Number.isFinite(updated) && updated >= duration * 0.95)
856 {
857 player.__filemanagerDurationApplied = true;
858 if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange');
859 return;
860 }
861
862 player.__filemanagerDurationApplied = true;
863 if (typeof player.trigger === 'function') player.trigger('durationchange');
864 } catch
865 {
866 // Ignore duration fallback failures.
867 }
868}
869
870function installDurationFallback (player, originalDuration, duration)
871{
872 if (!player || !originalDuration || player.__filemanagerDurationFallback) return;
873
874 player.__filemanagerDurationFallback = true;
875 player.duration = function durationWithFallback (...args)
876 {
877 if (args.length) return originalDuration(...args);
878 const current = Number(originalDuration());
879 return Number.isFinite(current) && current >= duration * 0.95 ? current : duration;
880 };
881}
882
883function formatDurationForDebug (seconds)
884{
885 const value = Number(seconds);
886 if (!Number.isFinite(value) || value < 0) return 'unknown';
887
888 const totalSeconds = Math.floor(value);
889 const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
890 const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
891 const ss = String(totalSeconds % 60).padStart(2, '0');
892 return `${hh}:${mm}:${ss}`;
893}
894
895function ensureVideoPlaybackUi (player, durationSeconds)
896{
897 if (!player || typeof player.on !== 'function') return;
898
899 const forceVodUi = () =>
900 {
901 normaliseVideoDuration(player, durationSeconds);
902
903 try
904 {
905 if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')
906 {
907 player.liveTracker.stopTracking();
908 }
909 } catch
910 {
911 // Ignore live tracker availability issues.
912 }
913
914 try
915 {
916 if (typeof player.removeClass === 'function')
917 {
918 player.removeClass('vjs-live');
919 }
920 } catch
921 {
922 // Ignore class update failures.
923 }
924
925 try
926 {
927 const display = player.el() && player.el().querySelector('.vjs-live-display');
928 if (display) display.style.display = 'none';
929 } catch
930 {
931 // Ignore missing DOM.
932 }
933 };
934
935 player.ready(forceVodUi);
936 player.on('loadedmetadata', forceVodUi);
937 player.on('durationchange', forceVodUi);
938 player.on('loadedplaylist', forceVodUi);
939}
940
941async function reportWatchProgress (filePath, progress)
942{
943 if (!filePath || !Number.isFinite(progress)) return;
944 await api('POST', '/files/watch-progress', {
945 filePath,
946 progress,
947 }).catch(() => null);
948
949 const nextStatus = progress >= 0.7 ? 'fully' : progress >= 0.1 ? 'partway' : null;
950 if (!nextStatus) return;
951
952 const prev = STATE.watchedStatusByPath[filePath];
953 if (prev === 'fully') return;
954 STATE.watchedStatusByPath[filePath] = nextStatus;
955
956 const iconEl = findTileIconByPath(filePath);
957 renderWatchedOverlayOnIcon(iconEl, nextStatus);
958}
959
960function getOrCreateClientBindingId ()
961{
962 if (STATE.clientBindingId) return STATE.clientBindingId;
963
964 try
965 {
966 const existing = localStorage.getItem(CLIENT_BINDING_KEY);
967 if (existing && typeof existing === 'string')
968 {
969 STATE.clientBindingId = existing;
970 return existing;
971 }
972 } catch
973 {
974 // Ignore storage read errors.
975 }
976
977 const created = randomIdHex(16);
978 STATE.clientBindingId = created;
979
980 try
981 {
982 localStorage.setItem(CLIENT_BINDING_KEY, created);
983 } catch
984 {
985 // Ignore storage write errors; in-memory fallback still keeps this stable
986 // for the current page session.
987 }
988
989 return created;
990}
991
992function formatBytes (bytes)
993{
994 if (bytes == null) return '—';
995 if (bytes < 1024) return bytes + ' B';
996 if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
997 if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
998 return (bytes / 1073741824).toFixed(2) + ' GB';
999}
1000
1001function parseHumanSize (input)
1002{
1003 const raw = String(input || '').trim();
1004 if (!raw) return null;
1005
1006 const m = raw.match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)(?:i?b)?$/i);
1007 if (!m) return null;
1008
1009 const value = Number(m[1]);
1010 if (!Number.isFinite(value) || value <= 0) return null;
1011
1012 const unit = String(m[2] || '').toLowerCase();
1013 const multipliers = {
1014 '': 1,
1015 k: 1024,
1016 m: 1024 * 1024,
1017 g: 1024 * 1024 * 1024,
1018 t: 1024 * 1024 * 1024 * 1024,
1019 };
1020 return Math.floor(value * (multipliers[unit] || 1));
1021}
1022
1023function updateAdminSizeFeedback (rawValue)
1024{
1025 const feedback = document.getElementById('admin-user-size-feedback');
1026 if (!feedback) return { bytes: null, valid: true };
1027
1028 const trimmed = String(rawValue || '').trim();
1029 if (!trimmed)
1030 {
1031 feedback.textContent = '';
1032 feedback.classList.add('hidden');
1033 feedback.classList.remove('ok', 'err');
1034 return { bytes: null, valid: true };
1035 }
1036
1037 const bytes = parseHumanSize(trimmed);
1038 feedback.classList.remove('hidden', 'ok', 'err');
1039 if (bytes == null)
1040 {
1041 feedback.textContent = 'Invalid size. Use formats like 25 MB, 1 GB, or 500 KB.';
1042 feedback.classList.add('err');
1043 return { bytes: null, valid: false };
1044 }
1045
1046 feedback.textContent = `Valid size: ${formatBytes(bytes)}`;
1047 feedback.classList.add('ok');
1048 return { bytes, valid: true };
1049}
1050
1051function extOf (name)
1052{
1053 const i = name.lastIndexOf('.');
1054 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
1055}
1056
1057function getPathSep (basePath)
1058{
1059 return basePath && basePath.includes('\\') ? '\\' : '/';
1060}
1061
1062function joinServerPath (basePath, segment)
1063{
1064 const sep = getPathSep(basePath);
1065 const base = String(basePath || '').replace(/[\\/]+$/, '');
1066 return base + sep + segment;
1067}
1068
1069function samePath (a, b)
1070{
1071 if (!a || !b) return false;
1072 return String(a).toLowerCase() === String(b).toLowerCase();
1073}
1074
1075function pathInside (child, root)
1076{
1077 if (!child || !root) return false;
1078 if (samePath(child, root)) return true;
1079 const sep = getPathSep(root);
1080 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
1081}
1082
1083function relativePathFromRoot (targetPath, rootPath)
1084{
1085 if (!targetPath || !rootPath) return String(targetPath || '');
1086 if (samePath(targetPath, rootPath)) return '.';
1087
1088 const prefix = String(rootPath).replace(/[\\/]+$/, '');
1089 const rel = String(targetPath).slice(prefix.length).replace(/^[\\/]+/, '');
1090 if (!rel) return '.';
1091 return rel;
1092}
1093
1094function displayPathWithRootLabel (targetPath, rootPath, rootLabel)
1095{
1096 const rel = relativePathFromRoot(targetPath, rootPath);
1097 const safeRoot = String(rootLabel || '').replace(/^\/+|\/+$/g, '');
1098 if (!safeRoot) return '/';
1099 if (rel === '.') return `/${safeRoot}`;
1100 return `/${safeRoot}/${String(rel).replace(/\\/g, '/')}`;
1101}
1102
1103function splitNameExt (name)
1104{
1105 const dot = String(name || '').lastIndexOf('.');
1106 if (dot <= 0) return { stem: String(name || ''), ext: '' };
1107 return {
1108 stem: String(name).slice(0, dot),
1109 ext: String(name).slice(dot),
1110 };
1111}
1112
1113function nextAvailableName (requestedName, existingNames)
1114{
1115 const set = existingNames instanceof Set ? existingNames : new Set(existingNames || []);
1116 if (!set.has(requestedName)) return requestedName;
1117
1118 const { stem, ext } = splitNameExt(requestedName);
1119 let n = 1;
1120 while (n <= 10000)
1121 {
1122 const candidate = `${stem || 'file'} (${n})${ext}`;
1123 if (!set.has(candidate)) return candidate;
1124 n++;
1125 }
1126
1127 return requestedName;
1128}
1129
1130async function listDirNameSet (dir)
1131{
1132 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dir)}`);
1133 const names = new Set();
1134 for (const it of ((data && data.items) || [])) names.add(it.name);
1135 return names;
1136}
1137
1138function cloneFileWithName (file, newName)
1139{
1140 return new File([file], newName, {
1141 type: file.type,
1142 lastModified: file.lastModified,
1143 });
1144}
1145
1146function saveSessionState ()
1147{
1148 if (!STATE.token) return;
1149 const now = Date.now();
1150 STATE.lastOperationAt = now;
1151 const payload = {
1152 token: STATE.token,
1153 dir: STATE.currentDir || null,
1154 rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,
1155 lastOperationAt: STATE.lastOperationAt,
1156 };
1157 try
1158 {
1159 localStorage.setItem(SESSION_KEY, JSON.stringify(payload));
1160 } catch
1161 {
1162 // Ignore storage errors (private mode/full quota).
1163 }
1164}
1165
1166function loadSessionState ()
1167{
1168 try
1169 {
1170 const raw = localStorage.getItem(SESSION_KEY);
1171 if (!raw) return null;
1172 const parsed = JSON.parse(raw);
1173 if (!parsed || typeof parsed.token !== 'string') return null;
1174 if (!Number.isFinite(parsed.lastOperationAt)) return null;
1175
1176 if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS)
1177 {
1178 clearSessionState();
1179 return null;
1180 }
1181
1182 return parsed;
1183 } catch
1184 {
1185 return null;
1186 }
1187}
1188
1189function clearSessionState ()
1190{
1191 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
1192}
1193
1194// ───────────────────────────────────────────────────────────────────────────
1195// API
1196// ───────────────────────────────────────────────────────────────────────────
1197
1198async function api (method, path, body, opts = {})
1199{
1200 const headers = { 'Content-Type': 'application/json' };
1201 const noAutoLogout = !!opts.noAutoLogout;
1202 if (STATE.token)
1203 {
1204 headers['Authorization'] = 'Bearer ' + STATE.token;
1205 try
1206 {
1207 const fp = getFingerprint();
1208 if (fp) headers['X-Fp'] = fp;
1209 } catch
1210 {
1211 // Continue without a fingerprint header in constrained test/runtime contexts.
1212 }
1213 }
1214 const fetchOpts = { ...opts };
1215 delete fetchOpts.noAutoLogout;
1216 const res = await fetch('/api' + path, {
1217 method,
1218 headers,
1219 body: body != null ? JSON.stringify(body) : undefined,
1220 ...fetchOpts,
1221 });
1222 if (!res.ok)
1223 {
1224 const j = await res.json().catch(() => ({}));
1225 // Session-expired → force re-login
1226 if (res.status === 401)
1227 {
1228 if (!noAutoLogout) logout();
1229 return null;
1230 }
1231 throw new Error(j.error || res.statusText);
1232 }
1233 if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed'))
1234 {
1235 saveSessionState();
1236 }
1237 return res.json();
1238}
1239
1240// ───────────────────────────────────────────────────────────────────────────
1241// TOAST
1242// ───────────────────────────────────────────────────────────────────────────
1243
1244function toast (msg, type = '')
1245{
1246 const el = document.createElement('div');
1247 el.className = 'toast-msg' + (type ? ' ' + type : '');
1248 el.textContent = msg;
1249 document.getElementById('toast').appendChild(el);
1250 setTimeout(() => el.remove(), 3500);
1251}
1252
1253// ───────────────────────────────────────────────────────────────────────────
1254// DIALOG MODALS — centralised replacements for alert / confirm / prompt
1255// ───────────────────────────────────────────────────────────────────────────
1256
1257/**
1258 * Show a confirmation dialog.
1259 * @param {string} title
1260 * @param {string} message
1261 * @returns {Promise<boolean>} true = OK, false = Cancel
1262 */
1263function showConfirm (title, message, { html = false, okLabel = null } = {})
1264{
1265 return new Promise((resolve) =>
1266 {
1267 const overlay = document.getElementById('confirm-modal');
1268 document.getElementById('confirm-modal-title').textContent = title;
1269 const msgEl = document.getElementById('confirm-modal-message');
1270 if (html) msgEl.innerHTML = message;
1271 else msgEl.textContent = message;
1272 overlay.classList.remove('hidden');
1273
1274 const ok = document.getElementById('confirm-modal-ok');
1275 const prevOkLabel = ok.textContent;
1276 if (okLabel != null) ok.textContent = okLabel;
1277
1278 const cancel = document.getElementById('confirm-modal-cancel');
1279
1280 function finish (result)
1281 {
1282 overlay.classList.add('hidden');
1283 ok.textContent = prevOkLabel;
1284 ok.removeEventListener('click', onOk);
1285 cancel.removeEventListener('click', onCancel);
1286 resolve(result);
1287 }
1288 function onOk () { finish(true); }
1289 function onCancel () { finish(false); }
1290
1291 ok.addEventListener('click', onOk);
1292 cancel.addEventListener('click', onCancel);
1293 ok.focus();
1294 });
1295}
1296
1297function escHtml (s)
1298{
1299 return String(s || '')
1300 .replace(/&/g, '&amp;')
1301 .replace(/</g, '&lt;')
1302 .replace(/>/g, '&gt;')
1303 .replace(/"/g, '&quot;');
1304}
1305
1306/**
1307 * Show a text-input dialog.
1308 * @param {string} title
1309 * @param {string} [message] — optional helper text shown above the input
1310 * @param {string} [defaultValue] — pre-filled value
1311 * @returns {Promise<string|null>} string = submitted value, null = cancelled
1312 */
1313function showPrompt (title, message = '', defaultValue = '')
1314{
1315 return new Promise((resolve) =>
1316 {
1317 const overlay = document.getElementById('prompt-modal');
1318 const msgEl = document.getElementById('prompt-modal-message');
1319 const input = document.getElementById('prompt-modal-input');
1320 const errorEl = document.getElementById('prompt-modal-error');
1321 const form = document.getElementById('prompt-modal-form');
1322 const cancel = document.getElementById('prompt-modal-cancel');
1323
1324 document.getElementById('prompt-modal-title').textContent = title;
1325 msgEl.textContent = message;
1326 msgEl.classList.toggle('hidden', !message);
1327 input.value = defaultValue;
1328 errorEl.classList.add('hidden');
1329 overlay.classList.remove('hidden');
1330 input.focus();
1331 input.select();
1332
1333 function finish (result)
1334 {
1335 overlay.classList.add('hidden');
1336 form.removeEventListener('submit', onSubmit);
1337 cancel.removeEventListener('click', onCancel);
1338 resolve(result);
1339 }
1340 function onSubmit (e)
1341 {
1342 e.preventDefault();
1343 finish(input.value);
1344 }
1345 function onCancel () { finish(null); }
1346
1347 form.addEventListener('submit', onSubmit);
1348 cancel.addEventListener('click', onCancel);
1349 });
1350}
1351
1352/**
1353 * Show an overwrite-decision dialog for a single file conflict.
1354 * @param {string} filename
1355 * @returns {Promise<'yes'|'no'|'all'|'none'>}
1356 */
1357function showOverwrite (filename)
1358{
1359 return new Promise((resolve) =>
1360 {
1361 const overlay = document.getElementById('overwrite-modal');
1362 document.getElementById('overwrite-modal-filename').textContent = filename;
1363 overlay.classList.remove('hidden');
1364
1365 const btnYes = document.getElementById('overwrite-modal-yes');
1366 const btnNo = document.getElementById('overwrite-modal-no');
1367 const btnAll = document.getElementById('overwrite-modal-all');
1368 const btnSkipAll = document.getElementById('overwrite-modal-skip-all');
1369
1370 function finish (result)
1371 {
1372 overlay.classList.add('hidden');
1373 btnYes.removeEventListener('click', onYes);
1374 btnNo.removeEventListener('click', onNo);
1375 btnAll.removeEventListener('click', onAll);
1376 btnSkipAll.removeEventListener('click', onSkipAll);
1377 resolve(result);
1378 }
1379 function onYes () { finish('yes'); }
1380 function onNo () { finish('no'); }
1381 function onAll () { finish('all'); }
1382 function onSkipAll () { finish('none'); }
1383
1384 btnYes.addEventListener('click', onYes);
1385 btnNo.addEventListener('click', onNo);
1386 btnAll.addEventListener('click', onAll);
1387 btnSkipAll.addEventListener('click', onSkipAll);
1388 btnNo.focus();
1389 });
1390}
1391
1392/**
1393 * Show single-file conflict options.
1394 * @param {string} filename
1395 * @param {string} renameTo
1396 * @param {string} mode - upload|move
1397 * @returns {Promise<'overwrite'|'rename'|'cancel'>}
1398 */
1399function showFileConflictChoice (filename, renameTo, mode = 'upload')
1400{
1401 return new Promise((resolve) =>
1402 {
1403 const overlay = document.getElementById('file-conflict-modal');
1404 const title = document.getElementById('file-conflict-title');
1405 const fileEl = document.getElementById('file-conflict-filename');
1406 const renameEl = document.getElementById('file-conflict-rename');
1407 const btnOverwrite = document.getElementById('file-conflict-overwrite');
1408 const btnRename = document.getElementById('file-conflict-rename-btn');
1409 const btnCancel = document.getElementById('file-conflict-cancel');
1410
1411 title.textContent = mode === 'move' ? 'Move file' : 'Upload file';
1412 fileEl.textContent = filename;
1413 renameEl.textContent = renameTo;
1414 btnRename.textContent = `Rename (${renameTo})`;
1415
1416 overlay.classList.remove('hidden');
1417
1418 function finish (result)
1419 {
1420 overlay.classList.add('hidden');
1421 btnOverwrite.removeEventListener('click', onOverwrite);
1422 btnRename.removeEventListener('click', onRename);
1423 btnCancel.removeEventListener('click', onCancel);
1424 resolve(result);
1425 }
1426
1427 function onOverwrite () { finish('overwrite'); }
1428 function onRename () { finish('rename'); }
1429 function onCancel () { finish('cancel'); }
1430
1431 btnOverwrite.addEventListener('click', onOverwrite);
1432 btnRename.addEventListener('click', onRename);
1433 btnCancel.addEventListener('click', onCancel);
1434 btnCancel.focus();
1435 });
1436}
1437
1438// ───────────────────────────────────────────────────────────────────────────
1439// SHARE MODAL
1440// ───────────────────────────────────────────────────────────────────────────
1441
1442async function openShareModal (item)
1443{
1444 const overlay = document.getElementById('share-modal');
1445 const urlInput = document.getElementById('share-url-input');
1446 const copyBtn = document.getElementById('share-copy-btn');
1447 const okBtn = document.getElementById('share-modal-ok');
1448 const closeBtn = document.getElementById('share-modal-close');
1449 const msgEl = document.getElementById('share-modal-msg');
1450
1451 urlInput.value = 'Creating link...';
1452 copyBtn.disabled = true;
1453 msgEl.textContent = 'This link is valid for 24 hours.';
1454 overlay.classList.remove('hidden');
1455
1456 let data;
1457 try
1458 {
1459 data = await api('POST', '/share/create', { filePath: item.path });
1460 } catch (err)
1461 {
1462 msgEl.textContent = 'Error: ' + (err.message || 'Could not create link.');
1463 urlInput.value = '';
1464 return;
1465 }
1466
1467 if (!data || !data.token)
1468 {
1469 msgEl.textContent = 'Unknown error while creating link.';
1470 urlInput.value = '';
1471 return;
1472 }
1473
1474 const shareUrl = `${location.origin}/share/${data.token}`;
1475 urlInput.value = shareUrl;
1476 copyBtn.disabled = false;
1477
1478 function close ()
1479 {
1480 overlay.classList.add('hidden');
1481 okBtn.removeEventListener('click', close);
1482 closeBtn.removeEventListener('click', close);
1483 copyBtn.removeEventListener('click', onCopy);
1484 }
1485
1486 function onCopy ()
1487 {
1488 navigator.clipboard.writeText(shareUrl).then(() =>
1489 {
1490 const orig = copyBtn.textContent;
1491 copyBtn.textContent = 'Copied!';
1492 setTimeout(() => { copyBtn.textContent = orig; }, 1500);
1493 }).catch(() =>
1494 {
1495 // Fallback: select the text
1496 urlInput.select();
1497 });
1498 }
1499
1500 okBtn.addEventListener('click', close);
1501 closeBtn.addEventListener('click', close);
1502 copyBtn.addEventListener('click', onCopy);
1503 okBtn.focus();
1504}
1505
1506// ───────────────────────────────────────────────────────────────────────────
1507// AUTH FLOW
1508// ───────────────────────────────────────────────────────────────────────────
1509
1510function showAuthOverlay (setupMode = false)
1511{
1512 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1513 document.getElementById('app').classList.add('hidden');
1514 const overlay = document.getElementById('auth-overlay');
1515 const usernameInput = document.getElementById('auth-username');
1516 const passwordInput = document.getElementById('auth-password');
1517 overlay.classList.remove('hidden');
1518 document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';
1519 document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);
1520 const submitBtn = document.getElementById('auth-submit');
1521 submitBtn.disabled = false;
1522 submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';
1523 document.getElementById('auth-error').classList.add('hidden');
1524 usernameInput.value = '';
1525 passwordInput.value = '';
1526 usernameInput.autocomplete = 'username';
1527 passwordInput.autocomplete = setupMode ? 'new-password' : 'current-password';
1528 usernameInput.focus();
1529 document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';
1530}
1531
1532function showApp ()
1533{
1534 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1535 document.getElementById('auth-overlay').classList.add('hidden');
1536 document.getElementById('app').classList.remove('hidden');
1537 if (isMobileViewport())
1538 {
1539 hideSidebarPanel();
1540 } else
1541 {
1542 openFolderSidebar();
1543 }
1544 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1545 const userLabel = document.getElementById('user-menu-label');
1546 if (userLabel) userLabel.textContent = STATE.username || 'User';
1547 void refreshGlobalFavicon();
1548 if (STATE.isAdmin)
1549 {
1550 void refreshAdminUpdateStatus();
1551 }
1552 else
1553 {
1554 setAdminUpdateBadge(0);
1555 }
1556 startAutoRefresh();
1557}
1558
1559async function initAuth ()
1560{
1561 // Generate a fresh key pair in the background; login falls back gracefully
1562 // while this is still in progress.
1563 generateClientKeyPair().catch(() =>
1564 {
1565 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
1566 });
1567
1568 // Fetch server public key
1569 const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null }));
1570 if (publicKey) STATE.serverPublicKeyJwk = publicKey;
1571 if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; }
1572 STATE.serverPublicKeyJwk = publicKey;
1573
1574 // Check whether first-run setup is needed
1575 const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));
1576
1577 if (!needed)
1578 {
1579 const saved = loadSessionState();
1580 if (saved && saved.token)
1581 {
1582 STATE.token = saved.token;
1583 STATE.restoreDir = saved.dir || null;
1584 STATE.restoreRootPath = saved.rootPath || null;
1585 STATE.lastOperationAt = saved.lastOperationAt;
1586
1587 const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);
1588 if (me)
1589 {
1590 STATE.username = me.username;
1591 STATE.isAdmin = me.isAdmin;
1592 STATE.permissions = me.permissions;
1593 showApp();
1594 await loadRoots({
1595 preferredDir: STATE.restoreDir,
1596 preferredRootPath: STATE.restoreRootPath,
1597 });
1598 return;
1599 }
1600
1601 STATE.token = null;
1602 clearSessionState();
1603 }
1604 }
1605
1606 showAuthOverlay(needed);
1607}
1608
1609async function doLogin (username, password, isSetup)
1610{
1611 const encrypted = await hybridEncryptForServer({ username, password });
1612 const endpoint = isSetup ? '/auth/setup' : '/auth/login';
1613
1614 let data;
1615 try
1616 {
1617 data = await api('POST', endpoint, {
1618 encrypted,
1619 clientPublicKey: STATE.clientPublicKeyJwk,
1620 fingerprint: getFingerprint(),
1621 });
1622 } catch (err)
1623 {
1624 return err.message;
1625 }
1626
1627 if (!data) return 'Login failed.';
1628
1629 // Decrypt the token sent back by the server
1630 const token = await hybridDecryptFromServer(data.encrypted || data);
1631 if (!token) return 'Login failed.';
1632 STATE.token = token;
1633
1634 // Load user info
1635 const me = await api('GET', '/auth/me');
1636 if (!me) return 'Session error.';
1637
1638 STATE.username = me.username;
1639 STATE.isAdmin = me.isAdmin;
1640 STATE.permissions = me.permissions;
1641
1642 saveSessionState();
1643 showApp();
1644 await loadRoots();
1645 return null; // no error
1646}
1647
1648function logout ()
1649{
1650 void performLogout();
1651}
1652
1653async function performLogout ()
1654{
1655 const tokenAtStart = STATE.token;
1656 stopAutoRefresh();
1657
1658 if (tokenAtStart)
1659 {
1660 try
1661 {
1662 await api('POST', '/auth/logout', {}, { noAutoLogout: true });
1663 } catch
1664 {
1665 // Ignore network errors while logging out locally.
1666 }
1667 }
1668
1669 STATE.token = null;
1670 STATE.username = null;
1671 STATE.isAdmin = false;
1672 STATE.permissions = {};
1673 STATE.currentDir = null;
1674 STATE.currentRoot = null;
1675 STATE.items = [];
1676 STATE.restoreDir = null;
1677 STATE.restoreRootPath = null;
1678 STATE.lastOperationAt = null;
1679 _adminUpdateStatus = null;
1680 setAdminUpdateBadge(0);
1681 clearSessionState();
1682 closePreview({ force: true });
1683 closeSidebar();
1684 await initAuth();
1685}
1686
1687// ───────────────────────────────────────────────────────────────────────────
1688// NAVIGATION
1689// ───────────────────────────────────────────────────────────────────────────
1690
1691async function loadRoots (opts = {})
1692{
1693 const data = await api('GET', '/files/roots');
1694 if (!data) return;
1695 STATE.roots = data.roots;
1696
1697 const preferredDir = opts.preferredDir || null;
1698 const preferredRootPath = opts.preferredRootPath || null;
1699
1700 if (preferredDir && preferredRootPath)
1701 {
1702 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
1703 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
1704 {
1705 try
1706 {
1707 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
1708 return;
1709 } catch
1710 {
1711 // Fall back to default root behavior.
1712 }
1713 }
1714 }
1715
1716 if (STATE.roots.length === 1)
1717 {
1718 // Single root → open it directly
1719 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
1720 } else
1721 {
1722 renderRootsView();
1723 }
1724}
1725
1726function renderRootsView ()
1727{
1728 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1729 disconnectThumbnailObserver();
1730 disconnectFolderIconObserver();
1731 revokeThumbnails();
1732
1733 STATE.currentDir = null;
1734 STATE.currentRoot = null;
1735 STATE.searchQuery = null;
1736 saveSessionState();
1737 renderBreadcrumb();
1738 const grid = document.getElementById('file-grid');
1739 grid.innerHTML = '';
1740 document.getElementById('empty-notice').classList.add('hidden');
1741 document.getElementById('folder-stats').classList.add('hidden');
1742 closeSidebar();
1743
1744 for (const root of STATE.roots)
1745 {
1746 const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root });
1747 grid.appendChild(el);
1748 }
1749
1750 loadThumbnails();
1751}
1752
1753async function navigateTo (absPath, root, opts = {})
1754{
1755 STATE.searchQuery = null;
1756 if (root) STATE.currentRoot = root;
1757 STATE.currentDir = absPath;
1758
1759 const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`);
1760 if (!data) return;
1761
1762 STATE.items = data.items;
1763 saveSessionState();
1764 renderBreadcrumb();
1765 renderFileGrid();
1766 await refreshFolderStats();
1767 closeSidebar();
1768}
1769
1770async function runGlobalFileSearch ()
1771{
1772 const input = document.getElementById('top-search-input');
1773 if (!input) return;
1774
1775 const query = String(input.value || '').trim();
1776 if (!query)
1777 {
1778 toast('Enter a search term first.', 'err');
1779 return;
1780 }
1781
1782 let data;
1783 try
1784 {
1785 data = await api('GET', `/files/search?query=${encodeURIComponent(query)}&limit=250`);
1786 }
1787 catch (err)
1788 {
1789 toast('Search failed: ' + err.message, 'err');
1790 return;
1791 }
1792
1793 STATE.searchQuery = query;
1794 STATE.currentDir = null;
1795 STATE.currentRoot = null;
1796 STATE.items = Array.isArray(data && data.results)
1797 ? data.results.map((it) => ({
1798 name: it.name,
1799 path: it.path,
1800 dir: it.dir,
1801 isDir: false,
1802 size: it.size,
1803 mtime: it.mtime,
1804 }))
1805 : [];
1806
1807 renderBreadcrumb();
1808 renderFileGrid();
1809 closeSidebar();
1810
1811 const stats = document.getElementById('folder-stats');
1812 if (stats)
1813 {
1814 const n = STATE.items.length;
1815 stats.textContent = n === 1
1816 ? `1 file found for "${query}".`
1817 : `${n} files found for "${query}".`;
1818 stats.classList.remove('hidden');
1819 }
1820}
1821
1822function renderBreadcrumb ()
1823{
1824 if (typeof document === 'undefined') return;
1825 const nav = document.getElementById('breadcrumb');
1826 if (!nav) return;
1827 nav.innerHTML = '';
1828
1829 // "Home" crumb
1830 const home = document.createElement('span');
1831 home.className = 'crumb' + (STATE.currentDir == null ? ' active' : '');
1832 home.textContent = 'Home';
1833 home.addEventListener('click', () =>
1834 {
1835 if (STATE.roots.length === 1)
1836 {
1837 navigateTo(STATE.roots[0].path, STATE.roots[0]);
1838 } else
1839 {
1840 renderRootsView();
1841 }
1842 });
1843 nav.appendChild(home);
1844
1845 if (STATE.searchQuery)
1846 {
1847 const sep = document.createElement('span');
1848 sep.className = 'sep';
1849 sep.textContent = ' / ';
1850 nav.appendChild(sep);
1851
1852 const searchCrumb = document.createElement('span');
1853 searchCrumb.className = 'crumb active';
1854 searchCrumb.textContent = `Search: ${STATE.searchQuery}`;
1855 nav.appendChild(searchCrumb);
1856 return;
1857 }
1858
1859 if (!STATE.currentDir || !STATE.currentRoot) return;
1860
1861 // Build path segments relative to the root.
1862 const rootPath = STATE.currentRoot.path;
1863 const relative = relativePathFromRoot(STATE.currentDir, rootPath);
1864 const segments = relative === '.' ? [] : relative.split(/[\\/]/).filter(Boolean);
1865 const parts = [STATE.currentRoot.label, ...segments];
1866
1867 for (let i = 0; i < parts.length; i++)
1868 {
1869 const sep = document.createElement('span');
1870 sep.className = 'sep';
1871 sep.textContent = ' / ';
1872 nav.appendChild(sep);
1873
1874 const crumb = document.createElement('span');
1875 crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : '');
1876 crumb.textContent = parts[i];
1877
1878 // Root crumb points to rootPath; segment crumbs point to their folder.
1879 const capturedPath = i === 0
1880 ? rootPath
1881 : joinServerPath(rootPath, segments.slice(0, i).join('/'));
1882 crumb.classList.add('crumb-drop-target');
1883 crumb.dataset.path = capturedPath;
1884 if (i < parts.length - 1)
1885 {
1886 crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot));
1887 }
1888
1889 nav.appendChild(crumb);
1890 }
1891}
1892
1893async function refreshFolderStats ()
1894{
1895 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1896 const el = document.getElementById('folder-stats');
1897 if (!STATE.currentDir || STATE.searchQuery)
1898 {
1899 el.classList.add('hidden');
1900 return;
1901 }
1902
1903 const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
1904 if (!data)
1905 {
1906 el.classList.add('hidden');
1907 return;
1908 }
1909
1910 const used = formatBytes(data.usedBytes);
1911 if (data.userFreeBytes != null)
1912 {
1913 el.textContent = `Folder usage: ${used} | Free space remaining: ${formatBytes(data.userFreeBytes)}`;
1914 } else
1915 {
1916 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
1917 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
1918 }
1919 el.classList.remove('hidden');
1920}
1921
1922function itemsSignature (items)
1923{
1924 return JSON.stringify(
1925 (items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
1926 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
1927 );
1928}
1929
1930async function incrementalRefreshCurrentDir ()
1931{
1932 if (STATE.previewExpandState) return;
1933 if (STATE.searchQuery) return;
1934 if (!STATE.currentDir || STATE.uploadInProgress) return;
1935
1936 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
1937 if (!data) return;
1938
1939 const oldSig = itemsSignature(STATE.items);
1940 const newSig = itemsSignature(data.items);
1941 if (oldSig !== newSig)
1942 {
1943 const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;
1944 STATE.items = data.items;
1945 renderFileGrid();
1946
1947 if (selectedPath)
1948 {
1949 const match = STATE.items.find(i => i.path === selectedPath);
1950 if (match)
1951 {
1952 const selectedEl = Array.from(document.querySelectorAll('.file-item'))
1953 .find(el => el.dataset.path === selectedPath);
1954 if (selectedEl) selectItem(selectedEl, match);
1955 } else
1956 {
1957 closeSidebar();
1958 }
1959 }
1960 }
1961 else
1962 {
1963 loadThumbnails();
1964 void loadWatchedStatusesForCurrentDir();
1965 }
1966
1967 await refreshFolderStats();
1968}
1969
1970function startAutoRefresh ()
1971{
1972 stopAutoRefresh();
1973 STATE.autoRefreshTimer = setInterval(() =>
1974 {
1975 if (document.hidden) return;
1976 incrementalRefreshCurrentDir();
1977 }, 5000);
1978}
1979
1980function stopAutoRefresh ()
1981{
1982 if (STATE.autoRefreshTimer)
1983 {
1984 clearInterval(STATE.autoRefreshTimer);
1985 STATE.autoRefreshTimer = null;
1986 }
1987}
1988
1989// ───────────────────────────────────────────────────────────────────────────
1990// FILE GRID RENDERING
1991// ───────────────────────────────────────────────────────────────────────────
1992
1993function renderFileGrid ()
1994{
1995 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1996 disconnectThumbnailObserver();
1997 disconnectFolderIconObserver();
1998 revokeThumbnails();
1999 const grid = document.getElementById('file-grid');
2000 grid.innerHTML = '';
2001 const empty = document.getElementById('empty-notice');
2002
2003 const sorted = [...STATE.items].sort((a, b) =>
2004 {
2005 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
2006 return a.name.localeCompare(b.name);
2007 });
2008
2009 empty.classList.toggle('hidden', sorted.length > 0);
2010
2011 for (const item of sorted)
2012 {
2013 grid.appendChild(makeFileItem(item));
2014 }
2015
2016 loadThumbnails();
2017 void loadWatchedStatusesForCurrentDir();
2018}
2019
2020function makeFileItem (item)
2021{
2022 const el = document.createElement('div');
2023 el.className = 'file-item';
2024 el.dataset.path = item.path;
2025 if (item.isDir) el.dataset.isdir = '1';
2026
2027 const icon = document.createElement('div');
2028 icon.className = 'icon';
2029 icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name);
2030 if (!item.isDir)
2031 {
2032 icon.dataset.previewPath = item.path;
2033 renderWatchedOverlayOnIcon(icon, watchStatusForTile(item));
2034 } else
2035 {
2036 icon.dataset.folderPath = item.path;
2037 }
2038 el.appendChild(icon);
2039
2040 const name = document.createElement('div');
2041 name.className = 'name';
2042 name.textContent = item.name;
2043 el.appendChild(name);
2044
2045 if (!item._root) makeDraggable(el, item);
2046 attachMobileLongPress(el, item);
2047
2048 el.addEventListener('contextmenu', (e) =>
2049 {
2050 if (!isMobileViewport()) return;
2051 e.preventDefault();
2052 e.stopPropagation();
2053 });
2054
2055 // Single-click: open sidebar
2056 el.addEventListener('click', (e) =>
2057 {
2058 e.stopPropagation();
2059 if (el.classList.contains('file-item--preview')) return;
2060 if (isMobileViewport())
2061 {
2062 if (el.dataset.longPressTriggered === '1')
2063 {
2064 el.dataset.longPressTriggered = '0';
2065 return;
2066 }
2067
2068 if (item.isDir)
2069 {
2070 navigateTo(item.path, item._root || STATE.currentRoot);
2071 } else
2072 {
2073 downloadOrView(item, icon.querySelector('svg'));
2074 }
2075 return;
2076 }
2077
2078 selectItem(el, item);
2079 });
2080
2081 // Double-click: enter folder or view/download file
2082 el.addEventListener('dblclick', (e) =>
2083 {
2084 e.stopPropagation();
2085 if (el.classList.contains('file-item--preview')) return;
2086 if (item.isDir)
2087 {
2088 navigateTo(item.path, item._root || STATE.currentRoot);
2089 } else
2090 {
2091 downloadOrView(item, icon.querySelector('svg'));
2092 }
2093 });
2094
2095 return el;
2096}
2097
2098function attachMobileLongPress (el, item)
2099{
2100 if (item._root) return;
2101
2102 let pressTimer = null;
2103 let startX = 0;
2104 let startY = 0;
2105
2106 function clearPress ()
2107 {
2108 if (!pressTimer) return;
2109 clearTimeout(pressTimer);
2110 pressTimer = null;
2111 }
2112
2113 function cancelPress ()
2114 {
2115 clearPress();
2116 }
2117
2118 el.addEventListener('pointerdown', (e) =>
2119 {
2120 if (!isMobileViewport()) return;
2121 if (e.button !== undefined && e.button !== 0) return;
2122 if (e.pointerType && e.pointerType === 'mouse') return;
2123
2124 startX = e.clientX;
2125 startY = e.clientY;
2126 clearPress();
2127
2128 pressTimer = setTimeout(() =>
2129 {
2130 pressTimer = null;
2131 el.dataset.longPressTriggered = '1';
2132 selectItem(el, item);
2133 }, MOBILE_LONG_PRESS_MS);
2134 });
2135
2136 el.addEventListener('pointermove', (e) =>
2137 {
2138 if (!pressTimer) return;
2139 if (Math.hypot(e.clientX - startX, e.clientY - startY) > MOBILE_LONG_PRESS_MOVE_THRESHOLD)
2140 {
2141 clearPress();
2142 }
2143 });
2144
2145 el.addEventListener('pointerup', cancelPress);
2146 el.addEventListener('pointercancel', cancelPress);
2147 el.addEventListener('pointerleave', cancelPress);
2148}
2149
2150function selectItem (el, item)
2151{
2152 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
2153 el.classList.add('selected');
2154 STATE.selectedItem = item;
2155 openSidebar(item);
2156}
2157
2158function isAbortError (err)
2159{
2160 if (!err) return false;
2161 return err.name === 'AbortError' || /abort/i.test(String(err.message || ''));
2162}
2163
2164function beginSidebarLoad ()
2165{
2166 if (STATE.sidebarAbortController && typeof STATE.sidebarAbortController.abort === 'function')
2167 {
2168 try { STATE.sidebarAbortController.abort(); } catch { /* ignore */ }
2169 }
2170
2171 STATE.sidebarLoadId += 1;
2172 STATE.sidebarAbortController = null;
2173
2174 return {
2175 id: STATE.sidebarLoadId,
2176 };
2177}
2178
2179function isSidebarLoadStale (item, sidebarLoadId)
2180{
2181 if (sidebarLoadId !== STATE.sidebarLoadId) return true;
2182 if (!STATE.selectedItem) return true;
2183 return STATE.selectedItem !== item && STATE.selectedItem.path !== item.path;
2184}
2185
2186// ───────────────────────────────────────────────────────────────────────────
2187// SIDEBAR
2188// ───────────────────────────────────────────────────────────────────────────
2189
2190/**
2191 * Renders (or clears) the duplicates panel at the bottom of the sidebar.
2192 * @param {object|null} item — the item whose duplicates are shown; null = clear
2193 * @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state
2194 */
2195function renderSidebarDuplicates (item, duplicates)
2196{
2197 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
2198 const panel = document.getElementById('sidebar-duplicates');
2199 if (!panel) return;
2200
2201 // Clear / hide when no item or no duplicates.
2202 if (!item || (Array.isArray(duplicates) && duplicates.length === 0))
2203 {
2204 panel.classList.add('hidden');
2205 panel.innerHTML = '';
2206 return;
2207 }
2208
2209 // Loading state.
2210 if (duplicates === null)
2211 {
2212 panel.classList.add('hidden');
2213 panel.innerHTML = '';
2214 return;
2215 }
2216
2217 panel.innerHTML = '';
2218 const heading = document.createElement('p');
2219 heading.className = 'sidebar-duplicates-heading';
2220 heading.textContent = `Duplicates (${duplicates.length})`;
2221 panel.appendChild(heading);
2222
2223 const list = document.createElement('ul');
2224 list.className = 'sidebar-duplicates-list';
2225
2226 for (const dup of duplicates)
2227 {
2228 const li = document.createElement('li');
2229 const btn = document.createElement('button');
2230 btn.className = 'sidebar-duplicate-entry';
2231 btn.title = dup.path;
2232 // Show path relative to its root; keep absolute path in the tooltip.
2233 btn.textContent = dup.relativePath || dup.path;
2234 btn.addEventListener('click', () => navigateToDuplicate(dup));
2235 li.appendChild(btn);
2236 list.appendChild(li);
2237 }
2238
2239 panel.appendChild(list);
2240 panel.classList.remove('hidden');
2241}
2242
2243/**
2244 * Navigates to the folder containing a duplicate file and then auto-opens it.
2245 * @param {{ path: string, name: string, dir: string }} dup
2246 */
2247async function navigateToDuplicate (dup)
2248{
2249 // If the duplicate lives in the folder already shown, just select it.
2250 if (STATE.currentDir && samePath(dup.dir, STATE.currentDir))
2251 {
2252 const tile = Array.from(document.querySelectorAll('.file-item'))
2253 .find((el) => el.dataset.path === dup.path);
2254 const dupItem = STATE.items.find((i) => i.path === dup.path);
2255 if (tile && dupItem)
2256 {
2257 selectItem(tile, dupItem);
2258 }
2259 return;
2260 }
2261
2262 // Find the root that contains the duplicate.
2263 const root = STATE.roots.find(
2264 (r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'),
2265 );
2266 if (!root)
2267 {
2268 toast('Cannot navigate to duplicate: root not accessible.', 'err');
2269 return;
2270 }
2271
2272 await navigateTo(dup.dir, root);
2273
2274 // After navigation, find and select the file tile to open it.
2275 const tile = Array.from(document.querySelectorAll('.file-item'))
2276 .find((el) => el.dataset.path === dup.path);
2277 const dupItem = STATE.items.find((i) => i.path === dup.path);
2278
2279 if (tile && dupItem)
2280 {
2281 selectItem(tile, dupItem);
2282 }
2283}
2284// ───────────────────────────────────────────────────────────────────────────
2285
2286async function openSidebar (item)
2287{
2288 const sidebarLoad = beginSidebarLoad();
2289
2290 const sidebar = document.getElementById('sidebar');
2291 sidebar.classList.remove('hidden');
2292 document.getElementById('app').classList.add('sidebar-open');
2293
2294 document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64);
2295 if (item.isDir)
2296 {
2297 document.getElementById('sidebar-icon').dataset.folderPath = item.path;
2298 } else
2299 {
2300 delete document.getElementById('sidebar-icon').dataset.folderPath;
2301 }
2302 document.getElementById('sidebar-name').textContent = item.name;
2303
2304 // Load metadata
2305 const dl = document.getElementById('sidebar-meta');
2306 dl.innerHTML = '<dt>Loading…</dt><dd></dd>';
2307
2308 const actions = document.getElementById('sidebar-actions');
2309 actions.innerHTML = '';
2310
2311 // Reset duplicates panel whenever a new item is opened.
2312 renderSidebarDuplicates(null, null);
2313
2314 if (!item.isDir)
2315 {
2316 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`).catch((err) =>
2317 {
2318 if (isAbortError(err)) return null;
2319 throw err;
2320 });
2321 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2322
2323 if (meta)
2324 {
2325 const watchedBy = VIDEO_EXTS.has(extOf(item.name))
2326 ? Object.entries(meta.watchedBy || {})
2327 .map(([user, status]) => `${String(user)}: ${String(status)}`)
2328 .sort((a, b) => a.localeCompare(b))
2329 : [];
2330
2331 dl.innerHTML = `
2332 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
2333 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
2334 <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd>
2335 <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd>
2336 ${VIDEO_EXTS.has(extOf(item.name)) ? `<dt>Watched by</dt><dd>${watchedBy.join(', ') || '—'}</dd>` : ''}
2337 `;
2338 }
2339
2340 // Fetch and render duplicate files.
2341 renderSidebarDuplicates(item, null); // show loading state
2342 const selectedPathAtRequest = item.path;
2343 api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`)
2344 .then((data) =>
2345 {
2346 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2347 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
2348 renderSidebarDuplicates(item, data ? data.duplicates : []);
2349 })
2350 .catch((err) =>
2351 {
2352 if (isAbortError(err)) return;
2353 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2354 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
2355 renderSidebarDuplicates(item, []);
2356 });
2357
2358 // View / download button
2359 const btnDl = document.createElement('button');
2360 btnDl.textContent = 'View / Download';
2361 btnDl.addEventListener('click', () =>
2362 {
2363 const tile = Array.from(document.querySelectorAll('.file-item')).find(node => node.dataset.path === item.path);
2364 const source = (tile ? tile.querySelector('.icon svg') : null) || document.querySelector('#sidebar-icon svg');
2365 downloadOrView(item, source);
2366 });
2367 actions.appendChild(btnDl);
2368
2369 // Share button (file)
2370 const btnShareFile = document.createElement('button');
2371 btnShareFile.textContent = 'Share';
2372 btnShareFile.addEventListener('click', () => openShareModal(item));
2373 actions.appendChild(btnShareFile);
2374 } else
2375 {
2376 dl.innerHTML = `<dt>Type</dt><dd>${item._root ? 'Root folder' : 'Folder'}</dd>`;
2377
2378 if (item._root)
2379 {
2380 dl.innerHTML += `
2381 <dt>Alias</dt><dd>${item.name}</dd>
2382 <dt>Original name</dt><dd>${item._root.originalName || basenameOfPath(item.path)}</dd>
2383 `;
2384
2385 const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch((err) =>
2386 {
2387 if (isAbortError(err)) return null;
2388 return null;
2389 });
2390 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2391
2392 if (space)
2393 {
2394 const used = formatBytes(space.usedBytes);
2395 const free = space.userFreeBytes != null
2396 ? formatBytes(space.userFreeBytes)
2397 : (space.freeBytes == null ? 'unknown' : formatBytes(space.freeBytes));
2398 const freeLabel = space.userFreeBytes != null ? 'Free space remaining' : 'Remaining';
2399 dl.innerHTML += `
2400 <dt>Used</dt><dd>${used}</dd>
2401 <dt>${freeLabel}</dt><dd>${free}</dd>
2402 `;
2403 }
2404
2405 if (item._root.isUserFolder)
2406 {
2407 dl.innerHTML += `
2408 <dt>Access</dt><dd>Private (your folder)</dd>
2409 `;
2410 } else
2411 {
2412 const accessUsers = await fetchRootAccessList(item.path);
2413 if (isSidebarLoadStale(item, sidebarLoad.id)) return;
2414 if (accessUsers)
2415 {
2416 dl.innerHTML += `
2417 <dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>
2418 `;
2419 }
2420 }
2421 }
2422
2423 const btnOpen = document.createElement('button');
2424 btnOpen.textContent = 'Open folder';
2425 btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot));
2426 actions.appendChild(btnOpen);
2427
2428 // Download as zip button (folder)
2429 const btnZip = document.createElement('button');
2430 btnZip.textContent = 'Download as zip';
2431 btnZip.addEventListener('click', () =>
2432 {
2433 btnZip.disabled = true;
2434 btnZip.textContent = 'Working...';
2435 const url = `/api/files/download-zip?dir=${encodeURIComponent(item.path)}`;
2436 const headers = {
2437 Authorization: 'Bearer ' + STATE.token,
2438 'X-Fp': getFingerprint(),
2439 };
2440 fetch(url, { headers })
2441 .then(res =>
2442 {
2443 if (!res.ok) throw new Error('Download mislukt');
2444 return res.blob();
2445 })
2446 .then(blob =>
2447 {
2448 const blobUrl = URL.createObjectURL(blob);
2449 const a = document.createElement('a');
2450 a.href = blobUrl;
2451 a.download = item.name + '.zip';
2452 a.click();
2453 setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
2454 })
2455 .catch((err) => toast(err.message || 'Download mislukt', 'err'))
2456 .finally(() =>
2457 {
2458 btnZip.disabled = false;
2459 btnZip.textContent = 'Download as zip';
2460 });
2461 });
2462 actions.appendChild(btnZip);
2463
2464 // Share button (folder)
2465 const btnShareFolder = document.createElement('button');
2466 btnShareFolder.textContent = 'Share';
2467 btnShareFolder.addEventListener('click', () => openShareModal(item));
2468 actions.appendChild(btnShareFolder);
2469
2470 // Load folder icon thumbnail into the sidebar icon element.
2471 void loadOneFolderIcon(document.getElementById('sidebar-icon'));
2472 }
2473
2474 // Rename button (write access required)
2475 if (canWrite(item))
2476 {
2477 if (item.isDir)
2478 {
2479 const btnSetIcon = document.createElement('button');
2480 btnSetIcon.textContent = 'Set icon';
2481 btnSetIcon.addEventListener('click', () => openFolderIconPicker(item));
2482 actions.appendChild(btnSetIcon);
2483 }
2484
2485 if (!item._root)
2486 {
2487 const btnMove = document.createElement('button');
2488 btnMove.textContent = 'Move to';
2489 btnMove.addEventListener('click', () => openMovePicker(item));
2490 actions.appendChild(btnMove);
2491
2492 if (!item.isDir)
2493 {
2494 const btnCopy = document.createElement('button');
2495 btnCopy.textContent = 'Copy to';
2496 btnCopy.addEventListener('click', () => openCopyPicker(item));
2497 actions.appendChild(btnCopy);
2498 }
2499 }
2500
2501 const btnRen = document.createElement('button');
2502 btnRen.textContent = 'Rename';
2503 btnRen.addEventListener('click', () => openRenameModal(item));
2504 actions.appendChild(btnRen);
2505
2506 if (!item._root)
2507 {
2508 const btnDel = document.createElement('button');
2509 btnDel.textContent = 'Delete';
2510 btnDel.className = 'danger';
2511 btnDel.addEventListener('click', () => deleteItem(item));
2512 actions.appendChild(btnDel);
2513 }
2514 }
2515}
2516
2517function openFolderSidebar ()
2518{
2519 beginSidebarLoad();
2520
2521 const sidebar = document.getElementById('sidebar');
2522 sidebar.classList.remove('hidden');
2523 document.getElementById('app').classList.add('sidebar-open');
2524
2525 document.getElementById('sidebar-icon').innerHTML = iconFolder(64);
2526
2527 const nameEl = document.getElementById('sidebar-name');
2528 const dl = document.getElementById('sidebar-meta');
2529 const actions = document.getElementById('sidebar-actions');
2530 actions.innerHTML = '';
2531 renderSidebarDuplicates(null, null);
2532
2533 if (!STATE.currentDir || !STATE.currentRoot)
2534 {
2535 nameEl.textContent = 'Storage Roots';
2536 dl.innerHTML = `
2537 <dt>Type</dt><dd>Root overview</dd>
2538 <dt>Roots</dt><dd>${STATE.roots.length}</dd>
2539 `;
2540 return;
2541 }
2542
2543 const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean);
2544 const fallback = STATE.currentRoot.label || 'Folder';
2545 nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback;
2546
2547 const dirs = STATE.items.filter(i => i.isDir).length;
2548 const files = STATE.items.length - dirs;
2549 const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label);
2550 const baseDetails = `
2551 <dt>Path</dt><dd>${displayPath}</dd>
2552 <dt>Folders</dt><dd>${dirs}</dd>
2553 <dt>Files</dt><dd>${files}</dd>
2554 `;
2555 dl.innerHTML = baseDetails;
2556
2557 if (samePath(STATE.currentDir, STATE.currentRoot.path))
2558 {
2559 if (STATE.currentRoot.isUserFolder)
2560 {
2561 dl.innerHTML += '<dt>Access</dt><dd>Private (your folder)</dd>';
2562 return;
2563 }
2564
2565 dl.innerHTML += '<dt>Access</dt><dd>Loading…</dd>';
2566 const currentDirAtStart = STATE.currentDir;
2567 const currentRootPathAtStart = STATE.currentRoot.path;
2568 void fetchRootAccessList(currentRootPathAtStart).then((accessUsers) =>
2569 {
2570 if (!accessUsers) return;
2571 if (!STATE.currentRoot) return;
2572 if (!samePath(STATE.currentDir, currentDirAtStart)) return;
2573 if (!samePath(STATE.currentRoot.path, currentRootPathAtStart)) return;
2574 dl.innerHTML = `${baseDetails}<dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>`;
2575 });
2576 }
2577}
2578
2579function closeSidebar ()
2580{
2581 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
2582 beginSidebarLoad();
2583 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
2584 STATE.selectedItem = null;
2585
2586 if (isMobileViewport())
2587 {
2588 hideSidebarPanel();
2589 return;
2590 }
2591
2592 openFolderSidebar();
2593}
2594
2595function isMobileViewport ()
2596{
2597 return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches;
2598}
2599
2600function hideSidebarPanel ()
2601{
2602 const sidebar = document.getElementById('sidebar');
2603 const app = document.getElementById('app');
2604 sidebar.classList.add('hidden');
2605 app.classList.remove('sidebar-open');
2606}
2607
2608function basenameOfPath (p)
2609{
2610 const parts = String(p || '').split(/[\\/]/).filter(Boolean);
2611 return parts.length ? parts[parts.length - 1] : String(p || '');
2612}
2613
2614async function fetchRootAccessList (rootPath)
2615{
2616 if (!rootPath) return null;
2617 const data = await api('GET', `/files/root-access?rootPath=${encodeURIComponent(rootPath)}`).catch((err) =>
2618 {
2619 if (isAbortError(err)) return null;
2620 return null;
2621 });
2622 if (!data || !Array.isArray(data.users)) return null;
2623 return data.users;
2624}
2625
2626function formatRootAccessList (users)
2627{
2628 if (!Array.isArray(users) || users.length === 0) return 'No users';
2629
2630 const sorted = [...users].sort((a, b) =>
2631 {
2632 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
2633 const byMode = modeRank(a.mode) - modeRank(b.mode);
2634 if (byMode !== 0) return byMode;
2635 return String(a.username).localeCompare(String(b.username));
2636 });
2637
2638 const items = sorted
2639 .map((u) => `<li>${escapeHtml(String(u.username || ''))} ${escapeHtml(String(u.mode || 'R'))}</li>`)
2640 .join('');
2641 return `<ul class="root-access-list">${items}</ul>`;
2642}
2643
2644function rootPermissionLabel (root)
2645{
2646 if (root && root.isUserFolder) return 'My Folder';
2647 return (root && (root.originalName || root.label)) || '';
2648}
2649
2650function resolveRootForPath (targetPath)
2651{
2652 if (!targetPath) return null;
2653 return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null;
2654}
2655
2656function writableRoots ()
2657{
2658 if (STATE.isAdmin) return STATE.roots.slice();
2659 return STATE.roots.filter((r) =>
2660 {
2661 if (r.isUserFolder) return true;
2662 const perm = STATE.permissions[rootPermissionLabel(r)];
2663 return !!(perm && perm.write);
2664 });
2665}
2666
2667async function moveWithConflictResolution (item, targetDir)
2668{
2669 try
2670 {
2671 return await api('POST', '/files/move', { from: item.path, toDir: targetDir });
2672 }
2673 catch (err)
2674 {
2675 if (!/already exists/i.test(err.message || '')) throw err;
2676
2677 const existingNames = await listDirNameSet(targetDir);
2678 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2679 const suggestedName = nextAvailableName(desiredName, existingNames);
2680 const decision = await showFileConflictChoice(desiredName, suggestedName, 'move');
2681 if (decision === 'cancel') return null;
2682
2683 if (decision === 'overwrite')
2684 {
2685 return api('POST', '/files/move', {
2686 from: item.path,
2687 toDir: targetDir,
2688 conflict: 'overwrite',
2689 });
2690 }
2691
2692 return api('POST', '/files/move', {
2693 from: item.path,
2694 toDir: targetDir,
2695 conflict: 'rename',
2696 targetName: suggestedName,
2697 });
2698 }
2699}
2700
2701async function copyWithConflictResolution (item, targetDir)
2702{
2703 try
2704 {
2705 return await api('POST', '/files/copy', { from: item.path, toDir: targetDir });
2706 }
2707 catch (err)
2708 {
2709 if (!/already exists/i.test(err.message || '')) throw err;
2710
2711 const existingNames = await listDirNameSet(targetDir);
2712 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2713 const suggestedName = nextAvailableName(desiredName, existingNames);
2714 const decision = await showFileConflictChoice(desiredName, suggestedName, 'copy');
2715 if (decision === 'cancel') return null;
2716
2717 if (decision === 'overwrite')
2718 {
2719 return api('POST', '/files/copy', {
2720 from: item.path,
2721 toDir: targetDir,
2722 conflict: 'overwrite',
2723 });
2724 }
2725
2726 return api('POST', '/files/copy', {
2727 from: item.path,
2728 toDir: targetDir,
2729 conflict: 'rename',
2730 targetName: suggestedName,
2731 });
2732 }
2733}
2734
2735function ensureMoveModal ()
2736{
2737 let overlay = document.getElementById('move-modal');
2738 if (overlay) return overlay;
2739
2740 overlay = document.createElement('div');
2741 overlay.id = 'move-modal';
2742 overlay.className = 'modal-overlay hidden';
2743 overlay.innerHTML = `
2744 <div class="modal move-modal">
2745 <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button>
2746 <h2>Move To</h2>
2747 <p id="move-modal-caption" class="muted"></p>
2748 <div id="move-tree" class="move-tree"></div>
2749 <p id="move-selected" class="muted"></p>
2750 <div class="dialog-actions">
2751 <button id="move-modal-cancel">Cancel</button>
2752 <button id="move-modal-confirm" class="primary">Move</button>
2753 </div>
2754 </div>
2755 `;
2756 document.body.appendChild(overlay);
2757
2758 const closeBtn = overlay.querySelector('#move-modal-close');
2759 const cancelBtn = overlay.querySelector('#move-modal-cancel');
2760 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2761
2762 function hide ()
2763 {
2764 overlay.classList.add('hidden');
2765 STATE.movePicker = null;
2766 }
2767
2768 closeBtn.addEventListener('click', hide);
2769 cancelBtn.addEventListener('click', hide);
2770 overlay.addEventListener('click', (e) =>
2771 {
2772 if (e.target === overlay) hide();
2773 });
2774
2775 confirmBtn.addEventListener('click', async () =>
2776 {
2777 const st = STATE.movePicker;
2778 if (!st || !st.item || !st.selectedPath)
2779 {
2780 toast('Select a destination folder first.', 'err');
2781 return;
2782 }
2783
2784 try
2785 {
2786 if (st.mode === 'copy')
2787 {
2788 const copied = await copyWithConflictResolution(st.item, st.selectedPath);
2789 if (!copied) return;
2790 }
2791 else
2792 {
2793 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
2794 if (!moved) return;
2795 }
2796 }
2797 catch (err)
2798 {
2799 const action = st.mode === 'copy' ? 'Copy' : 'Move';
2800 toast(`${action} failed: ${err.message}`, 'err');
2801 return;
2802 }
2803
2804 hide();
2805 if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2806 navigateTo(STATE.currentDir, STATE.currentRoot);
2807 });
2808
2809 return overlay;
2810}
2811
2812function setMoveSelection (path, buttonEl)
2813{
2814 if (!STATE.movePicker) return;
2815 STATE.movePicker.selectedPath = path;
2816
2817 document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected'));
2818 if (buttonEl) buttonEl.classList.add('selected');
2819
2820 const selectedEl = document.getElementById('move-selected');
2821 selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none';
2822}
2823
2824async function loadMoveChildren (containerEl, dirPath)
2825{
2826 if (containerEl.dataset.loaded === '1') return;
2827 containerEl.dataset.loaded = '1';
2828
2829 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
2830 const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : [];
2831
2832 if (!folders.length)
2833 {
2834 const empty = document.createElement('div');
2835 empty.className = 'move-empty';
2836 empty.textContent = 'No subfolders';
2837 containerEl.appendChild(empty);
2838 return;
2839 }
2840
2841 for (const child of folders)
2842 {
2843 containerEl.appendChild(createMoveNode(child.path, child.name));
2844 }
2845}
2846
2847function createMoveNode (folderPath, label)
2848{
2849 const node = document.createElement('div');
2850 node.className = 'move-node';
2851
2852 const row = document.createElement('div');
2853 row.className = 'move-node-row';
2854
2855 const toggle = document.createElement('button');
2856 toggle.type = 'button';
2857 toggle.className = 'move-toggle';
2858 toggle.textContent = '▸';
2859
2860 const selectBtn = document.createElement('button');
2861 selectBtn.type = 'button';
2862 selectBtn.className = 'move-node-label';
2863 selectBtn.textContent = label;
2864 selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn));
2865
2866 const children = document.createElement('div');
2867 children.className = 'move-children hidden';
2868
2869 toggle.addEventListener('click', async () =>
2870 {
2871 if (children.classList.contains('hidden'))
2872 {
2873 await loadMoveChildren(children, folderPath);
2874 children.classList.remove('hidden');
2875 toggle.textContent = '▾';
2876 } else
2877 {
2878 children.classList.add('hidden');
2879 toggle.textContent = '▸';
2880 }
2881 });
2882
2883 row.appendChild(toggle);
2884 row.appendChild(selectBtn);
2885 node.appendChild(row);
2886 node.appendChild(children);
2887 return node;
2888}
2889
2890function openDestinationPicker (item, mode)
2891{
2892 if (!canWrite())
2893 {
2894 toast('No write access.', 'err');
2895 return;
2896 }
2897
2898 const roots = writableRoots();
2899 if (!roots.length)
2900 {
2901 toast('No writable destination roots available.', 'err');
2902 return;
2903 }
2904
2905 const overlay = ensureMoveModal();
2906 const tree = overlay.querySelector('#move-tree');
2907 const caption = overlay.querySelector('#move-modal-caption');
2908 const titleEl = overlay.querySelector('h2');
2909 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2910
2911 const op = mode === 'copy' ? 'copy' : 'move';
2912 STATE.movePicker = { item, selectedPath: null, mode: op };
2913 titleEl.textContent = op === 'copy' ? 'Copy To' : 'Move To';
2914 confirmBtn.textContent = op === 'copy' ? 'Copy' : 'Move';
2915 caption.textContent = `Select destination folder for: ${item.name}`;
2916 tree.innerHTML = '';
2917
2918 for (const root of roots)
2919 {
2920 tree.appendChild(createMoveNode(root.path, root.label));
2921 }
2922
2923 setMoveSelection(null, null);
2924 overlay.classList.remove('hidden');
2925}
2926
2927function openMovePicker (item)
2928{
2929 openDestinationPicker(item, 'move');
2930}
2931
2932function openCopyPicker (item)
2933{
2934 openDestinationPicker(item, 'copy');
2935}
2936
2937// ───────────────────────────────────────────────────────────────────────────
2938// FOLDER ICON PICKER
2939// ───────────────────────────────────────────────────────────────────────────
2940
2941function globalFaviconFallbackMarkup ()
2942{
2943 return iconFile('favicon.png', 18);
2944}
2945
2946function applyGlobalFaviconPreview (hasFavicon)
2947{
2948 const preview = document.getElementById('global-favicon-preview');
2949 if (!preview) return;
2950
2951 if (!hasFavicon)
2952 {
2953 preview.innerHTML = globalFaviconFallbackMarkup();
2954 return;
2955 }
2956
2957 const img = document.createElement('img');
2958 img.alt = 'Current favicon';
2959 img.src = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`;
2960 img.addEventListener('error', () =>
2961 {
2962 preview.innerHTML = globalFaviconFallbackMarkup();
2963 }, { once: true });
2964 preview.innerHTML = '';
2965 preview.appendChild(img);
2966}
2967
2968function applyGlobalFaviconLink (hasFavicon)
2969{
2970 let link = document.getElementById('global-favicon-link');
2971 if (!link)
2972 {
2973 link = document.createElement('link');
2974 link.id = 'global-favicon-link';
2975 link.rel = 'icon';
2976 document.head.appendChild(link);
2977 }
2978
2979 if (!hasFavicon)
2980 {
2981 link.removeAttribute('href');
2982 return;
2983 }
2984
2985 link.href = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`;
2986}
2987
2988async function refreshGlobalFavicon ()
2989{
2990 const data = await api('GET', '/files/global-favicon').catch(() => null);
2991 const hasFavicon = !!(data && data.favicon && data.favicon.filePath);
2992 applyGlobalFaviconPreview(hasFavicon);
2993 applyGlobalFaviconLink(hasFavicon);
2994}
2995
2996async function openIconPickerModal ({
2997 dirPath,
2998 titleText,
2999 subtitleText,
3000 emptyText,
3001 confirmLabel,
3002 clearLabel,
3003 onSelect,
3004 onClear,
3005})
3006{
3007 if (!dirPath)
3008 {
3009 toast('Open a folder first.', 'err');
3010 return;
3011 }
3012
3013 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
3014 const images = data ? data.images : [];
3015
3016 const existingIconOverlay = document.getElementById('folder-icon-picker');
3017 if (existingIconOverlay) existingIconOverlay.remove();
3018
3019 const overlay = document.createElement('div');
3020 overlay.id = 'folder-icon-picker';
3021 overlay.className = 'modal-overlay';
3022
3023 const modal = document.createElement('div');
3024 modal.className = 'modal folder-icon-modal';
3025
3026 const closeBtn = document.createElement('button');
3027 closeBtn.className = 'modal-close';
3028 closeBtn.setAttribute('aria-label', 'Close');
3029 closeBtn.textContent = '✕';
3030
3031 const title = document.createElement('h2');
3032 title.textContent = titleText;
3033
3034 const filterInput = document.createElement('input');
3035 filterInput.type = 'text';
3036 filterInput.className = 'folder-icon-filter';
3037 filterInput.placeholder = 'Search icons';
3038 filterInput.setAttribute('aria-label', 'Search icons');
3039
3040 const subtitle = document.createElement('p');
3041 subtitle.className = 'muted';
3042 subtitle.textContent = images.length ? subtitleText : emptyText;
3043
3044 const grid = document.createElement('div');
3045 grid.className = 'folder-icon-grid';
3046
3047 for (const { filePath } of images)
3048 {
3049 const name = filePath.split('/').pop();
3050 const cell = document.createElement('div');
3051 cell.className = 'folder-icon-cell';
3052 cell.dataset.path = filePath;
3053 cell.dataset.name = String(name || '').toLowerCase();
3054
3055 const imgEl = document.createElement('img');
3056 imgEl.alt = name;
3057 imgEl.className = 'folder-icon-thumb';
3058 imgEl.dataset.src = filePath;
3059
3060 const label = document.createElement('div');
3061 label.className = 'folder-icon-label';
3062 label.textContent = name;
3063
3064 cell.appendChild(imgEl);
3065 cell.appendChild(label);
3066
3067 cell.addEventListener('click', () =>
3068 {
3069 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
3070 cell.classList.add('selected');
3071 confirmBtn.disabled = false;
3072 });
3073
3074 grid.appendChild(cell);
3075 }
3076
3077 function applyFilter ()
3078 {
3079 const needle = String(filterInput.value || '').trim().toLowerCase();
3080 let visible = 0;
3081 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3082 {
3083 const name = cell.dataset.name || '';
3084 const show = !needle || name.includes(needle);
3085 cell.classList.toggle('hidden', !show);
3086 if (show) visible += 1;
3087 }
3088 subtitle.textContent = visible
3089 ? subtitleText
3090 : 'No matching thumbnails were found.';
3091 }
3092
3093 filterInput.addEventListener('input', applyFilter);
3094
3095 const dialogActions = document.createElement('div');
3096 dialogActions.className = 'dialog-actions';
3097
3098 const clearBtn = document.createElement('button');
3099 clearBtn.textContent = clearLabel;
3100 clearBtn.addEventListener('click', async () =>
3101 {
3102 try
3103 {
3104 await onClear();
3105 }
3106 catch (err)
3107 {
3108 toast('Failed to clear icon: ' + err.message, 'err');
3109 return;
3110 }
3111 hide();
3112 });
3113
3114 const cancelBtn = document.createElement('button');
3115 cancelBtn.textContent = 'Cancel';
3116 cancelBtn.addEventListener('click', () => hide());
3117
3118 const confirmBtn = document.createElement('button');
3119 confirmBtn.className = 'primary';
3120 confirmBtn.textContent = confirmLabel;
3121 confirmBtn.disabled = true;
3122 confirmBtn.addEventListener('click', async () =>
3123 {
3124 const selected = grid.querySelector('.folder-icon-cell.selected');
3125 if (!selected) return;
3126
3127 try
3128 {
3129 await onSelect(selected.dataset.path);
3130 }
3131 catch (err)
3132 {
3133 toast('Failed to set icon: ' + err.message, 'err');
3134 return;
3135 }
3136
3137 hide();
3138 });
3139
3140 dialogActions.appendChild(clearBtn);
3141 dialogActions.appendChild(cancelBtn);
3142 dialogActions.appendChild(confirmBtn);
3143
3144 modal.appendChild(closeBtn);
3145 modal.appendChild(title);
3146 modal.appendChild(filterInput);
3147 modal.appendChild(subtitle);
3148 modal.appendChild(grid);
3149 modal.appendChild(dialogActions);
3150 overlay.appendChild(modal);
3151 document.body.appendChild(overlay);
3152
3153 function hide ()
3154 {
3155 overlay.remove();
3156 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) =>
3157 {
3158 URL.revokeObjectURL(img.src);
3159 });
3160 }
3161
3162 closeBtn.addEventListener('click', hide);
3163 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3164
3165 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
3166 {
3167 const imgEl = cell.querySelector('.folder-icon-thumb');
3168 const filePath = imgEl.dataset.src;
3169 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
3170 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3171 }).then(async (r) =>
3172 {
3173 if (!r.ok || !overlay.isConnected) return;
3174 const blob = await r.blob();
3175 const url = URL.createObjectURL(blob);
3176 imgEl.src = url;
3177 }).catch(() => { });
3178 }
3179
3180 filterInput.focus();
3181}
3182
3183async function openFolderIconPicker (item)
3184{
3185 if (!canWrite(item))
3186 {
3187 toast('No write access.', 'err');
3188 return;
3189 }
3190
3191 await openIconPickerModal({
3192 dirPath: item.path,
3193 titleText: 'Set folder icon',
3194 subtitleText: 'Select a file thumbnail to use as the folder icon.',
3195 emptyText: 'No files with cached thumbnails were found inside this folder.',
3196 confirmLabel: 'Set icon',
3197 clearLabel: 'Clear icon',
3198 onSelect: async (imagePath) =>
3199 {
3200 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
3201 refreshAfterIconChange(item);
3202 },
3203 onClear: async () =>
3204 {
3205 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
3206 refreshAfterIconChange(item);
3207 },
3208 });
3209}
3210
3211async function openGlobalFaviconPicker ()
3212{
3213 if (!STATE.isAdmin)
3214 {
3215 toast('Admin access required.', 'err');
3216 return;
3217 }
3218
3219 const existingIconOverlay = document.getElementById('folder-icon-picker');
3220 if (existingIconOverlay) existingIconOverlay.remove();
3221
3222 const overlay = document.createElement('div');
3223 overlay.id = 'folder-icon-picker';
3224 overlay.className = 'modal-overlay';
3225
3226 const modal = document.createElement('div');
3227 modal.className = 'modal folder-icon-modal';
3228
3229 const closeBtn = document.createElement('button');
3230 closeBtn.className = 'modal-close';
3231 closeBtn.setAttribute('aria-label', 'Close');
3232 closeBtn.textContent = '✕';
3233
3234 const title = document.createElement('h2');
3235 title.textContent = 'Set global favicon';
3236
3237 const filterInput = document.createElement('input');
3238 filterInput.type = 'text';
3239 filterInput.className = 'folder-icon-filter';
3240 filterInput.placeholder = 'Search images across all folders';
3241 filterInput.setAttribute('aria-label', 'Search images');
3242
3243 const subtitle = document.createElement('p');
3244 subtitle.className = 'muted';
3245 subtitle.textContent = 'Type at least 2 characters to search accessible images.';
3246
3247 const grid = document.createElement('div');
3248 grid.className = 'folder-icon-grid';
3249
3250 const dialogActions = document.createElement('div');
3251 dialogActions.className = 'dialog-actions';
3252
3253 const clearBtn = document.createElement('button');
3254 clearBtn.textContent = 'Clear favicon';
3255 clearBtn.addEventListener('click', async () =>
3256 {
3257 try
3258 {
3259 await api('POST', '/files/global-favicon', { imagePath: null });
3260 STATE.faviconVersion = Date.now();
3261 await refreshGlobalFavicon();
3262 }
3263 catch (err)
3264 {
3265 toast('Failed to clear icon: ' + err.message, 'err');
3266 return;
3267 }
3268 hide();
3269 });
3270
3271 const cancelBtn = document.createElement('button');
3272 cancelBtn.textContent = 'Cancel';
3273 cancelBtn.addEventListener('click', () => hide());
3274
3275 const confirmBtn = document.createElement('button');
3276 confirmBtn.className = 'primary';
3277 confirmBtn.textContent = 'Set favicon';
3278 confirmBtn.disabled = true;
3279
3280 let selectedPath = null;
3281 let searchToken = 0;
3282 let searchTimer = null;
3283
3284 confirmBtn.addEventListener('click', async () =>
3285 {
3286 if (!selectedPath) return;
3287 try
3288 {
3289 await api('POST', '/files/global-favicon', { imagePath: selectedPath });
3290 STATE.faviconVersion = Date.now();
3291 await refreshGlobalFavicon();
3292 }
3293 catch (err)
3294 {
3295 toast('Failed to set icon: ' + err.message, 'err');
3296 return;
3297 }
3298 hide();
3299 });
3300
3301 function revokeCellThumbs ()
3302 {
3303 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) =>
3304 {
3305 URL.revokeObjectURL(img.src);
3306 });
3307 }
3308
3309 function renderResults (items)
3310 {
3311 selectedPath = null;
3312 confirmBtn.disabled = true;
3313 revokeCellThumbs();
3314 grid.innerHTML = '';
3315
3316 for (const { path: filePath, name } of (items || []))
3317 {
3318 const cell = document.createElement('div');
3319 cell.className = 'folder-icon-cell';
3320 cell.dataset.path = filePath;
3321
3322 const imgEl = document.createElement('img');
3323 imgEl.alt = name;
3324 imgEl.className = 'folder-icon-thumb';
3325
3326 const label = document.createElement('div');
3327 label.className = 'folder-icon-label';
3328 label.textContent = name;
3329
3330 cell.appendChild(imgEl);
3331 cell.appendChild(label);
3332
3333 cell.addEventListener('click', () =>
3334 {
3335 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
3336 cell.classList.add('selected');
3337 selectedPath = filePath;
3338 confirmBtn.disabled = false;
3339 });
3340
3341 grid.appendChild(cell);
3342
3343 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
3344 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
3345 }).then(async (r) =>
3346 {
3347 if (!r.ok || !overlay.isConnected) return;
3348 const blob = await r.blob();
3349 const url = URL.createObjectURL(blob);
3350 imgEl.src = url;
3351 }).catch(() => { });
3352 }
3353 }
3354
3355 async function runSearchNow ()
3356 {
3357 const query = String(filterInput.value || '').trim();
3358 searchToken += 1;
3359 const token = searchToken;
3360
3361 if (query.length < 2)
3362 {
3363 subtitle.textContent = 'Type at least 2 characters to search accessible images.';
3364 renderResults([]);
3365 return;
3366 }
3367
3368 subtitle.textContent = 'Searching…';
3369 const data = await api('GET', `/files/search-images?query=${encodeURIComponent(query)}&limit=80`).catch(() => null);
3370 if (!overlay.isConnected || token !== searchToken) return;
3371
3372 const results = Array.isArray(data && data.results) ? data.results : [];
3373 renderResults(results);
3374
3375 if (!results.length)
3376 {
3377 subtitle.textContent = 'No matching thumbnails were found.';
3378 return;
3379 }
3380
3381 const suffix = data && data.truncated
3382 ? ` Scanned first ${Number(data.scannedFiles) || 0} files; refine your search for more.`
3383 : '';
3384 subtitle.textContent = `${results.length} matching image${results.length === 1 ? '' : 's'} found.${suffix}`;
3385 }
3386
3387 filterInput.addEventListener('input', () =>
3388 {
3389 if (searchTimer) clearTimeout(searchTimer);
3390 searchTimer = setTimeout(() =>
3391 {
3392 void runSearchNow();
3393 }, 240);
3394 });
3395
3396 dialogActions.appendChild(clearBtn);
3397 dialogActions.appendChild(cancelBtn);
3398 dialogActions.appendChild(confirmBtn);
3399
3400 modal.appendChild(closeBtn);
3401 modal.appendChild(title);
3402 modal.appendChild(filterInput);
3403 modal.appendChild(subtitle);
3404 modal.appendChild(grid);
3405 modal.appendChild(dialogActions);
3406 overlay.appendChild(modal);
3407 document.body.appendChild(overlay);
3408
3409 function hide ()
3410 {
3411 if (searchTimer) clearTimeout(searchTimer);
3412 overlay.remove();
3413 revokeCellThumbs();
3414 }
3415
3416 closeBtn.addEventListener('click', hide);
3417 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
3418 filterInput.focus();
3419}
3420
3421function refreshAfterIconChange (item)
3422{
3423 // Reset and reload icon in grid tiles.
3424 const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]'))
3425 .find(el => el.dataset.folderPath === item.path);
3426 if (gridTile)
3427 {
3428 const svg = gridTile.querySelector('svg');
3429 if (svg)
3430 {
3431 // Rebuild to plain folder SVG, then reload.
3432 gridTile.innerHTML = iconFolder();
3433 delete gridTile.dataset.thumbReady;
3434 gridTile.dataset.folderPath = item.path;
3435 void loadOneFolderIcon(gridTile);
3436 }
3437 }
3438
3439 // Also reset the sidebar icon if it's showing the same folder.
3440 const sidebarIcon = document.getElementById('sidebar-icon');
3441 if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path)
3442 {
3443 sidebarIcon.innerHTML = iconFolder(64);
3444 delete sidebarIcon.dataset.thumbReady;
3445 void loadOneFolderIcon(sidebarIcon);
3446 }
3447}
3448
3449// ───────────────────────────────────────────────────────────────────────────
3450// DOWNLOAD / VIEW
3451// ───────────────────────────────────────────────────────────────────────────
3452
3453function isInlinePreviewableBlob (blob, name)
3454{
3455 const mime = String(blob.type || '').toLowerCase();
3456 if (/^(image|video|audio)\//.test(mime)) return true;
3457 if (/^text\//.test(mime)) return true;
3458 if (mime === 'application/pdf') return true;
3459 if (mime === 'application/json') return true;
3460 if (mime === 'application/xml') return true;
3461 if (mime === 'application/javascript') return true;
3462
3463 // Fallback by extension when MIME is missing or generic.
3464 const ext = extOf(name || '');
3465 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true;
3466 if (MODEL_EXTS.has(ext)) return true;
3467 if (MODEL_EXTS.has(ext)) return true;
3468 if (CODE_EXTS.has(ext)) return true;
3469 return false;
3470}
3471
3472function isTextLikeBlob (blob, name)
3473{
3474 const mime = String(blob.type || '').toLowerCase();
3475 if (/^text\//.test(mime)) return true;
3476 if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true;
3477 const ext = extOf(name || '');
3478 return CODE_EXTS.has(ext);
3479}
3480
3481function detectCodeLanguage (name, mime)
3482{
3483 const ext = extOf(name || '');
3484 const m = String(mime || '').toLowerCase();
3485 if (m.includes('json') || ext === 'json') return 'json';
3486 if (m.includes('xml') || ext === 'xml') return 'xml';
3487 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
3488 if (m.includes('css') || ext === 'css') return 'css';
3489 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
3490 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
3491 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
3492 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
3493 return CODE_EXTS.has(ext) ? 'js' : 'plain';
3494}
3495
3496function prettyPrintMarkup (raw)
3497{
3498 const src = String(raw || '')
3499 .replace(/>\s+</g, '><')
3500 .replace(/\r\n/g, '\n');
3501
3502 const lines = src.replace(/></g, '>\n<').split('\n');
3503 let indent = 0;
3504 const out = [];
3505
3506 for (const ln of lines)
3507 {
3508 const line = ln.trim();
3509 if (!line) continue;
3510 const isClose = /^<\//.test(line);
3511 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
3512 const isOpen = /^<[^!?/][^>]*>$/.test(line);
3513
3514 if (isClose) indent = Math.max(0, indent - 1);
3515 out.push(' '.repeat(indent) + line);
3516 if (isOpen && !isSelf) indent += 1;
3517 }
3518
3519 return out.join('\n');
3520}
3521
3522function prettyPrintBraces (raw)
3523{
3524 const lines = String(raw || '')
3525 .replace(/\r\n/g, '\n')
3526 .split('\n');
3527 let indent = 0;
3528 const out = [];
3529
3530 for (const ln of lines)
3531 {
3532 const line = ln.trim();
3533 if (!line)
3534 {
3535 out.push('');
3536 continue;
3537 }
3538 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
3539 out.push(' '.repeat(indent) + line);
3540 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
3541 }
3542 return out.join('\n');
3543}
3544
3545function prettyPrintCode (raw, lang)
3546{
3547 const text = String(raw || '').replace(/\r\n/g, '\n');
3548 if (lang === 'json')
3549 {
3550 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
3551 }
3552 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
3553 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
3554 return text;
3555}
3556
3557function escapeHtml (s)
3558{
3559 return String(s)
3560 .replace(/&/g, '&amp;')
3561 .replace(/</g, '&lt;')
3562 .replace(/>/g, '&gt;');
3563}
3564
3565function highlightCode (raw, lang)
3566{
3567 if (lang === 'plain') return escapeHtml(raw);
3568
3569 let html = escapeHtml(raw);
3570 const stash = [];
3571 const keep = (regex, cls) =>
3572 {
3573 html = html.replace(regex, (m) =>
3574 {
3575 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
3576 return `@@TOK${idx}@@`;
3577 });
3578 };
3579
3580 if (lang === 'json')
3581 {
3582 html = html
3583 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
3584 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
3585 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
3586 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
3587 return html;
3588 }
3589
3590 if (lang === 'xml' || lang === 'html')
3591 {
3592 html = html
3593 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
3594 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
3595 return html;
3596 }
3597
3598 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
3599 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
3600 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
3601
3602 html = html
3603 .replace(/\b(function|return|if|else|for|while|switch|case|break|continue|const|let|var|class|new|import|from|export|default|try|catch|finally|throw|await|async|true|false|null|undefined)\b/g, '<span class="tok-keyword">$1</span>')
3604 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
3605
3606 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
3607 return html;
3608}
3609
3610function clearPreviewObjectUrl ()
3611{
3612 if (typeof STATE.previewCleanup === 'function')
3613 {
3614 try { STATE.previewCleanup(); } catch { /* ignore */ }
3615 }
3616 STATE.previewCleanup = null;
3617 STATE.previewDownloadAction = null;
3618 if (!STATE.previewObjectUrl) return;
3619 if (String(STATE.previewObjectUrl).startsWith('blob:'))
3620 {
3621 URL.revokeObjectURL(STATE.previewObjectUrl);
3622 }
3623 STATE.previewObjectUrl = null;
3624}
3625
3626function ensureStylesheet (id, href)
3627{
3628 let link = document.getElementById(id);
3629 if (link) return Promise.resolve(link);
3630
3631 link = document.createElement('link');
3632 link.id = id;
3633 link.rel = 'stylesheet';
3634 link.href = href;
3635
3636 return new Promise((resolve, reject) =>
3637 {
3638 link.addEventListener('load', () => resolve(link), { once: true });
3639 link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true });
3640 document.head.appendChild(link);
3641 });
3642}
3643
3644function ensureScript (id, src)
3645{
3646 let script = document.getElementById(id);
3647 if (script && window.videojs) return Promise.resolve(window.videojs);
3648
3649 if (!script)
3650 {
3651 script = document.createElement('script');
3652 script.id = id;
3653 script.src = src;
3654 }
3655
3656 return new Promise((resolve, reject) =>
3657 {
3658 script.addEventListener('load', () => resolve(window.videojs), { once: true });
3659 script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true });
3660 if (!script.isConnected) document.head.appendChild(script);
3661 });
3662}
3663
3664async function ensureVideoJsLoaded ()
3665{
3666 if (window.videojs)
3667 {
3668 configureVideoJsBuffering(window.videojs);
3669 return window.videojs;
3670 }
3671 if (!videoJsLoaderPromise)
3672 {
3673 videoJsLoaderPromise = Promise.all([
3674 ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'),
3675 ensureScript('videojs-script', '/vendor/video.js/video.min.js'),
3676 ]).then(() =>
3677 {
3678 configureVideoJsBuffering(window.videojs);
3679 return window.videojs;
3680 });
3681 }
3682 return videoJsLoaderPromise;
3683}
3684
3685function configureVideoJsBuffering (videojs)
3686{
3687 if (!VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED)
3688 return;
3689
3690 if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return;
3691 videojs.__filemanagerBufferingConfigured = true;
3692
3693 try
3694 {
3695 videojs.Vhs.GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;
3696 videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;
3697 } catch
3698 {
3699 // Ignore builds that do not expose VHS buffer configuration.
3700 }
3701}
3702
3703async function createVideoStreamSessionForItem (item)
3704{
3705 return api('POST', '/files/video-stream', { filePath: item.path });
3706}
3707
3708async function releaseVideoStreamSession (sessionId, opts = {})
3709{
3710 const id = String(sessionId || '').trim();
3711 if (!id) return;
3712
3713 await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, {
3714 keepalive: !!opts.keepalive,
3715 noAutoLogout: true,
3716 }).catch(() => null);
3717}
3718
3719function releaseActivePreviewVideoStreamSession (opts = {})
3720{
3721 const sessionId = String(STATE.previewVideoStreamSessionId || '').trim();
3722 if (!sessionId) return;
3723 STATE.previewVideoStreamSessionId = null;
3724 void releaseVideoStreamSession(sessionId, opts);
3725}
3726
3727async function preparePreviewDownload (item)
3728{
3729 const blob = await fetchFileBlob(item);
3730 if (!blob)
3731 {
3732 toast('Download failed.', 'err');
3733 return;
3734 }
3735
3736 const objectUrl = URL.createObjectURL(blob);
3737 triggerDownload(item.name, objectUrl);
3738 setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
3739}
3740
3741async function renderStreamedVideoPreview (item, targetEl)
3742{
3743 const videojs = await ensureVideoJsLoaded();
3744 const session = await createVideoStreamSessionForItem(item);
3745 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
3746 const prefs = loadUserVideoPrefs();
3747 applyUserVideoTextTrackPrefs();
3748
3749 if ((session.subtitleSummary && session.subtitleSummary.skipped > 0))
3750 {
3751 toast('Some subtitle tracks could not be converted for web playback.', 'err');
3752 }
3753
3754 STATE.previewDownloadAction = () => preparePreviewDownload(item);
3755
3756 const video = document.createElement('video');
3757 video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';
3758 video.controls = true;
3759 video.preload = 'auto';
3760 video.playsInline = true;
3761 targetEl.classList.add('preview-expand-content--video');
3762 targetEl.appendChild(video);
3763
3764 const player = videojs(video, {
3765 controls: true,
3766 fluid: false,
3767 fill: true,
3768 responsive: false,
3769 preload: 'auto',
3770 controlBar: {
3771 currentTimeDisplay: true,
3772 timeDivider: true,
3773 durationDisplay: true,
3774 remainingTimeDisplay: false,
3775 },
3776 sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],
3777 tracks: (session.subtitleTracks || []).map((track) => ({
3778 kind: 'subtitles',
3779 src: track.src,
3780 srclang: track.language || 'und',
3781 label: track.label,
3782 default: !!track.default,
3783 })),
3784 });
3785
3786 const trackPrefs = bindUserVideoTrackPrefs(player, prefs);
3787
3788 ensureVideoPlaybackUi(player, session.durationSeconds);
3789 const imageSubtitleController = bindImageSubtitleOverlay(player, videojs, prefs, session, item);
3790
3791 // -------------------------------------------------------------------------
3792
3793 let sentPartway = false;
3794 let sentFully = false;
3795 const markWatch = async () =>
3796 {
3797 let ratio = 0;
3798 try
3799 {
3800 const duration = Number(player.duration());
3801 const current = Number(player.currentTime());
3802 if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current))
3803 {
3804 ratio = current / duration;
3805 }
3806 } catch
3807 {
3808 return;
3809 }
3810
3811 if (ratio >= 0.7)
3812 {
3813 if (sentFully) return;
3814 sentPartway = true;
3815 sentFully = true;
3816 void reportWatchProgress(item.path, ratio);
3817 return;
3818 }
3819
3820 if (ratio >= 0.05)
3821 {
3822 if (sentPartway) return;
3823 sentPartway = true;
3824 void reportWatchProgress(item.path, ratio);
3825 }
3826 };
3827
3828 player.ready(() =>
3829 {
3830 const volume = Number(prefs.volume);
3831 if (Number.isFinite(volume))
3832 {
3833 player.volume(Math.max(0, Math.min(1, volume)));
3834 }
3835
3836 const settings = player && player.textTrackSettings;
3837 if (settings && typeof settings.setValues === 'function' && typeof settings.updateDisplay === 'function')
3838 {
3839 settings.setValues({
3840 backgroundColor: '#000',
3841 backgroundOpacity: '0',
3842 edgeStyle: 'uniform',
3843 });
3844 settings.updateDisplay();
3845 }
3846
3847 trackPrefs.applySavedTracks();
3848 });
3849
3850 player.on('loadedmetadata', trackPrefs.applySavedTracks);
3851 player.on('loadedplaylist', trackPrefs.applySavedTracks);
3852 player.on('timeupdate', markWatch);
3853 player.on('ended', () =>
3854 {
3855 sentPartway = true;
3856 sentFully = true;
3857 void reportWatchProgress(item.path, 1);
3858 });
3859 player.on('volumechange', () =>
3860 {
3861 const v = Number(player.volume());
3862 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
3863 });
3864
3865 STATE.previewCleanup = () =>
3866 {
3867 if (imageSubtitleController)
3868 {
3869 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
3870 try { imageSubtitleController.detach(); } catch { /* ignore */ }
3871 }
3872 releaseActivePreviewVideoStreamSession();
3873 try { markWatch(); } catch { /* ignore */ }
3874 try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
3875 try { trackPrefs.detach(); } catch { /* ignore */ }
3876 try { player.dispose(); } catch { /* ignore */ }
3877 };
3878}
3879
3880function fileAccentColor (name)
3881{
3882 const ext = extOf(name || '');
3883 if (IMAGE_EXTS.has(ext)) return '#3fcf8e';
3884 if (VIDEO_EXTS.has(ext)) return '#e05c6e';
3885 if (AUDIO_EXTS.has(ext)) return '#c084fc';
3886 if (MODEL_EXTS.has(ext)) return '#2f6dff';
3887 if (DOC_EXTS.has(ext)) return '#f97316';
3888 if (CODE_EXTS.has(ext)) return '#38bdf8';
3889 if (ARCHIVE_EXTS.has(ext)) return '#facc15';
3890 return '#7880a0';
3891}
3892
3893function animateRect (el, fromRect, toRect, opts = {})
3894{
3895 const duration = opts.duration == null ? 260 : opts.duration;
3896 const easeOut = (t) => 1 - Math.pow(1 - t, 3);
3897
3898 el.style.left = `${fromRect.left}px`;
3899 el.style.top = `${fromRect.top}px`;
3900 el.style.width = `${fromRect.width}px`;
3901 el.style.height = `${fromRect.height}px`;
3902
3903 return new Promise((resolve) =>
3904 {
3905 const t0 = performance.now();
3906
3907 function frame (now)
3908 {
3909 const raw = Math.min((now - t0) / duration, 1);
3910 const t = easeOut(raw);
3911
3912 const left = fromRect.left + (toRect.left - fromRect.left) * t;
3913 const top = fromRect.top + (toRect.top - fromRect.top) * t;
3914 const width = fromRect.width + (toRect.width - fromRect.width) * t;
3915 const height = fromRect.height + (toRect.height - fromRect.height) * t;
3916
3917 el.style.left = `${left}px`;
3918 el.style.top = `${top}px`;
3919 el.style.width = `${width}px`;
3920 el.style.height = `${height}px`;
3921
3922 if (raw < 1)
3923 {
3924 requestAnimationFrame(frame);
3925 } else
3926 {
3927 resolve();
3928 }
3929 }
3930
3931 requestAnimationFrame(frame);
3932 });
3933}
3934
3935async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent)
3936{
3937 if (!tileEl || !sourceSvgEl) return false;
3938
3939 if (STATE.previewExpandState)
3940 {
3941 await closeExpandedTilePreview();
3942 }
3943
3944 const iconEl = tileEl.querySelector('.icon');
3945 const nameEl = tileEl.querySelector('.name');
3946 if (!iconEl) return false;
3947
3948 const startRect = tileEl.getBoundingClientRect();
3949 const targetW = Math.min(window.innerWidth * 0.94, 1100);
3950 const targetH = Math.min(window.innerHeight * 0.9, 860);
3951 const targetRect = {
3952 left: (window.innerWidth - targetW) / 2,
3953 top: (window.innerHeight - targetH) / 2,
3954 width: targetW,
3955 height: targetH,
3956 };
3957
3958 const backdrop = document.createElement('div');
3959 backdrop.className = 'preview-backdrop';
3960 document.body.appendChild(backdrop);
3961
3962 const parent = tileEl.parentNode;
3963 const nextSibling = tileEl.nextSibling;
3964 const iconHtml = iconEl.innerHTML;
3965 const originalIconSvg = iconEl.querySelector('svg');
3966 const placeholder = document.createElement('div');
3967 placeholder.className = 'file-item file-item--preview-placeholder';
3968 placeholder.style.width = `${startRect.width}px`;
3969 placeholder.style.height = `${startRect.height}px`;
3970
3971 if (parent)
3972 {
3973 parent.insertBefore(placeholder, tileEl);
3974 }
3975
3976 tileEl.remove();
3977 document.body.appendChild(tileEl);
3978 tileEl.classList.add('file-item--preview');
3979 tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name));
3980 tileEl.style.position = 'fixed';
3981 tileEl.style.left = `${startRect.left}px`;
3982 tileEl.style.top = `${startRect.top}px`;
3983 tileEl.style.width = `${startRect.width}px`;
3984 tileEl.style.height = `${startRect.height}px`;
3985 tileEl.style.margin = '0';
3986 tileEl.style.zIndex = '10000';
3987
3988 if (nameEl) nameEl.style.display = 'none';
3989
3990 const titleEl = document.createElement('div');
3991 titleEl.className = 'preview-expand-title';
3992 titleEl.textContent = item.name;
3993
3994 const closeBtn = document.createElement('button');
3995 closeBtn.className = 'preview-expand-close';
3996 closeBtn.type = 'button';
3997 closeBtn.textContent = '×';
3998 closeBtn.setAttribute('aria-label', 'Close preview');
3999
4000 const dlBtn = document.createElement('button');
4001 dlBtn.className = 'preview-expand-download';
4002 dlBtn.type = 'button';
4003 dlBtn.textContent = 'Download';
4004 dlBtn.addEventListener('click', async (e) =>
4005 {
4006 e.stopPropagation();
4007 if (STATE.previewDownloadAction)
4008 {
4009 await STATE.previewDownloadAction();
4010 return;
4011 }
4012 if (!STATE.previewObjectUrl)
4013 {
4014 toast('Preview still loading.', 'err');
4015 return;
4016 }
4017 triggerDownload(item.name, STATE.previewObjectUrl);
4018 });
4019
4020 const shareBtn = document.createElement('button');
4021 shareBtn.className = 'preview-expand-share';
4022 shareBtn.type = 'button';
4023 shareBtn.textContent = 'Share';
4024 shareBtn.addEventListener('click', (e) =>
4025 {
4026 e.stopPropagation();
4027 openShareModal(item);
4028 });
4029
4030 const actionsEl = document.createElement('div');
4031 actionsEl.className = 'preview-expand-actions';
4032 actionsEl.appendChild(shareBtn);
4033 actionsEl.appendChild(dlBtn);
4034
4035 iconEl.innerHTML = '';
4036
4037 if (originalIconSvg)
4038 {
4039 const outline = originalIconSvg.cloneNode(true);
4040 outline.classList.add('preview-expand-outline');
4041 iconEl.appendChild(outline);
4042 }
4043
4044 const previewMount = document.createElement('div');
4045 previewMount.className = 'preview-expand-content';
4046 iconEl.appendChild(previewMount);
4047
4048 // Show spinner during expansion animation; content loads after it finishes
4049 const spinner = document.createElement('div');
4050 spinner.className = 'preview-loading-spinner';
4051 previewMount.appendChild(spinner);
4052
4053 tileEl.insertBefore(titleEl, tileEl.firstChild);
4054 tileEl.appendChild(closeBtn);
4055 tileEl.appendChild(actionsEl);
4056
4057 STATE.previewExpandState = {
4058 item,
4059 requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)),
4060 tileEl,
4061 sourceSvgEl,
4062 parent,
4063 nextSibling,
4064 iconEl,
4065 iconHtml,
4066 nameEl,
4067 backdrop,
4068 placeholder,
4069 closeBtn,
4070 dlBtn,
4071 shareBtn,
4072 actionsEl,
4073 titleEl,
4074 previewMount,
4075 startRect,
4076 };
4077
4078 const onBackdrop = (e) =>
4079 {
4080 if (e.target === backdrop) closePreview();
4081 };
4082 const onClose = () => closePreview({ force: true });
4083 backdrop.addEventListener('click', onBackdrop);
4084 closeBtn.addEventListener('click', onClose);
4085 STATE.previewExpandState.onBackdrop = onBackdrop;
4086 STATE.previewExpandState.onClose = onClose;
4087
4088 requestAnimationFrame(() => backdrop.classList.add('visible'));
4089 await animateRect(tileEl, startRect, targetRect);
4090
4091 tileEl.style.left = `${targetRect.left}px`;
4092 tileEl.style.top = `${targetRect.top}px`;
4093 tileEl.style.width = `${targetRect.width}px`;
4094 tileEl.style.height = `${targetRect.height}px`;
4095
4096 try
4097 {
4098 await loadPreviewContent(previewMount);
4099 } catch
4100 {
4101 if (previewMount.isConnected)
4102 {
4103 previewMount.innerHTML = '';
4104 const msg = document.createElement('p');
4105 msg.className = 'preview-unsupported';
4106 msg.textContent = 'Preview failed to load. You can try again.';
4107 previewMount.appendChild(msg);
4108 }
4109 }
4110
4111 return true;
4112}
4113
4114async function closeExpandedTilePreview ()
4115{
4116 const st = STATE.previewExpandState;
4117 if (!st) return;
4118
4119 st.backdrop.classList.remove('visible');
4120 if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop);
4121 if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose);
4122
4123 const fromRect = st.tileEl.getBoundingClientRect();
4124 await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 });
4125
4126 st.tileEl.classList.remove('file-item--preview');
4127 st.tileEl.style.position = '';
4128 st.tileEl.style.left = '';
4129 st.tileEl.style.top = '';
4130 st.tileEl.style.width = '';
4131 st.tileEl.style.height = '';
4132 st.tileEl.style.margin = '';
4133 st.tileEl.style.zIndex = '';
4134
4135 if (st.titleEl) st.titleEl.remove();
4136 if (st.closeBtn) st.closeBtn.remove();
4137 if (st.actionsEl) st.actionsEl.remove();
4138 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
4139 if (st.nameEl) st.nameEl.style.display = '';
4140
4141 if (st.placeholder && st.placeholder.parentNode)
4142 {
4143 st.placeholder.parentNode.insertBefore(st.tileEl, st.placeholder);
4144 st.placeholder.remove();
4145 } else if (st.parent)
4146 {
4147 if (st.nextSibling && st.nextSibling.parentNode === st.parent)
4148 {
4149 st.parent.insertBefore(st.tileEl, st.nextSibling);
4150 } else
4151 {
4152 st.parent.appendChild(st.tileEl);
4153 }
4154 }
4155
4156 if (st.backdrop) st.backdrop.remove();
4157 STATE.previewExpandState = null;
4158}
4159
4160async function closePreview (opts = {})
4161{
4162 if (STATE.previewClosing) return;
4163 if (STATE.previewExpandState)
4164 {
4165 if (STATE.previewExpandState.requireExplicitClose && !opts.force)
4166 {
4167 return;
4168 }
4169
4170 STATE.previewClosing = true;
4171 clearPreviewObjectUrl();
4172 try
4173 {
4174 await closeExpandedTilePreview();
4175 STATE.previewSourceEl = null;
4176 } finally
4177 {
4178 STATE.previewClosing = false;
4179 }
4180 }
4181}
4182
4183async function fetchFileBlob (item)
4184{
4185 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
4186 try
4187 {
4188 const res = await fetch(url, {
4189 headers: {
4190 Authorization: 'Bearer ' + STATE.token,
4191 'X-Fp': getFingerprint(),
4192 },
4193 });
4194 if (!res.ok) throw new Error('Download failed.');
4195 return await res.blob();
4196 } catch
4197 {
4198 return null;
4199 }
4200}
4201
4202function triggerDownload (filename, objectUrl)
4203{
4204 const a = document.createElement('a');
4205 a.href = objectUrl;
4206 a.download = filename;
4207 a.click();
4208}
4209
4210function modelPreviewType (name)
4211{
4212 const ext = extOf(name || '');
4213 if (MODEL_EXTS.has(ext)) return ext;
4214 return null;
4215}
4216
4217async function loadThreePreviewModules ()
4218{
4219 if (!threePreviewModulesPromise)
4220 {
4221 threePreviewModulesPromise = Promise.all([
4222 import('/vendor/three/three.module.js'),
4223 import('/vendor/three/addons/controls/OrbitControls.js'),
4224 import('/vendor/three/addons/loaders/STLLoader.js'),
4225 import('/vendor/three/addons/loaders/OBJLoader.js'),
4226 ]).then(([THREE, controlsMod, stlMod, objMod]) =>
4227 {
4228 return {
4229 THREE,
4230 OrbitControls: controlsMod.OrbitControls,
4231 STLLoader: stlMod.STLLoader,
4232 OBJLoader: objMod.OBJLoader,
4233 };
4234 });
4235 }
4236
4237 return threePreviewModulesPromise;
4238}
4239
4240function disposeObject3D (root)
4241{
4242 if (!root || typeof root.traverse !== 'function') return;
4243 root.traverse((node) =>
4244 {
4245 if (node.geometry && typeof node.geometry.dispose === 'function')
4246 {
4247 node.geometry.dispose();
4248 }
4249
4250 if (!node.material) return;
4251 if (Array.isArray(node.material))
4252 {
4253 node.material.forEach((material) =>
4254 {
4255 if (material && typeof material.dispose === 'function') material.dispose();
4256 });
4257 return;
4258 }
4259
4260 if (typeof node.material.dispose === 'function') node.material.dispose();
4261 });
4262}
4263
4264async function buildModelObjectFromBlob (blob, type, modules)
4265{
4266 const { THREE, STLLoader, OBJLoader } = modules;
4267 const sharedMaterial = new THREE.MeshStandardMaterial({
4268 color: 0x2f6dff,
4269 metalness: 0.08,
4270 roughness: 0.72,
4271 });
4272
4273 if (type === 'stl')
4274 {
4275 const arr = await blob.arrayBuffer();
4276 const geometry = new STLLoader().parse(arr);
4277 geometry.computeVertexNormals();
4278 return new THREE.Mesh(geometry, sharedMaterial);
4279 }
4280
4281 if (type === 'obj')
4282 {
4283 const text = await blob.text();
4284 const obj = new OBJLoader().parse(text);
4285 obj.traverse((node) =>
4286 {
4287 if (!node || !node.isMesh) return;
4288 node.material = sharedMaterial.clone();
4289 });
4290 sharedMaterial.dispose();
4291 return obj;
4292 }
4293
4294 throw new Error('Unsupported 3D model format.');
4295}
4296
4297function setModelPreviewMessage (wrap, text)
4298{
4299 wrap.innerHTML = '';
4300 const msg = document.createElement('p');
4301 msg.className = 'preview-unsupported';
4302 msg.textContent = text;
4303 wrap.appendChild(msg);
4304}
4305
4306async function renderModelPreview (item, blob, targetEl)
4307{
4308 const type = modelPreviewType(item && item.name);
4309 if (!type)
4310 {
4311 const msg = document.createElement('p');
4312 msg.className = 'preview-unsupported';
4313 msg.textContent = 'This 3D file type is not supported yet.';
4314 targetEl.appendChild(msg);
4315 return;
4316 }
4317
4318 const wrap = document.createElement('div');
4319 wrap.className = 'preview-model-wrap';
4320 targetEl.appendChild(wrap);
4321
4322 const canvas = document.createElement('canvas');
4323 canvas.className = 'preview-model-canvas';
4324 canvas.style.touchAction = 'none';
4325 wrap.appendChild(canvas);
4326
4327 const hint = document.createElement('p');
4328 hint.className = 'preview-model-hint';
4329 hint.textContent = 'Drag to rotate. Use the scroll wheel to zoom.';
4330 wrap.appendChild(hint);
4331
4332 const gl =
4333 canvas.getContext('webgl2', { antialias: true, alpha: true }) ||
4334 canvas.getContext('webgl', { antialias: true, alpha: true });
4335 if (!gl)
4336 {
4337 setModelPreviewMessage(wrap, '3D preview is not available in this browser. You can still download this file.');
4338 return;
4339 }
4340
4341 let modules;
4342 try
4343 {
4344 modules = await loadThreePreviewModules();
4345 } catch
4346 {
4347 setModelPreviewMessage(wrap, '3D preview dependencies failed to load. You can still download this file.');
4348 return;
4349 }
4350
4351 if (!wrap.isConnected) return;
4352
4353 const { THREE, OrbitControls } = modules;
4354 const scene = new THREE.Scene();
4355 scene.background = new THREE.Color(0x0d111a);
4356
4357 const camera = new THREE.PerspectiveCamera(50, 1, 0.01, 5000);
4358 const renderer = new THREE.WebGLRenderer({ canvas, context: gl, antialias: true, alpha: true });
4359 renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
4360
4361 const ambient = new THREE.AmbientLight(0xffffff, 0.9);
4362 const key = new THREE.DirectionalLight(0xffffff, 0.95);
4363 key.position.set(1.2, 1.6, 1.1);
4364 scene.add(ambient);
4365 scene.add(key);
4366
4367 let modelRoot;
4368 try
4369 {
4370 modelRoot = await buildModelObjectFromBlob(blob, type, modules);
4371 } catch
4372 {
4373 renderer.dispose();
4374 setModelPreviewMessage(wrap, 'This 3D file could not be parsed. You can still download it.');
4375 return;
4376 }
4377
4378 if (!wrap.isConnected)
4379 {
4380 disposeObject3D(modelRoot);
4381 renderer.dispose();
4382 return;
4383 }
4384
4385 scene.add(modelRoot);
4386
4387 const box = new THREE.Box3().setFromObject(modelRoot);
4388 if (box.isEmpty())
4389 {
4390 disposeObject3D(modelRoot);
4391 renderer.dispose();
4392 setModelPreviewMessage(wrap, 'This 3D file has no visible geometry to preview.');
4393 return;
4394 }
4395
4396 const size = new THREE.Vector3();
4397 const center = new THREE.Vector3();
4398 box.getSize(size);
4399 box.getCenter(center);
4400 modelRoot.position.sub(center);
4401
4402 const maxDim = Math.max(size.x, size.y, size.z) || 1;
4403 const camDistance = maxDim * 1.8;
4404 camera.position.set(camDistance, camDistance * 0.75, camDistance);
4405 camera.near = Math.max(0.001, maxDim / 2000);
4406 camera.far = Math.max(1000, maxDim * 2000);
4407 camera.updateProjectionMatrix();
4408
4409 const controls = new OrbitControls(camera, renderer.domElement);
4410 controls.enableDamping = true;
4411 controls.dampingFactor = 0.08;
4412 controls.target.set(0, 0, 0);
4413 controls.minDistance = maxDim * 0.2;
4414 controls.maxDistance = maxDim * 25;
4415 controls.update();
4416
4417 const resize = () =>
4418 {
4419 const w = Math.max(160, Math.floor(wrap.clientWidth || 0));
4420 const h = Math.max(160, Math.floor((wrap.clientHeight || 0) - (hint.offsetHeight || 0) - 6));
4421 renderer.setSize(w, h, false);
4422 camera.aspect = w / h;
4423 camera.updateProjectionMatrix();
4424 };
4425 resize();
4426
4427 let stop = false;
4428 let rafId = 0;
4429 const frame = () =>
4430 {
4431 if (stop) return;
4432 controls.update();
4433 renderer.render(scene, camera);
4434 rafId = requestAnimationFrame(frame);
4435 };
4436 frame();
4437
4438 const resizeObserver = typeof ResizeObserver === 'function'
4439 ? new ResizeObserver(() => resize())
4440 : null;
4441 if (resizeObserver) resizeObserver.observe(wrap);
4442
4443 STATE.previewCleanup = () =>
4444 {
4445 stop = true;
4446 if (rafId) cancelAnimationFrame(rafId);
4447 if (resizeObserver) resizeObserver.disconnect();
4448 try { controls.dispose(); } catch { /* ignore */ }
4449 try { disposeObject3D(modelRoot); } catch { /* ignore */ }
4450 try { renderer.dispose(); } catch { /* ignore */ }
4451 };
4452}
4453
4454async function renderPreviewBody (item, blob, objectUrl, targetEl = null)
4455{
4456 const body = targetEl || document.getElementById('preview-body');
4457 body.innerHTML = '';
4458
4459 const mime = String(blob.type || '').toLowerCase();
4460 const previewable = isInlinePreviewableBlob(blob, item.name);
4461
4462 if (!previewable)
4463 {
4464 const msg = document.createElement('p');
4465 msg.className = 'preview-unsupported';
4466 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
4467 body.appendChild(msg);
4468 return;
4469 }
4470
4471 if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name)))
4472 {
4473 const img = document.createElement('img');
4474 img.className = 'preview-media';
4475 img.src = objectUrl;
4476 img.alt = item.name;
4477 body.appendChild(img);
4478 return;
4479 }
4480
4481 if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name)))
4482 {
4483 const video = document.createElement('video');
4484 video.className = 'preview-media';
4485 video.src = objectUrl;
4486 video.controls = true;
4487 video.preload = 'metadata';
4488 body.appendChild(video);
4489 return;
4490 }
4491
4492 if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name)))
4493 {
4494 const audio = document.createElement('audio');
4495 audio.className = 'preview-audio';
4496 audio.src = objectUrl;
4497 audio.controls = true;
4498 body.appendChild(audio);
4499 return;
4500 }
4501
4502 if (modelPreviewType(item.name))
4503 {
4504 await renderModelPreview(item, blob, body);
4505 return;
4506 }
4507
4508 if (mime === 'application/pdf')
4509 {
4510 const frame = document.createElement('iframe');
4511 frame.className = 'preview-frame';
4512 frame.src = objectUrl;
4513 frame.title = item.name;
4514 body.appendChild(frame);
4515 return;
4516 }
4517
4518 if (isTextLikeBlob(blob, item.name))
4519 {
4520 const text = await blob.text();
4521 const lang = detectCodeLanguage(item.name, mime);
4522 const formatted = prettyPrintCode(text, lang);
4523 const pre = document.createElement('pre');
4524 pre.className = 'preview-text preview-code';
4525 pre.innerHTML = highlightCode(formatted, lang);
4526 body.appendChild(pre);
4527 return;
4528 }
4529
4530 const msg = document.createElement('p');
4531 msg.className = 'preview-unsupported';
4532 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
4533 body.appendChild(msg);
4534}
4535
4536async function downloadOrView (item, sourceSvgEl = null)
4537{
4538 if (STATE.previewExpandState)
4539 {
4540 await closePreview({ force: true });
4541 }
4542
4543 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
4544 if (sourceTileEl)
4545 {
4546 STATE.previewSourceEl = sourceSvgEl;
4547 const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>
4548 {
4549 if (VIDEO_EXTS.has(extOf(item.name)))
4550 {
4551 clearPreviewObjectUrl();
4552 previewMount.innerHTML = '';
4553 await renderStreamedVideoPreview(item, previewMount);
4554 return;
4555 }
4556
4557 const blob = await fetchFileBlob(item);
4558 if (!blob) throw new Error('Download failed');
4559
4560 clearPreviewObjectUrl();
4561 const objectUrl = URL.createObjectURL(blob);
4562 STATE.previewObjectUrl = objectUrl;
4563
4564 if (!previewMount.isConnected) return;
4565
4566 previewMount.innerHTML = '';
4567 await renderPreviewBody(item, blob, objectUrl, previewMount);
4568 });
4569 if (expanded) return;
4570 }
4571
4572 toast('Preview unavailable — no source tile found.', 'err');
4573}
4574
4575// ───────────────────────────────────────────────────────────────────────────
4576// UPLOAD
4577// ───────────────────────────────────────────────────────────────────────────
4578
4579function canWrite (item = null)
4580{
4581 if (STATE.isAdmin) return true;
4582 const root = item && item._root
4583 ? item._root
4584 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
4585 if (!root) return false;
4586 if (root.isUserFolder) return true;
4587 const p = STATE.permissions[rootPermissionLabel(root)];
4588 return p && p.write;
4589}
4590
4591async function uploadFiles (fileList)
4592{
4593 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4594 if (!canWrite()) { toast('No write access.', 'err'); return; }
4595
4596 const files = Array.from(fileList || []);
4597 if (!files.length) return;
4598
4599 // Show upload bar
4600 const wrap = document.createElement('div');
4601 wrap.className = 'upload-bar-wrap';
4602 wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
4603 document.body.appendChild(wrap);
4604 STATE.uploadInProgress = true;
4605
4606 try
4607 {
4608 const existingNames = await listDirNameSet(STATE.currentDir);
4609 let done = 0;
4610 let uploaded = 0;
4611
4612 for (const original of files)
4613 {
4614 let fileToUpload = original;
4615
4616 if (existingNames.has(original.name))
4617 {
4618 const suggested = nextAvailableName(original.name, existingNames);
4619 const decision = await showFileConflictChoice(original.name, suggested, 'upload');
4620 if (decision === 'cancel')
4621 {
4622 done++;
4623 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
4624 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
4625 continue;
4626 }
4627
4628 if (decision === 'rename')
4629 {
4630 fileToUpload = cloneFileWithName(original, suggested);
4631 }
4632 }
4633
4634 await uploadSingleFile(fileToUpload, STATE.currentDir);
4635 existingNames.add(fileToUpload.name);
4636 done++;
4637 uploaded++;
4638 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
4639 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
4640 }
4641
4642 toast(`Uploaded ${uploaded} file(s).`, 'ok');
4643 await navigateTo(STATE.currentDir, STATE.currentRoot);
4644 } catch (err)
4645 {
4646 toast(err.message, 'err');
4647 } finally
4648 {
4649 STATE.uploadInProgress = false;
4650 wrap.remove();
4651 }
4652}
4653
4654async function uploadSingleFile (file, targetDir)
4655{
4656 const formData = new FormData();
4657 formData.append('files', file);
4658
4659 await new Promise((resolve, reject) =>
4660 {
4661 const xhr = new XMLHttpRequest();
4662 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
4663 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
4664 xhr.setRequestHeader('X-Fp', getFingerprint());
4665 xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
4666 xhr.onload = () => xhr.status === 200
4667 ? resolve()
4668 : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
4669 xhr.onerror = () => reject(new Error('Network error'));
4670 xhr.send(formData);
4671 });
4672}
4673
4674async function ensureServerDir (baseDir, relativeDir)
4675{
4676 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
4677 let current = baseDir;
4678 for (const part of parts)
4679 {
4680 try
4681 {
4682 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
4683 current = resp && resp.path ? resp.path : joinServerPath(current, part);
4684 } catch (err)
4685 {
4686 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
4687 current = joinServerPath(current, part);
4688 }
4689 }
4690 return current;
4691}
4692
4693async function uploadFolderInputFiles (fileList)
4694{
4695 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4696 if (!canWrite()) { toast('No write access.', 'err'); return; }
4697 if (!fileList || !fileList.length) return;
4698
4699 const files = Array.from(fileList);
4700 const total = files.length;
4701 let done = 0;
4702
4703 const wrap = document.createElement('div');
4704 wrap.className = 'upload-bar-wrap';
4705 wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
4706 document.body.appendChild(wrap);
4707 STATE.uploadInProgress = true;
4708
4709 try
4710 {
4711 const dirCache = new Map();
4712 dirCache.set('', STATE.currentDir);
4713
4714 for (const file of files)
4715 {
4716 const rel = file.webkitRelativePath || file.name;
4717 const relParts = rel.split(/[\\/]/).filter(Boolean);
4718 const relDir = relParts.slice(0, -1).join('/');
4719
4720 if (!dirCache.has(relDir))
4721 {
4722 const parentRel = relParts.slice(0, -2).join('/');
4723 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
4724 const thisName = relParts[relParts.length - 2];
4725
4726 try
4727 {
4728 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
4729 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
4730 } catch (err)
4731 {
4732 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
4733 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
4734 }
4735 }
4736
4737 const targetDir = dirCache.get(relDir) || STATE.currentDir;
4738 await uploadSingleFile(file, targetDir);
4739 done++;
4740 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
4741 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
4742 }
4743
4744 toast(`Uploaded ${total} file(s).`, 'ok');
4745 await navigateTo(STATE.currentDir, STATE.currentRoot);
4746 } catch (err)
4747 {
4748 toast(err.message, 'err');
4749 } finally
4750 {
4751 STATE.uploadInProgress = false;
4752 wrap.remove();
4753 }
4754}
4755
4756// ───────────────────────────────────────────────────────────────────────────
4757// FOLDER DRAG-AND-DROP (recursive)
4758// ───────────────────────────────────────────────────────────────────────────
4759
4760/**
4761 * Reads all readEntries batches from a DirectoryReader (browsers may return
4762 * results in chunks; we must keep calling until we get an empty array).
4763 */
4764function readAllEntries (reader)
4765{
4766 return new Promise((resolve, reject) =>
4767 {
4768 const all = [];
4769 function next ()
4770 {
4771 reader.readEntries(batch =>
4772 {
4773 if (!batch.length) { resolve(all); return; }
4774 all.push(...batch);
4775 next();
4776 }, reject);
4777 }
4778 next();
4779 });
4780}
4781
4782/**
4783 * Recursively walk a FileSystemEntry tree, creating server-side directories
4784 * on the fly and collecting { file, targetDir } pairs for upload.
4785 */
4786async function collectEntries (entry, serverDir, toUpload)
4787{
4788 if (entry.isFile)
4789 {
4790 const file = await new Promise((res, rej) => entry.file(res, rej));
4791 toUpload.push({ file, targetDir: serverDir });
4792 } else if (entry.isDirectory)
4793 {
4794 // Ask the server to create the directory; it returns the canonical path.
4795 let newServerDir;
4796 try
4797 {
4798 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
4799 newServerDir = resp.path;
4800 } catch
4801 {
4802 // Directory may already exist — reconstruct path from what we know.
4803 // The server always returns JSON with {error} on failure, so we can
4804 // still continue by falling back to a best-effort path join.
4805 // We rely on the fact that the server separator is consistent within
4806 // a session (the list/browse API already returned paths in that format).
4807 const sep = serverDir.includes('\\') ? '\\' : '/';
4808 newServerDir = serverDir + sep + entry.name;
4809 }
4810 const reader = entry.createReader();
4811 const subEntries = await readAllEntries(reader);
4812 for (const sub of subEntries)
4813 {
4814 await collectEntries(sub, newServerDir, toUpload);
4815 }
4816 }
4817}
4818
4819async function uploadEntries (entries)
4820{
4821 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4822 if (!canWrite()) { toast('No write access.', 'err'); return; }
4823
4824 const wrap = document.createElement('div');
4825 wrap.className = 'upload-bar-wrap';
4826 wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
4827 document.body.appendChild(wrap);
4828 STATE.uploadInProgress = true;
4829
4830 try
4831 {
4832 const toUpload = [];
4833 for (const entry of entries)
4834 {
4835 await collectEntries(entry, STATE.currentDir, toUpload);
4836 }
4837
4838 if (!toUpload.length) { toast('No files found.', 'err'); return; }
4839
4840 let done = 0;
4841 const total = toUpload.length;
4842 const updateBar = () =>
4843 {
4844 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
4845 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
4846 };
4847 updateBar();
4848
4849 for (const { file, targetDir } of toUpload)
4850 {
4851 await uploadSingleFile(file, targetDir);
4852 done++;
4853 updateBar();
4854 }
4855
4856 toast(`Uploaded ${total} file(s).`, 'ok');
4857 await navigateTo(STATE.currentDir, STATE.currentRoot);
4858 } catch (err)
4859 {
4860 toast(err.message, 'err');
4861 } finally
4862 {
4863 STATE.uploadInProgress = false;
4864 wrap.remove();
4865 }
4866}
4867
4868// DRAG-AND-DROP
4869// ───────────────────────────────────────────────────────────────────────────
4870
4871function initDragDrop ()
4872{
4873 const main = document.getElementById('main-content');
4874 const dropOvl = document.getElementById('drop-overlay');
4875 let dragDepth = 0;
4876
4877 main.addEventListener('dragenter', e =>
4878 {
4879 e.preventDefault();
4880 dragDepth++;
4881 dropOvl.classList.remove('hidden');
4882 });
4883 main.addEventListener('dragleave', () =>
4884 {
4885 dragDepth--;
4886 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
4887 });
4888 main.addEventListener('dragover', e => e.preventDefault());
4889 main.addEventListener('drop', async e =>
4890 {
4891 e.preventDefault();
4892 dragDepth = 0;
4893 dropOvl.classList.add('hidden');
4894 if (!canWrite()) { toast('No write access.', 'err'); return; }
4895
4896 const items = Array.from(e.dataTransfer.items || []);
4897 // Use the FileSystem Entry API when available so we can handle folders.
4898 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
4899 {
4900 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
4901 if (entries.some(en => en.isDirectory))
4902 {
4903 await uploadEntries(entries);
4904 return;
4905 }
4906 }
4907 // Plain files only — use the fast batch path.
4908 const files = e.dataTransfer.files;
4909 if (files.length) await uploadFiles(files);
4910 });
4911}
4912
4913// ───────────────────────────────────────────────────────────────────────────
4914// RENAME
4915// ───────────────────────────────────────────────────────────────────────────
4916
4917function openRenameModal (item)
4918{
4919 const modal = document.getElementById('rename-modal');
4920 modal.classList.remove('hidden');
4921 const input = document.getElementById('rename-input');
4922 input.value = item.name;
4923 input.focus();
4924 input.select();
4925 document.getElementById('rename-error').classList.add('hidden');
4926 document.getElementById('rename-form').onsubmit = async (e) =>
4927 {
4928 e.preventDefault();
4929 const newName = input.value.trim();
4930 if (!newName) return;
4931 try
4932 {
4933 if (item._root)
4934 {
4935 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
4936 } else
4937 {
4938 await api('POST', '/files/rename', { from: item.path, to: newName });
4939 }
4940 modal.classList.add('hidden');
4941 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
4942 if (item._root)
4943 {
4944 await loadRoots({
4945 preferredDir: STATE.currentDir,
4946 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
4947 });
4948 } else
4949 {
4950 await navigateTo(STATE.currentDir, STATE.currentRoot);
4951 }
4952 } catch (err)
4953 {
4954 document.getElementById('rename-error').textContent = err.message;
4955 document.getElementById('rename-error').classList.remove('hidden');
4956 }
4957 };
4958}
4959
4960// ───────────────────────────────────────────────────────────────────────────
4961// DELETE
4962// ───────────────────────────────────────────────────────────────────────────
4963
4964async function deleteItem (item)
4965{
4966 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
4967 try
4968 {
4969 await api('POST', '/files/delete', { path: item.path });
4970 toast('Deleted.', 'ok');
4971 closeSidebar();
4972 await navigateTo(STATE.currentDir, STATE.currentRoot);
4973 } catch (err)
4974 {
4975 toast(err.message, 'err');
4976 }
4977}
4978
4979// ───────────────────────────────────────────────────────────────────────────
4980// ADMIN PANEL
4981// ───────────────────────────────────────────────────────────────────────────
4982
4983let _adminUpdateStatus = null;
4984
4985function animateBadgeToTarget (targetEl)
4986{
4987 const badge = document.getElementById('admin-update-badge');
4988 if (!badge || !targetEl) return;
4989 if (badge.parentElement === targetEl) return;
4990
4991 const from = badge.getBoundingClientRect();
4992 targetEl.appendChild(badge);
4993 const to = badge.getBoundingClientRect();
4994
4995 const dx = from.left - to.left;
4996 const dy = from.top - to.top;
4997
4998 badge.style.transition = 'none';
4999 badge.style.transform = `translate(${dx}px, ${dy}px)`;
5000 badge.style.willChange = 'transform';
5001
5002 requestAnimationFrame(() =>
5003 {
5004 badge.style.transition = 'transform 240ms cubic-bezier(0.22, 1, 0.36, 1)';
5005 badge.style.transform = 'translate(0, 0)';
5006 });
5007
5008 const cleanup = () =>
5009 {
5010 badge.style.transition = '';
5011 badge.style.transform = '';
5012 badge.style.willChange = '';
5013 badge.removeEventListener('transitionend', cleanup);
5014 };
5015 badge.addEventListener('transitionend', cleanup);
5016}
5017
5018function moveBadgeToTarget (targetEl)
5019{
5020 const badge = document.getElementById('admin-update-badge');
5021 if (!badge || !targetEl) return;
5022 if (badge.parentElement === targetEl) return;
5023
5024 badge.style.transition = '';
5025 badge.style.transform = '';
5026 badge.style.willChange = '';
5027 targetEl.appendChild(badge);
5028}
5029
5030function syncAdminUpdateBadgeAnchor ({ animate = true, forceUserAnchor = false } = {})
5031{
5032 const badge = document.getElementById('admin-update-badge');
5033 const userMenuBtn = document.getElementById('btn-user-menu');
5034 const adminBtn = document.getElementById('btn-admin');
5035 if (!badge || !userMenuBtn || !adminBtn) return;
5036
5037 const userDropdown = userMenuBtn.closest('.topbar-dropdown');
5038 const userMenuOpen = !!(userDropdown && userDropdown.classList.contains('open'));
5039 const target = forceUserAnchor ? userMenuBtn : (userMenuOpen ? adminBtn : userMenuBtn);
5040
5041 if (badge.classList.contains('hidden'))
5042 {
5043 moveBadgeToTarget(userMenuBtn);
5044 return;
5045 }
5046
5047 if (animate) animateBadgeToTarget(target);
5048 else moveBadgeToTarget(target);
5049}
5050
5051function setAdminUpdateBadge (count)
5052{
5053 const badge = document.getElementById('admin-update-badge');
5054 const userMenuBtn = document.getElementById('btn-user-menu');
5055 if (!badge || !userMenuBtn) return;
5056
5057 if (!STATE.isAdmin || !Number.isFinite(count) || count <= 0)
5058 {
5059 badge.classList.add('hidden');
5060 badge.textContent = '';
5061 if (badge.parentElement !== userMenuBtn) userMenuBtn.appendChild(badge);
5062 userMenuBtn.removeAttribute('data-update-count');
5063 return;
5064 }
5065
5066 const whole = Math.floor(count);
5067 const capped = Math.min(whole, 99);
5068 badge.textContent = capped >= 99 ? '99+' : String(capped);
5069 badge.classList.remove('hidden');
5070 userMenuBtn.dataset.updateCount = String(whole);
5071 syncAdminUpdateBadgeAnchor();
5072}
5073
5074function pulseAdminUpdateButton ()
5075{
5076 const btn = document.getElementById('admin-shutdown-btn');
5077 if (!btn) return;
5078
5079 if (typeof btn.scrollIntoView === 'function')
5080 {
5081 btn.scrollIntoView({ behavior: 'smooth', block: 'center' });
5082 }
5083
5084 btn.classList.remove('admin-update-highlight');
5085 // Force reflow so repeated openings can replay the pulse animation.
5086 void btn.offsetWidth;
5087 btn.classList.add('admin-update-highlight');
5088
5089 setTimeout(() =>
5090 {
5091 btn.classList.remove('admin-update-highlight');
5092 }, 1800);
5093}
5094
5095async function openAdminModal ()
5096{
5097 document.getElementById('admin-modal').classList.remove('hidden');
5098 await refreshGlobalFavicon();
5099 await refreshAdminConfig();
5100 await refreshAdminUsers();
5101 await refreshAdminUpdateStatus({ pulseIfUpdateAvailable: true });
5102}
5103
5104async function refreshAdminConfig ()
5105{
5106 const data = await api('GET', '/admin/config');
5107 if (!data) return;
5108
5109 const userPathInput = document.getElementById('admin-user-path');
5110 const sizeInput = document.getElementById('admin-user-size-limit');
5111 if (userPathInput) userPathInput.value = data.userPath || '';
5112 if (sizeInput)
5113 {
5114 sizeInput.value = data.userFolderSizeLimit ? formatBytes(data.userFolderSizeLimit) : '';
5115 updateAdminSizeFeedback(sizeInput.value);
5116 }
5117
5118 const container = document.getElementById('admin-paths');
5119 container.innerHTML = '';
5120 for (const p of data.paths)
5121 {
5122 const row = document.createElement('div');
5123 row.className = 'path-row';
5124 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
5125 row.querySelector('button').addEventListener('click', () =>
5126 {
5127 row.remove();
5128 });
5129 container.appendChild(row);
5130 }
5131}
5132
5133async function refreshAdminUsers ()
5134{
5135 const data = await api('GET', '/admin/users');
5136 if (!data) return;
5137 const container = document.getElementById('admin-users-list');
5138 container.innerHTML = '';
5139
5140 // Need paths for permission rows
5141 const cfg = await api('GET', '/admin/config');
5142 const paths = cfg ? (cfg.effectivePaths || []) : [];
5143
5144 for (const u of data.users)
5145 {
5146 const row = document.createElement('div');
5147 row.className = 'user-row';
5148 row.innerHTML = `
5149 <span class="user-name">${u.username}</span>
5150 ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''}
5151 <button data-id="${u.id}" data-action="edit">Edit</button>
5152 ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`}
5153 `;
5154 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
5155 openUserModal(u, paths));
5156 const deleteBtn = row.querySelector('[data-action="delete"]');
5157 if (deleteBtn) deleteBtn.addEventListener('click', async () =>
5158 {
5159 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
5160 try
5161 {
5162 await api('DELETE', `/admin/users/${u.id}`);
5163 toast('User deleted.', 'ok');
5164 await refreshAdminUsers();
5165 } catch (err) { toast(err.message, 'err'); }
5166 });
5167 container.appendChild(row);
5168 }
5169}
5170
5171async function refreshAdminUpdateStatus (opts = {})
5172{
5173 const pulseIfUpdateAvailable = !!opts.pulseIfUpdateAvailable;
5174 const btn = document.getElementById('admin-shutdown-btn');
5175 _adminUpdateStatus = null;
5176 btn.textContent = 'Shut down server';
5177 setAdminUpdateBadge(0);
5178
5179 try
5180 {
5181 const data = await api('GET', '/admin/update-status');
5182 if (!data) return;
5183 _adminUpdateStatus = data;
5184
5185 const updateCount = (data.underSystemd && Array.isArray(data.commitsAhead))
5186 ? data.commitsAhead.length
5187 : 0;
5188 setAdminUpdateBadge(updateCount);
5189
5190 if (!data.underSystemd)
5191 {
5192 btn.textContent = 'Shut down server';
5193 }
5194 else if (data.commitsAhead.length === 0)
5195 {
5196 btn.textContent = 'Restart Server';
5197 }
5198 else
5199 {
5200 btn.textContent = 'Restart & Update';
5201 if (pulseIfUpdateAvailable) pulseAdminUpdateButton();
5202 }
5203 }
5204 catch
5205 {
5206 // Not critical; button stays as "Shut down server".
5207 }
5208}
5209
5210function openUserModal (user, paths)
5211{
5212 const modal = document.getElementById('user-modal');
5213 modal.classList.remove('hidden');
5214 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
5215 document.getElementById('user-error').classList.add('hidden');
5216
5217 const usernameInput = document.getElementById('user-username');
5218 usernameInput.value = user ? user.username : '';
5219 usernameInput.readOnly = !!user;
5220
5221 document.getElementById('user-password').value = '';
5222 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
5223
5224 // Password placeholder
5225 document.getElementById('user-password').placeholder =
5226 user ? 'Leave blank to keep current' : 'Min 8 characters';
5227
5228 // Build permissions grid
5229 const permDiv = document.getElementById('user-permissions');
5230 permDiv.innerHTML = '';
5231 if (paths.length)
5232 {
5233 const heading = document.createElement('h4');
5234 heading.textContent = 'Path Permissions';
5235 permDiv.appendChild(heading);
5236
5237 const isAdminUser = !!(user && user.isAdmin);
5238 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
5239 const adminChk = document.getElementById('user-is-admin');
5240 const rebuildPermRows = (admin) =>
5241 {
5242 permDiv.querySelectorAll('.perm-row').forEach(r =>
5243 {
5244 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
5245 {
5246 cb.disabled = admin;
5247 if (admin) cb.checked = true;
5248 });
5249 r.title = admin ? 'Admins always have full access' : '';
5250 });
5251 };
5252 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
5253
5254 const syncReadWriteConstraints = (row, admin = false) =>
5255 {
5256 const readCb = row.querySelector('input[data-type="read"]');
5257 const writeCb = row.querySelector('input[data-type="write"]');
5258 if (!readCb || !writeCb) return;
5259
5260 if (admin)
5261 {
5262 readCb.checked = true;
5263 writeCb.checked = true;
5264 readCb.disabled = true;
5265 writeCb.disabled = true;
5266 return;
5267 }
5268
5269 readCb.disabled = false;
5270 if (!readCb.checked)
5271 {
5272 writeCb.checked = false;
5273 writeCb.disabled = true;
5274 }
5275 else
5276 {
5277 writeCb.disabled = false;
5278 }
5279 };
5280
5281 const syncAllReadWriteConstraints = () =>
5282 {
5283 const admin = adminChk.checked;
5284 permDiv.querySelectorAll('.perm-row').forEach((row) =>
5285 {
5286 syncReadWriteConstraints(row, admin);
5287 });
5288 };
5289
5290 for (const p of paths)
5291 {
5292 const label = p.split(/[\\/]/).pop();
5293 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
5294 const row = document.createElement('div');
5295 row.className = 'perm-row';
5296 const readChecked = isAdminUser || perms.read;
5297 const writeChecked = isAdminUser || perms.write;
5298 row.innerHTML = `
5299 <span class="perm-label">${label}</span>
5300 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label>
5301 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label>
5302 `;
5303 if (isAdminUser) row.title = 'Admins always have full access';
5304 const readCb = row.querySelector('input[data-type="read"]');
5305 if (readCb)
5306 {
5307 readCb.addEventListener('change', () =>
5308 {
5309 syncReadWriteConstraints(row, adminChk.checked);
5310 });
5311 }
5312 permDiv.appendChild(row);
5313 }
5314
5315 syncAllReadWriteConstraints();
5316 adminChk.addEventListener('change', syncAllReadWriteConstraints);
5317 }
5318
5319 document.getElementById('user-form').onsubmit = async (e) =>
5320 {
5321 e.preventDefault();
5322 const password = document.getElementById('user-password').value;
5323 const isAdmin = document.getElementById('user-is-admin').checked;
5324 const permissions = {};
5325 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
5326 {
5327 const lbl = cb.dataset.label;
5328 if (!permissions[lbl]) permissions[lbl] = {};
5329 permissions[lbl][cb.dataset.type] = cb.checked;
5330 });
5331
5332 try
5333 {
5334 if (user)
5335 {
5336 const body = { isAdmin, permissions };
5337 if (password) body.password = password;
5338 await api('PATCH', `/admin/users/${user.id}`, body);
5339 } else
5340 {
5341 const uname = document.getElementById('user-username').value.trim();
5342 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
5343 }
5344 modal.classList.add('hidden');
5345 toast('User saved.', 'ok');
5346 await refreshAdminUsers();
5347 } catch (err)
5348 {
5349 document.getElementById('user-error').textContent = err.message;
5350 document.getElementById('user-error').classList.remove('hidden');
5351 }
5352 };
5353}
5354
5355// ───────────────────────────────────────────────────────────────────────────
5356// SVG ICONS
5357// ───────────────────────────────────────────────────────────────────────────
5358
5359const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
5360const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
5361const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
5362const MODEL_EXTS = new Set(['stl', 'obj']);
5363const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
5364const CODE_EXTS = new Set(['js', 'ts', 'py', 'rb', 'go', 'rs', 'c', 'cpp', 'h', 'cs', 'java', 'php', 'html', 'css', 'json', 'xml', 'yaml', 'yml', 'sh', 'bash', 'md', 'txt']);
5365const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
5366const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024;
5367
5368function iconFolder (size = 52)
5369{
5370 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
5371 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
5372 <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
5373 </svg>`;
5374}
5375
5376function iconFile (name, size = 52)
5377{
5378 const color = fileAccentColor(name);
5379 let symbol = '';
5380
5381 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
5382 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
5383 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
5384 <polyline points="14 2 14 8 20 8"/>
5385 </svg>`;
5386}
5387
5388function watchStatusForTile (item)
5389{
5390 if (!item || item.isDir) return null;
5391 if (!VIDEO_EXTS.has(extOf(item.name || ''))) return null;
5392
5393 const cached = STATE.watchedStatusByPath[item.path];
5394 if (cached === 'fully' || cached === 'partway') return cached;
5395
5396 const currentUser = String(STATE.username || '').trim();
5397 if (!currentUser) return null;
5398
5399 const watchedBy = item.watchedBy && typeof item.watchedBy === 'object' ? item.watchedBy : {};
5400 const statusRaw = watchedBy[currentUser];
5401 const status = String(statusRaw || '').toLowerCase();
5402 if (status === 'fully' || status === 'partway') return status;
5403 return null;
5404}
5405
5406function renderWatchedOverlayOnIcon (iconEl, watchStatus)
5407{
5408 if (!iconEl) return;
5409
5410 const existing = iconEl.querySelector('.watched-overlay');
5411 if (existing) existing.remove();
5412 if (watchStatus !== 'fully' && watchStatus !== 'partway') return;
5413
5414 const overlay = document.createElement('div');
5415 overlay.className = `watched-overlay watched-overlay--${watchStatus}`;
5416 overlay.innerHTML = watchedEyeFilledSvg();
5417 iconEl.appendChild(overlay);
5418}
5419
5420function findTileIconByPath (filePath)
5421{
5422 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return null;
5423 const tile = Array.from(document.querySelectorAll('.file-item')).find((el) => el.dataset.path === filePath);
5424 if (!tile) return null;
5425 return tile.querySelector('.icon');
5426}
5427
5428function watchStatusFromWatchedBy (watchedBy)
5429{
5430 const currentUser = String(STATE.username || '').trim();
5431 if (!currentUser) return null;
5432
5433 const map = watchedBy && typeof watchedBy === 'object' ? watchedBy : {};
5434 const statusRaw = map[currentUser];
5435 const status = String(statusRaw || '').toLowerCase();
5436 if (status === 'fully' || status === 'partway') return status;
5437 return null;
5438}
5439
5440async function loadWatchedStatusesForCurrentDir ()
5441{
5442 const dirAtStart = STATE.currentDir;
5443 if (!dirAtStart) return;
5444
5445 const videoItems = (STATE.items || []).filter((item) =>
5446 item && !item.isDir && VIDEO_EXTS.has(extOf(item.name || ''))
5447 );
5448 if (!videoItems.length) return;
5449
5450 const loadId = ++STATE.watchedLoadId;
5451
5452 let statusMap = null;
5453 const filePaths = videoItems.map((item) => item.path);
5454
5455 const bulk = await api('POST', '/files/watched-statuses', { filePaths }).catch(() => null);
5456 if (bulk && bulk.statuses && typeof bulk.statuses === 'object')
5457 {
5458 statusMap = {};
5459 for (const item of videoItems)
5460 {
5461 const status = String(bulk.statuses[item.path] || '').toLowerCase();
5462 statusMap[item.path] = status === 'fully' || status === 'partway' ? status : null;
5463 }
5464 }
5465
5466 // Compatibility fallback for older servers that do not expose bulk statuses yet.
5467 if (!statusMap)
5468 {
5469 statusMap = {};
5470 const statuses = await Promise.all(videoItems.map(async (item) =>
5471 {
5472 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`).catch(() => null);
5473 return {
5474 path: item.path,
5475 status: watchStatusFromWatchedBy(meta && meta.watchedBy),
5476 };
5477 }));
5478
5479 for (const entry of statuses)
5480 {
5481 statusMap[entry.path] = entry.status;
5482 }
5483 }
5484
5485 if (loadId !== STATE.watchedLoadId) return;
5486 if (!samePath(STATE.currentDir, dirAtStart)) return;
5487 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
5488
5489 for (const item of videoItems)
5490 {
5491 const status = statusMap[item.path] || null;
5492 if (status) STATE.watchedStatusByPath[item.path] = status;
5493 else delete STATE.watchedStatusByPath[item.path];
5494
5495 const iconEl = findTileIconByPath(item.path);
5496 renderWatchedOverlayOnIcon(iconEl, status);
5497 }
5498}
5499
5500function watchedEyeFilledSvg ()
5501{
5502 return `<svg class="watched-overlay-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path fill="#ffffff" d="M651.669528 512c0-14.5903-2.084475-28.290323-6.251378-41.395806-11.019984 24.423249-35.143405 41.395806-63.733557 41.395806l-7.440459-0.593518-5.957689 0.593518c-30.973432 0-56.285934-25.607214-56.285934-56.882522l0.297782-5.952572-0.297782-7.447623c0-28.290323 16.97665-52.709479 41.097-63.727417-13.104459-4.172019-26.802436-6.252401-41.097-6.252401-77.132728 0-139.67311 62.834071-139.67311 140.263557 0 77.428464 62.540382 139.971915 139.67311 139.971915S651.669528 589.428464 651.669528 512L651.669528 512zM958.70846 512c0 0-153.36904-297.80564-448.198905-297.80564-293.63669 0-445.219037 297.80564-445.219037 297.80564s164.385954 297.804616 447.306582 297.804616C805.038568 809.80564 958.70846 512 958.70846 512L958.70846 512zM304.725748 512c0-114.954125 92.619444-208.164017 207.27374-208.164017 114.657366 0 207.27067 93.209892 207.27067 208.164017 0 114.953102-92.613304 208.167087-207.27067 208.167087C397.345192 720.167087 304.725748 626.953102 304.725748 512L304.725748 512zM304.725748 512"/></svg>`;
5503}
5504
5505// ───────────────────────────────────────────────────────────────────────────
5506// EVENT WIRING
5507// ───────────────────────────────────────────────────────────────────────────
5508
5509// ───────────────────────────────────────────────────────────────────────────
5510// THUMBNAIL PREVIEWS
5511// ───────────────────────────────────────────────────────────────────────────
5512
5513function revokeThumbnails ()
5514{
5515 STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u));
5516 STATE.thumbnailUrls = [];
5517}
5518
5519function disconnectThumbnailObserver ()
5520{
5521 if (!STATE.thumbnailObserver) return;
5522 STATE.thumbnailObserver.disconnect();
5523 STATE.thumbnailObserver = null;
5524}
5525
5526function disconnectFolderIconObserver ()
5527{
5528 if (!STATE.folderIconObserver) return;
5529 STATE.folderIconObserver.disconnect();
5530 STATE.folderIconObserver = null;
5531}
5532
5533function setThumbnailPending (iconEl, pending)
5534{
5535 if (!iconEl) return;
5536 if (pending)
5537 {
5538 iconEl.classList.add('thumb-pending');
5539 iconEl.dataset.thumbPending = '1';
5540 return;
5541 }
5542
5543 iconEl.classList.remove('thumb-pending');
5544 delete iconEl.dataset.thumbPending;
5545}
5546
5547function getThumbnailKind (name)
5548{
5549 const ext = extOf(name || '');
5550 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || MODEL_EXTS.has(ext)) return 'image';
5551 if (CODE_EXTS.has(ext)) return 'text';
5552 return 'badge';
5553}
5554
5555function maxThumbBytesForKind (kind)
5556{
5557 if (kind === 'image') return 15 * 1024 * 1024;
5558 if (kind === 'text') return 1024 * 1024;
5559 return 0;
5560}
5561
5562function drawTokenizedLine (ctx, line, x, y)
5563{
5564 const tokenRe = /(\/\/.*$|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\b(?:function|return|if|else|for|while|switch|case|break|continue|const|let|var|class|new|import|from|export|default|try|catch|finally|throw|await|async|true|false|null|undefined)\b|\b\d+(?:\.\d+)?\b)/g;
5565 let last = 0;
5566 let cursor = x;
5567 for (const m of line.matchAll(tokenRe))
5568 {
5569 const i = m.index == null ? 0 : m.index;
5570 if (i > last)
5571 {
5572 const plain = line.slice(last, i);
5573 ctx.fillStyle = '#dce4ff';
5574 ctx.fillText(plain, cursor, y);
5575 cursor += ctx.measureText(plain).width;
5576 }
5577
5578 const tok = m[0];
5579 if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a';
5580 else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d';
5581 else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a';
5582 else ctx.fillStyle = '#8bb4ff';
5583
5584 ctx.fillText(tok, cursor, y);
5585 cursor += ctx.measureText(tok).width;
5586 last = i + tok.length;
5587 }
5588
5589 if (last < line.length)
5590 {
5591 const tail = line.slice(last);
5592 ctx.fillStyle = '#dce4ff';
5593 ctx.fillText(tail, cursor, y);
5594 }
5595}
5596
5597function textThumbnailDataUrl (text)
5598{
5599 const canvas = document.createElement('canvas');
5600 canvas.width = 160;
5601 canvas.height = 200;
5602 const ctx = canvas.getContext('2d');
5603 if (!ctx) return null;
5604
5605 ctx.fillStyle = '#0d111a';
5606 ctx.fillRect(0, 0, canvas.width, canvas.height);
5607 ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
5608 ctx.textBaseline = 'top';
5609
5610 const lines = String(text || '')
5611 .replace(/\r\n/g, '\n')
5612 .split('\n')
5613 .slice(0, 17);
5614
5615 let y = 8;
5616 for (const line of lines)
5617 {
5618 drawTokenizedLine(ctx, line.slice(0, 42), 6, y);
5619 y += 11;
5620 if (y > 190) break;
5621 }
5622 return canvas.toDataURL('image/png');
5623}
5624
5625function badgeThumbnailDataUrl (name, kind)
5626{
5627 const canvas = document.createElement('canvas');
5628 canvas.width = 160;
5629 canvas.height = 200;
5630 const ctx = canvas.getContext('2d');
5631 if (!ctx) return null;
5632
5633 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
5634 const color = '#5b7fff';
5635
5636 ctx.fillStyle = '#111826';
5637 ctx.fillRect(0, 0, 160, 200);
5638 ctx.fillStyle = color;
5639 ctx.fillRect(0, 0, 160, 28);
5640 ctx.fillStyle = '#ffffff';
5641 ctx.font = 'bold 12px sans-serif';
5642 ctx.textAlign = 'center';
5643 ctx.fillText(ext, 80, 8);
5644 ctx.textAlign = 'left';
5645 ctx.fillStyle = '#9fb1d8';
5646 ctx.font = '10px sans-serif';
5647 ctx.fillText('Preview', 8, 48);
5648 ctx.fillStyle = '#dce4ff';
5649 ctx.font = 'bold 11px sans-serif';
5650 ctx.fillText(ext, 8, 66);
5651 return canvas.toDataURL('image/png');
5652}
5653
5654async function buildThumbnailSource (item, blob, kind)
5655{
5656 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
5657 return badgeThumbnailDataUrl(item.name, kind);
5658}
5659
5660function observeThumbnailIcon (iconEl)
5661{
5662 if (!iconEl || !iconEl.isConnected) return;
5663 if (iconEl.dataset.thumbReady === '1') return;
5664
5665 if (!('IntersectionObserver' in window))
5666 {
5667 void loadOneThumbnail(iconEl);
5668 return;
5669 }
5670
5671 if (!STATE.thumbnailObserver)
5672 {
5673 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
5674 {
5675 for (const entry of entries)
5676 {
5677 if (!entry.isIntersecting) continue;
5678 const icon = entry.target;
5679 STATE.thumbnailObserver.unobserve(icon);
5680 void loadOneThumbnail(icon);
5681 }
5682 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
5683 }
5684
5685 STATE.thumbnailObserver.observe(iconEl);
5686}
5687
5688async function loadThumbnails ()
5689{
5690 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
5691 for (const icon of icons)
5692 {
5693 observeThumbnailIcon(icon);
5694 }
5695
5696 const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]'));
5697 for (const icon of folderIcons)
5698 {
5699 observeFolderIcon(icon);
5700 }
5701}
5702
5703async function loadOneThumbnail (iconEl)
5704{
5705 if (!iconEl.isConnected || !STATE.token) return;
5706 if (iconEl.dataset.thumbReady === '1') return;
5707 const filePath = iconEl.dataset.previewPath;
5708 const item = STATE.items.find(i => i.path === filePath);
5709 if (!item) return;
5710
5711 const kind = getThumbnailKind(item.name);
5712 let srcUrl = null;
5713
5714 if (kind === 'badge')
5715 {
5716 setThumbnailPending(iconEl, false);
5717 srcUrl = badgeThumbnailDataUrl(item.name, kind);
5718 }
5719 else if (kind === 'image')
5720 {
5721 const ext = extOf(item.name || '');
5722 const useDirectSource =
5723 ext === 'ico' ||
5724 (
5725 ext === 'svg' &&
5726 typeof item.size === 'number' &&
5727 item.size > 0 &&
5728 item.size <= MAX_DIRECT_SVG_THUMB_BYTES
5729 );
5730
5731 const url = useDirectSource
5732 ? `/api/files/download?file=${encodeURIComponent(filePath)}`
5733 : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
5734
5735 let res;
5736 try
5737 {
5738 res = await fetch(url, {
5739 headers: {
5740 Authorization: `Bearer ${STATE.token}`,
5741 'X-Fp': getFingerprint(),
5742 },
5743 });
5744 } catch
5745 {
5746 return;
5747 }
5748
5749 if (!useDirectSource && res.status === 404)
5750 {
5751 setThumbnailPending(iconEl, true);
5752 return;
5753 }
5754
5755 if (!res.ok || !iconEl.isConnected) return;
5756 setThumbnailPending(iconEl, false);
5757
5758 const blob = await res.blob();
5759 srcUrl = URL.createObjectURL(blob);
5760 STATE.thumbnailUrls.push(srcUrl);
5761 }
5762 else
5763 {
5764 setThumbnailPending(iconEl, false);
5765 const maxBytes = maxThumbBytesForKind(kind);
5766 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
5767 {
5768 srcUrl = badgeThumbnailDataUrl(item.name, kind);
5769 } else
5770 {
5771 const url = `/api/files/download?file=${encodeURIComponent(filePath)}`;
5772
5773 let res;
5774 try
5775 {
5776 res = await fetch(url, {
5777 headers: {
5778 Authorization: `Bearer ${STATE.token}`,
5779 'X-Fp': getFingerprint(),
5780 },
5781 });
5782 } catch { return; }
5783 if (!res.ok || !iconEl.isConnected) return;
5784
5785 const blob = await res.blob();
5786 srcUrl = await buildThumbnailSource(item, blob, kind);
5787 }
5788 }
5789 if (!srcUrl || !iconEl.isConnected) return;
5790
5791 const svg = iconEl.querySelector('svg');
5792 if (!svg)
5793 {
5794 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
5795 return;
5796 }
5797
5798 const NS = 'http://www.w3.org/2000/svg';
5799 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
5800
5801 // clipPath matches the main file body outline exactly (viewBox 0 0 24 24)
5802 const defs = document.createElementNS(NS, 'defs');
5803 const clipPath = document.createElementNS(NS, 'clipPath');
5804 clipPath.setAttribute('id', id);
5805 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
5806 const clipShape = document.createElementNS(NS, 'path');
5807 clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z');
5808 clipPath.appendChild(clipShape);
5809 defs.appendChild(clipPath);
5810
5811 // Image fills the file bounding box; clip keeps it inside the outline
5812 const img = document.createElementNS(NS, 'image');
5813 img.setAttribute('href', srcUrl);
5814 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
5815 img.setAttribute('x', '4');
5816 img.setAttribute('y', '2');
5817 img.setAttribute('width', '16');
5818 img.setAttribute('height', '20');
5819 img.setAttribute('clip-path', `url(#${id})`);
5820 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
5821
5822 // Prepend so existing path/polyline elements (the outline) render on top
5823 svg.prepend(img);
5824 svg.prepend(defs);
5825 iconEl.dataset.thumbReady = '1';
5826}
5827
5828// ───────────────────────────────────────────────────────────────────────────
5829// FOLDER ICON THUMBNAILS
5830// ───────────────────────────────────────────────────────────────────────────
5831
5832function observeFolderIcon (iconEl)
5833{
5834 if (!iconEl || !iconEl.isConnected) return;
5835 if (iconEl.dataset.thumbReady === '1') return;
5836
5837 if (!('IntersectionObserver' in window))
5838 {
5839 void loadOneFolderIcon(iconEl);
5840 return;
5841 }
5842
5843 if (!STATE.folderIconObserver)
5844 {
5845 STATE.folderIconObserver = new IntersectionObserver((entries) =>
5846 {
5847 for (const entry of entries)
5848 {
5849 if (!entry.isIntersecting) continue;
5850 const icon = entry.target;
5851 STATE.folderIconObserver.unobserve(icon);
5852 void loadOneFolderIcon(icon);
5853 }
5854 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
5855 }
5856
5857 STATE.folderIconObserver.observe(iconEl);
5858}
5859
5860async function loadOneFolderIcon (iconEl)
5861{
5862 if (!iconEl.isConnected || !STATE.token) return;
5863 if (iconEl.dataset.thumbReady === '1') return;
5864
5865 const folderPath = iconEl.dataset.folderPath;
5866 if (!folderPath) return;
5867
5868 let res;
5869 try
5870 {
5871 res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, {
5872 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
5873 });
5874 } catch { return; }
5875
5876 if (!res.ok || !iconEl.isConnected) return;
5877
5878 const data = await res.json();
5879 if (!data.icon) return; // No icon available — keep plain folder SVG.
5880
5881 // Fetch the thumbnail through the auth-gated endpoint.
5882 let thumbRes;
5883 try
5884 {
5885 thumbRes = await fetch(
5886 `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`,
5887 { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } },
5888 );
5889 } catch { return; }
5890
5891 if (!thumbRes.ok || !iconEl.isConnected) return;
5892
5893 const blob = await thumbRes.blob();
5894 const srcUrl = URL.createObjectURL(blob);
5895 STATE.thumbnailUrls.push(srcUrl);
5896
5897 applyFolderThumbnail(iconEl, srcUrl);
5898}
5899
5900/**
5901 * Overlays a thumbnail image inside the folder SVG outline.
5902 * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21.
5903 */
5904function applyFolderThumbnail (iconEl, srcUrl)
5905{
5906 if (!iconEl.isConnected) return;
5907 const svg = iconEl.querySelector('svg');
5908 if (!svg)
5909 {
5910 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
5911 return;
5912 }
5913
5914 const NS = 'http://www.w3.org/2000/svg';
5915 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
5916
5917 const defs = document.createElementNS(NS, 'defs');
5918 const clipPath = document.createElementNS(NS, 'clipPath');
5919 clipPath.setAttribute('id', id);
5920 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
5921 const clipShape = document.createElementNS(NS, 'path');
5922 // Folder outline path (same as iconFolder SVG path)
5923 clipShape.setAttribute('d', 'M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z');
5924 clipPath.appendChild(clipShape);
5925 defs.appendChild(clipPath);
5926
5927 // Image covers the folder body area; clip keeps it inside the outline.
5928 const img = document.createElementNS(NS, 'image');
5929 img.setAttribute('href', srcUrl);
5930 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
5931 img.setAttribute('x', '2');
5932 img.setAttribute('y', '3');
5933 img.setAttribute('width', '20');
5934 img.setAttribute('height', '18');
5935 img.setAttribute('clip-path', `url(#${id})`);
5936 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
5937
5938 // Prepend so the folder outline strokes render on top.
5939 svg.prepend(img);
5940 svg.prepend(defs);
5941 iconEl.dataset.thumbReady = '1';
5942}
5943
5944function closeTopbarDropdowns ()
5945{
5946 // Prevent jump-to-(0,0) glitches by snapping badge back before the menu is hidden.
5947 syncAdminUpdateBadgeAnchor({ animate: false, forceUserAnchor: true });
5948
5949 document.querySelectorAll('.topbar-dropdown.open').forEach((dropdown) =>
5950 {
5951 dropdown.classList.remove('open');
5952 const trigger = dropdown.querySelector('button[aria-expanded]');
5953 if (trigger) trigger.setAttribute('aria-expanded', 'false');
5954 });
5955}
5956
5957function initTopbarDropdowns ()
5958{
5959 document.querySelectorAll('.topbar-dropdown').forEach((dropdown) =>
5960 {
5961 const trigger = dropdown.querySelector('button[aria-expanded]');
5962 if (!trigger) return;
5963
5964 trigger.addEventListener('click', (e) =>
5965 {
5966 e.stopPropagation();
5967 const shouldOpen = !dropdown.classList.contains('open');
5968 closeTopbarDropdowns();
5969 if (shouldOpen)
5970 {
5971 dropdown.classList.add('open');
5972 trigger.setAttribute('aria-expanded', 'true');
5973 syncAdminUpdateBadgeAnchor();
5974 }
5975 });
5976
5977 dropdown.querySelectorAll('.topbar-menu-item').forEach((itemBtn) =>
5978 {
5979 itemBtn.addEventListener('click', () => closeTopbarDropdowns());
5980 });
5981 });
5982
5983 document.addEventListener('click', (e) =>
5984 {
5985 if (e.target && e.target.closest && e.target.closest('.topbar-dropdown')) return;
5986 closeTopbarDropdowns();
5987 });
5988
5989 document.addEventListener('keydown', (e) =>
5990 {
5991 if (e.key === 'Escape') closeTopbarDropdowns();
5992 });
5993}
5994
5995function wireEvents ()
5996{
5997 initTopbarDropdowns();
5998
5999 // Auth form
6000 document.getElementById('auth-form').addEventListener('submit', async (e) =>
6001 {
6002 e.preventDefault();
6003 const username = document.getElementById('auth-username').value.trim();
6004 const password = document.getElementById('auth-password').value;
6005 const isSetup = e.target.dataset.mode === 'setup';
6006 const errEl = document.getElementById('auth-error');
6007 const btn = document.getElementById('auth-submit');
6008 btn.disabled = true;
6009 btn.textContent = 'Please wait…';
6010 const err = await doLogin(username, password, isSetup);
6011 if (err)
6012 {
6013 errEl.textContent = err;
6014 errEl.classList.remove('hidden');
6015 btn.disabled = false;
6016 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
6017 }
6018 });
6019
6020 // Logout
6021 document.getElementById('btn-logout').addEventListener('click', logout);
6022
6023 // Hard refresh while keeping auth/session state.
6024 document.getElementById('btn-refresh').addEventListener('click', () =>
6025 {
6026 saveSessionState();
6027 location.reload();
6028 });
6029
6030 const topSearchInput = document.getElementById('top-search-input');
6031 const topSearchBtn = document.getElementById('btn-search');
6032 if (topSearchInput && topSearchBtn)
6033 {
6034 topSearchInput.addEventListener('keydown', (e) =>
6035 {
6036 if (e.key !== 'Enter') return;
6037 e.preventDefault();
6038 void runGlobalFileSearch();
6039 });
6040 topSearchBtn.addEventListener('click', () =>
6041 {
6042 void runGlobalFileSearch();
6043 });
6044 }
6045
6046 // Upload button
6047 document.getElementById('btn-upload').addEventListener('click', () =>
6048 {
6049 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
6050 if (!canWrite()) { toast('No write access.', 'err'); return; }
6051 document.getElementById('file-input').click();
6052 });
6053
6054 document.getElementById('file-input').addEventListener('change', async (e) =>
6055 {
6056 if (e.target.files.length) await uploadFiles(e.target.files);
6057 e.target.value = '';
6058 });
6059
6060 document.getElementById('btn-upload-folder').addEventListener('click', () =>
6061 {
6062 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
6063 if (!canWrite()) { toast('No write access.', 'err'); return; }
6064 document.getElementById('folder-input').click();
6065 });
6066
6067 document.getElementById('folder-input').addEventListener('change', async (e) =>
6068 {
6069 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
6070 e.target.value = '';
6071 });
6072
6073 document.getElementById('btn-new-folder').addEventListener('click', async () =>
6074 {
6075 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
6076 if (!canWrite()) { toast('No write access.', 'err'); return; }
6077
6078 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
6079 if (name == null) return;
6080 const folderName = name.trim();
6081 if (!folderName)
6082 {
6083 toast('Folder name is required.', 'err');
6084 return;
6085 }
6086
6087 try
6088 {
6089 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
6090 toast('Folder created.', 'ok');
6091 await navigateTo(STATE.currentDir, STATE.currentRoot);
6092 } catch (err)
6093 {
6094 toast(err.message, 'err');
6095 }
6096 });
6097
6098 document.getElementById('sidebar-close').addEventListener('click', (e) =>
6099 {
6100 e.stopPropagation();
6101 hideSidebarPanel();
6102 });
6103
6104 const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY);
6105 const syncSidebarForViewport = () =>
6106 {
6107 if (isMobileViewport())
6108 {
6109 hideSidebarPanel();
6110 return;
6111 }
6112
6113 if (!STATE.selectedItem) openFolderSidebar();
6114 };
6115
6116 if (typeof mobileQuery.addEventListener === 'function')
6117 {
6118 mobileQuery.addEventListener('change', syncSidebarForViewport);
6119 } else if (typeof mobileQuery.addListener === 'function')
6120 {
6121 mobileQuery.addListener(syncSidebarForViewport);
6122 }
6123
6124 // Click outside grid clears selection and returns to folder sidebar info.
6125 document.getElementById('main-content').addEventListener('click', (e) =>
6126 {
6127 if (!e.target.closest('.file-item')) closeSidebar();
6128 });
6129
6130 // Admin panel
6131 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
6132 document.getElementById('btn-admin-favicon').addEventListener('click', () =>
6133 {
6134 void openGlobalFaviconPicker();
6135 });
6136 document.getElementById('admin-modal-close').addEventListener('click', () =>
6137 document.getElementById('admin-modal').classList.add('hidden'));
6138
6139 // Add path
6140 document.getElementById('admin-add-path').addEventListener('click', () =>
6141 {
6142 const val = document.getElementById('admin-new-path').value.trim();
6143 if (!val) return;
6144 const row = document.createElement('div');
6145 row.className = 'path-row';
6146 row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`;
6147 row.querySelector('button').addEventListener('click', () => row.remove());
6148 document.getElementById('admin-paths').appendChild(row);
6149 document.getElementById('admin-new-path').value = '';
6150 });
6151
6152 // Save paths
6153 document.getElementById('admin-save-paths').addEventListener('click', async () =>
6154 {
6155 const rows = document.querySelectorAll('#admin-paths .path-row span');
6156 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
6157 try
6158 {
6159 await api('PUT', '/admin/config', { paths });
6160 toast('Paths saved.', 'ok');
6161 await loadRoots();
6162 } catch (err) { toast(err.message, 'err'); }
6163 });
6164
6165 const sizeInput = document.getElementById('admin-user-size-limit');
6166 if (sizeInput)
6167 {
6168 sizeInput.addEventListener('input', () =>
6169 {
6170 updateAdminSizeFeedback(sizeInput.value);
6171 });
6172 }
6173
6174 document.getElementById('admin-save-userpath').addEventListener('click', async () =>
6175 {
6176 const rows = document.querySelectorAll('#admin-paths .path-row span');
6177 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
6178 const userPath = document.getElementById('admin-user-path').value.trim();
6179 const rawLimit = document.getElementById('admin-user-size-limit').value.trim();
6180 const parsed = updateAdminSizeFeedback(rawLimit);
6181 if (!parsed.valid)
6182 {
6183 toast('Please enter a valid user size limit.', 'err');
6184 return;
6185 }
6186
6187 try
6188 {
6189 await api('PUT', '/admin/config', {
6190 paths,
6191 userPath: userPath || null,
6192 userFolderSizeLimit: rawLimit ? parsed.bytes : null,
6193 });
6194 toast('User folder settings saved.', 'ok');
6195 await loadRoots();
6196 await refreshAdminConfig();
6197 }
6198 catch (err)
6199 {
6200 toast(err.message, 'err');
6201 }
6202 });
6203
6204 // Shutdown / restart server
6205 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
6206 {
6207 const status = _adminUpdateStatus;
6208
6209 if (!status || !status.underSystemd)
6210 {
6211 // Not running under systemd — plain shutdown (manual restart required).
6212 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
6213 }
6214 else if (status.commitsAhead.length === 0)
6215 {
6216 // Under systemd, no updates — restart only.
6217 if (!await showConfirm('Restart server', 'No update available. Would you like to restart?', { okLabel: 'Restart' })) return;
6218 }
6219 else
6220 {
6221 // Under systemd, updates available.
6222 const commitList = status.commitsAhead.map(c => escHtml(c)).join('<br/>');
6223 const msg = `Updates available:<br/><br/>${commitList}<br/><br/>Update now?`;
6224 if (!await showConfirm('Restart &amp; Update', msg, { html: true, okLabel: 'Update now' })) return;
6225 }
6226
6227 try
6228 {
6229 await api('POST', '/admin/shutdown');
6230 const toastMsg = (!status || !status.underSystemd)
6231 ? 'Server is shutting down\u2026'
6232 : status.commitsAhead.length > 0
6233 ? 'Server is updating and restarting\u2026'
6234 : 'Server is restarting\u2026';
6235 toast(toastMsg, 'ok');
6236 document.getElementById('admin-modal').classList.add('hidden');
6237 } catch
6238 {
6239 // Fetch may throw because the connection closes before a response arrives.
6240 const toastMsg = (!status || !status.underSystemd)
6241 ? 'Server is shutting down\u2026'
6242 : status.commitsAhead.length > 0
6243 ? 'Server is updating and restarting\u2026'
6244 : 'Server is restarting\u2026';
6245 toast(toastMsg, 'ok');
6246 document.getElementById('admin-modal').classList.add('hidden');
6247 }
6248 setTimeout(() => location.reload(), 3000);
6249 });
6250
6251 // New user
6252 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
6253 {
6254 const cfg = await api('GET', '/admin/config');
6255 const paths = cfg ? (cfg.effectivePaths || []) : [];
6256 openUserModal(null, paths);
6257 });
6258
6259 // User modal close
6260 document.getElementById('user-modal-close').addEventListener('click', () =>
6261 document.getElementById('user-modal').classList.add('hidden'));
6262
6263 // Rename modal close
6264 document.getElementById('rename-modal-close').addEventListener('click', () =>
6265 document.getElementById('rename-modal').classList.add('hidden'));
6266
6267 // Close modals on backdrop click
6268 document.querySelectorAll('.modal-overlay').forEach(overlay =>
6269 {
6270 overlay.addEventListener('click', e =>
6271 {
6272 if (e.target === overlay) overlay.classList.add('hidden');
6273 });
6274 });
6275}
6276
6277// ───────────────────────────────────────────────────────────────────────────
6278// BOOT
6279// ───────────────────────────────────────────────────────────────────────────
6280
6281(async function boot ()
6282{
6283 wireEvents();
6284 initDragDrop();
6285 window.addEventListener('beforeunload', () =>
6286 {
6287 saveSessionState();
6288 releaseActivePreviewVideoStreamSession({ keepalive: true });
6289 });
6290 window.addEventListener('pagehide', () =>
6291 {
6292 releaseActivePreviewVideoStreamSession({ keepalive: true });
6293 });
6294 await initAuth();
6295})();