BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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