BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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