BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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