BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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