BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

userdirs
timfa Tim Falken · pushed by timfa · 6 months ago
f803c52f History
app.js 145.6 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 // Background refresh state
42 autoRefreshTimer: null,
43 uploadInProgress: false,
44 // Blob URLs for thumbnail previews — revoked on each grid rebuild
45 thumbnailUrls: [],
46 thumbnailObserver: null,
47 folderIconObserver: null,
48
49 // Preview overlay state
50 previewObjectUrl: null,
51 previewCleanup: null,
52 previewDownloadAction: null,
53 previewVideoStreamSessionId: null,
54 previewSourceEl: null, // SVG element that triggered the preview
55 previewClosing: false, // guard to prevent double-close during animation
56 previewExpandState: null, // in-place expanded tile preview state
57 movePicker: null,
58};
59
60const SESSION_KEY = 'filemanager.session.v1';
61const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
62const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
63const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
64const MOBILE_LONG_PRESS_MS = 420;
65const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
66const THUMB_OBSERVER_ROOT_MARGIN = '120px';
67const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.';
68const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings';
69const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({
70 backgroundOpacity: '0',
71 edgeStyle: 'uniform',
72});
73const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
74const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
75let videoJsLoaderPromise = null;
76
77// ───────────────────────────────────────────────────────────────────────────
78// CRYPTO HELPERS (Web Crypto API)
79// ───────────────────────────────────────────────────────────────────────────
80
81async function generateClientKeyPair ()
82{
83 if (!hasWebCrypto()) return;
84 const kp = await crypto.subtle.generateKey(
85 { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
86 true,
87 ['encrypt', 'decrypt'],
88 );
89 STATE.clientPrivateKey = kp.privateKey;
90 STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey);
91}
92
93/**
94 * Hybrid-encrypt a JS object using the server's RSA public key.
95 * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.
96 */
97async function hybridEncryptForServer (obj)
98{
99 if (!hasWebCrypto() || !STATE.serverPublicKeyJwk)
100 {
101 return { plaintext: obj };
102 }
103
104 const serverPub = await crypto.subtle.importKey(
105 'jwk', STATE.serverPublicKeyJwk,
106 { name: 'RSA-OAEP', hash: 'SHA-256' },
107 false, ['encrypt'],
108 );
109
110 const plaintext = new TextEncoder().encode(JSON.stringify(obj));
111 const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
112 const iv = crypto.getRandomValues(new Uint8Array(12));
113 const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext);
114
115 // gcmResult = ciphertext || tag (last 16 bytes are auth tag)
116 const gcmBytes = new Uint8Array(gcmResult);
117 const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16);
118 const tag = gcmBytes.slice(gcmBytes.length - 16);
119
120 const rawAes = await crypto.subtle.exportKey('raw', aesKey);
121 const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes);
122
123 return {
124 encryptedKey: b64(encryptedKey),
125 iv: b64(iv),
126 ciphertext: b64(ciphertext),
127 tag: b64(tag),
128 };
129}
130
131/**
132 * Hybrid-decrypt a payload encrypted by the server for us (using our public key).
133 */
134async function hybridDecryptFromServer (payload)
135{
136 if (!payload) return null;
137 if (payload.token) return payload.token;
138 if (!hasWebCrypto()) return null;
139
140 const encryptedKey = unb64(payload.encryptedKey);
141 const iv = unb64(payload.iv);
142 const ciphertext = unb64(payload.ciphertext);
143 const tag = unb64(payload.tag);
144
145 const rawAes = await crypto.subtle.decrypt(
146 { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey,
147 );
148
149 const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']);
150
151 // Recombine ciphertext + tag for AES-GCM
152 const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength);
153 combined.set(new Uint8Array(ciphertext));
154 combined.set(new Uint8Array(tag), ciphertext.byteLength);
155
156 const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined);
157 return new TextDecoder().decode(plain);
158}
159
160// ───────────────────────────────────────────────────────────────────────────
161// UTIL
162// ───────────────────────────────────────────────────────────────────────────
163
164function b64 (buf)
165{
166 return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));
167}
168
169function hasWebCrypto ()
170{
171 return !!(window.crypto && window.crypto.subtle);
172}
173
174function unb64 (str)
175{
176 const binary = atob(str);
177 const buf = new Uint8Array(binary.length);
178 for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);
179 return buf.buffer;
180}
181
182/** Stable browser fingerprint (not stored, derived fresh each load) */
183function getFingerprint ()
184{
185 const binding = getOrCreateClientBindingId();
186 const nav = navigator;
187
188 // Keep this stable: avoid viewport/screen metrics that can change when
189 // devtools opens, orientation changes, or window state changes.
190 return [
191 binding,
192 nav.userAgent || '',
193 nav.language,
194 nav.platform || nav.userAgentData?.platform || '',
195 Intl.DateTimeFormat().resolvedOptions().timeZone,
196 ].join('|');
197}
198
199function randomIdHex (bytes = 16)
200{
201 const arr = new Uint8Array(bytes);
202 if (window.crypto && typeof window.crypto.getRandomValues === 'function')
203 {
204 window.crypto.getRandomValues(arr);
205 } else
206 {
207 for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);
208 }
209 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
210}
211
212function userVideoPrefsKey ()
213{
214 const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous';
215 return VIDEO_PREFS_KEY_PREFIX + name;
216}
217
218function loadUserVideoPrefs ()
219{
220 try
221 {
222 const raw = localStorage.getItem(userVideoPrefsKey());
223 const parsed = raw ? JSON.parse(raw) : {};
224 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
225 return parsed;
226 } catch
227 {
228 return {};
229 }
230}
231
232function saveUserVideoPrefs (patch)
233{
234 try
235 {
236 const current = loadUserVideoPrefs();
237 localStorage.setItem(userVideoPrefsKey(), JSON.stringify({ ...current, ...(patch || {}) }));
238 } catch
239 {
240 // Ignore localStorage failures.
241 }
242}
243
244function applyUserVideoTextTrackPrefs ()
245{
246 try
247 {
248 // Only override the two requested defaults and leave other settings at Video.js defaults.
249 localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW);
250 } catch
251 {
252 // Ignore localStorage failures.
253 }
254}
255
256function normaliseTrackName (name)
257{
258 return String(name || '').trim().toLowerCase();
259}
260
261function getTrackName (track)
262{
263 if (!track || typeof track !== 'object') return '';
264 const label = String(track.label || '').trim();
265 if (label) return label;
266 const name = String(track.name || '').trim();
267 if (name) return name;
268 const language = String(track.language || '').trim();
269 if (language) return language;
270 const id = String(track.id || '').trim();
271 if (id) return id;
272 return '';
273}
274
275function trackListToArray (trackList)
276{
277 if (!trackList || typeof trackList.length !== 'number') return [];
278 const out = [];
279 for (let i = 0; i < trackList.length; i++)
280 {
281 const track = trackList[i] || (typeof trackList.item === 'function' ? trackList.item(i) : null);
282 if (track) out.push(track);
283 }
284 return out;
285}
286
287function subtitleTracksFromPlayer (player)
288{
289 if (!player || typeof player.textTracks !== 'function') return [];
290 return trackListToArray(player.textTracks()).filter((track) =>
291 {
292 const kind = String(track.kind || '').toLowerCase();
293 return kind === 'subtitles' || kind === 'captions';
294 });
295}
296
297function audioTracksFromPlayer (player)
298{
299 if (!player || typeof player.audioTracks !== 'function') return [];
300 return trackListToArray(player.audioTracks());
301}
302
303function applySavedSubtitleTrack (player, savedName)
304{
305 if (typeof savedName !== 'string') return;
306 const tracks = subtitleTracksFromPlayer(player);
307 if (!tracks.length) return;
308
309 const wanted = normaliseTrackName(savedName);
310 if (!wanted)
311 {
312 for (const track of tracks) track.mode = 'disabled';
313 return;
314 }
315
316 const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted);
317 if (!match) return;
318
319 for (const track of tracks)
320 {
321 track.mode = track === match ? 'showing' : 'disabled';
322 }
323}
324
325function applySavedAudioTrack (player, savedName)
326{
327 if (typeof savedName !== 'string') return;
328 const tracks = audioTracksFromPlayer(player);
329 if (!tracks.length) return;
330
331 const wanted = normaliseTrackName(savedName);
332 if (!wanted) return;
333
334 const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted);
335 if (!match) return;
336
337 for (const track of tracks)
338 {
339 track.enabled = track === match;
340 }
341}
342
343function getSelectedSubtitleTrackName (player)
344{
345 const tracks = subtitleTracksFromPlayer(player);
346 if (!tracks.length) return null;
347 const active = tracks.find((track) => String(track.mode || '').toLowerCase() === 'showing');
348 return active ? getTrackName(active) : '';
349}
350
351function getSelectedAudioTrackName (player)
352{
353 const tracks = audioTracksFromPlayer(player);
354 if (!tracks.length) return null;
355 const active = tracks.find((track) => !!track.enabled);
356 return active ? getTrackName(active) : '';
357}
358
359function bindUserVideoTrackPrefs (player, prefs)
360{
361 const applySavedTracks = () =>
362 {
363 applySavedSubtitleTrack(player, prefs.subtitleTrackName);
364 applySavedAudioTrack(player, prefs.audioTrackName);
365 };
366
367 const captureSelectedTracks = () =>
368 {
369 const subtitleTrackName = getSelectedSubtitleTrackName(player);
370 const audioTrackName = getSelectedAudioTrackName(player);
371 const patch = {};
372
373 if (subtitleTrackName !== null) patch.subtitleTrackName = subtitleTrackName;
374 if (audioTrackName !== null) patch.audioTrackName = audioTrackName;
375
376 if (Object.keys(patch).length) saveUserVideoPrefs(patch);
377 };
378
379 const textTrackList = typeof player.textTracks === 'function' ? player.textTracks() : null;
380 const audioTrackList = typeof player.audioTracks === 'function' ? player.audioTracks() : null;
381 const onTrackListChange = () => captureSelectedTracks();
382
383 if (textTrackList && typeof textTrackList.addEventListener === 'function')
384 {
385 textTrackList.addEventListener('change', onTrackListChange);
386 }
387
388 if (audioTrackList && typeof audioTrackList.addEventListener === 'function')
389 {
390 audioTrackList.addEventListener('change', onTrackListChange);
391 }
392
393 return {
394 applySavedTracks,
395 captureSelectedTracks,
396 detach: () =>
397 {
398 if (textTrackList && typeof textTrackList.removeEventListener === 'function')
399 {
400 textTrackList.removeEventListener('change', onTrackListChange);
401 }
402 if (audioTrackList && typeof audioTrackList.removeEventListener === 'function')
403 {
404 audioTrackList.removeEventListener('change', onTrackListChange);
405 }
406 },
407 };
408}
409
410function normaliseVideoDuration (player, durationSeconds)
411{
412 const duration = Number(durationSeconds);
413 if (!player || !Number.isFinite(duration) || duration <= 0) return;
414
415 let originalDuration = null;
416 let durationWasChanged = false;
417 try
418 {
419 originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null;
420 installDurationFallback(player, originalDuration, duration);
421 if (player.__filemanagerDurationApplied) return;
422
423 const current = originalDuration ? Number(originalDuration()) : NaN;
424 const withinTolerance = Number.isFinite(current) && current >= duration * 0.95;
425 console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`);
426 if (withinTolerance)
427 {
428 player.__filemanagerDurationApplied = true;
429 return;
430 }
431
432 if (originalDuration)
433 {
434 durationWasChanged = true;
435 originalDuration(duration);
436 }
437 } catch
438 {
439 // Ignore players that do not support setting duration.
440 }
441
442 try
443 {
444 const updated = originalDuration ? Number(originalDuration()) : NaN;
445 if (Number.isFinite(updated) && updated >= duration * 0.95)
446 {
447 player.__filemanagerDurationApplied = true;
448 if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange');
449 return;
450 }
451
452 player.__filemanagerDurationApplied = true;
453 if (typeof player.trigger === 'function') player.trigger('durationchange');
454 } catch
455 {
456 // Ignore duration fallback failures.
457 }
458}
459
460function installDurationFallback (player, originalDuration, duration)
461{
462 if (!player || !originalDuration || player.__filemanagerDurationFallback) return;
463
464 player.__filemanagerDurationFallback = true;
465 player.duration = function durationWithFallback (...args)
466 {
467 if (args.length) return originalDuration(...args);
468 const current = Number(originalDuration());
469 return Number.isFinite(current) && current >= duration * 0.95 ? current : duration;
470 };
471}
472
473function formatDurationForDebug (seconds)
474{
475 const value = Number(seconds);
476 if (!Number.isFinite(value) || value < 0) return 'unknown';
477
478 const totalSeconds = Math.floor(value);
479 const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
480 const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
481 const ss = String(totalSeconds % 60).padStart(2, '0');
482 return `${hh}:${mm}:${ss}`;
483}
484
485function ensureVideoPlaybackUi (player, durationSeconds)
486{
487 if (!player || typeof player.on !== 'function') return;
488
489 const forceVodUi = () =>
490 {
491 normaliseVideoDuration(player, durationSeconds);
492
493 try
494 {
495 if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')
496 {
497 player.liveTracker.stopTracking();
498 }
499 } catch
500 {
501 // Ignore live tracker availability issues.
502 }
503
504 try
505 {
506 if (typeof player.removeClass === 'function')
507 {
508 player.removeClass('vjs-live');
509 }
510 } catch
511 {
512 // Ignore class update failures.
513 }
514
515 try
516 {
517 const display = player.el() && player.el().querySelector('.vjs-live-display');
518 if (display) display.style.display = 'none';
519 } catch
520 {
521 // Ignore missing DOM.
522 }
523 };
524
525 player.ready(forceVodUi);
526 player.on('loadedmetadata', forceVodUi);
527 player.on('durationchange', forceVodUi);
528 player.on('loadedplaylist', forceVodUi);
529}
530
531async function reportWatchProgress (filePath, progress)
532{
533 if (!filePath || !Number.isFinite(progress)) return;
534 await api('POST', '/files/watch-progress', {
535 filePath,
536 progress,
537 }).catch(() => null);
538}
539
540function getOrCreateClientBindingId ()
541{
542 if (STATE.clientBindingId) return STATE.clientBindingId;
543
544 try
545 {
546 const existing = localStorage.getItem(CLIENT_BINDING_KEY);
547 if (existing && typeof existing === 'string')
548 {
549 STATE.clientBindingId = existing;
550 return existing;
551 }
552 } catch
553 {
554 // Ignore storage read errors.
555 }
556
557 const created = randomIdHex(16);
558 STATE.clientBindingId = created;
559
560 try
561 {
562 localStorage.setItem(CLIENT_BINDING_KEY, created);
563 } catch
564 {
565 // Ignore storage write errors; in-memory fallback still keeps this stable
566 // for the current page session.
567 }
568
569 return created;
570}
571
572function formatBytes (bytes)
573{
574 if (bytes == null) return '—';
575 if (bytes < 1024) return bytes + ' B';
576 if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
577 if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
578 return (bytes / 1073741824).toFixed(2) + ' GB';
579}
580
581function parseHumanSize (input)
582{
583 const raw = String(input || '').trim();
584 if (!raw) return null;
585
586 const m = raw.match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)(?:i?b)?$/i);
587 if (!m) return null;
588
589 const value = Number(m[1]);
590 if (!Number.isFinite(value) || value <= 0) return null;
591
592 const unit = String(m[2] || '').toLowerCase();
593 const multipliers = {
594 '': 1,
595 k: 1024,
596 m: 1024 * 1024,
597 g: 1024 * 1024 * 1024,
598 t: 1024 * 1024 * 1024 * 1024,
599 };
600 return Math.floor(value * (multipliers[unit] || 1));
601}
602
603function updateAdminSizeFeedback (rawValue)
604{
605 const feedback = document.getElementById('admin-user-size-feedback');
606 if (!feedback) return { bytes: null, valid: true };
607
608 const trimmed = String(rawValue || '').trim();
609 if (!trimmed)
610 {
611 feedback.textContent = '';
612 feedback.classList.add('hidden');
613 feedback.classList.remove('ok', 'err');
614 return { bytes: null, valid: true };
615 }
616
617 const bytes = parseHumanSize(trimmed);
618 feedback.classList.remove('hidden', 'ok', 'err');
619 if (bytes == null)
620 {
621 feedback.textContent = 'Invalid size. Use formats like 25 MB, 1 GB, or 500 KB.';
622 feedback.classList.add('err');
623 return { bytes: null, valid: false };
624 }
625
626 feedback.textContent = `Valid size: ${formatBytes(bytes)}`;
627 feedback.classList.add('ok');
628 return { bytes, valid: true };
629}
630
631function extOf (name)
632{
633 const i = name.lastIndexOf('.');
634 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
635}
636
637function getPathSep (basePath)
638{
639 return basePath && basePath.includes('\\') ? '\\' : '/';
640}
641
642function joinServerPath (basePath, segment)
643{
644 const sep = getPathSep(basePath);
645 const base = String(basePath || '').replace(/[\\/]+$/, '');
646 return base + sep + segment;
647}
648
649function samePath (a, b)
650{
651 if (!a || !b) return false;
652 return String(a).toLowerCase() === String(b).toLowerCase();
653}
654
655function pathInside (child, root)
656{
657 if (!child || !root) return false;
658 if (samePath(child, root)) return true;
659 const sep = getPathSep(root);
660 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
661}
662
663function relativePathFromRoot (targetPath, rootPath)
664{
665 if (!targetPath || !rootPath) return String(targetPath || '');
666 if (samePath(targetPath, rootPath)) return '.';
667
668 const prefix = String(rootPath).replace(/[\\/]+$/, '');
669 const rel = String(targetPath).slice(prefix.length).replace(/^[\\/]+/, '');
670 if (!rel) return '.';
671 return rel;
672}
673
674function displayPathWithRootLabel (targetPath, rootPath, rootLabel)
675{
676 const rel = relativePathFromRoot(targetPath, rootPath);
677 const safeRoot = String(rootLabel || '').replace(/^\/+|\/+$/g, '');
678 if (!safeRoot) return '/';
679 if (rel === '.') return `/${safeRoot}`;
680 return `/${safeRoot}/${String(rel).replace(/\\/g, '/')}`;
681}
682
683function splitNameExt (name)
684{
685 const dot = String(name || '').lastIndexOf('.');
686 if (dot <= 0) return { stem: String(name || ''), ext: '' };
687 return {
688 stem: String(name).slice(0, dot),
689 ext: String(name).slice(dot),
690 };
691}
692
693function nextAvailableName (requestedName, existingNames)
694{
695 const set = existingNames instanceof Set ? existingNames : new Set(existingNames || []);
696 if (!set.has(requestedName)) return requestedName;
697
698 const { stem, ext } = splitNameExt(requestedName);
699 let n = 1;
700 while (n <= 10000)
701 {
702 const candidate = `${stem || 'file'} (${n})${ext}`;
703 if (!set.has(candidate)) return candidate;
704 n++;
705 }
706
707 return requestedName;
708}
709
710async function listDirNameSet (dir)
711{
712 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dir)}`);
713 const names = new Set();
714 for (const it of ((data && data.items) || [])) names.add(it.name);
715 return names;
716}
717
718function cloneFileWithName (file, newName)
719{
720 return new File([file], newName, {
721 type: file.type,
722 lastModified: file.lastModified,
723 });
724}
725
726function saveSessionState ()
727{
728 if (!STATE.token) return;
729 const now = Date.now();
730 STATE.lastOperationAt = now;
731 const payload = {
732 token: STATE.token,
733 dir: STATE.currentDir || null,
734 rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,
735 lastOperationAt: STATE.lastOperationAt,
736 };
737 try
738 {
739 localStorage.setItem(SESSION_KEY, JSON.stringify(payload));
740 } catch
741 {
742 // Ignore storage errors (private mode/full quota).
743 }
744}
745
746function loadSessionState ()
747{
748 try
749 {
750 const raw = localStorage.getItem(SESSION_KEY);
751 if (!raw) return null;
752 const parsed = JSON.parse(raw);
753 if (!parsed || typeof parsed.token !== 'string') return null;
754 if (!Number.isFinite(parsed.lastOperationAt)) return null;
755
756 if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS)
757 {
758 clearSessionState();
759 return null;
760 }
761
762 return parsed;
763 } catch
764 {
765 return null;
766 }
767}
768
769function clearSessionState ()
770{
771 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
772}
773
774// ───────────────────────────────────────────────────────────────────────────
775// API
776// ───────────────────────────────────────────────────────────────────────────
777
778async function api (method, path, body, opts = {})
779{
780 const headers = { 'Content-Type': 'application/json' };
781 const noAutoLogout = !!opts.noAutoLogout;
782 if (STATE.token)
783 {
784 headers['Authorization'] = 'Bearer ' + STATE.token;
785 try
786 {
787 const fp = getFingerprint();
788 if (fp) headers['X-Fp'] = fp;
789 } catch
790 {
791 // Continue without a fingerprint header in constrained test/runtime contexts.
792 }
793 }
794 const fetchOpts = { ...opts };
795 delete fetchOpts.noAutoLogout;
796 const res = await fetch('/api' + path, {
797 method,
798 headers,
799 body: body != null ? JSON.stringify(body) : undefined,
800 ...fetchOpts,
801 });
802 if (!res.ok)
803 {
804 const j = await res.json().catch(() => ({}));
805 // Session-expired → force re-login
806 if (res.status === 401)
807 {
808 if (!noAutoLogout) logout();
809 return null;
810 }
811 throw new Error(j.error || res.statusText);
812 }
813 if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed'))
814 {
815 saveSessionState();
816 }
817 return res.json();
818}
819
820// ───────────────────────────────────────────────────────────────────────────
821// TOAST
822// ───────────────────────────────────────────────────────────────────────────
823
824function toast (msg, type = '')
825{
826 const el = document.createElement('div');
827 el.className = 'toast-msg' + (type ? ' ' + type : '');
828 el.textContent = msg;
829 document.getElementById('toast').appendChild(el);
830 setTimeout(() => el.remove(), 3500);
831}
832
833// ───────────────────────────────────────────────────────────────────────────
834// DIALOG MODALS — centralised replacements for alert / confirm / prompt
835// ───────────────────────────────────────────────────────────────────────────
836
837/**
838 * Show a confirmation dialog.
839 * @param {string} title
840 * @param {string} message
841 * @returns {Promise<boolean>} true = OK, false = Cancel
842 */
843function showConfirm (title, message, { html = false, okLabel = null } = {})
844{
845 return new Promise((resolve) =>
846 {
847 const overlay = document.getElementById('confirm-modal');
848 document.getElementById('confirm-modal-title').textContent = title;
849 const msgEl = document.getElementById('confirm-modal-message');
850 if (html) msgEl.innerHTML = message;
851 else msgEl.textContent = message;
852 overlay.classList.remove('hidden');
853
854 const ok = document.getElementById('confirm-modal-ok');
855 const prevOkLabel = ok.textContent;
856 if (okLabel != null) ok.textContent = okLabel;
857
858 const cancel = document.getElementById('confirm-modal-cancel');
859
860 function finish (result)
861 {
862 overlay.classList.add('hidden');
863 ok.textContent = prevOkLabel;
864 ok.removeEventListener('click', onOk);
865 cancel.removeEventListener('click', onCancel);
866 resolve(result);
867 }
868 function onOk () { finish(true); }
869 function onCancel () { finish(false); }
870
871 ok.addEventListener('click', onOk);
872 cancel.addEventListener('click', onCancel);
873 ok.focus();
874 });
875}
876
877function escHtml (s)
878{
879 return String(s || '')
880 .replace(/&/g, '&amp;')
881 .replace(/</g, '&lt;')
882 .replace(/>/g, '&gt;')
883 .replace(/"/g, '&quot;');
884}
885
886/**
887 * Show a text-input dialog.
888 * @param {string} title
889 * @param {string} [message] — optional helper text shown above the input
890 * @param {string} [defaultValue] — pre-filled value
891 * @returns {Promise<string|null>} string = submitted value, null = cancelled
892 */
893function showPrompt (title, message = '', defaultValue = '')
894{
895 return new Promise((resolve) =>
896 {
897 const overlay = document.getElementById('prompt-modal');
898 const msgEl = document.getElementById('prompt-modal-message');
899 const input = document.getElementById('prompt-modal-input');
900 const errorEl = document.getElementById('prompt-modal-error');
901 const form = document.getElementById('prompt-modal-form');
902 const cancel = document.getElementById('prompt-modal-cancel');
903
904 document.getElementById('prompt-modal-title').textContent = title;
905 msgEl.textContent = message;
906 msgEl.classList.toggle('hidden', !message);
907 input.value = defaultValue;
908 errorEl.classList.add('hidden');
909 overlay.classList.remove('hidden');
910 input.focus();
911 input.select();
912
913 function finish (result)
914 {
915 overlay.classList.add('hidden');
916 form.removeEventListener('submit', onSubmit);
917 cancel.removeEventListener('click', onCancel);
918 resolve(result);
919 }
920 function onSubmit (e)
921 {
922 e.preventDefault();
923 finish(input.value);
924 }
925 function onCancel () { finish(null); }
926
927 form.addEventListener('submit', onSubmit);
928 cancel.addEventListener('click', onCancel);
929 });
930}
931
932/**
933 * Show an overwrite-decision dialog for a single file conflict.
934 * @param {string} filename
935 * @returns {Promise<'yes'|'no'|'all'|'none'>}
936 */
937function showOverwrite (filename)
938{
939 return new Promise((resolve) =>
940 {
941 const overlay = document.getElementById('overwrite-modal');
942 document.getElementById('overwrite-modal-filename').textContent = filename;
943 overlay.classList.remove('hidden');
944
945 const btnYes = document.getElementById('overwrite-modal-yes');
946 const btnNo = document.getElementById('overwrite-modal-no');
947 const btnAll = document.getElementById('overwrite-modal-all');
948 const btnSkipAll = document.getElementById('overwrite-modal-skip-all');
949
950 function finish (result)
951 {
952 overlay.classList.add('hidden');
953 btnYes.removeEventListener('click', onYes);
954 btnNo.removeEventListener('click', onNo);
955 btnAll.removeEventListener('click', onAll);
956 btnSkipAll.removeEventListener('click', onSkipAll);
957 resolve(result);
958 }
959 function onYes () { finish('yes'); }
960 function onNo () { finish('no'); }
961 function onAll () { finish('all'); }
962 function onSkipAll () { finish('none'); }
963
964 btnYes.addEventListener('click', onYes);
965 btnNo.addEventListener('click', onNo);
966 btnAll.addEventListener('click', onAll);
967 btnSkipAll.addEventListener('click', onSkipAll);
968 btnNo.focus();
969 });
970}
971
972/**
973 * Show single-file conflict options.
974 * @param {string} filename
975 * @param {string} renameTo
976 * @param {string} mode - upload|move
977 * @returns {Promise<'overwrite'|'rename'|'cancel'>}
978 */
979function showFileConflictChoice (filename, renameTo, mode = 'upload')
980{
981 return new Promise((resolve) =>
982 {
983 const overlay = document.getElementById('file-conflict-modal');
984 const title = document.getElementById('file-conflict-title');
985 const fileEl = document.getElementById('file-conflict-filename');
986 const renameEl = document.getElementById('file-conflict-rename');
987 const btnOverwrite = document.getElementById('file-conflict-overwrite');
988 const btnRename = document.getElementById('file-conflict-rename-btn');
989 const btnCancel = document.getElementById('file-conflict-cancel');
990
991 title.textContent = mode === 'move' ? 'Move file' : 'Upload file';
992 fileEl.textContent = filename;
993 renameEl.textContent = renameTo;
994 btnRename.textContent = `Rename (${renameTo})`;
995
996 overlay.classList.remove('hidden');
997
998 function finish (result)
999 {
1000 overlay.classList.add('hidden');
1001 btnOverwrite.removeEventListener('click', onOverwrite);
1002 btnRename.removeEventListener('click', onRename);
1003 btnCancel.removeEventListener('click', onCancel);
1004 resolve(result);
1005 }
1006
1007 function onOverwrite () { finish('overwrite'); }
1008 function onRename () { finish('rename'); }
1009 function onCancel () { finish('cancel'); }
1010
1011 btnOverwrite.addEventListener('click', onOverwrite);
1012 btnRename.addEventListener('click', onRename);
1013 btnCancel.addEventListener('click', onCancel);
1014 btnCancel.focus();
1015 });
1016}
1017
1018// ───────────────────────────────────────────────────────────────────────────
1019// SHARE MODAL
1020// ───────────────────────────────────────────────────────────────────────────
1021
1022async function openShareModal (item)
1023{
1024 const overlay = document.getElementById('share-modal');
1025 const urlInput = document.getElementById('share-url-input');
1026 const copyBtn = document.getElementById('share-copy-btn');
1027 const okBtn = document.getElementById('share-modal-ok');
1028 const closeBtn = document.getElementById('share-modal-close');
1029 const msgEl = document.getElementById('share-modal-msg');
1030
1031 urlInput.value = 'Creating link...';
1032 copyBtn.disabled = true;
1033 msgEl.textContent = 'This link is valid for 24 hours.';
1034 overlay.classList.remove('hidden');
1035
1036 let data;
1037 try
1038 {
1039 data = await api('POST', '/share/create', { filePath: item.path });
1040 } catch (err)
1041 {
1042 msgEl.textContent = 'Error: ' + (err.message || 'Could not create link.');
1043 urlInput.value = '';
1044 return;
1045 }
1046
1047 if (!data || !data.token)
1048 {
1049 msgEl.textContent = 'Unknown error while creating link.';
1050 urlInput.value = '';
1051 return;
1052 }
1053
1054 const shareUrl = `${location.origin}/share/${data.token}`;
1055 urlInput.value = shareUrl;
1056 copyBtn.disabled = false;
1057
1058 function close ()
1059 {
1060 overlay.classList.add('hidden');
1061 okBtn.removeEventListener('click', close);
1062 closeBtn.removeEventListener('click', close);
1063 copyBtn.removeEventListener('click', onCopy);
1064 }
1065
1066 function onCopy ()
1067 {
1068 navigator.clipboard.writeText(shareUrl).then(() =>
1069 {
1070 const orig = copyBtn.textContent;
1071 copyBtn.textContent = 'Copied!';
1072 setTimeout(() => { copyBtn.textContent = orig; }, 1500);
1073 }).catch(() =>
1074 {
1075 // Fallback: select the text
1076 urlInput.select();
1077 });
1078 }
1079
1080 okBtn.addEventListener('click', close);
1081 closeBtn.addEventListener('click', close);
1082 copyBtn.addEventListener('click', onCopy);
1083 okBtn.focus();
1084}
1085
1086// ───────────────────────────────────────────────────────────────────────────
1087// AUTH FLOW
1088// ───────────────────────────────────────────────────────────────────────────
1089
1090function showAuthOverlay (setupMode = false)
1091{
1092 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1093 document.getElementById('app').classList.add('hidden');
1094 const overlay = document.getElementById('auth-overlay');
1095 const usernameInput = document.getElementById('auth-username');
1096 const passwordInput = document.getElementById('auth-password');
1097 overlay.classList.remove('hidden');
1098 document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';
1099 document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);
1100 const submitBtn = document.getElementById('auth-submit');
1101 submitBtn.disabled = false;
1102 submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';
1103 document.getElementById('auth-error').classList.add('hidden');
1104 usernameInput.value = '';
1105 passwordInput.value = '';
1106 usernameInput.autocomplete = 'username';
1107 passwordInput.autocomplete = setupMode ? 'new-password' : 'current-password';
1108 usernameInput.focus();
1109 document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';
1110}
1111
1112function showApp ()
1113{
1114 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1115 document.getElementById('auth-overlay').classList.add('hidden');
1116 document.getElementById('app').classList.remove('hidden');
1117 if (isMobileViewport())
1118 {
1119 hideSidebarPanel();
1120 } else
1121 {
1122 openFolderSidebar();
1123 }
1124 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1125 startAutoRefresh();
1126}
1127
1128async function initAuth ()
1129{
1130 // Generate a fresh key pair in the background; login falls back gracefully
1131 // while this is still in progress.
1132 generateClientKeyPair().catch(() =>
1133 {
1134 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
1135 });
1136
1137 // Fetch server public key
1138 const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null }));
1139 if (publicKey) STATE.serverPublicKeyJwk = publicKey;
1140 if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; }
1141 STATE.serverPublicKeyJwk = publicKey;
1142
1143 // Check whether first-run setup is needed
1144 const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));
1145
1146 if (!needed)
1147 {
1148 const saved = loadSessionState();
1149 if (saved && saved.token)
1150 {
1151 STATE.token = saved.token;
1152 STATE.restoreDir = saved.dir || null;
1153 STATE.restoreRootPath = saved.rootPath || null;
1154 STATE.lastOperationAt = saved.lastOperationAt;
1155
1156 const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);
1157 if (me)
1158 {
1159 STATE.username = me.username;
1160 STATE.isAdmin = me.isAdmin;
1161 STATE.permissions = me.permissions;
1162 showApp();
1163 await loadRoots({
1164 preferredDir: STATE.restoreDir,
1165 preferredRootPath: STATE.restoreRootPath,
1166 });
1167 return;
1168 }
1169
1170 STATE.token = null;
1171 clearSessionState();
1172 }
1173 }
1174
1175 showAuthOverlay(needed);
1176}
1177
1178async function doLogin (username, password, isSetup)
1179{
1180 const encrypted = await hybridEncryptForServer({ username, password });
1181 const endpoint = isSetup ? '/auth/setup' : '/auth/login';
1182
1183 let data;
1184 try
1185 {
1186 data = await api('POST', endpoint, {
1187 encrypted,
1188 clientPublicKey: STATE.clientPublicKeyJwk,
1189 fingerprint: getFingerprint(),
1190 });
1191 } catch (err)
1192 {
1193 return err.message;
1194 }
1195
1196 if (!data) return 'Login failed.';
1197
1198 // Decrypt the token sent back by the server
1199 const token = await hybridDecryptFromServer(data.encrypted || data);
1200 if (!token) return 'Login failed.';
1201 STATE.token = token;
1202
1203 // Load user info
1204 const me = await api('GET', '/auth/me');
1205 if (!me) return 'Session error.';
1206
1207 STATE.username = me.username;
1208 STATE.isAdmin = me.isAdmin;
1209 STATE.permissions = me.permissions;
1210
1211 saveSessionState();
1212 showApp();
1213 await loadRoots();
1214 return null; // no error
1215}
1216
1217function logout ()
1218{
1219 void performLogout();
1220}
1221
1222async function performLogout ()
1223{
1224 const tokenAtStart = STATE.token;
1225 stopAutoRefresh();
1226
1227 if (tokenAtStart)
1228 {
1229 try
1230 {
1231 await api('POST', '/auth/logout', {}, { noAutoLogout: true });
1232 } catch
1233 {
1234 // Ignore network errors while logging out locally.
1235 }
1236 }
1237
1238 STATE.token = null;
1239 STATE.username = null;
1240 STATE.isAdmin = false;
1241 STATE.permissions = {};
1242 STATE.currentDir = null;
1243 STATE.currentRoot = null;
1244 STATE.items = [];
1245 STATE.restoreDir = null;
1246 STATE.restoreRootPath = null;
1247 STATE.lastOperationAt = null;
1248 clearSessionState();
1249 closePreview({ force: true });
1250 closeSidebar();
1251 await initAuth();
1252}
1253
1254// ───────────────────────────────────────────────────────────────────────────
1255// NAVIGATION
1256// ───────────────────────────────────────────────────────────────────────────
1257
1258async function loadRoots (opts = {})
1259{
1260 const data = await api('GET', '/files/roots');
1261 if (!data) return;
1262 STATE.roots = data.roots;
1263
1264 const preferredDir = opts.preferredDir || null;
1265 const preferredRootPath = opts.preferredRootPath || null;
1266
1267 if (preferredDir && preferredRootPath)
1268 {
1269 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
1270 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
1271 {
1272 try
1273 {
1274 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
1275 return;
1276 } catch
1277 {
1278 // Fall back to default root behavior.
1279 }
1280 }
1281 }
1282
1283 if (STATE.roots.length === 1)
1284 {
1285 // Single root → open it directly
1286 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
1287 } else
1288 {
1289 renderRootsView();
1290 }
1291}
1292
1293function renderRootsView ()
1294{
1295 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1296 disconnectThumbnailObserver();
1297 disconnectFolderIconObserver();
1298 revokeThumbnails();
1299
1300 STATE.currentDir = null;
1301 STATE.currentRoot = null;
1302 saveSessionState();
1303 renderBreadcrumb();
1304 const grid = document.getElementById('file-grid');
1305 grid.innerHTML = '';
1306 document.getElementById('empty-notice').classList.add('hidden');
1307 document.getElementById('folder-stats').classList.add('hidden');
1308 closeSidebar();
1309
1310 for (const root of STATE.roots)
1311 {
1312 const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root });
1313 grid.appendChild(el);
1314 }
1315
1316 loadThumbnails();
1317}
1318
1319async function navigateTo (absPath, root, opts = {})
1320{
1321 if (root) STATE.currentRoot = root;
1322 STATE.currentDir = absPath;
1323
1324 const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`);
1325 if (!data) return;
1326
1327 STATE.items = data.items;
1328 saveSessionState();
1329 renderBreadcrumb();
1330 renderFileGrid();
1331 await refreshFolderStats();
1332 closeSidebar();
1333}
1334
1335function renderBreadcrumb ()
1336{
1337 if (typeof document === 'undefined') return;
1338 const nav = document.getElementById('breadcrumb');
1339 if (!nav) return;
1340 nav.innerHTML = '';
1341
1342 // "Home" crumb
1343 const home = document.createElement('span');
1344 home.className = 'crumb' + (STATE.currentDir == null ? ' active' : '');
1345 home.textContent = 'Home';
1346 home.addEventListener('click', () =>
1347 {
1348 if (STATE.roots.length === 1)
1349 {
1350 navigateTo(STATE.roots[0].path, STATE.roots[0]);
1351 } else
1352 {
1353 renderRootsView();
1354 }
1355 });
1356 nav.appendChild(home);
1357
1358 if (!STATE.currentDir || !STATE.currentRoot) return;
1359
1360 // Build path segments relative to the root.
1361 const rootPath = STATE.currentRoot.path;
1362 const relative = relativePathFromRoot(STATE.currentDir, rootPath);
1363 const segments = relative === '.' ? [] : relative.split(/[\\/]/).filter(Boolean);
1364 const parts = [STATE.currentRoot.label, ...segments];
1365
1366 for (let i = 0; i < parts.length; i++)
1367 {
1368 const sep = document.createElement('span');
1369 sep.className = 'sep';
1370 sep.textContent = ' / ';
1371 nav.appendChild(sep);
1372
1373 const crumb = document.createElement('span');
1374 crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : '');
1375 crumb.textContent = parts[i];
1376
1377 // Root crumb points to rootPath; segment crumbs point to their folder.
1378 const capturedPath = i === 0
1379 ? rootPath
1380 : joinServerPath(rootPath, segments.slice(0, i).join('/'));
1381 crumb.classList.add('crumb-drop-target');
1382 crumb.dataset.path = capturedPath;
1383 if (i < parts.length - 1)
1384 {
1385 crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot));
1386 }
1387
1388 nav.appendChild(crumb);
1389 }
1390}
1391
1392async function refreshFolderStats ()
1393{
1394 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1395 const el = document.getElementById('folder-stats');
1396 if (!STATE.currentDir)
1397 {
1398 el.classList.add('hidden');
1399 return;
1400 }
1401
1402 const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
1403 if (!data)
1404 {
1405 el.classList.add('hidden');
1406 return;
1407 }
1408
1409 const used = formatBytes(data.usedBytes);
1410 if (data.userFreeBytes != null)
1411 {
1412 el.textContent = `Folder usage: ${used} | Free space remaining: ${formatBytes(data.userFreeBytes)}`;
1413 } else
1414 {
1415 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
1416 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
1417 }
1418 el.classList.remove('hidden');
1419}
1420
1421function itemsSignature (items)
1422{
1423 return JSON.stringify(
1424 (items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
1425 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
1426 );
1427}
1428
1429async function incrementalRefreshCurrentDir ()
1430{
1431 if (STATE.previewExpandState) return;
1432 if (!STATE.currentDir || STATE.uploadInProgress) return;
1433
1434 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
1435 if (!data) return;
1436
1437 const oldSig = itemsSignature(STATE.items);
1438 const newSig = itemsSignature(data.items);
1439 if (oldSig !== newSig)
1440 {
1441 const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;
1442 STATE.items = data.items;
1443 renderFileGrid();
1444
1445 if (selectedPath)
1446 {
1447 const match = STATE.items.find(i => i.path === selectedPath);
1448 if (match)
1449 {
1450 const selectedEl = Array.from(document.querySelectorAll('.file-item'))
1451 .find(el => el.dataset.path === selectedPath);
1452 if (selectedEl) selectItem(selectedEl, match);
1453 } else
1454 {
1455 closeSidebar();
1456 }
1457 }
1458 }
1459 else
1460 {
1461 loadThumbnails();
1462 }
1463
1464 await refreshFolderStats();
1465}
1466
1467function startAutoRefresh ()
1468{
1469 stopAutoRefresh();
1470 STATE.autoRefreshTimer = setInterval(() =>
1471 {
1472 if (document.hidden) return;
1473 incrementalRefreshCurrentDir();
1474 }, 5000);
1475}
1476
1477function stopAutoRefresh ()
1478{
1479 if (STATE.autoRefreshTimer)
1480 {
1481 clearInterval(STATE.autoRefreshTimer);
1482 STATE.autoRefreshTimer = null;
1483 }
1484}
1485
1486// ───────────────────────────────────────────────────────────────────────────
1487// FILE GRID RENDERING
1488// ───────────────────────────────────────────────────────────────────────────
1489
1490function renderFileGrid ()
1491{
1492 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1493 disconnectThumbnailObserver();
1494 disconnectFolderIconObserver();
1495 revokeThumbnails();
1496 const grid = document.getElementById('file-grid');
1497 grid.innerHTML = '';
1498 const empty = document.getElementById('empty-notice');
1499
1500 const sorted = [...STATE.items].sort((a, b) =>
1501 {
1502 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
1503 return a.name.localeCompare(b.name);
1504 });
1505
1506 empty.classList.toggle('hidden', sorted.length > 0);
1507
1508 for (const item of sorted)
1509 {
1510 grid.appendChild(makeFileItem(item));
1511 }
1512
1513 loadThumbnails();
1514}
1515
1516function makeFileItem (item)
1517{
1518 const el = document.createElement('div');
1519 el.className = 'file-item';
1520 el.dataset.path = item.path;
1521 if (item.isDir) el.dataset.isdir = '1';
1522
1523 const icon = document.createElement('div');
1524 icon.className = 'icon';
1525 icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name);
1526 if (!item.isDir)
1527 {
1528 icon.dataset.previewPath = item.path;
1529 } else
1530 {
1531 icon.dataset.folderPath = item.path;
1532 }
1533 el.appendChild(icon);
1534
1535 const name = document.createElement('div');
1536 name.className = 'name';
1537 name.textContent = item.name;
1538 el.appendChild(name);
1539
1540 if (!item._root) makeDraggable(el, item);
1541 attachMobileLongPress(el, item);
1542
1543 el.addEventListener('contextmenu', (e) =>
1544 {
1545 if (!isMobileViewport()) return;
1546 e.preventDefault();
1547 e.stopPropagation();
1548 });
1549
1550 // Single-click: open sidebar
1551 el.addEventListener('click', (e) =>
1552 {
1553 e.stopPropagation();
1554 if (isMobileViewport())
1555 {
1556 if (el.dataset.longPressTriggered === '1')
1557 {
1558 el.dataset.longPressTriggered = '0';
1559 return;
1560 }
1561
1562 if (item.isDir)
1563 {
1564 navigateTo(item.path, item._root || STATE.currentRoot);
1565 } else
1566 {
1567 downloadOrView(item, icon.querySelector('svg'));
1568 }
1569 return;
1570 }
1571
1572 selectItem(el, item);
1573 });
1574
1575 // Double-click: enter folder or view/download file
1576 el.addEventListener('dblclick', (e) =>
1577 {
1578 e.stopPropagation();
1579 if (item.isDir)
1580 {
1581 navigateTo(item.path, item._root || STATE.currentRoot);
1582 } else
1583 {
1584 downloadOrView(item, icon.querySelector('svg'));
1585 }
1586 });
1587
1588 return el;
1589}
1590
1591function attachMobileLongPress (el, item)
1592{
1593 if (item._root) return;
1594
1595 let pressTimer = null;
1596 let startX = 0;
1597 let startY = 0;
1598
1599 function clearPress ()
1600 {
1601 if (!pressTimer) return;
1602 clearTimeout(pressTimer);
1603 pressTimer = null;
1604 }
1605
1606 function cancelPress ()
1607 {
1608 clearPress();
1609 }
1610
1611 el.addEventListener('pointerdown', (e) =>
1612 {
1613 if (!isMobileViewport()) return;
1614 if (e.button !== undefined && e.button !== 0) return;
1615 if (e.pointerType && e.pointerType === 'mouse') return;
1616
1617 startX = e.clientX;
1618 startY = e.clientY;
1619 clearPress();
1620
1621 pressTimer = setTimeout(() =>
1622 {
1623 pressTimer = null;
1624 el.dataset.longPressTriggered = '1';
1625 selectItem(el, item);
1626 }, MOBILE_LONG_PRESS_MS);
1627 });
1628
1629 el.addEventListener('pointermove', (e) =>
1630 {
1631 if (!pressTimer) return;
1632 if (Math.hypot(e.clientX - startX, e.clientY - startY) > MOBILE_LONG_PRESS_MOVE_THRESHOLD)
1633 {
1634 clearPress();
1635 }
1636 });
1637
1638 el.addEventListener('pointerup', cancelPress);
1639 el.addEventListener('pointercancel', cancelPress);
1640 el.addEventListener('pointerleave', cancelPress);
1641}
1642
1643function selectItem (el, item)
1644{
1645 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
1646 el.classList.add('selected');
1647 STATE.selectedItem = item;
1648 openSidebar(item);
1649}
1650
1651// ───────────────────────────────────────────────────────────────────────────
1652// SIDEBAR
1653// ───────────────────────────────────────────────────────────────────────────
1654
1655/**
1656 * Renders (or clears) the duplicates panel at the bottom of the sidebar.
1657 * @param {object|null} item — the item whose duplicates are shown; null = clear
1658 * @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state
1659 */
1660function renderSidebarDuplicates (item, duplicates)
1661{
1662 const panel = document.getElementById('sidebar-duplicates');
1663 if (!panel) return;
1664
1665 // Clear / hide when no item or no duplicates.
1666 if (!item || (Array.isArray(duplicates) && duplicates.length === 0))
1667 {
1668 panel.classList.add('hidden');
1669 panel.innerHTML = '';
1670 return;
1671 }
1672
1673 // Loading state.
1674 if (duplicates === null)
1675 {
1676 panel.classList.add('hidden');
1677 panel.innerHTML = '';
1678 return;
1679 }
1680
1681 panel.innerHTML = '';
1682 const heading = document.createElement('p');
1683 heading.className = 'sidebar-duplicates-heading';
1684 heading.textContent = `Duplicates (${duplicates.length})`;
1685 panel.appendChild(heading);
1686
1687 const list = document.createElement('ul');
1688 list.className = 'sidebar-duplicates-list';
1689
1690 for (const dup of duplicates)
1691 {
1692 const li = document.createElement('li');
1693 const btn = document.createElement('button');
1694 btn.className = 'sidebar-duplicate-entry';
1695 btn.title = dup.path;
1696 // Show path relative to its root; keep absolute path in the tooltip.
1697 btn.textContent = dup.relativePath || dup.path;
1698 btn.addEventListener('click', () => navigateToDuplicate(dup));
1699 li.appendChild(btn);
1700 list.appendChild(li);
1701 }
1702
1703 panel.appendChild(list);
1704 panel.classList.remove('hidden');
1705}
1706
1707/**
1708 * Navigates to the folder containing a duplicate file and then auto-opens it.
1709 * @param {{ path: string, name: string, dir: string }} dup
1710 */
1711async function navigateToDuplicate (dup)
1712{
1713 // If the duplicate lives in the folder already shown, just select it.
1714 if (STATE.currentDir && samePath(dup.dir, STATE.currentDir))
1715 {
1716 const tile = Array.from(document.querySelectorAll('.file-item'))
1717 .find((el) => el.dataset.path === dup.path);
1718 const dupItem = STATE.items.find((i) => i.path === dup.path);
1719 if (tile && dupItem)
1720 {
1721 selectItem(tile, dupItem);
1722 }
1723 return;
1724 }
1725
1726 // Find the root that contains the duplicate.
1727 const root = STATE.roots.find(
1728 (r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'),
1729 );
1730 if (!root)
1731 {
1732 toast('Cannot navigate to duplicate: root not accessible.', 'err');
1733 return;
1734 }
1735
1736 await navigateTo(dup.dir, root);
1737
1738 // After navigation, find and select the file tile to open it.
1739 const tile = Array.from(document.querySelectorAll('.file-item'))
1740 .find((el) => el.dataset.path === dup.path);
1741 const dupItem = STATE.items.find((i) => i.path === dup.path);
1742
1743 if (tile && dupItem)
1744 {
1745 selectItem(tile, dupItem);
1746 }
1747}
1748// ───────────────────────────────────────────────────────────────────────────
1749
1750async function openSidebar (item)
1751{
1752 const sidebar = document.getElementById('sidebar');
1753 sidebar.classList.remove('hidden');
1754 document.getElementById('app').classList.add('sidebar-open');
1755
1756 document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64);
1757 if (item.isDir)
1758 {
1759 document.getElementById('sidebar-icon').dataset.folderPath = item.path;
1760 } else
1761 {
1762 delete document.getElementById('sidebar-icon').dataset.folderPath;
1763 }
1764 document.getElementById('sidebar-name').textContent = item.name;
1765
1766 // Load metadata
1767 const dl = document.getElementById('sidebar-meta');
1768 dl.innerHTML = '<dt>Loading…</dt><dd></dd>';
1769
1770 const actions = document.getElementById('sidebar-actions');
1771 actions.innerHTML = '';
1772
1773 // Reset duplicates panel whenever a new item is opened.
1774 renderSidebarDuplicates(null, null);
1775
1776 if (!item.isDir)
1777 {
1778 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
1779 if (meta)
1780 {
1781 const watchedBy = VIDEO_EXTS.has(extOf(item.name))
1782 ? Object.entries(meta.watchedBy || {})
1783 .map(([user, status]) => `${String(user)}: ${String(status)}`)
1784 .sort((a, b) => a.localeCompare(b))
1785 : [];
1786
1787 dl.innerHTML = `
1788 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
1789 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
1790 <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd>
1791 <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd>
1792 ${VIDEO_EXTS.has(extOf(item.name)) ? `<dt>Watched by</dt><dd>${watchedBy.join(', ') || '—'}</dd>` : ''}
1793 `;
1794 }
1795
1796 // Fetch and render duplicate files.
1797 renderSidebarDuplicates(item, null); // show loading state
1798 const selectedPathAtRequest = item.path;
1799 api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`)
1800 .then((data) =>
1801 {
1802 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
1803 renderSidebarDuplicates(item, data ? data.duplicates : []);
1804 })
1805 .catch(() =>
1806 {
1807 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
1808 renderSidebarDuplicates(item, []);
1809 });
1810
1811 // View / download button
1812 const btnDl = document.createElement('button');
1813 btnDl.textContent = 'View / Download';
1814 btnDl.addEventListener('click', () =>
1815 {
1816 const tile = Array.from(document.querySelectorAll('.file-item')).find(node => node.dataset.path === item.path);
1817 const source = (tile ? tile.querySelector('.icon svg') : null) || document.querySelector('#sidebar-icon svg');
1818 downloadOrView(item, source);
1819 });
1820 actions.appendChild(btnDl);
1821
1822 // Share button (file)
1823 const btnShareFile = document.createElement('button');
1824 btnShareFile.textContent = 'Share';
1825 btnShareFile.addEventListener('click', () => openShareModal(item));
1826 actions.appendChild(btnShareFile);
1827 } else
1828 {
1829 dl.innerHTML = `<dt>Type</dt><dd>${item._root ? 'Root folder' : 'Folder'}</dd>`;
1830
1831 if (item._root)
1832 {
1833 dl.innerHTML += `
1834 <dt>Alias</dt><dd>${item.name}</dd>
1835 <dt>Original name</dt><dd>${item._root.originalName || basenameOfPath(item.path)}</dd>
1836 `;
1837
1838 const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch(() => null);
1839 if (space)
1840 {
1841 const used = formatBytes(space.usedBytes);
1842 const free = space.freeBytes == null ? 'unknown' : formatBytes(space.freeBytes);
1843 dl.innerHTML += `
1844 <dt>Used</dt><dd>${used}</dd>
1845 <dt>Remaining</dt><dd>${free}</dd>
1846 `;
1847 }
1848
1849 const accessUsers = await fetchRootAccessList(item.path);
1850 if (accessUsers)
1851 {
1852 dl.innerHTML += `
1853 <dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>
1854 `;
1855 }
1856 }
1857
1858 const btnOpen = document.createElement('button');
1859 btnOpen.textContent = 'Open folder';
1860 btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot));
1861 actions.appendChild(btnOpen);
1862
1863 // Download as zip button (folder)
1864 const btnZip = document.createElement('button');
1865 btnZip.textContent = 'Download as zip';
1866 btnZip.addEventListener('click', () =>
1867 {
1868 btnZip.disabled = true;
1869 btnZip.textContent = 'Working...';
1870 const url = `/api/files/download-zip?dir=${encodeURIComponent(item.path)}`;
1871 const headers = {
1872 Authorization: 'Bearer ' + STATE.token,
1873 'X-Fp': getFingerprint(),
1874 };
1875 fetch(url, { headers })
1876 .then(res =>
1877 {
1878 if (!res.ok) throw new Error('Download mislukt');
1879 return res.blob();
1880 })
1881 .then(blob =>
1882 {
1883 const blobUrl = URL.createObjectURL(blob);
1884 const a = document.createElement('a');
1885 a.href = blobUrl;
1886 a.download = item.name + '.zip';
1887 a.click();
1888 setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
1889 })
1890 .catch((err) => toast(err.message || 'Download mislukt', 'err'))
1891 .finally(() =>
1892 {
1893 btnZip.disabled = false;
1894 btnZip.textContent = 'Download as zip';
1895 });
1896 });
1897 actions.appendChild(btnZip);
1898
1899 // Share button (folder)
1900 const btnShareFolder = document.createElement('button');
1901 btnShareFolder.textContent = 'Share';
1902 btnShareFolder.addEventListener('click', () => openShareModal(item));
1903 actions.appendChild(btnShareFolder);
1904
1905 // Load folder icon thumbnail into the sidebar icon element.
1906 void loadOneFolderIcon(document.getElementById('sidebar-icon'));
1907 }
1908
1909 // Rename button (write access required)
1910 if (canWrite(item))
1911 {
1912 if (item.isDir)
1913 {
1914 const btnSetIcon = document.createElement('button');
1915 btnSetIcon.textContent = 'Set icon';
1916 btnSetIcon.addEventListener('click', () => openFolderIconPicker(item));
1917 actions.appendChild(btnSetIcon);
1918 }
1919
1920 if (!item._root)
1921 {
1922 const btnMove = document.createElement('button');
1923 btnMove.textContent = 'Move to';
1924 btnMove.addEventListener('click', () => openMovePicker(item));
1925 actions.appendChild(btnMove);
1926
1927 if (!item.isDir)
1928 {
1929 const btnCopy = document.createElement('button');
1930 btnCopy.textContent = 'Copy to';
1931 btnCopy.addEventListener('click', () => openCopyPicker(item));
1932 actions.appendChild(btnCopy);
1933 }
1934 }
1935
1936 const btnRen = document.createElement('button');
1937 btnRen.textContent = 'Rename';
1938 btnRen.addEventListener('click', () => openRenameModal(item));
1939 actions.appendChild(btnRen);
1940
1941 if (!item._root)
1942 {
1943 const btnDel = document.createElement('button');
1944 btnDel.textContent = 'Delete';
1945 btnDel.className = 'danger';
1946 btnDel.addEventListener('click', () => deleteItem(item));
1947 actions.appendChild(btnDel);
1948 }
1949 }
1950}
1951
1952function openFolderSidebar ()
1953{
1954 const sidebar = document.getElementById('sidebar');
1955 sidebar.classList.remove('hidden');
1956 document.getElementById('app').classList.add('sidebar-open');
1957
1958 document.getElementById('sidebar-icon').innerHTML = iconFolder(64);
1959
1960 const nameEl = document.getElementById('sidebar-name');
1961 const dl = document.getElementById('sidebar-meta');
1962 const actions = document.getElementById('sidebar-actions');
1963 actions.innerHTML = '';
1964 renderSidebarDuplicates(null, null);
1965
1966 if (!STATE.currentDir || !STATE.currentRoot)
1967 {
1968 nameEl.textContent = 'Storage Roots';
1969 dl.innerHTML = `
1970 <dt>Type</dt><dd>Root overview</dd>
1971 <dt>Roots</dt><dd>${STATE.roots.length}</dd>
1972 `;
1973 return;
1974 }
1975
1976 const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean);
1977 const fallback = STATE.currentRoot.label || 'Folder';
1978 nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback;
1979
1980 const dirs = STATE.items.filter(i => i.isDir).length;
1981 const files = STATE.items.length - dirs;
1982 const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label);
1983 const baseDetails = `
1984 <dt>Path</dt><dd>${displayPath}</dd>
1985 <dt>Folders</dt><dd>${dirs}</dd>
1986 <dt>Files</dt><dd>${files}</dd>
1987 `;
1988 dl.innerHTML = baseDetails;
1989
1990 if (samePath(STATE.currentDir, STATE.currentRoot.path))
1991 {
1992 dl.innerHTML += '<dt>Access</dt><dd>Loading…</dd>';
1993 const currentDirAtStart = STATE.currentDir;
1994 const currentRootPathAtStart = STATE.currentRoot.path;
1995 void fetchRootAccessList(currentRootPathAtStart).then((accessUsers) =>
1996 {
1997 if (!accessUsers) return;
1998 if (!STATE.currentRoot) return;
1999 if (!samePath(STATE.currentDir, currentDirAtStart)) return;
2000 if (!samePath(STATE.currentRoot.path, currentRootPathAtStart)) return;
2001 dl.innerHTML = `${baseDetails}<dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>`;
2002 });
2003 }
2004}
2005
2006function closeSidebar ()
2007{
2008 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
2009 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
2010 STATE.selectedItem = null;
2011
2012 if (isMobileViewport())
2013 {
2014 hideSidebarPanel();
2015 return;
2016 }
2017
2018 openFolderSidebar();
2019}
2020
2021function isMobileViewport ()
2022{
2023 return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches;
2024}
2025
2026function hideSidebarPanel ()
2027{
2028 const sidebar = document.getElementById('sidebar');
2029 const app = document.getElementById('app');
2030 sidebar.classList.add('hidden');
2031 app.classList.remove('sidebar-open');
2032}
2033
2034function basenameOfPath (p)
2035{
2036 const parts = String(p || '').split(/[\\/]/).filter(Boolean);
2037 return parts.length ? parts[parts.length - 1] : String(p || '');
2038}
2039
2040async function fetchRootAccessList (rootPath)
2041{
2042 if (!rootPath) return null;
2043 const data = await api('GET', `/files/root-access?rootPath=${encodeURIComponent(rootPath)}`).catch(() => null);
2044 if (!data || !Array.isArray(data.users)) return null;
2045 return data.users;
2046}
2047
2048function formatRootAccessList (users)
2049{
2050 if (!Array.isArray(users) || users.length === 0) return 'No users';
2051
2052 const sorted = [...users].sort((a, b) =>
2053 {
2054 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
2055 const byMode = modeRank(a.mode) - modeRank(b.mode);
2056 if (byMode !== 0) return byMode;
2057 return String(a.username).localeCompare(String(b.username));
2058 });
2059
2060 const items = sorted
2061 .map((u) => `<li>${escapeHtml(String(u.username || ''))} ${escapeHtml(String(u.mode || 'R'))}</li>`)
2062 .join('');
2063 return `<ul class="root-access-list">${items}</ul>`;
2064}
2065
2066function rootPermissionLabel (root)
2067{
2068 return (root && (root.originalName || root.label)) || '';
2069}
2070
2071function resolveRootForPath (targetPath)
2072{
2073 if (!targetPath) return null;
2074 return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null;
2075}
2076
2077function writableRoots ()
2078{
2079 if (STATE.isAdmin) return STATE.roots.slice();
2080 return STATE.roots.filter((r) =>
2081 {
2082 if (r.isUserFolder) return true;
2083 const perm = STATE.permissions[rootPermissionLabel(r)];
2084 return !!(perm && perm.write);
2085 });
2086}
2087
2088async function moveWithConflictResolution (item, targetDir)
2089{
2090 try
2091 {
2092 return await api('POST', '/files/move', { from: item.path, toDir: targetDir });
2093 }
2094 catch (err)
2095 {
2096 if (!/already exists/i.test(err.message || '')) throw err;
2097
2098 const existingNames = await listDirNameSet(targetDir);
2099 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2100 const suggestedName = nextAvailableName(desiredName, existingNames);
2101 const decision = await showFileConflictChoice(desiredName, suggestedName, 'move');
2102 if (decision === 'cancel') return null;
2103
2104 if (decision === 'overwrite')
2105 {
2106 return api('POST', '/files/move', {
2107 from: item.path,
2108 toDir: targetDir,
2109 conflict: 'overwrite',
2110 });
2111 }
2112
2113 return api('POST', '/files/move', {
2114 from: item.path,
2115 toDir: targetDir,
2116 conflict: 'rename',
2117 targetName: suggestedName,
2118 });
2119 }
2120}
2121
2122async function copyWithConflictResolution (item, targetDir)
2123{
2124 try
2125 {
2126 return await api('POST', '/files/copy', { from: item.path, toDir: targetDir });
2127 }
2128 catch (err)
2129 {
2130 if (!/already exists/i.test(err.message || '')) throw err;
2131
2132 const existingNames = await listDirNameSet(targetDir);
2133 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2134 const suggestedName = nextAvailableName(desiredName, existingNames);
2135 const decision = await showFileConflictChoice(desiredName, suggestedName, 'copy');
2136 if (decision === 'cancel') return null;
2137
2138 if (decision === 'overwrite')
2139 {
2140 return api('POST', '/files/copy', {
2141 from: item.path,
2142 toDir: targetDir,
2143 conflict: 'overwrite',
2144 });
2145 }
2146
2147 return api('POST', '/files/copy', {
2148 from: item.path,
2149 toDir: targetDir,
2150 conflict: 'rename',
2151 targetName: suggestedName,
2152 });
2153 }
2154}
2155
2156function ensureMoveModal ()
2157{
2158 let overlay = document.getElementById('move-modal');
2159 if (overlay) return overlay;
2160
2161 overlay = document.createElement('div');
2162 overlay.id = 'move-modal';
2163 overlay.className = 'modal-overlay hidden';
2164 overlay.innerHTML = `
2165 <div class="modal move-modal">
2166 <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button>
2167 <h2>Move To</h2>
2168 <p id="move-modal-caption" class="muted"></p>
2169 <div id="move-tree" class="move-tree"></div>
2170 <p id="move-selected" class="muted"></p>
2171 <div class="dialog-actions">
2172 <button id="move-modal-cancel">Cancel</button>
2173 <button id="move-modal-confirm" class="primary">Move</button>
2174 </div>
2175 </div>
2176 `;
2177 document.body.appendChild(overlay);
2178
2179 const closeBtn = overlay.querySelector('#move-modal-close');
2180 const cancelBtn = overlay.querySelector('#move-modal-cancel');
2181 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2182
2183 function hide ()
2184 {
2185 overlay.classList.add('hidden');
2186 STATE.movePicker = null;
2187 }
2188
2189 closeBtn.addEventListener('click', hide);
2190 cancelBtn.addEventListener('click', hide);
2191 overlay.addEventListener('click', (e) =>
2192 {
2193 if (e.target === overlay) hide();
2194 });
2195
2196 confirmBtn.addEventListener('click', async () =>
2197 {
2198 const st = STATE.movePicker;
2199 if (!st || !st.item || !st.selectedPath)
2200 {
2201 toast('Select a destination folder first.', 'err');
2202 return;
2203 }
2204
2205 try
2206 {
2207 if (st.mode === 'copy')
2208 {
2209 const copied = await copyWithConflictResolution(st.item, st.selectedPath);
2210 if (!copied) return;
2211 }
2212 else
2213 {
2214 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
2215 if (!moved) return;
2216 }
2217 }
2218 catch (err)
2219 {
2220 const action = st.mode === 'copy' ? 'Copy' : 'Move';
2221 toast(`${action} failed: ${err.message}`, 'err');
2222 return;
2223 }
2224
2225 hide();
2226 if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2227 navigateTo(STATE.currentDir, STATE.currentRoot);
2228 });
2229
2230 return overlay;
2231}
2232
2233function setMoveSelection (path, buttonEl)
2234{
2235 if (!STATE.movePicker) return;
2236 STATE.movePicker.selectedPath = path;
2237
2238 document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected'));
2239 if (buttonEl) buttonEl.classList.add('selected');
2240
2241 const selectedEl = document.getElementById('move-selected');
2242 selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none';
2243}
2244
2245async function loadMoveChildren (containerEl, dirPath)
2246{
2247 if (containerEl.dataset.loaded === '1') return;
2248 containerEl.dataset.loaded = '1';
2249
2250 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
2251 const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : [];
2252
2253 if (!folders.length)
2254 {
2255 const empty = document.createElement('div');
2256 empty.className = 'move-empty';
2257 empty.textContent = 'No subfolders';
2258 containerEl.appendChild(empty);
2259 return;
2260 }
2261
2262 for (const child of folders)
2263 {
2264 containerEl.appendChild(createMoveNode(child.path, child.name));
2265 }
2266}
2267
2268function createMoveNode (folderPath, label)
2269{
2270 const node = document.createElement('div');
2271 node.className = 'move-node';
2272
2273 const row = document.createElement('div');
2274 row.className = 'move-node-row';
2275
2276 const toggle = document.createElement('button');
2277 toggle.type = 'button';
2278 toggle.className = 'move-toggle';
2279 toggle.textContent = '▸';
2280
2281 const selectBtn = document.createElement('button');
2282 selectBtn.type = 'button';
2283 selectBtn.className = 'move-node-label';
2284 selectBtn.textContent = label;
2285 selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn));
2286
2287 const children = document.createElement('div');
2288 children.className = 'move-children hidden';
2289
2290 toggle.addEventListener('click', async () =>
2291 {
2292 if (children.classList.contains('hidden'))
2293 {
2294 await loadMoveChildren(children, folderPath);
2295 children.classList.remove('hidden');
2296 toggle.textContent = '▾';
2297 } else
2298 {
2299 children.classList.add('hidden');
2300 toggle.textContent = '▸';
2301 }
2302 });
2303
2304 row.appendChild(toggle);
2305 row.appendChild(selectBtn);
2306 node.appendChild(row);
2307 node.appendChild(children);
2308 return node;
2309}
2310
2311function openDestinationPicker (item, mode)
2312{
2313 if (!canWrite())
2314 {
2315 toast('No write access.', 'err');
2316 return;
2317 }
2318
2319 const roots = writableRoots();
2320 if (!roots.length)
2321 {
2322 toast('No writable destination roots available.', 'err');
2323 return;
2324 }
2325
2326 const overlay = ensureMoveModal();
2327 const tree = overlay.querySelector('#move-tree');
2328 const caption = overlay.querySelector('#move-modal-caption');
2329 const titleEl = overlay.querySelector('h2');
2330 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2331
2332 const op = mode === 'copy' ? 'copy' : 'move';
2333 STATE.movePicker = { item, selectedPath: null, mode: op };
2334 titleEl.textContent = op === 'copy' ? 'Copy To' : 'Move To';
2335 confirmBtn.textContent = op === 'copy' ? 'Copy' : 'Move';
2336 caption.textContent = `Select destination folder for: ${item.name}`;
2337 tree.innerHTML = '';
2338
2339 for (const root of roots)
2340 {
2341 tree.appendChild(createMoveNode(root.path, root.label));
2342 }
2343
2344 setMoveSelection(null, null);
2345 overlay.classList.remove('hidden');
2346}
2347
2348function openMovePicker (item)
2349{
2350 openDestinationPicker(item, 'move');
2351}
2352
2353function openCopyPicker (item)
2354{
2355 openDestinationPicker(item, 'copy');
2356}
2357
2358// ───────────────────────────────────────────────────────────────────────────
2359// FOLDER ICON PICKER
2360// ───────────────────────────────────────────────────────────────────────────
2361
2362async function openFolderIconPicker (item)
2363{
2364 if (!canWrite(item))
2365 {
2366 toast('No write access.', 'err');
2367 return;
2368 }
2369
2370 // Fetch the list of available images (only those with cached thumbnails).
2371 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(item.path)}`).catch(() => null);
2372 const images = data ? data.images : [];
2373
2374 let existingIconOverlay = document.getElementById('folder-icon-picker');
2375 if (existingIconOverlay) existingIconOverlay.remove();
2376
2377 const overlay = document.createElement('div');
2378 overlay.id = 'folder-icon-picker';
2379 overlay.className = 'modal-overlay';
2380
2381 const modal = document.createElement('div');
2382 modal.className = 'modal folder-icon-modal';
2383
2384 const closeBtn = document.createElement('button');
2385 closeBtn.className = 'modal-close';
2386 closeBtn.setAttribute('aria-label', 'Close');
2387 closeBtn.textContent = '✕';
2388
2389 const title = document.createElement('h2');
2390 title.textContent = 'Set folder icon';
2391
2392 const subtitle = document.createElement('p');
2393 subtitle.className = 'muted';
2394
2395 const grid = document.createElement('div');
2396 grid.className = 'folder-icon-grid';
2397
2398 if (!images.length)
2399 {
2400 subtitle.textContent = 'No images with cached thumbnails were found inside this folder.';
2401 } else
2402 {
2403 subtitle.textContent = 'Select an image to use as the folder icon.';
2404
2405 for (const { filePath } of images)
2406 {
2407 const cell = document.createElement('div');
2408 cell.className = 'folder-icon-cell';
2409 cell.dataset.path = filePath;
2410
2411 const imgEl = document.createElement('img');
2412 imgEl.alt = filePath.split('/').pop();
2413 imgEl.className = 'folder-icon-thumb';
2414 // Lazy-load via IntersectionObserver on the cell.
2415 imgEl.dataset.src = filePath;
2416
2417 const label = document.createElement('div');
2418 label.className = 'folder-icon-label';
2419 label.textContent = filePath.split('/').pop();
2420
2421 cell.appendChild(imgEl);
2422 cell.appendChild(label);
2423
2424 cell.addEventListener('click', () =>
2425 {
2426 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
2427 cell.classList.add('selected');
2428 confirmBtn.disabled = false;
2429 });
2430
2431 grid.appendChild(cell);
2432 }
2433 }
2434
2435 const dialogActions = document.createElement('div');
2436 dialogActions.className = 'dialog-actions';
2437
2438 const clearBtn = document.createElement('button');
2439 clearBtn.textContent = 'Clear icon';
2440 clearBtn.addEventListener('click', async () =>
2441 {
2442 try
2443 {
2444 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
2445 } catch (err)
2446 {
2447 toast('Failed to clear icon: ' + err.message, 'err');
2448 return;
2449 }
2450 hide();
2451 refreshAfterIconChange(item);
2452 });
2453
2454 const cancelBtn = document.createElement('button');
2455 cancelBtn.textContent = 'Cancel';
2456 cancelBtn.addEventListener('click', () => hide());
2457
2458 const confirmBtn = document.createElement('button');
2459 confirmBtn.className = 'primary';
2460 confirmBtn.textContent = 'Set icon';
2461 confirmBtn.disabled = true;
2462 confirmBtn.addEventListener('click', async () =>
2463 {
2464 const selected = grid.querySelector('.folder-icon-cell.selected');
2465 if (!selected) return;
2466 const imagePath = selected.dataset.path;
2467 try
2468 {
2469 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
2470 } catch (err)
2471 {
2472 toast('Failed to set icon: ' + err.message, 'err');
2473 return;
2474 }
2475 hide();
2476 refreshAfterIconChange(item);
2477 });
2478
2479 dialogActions.appendChild(clearBtn);
2480 dialogActions.appendChild(cancelBtn);
2481 dialogActions.appendChild(confirmBtn);
2482
2483 modal.appendChild(closeBtn);
2484 modal.appendChild(title);
2485 modal.appendChild(subtitle);
2486 modal.appendChild(grid);
2487 modal.appendChild(dialogActions);
2488 overlay.appendChild(modal);
2489 document.body.appendChild(overlay);
2490
2491 function hide ()
2492 {
2493 overlay.remove();
2494 // Revoke any blob URLs we created for the picker thumbnails.
2495 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach(img =>
2496 {
2497 URL.revokeObjectURL(img.src);
2498 });
2499 }
2500
2501 closeBtn.addEventListener('click', hide);
2502 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
2503
2504 // Eagerly load thumbnails for all cells (picker is small, fetch all).
2505 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
2506 {
2507 const imgEl = cell.querySelector('.folder-icon-thumb');
2508 const filePath = imgEl.dataset.src;
2509 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
2510 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
2511 }).then(async (r) =>
2512 {
2513 if (!r.ok || !overlay.isConnected) return;
2514 const blob = await r.blob();
2515 const url = URL.createObjectURL(blob);
2516 imgEl.src = url;
2517 }).catch(() => {});
2518 }
2519}
2520
2521function refreshAfterIconChange (item)
2522{
2523 // Reset and reload icon in grid tiles.
2524 const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]'))
2525 .find(el => el.dataset.folderPath === item.path);
2526 if (gridTile)
2527 {
2528 const svg = gridTile.querySelector('svg');
2529 if (svg)
2530 {
2531 // Rebuild to plain folder SVG, then reload.
2532 gridTile.innerHTML = iconFolder();
2533 delete gridTile.dataset.thumbReady;
2534 gridTile.dataset.folderPath = item.path;
2535 void loadOneFolderIcon(gridTile);
2536 }
2537 }
2538
2539 // Also reset the sidebar icon if it's showing the same folder.
2540 const sidebarIcon = document.getElementById('sidebar-icon');
2541 if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path)
2542 {
2543 sidebarIcon.innerHTML = iconFolder(64);
2544 delete sidebarIcon.dataset.thumbReady;
2545 void loadOneFolderIcon(sidebarIcon);
2546 }
2547}
2548
2549// ───────────────────────────────────────────────────────────────────────────
2550// DOWNLOAD / VIEW
2551// ───────────────────────────────────────────────────────────────────────────
2552
2553function isInlinePreviewableBlob (blob, name)
2554{
2555 const mime = String(blob.type || '').toLowerCase();
2556 if (/^(image|video|audio)\//.test(mime)) return true;
2557 if (/^text\//.test(mime)) return true;
2558 if (mime === 'application/pdf') return true;
2559 if (mime === 'application/json') return true;
2560 if (mime === 'application/xml') return true;
2561 if (mime === 'application/javascript') return true;
2562
2563 // Fallback by extension when MIME is missing or generic.
2564 const ext = extOf(name || '');
2565 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true;
2566 if (CODE_EXTS.has(ext)) return true;
2567 return false;
2568}
2569
2570function isTextLikeBlob (blob, name)
2571{
2572 const mime = String(blob.type || '').toLowerCase();
2573 if (/^text\//.test(mime)) return true;
2574 if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true;
2575 const ext = extOf(name || '');
2576 return CODE_EXTS.has(ext);
2577}
2578
2579function detectCodeLanguage (name, mime)
2580{
2581 const ext = extOf(name || '');
2582 const m = String(mime || '').toLowerCase();
2583 if (m.includes('json') || ext === 'json') return 'json';
2584 if (m.includes('xml') || ext === 'xml') return 'xml';
2585 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
2586 if (m.includes('css') || ext === 'css') return 'css';
2587 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
2588 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
2589 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
2590 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
2591 return CODE_EXTS.has(ext) ? 'js' : 'plain';
2592}
2593
2594function prettyPrintMarkup (raw)
2595{
2596 const src = String(raw || '')
2597 .replace(/>\s+</g, '><')
2598 .replace(/\r\n/g, '\n');
2599
2600 const lines = src.replace(/></g, '>\n<').split('\n');
2601 let indent = 0;
2602 const out = [];
2603
2604 for (const ln of lines)
2605 {
2606 const line = ln.trim();
2607 if (!line) continue;
2608 const isClose = /^<\//.test(line);
2609 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
2610 const isOpen = /^<[^!?/][^>]*>$/.test(line);
2611
2612 if (isClose) indent = Math.max(0, indent - 1);
2613 out.push(' '.repeat(indent) + line);
2614 if (isOpen && !isSelf) indent += 1;
2615 }
2616
2617 return out.join('\n');
2618}
2619
2620function prettyPrintBraces (raw)
2621{
2622 const lines = String(raw || '')
2623 .replace(/\r\n/g, '\n')
2624 .split('\n');
2625 let indent = 0;
2626 const out = [];
2627
2628 for (const ln of lines)
2629 {
2630 const line = ln.trim();
2631 if (!line)
2632 {
2633 out.push('');
2634 continue;
2635 }
2636 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
2637 out.push(' '.repeat(indent) + line);
2638 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
2639 }
2640 return out.join('\n');
2641}
2642
2643function prettyPrintCode (raw, lang)
2644{
2645 const text = String(raw || '').replace(/\r\n/g, '\n');
2646 if (lang === 'json')
2647 {
2648 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
2649 }
2650 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
2651 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
2652 return text;
2653}
2654
2655function escapeHtml (s)
2656{
2657 return String(s)
2658 .replace(/&/g, '&amp;')
2659 .replace(/</g, '&lt;')
2660 .replace(/>/g, '&gt;');
2661}
2662
2663function highlightCode (raw, lang)
2664{
2665 if (lang === 'plain') return escapeHtml(raw);
2666
2667 let html = escapeHtml(raw);
2668 const stash = [];
2669 const keep = (regex, cls) =>
2670 {
2671 html = html.replace(regex, (m) =>
2672 {
2673 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
2674 return `@@TOK${idx}@@`;
2675 });
2676 };
2677
2678 if (lang === 'json')
2679 {
2680 html = html
2681 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
2682 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
2683 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
2684 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
2685 return html;
2686 }
2687
2688 if (lang === 'xml' || lang === 'html')
2689 {
2690 html = html
2691 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
2692 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
2693 return html;
2694 }
2695
2696 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
2697 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
2698 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
2699
2700 html = html
2701 .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>')
2702 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
2703
2704 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
2705 return html;
2706}
2707
2708function clearPreviewObjectUrl ()
2709{
2710 if (typeof STATE.previewCleanup === 'function')
2711 {
2712 try { STATE.previewCleanup(); } catch { /* ignore */ }
2713 }
2714 STATE.previewCleanup = null;
2715 STATE.previewDownloadAction = null;
2716 if (!STATE.previewObjectUrl) return;
2717 if (String(STATE.previewObjectUrl).startsWith('blob:'))
2718 {
2719 URL.revokeObjectURL(STATE.previewObjectUrl);
2720 }
2721 STATE.previewObjectUrl = null;
2722}
2723
2724function ensureStylesheet (id, href)
2725{
2726 let link = document.getElementById(id);
2727 if (link) return Promise.resolve(link);
2728
2729 link = document.createElement('link');
2730 link.id = id;
2731 link.rel = 'stylesheet';
2732 link.href = href;
2733
2734 return new Promise((resolve, reject) =>
2735 {
2736 link.addEventListener('load', () => resolve(link), { once: true });
2737 link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true });
2738 document.head.appendChild(link);
2739 });
2740}
2741
2742function ensureScript (id, src)
2743{
2744 let script = document.getElementById(id);
2745 if (script && window.videojs) return Promise.resolve(window.videojs);
2746
2747 if (!script)
2748 {
2749 script = document.createElement('script');
2750 script.id = id;
2751 script.src = src;
2752 }
2753
2754 return new Promise((resolve, reject) =>
2755 {
2756 script.addEventListener('load', () => resolve(window.videojs), { once: true });
2757 script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true });
2758 if (!script.isConnected) document.head.appendChild(script);
2759 });
2760}
2761
2762async function ensureVideoJsLoaded ()
2763{
2764 if (window.videojs)
2765 {
2766 configureVideoJsBuffering(window.videojs);
2767 return window.videojs;
2768 }
2769 if (!videoJsLoaderPromise)
2770 {
2771 videoJsLoaderPromise = Promise.all([
2772 ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'),
2773 ensureScript('videojs-script', '/vendor/video.js/video.min.js'),
2774 ]).then(() =>
2775 {
2776 configureVideoJsBuffering(window.videojs);
2777 return window.videojs;
2778 });
2779 }
2780 return videoJsLoaderPromise;
2781}
2782
2783function configureVideoJsBuffering (videojs)
2784{
2785 if (! VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED)
2786return;
2787
2788 if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return;
2789 videojs.__filemanagerBufferingConfigured = true;
2790
2791 try
2792 {
2793 videojs.Vhs.GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;
2794 videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;
2795 } catch
2796 {
2797 // Ignore builds that do not expose VHS buffer configuration.
2798 }
2799}
2800
2801async function createVideoStreamSessionForItem (item)
2802{
2803 return api('POST', '/files/video-stream', { filePath: item.path });
2804}
2805
2806async function releaseVideoStreamSession (sessionId, opts = {})
2807{
2808 const id = String(sessionId || '').trim();
2809 if (!id) return;
2810
2811 await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, {
2812 keepalive: !!opts.keepalive,
2813 noAutoLogout: true,
2814 }).catch(() => null);
2815}
2816
2817function releaseActivePreviewVideoStreamSession (opts = {})
2818{
2819 const sessionId = String(STATE.previewVideoStreamSessionId || '').trim();
2820 if (!sessionId) return;
2821 STATE.previewVideoStreamSessionId = null;
2822 void releaseVideoStreamSession(sessionId, opts);
2823}
2824
2825async function preparePreviewDownload (item)
2826{
2827 const blob = await fetchFileBlob(item);
2828 if (!blob)
2829 {
2830 toast('Download failed.', 'err');
2831 return;
2832 }
2833
2834 const objectUrl = URL.createObjectURL(blob);
2835 triggerDownload(item.name, objectUrl);
2836 setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
2837}
2838
2839async function renderStreamedVideoPreview (item, targetEl)
2840{
2841 const videojs = await ensureVideoJsLoaded();
2842 const session = await createVideoStreamSessionForItem(item);
2843 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
2844 const prefs = loadUserVideoPrefs();
2845 applyUserVideoTextTrackPrefs();
2846
2847 if ((session.subtitleSummary && session.subtitleSummary.total > 0) && !(session.subtitleTracks || []).length)
2848 {
2849 toast('This video has subtitle tracks, but none are compatible with web playback.', 'err');
2850 }
2851
2852 STATE.previewDownloadAction = () => preparePreviewDownload(item);
2853
2854 const video = document.createElement('video');
2855 video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';
2856 video.controls = true;
2857 video.preload = 'auto';
2858 video.playsInline = true;
2859 targetEl.classList.add('preview-expand-content--video');
2860 targetEl.appendChild(video);
2861
2862 const player = videojs(video, {
2863 controls: true,
2864 fluid: false,
2865 fill: true,
2866 responsive: false,
2867 preload: 'auto',
2868 controlBar: {
2869 currentTimeDisplay: true,
2870 timeDivider: true,
2871 durationDisplay: true,
2872 remainingTimeDisplay: false,
2873 },
2874 sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],
2875 tracks: (session.subtitleTracks || []).map((track) => ({
2876 kind: 'subtitles',
2877 src: track.src,
2878 srclang: track.language || 'und',
2879 label: track.label,
2880 default: !!track.default,
2881 })),
2882 });
2883
2884 const trackPrefs = bindUserVideoTrackPrefs(player, prefs);
2885
2886 ensureVideoPlaybackUi(player, session.durationSeconds);
2887
2888 let sentPartway = false;
2889 let sentFully = false;
2890 const markWatch = async () =>
2891 {
2892 let ratio = 0;
2893 try
2894 {
2895 const duration = Number(player.duration());
2896 const current = Number(player.currentTime());
2897 if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current))
2898 {
2899 ratio = current / duration;
2900 }
2901 } catch
2902 {
2903 return;
2904 }
2905
2906 if (ratio >= 0.7)
2907 {
2908 if (sentFully) return;
2909 sentPartway = true;
2910 sentFully = true;
2911 void reportWatchProgress(item.path, ratio);
2912 return;
2913 }
2914
2915 if (ratio >= 0.05)
2916 {
2917 if (sentPartway) return;
2918 sentPartway = true;
2919 void reportWatchProgress(item.path, ratio);
2920 }
2921 };
2922
2923 player.ready(() =>
2924 {
2925 const volume = Number(prefs.volume);
2926 if (Number.isFinite(volume))
2927 {
2928 player.volume(Math.max(0, Math.min(1, volume)));
2929 }
2930 trackPrefs.applySavedTracks();
2931 });
2932
2933 player.on('loadedmetadata', trackPrefs.applySavedTracks);
2934 player.on('loadedplaylist', trackPrefs.applySavedTracks);
2935
2936 player.on('timeupdate', markWatch);
2937 player.on('ended', () =>
2938 {
2939 sentPartway = true;
2940 sentFully = true;
2941 void reportWatchProgress(item.path, 1);
2942 });
2943 player.on('volumechange', () =>
2944 {
2945 const v = Number(player.volume());
2946 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
2947 });
2948
2949 STATE.previewCleanup = () =>
2950 {
2951 releaseActivePreviewVideoStreamSession();
2952 try { markWatch(); } catch { /* ignore */ }
2953 try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
2954 try { trackPrefs.detach(); } catch { /* ignore */ }
2955 try { player.dispose(); } catch { /* ignore */ }
2956 };
2957}
2958
2959function fileAccentColor (name)
2960{
2961 const ext = extOf(name || '');
2962 if (IMAGE_EXTS.has(ext)) return '#3fcf8e';
2963 if (VIDEO_EXTS.has(ext)) return '#e05c6e';
2964 if (AUDIO_EXTS.has(ext)) return '#c084fc';
2965 if (DOC_EXTS.has(ext)) return '#f97316';
2966 if (CODE_EXTS.has(ext)) return '#38bdf8';
2967 if (ARCHIVE_EXTS.has(ext)) return '#facc15';
2968 return '#7880a0';
2969}
2970
2971function animateRect (el, fromRect, toRect, opts = {})
2972{
2973 const duration = opts.duration == null ? 260 : opts.duration;
2974 const easeOut = (t) => 1 - Math.pow(1 - t, 3);
2975
2976 el.style.left = `${fromRect.left}px`;
2977 el.style.top = `${fromRect.top}px`;
2978 el.style.width = `${fromRect.width}px`;
2979 el.style.height = `${fromRect.height}px`;
2980
2981 return new Promise((resolve) =>
2982 {
2983 const t0 = performance.now();
2984
2985 function frame (now)
2986 {
2987 const raw = Math.min((now - t0) / duration, 1);
2988 const t = easeOut(raw);
2989
2990 const left = fromRect.left + (toRect.left - fromRect.left) * t;
2991 const top = fromRect.top + (toRect.top - fromRect.top) * t;
2992 const width = fromRect.width + (toRect.width - fromRect.width) * t;
2993 const height = fromRect.height + (toRect.height - fromRect.height) * t;
2994
2995 el.style.left = `${left}px`;
2996 el.style.top = `${top}px`;
2997 el.style.width = `${width}px`;
2998 el.style.height = `${height}px`;
2999
3000 if (raw < 1)
3001 {
3002 requestAnimationFrame(frame);
3003 } else
3004 {
3005 resolve();
3006 }
3007 }
3008
3009 requestAnimationFrame(frame);
3010 });
3011}
3012
3013async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent)
3014{
3015 if (!tileEl || !sourceSvgEl) return false;
3016
3017 if (STATE.previewExpandState)
3018 {
3019 await closeExpandedTilePreview();
3020 }
3021
3022 const iconEl = tileEl.querySelector('.icon');
3023 const nameEl = tileEl.querySelector('.name');
3024 if (!iconEl) return false;
3025
3026 const startRect = tileEl.getBoundingClientRect();
3027 const targetW = Math.min(window.innerWidth * 0.94, 1100);
3028 const targetH = Math.min(window.innerHeight * 0.9, 860);
3029 const targetRect = {
3030 left: (window.innerWidth - targetW) / 2,
3031 top: (window.innerHeight - targetH) / 2,
3032 width: targetW,
3033 height: targetH,
3034 };
3035
3036 const backdrop = document.createElement('div');
3037 backdrop.className = 'preview-backdrop';
3038 document.body.appendChild(backdrop);
3039
3040 const parent = tileEl.parentNode;
3041 const nextSibling = tileEl.nextSibling;
3042 const iconHtml = iconEl.innerHTML;
3043 const originalIconSvg = iconEl.querySelector('svg');
3044
3045 tileEl.remove();
3046 document.body.appendChild(tileEl);
3047 tileEl.classList.add('file-item--preview');
3048 tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name));
3049 tileEl.style.position = 'fixed';
3050 tileEl.style.left = `${startRect.left}px`;
3051 tileEl.style.top = `${startRect.top}px`;
3052 tileEl.style.width = `${startRect.width}px`;
3053 tileEl.style.height = `${startRect.height}px`;
3054 tileEl.style.margin = '0';
3055 tileEl.style.zIndex = '10000';
3056
3057 if (nameEl) nameEl.style.display = 'none';
3058
3059 const titleEl = document.createElement('div');
3060 titleEl.className = 'preview-expand-title';
3061 titleEl.textContent = item.name;
3062
3063 const closeBtn = document.createElement('button');
3064 closeBtn.className = 'preview-expand-close';
3065 closeBtn.type = 'button';
3066 closeBtn.textContent = '×';
3067 closeBtn.setAttribute('aria-label', 'Close preview');
3068
3069 const dlBtn = document.createElement('button');
3070 dlBtn.className = 'preview-expand-download';
3071 dlBtn.type = 'button';
3072 dlBtn.textContent = 'Download';
3073 dlBtn.addEventListener('click', async (e) =>
3074 {
3075 e.stopPropagation();
3076 if (STATE.previewDownloadAction)
3077 {
3078 await STATE.previewDownloadAction();
3079 return;
3080 }
3081 if (!STATE.previewObjectUrl)
3082 {
3083 toast('Preview still loading.', 'err');
3084 return;
3085 }
3086 triggerDownload(item.name, STATE.previewObjectUrl);
3087 });
3088
3089 const shareBtn = document.createElement('button');
3090 shareBtn.className = 'preview-expand-share';
3091 shareBtn.type = 'button';
3092 shareBtn.textContent = 'Share';
3093 shareBtn.addEventListener('click', (e) =>
3094 {
3095 e.stopPropagation();
3096 openShareModal(item);
3097 });
3098
3099 const actionsEl = document.createElement('div');
3100 actionsEl.className = 'preview-expand-actions';
3101 actionsEl.appendChild(shareBtn);
3102 actionsEl.appendChild(dlBtn);
3103
3104 iconEl.innerHTML = '';
3105
3106 if (originalIconSvg)
3107 {
3108 const outline = originalIconSvg.cloneNode(true);
3109 outline.classList.add('preview-expand-outline');
3110 iconEl.appendChild(outline);
3111 }
3112
3113 const previewMount = document.createElement('div');
3114 previewMount.className = 'preview-expand-content';
3115 iconEl.appendChild(previewMount);
3116
3117 // Show spinner during expansion animation; content loads after it finishes
3118 const spinner = document.createElement('div');
3119 spinner.className = 'preview-loading-spinner';
3120 previewMount.appendChild(spinner);
3121
3122 tileEl.insertBefore(titleEl, tileEl.firstChild);
3123 tileEl.appendChild(closeBtn);
3124 tileEl.appendChild(actionsEl);
3125
3126 STATE.previewExpandState = {
3127 item,
3128 requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)),
3129 tileEl,
3130 sourceSvgEl,
3131 parent,
3132 nextSibling,
3133 iconEl,
3134 iconHtml,
3135 nameEl,
3136 backdrop,
3137 closeBtn,
3138 dlBtn,
3139 shareBtn,
3140 actionsEl,
3141 titleEl,
3142 previewMount,
3143 startRect,
3144 };
3145
3146 const onBackdrop = (e) =>
3147 {
3148 if (e.target === backdrop) closePreview();
3149 };
3150 const onClose = () => closePreview({ force: true });
3151 backdrop.addEventListener('click', onBackdrop);
3152 closeBtn.addEventListener('click', onClose);
3153 STATE.previewExpandState.onBackdrop = onBackdrop;
3154 STATE.previewExpandState.onClose = onClose;
3155
3156 requestAnimationFrame(() => backdrop.classList.add('visible'));
3157 await animateRect(tileEl, startRect, targetRect);
3158
3159 tileEl.style.left = `${targetRect.left}px`;
3160 tileEl.style.top = `${targetRect.top}px`;
3161 tileEl.style.width = `${targetRect.width}px`;
3162 tileEl.style.height = `${targetRect.height}px`;
3163
3164 try
3165 {
3166 await loadPreviewContent(previewMount);
3167 } catch
3168 {
3169 if (previewMount.isConnected)
3170 {
3171 previewMount.innerHTML = '';
3172 const msg = document.createElement('p');
3173 msg.className = 'preview-unsupported';
3174 msg.textContent = 'Preview failed to load. You can try again.';
3175 previewMount.appendChild(msg);
3176 }
3177 }
3178
3179 return true;
3180}
3181
3182async function closeExpandedTilePreview ()
3183{
3184 const st = STATE.previewExpandState;
3185 if (!st) return;
3186
3187 st.backdrop.classList.remove('visible');
3188 if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop);
3189 if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose);
3190
3191 const fromRect = st.tileEl.getBoundingClientRect();
3192 await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 });
3193
3194 st.tileEl.classList.remove('file-item--preview');
3195 st.tileEl.style.position = '';
3196 st.tileEl.style.left = '';
3197 st.tileEl.style.top = '';
3198 st.tileEl.style.width = '';
3199 st.tileEl.style.height = '';
3200 st.tileEl.style.margin = '';
3201 st.tileEl.style.zIndex = '';
3202
3203 if (st.titleEl) st.titleEl.remove();
3204 if (st.closeBtn) st.closeBtn.remove();
3205 if (st.actionsEl) st.actionsEl.remove();
3206 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
3207 if (st.nameEl) st.nameEl.style.display = '';
3208
3209 if (st.parent)
3210 {
3211 if (st.nextSibling && st.nextSibling.parentNode === st.parent)
3212 {
3213 st.parent.insertBefore(st.tileEl, st.nextSibling);
3214 } else
3215 {
3216 st.parent.appendChild(st.tileEl);
3217 }
3218 }
3219
3220 if (st.backdrop) st.backdrop.remove();
3221 STATE.previewExpandState = null;
3222}
3223
3224async function closePreview (opts = {})
3225{
3226 if (STATE.previewClosing) return;
3227 if (STATE.previewExpandState)
3228 {
3229 if (STATE.previewExpandState.requireExplicitClose && !opts.force)
3230 {
3231 return;
3232 }
3233
3234 STATE.previewClosing = true;
3235 clearPreviewObjectUrl();
3236 try
3237 {
3238 await closeExpandedTilePreview();
3239 STATE.previewSourceEl = null;
3240 } finally
3241 {
3242 STATE.previewClosing = false;
3243 }
3244 }
3245}
3246
3247async function fetchFileBlob (item)
3248{
3249 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
3250 try
3251 {
3252 const res = await fetch(url, {
3253 headers: {
3254 Authorization: 'Bearer ' + STATE.token,
3255 'X-Fp': getFingerprint(),
3256 },
3257 });
3258 if (!res.ok) throw new Error('Download failed.');
3259 return await res.blob();
3260 } catch
3261 {
3262 return null;
3263 }
3264}
3265
3266function triggerDownload (filename, objectUrl)
3267{
3268 const a = document.createElement('a');
3269 a.href = objectUrl;
3270 a.download = filename;
3271 a.click();
3272}
3273
3274async function renderPreviewBody (item, blob, objectUrl, targetEl = null)
3275{
3276 const body = targetEl || document.getElementById('preview-body');
3277 body.innerHTML = '';
3278
3279 const mime = String(blob.type || '').toLowerCase();
3280 const previewable = isInlinePreviewableBlob(blob, item.name);
3281
3282 if (!previewable)
3283 {
3284 const msg = document.createElement('p');
3285 msg.className = 'preview-unsupported';
3286 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
3287 body.appendChild(msg);
3288 return;
3289 }
3290
3291 if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name)))
3292 {
3293 const img = document.createElement('img');
3294 img.className = 'preview-media';
3295 img.src = objectUrl;
3296 img.alt = item.name;
3297 body.appendChild(img);
3298 return;
3299 }
3300
3301 if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name)))
3302 {
3303 const video = document.createElement('video');
3304 video.className = 'preview-media';
3305 video.src = objectUrl;
3306 video.controls = true;
3307 video.preload = 'metadata';
3308 body.appendChild(video);
3309 return;
3310 }
3311
3312 if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name)))
3313 {
3314 const audio = document.createElement('audio');
3315 audio.className = 'preview-audio';
3316 audio.src = objectUrl;
3317 audio.controls = true;
3318 body.appendChild(audio);
3319 return;
3320 }
3321
3322 if (mime === 'application/pdf')
3323 {
3324 const frame = document.createElement('iframe');
3325 frame.className = 'preview-frame';
3326 frame.src = objectUrl;
3327 frame.title = item.name;
3328 body.appendChild(frame);
3329 return;
3330 }
3331
3332 if (isTextLikeBlob(blob, item.name))
3333 {
3334 const text = await blob.text();
3335 const lang = detectCodeLanguage(item.name, mime);
3336 const formatted = prettyPrintCode(text, lang);
3337 const pre = document.createElement('pre');
3338 pre.className = 'preview-text preview-code';
3339 pre.innerHTML = highlightCode(formatted, lang);
3340 body.appendChild(pre);
3341 return;
3342 }
3343
3344 const msg = document.createElement('p');
3345 msg.className = 'preview-unsupported';
3346 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
3347 body.appendChild(msg);
3348}
3349
3350async function downloadOrView (item, sourceSvgEl = null)
3351{
3352 if (STATE.previewExpandState)
3353 {
3354 await closePreview({ force: true });
3355 }
3356
3357 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
3358 if (sourceTileEl)
3359 {
3360 STATE.previewSourceEl = sourceSvgEl;
3361 const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>
3362 {
3363 if (VIDEO_EXTS.has(extOf(item.name)))
3364 {
3365 clearPreviewObjectUrl();
3366 previewMount.innerHTML = '';
3367 await renderStreamedVideoPreview(item, previewMount);
3368 return;
3369 }
3370
3371 const blob = await fetchFileBlob(item);
3372 if (!blob) throw new Error('Download failed');
3373
3374 clearPreviewObjectUrl();
3375 const objectUrl = URL.createObjectURL(blob);
3376 STATE.previewObjectUrl = objectUrl;
3377
3378 if (!previewMount.isConnected) return;
3379
3380 previewMount.innerHTML = '';
3381 await renderPreviewBody(item, blob, objectUrl, previewMount);
3382 });
3383 if (expanded) return;
3384 }
3385
3386 toast('Preview unavailable — no source tile found.', 'err');
3387}
3388
3389// ───────────────────────────────────────────────────────────────────────────
3390// UPLOAD
3391// ───────────────────────────────────────────────────────────────────────────
3392
3393function canWrite (item = null)
3394{
3395 if (STATE.isAdmin) return true;
3396 const root = item && item._root
3397 ? item._root
3398 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
3399 if (!root) return false;
3400 const p = STATE.permissions[rootPermissionLabel(root)];
3401 return p && p.write;
3402}
3403
3404async function uploadFiles (fileList)
3405{
3406 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3407 if (!canWrite()) { toast('No write access.', 'err'); return; }
3408
3409 const files = Array.from(fileList || []);
3410 if (!files.length) return;
3411
3412 // Show upload bar
3413 const wrap = document.createElement('div');
3414 wrap.className = 'upload-bar-wrap';
3415 wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
3416 document.body.appendChild(wrap);
3417 STATE.uploadInProgress = true;
3418
3419 try
3420 {
3421 const existingNames = await listDirNameSet(STATE.currentDir);
3422 let done = 0;
3423 let uploaded = 0;
3424
3425 for (const original of files)
3426 {
3427 let fileToUpload = original;
3428
3429 if (existingNames.has(original.name))
3430 {
3431 const suggested = nextAvailableName(original.name, existingNames);
3432 const decision = await showFileConflictChoice(original.name, suggested, 'upload');
3433 if (decision === 'cancel')
3434 {
3435 done++;
3436 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
3437 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
3438 continue;
3439 }
3440
3441 if (decision === 'rename')
3442 {
3443 fileToUpload = cloneFileWithName(original, suggested);
3444 }
3445 }
3446
3447 await uploadSingleFile(fileToUpload, STATE.currentDir);
3448 existingNames.add(fileToUpload.name);
3449 done++;
3450 uploaded++;
3451 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
3452 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
3453 }
3454
3455 toast(`Uploaded ${uploaded} file(s).`, 'ok');
3456 await navigateTo(STATE.currentDir, STATE.currentRoot);
3457 } catch (err)
3458 {
3459 toast(err.message, 'err');
3460 } finally
3461 {
3462 STATE.uploadInProgress = false;
3463 wrap.remove();
3464 }
3465}
3466
3467async function uploadSingleFile (file, targetDir)
3468{
3469 const formData = new FormData();
3470 formData.append('files', file);
3471
3472 await new Promise((resolve, reject) =>
3473 {
3474 const xhr = new XMLHttpRequest();
3475 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
3476 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
3477 xhr.setRequestHeader('X-Fp', getFingerprint());
3478 xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
3479 xhr.onload = () => xhr.status === 200
3480 ? resolve()
3481 : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
3482 xhr.onerror = () => reject(new Error('Network error'));
3483 xhr.send(formData);
3484 });
3485}
3486
3487async function ensureServerDir (baseDir, relativeDir)
3488{
3489 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
3490 let current = baseDir;
3491 for (const part of parts)
3492 {
3493 try
3494 {
3495 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
3496 current = resp && resp.path ? resp.path : joinServerPath(current, part);
3497 } catch (err)
3498 {
3499 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
3500 current = joinServerPath(current, part);
3501 }
3502 }
3503 return current;
3504}
3505
3506async function uploadFolderInputFiles (fileList)
3507{
3508 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3509 if (!canWrite()) { toast('No write access.', 'err'); return; }
3510 if (!fileList || !fileList.length) return;
3511
3512 const files = Array.from(fileList);
3513 const total = files.length;
3514 let done = 0;
3515
3516 const wrap = document.createElement('div');
3517 wrap.className = 'upload-bar-wrap';
3518 wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
3519 document.body.appendChild(wrap);
3520 STATE.uploadInProgress = true;
3521
3522 try
3523 {
3524 const dirCache = new Map();
3525 dirCache.set('', STATE.currentDir);
3526
3527 for (const file of files)
3528 {
3529 const rel = file.webkitRelativePath || file.name;
3530 const relParts = rel.split(/[\\/]/).filter(Boolean);
3531 const relDir = relParts.slice(0, -1).join('/');
3532
3533 if (!dirCache.has(relDir))
3534 {
3535 const parentRel = relParts.slice(0, -2).join('/');
3536 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
3537 const thisName = relParts[relParts.length - 2];
3538
3539 try
3540 {
3541 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
3542 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
3543 } catch (err)
3544 {
3545 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
3546 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
3547 }
3548 }
3549
3550 const targetDir = dirCache.get(relDir) || STATE.currentDir;
3551 await uploadSingleFile(file, targetDir);
3552 done++;
3553 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
3554 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
3555 }
3556
3557 toast(`Uploaded ${total} file(s).`, 'ok');
3558 await navigateTo(STATE.currentDir, STATE.currentRoot);
3559 } catch (err)
3560 {
3561 toast(err.message, 'err');
3562 } finally
3563 {
3564 STATE.uploadInProgress = false;
3565 wrap.remove();
3566 }
3567}
3568
3569// ───────────────────────────────────────────────────────────────────────────
3570// FOLDER DRAG-AND-DROP (recursive)
3571// ───────────────────────────────────────────────────────────────────────────
3572
3573/**
3574 * Reads all readEntries batches from a DirectoryReader (browsers may return
3575 * results in chunks; we must keep calling until we get an empty array).
3576 */
3577function readAllEntries (reader)
3578{
3579 return new Promise((resolve, reject) =>
3580 {
3581 const all = [];
3582 function next ()
3583 {
3584 reader.readEntries(batch =>
3585 {
3586 if (!batch.length) { resolve(all); return; }
3587 all.push(...batch);
3588 next();
3589 }, reject);
3590 }
3591 next();
3592 });
3593}
3594
3595/**
3596 * Recursively walk a FileSystemEntry tree, creating server-side directories
3597 * on the fly and collecting { file, targetDir } pairs for upload.
3598 */
3599async function collectEntries (entry, serverDir, toUpload)
3600{
3601 if (entry.isFile)
3602 {
3603 const file = await new Promise((res, rej) => entry.file(res, rej));
3604 toUpload.push({ file, targetDir: serverDir });
3605 } else if (entry.isDirectory)
3606 {
3607 // Ask the server to create the directory; it returns the canonical path.
3608 let newServerDir;
3609 try
3610 {
3611 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
3612 newServerDir = resp.path;
3613 } catch
3614 {
3615 // Directory may already exist — reconstruct path from what we know.
3616 // The server always returns JSON with {error} on failure, so we can
3617 // still continue by falling back to a best-effort path join.
3618 // We rely on the fact that the server separator is consistent within
3619 // a session (the list/browse API already returned paths in that format).
3620 const sep = serverDir.includes('\\') ? '\\' : '/';
3621 newServerDir = serverDir + sep + entry.name;
3622 }
3623 const reader = entry.createReader();
3624 const subEntries = await readAllEntries(reader);
3625 for (const sub of subEntries)
3626 {
3627 await collectEntries(sub, newServerDir, toUpload);
3628 }
3629 }
3630}
3631
3632async function uploadEntries (entries)
3633{
3634 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3635 if (!canWrite()) { toast('No write access.', 'err'); return; }
3636
3637 const wrap = document.createElement('div');
3638 wrap.className = 'upload-bar-wrap';
3639 wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
3640 document.body.appendChild(wrap);
3641 STATE.uploadInProgress = true;
3642
3643 try
3644 {
3645 const toUpload = [];
3646 for (const entry of entries)
3647 {
3648 await collectEntries(entry, STATE.currentDir, toUpload);
3649 }
3650
3651 if (!toUpload.length) { toast('No files found.', 'err'); return; }
3652
3653 let done = 0;
3654 const total = toUpload.length;
3655 const updateBar = () =>
3656 {
3657 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
3658 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
3659 };
3660 updateBar();
3661
3662 for (const { file, targetDir } of toUpload)
3663 {
3664 await uploadSingleFile(file, targetDir);
3665 done++;
3666 updateBar();
3667 }
3668
3669 toast(`Uploaded ${total} file(s).`, 'ok');
3670 await navigateTo(STATE.currentDir, STATE.currentRoot);
3671 } catch (err)
3672 {
3673 toast(err.message, 'err');
3674 } finally
3675 {
3676 STATE.uploadInProgress = false;
3677 wrap.remove();
3678 }
3679}
3680
3681// DRAG-AND-DROP
3682// ───────────────────────────────────────────────────────────────────────────
3683
3684function initDragDrop ()
3685{
3686 const main = document.getElementById('main-content');
3687 const dropOvl = document.getElementById('drop-overlay');
3688 let dragDepth = 0;
3689
3690 main.addEventListener('dragenter', e =>
3691 {
3692 e.preventDefault();
3693 dragDepth++;
3694 dropOvl.classList.remove('hidden');
3695 });
3696 main.addEventListener('dragleave', () =>
3697 {
3698 dragDepth--;
3699 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
3700 });
3701 main.addEventListener('dragover', e => e.preventDefault());
3702 main.addEventListener('drop', async e =>
3703 {
3704 e.preventDefault();
3705 dragDepth = 0;
3706 dropOvl.classList.add('hidden');
3707 if (!canWrite()) { toast('No write access.', 'err'); return; }
3708
3709 const items = Array.from(e.dataTransfer.items || []);
3710 // Use the FileSystem Entry API when available so we can handle folders.
3711 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
3712 {
3713 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
3714 if (entries.some(en => en.isDirectory))
3715 {
3716 await uploadEntries(entries);
3717 return;
3718 }
3719 }
3720 // Plain files only — use the fast batch path.
3721 const files = e.dataTransfer.files;
3722 if (files.length) await uploadFiles(files);
3723 });
3724}
3725
3726// ───────────────────────────────────────────────────────────────────────────
3727// RENAME
3728// ───────────────────────────────────────────────────────────────────────────
3729
3730function openRenameModal (item)
3731{
3732 const modal = document.getElementById('rename-modal');
3733 modal.classList.remove('hidden');
3734 const input = document.getElementById('rename-input');
3735 input.value = item.name;
3736 input.focus();
3737 input.select();
3738 document.getElementById('rename-error').classList.add('hidden');
3739 document.getElementById('rename-form').onsubmit = async (e) =>
3740 {
3741 e.preventDefault();
3742 const newName = input.value.trim();
3743 if (!newName) return;
3744 try
3745 {
3746 if (item._root)
3747 {
3748 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
3749 } else
3750 {
3751 await api('POST', '/files/rename', { from: item.path, to: newName });
3752 }
3753 modal.classList.add('hidden');
3754 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
3755 if (item._root)
3756 {
3757 await loadRoots({
3758 preferredDir: STATE.currentDir,
3759 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
3760 });
3761 } else
3762 {
3763 await navigateTo(STATE.currentDir, STATE.currentRoot);
3764 }
3765 } catch (err)
3766 {
3767 document.getElementById('rename-error').textContent = err.message;
3768 document.getElementById('rename-error').classList.remove('hidden');
3769 }
3770 };
3771}
3772
3773// ───────────────────────────────────────────────────────────────────────────
3774// DELETE
3775// ───────────────────────────────────────────────────────────────────────────
3776
3777async function deleteItem (item)
3778{
3779 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
3780 try
3781 {
3782 await api('POST', '/files/delete', { path: item.path });
3783 toast('Deleted.', 'ok');
3784 closeSidebar();
3785 await navigateTo(STATE.currentDir, STATE.currentRoot);
3786 } catch (err)
3787 {
3788 toast(err.message, 'err');
3789 }
3790}
3791
3792// ───────────────────────────────────────────────────────────────────────────
3793// ADMIN PANEL
3794// ───────────────────────────────────────────────────────────────────────────
3795
3796let _adminUpdateStatus = null;
3797
3798async function openAdminModal ()
3799{
3800 document.getElementById('admin-modal').classList.remove('hidden');
3801 await refreshAdminConfig();
3802 await refreshAdminUsers();
3803 void refreshAdminUpdateStatus();
3804}
3805
3806async function refreshAdminConfig ()
3807{
3808 const data = await api('GET', '/admin/config');
3809 if (!data) return;
3810
3811 const userPathInput = document.getElementById('admin-user-path');
3812 const sizeInput = document.getElementById('admin-user-size-limit');
3813 if (userPathInput) userPathInput.value = data.userPath || '';
3814 if (sizeInput)
3815 {
3816 sizeInput.value = data.userFolderSizeLimit ? formatBytes(data.userFolderSizeLimit) : '';
3817 updateAdminSizeFeedback(sizeInput.value);
3818 }
3819
3820 const container = document.getElementById('admin-paths');
3821 container.innerHTML = '';
3822 for (const p of data.paths)
3823 {
3824 const row = document.createElement('div');
3825 row.className = 'path-row';
3826 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
3827 row.querySelector('button').addEventListener('click', () =>
3828 {
3829 row.remove();
3830 });
3831 container.appendChild(row);
3832 }
3833}
3834
3835async function refreshAdminUsers ()
3836{
3837 const data = await api('GET', '/admin/users');
3838 if (!data) return;
3839 const container = document.getElementById('admin-users-list');
3840 container.innerHTML = '';
3841
3842 // Need paths for permission rows
3843 const cfg = await api('GET', '/admin/config');
3844 const paths = cfg ? (cfg.effectivePaths || []) : [];
3845
3846 for (const u of data.users)
3847 {
3848 const row = document.createElement('div');
3849 row.className = 'user-row';
3850 row.innerHTML = `
3851 <span class="user-name">${u.username}</span>
3852 ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''}
3853 <button data-id="${u.id}" data-action="edit">Edit</button>
3854 ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`}
3855 `;
3856 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
3857 openUserModal(u, paths));
3858 const deleteBtn = row.querySelector('[data-action="delete"]');
3859 if (deleteBtn) deleteBtn.addEventListener('click', async () =>
3860 {
3861 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
3862 try
3863 {
3864 await api('DELETE', `/admin/users/${u.id}`);
3865 toast('User deleted.', 'ok');
3866 await refreshAdminUsers();
3867 } catch (err) { toast(err.message, 'err'); }
3868 });
3869 container.appendChild(row);
3870 }
3871}
3872
3873async function refreshAdminUpdateStatus ()
3874{
3875 const btn = document.getElementById('admin-shutdown-btn');
3876 _adminUpdateStatus = null;
3877 btn.textContent = 'Shut down server';
3878
3879 try
3880 {
3881 const data = await api('GET', '/admin/update-status');
3882 if (!data) return;
3883 _adminUpdateStatus = data;
3884
3885 if (!data.underSystemd)
3886 {
3887 btn.textContent = 'Shut down server';
3888 }
3889 else if (data.commitsAhead.length === 0)
3890 {
3891 btn.textContent = 'Restart Server';
3892 }
3893 else
3894 {
3895 btn.textContent = 'Restart & Update';
3896 }
3897 }
3898 catch
3899 {
3900 // Not critical; button stays as "Shut down server".
3901 }
3902}
3903
3904function openUserModal (user, paths)
3905{
3906 const modal = document.getElementById('user-modal');
3907 modal.classList.remove('hidden');
3908 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
3909 document.getElementById('user-error').classList.add('hidden');
3910
3911 const usernameInput = document.getElementById('user-username');
3912 usernameInput.value = user ? user.username : '';
3913 usernameInput.readOnly = !!user;
3914
3915 document.getElementById('user-password').value = '';
3916 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
3917
3918 // Password placeholder
3919 document.getElementById('user-password').placeholder =
3920 user ? 'Leave blank to keep current' : 'Min 8 characters';
3921
3922 // Build permissions grid
3923 const permDiv = document.getElementById('user-permissions');
3924 permDiv.innerHTML = '';
3925 if (paths.length)
3926 {
3927 const heading = document.createElement('h4');
3928 heading.textContent = 'Path Permissions';
3929 permDiv.appendChild(heading);
3930
3931 const isAdminUser = !!(user && user.isAdmin);
3932 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
3933 const adminChk = document.getElementById('user-is-admin');
3934 const rebuildPermRows = (admin) =>
3935 {
3936 permDiv.querySelectorAll('.perm-row').forEach(r =>
3937 {
3938 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
3939 {
3940 cb.disabled = admin;
3941 if (admin) cb.checked = true;
3942 });
3943 r.title = admin ? 'Admins always have full access' : '';
3944 });
3945 };
3946 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
3947
3948 const syncReadWriteConstraints = (row, admin = false) =>
3949 {
3950 const readCb = row.querySelector('input[data-type="read"]');
3951 const writeCb = row.querySelector('input[data-type="write"]');
3952 if (!readCb || !writeCb) return;
3953
3954 if (admin)
3955 {
3956 readCb.checked = true;
3957 writeCb.checked = true;
3958 readCb.disabled = true;
3959 writeCb.disabled = true;
3960 return;
3961 }
3962
3963 readCb.disabled = false;
3964 if (!readCb.checked)
3965 {
3966 writeCb.checked = false;
3967 writeCb.disabled = true;
3968 }
3969 else
3970 {
3971 writeCb.disabled = false;
3972 }
3973 };
3974
3975 const syncAllReadWriteConstraints = () =>
3976 {
3977 const admin = adminChk.checked;
3978 permDiv.querySelectorAll('.perm-row').forEach((row) =>
3979 {
3980 syncReadWriteConstraints(row, admin);
3981 });
3982 };
3983
3984 for (const p of paths)
3985 {
3986 const label = p.split(/[\\/]/).pop();
3987 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
3988 const row = document.createElement('div');
3989 row.className = 'perm-row';
3990 const readChecked = isAdminUser || perms.read;
3991 const writeChecked = isAdminUser || perms.write;
3992 row.innerHTML = `
3993 <span class="perm-label">${label}</span>
3994 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label>
3995 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label>
3996 `;
3997 if (isAdminUser) row.title = 'Admins always have full access';
3998 const readCb = row.querySelector('input[data-type="read"]');
3999 if (readCb)
4000 {
4001 readCb.addEventListener('change', () =>
4002 {
4003 syncReadWriteConstraints(row, adminChk.checked);
4004 });
4005 }
4006 permDiv.appendChild(row);
4007 }
4008
4009 syncAllReadWriteConstraints();
4010 adminChk.addEventListener('change', syncAllReadWriteConstraints);
4011 }
4012
4013 document.getElementById('user-form').onsubmit = async (e) =>
4014 {
4015 e.preventDefault();
4016 const password = document.getElementById('user-password').value;
4017 const isAdmin = document.getElementById('user-is-admin').checked;
4018 const permissions = {};
4019 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
4020 {
4021 const lbl = cb.dataset.label;
4022 if (!permissions[lbl]) permissions[lbl] = {};
4023 permissions[lbl][cb.dataset.type] = cb.checked;
4024 });
4025
4026 try
4027 {
4028 if (user)
4029 {
4030 const body = { isAdmin, permissions };
4031 if (password) body.password = password;
4032 await api('PATCH', `/admin/users/${user.id}`, body);
4033 } else
4034 {
4035 const uname = document.getElementById('user-username').value.trim();
4036 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
4037 }
4038 modal.classList.add('hidden');
4039 toast('User saved.', 'ok');
4040 await refreshAdminUsers();
4041 } catch (err)
4042 {
4043 document.getElementById('user-error').textContent = err.message;
4044 document.getElementById('user-error').classList.remove('hidden');
4045 }
4046 };
4047}
4048
4049// ───────────────────────────────────────────────────────────────────────────
4050// SVG ICONS
4051// ───────────────────────────────────────────────────────────────────────────
4052
4053const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
4054const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
4055const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
4056const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
4057const CODE_EXTS = new Set(['js', 'ts', 'py', 'rb', 'go', 'rs', 'c', 'cpp', 'h', 'cs', 'java', 'php', 'html', 'css', 'json', 'xml', 'yaml', 'yml', 'sh', 'bash', 'md', 'txt']);
4058const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
4059const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024;
4060
4061function iconFolder (size = 52)
4062{
4063 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
4064 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
4065 <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
4066 </svg>`;
4067}
4068
4069function iconFile (name, size = 52)
4070{
4071 const color = fileAccentColor(name);
4072 let symbol = '';
4073
4074 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
4075 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
4076 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
4077 <polyline points="14 2 14 8 20 8"/>
4078 </svg>`;
4079}
4080
4081// ───────────────────────────────────────────────────────────────────────────
4082// EVENT WIRING
4083// ───────────────────────────────────────────────────────────────────────────
4084
4085// ───────────────────────────────────────────────────────────────────────────
4086// THUMBNAIL PREVIEWS
4087// ───────────────────────────────────────────────────────────────────────────
4088
4089function revokeThumbnails ()
4090{
4091 STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u));
4092 STATE.thumbnailUrls = [];
4093}
4094
4095function disconnectThumbnailObserver ()
4096{
4097 if (!STATE.thumbnailObserver) return;
4098 STATE.thumbnailObserver.disconnect();
4099 STATE.thumbnailObserver = null;
4100}
4101
4102function disconnectFolderIconObserver ()
4103{
4104 if (!STATE.folderIconObserver) return;
4105 STATE.folderIconObserver.disconnect();
4106 STATE.folderIconObserver = null;
4107}
4108
4109function setThumbnailPending (iconEl, pending)
4110{
4111 if (!iconEl) return;
4112 if (pending)
4113 {
4114 iconEl.classList.add('thumb-pending');
4115 iconEl.dataset.thumbPending = '1';
4116 return;
4117 }
4118
4119 iconEl.classList.remove('thumb-pending');
4120 delete iconEl.dataset.thumbPending;
4121}
4122
4123function getThumbnailKind (name)
4124{
4125 const ext = extOf(name || '');
4126 if (IMAGE_EXTS.has(ext)) return 'image';
4127 if (CODE_EXTS.has(ext)) return 'text';
4128 return 'badge';
4129}
4130
4131function maxThumbBytesForKind (kind)
4132{
4133 if (kind === 'image') return 15 * 1024 * 1024;
4134 if (kind === 'text') return 1024 * 1024;
4135 return 0;
4136}
4137
4138function drawTokenizedLine (ctx, line, x, y)
4139{
4140 const tokenRe = /(\/\/.*$|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\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|\b\d+(?:\.\d+)?\b)/g;
4141 let last = 0;
4142 let cursor = x;
4143 for (const m of line.matchAll(tokenRe))
4144 {
4145 const i = m.index == null ? 0 : m.index;
4146 if (i > last)
4147 {
4148 const plain = line.slice(last, i);
4149 ctx.fillStyle = '#dce4ff';
4150 ctx.fillText(plain, cursor, y);
4151 cursor += ctx.measureText(plain).width;
4152 }
4153
4154 const tok = m[0];
4155 if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a';
4156 else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d';
4157 else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a';
4158 else ctx.fillStyle = '#8bb4ff';
4159
4160 ctx.fillText(tok, cursor, y);
4161 cursor += ctx.measureText(tok).width;
4162 last = i + tok.length;
4163 }
4164
4165 if (last < line.length)
4166 {
4167 const tail = line.slice(last);
4168 ctx.fillStyle = '#dce4ff';
4169 ctx.fillText(tail, cursor, y);
4170 }
4171}
4172
4173function textThumbnailDataUrl (text)
4174{
4175 const canvas = document.createElement('canvas');
4176 canvas.width = 160;
4177 canvas.height = 200;
4178 const ctx = canvas.getContext('2d');
4179 if (!ctx) return null;
4180
4181 ctx.fillStyle = '#0d111a';
4182 ctx.fillRect(0, 0, canvas.width, canvas.height);
4183 ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
4184 ctx.textBaseline = 'top';
4185
4186 const lines = String(text || '')
4187 .replace(/\r\n/g, '\n')
4188 .split('\n')
4189 .slice(0, 17);
4190
4191 let y = 8;
4192 for (const line of lines)
4193 {
4194 drawTokenizedLine(ctx, line.slice(0, 42), 6, y);
4195 y += 11;
4196 if (y > 190) break;
4197 }
4198 return canvas.toDataURL('image/png');
4199}
4200
4201function badgeThumbnailDataUrl (name, kind)
4202{
4203 const canvas = document.createElement('canvas');
4204 canvas.width = 160;
4205 canvas.height = 200;
4206 const ctx = canvas.getContext('2d');
4207 if (!ctx) return null;
4208
4209 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
4210 const color = '#5b7fff';
4211
4212 ctx.fillStyle = '#111826';
4213 ctx.fillRect(0, 0, 160, 200);
4214 ctx.fillStyle = color;
4215 ctx.fillRect(0, 0, 160, 28);
4216 ctx.fillStyle = '#ffffff';
4217 ctx.font = 'bold 12px sans-serif';
4218 ctx.textAlign = 'center';
4219 ctx.fillText(ext, 80, 8);
4220 ctx.textAlign = 'left';
4221 ctx.fillStyle = '#9fb1d8';
4222 ctx.font = '10px sans-serif';
4223 ctx.fillText('Preview', 8, 48);
4224 ctx.fillStyle = '#dce4ff';
4225 ctx.font = 'bold 11px sans-serif';
4226 ctx.fillText(ext, 8, 66);
4227 return canvas.toDataURL('image/png');
4228}
4229
4230async function buildThumbnailSource (item, blob, kind)
4231{
4232 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
4233 return badgeThumbnailDataUrl(item.name, kind);
4234}
4235
4236function observeThumbnailIcon (iconEl)
4237{
4238 if (!iconEl || !iconEl.isConnected) return;
4239 if (iconEl.dataset.thumbReady === '1') return;
4240
4241 if (!('IntersectionObserver' in window))
4242 {
4243 void loadOneThumbnail(iconEl);
4244 return;
4245 }
4246
4247 if (!STATE.thumbnailObserver)
4248 {
4249 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
4250 {
4251 for (const entry of entries)
4252 {
4253 if (!entry.isIntersecting) continue;
4254 const icon = entry.target;
4255 STATE.thumbnailObserver.unobserve(icon);
4256 void loadOneThumbnail(icon);
4257 }
4258 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
4259 }
4260
4261 STATE.thumbnailObserver.observe(iconEl);
4262}
4263
4264async function loadThumbnails ()
4265{
4266 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
4267 for (const icon of icons)
4268 {
4269 observeThumbnailIcon(icon);
4270 }
4271
4272 const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]'));
4273 for (const icon of folderIcons)
4274 {
4275 observeFolderIcon(icon);
4276 }
4277}
4278
4279async function loadOneThumbnail (iconEl)
4280{
4281 if (!iconEl.isConnected || !STATE.token) return;
4282 if (iconEl.dataset.thumbReady === '1') return;
4283 const filePath = iconEl.dataset.previewPath;
4284 const item = STATE.items.find(i => i.path === filePath);
4285 if (!item) return;
4286
4287 const kind = getThumbnailKind(item.name);
4288 let srcUrl = null;
4289
4290 if (kind === 'badge')
4291 {
4292 setThumbnailPending(iconEl, false);
4293 srcUrl = badgeThumbnailDataUrl(item.name, kind);
4294 }
4295 else if (kind === 'image')
4296 {
4297 const ext = extOf(item.name || '');
4298 const useDirectSource =
4299 ext === 'ico' ||
4300 (
4301 ext === 'svg' &&
4302 typeof item.size === 'number' &&
4303 item.size > 0 &&
4304 item.size <= MAX_DIRECT_SVG_THUMB_BYTES
4305 );
4306
4307 const url = useDirectSource
4308 ? `/api/files/download?file=${encodeURIComponent(filePath)}`
4309 : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
4310
4311 let res;
4312 try
4313 {
4314 res = await fetch(url, {
4315 headers: {
4316 Authorization: `Bearer ${STATE.token}`,
4317 'X-Fp': getFingerprint(),
4318 },
4319 });
4320 } catch
4321 {
4322 return;
4323 }
4324
4325 if (!useDirectSource && res.status === 404)
4326 {
4327 setThumbnailPending(iconEl, true);
4328 return;
4329 }
4330
4331 if (!res.ok || !iconEl.isConnected) return;
4332 setThumbnailPending(iconEl, false);
4333
4334 const blob = await res.blob();
4335 srcUrl = URL.createObjectURL(blob);
4336 STATE.thumbnailUrls.push(srcUrl);
4337 }
4338 else
4339 {
4340 setThumbnailPending(iconEl, false);
4341 const maxBytes = maxThumbBytesForKind(kind);
4342 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
4343 {
4344 srcUrl = badgeThumbnailDataUrl(item.name, kind);
4345 } else
4346 {
4347 const url = `/api/files/download?file=${encodeURIComponent(filePath)}`;
4348
4349 let res;
4350 try
4351 {
4352 res = await fetch(url, {
4353 headers: {
4354 Authorization: `Bearer ${STATE.token}`,
4355 'X-Fp': getFingerprint(),
4356 },
4357 });
4358 } catch { return; }
4359 if (!res.ok || !iconEl.isConnected) return;
4360
4361 const blob = await res.blob();
4362 srcUrl = await buildThumbnailSource(item, blob, kind);
4363 }
4364 }
4365 if (!srcUrl || !iconEl.isConnected) return;
4366
4367 const svg = iconEl.querySelector('svg');
4368 if (!svg)
4369 {
4370 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
4371 return;
4372 }
4373
4374 const NS = 'http://www.w3.org/2000/svg';
4375 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
4376
4377 // clipPath matches the main file body outline exactly (viewBox 0 0 24 24)
4378 const defs = document.createElementNS(NS, 'defs');
4379 const clipPath = document.createElementNS(NS, 'clipPath');
4380 clipPath.setAttribute('id', id);
4381 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
4382 const clipShape = document.createElementNS(NS, 'path');
4383 clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z');
4384 clipPath.appendChild(clipShape);
4385 defs.appendChild(clipPath);
4386
4387 // Image fills the file bounding box; clip keeps it inside the outline
4388 const img = document.createElementNS(NS, 'image');
4389 img.setAttribute('href', srcUrl);
4390 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
4391 img.setAttribute('x', '4');
4392 img.setAttribute('y', '2');
4393 img.setAttribute('width', '16');
4394 img.setAttribute('height', '20');
4395 img.setAttribute('clip-path', `url(#${id})`);
4396 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
4397
4398 // Prepend so existing path/polyline elements (the outline) render on top
4399 svg.prepend(img);
4400 svg.prepend(defs);
4401 iconEl.dataset.thumbReady = '1';
4402}
4403
4404// ───────────────────────────────────────────────────────────────────────────
4405// FOLDER ICON THUMBNAILS
4406// ───────────────────────────────────────────────────────────────────────────
4407
4408function observeFolderIcon (iconEl)
4409{
4410 if (!iconEl || !iconEl.isConnected) return;
4411 if (iconEl.dataset.thumbReady === '1') return;
4412
4413 if (!('IntersectionObserver' in window))
4414 {
4415 void loadOneFolderIcon(iconEl);
4416 return;
4417 }
4418
4419 if (!STATE.folderIconObserver)
4420 {
4421 STATE.folderIconObserver = new IntersectionObserver((entries) =>
4422 {
4423 for (const entry of entries)
4424 {
4425 if (!entry.isIntersecting) continue;
4426 const icon = entry.target;
4427 STATE.folderIconObserver.unobserve(icon);
4428 void loadOneFolderIcon(icon);
4429 }
4430 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
4431 }
4432
4433 STATE.folderIconObserver.observe(iconEl);
4434}
4435
4436async function loadOneFolderIcon (iconEl)
4437{
4438 if (!iconEl.isConnected || !STATE.token) return;
4439 if (iconEl.dataset.thumbReady === '1') return;
4440
4441 const folderPath = iconEl.dataset.folderPath;
4442 if (!folderPath) return;
4443
4444 let res;
4445 try
4446 {
4447 res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, {
4448 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
4449 });
4450 } catch { return; }
4451
4452 if (!res.ok || !iconEl.isConnected) return;
4453
4454 const data = await res.json();
4455 if (!data.icon) return; // No icon available — keep plain folder SVG.
4456
4457 // Fetch the thumbnail through the auth-gated endpoint.
4458 let thumbRes;
4459 try
4460 {
4461 thumbRes = await fetch(
4462 `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`,
4463 { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } },
4464 );
4465 } catch { return; }
4466
4467 if (!thumbRes.ok || !iconEl.isConnected) return;
4468
4469 const blob = await thumbRes.blob();
4470 const srcUrl = URL.createObjectURL(blob);
4471 STATE.thumbnailUrls.push(srcUrl);
4472
4473 applyFolderThumbnail(iconEl, srcUrl);
4474}
4475
4476/**
4477 * Overlays a thumbnail image inside the folder SVG outline.
4478 * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21.
4479 */
4480function applyFolderThumbnail (iconEl, srcUrl)
4481{
4482 if (!iconEl.isConnected) return;
4483 const svg = iconEl.querySelector('svg');
4484 if (!svg)
4485 {
4486 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
4487 return;
4488 }
4489
4490 const NS = 'http://www.w3.org/2000/svg';
4491 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
4492
4493 const defs = document.createElementNS(NS, 'defs');
4494 const clipPath = document.createElementNS(NS, 'clipPath');
4495 clipPath.setAttribute('id', id);
4496 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
4497 const clipShape = document.createElementNS(NS, 'path');
4498 // Folder outline path (same as iconFolder SVG path)
4499 clipShape.setAttribute('d', 'M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z');
4500 clipPath.appendChild(clipShape);
4501 defs.appendChild(clipPath);
4502
4503 // Image covers the folder body area; clip keeps it inside the outline.
4504 const img = document.createElementNS(NS, 'image');
4505 img.setAttribute('href', srcUrl);
4506 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
4507 img.setAttribute('x', '2');
4508 img.setAttribute('y', '3');
4509 img.setAttribute('width', '20');
4510 img.setAttribute('height', '18');
4511 img.setAttribute('clip-path', `url(#${id})`);
4512 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
4513
4514 // Prepend so the folder outline strokes render on top.
4515 svg.prepend(img);
4516 svg.prepend(defs);
4517 iconEl.dataset.thumbReady = '1';
4518}
4519
4520function wireEvents ()
4521{
4522 // Auth form
4523 document.getElementById('auth-form').addEventListener('submit', async (e) =>
4524 {
4525 e.preventDefault();
4526 const username = document.getElementById('auth-username').value.trim();
4527 const password = document.getElementById('auth-password').value;
4528 const isSetup = e.target.dataset.mode === 'setup';
4529 const errEl = document.getElementById('auth-error');
4530 const btn = document.getElementById('auth-submit');
4531 btn.disabled = true;
4532 btn.textContent = 'Please wait…';
4533 const err = await doLogin(username, password, isSetup);
4534 if (err)
4535 {
4536 errEl.textContent = err;
4537 errEl.classList.remove('hidden');
4538 btn.disabled = false;
4539 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
4540 }
4541 });
4542
4543 // Logout
4544 document.getElementById('btn-logout').addEventListener('click', logout);
4545
4546 // Hard refresh while keeping auth/session state.
4547 document.getElementById('btn-refresh').addEventListener('click', () =>
4548 {
4549 saveSessionState();
4550 location.reload();
4551 });
4552
4553 // Upload button
4554 document.getElementById('btn-upload').addEventListener('click', () =>
4555 {
4556 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4557 if (!canWrite()) { toast('No write access.', 'err'); return; }
4558 document.getElementById('file-input').click();
4559 });
4560
4561 document.getElementById('file-input').addEventListener('change', async (e) =>
4562 {
4563 if (e.target.files.length) await uploadFiles(e.target.files);
4564 e.target.value = '';
4565 });
4566
4567 document.getElementById('btn-upload-folder').addEventListener('click', () =>
4568 {
4569 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4570 if (!canWrite()) { toast('No write access.', 'err'); return; }
4571 document.getElementById('folder-input').click();
4572 });
4573
4574 document.getElementById('folder-input').addEventListener('change', async (e) =>
4575 {
4576 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
4577 e.target.value = '';
4578 });
4579
4580 document.getElementById('btn-new-folder').addEventListener('click', async () =>
4581 {
4582 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4583 if (!canWrite()) { toast('No write access.', 'err'); return; }
4584
4585 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
4586 if (name == null) return;
4587 const folderName = name.trim();
4588 if (!folderName)
4589 {
4590 toast('Folder name is required.', 'err');
4591 return;
4592 }
4593
4594 try
4595 {
4596 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
4597 toast('Folder created.', 'ok');
4598 await navigateTo(STATE.currentDir, STATE.currentRoot);
4599 } catch (err)
4600 {
4601 toast(err.message, 'err');
4602 }
4603 });
4604
4605 document.getElementById('sidebar-close').addEventListener('click', (e) =>
4606 {
4607 e.stopPropagation();
4608 hideSidebarPanel();
4609 });
4610
4611 const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY);
4612 const syncSidebarForViewport = () =>
4613 {
4614 if (isMobileViewport())
4615 {
4616 hideSidebarPanel();
4617 return;
4618 }
4619
4620 if (!STATE.selectedItem) openFolderSidebar();
4621 };
4622
4623 if (typeof mobileQuery.addEventListener === 'function')
4624 {
4625 mobileQuery.addEventListener('change', syncSidebarForViewport);
4626 } else if (typeof mobileQuery.addListener === 'function')
4627 {
4628 mobileQuery.addListener(syncSidebarForViewport);
4629 }
4630
4631 // Click outside grid clears selection and returns to folder sidebar info.
4632 document.getElementById('main-content').addEventListener('click', (e) =>
4633 {
4634 if (!e.target.closest('.file-item')) closeSidebar();
4635 });
4636
4637 // Admin panel
4638 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
4639 document.getElementById('admin-modal-close').addEventListener('click', () =>
4640 document.getElementById('admin-modal').classList.add('hidden'));
4641
4642 // Add path
4643 document.getElementById('admin-add-path').addEventListener('click', () =>
4644 {
4645 const val = document.getElementById('admin-new-path').value.trim();
4646 if (!val) return;
4647 const row = document.createElement('div');
4648 row.className = 'path-row';
4649 row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`;
4650 row.querySelector('button').addEventListener('click', () => row.remove());
4651 document.getElementById('admin-paths').appendChild(row);
4652 document.getElementById('admin-new-path').value = '';
4653 });
4654
4655 // Save paths
4656 document.getElementById('admin-save-paths').addEventListener('click', async () =>
4657 {
4658 const rows = document.querySelectorAll('#admin-paths .path-row span');
4659 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
4660 try
4661 {
4662 await api('PUT', '/admin/config', { paths });
4663 toast('Paths saved.', 'ok');
4664 await loadRoots();
4665 } catch (err) { toast(err.message, 'err'); }
4666 });
4667
4668 const sizeInput = document.getElementById('admin-user-size-limit');
4669 if (sizeInput)
4670 {
4671 sizeInput.addEventListener('input', () =>
4672 {
4673 updateAdminSizeFeedback(sizeInput.value);
4674 });
4675 }
4676
4677 document.getElementById('admin-save-userpath').addEventListener('click', async () =>
4678 {
4679 const rows = document.querySelectorAll('#admin-paths .path-row span');
4680 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
4681 const userPath = document.getElementById('admin-user-path').value.trim();
4682 const rawLimit = document.getElementById('admin-user-size-limit').value.trim();
4683 const parsed = updateAdminSizeFeedback(rawLimit);
4684 if (!parsed.valid)
4685 {
4686 toast('Please enter a valid user size limit.', 'err');
4687 return;
4688 }
4689
4690 try
4691 {
4692 await api('PUT', '/admin/config', {
4693 paths,
4694 userPath: userPath || null,
4695 userFolderSizeLimit: rawLimit ? parsed.bytes : null,
4696 });
4697 toast('User folder settings saved.', 'ok');
4698 await loadRoots();
4699 await refreshAdminConfig();
4700 }
4701 catch (err)
4702 {
4703 toast(err.message, 'err');
4704 }
4705 });
4706
4707 // Shutdown / restart server
4708 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4709 {
4710 const status = _adminUpdateStatus;
4711
4712 if (!status || !status.underSystemd)
4713 {
4714 // Not running under systemd — plain shutdown (manual restart required).
4715 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
4716 }
4717 else if (status.commitsAhead.length === 0)
4718 {
4719 // Under systemd, no updates — restart only.
4720 if (!await showConfirm('Restart server', 'No update available. Would you like to restart?', { okLabel: 'Restart' })) return;
4721 }
4722 else
4723 {
4724 // Under systemd, updates available.
4725 const commitList = status.commitsAhead.map(c => escHtml(c)).join('<br/>');
4726 const msg = `Updates available:<br/><br/>${commitList}<br/><br/>Update now?`;
4727 if (!await showConfirm('Restart &amp; Update', msg, { html: true, okLabel: 'Update now' })) return;
4728 }
4729
4730 try
4731 {
4732 await api('POST', '/admin/shutdown');
4733 const toastMsg = (!status || !status.underSystemd)
4734 ? 'Server is shutting down\u2026'
4735 : status.commitsAhead.length > 0
4736 ? 'Server is updating and restarting\u2026'
4737 : 'Server is restarting\u2026';
4738 toast(toastMsg, 'ok');
4739 document.getElementById('admin-modal').classList.add('hidden');
4740 } catch
4741 {
4742 // Fetch may throw because the connection closes before a response arrives.
4743 const toastMsg = (!status || !status.underSystemd)
4744 ? 'Server is shutting down\u2026'
4745 : status.commitsAhead.length > 0
4746 ? 'Server is updating and restarting\u2026'
4747 : 'Server is restarting\u2026';
4748 toast(toastMsg, 'ok');
4749 document.getElementById('admin-modal').classList.add('hidden');
4750 }
4751 setTimeout(() => location.reload(), 3000);
4752 });
4753
4754 // New user
4755 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
4756 {
4757 const cfg = await api('GET', '/admin/config');
4758 const paths = cfg ? (cfg.effectivePaths || []) : [];
4759 openUserModal(null, paths);
4760 });
4761
4762 // User modal close
4763 document.getElementById('user-modal-close').addEventListener('click', () =>
4764 document.getElementById('user-modal').classList.add('hidden'));
4765
4766 // Rename modal close
4767 document.getElementById('rename-modal-close').addEventListener('click', () =>
4768 document.getElementById('rename-modal').classList.add('hidden'));
4769
4770 // Close modals on backdrop click
4771 document.querySelectorAll('.modal-overlay').forEach(overlay =>
4772 {
4773 overlay.addEventListener('click', e =>
4774 {
4775 if (e.target === overlay) overlay.classList.add('hidden');
4776 });
4777 });
4778}
4779
4780// ───────────────────────────────────────────────────────────────────────────
4781// BOOT
4782// ───────────────────────────────────────────────────────────────────────────
4783
4784(async function boot ()
4785{
4786 wireEvents();
4787 initDragDrop();
4788 window.addEventListener('beforeunload', () =>
4789 {
4790 saveSessionState();
4791 releaseActivePreviewVideoStreamSession({ keepalive: true });
4792 });
4793 window.addEventListener('pagehide', () =>
4794 {
4795 releaseActivePreviewVideoStreamSession({ keepalive: true });
4796 });
4797 await initAuth();
4798})();