BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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