BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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