BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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