BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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