BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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