BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

app.js 146.0 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.userFreeBytes != null
1843 ? formatBytes(space.userFreeBytes)
1844 : (space.freeBytes == null ? 'unknown' : formatBytes(space.freeBytes));
1845 const freeLabel = space.userFreeBytes != null ? 'Free space remaining' : 'Remaining';
1846 dl.innerHTML += `
1847 <dt>Used</dt><dd>${used}</dd>
1848 <dt>${freeLabel}</dt><dd>${free}</dd>
1849 `;
1850 }
1851
1852 if (item._root.isUserFolder)
1853 {
1854 dl.innerHTML += `
1855 <dt>Access</dt><dd>Private (your folder)</dd>
1856 `;
1857 } else
1858 {
1859 const accessUsers = await fetchRootAccessList(item.path);
1860 if (accessUsers)
1861 {
1862 dl.innerHTML += `
1863 <dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>
1864 `;
1865 }
1866 }
1867 }
1868
1869 const btnOpen = document.createElement('button');
1870 btnOpen.textContent = 'Open folder';
1871 btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot));
1872 actions.appendChild(btnOpen);
1873
1874 // Download as zip button (folder)
1875 const btnZip = document.createElement('button');
1876 btnZip.textContent = 'Download as zip';
1877 btnZip.addEventListener('click', () =>
1878 {
1879 btnZip.disabled = true;
1880 btnZip.textContent = 'Working...';
1881 const url = `/api/files/download-zip?dir=${encodeURIComponent(item.path)}`;
1882 const headers = {
1883 Authorization: 'Bearer ' + STATE.token,
1884 'X-Fp': getFingerprint(),
1885 };
1886 fetch(url, { headers })
1887 .then(res =>
1888 {
1889 if (!res.ok) throw new Error('Download mislukt');
1890 return res.blob();
1891 })
1892 .then(blob =>
1893 {
1894 const blobUrl = URL.createObjectURL(blob);
1895 const a = document.createElement('a');
1896 a.href = blobUrl;
1897 a.download = item.name + '.zip';
1898 a.click();
1899 setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
1900 })
1901 .catch((err) => toast(err.message || 'Download mislukt', 'err'))
1902 .finally(() =>
1903 {
1904 btnZip.disabled = false;
1905 btnZip.textContent = 'Download as zip';
1906 });
1907 });
1908 actions.appendChild(btnZip);
1909
1910 // Share button (folder)
1911 const btnShareFolder = document.createElement('button');
1912 btnShareFolder.textContent = 'Share';
1913 btnShareFolder.addEventListener('click', () => openShareModal(item));
1914 actions.appendChild(btnShareFolder);
1915
1916 // Load folder icon thumbnail into the sidebar icon element.
1917 void loadOneFolderIcon(document.getElementById('sidebar-icon'));
1918 }
1919
1920 // Rename button (write access required)
1921 if (canWrite(item))
1922 {
1923 if (item.isDir)
1924 {
1925 const btnSetIcon = document.createElement('button');
1926 btnSetIcon.textContent = 'Set icon';
1927 btnSetIcon.addEventListener('click', () => openFolderIconPicker(item));
1928 actions.appendChild(btnSetIcon);
1929 }
1930
1931 if (!item._root)
1932 {
1933 const btnMove = document.createElement('button');
1934 btnMove.textContent = 'Move to';
1935 btnMove.addEventListener('click', () => openMovePicker(item));
1936 actions.appendChild(btnMove);
1937
1938 if (!item.isDir)
1939 {
1940 const btnCopy = document.createElement('button');
1941 btnCopy.textContent = 'Copy to';
1942 btnCopy.addEventListener('click', () => openCopyPicker(item));
1943 actions.appendChild(btnCopy);
1944 }
1945 }
1946
1947 const btnRen = document.createElement('button');
1948 btnRen.textContent = 'Rename';
1949 btnRen.addEventListener('click', () => openRenameModal(item));
1950 actions.appendChild(btnRen);
1951
1952 if (!item._root)
1953 {
1954 const btnDel = document.createElement('button');
1955 btnDel.textContent = 'Delete';
1956 btnDel.className = 'danger';
1957 btnDel.addEventListener('click', () => deleteItem(item));
1958 actions.appendChild(btnDel);
1959 }
1960 }
1961}
1962
1963function openFolderSidebar ()
1964{
1965 const sidebar = document.getElementById('sidebar');
1966 sidebar.classList.remove('hidden');
1967 document.getElementById('app').classList.add('sidebar-open');
1968
1969 document.getElementById('sidebar-icon').innerHTML = iconFolder(64);
1970
1971 const nameEl = document.getElementById('sidebar-name');
1972 const dl = document.getElementById('sidebar-meta');
1973 const actions = document.getElementById('sidebar-actions');
1974 actions.innerHTML = '';
1975 renderSidebarDuplicates(null, null);
1976
1977 if (!STATE.currentDir || !STATE.currentRoot)
1978 {
1979 nameEl.textContent = 'Storage Roots';
1980 dl.innerHTML = `
1981 <dt>Type</dt><dd>Root overview</dd>
1982 <dt>Roots</dt><dd>${STATE.roots.length}</dd>
1983 `;
1984 return;
1985 }
1986
1987 const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean);
1988 const fallback = STATE.currentRoot.label || 'Folder';
1989 nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback;
1990
1991 const dirs = STATE.items.filter(i => i.isDir).length;
1992 const files = STATE.items.length - dirs;
1993 const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label);
1994 const baseDetails = `
1995 <dt>Path</dt><dd>${displayPath}</dd>
1996 <dt>Folders</dt><dd>${dirs}</dd>
1997 <dt>Files</dt><dd>${files}</dd>
1998 `;
1999 dl.innerHTML = baseDetails;
2000
2001 if (samePath(STATE.currentDir, STATE.currentRoot.path))
2002 {
2003 if (STATE.currentRoot.isUserFolder)
2004 {
2005 dl.innerHTML += '<dt>Access</dt><dd>Private (your folder)</dd>';
2006 return;
2007 }
2008
2009 dl.innerHTML += '<dt>Access</dt><dd>Loading…</dd>';
2010 const currentDirAtStart = STATE.currentDir;
2011 const currentRootPathAtStart = STATE.currentRoot.path;
2012 void fetchRootAccessList(currentRootPathAtStart).then((accessUsers) =>
2013 {
2014 if (!accessUsers) return;
2015 if (!STATE.currentRoot) return;
2016 if (!samePath(STATE.currentDir, currentDirAtStart)) return;
2017 if (!samePath(STATE.currentRoot.path, currentRootPathAtStart)) return;
2018 dl.innerHTML = `${baseDetails}<dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>`;
2019 });
2020 }
2021}
2022
2023function closeSidebar ()
2024{
2025 if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
2026 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
2027 STATE.selectedItem = null;
2028
2029 if (isMobileViewport())
2030 {
2031 hideSidebarPanel();
2032 return;
2033 }
2034
2035 openFolderSidebar();
2036}
2037
2038function isMobileViewport ()
2039{
2040 return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches;
2041}
2042
2043function hideSidebarPanel ()
2044{
2045 const sidebar = document.getElementById('sidebar');
2046 const app = document.getElementById('app');
2047 sidebar.classList.add('hidden');
2048 app.classList.remove('sidebar-open');
2049}
2050
2051function basenameOfPath (p)
2052{
2053 const parts = String(p || '').split(/[\\/]/).filter(Boolean);
2054 return parts.length ? parts[parts.length - 1] : String(p || '');
2055}
2056
2057async function fetchRootAccessList (rootPath)
2058{
2059 if (!rootPath) return null;
2060 const data = await api('GET', `/files/root-access?rootPath=${encodeURIComponent(rootPath)}`).catch(() => null);
2061 if (!data || !Array.isArray(data.users)) return null;
2062 return data.users;
2063}
2064
2065function formatRootAccessList (users)
2066{
2067 if (!Array.isArray(users) || users.length === 0) return 'No users';
2068
2069 const sorted = [...users].sort((a, b) =>
2070 {
2071 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
2072 const byMode = modeRank(a.mode) - modeRank(b.mode);
2073 if (byMode !== 0) return byMode;
2074 return String(a.username).localeCompare(String(b.username));
2075 });
2076
2077 const items = sorted
2078 .map((u) => `<li>${escapeHtml(String(u.username || ''))} ${escapeHtml(String(u.mode || 'R'))}</li>`)
2079 .join('');
2080 return `<ul class="root-access-list">${items}</ul>`;
2081}
2082
2083function rootPermissionLabel (root)
2084{
2085 return (root && (root.originalName || root.label)) || '';
2086}
2087
2088function resolveRootForPath (targetPath)
2089{
2090 if (!targetPath) return null;
2091 return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null;
2092}
2093
2094function writableRoots ()
2095{
2096 if (STATE.isAdmin) return STATE.roots.slice();
2097 return STATE.roots.filter((r) =>
2098 {
2099 if (r.isUserFolder) return true;
2100 const perm = STATE.permissions[rootPermissionLabel(r)];
2101 return !!(perm && perm.write);
2102 });
2103}
2104
2105async function moveWithConflictResolution (item, targetDir)
2106{
2107 try
2108 {
2109 return await api('POST', '/files/move', { from: item.path, toDir: targetDir });
2110 }
2111 catch (err)
2112 {
2113 if (!/already exists/i.test(err.message || '')) throw err;
2114
2115 const existingNames = await listDirNameSet(targetDir);
2116 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2117 const suggestedName = nextAvailableName(desiredName, existingNames);
2118 const decision = await showFileConflictChoice(desiredName, suggestedName, 'move');
2119 if (decision === 'cancel') return null;
2120
2121 if (decision === 'overwrite')
2122 {
2123 return api('POST', '/files/move', {
2124 from: item.path,
2125 toDir: targetDir,
2126 conflict: 'overwrite',
2127 });
2128 }
2129
2130 return api('POST', '/files/move', {
2131 from: item.path,
2132 toDir: targetDir,
2133 conflict: 'rename',
2134 targetName: suggestedName,
2135 });
2136 }
2137}
2138
2139async function copyWithConflictResolution (item, targetDir)
2140{
2141 try
2142 {
2143 return await api('POST', '/files/copy', { from: item.path, toDir: targetDir });
2144 }
2145 catch (err)
2146 {
2147 if (!/already exists/i.test(err.message || '')) throw err;
2148
2149 const existingNames = await listDirNameSet(targetDir);
2150 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2151 const suggestedName = nextAvailableName(desiredName, existingNames);
2152 const decision = await showFileConflictChoice(desiredName, suggestedName, 'copy');
2153 if (decision === 'cancel') return null;
2154
2155 if (decision === 'overwrite')
2156 {
2157 return api('POST', '/files/copy', {
2158 from: item.path,
2159 toDir: targetDir,
2160 conflict: 'overwrite',
2161 });
2162 }
2163
2164 return api('POST', '/files/copy', {
2165 from: item.path,
2166 toDir: targetDir,
2167 conflict: 'rename',
2168 targetName: suggestedName,
2169 });
2170 }
2171}
2172
2173function ensureMoveModal ()
2174{
2175 let overlay = document.getElementById('move-modal');
2176 if (overlay) return overlay;
2177
2178 overlay = document.createElement('div');
2179 overlay.id = 'move-modal';
2180 overlay.className = 'modal-overlay hidden';
2181 overlay.innerHTML = `
2182 <div class="modal move-modal">
2183 <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button>
2184 <h2>Move To</h2>
2185 <p id="move-modal-caption" class="muted"></p>
2186 <div id="move-tree" class="move-tree"></div>
2187 <p id="move-selected" class="muted"></p>
2188 <div class="dialog-actions">
2189 <button id="move-modal-cancel">Cancel</button>
2190 <button id="move-modal-confirm" class="primary">Move</button>
2191 </div>
2192 </div>
2193 `;
2194 document.body.appendChild(overlay);
2195
2196 const closeBtn = overlay.querySelector('#move-modal-close');
2197 const cancelBtn = overlay.querySelector('#move-modal-cancel');
2198 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2199
2200 function hide ()
2201 {
2202 overlay.classList.add('hidden');
2203 STATE.movePicker = null;
2204 }
2205
2206 closeBtn.addEventListener('click', hide);
2207 cancelBtn.addEventListener('click', hide);
2208 overlay.addEventListener('click', (e) =>
2209 {
2210 if (e.target === overlay) hide();
2211 });
2212
2213 confirmBtn.addEventListener('click', async () =>
2214 {
2215 const st = STATE.movePicker;
2216 if (!st || !st.item || !st.selectedPath)
2217 {
2218 toast('Select a destination folder first.', 'err');
2219 return;
2220 }
2221
2222 try
2223 {
2224 if (st.mode === 'copy')
2225 {
2226 const copied = await copyWithConflictResolution(st.item, st.selectedPath);
2227 if (!copied) return;
2228 }
2229 else
2230 {
2231 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
2232 if (!moved) return;
2233 }
2234 }
2235 catch (err)
2236 {
2237 const action = st.mode === 'copy' ? 'Copy' : 'Move';
2238 toast(`${action} failed: ${err.message}`, 'err');
2239 return;
2240 }
2241
2242 hide();
2243 if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2244 navigateTo(STATE.currentDir, STATE.currentRoot);
2245 });
2246
2247 return overlay;
2248}
2249
2250function setMoveSelection (path, buttonEl)
2251{
2252 if (!STATE.movePicker) return;
2253 STATE.movePicker.selectedPath = path;
2254
2255 document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected'));
2256 if (buttonEl) buttonEl.classList.add('selected');
2257
2258 const selectedEl = document.getElementById('move-selected');
2259 selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none';
2260}
2261
2262async function loadMoveChildren (containerEl, dirPath)
2263{
2264 if (containerEl.dataset.loaded === '1') return;
2265 containerEl.dataset.loaded = '1';
2266
2267 const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null);
2268 const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : [];
2269
2270 if (!folders.length)
2271 {
2272 const empty = document.createElement('div');
2273 empty.className = 'move-empty';
2274 empty.textContent = 'No subfolders';
2275 containerEl.appendChild(empty);
2276 return;
2277 }
2278
2279 for (const child of folders)
2280 {
2281 containerEl.appendChild(createMoveNode(child.path, child.name));
2282 }
2283}
2284
2285function createMoveNode (folderPath, label)
2286{
2287 const node = document.createElement('div');
2288 node.className = 'move-node';
2289
2290 const row = document.createElement('div');
2291 row.className = 'move-node-row';
2292
2293 const toggle = document.createElement('button');
2294 toggle.type = 'button';
2295 toggle.className = 'move-toggle';
2296 toggle.textContent = '▸';
2297
2298 const selectBtn = document.createElement('button');
2299 selectBtn.type = 'button';
2300 selectBtn.className = 'move-node-label';
2301 selectBtn.textContent = label;
2302 selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn));
2303
2304 const children = document.createElement('div');
2305 children.className = 'move-children hidden';
2306
2307 toggle.addEventListener('click', async () =>
2308 {
2309 if (children.classList.contains('hidden'))
2310 {
2311 await loadMoveChildren(children, folderPath);
2312 children.classList.remove('hidden');
2313 toggle.textContent = '▾';
2314 } else
2315 {
2316 children.classList.add('hidden');
2317 toggle.textContent = '▸';
2318 }
2319 });
2320
2321 row.appendChild(toggle);
2322 row.appendChild(selectBtn);
2323 node.appendChild(row);
2324 node.appendChild(children);
2325 return node;
2326}
2327
2328function openDestinationPicker (item, mode)
2329{
2330 if (!canWrite())
2331 {
2332 toast('No write access.', 'err');
2333 return;
2334 }
2335
2336 const roots = writableRoots();
2337 if (!roots.length)
2338 {
2339 toast('No writable destination roots available.', 'err');
2340 return;
2341 }
2342
2343 const overlay = ensureMoveModal();
2344 const tree = overlay.querySelector('#move-tree');
2345 const caption = overlay.querySelector('#move-modal-caption');
2346 const titleEl = overlay.querySelector('h2');
2347 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2348
2349 const op = mode === 'copy' ? 'copy' : 'move';
2350 STATE.movePicker = { item, selectedPath: null, mode: op };
2351 titleEl.textContent = op === 'copy' ? 'Copy To' : 'Move To';
2352 confirmBtn.textContent = op === 'copy' ? 'Copy' : 'Move';
2353 caption.textContent = `Select destination folder for: ${item.name}`;
2354 tree.innerHTML = '';
2355
2356 for (const root of roots)
2357 {
2358 tree.appendChild(createMoveNode(root.path, root.label));
2359 }
2360
2361 setMoveSelection(null, null);
2362 overlay.classList.remove('hidden');
2363}
2364
2365function openMovePicker (item)
2366{
2367 openDestinationPicker(item, 'move');
2368}
2369
2370function openCopyPicker (item)
2371{
2372 openDestinationPicker(item, 'copy');
2373}
2374
2375// ───────────────────────────────────────────────────────────────────────────
2376// FOLDER ICON PICKER
2377// ───────────────────────────────────────────────────────────────────────────
2378
2379async function openFolderIconPicker (item)
2380{
2381 if (!canWrite(item))
2382 {
2383 toast('No write access.', 'err');
2384 return;
2385 }
2386
2387 // Fetch the list of available images (only those with cached thumbnails).
2388 const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(item.path)}`).catch(() => null);
2389 const images = data ? data.images : [];
2390
2391 let existingIconOverlay = document.getElementById('folder-icon-picker');
2392 if (existingIconOverlay) existingIconOverlay.remove();
2393
2394 const overlay = document.createElement('div');
2395 overlay.id = 'folder-icon-picker';
2396 overlay.className = 'modal-overlay';
2397
2398 const modal = document.createElement('div');
2399 modal.className = 'modal folder-icon-modal';
2400
2401 const closeBtn = document.createElement('button');
2402 closeBtn.className = 'modal-close';
2403 closeBtn.setAttribute('aria-label', 'Close');
2404 closeBtn.textContent = '✕';
2405
2406 const title = document.createElement('h2');
2407 title.textContent = 'Set folder icon';
2408
2409 const subtitle = document.createElement('p');
2410 subtitle.className = 'muted';
2411
2412 const grid = document.createElement('div');
2413 grid.className = 'folder-icon-grid';
2414
2415 if (!images.length)
2416 {
2417 subtitle.textContent = 'No images with cached thumbnails were found inside this folder.';
2418 } else
2419 {
2420 subtitle.textContent = 'Select an image to use as the folder icon.';
2421
2422 for (const { filePath } of images)
2423 {
2424 const cell = document.createElement('div');
2425 cell.className = 'folder-icon-cell';
2426 cell.dataset.path = filePath;
2427
2428 const imgEl = document.createElement('img');
2429 imgEl.alt = filePath.split('/').pop();
2430 imgEl.className = 'folder-icon-thumb';
2431 // Lazy-load via IntersectionObserver on the cell.
2432 imgEl.dataset.src = filePath;
2433
2434 const label = document.createElement('div');
2435 label.className = 'folder-icon-label';
2436 label.textContent = filePath.split('/').pop();
2437
2438 cell.appendChild(imgEl);
2439 cell.appendChild(label);
2440
2441 cell.addEventListener('click', () =>
2442 {
2443 grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected'));
2444 cell.classList.add('selected');
2445 confirmBtn.disabled = false;
2446 });
2447
2448 grid.appendChild(cell);
2449 }
2450 }
2451
2452 const dialogActions = document.createElement('div');
2453 dialogActions.className = 'dialog-actions';
2454
2455 const clearBtn = document.createElement('button');
2456 clearBtn.textContent = 'Clear icon';
2457 clearBtn.addEventListener('click', async () =>
2458 {
2459 try
2460 {
2461 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null });
2462 } catch (err)
2463 {
2464 toast('Failed to clear icon: ' + err.message, 'err');
2465 return;
2466 }
2467 hide();
2468 refreshAfterIconChange(item);
2469 });
2470
2471 const cancelBtn = document.createElement('button');
2472 cancelBtn.textContent = 'Cancel';
2473 cancelBtn.addEventListener('click', () => hide());
2474
2475 const confirmBtn = document.createElement('button');
2476 confirmBtn.className = 'primary';
2477 confirmBtn.textContent = 'Set icon';
2478 confirmBtn.disabled = true;
2479 confirmBtn.addEventListener('click', async () =>
2480 {
2481 const selected = grid.querySelector('.folder-icon-cell.selected');
2482 if (!selected) return;
2483 const imagePath = selected.dataset.path;
2484 try
2485 {
2486 await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath });
2487 } catch (err)
2488 {
2489 toast('Failed to set icon: ' + err.message, 'err');
2490 return;
2491 }
2492 hide();
2493 refreshAfterIconChange(item);
2494 });
2495
2496 dialogActions.appendChild(clearBtn);
2497 dialogActions.appendChild(cancelBtn);
2498 dialogActions.appendChild(confirmBtn);
2499
2500 modal.appendChild(closeBtn);
2501 modal.appendChild(title);
2502 modal.appendChild(subtitle);
2503 modal.appendChild(grid);
2504 modal.appendChild(dialogActions);
2505 overlay.appendChild(modal);
2506 document.body.appendChild(overlay);
2507
2508 function hide ()
2509 {
2510 overlay.remove();
2511 // Revoke any blob URLs we created for the picker thumbnails.
2512 grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach(img =>
2513 {
2514 URL.revokeObjectURL(img.src);
2515 });
2516 }
2517
2518 closeBtn.addEventListener('click', hide);
2519 overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); });
2520
2521 // Eagerly load thumbnails for all cells (picker is small, fetch all).
2522 for (const cell of grid.querySelectorAll('.folder-icon-cell'))
2523 {
2524 const imgEl = cell.querySelector('.folder-icon-thumb');
2525 const filePath = imgEl.dataset.src;
2526 void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, {
2527 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
2528 }).then(async (r) =>
2529 {
2530 if (!r.ok || !overlay.isConnected) return;
2531 const blob = await r.blob();
2532 const url = URL.createObjectURL(blob);
2533 imgEl.src = url;
2534 }).catch(() => {});
2535 }
2536}
2537
2538function refreshAfterIconChange (item)
2539{
2540 // Reset and reload icon in grid tiles.
2541 const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]'))
2542 .find(el => el.dataset.folderPath === item.path);
2543 if (gridTile)
2544 {
2545 const svg = gridTile.querySelector('svg');
2546 if (svg)
2547 {
2548 // Rebuild to plain folder SVG, then reload.
2549 gridTile.innerHTML = iconFolder();
2550 delete gridTile.dataset.thumbReady;
2551 gridTile.dataset.folderPath = item.path;
2552 void loadOneFolderIcon(gridTile);
2553 }
2554 }
2555
2556 // Also reset the sidebar icon if it's showing the same folder.
2557 const sidebarIcon = document.getElementById('sidebar-icon');
2558 if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path)
2559 {
2560 sidebarIcon.innerHTML = iconFolder(64);
2561 delete sidebarIcon.dataset.thumbReady;
2562 void loadOneFolderIcon(sidebarIcon);
2563 }
2564}
2565
2566// ───────────────────────────────────────────────────────────────────────────
2567// DOWNLOAD / VIEW
2568// ───────────────────────────────────────────────────────────────────────────
2569
2570function isInlinePreviewableBlob (blob, name)
2571{
2572 const mime = String(blob.type || '').toLowerCase();
2573 if (/^(image|video|audio)\//.test(mime)) return true;
2574 if (/^text\//.test(mime)) return true;
2575 if (mime === 'application/pdf') return true;
2576 if (mime === 'application/json') return true;
2577 if (mime === 'application/xml') return true;
2578 if (mime === 'application/javascript') return true;
2579
2580 // Fallback by extension when MIME is missing or generic.
2581 const ext = extOf(name || '');
2582 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true;
2583 if (CODE_EXTS.has(ext)) return true;
2584 return false;
2585}
2586
2587function isTextLikeBlob (blob, name)
2588{
2589 const mime = String(blob.type || '').toLowerCase();
2590 if (/^text\//.test(mime)) return true;
2591 if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true;
2592 const ext = extOf(name || '');
2593 return CODE_EXTS.has(ext);
2594}
2595
2596function detectCodeLanguage (name, mime)
2597{
2598 const ext = extOf(name || '');
2599 const m = String(mime || '').toLowerCase();
2600 if (m.includes('json') || ext === 'json') return 'json';
2601 if (m.includes('xml') || ext === 'xml') return 'xml';
2602 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
2603 if (m.includes('css') || ext === 'css') return 'css';
2604 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
2605 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
2606 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
2607 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
2608 return CODE_EXTS.has(ext) ? 'js' : 'plain';
2609}
2610
2611function prettyPrintMarkup (raw)
2612{
2613 const src = String(raw || '')
2614 .replace(/>\s+</g, '><')
2615 .replace(/\r\n/g, '\n');
2616
2617 const lines = src.replace(/></g, '>\n<').split('\n');
2618 let indent = 0;
2619 const out = [];
2620
2621 for (const ln of lines)
2622 {
2623 const line = ln.trim();
2624 if (!line) continue;
2625 const isClose = /^<\//.test(line);
2626 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
2627 const isOpen = /^<[^!?/][^>]*>$/.test(line);
2628
2629 if (isClose) indent = Math.max(0, indent - 1);
2630 out.push(' '.repeat(indent) + line);
2631 if (isOpen && !isSelf) indent += 1;
2632 }
2633
2634 return out.join('\n');
2635}
2636
2637function prettyPrintBraces (raw)
2638{
2639 const lines = String(raw || '')
2640 .replace(/\r\n/g, '\n')
2641 .split('\n');
2642 let indent = 0;
2643 const out = [];
2644
2645 for (const ln of lines)
2646 {
2647 const line = ln.trim();
2648 if (!line)
2649 {
2650 out.push('');
2651 continue;
2652 }
2653 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
2654 out.push(' '.repeat(indent) + line);
2655 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
2656 }
2657 return out.join('\n');
2658}
2659
2660function prettyPrintCode (raw, lang)
2661{
2662 const text = String(raw || '').replace(/\r\n/g, '\n');
2663 if (lang === 'json')
2664 {
2665 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
2666 }
2667 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
2668 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
2669 return text;
2670}
2671
2672function escapeHtml (s)
2673{
2674 return String(s)
2675 .replace(/&/g, '&amp;')
2676 .replace(/</g, '&lt;')
2677 .replace(/>/g, '&gt;');
2678}
2679
2680function highlightCode (raw, lang)
2681{
2682 if (lang === 'plain') return escapeHtml(raw);
2683
2684 let html = escapeHtml(raw);
2685 const stash = [];
2686 const keep = (regex, cls) =>
2687 {
2688 html = html.replace(regex, (m) =>
2689 {
2690 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
2691 return `@@TOK${idx}@@`;
2692 });
2693 };
2694
2695 if (lang === 'json')
2696 {
2697 html = html
2698 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
2699 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
2700 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
2701 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
2702 return html;
2703 }
2704
2705 if (lang === 'xml' || lang === 'html')
2706 {
2707 html = html
2708 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
2709 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
2710 return html;
2711 }
2712
2713 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
2714 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
2715 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
2716
2717 html = html
2718 .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>')
2719 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
2720
2721 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
2722 return html;
2723}
2724
2725function clearPreviewObjectUrl ()
2726{
2727 if (typeof STATE.previewCleanup === 'function')
2728 {
2729 try { STATE.previewCleanup(); } catch { /* ignore */ }
2730 }
2731 STATE.previewCleanup = null;
2732 STATE.previewDownloadAction = null;
2733 if (!STATE.previewObjectUrl) return;
2734 if (String(STATE.previewObjectUrl).startsWith('blob:'))
2735 {
2736 URL.revokeObjectURL(STATE.previewObjectUrl);
2737 }
2738 STATE.previewObjectUrl = null;
2739}
2740
2741function ensureStylesheet (id, href)
2742{
2743 let link = document.getElementById(id);
2744 if (link) return Promise.resolve(link);
2745
2746 link = document.createElement('link');
2747 link.id = id;
2748 link.rel = 'stylesheet';
2749 link.href = href;
2750
2751 return new Promise((resolve, reject) =>
2752 {
2753 link.addEventListener('load', () => resolve(link), { once: true });
2754 link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true });
2755 document.head.appendChild(link);
2756 });
2757}
2758
2759function ensureScript (id, src)
2760{
2761 let script = document.getElementById(id);
2762 if (script && window.videojs) return Promise.resolve(window.videojs);
2763
2764 if (!script)
2765 {
2766 script = document.createElement('script');
2767 script.id = id;
2768 script.src = src;
2769 }
2770
2771 return new Promise((resolve, reject) =>
2772 {
2773 script.addEventListener('load', () => resolve(window.videojs), { once: true });
2774 script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true });
2775 if (!script.isConnected) document.head.appendChild(script);
2776 });
2777}
2778
2779async function ensureVideoJsLoaded ()
2780{
2781 if (window.videojs)
2782 {
2783 configureVideoJsBuffering(window.videojs);
2784 return window.videojs;
2785 }
2786 if (!videoJsLoaderPromise)
2787 {
2788 videoJsLoaderPromise = Promise.all([
2789 ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'),
2790 ensureScript('videojs-script', '/vendor/video.js/video.min.js'),
2791 ]).then(() =>
2792 {
2793 configureVideoJsBuffering(window.videojs);
2794 return window.videojs;
2795 });
2796 }
2797 return videoJsLoaderPromise;
2798}
2799
2800function configureVideoJsBuffering (videojs)
2801{
2802 if (! VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED)
2803return;
2804
2805 if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return;
2806 videojs.__filemanagerBufferingConfigured = true;
2807
2808 try
2809 {
2810 videojs.Vhs.GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;
2811 videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;
2812 } catch
2813 {
2814 // Ignore builds that do not expose VHS buffer configuration.
2815 }
2816}
2817
2818async function createVideoStreamSessionForItem (item)
2819{
2820 return api('POST', '/files/video-stream', { filePath: item.path });
2821}
2822
2823async function releaseVideoStreamSession (sessionId, opts = {})
2824{
2825 const id = String(sessionId || '').trim();
2826 if (!id) return;
2827
2828 await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, {
2829 keepalive: !!opts.keepalive,
2830 noAutoLogout: true,
2831 }).catch(() => null);
2832}
2833
2834function releaseActivePreviewVideoStreamSession (opts = {})
2835{
2836 const sessionId = String(STATE.previewVideoStreamSessionId || '').trim();
2837 if (!sessionId) return;
2838 STATE.previewVideoStreamSessionId = null;
2839 void releaseVideoStreamSession(sessionId, opts);
2840}
2841
2842async function preparePreviewDownload (item)
2843{
2844 const blob = await fetchFileBlob(item);
2845 if (!blob)
2846 {
2847 toast('Download failed.', 'err');
2848 return;
2849 }
2850
2851 const objectUrl = URL.createObjectURL(blob);
2852 triggerDownload(item.name, objectUrl);
2853 setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
2854}
2855
2856async function renderStreamedVideoPreview (item, targetEl)
2857{
2858 const videojs = await ensureVideoJsLoaded();
2859 const session = await createVideoStreamSessionForItem(item);
2860 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
2861 const prefs = loadUserVideoPrefs();
2862 applyUserVideoTextTrackPrefs();
2863
2864 if ((session.subtitleSummary && session.subtitleSummary.total > 0) && !(session.subtitleTracks || []).length)
2865 {
2866 toast('This video has subtitle tracks, but none are compatible with web playback.', 'err');
2867 }
2868
2869 STATE.previewDownloadAction = () => preparePreviewDownload(item);
2870
2871 const video = document.createElement('video');
2872 video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';
2873 video.controls = true;
2874 video.preload = 'auto';
2875 video.playsInline = true;
2876 targetEl.classList.add('preview-expand-content--video');
2877 targetEl.appendChild(video);
2878
2879 const player = videojs(video, {
2880 controls: true,
2881 fluid: false,
2882 fill: true,
2883 responsive: false,
2884 preload: 'auto',
2885 controlBar: {
2886 currentTimeDisplay: true,
2887 timeDivider: true,
2888 durationDisplay: true,
2889 remainingTimeDisplay: false,
2890 },
2891 sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],
2892 tracks: (session.subtitleTracks || []).map((track) => ({
2893 kind: 'subtitles',
2894 src: track.src,
2895 srclang: track.language || 'und',
2896 label: track.label,
2897 default: !!track.default,
2898 })),
2899 });
2900
2901 const trackPrefs = bindUserVideoTrackPrefs(player, prefs);
2902
2903 ensureVideoPlaybackUi(player, session.durationSeconds);
2904
2905 let sentPartway = false;
2906 let sentFully = false;
2907 const markWatch = async () =>
2908 {
2909 let ratio = 0;
2910 try
2911 {
2912 const duration = Number(player.duration());
2913 const current = Number(player.currentTime());
2914 if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current))
2915 {
2916 ratio = current / duration;
2917 }
2918 } catch
2919 {
2920 return;
2921 }
2922
2923 if (ratio >= 0.7)
2924 {
2925 if (sentFully) return;
2926 sentPartway = true;
2927 sentFully = true;
2928 void reportWatchProgress(item.path, ratio);
2929 return;
2930 }
2931
2932 if (ratio >= 0.05)
2933 {
2934 if (sentPartway) return;
2935 sentPartway = true;
2936 void reportWatchProgress(item.path, ratio);
2937 }
2938 };
2939
2940 player.ready(() =>
2941 {
2942 const volume = Number(prefs.volume);
2943 if (Number.isFinite(volume))
2944 {
2945 player.volume(Math.max(0, Math.min(1, volume)));
2946 }
2947 trackPrefs.applySavedTracks();
2948 });
2949
2950 player.on('loadedmetadata', trackPrefs.applySavedTracks);
2951 player.on('loadedplaylist', trackPrefs.applySavedTracks);
2952
2953 player.on('timeupdate', markWatch);
2954 player.on('ended', () =>
2955 {
2956 sentPartway = true;
2957 sentFully = true;
2958 void reportWatchProgress(item.path, 1);
2959 });
2960 player.on('volumechange', () =>
2961 {
2962 const v = Number(player.volume());
2963 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
2964 });
2965
2966 STATE.previewCleanup = () =>
2967 {
2968 releaseActivePreviewVideoStreamSession();
2969 try { markWatch(); } catch { /* ignore */ }
2970 try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
2971 try { trackPrefs.detach(); } catch { /* ignore */ }
2972 try { player.dispose(); } catch { /* ignore */ }
2973 };
2974}
2975
2976function fileAccentColor (name)
2977{
2978 const ext = extOf(name || '');
2979 if (IMAGE_EXTS.has(ext)) return '#3fcf8e';
2980 if (VIDEO_EXTS.has(ext)) return '#e05c6e';
2981 if (AUDIO_EXTS.has(ext)) return '#c084fc';
2982 if (DOC_EXTS.has(ext)) return '#f97316';
2983 if (CODE_EXTS.has(ext)) return '#38bdf8';
2984 if (ARCHIVE_EXTS.has(ext)) return '#facc15';
2985 return '#7880a0';
2986}
2987
2988function animateRect (el, fromRect, toRect, opts = {})
2989{
2990 const duration = opts.duration == null ? 260 : opts.duration;
2991 const easeOut = (t) => 1 - Math.pow(1 - t, 3);
2992
2993 el.style.left = `${fromRect.left}px`;
2994 el.style.top = `${fromRect.top}px`;
2995 el.style.width = `${fromRect.width}px`;
2996 el.style.height = `${fromRect.height}px`;
2997
2998 return new Promise((resolve) =>
2999 {
3000 const t0 = performance.now();
3001
3002 function frame (now)
3003 {
3004 const raw = Math.min((now - t0) / duration, 1);
3005 const t = easeOut(raw);
3006
3007 const left = fromRect.left + (toRect.left - fromRect.left) * t;
3008 const top = fromRect.top + (toRect.top - fromRect.top) * t;
3009 const width = fromRect.width + (toRect.width - fromRect.width) * t;
3010 const height = fromRect.height + (toRect.height - fromRect.height) * t;
3011
3012 el.style.left = `${left}px`;
3013 el.style.top = `${top}px`;
3014 el.style.width = `${width}px`;
3015 el.style.height = `${height}px`;
3016
3017 if (raw < 1)
3018 {
3019 requestAnimationFrame(frame);
3020 } else
3021 {
3022 resolve();
3023 }
3024 }
3025
3026 requestAnimationFrame(frame);
3027 });
3028}
3029
3030async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent)
3031{
3032 if (!tileEl || !sourceSvgEl) return false;
3033
3034 if (STATE.previewExpandState)
3035 {
3036 await closeExpandedTilePreview();
3037 }
3038
3039 const iconEl = tileEl.querySelector('.icon');
3040 const nameEl = tileEl.querySelector('.name');
3041 if (!iconEl) return false;
3042
3043 const startRect = tileEl.getBoundingClientRect();
3044 const targetW = Math.min(window.innerWidth * 0.94, 1100);
3045 const targetH = Math.min(window.innerHeight * 0.9, 860);
3046 const targetRect = {
3047 left: (window.innerWidth - targetW) / 2,
3048 top: (window.innerHeight - targetH) / 2,
3049 width: targetW,
3050 height: targetH,
3051 };
3052
3053 const backdrop = document.createElement('div');
3054 backdrop.className = 'preview-backdrop';
3055 document.body.appendChild(backdrop);
3056
3057 const parent = tileEl.parentNode;
3058 const nextSibling = tileEl.nextSibling;
3059 const iconHtml = iconEl.innerHTML;
3060 const originalIconSvg = iconEl.querySelector('svg');
3061
3062 tileEl.remove();
3063 document.body.appendChild(tileEl);
3064 tileEl.classList.add('file-item--preview');
3065 tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name));
3066 tileEl.style.position = 'fixed';
3067 tileEl.style.left = `${startRect.left}px`;
3068 tileEl.style.top = `${startRect.top}px`;
3069 tileEl.style.width = `${startRect.width}px`;
3070 tileEl.style.height = `${startRect.height}px`;
3071 tileEl.style.margin = '0';
3072 tileEl.style.zIndex = '10000';
3073
3074 if (nameEl) nameEl.style.display = 'none';
3075
3076 const titleEl = document.createElement('div');
3077 titleEl.className = 'preview-expand-title';
3078 titleEl.textContent = item.name;
3079
3080 const closeBtn = document.createElement('button');
3081 closeBtn.className = 'preview-expand-close';
3082 closeBtn.type = 'button';
3083 closeBtn.textContent = '×';
3084 closeBtn.setAttribute('aria-label', 'Close preview');
3085
3086 const dlBtn = document.createElement('button');
3087 dlBtn.className = 'preview-expand-download';
3088 dlBtn.type = 'button';
3089 dlBtn.textContent = 'Download';
3090 dlBtn.addEventListener('click', async (e) =>
3091 {
3092 e.stopPropagation();
3093 if (STATE.previewDownloadAction)
3094 {
3095 await STATE.previewDownloadAction();
3096 return;
3097 }
3098 if (!STATE.previewObjectUrl)
3099 {
3100 toast('Preview still loading.', 'err');
3101 return;
3102 }
3103 triggerDownload(item.name, STATE.previewObjectUrl);
3104 });
3105
3106 const shareBtn = document.createElement('button');
3107 shareBtn.className = 'preview-expand-share';
3108 shareBtn.type = 'button';
3109 shareBtn.textContent = 'Share';
3110 shareBtn.addEventListener('click', (e) =>
3111 {
3112 e.stopPropagation();
3113 openShareModal(item);
3114 });
3115
3116 const actionsEl = document.createElement('div');
3117 actionsEl.className = 'preview-expand-actions';
3118 actionsEl.appendChild(shareBtn);
3119 actionsEl.appendChild(dlBtn);
3120
3121 iconEl.innerHTML = '';
3122
3123 if (originalIconSvg)
3124 {
3125 const outline = originalIconSvg.cloneNode(true);
3126 outline.classList.add('preview-expand-outline');
3127 iconEl.appendChild(outline);
3128 }
3129
3130 const previewMount = document.createElement('div');
3131 previewMount.className = 'preview-expand-content';
3132 iconEl.appendChild(previewMount);
3133
3134 // Show spinner during expansion animation; content loads after it finishes
3135 const spinner = document.createElement('div');
3136 spinner.className = 'preview-loading-spinner';
3137 previewMount.appendChild(spinner);
3138
3139 tileEl.insertBefore(titleEl, tileEl.firstChild);
3140 tileEl.appendChild(closeBtn);
3141 tileEl.appendChild(actionsEl);
3142
3143 STATE.previewExpandState = {
3144 item,
3145 requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)),
3146 tileEl,
3147 sourceSvgEl,
3148 parent,
3149 nextSibling,
3150 iconEl,
3151 iconHtml,
3152 nameEl,
3153 backdrop,
3154 closeBtn,
3155 dlBtn,
3156 shareBtn,
3157 actionsEl,
3158 titleEl,
3159 previewMount,
3160 startRect,
3161 };
3162
3163 const onBackdrop = (e) =>
3164 {
3165 if (e.target === backdrop) closePreview();
3166 };
3167 const onClose = () => closePreview({ force: true });
3168 backdrop.addEventListener('click', onBackdrop);
3169 closeBtn.addEventListener('click', onClose);
3170 STATE.previewExpandState.onBackdrop = onBackdrop;
3171 STATE.previewExpandState.onClose = onClose;
3172
3173 requestAnimationFrame(() => backdrop.classList.add('visible'));
3174 await animateRect(tileEl, startRect, targetRect);
3175
3176 tileEl.style.left = `${targetRect.left}px`;
3177 tileEl.style.top = `${targetRect.top}px`;
3178 tileEl.style.width = `${targetRect.width}px`;
3179 tileEl.style.height = `${targetRect.height}px`;
3180
3181 try
3182 {
3183 await loadPreviewContent(previewMount);
3184 } catch
3185 {
3186 if (previewMount.isConnected)
3187 {
3188 previewMount.innerHTML = '';
3189 const msg = document.createElement('p');
3190 msg.className = 'preview-unsupported';
3191 msg.textContent = 'Preview failed to load. You can try again.';
3192 previewMount.appendChild(msg);
3193 }
3194 }
3195
3196 return true;
3197}
3198
3199async function closeExpandedTilePreview ()
3200{
3201 const st = STATE.previewExpandState;
3202 if (!st) return;
3203
3204 st.backdrop.classList.remove('visible');
3205 if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop);
3206 if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose);
3207
3208 const fromRect = st.tileEl.getBoundingClientRect();
3209 await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 });
3210
3211 st.tileEl.classList.remove('file-item--preview');
3212 st.tileEl.style.position = '';
3213 st.tileEl.style.left = '';
3214 st.tileEl.style.top = '';
3215 st.tileEl.style.width = '';
3216 st.tileEl.style.height = '';
3217 st.tileEl.style.margin = '';
3218 st.tileEl.style.zIndex = '';
3219
3220 if (st.titleEl) st.titleEl.remove();
3221 if (st.closeBtn) st.closeBtn.remove();
3222 if (st.actionsEl) st.actionsEl.remove();
3223 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
3224 if (st.nameEl) st.nameEl.style.display = '';
3225
3226 if (st.parent)
3227 {
3228 if (st.nextSibling && st.nextSibling.parentNode === st.parent)
3229 {
3230 st.parent.insertBefore(st.tileEl, st.nextSibling);
3231 } else
3232 {
3233 st.parent.appendChild(st.tileEl);
3234 }
3235 }
3236
3237 if (st.backdrop) st.backdrop.remove();
3238 STATE.previewExpandState = null;
3239}
3240
3241async function closePreview (opts = {})
3242{
3243 if (STATE.previewClosing) return;
3244 if (STATE.previewExpandState)
3245 {
3246 if (STATE.previewExpandState.requireExplicitClose && !opts.force)
3247 {
3248 return;
3249 }
3250
3251 STATE.previewClosing = true;
3252 clearPreviewObjectUrl();
3253 try
3254 {
3255 await closeExpandedTilePreview();
3256 STATE.previewSourceEl = null;
3257 } finally
3258 {
3259 STATE.previewClosing = false;
3260 }
3261 }
3262}
3263
3264async function fetchFileBlob (item)
3265{
3266 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
3267 try
3268 {
3269 const res = await fetch(url, {
3270 headers: {
3271 Authorization: 'Bearer ' + STATE.token,
3272 'X-Fp': getFingerprint(),
3273 },
3274 });
3275 if (!res.ok) throw new Error('Download failed.');
3276 return await res.blob();
3277 } catch
3278 {
3279 return null;
3280 }
3281}
3282
3283function triggerDownload (filename, objectUrl)
3284{
3285 const a = document.createElement('a');
3286 a.href = objectUrl;
3287 a.download = filename;
3288 a.click();
3289}
3290
3291async function renderPreviewBody (item, blob, objectUrl, targetEl = null)
3292{
3293 const body = targetEl || document.getElementById('preview-body');
3294 body.innerHTML = '';
3295
3296 const mime = String(blob.type || '').toLowerCase();
3297 const previewable = isInlinePreviewableBlob(blob, item.name);
3298
3299 if (!previewable)
3300 {
3301 const msg = document.createElement('p');
3302 msg.className = 'preview-unsupported';
3303 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
3304 body.appendChild(msg);
3305 return;
3306 }
3307
3308 if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name)))
3309 {
3310 const img = document.createElement('img');
3311 img.className = 'preview-media';
3312 img.src = objectUrl;
3313 img.alt = item.name;
3314 body.appendChild(img);
3315 return;
3316 }
3317
3318 if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name)))
3319 {
3320 const video = document.createElement('video');
3321 video.className = 'preview-media';
3322 video.src = objectUrl;
3323 video.controls = true;
3324 video.preload = 'metadata';
3325 body.appendChild(video);
3326 return;
3327 }
3328
3329 if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name)))
3330 {
3331 const audio = document.createElement('audio');
3332 audio.className = 'preview-audio';
3333 audio.src = objectUrl;
3334 audio.controls = true;
3335 body.appendChild(audio);
3336 return;
3337 }
3338
3339 if (mime === 'application/pdf')
3340 {
3341 const frame = document.createElement('iframe');
3342 frame.className = 'preview-frame';
3343 frame.src = objectUrl;
3344 frame.title = item.name;
3345 body.appendChild(frame);
3346 return;
3347 }
3348
3349 if (isTextLikeBlob(blob, item.name))
3350 {
3351 const text = await blob.text();
3352 const lang = detectCodeLanguage(item.name, mime);
3353 const formatted = prettyPrintCode(text, lang);
3354 const pre = document.createElement('pre');
3355 pre.className = 'preview-text preview-code';
3356 pre.innerHTML = highlightCode(formatted, lang);
3357 body.appendChild(pre);
3358 return;
3359 }
3360
3361 const msg = document.createElement('p');
3362 msg.className = 'preview-unsupported';
3363 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
3364 body.appendChild(msg);
3365}
3366
3367async function downloadOrView (item, sourceSvgEl = null)
3368{
3369 if (STATE.previewExpandState)
3370 {
3371 await closePreview({ force: true });
3372 }
3373
3374 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
3375 if (sourceTileEl)
3376 {
3377 STATE.previewSourceEl = sourceSvgEl;
3378 const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>
3379 {
3380 if (VIDEO_EXTS.has(extOf(item.name)))
3381 {
3382 clearPreviewObjectUrl();
3383 previewMount.innerHTML = '';
3384 await renderStreamedVideoPreview(item, previewMount);
3385 return;
3386 }
3387
3388 const blob = await fetchFileBlob(item);
3389 if (!blob) throw new Error('Download failed');
3390
3391 clearPreviewObjectUrl();
3392 const objectUrl = URL.createObjectURL(blob);
3393 STATE.previewObjectUrl = objectUrl;
3394
3395 if (!previewMount.isConnected) return;
3396
3397 previewMount.innerHTML = '';
3398 await renderPreviewBody(item, blob, objectUrl, previewMount);
3399 });
3400 if (expanded) return;
3401 }
3402
3403 toast('Preview unavailable — no source tile found.', 'err');
3404}
3405
3406// ───────────────────────────────────────────────────────────────────────────
3407// UPLOAD
3408// ───────────────────────────────────────────────────────────────────────────
3409
3410function canWrite (item = null)
3411{
3412 if (STATE.isAdmin) return true;
3413 const root = item && item._root
3414 ? item._root
3415 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
3416 if (!root) return false;
3417 const p = STATE.permissions[rootPermissionLabel(root)];
3418 return p && p.write;
3419}
3420
3421async function uploadFiles (fileList)
3422{
3423 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3424 if (!canWrite()) { toast('No write access.', 'err'); return; }
3425
3426 const files = Array.from(fileList || []);
3427 if (!files.length) return;
3428
3429 // Show upload bar
3430 const wrap = document.createElement('div');
3431 wrap.className = 'upload-bar-wrap';
3432 wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
3433 document.body.appendChild(wrap);
3434 STATE.uploadInProgress = true;
3435
3436 try
3437 {
3438 const existingNames = await listDirNameSet(STATE.currentDir);
3439 let done = 0;
3440 let uploaded = 0;
3441
3442 for (const original of files)
3443 {
3444 let fileToUpload = original;
3445
3446 if (existingNames.has(original.name))
3447 {
3448 const suggested = nextAvailableName(original.name, existingNames);
3449 const decision = await showFileConflictChoice(original.name, suggested, 'upload');
3450 if (decision === 'cancel')
3451 {
3452 done++;
3453 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
3454 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
3455 continue;
3456 }
3457
3458 if (decision === 'rename')
3459 {
3460 fileToUpload = cloneFileWithName(original, suggested);
3461 }
3462 }
3463
3464 await uploadSingleFile(fileToUpload, STATE.currentDir);
3465 existingNames.add(fileToUpload.name);
3466 done++;
3467 uploaded++;
3468 wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`;
3469 wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%';
3470 }
3471
3472 toast(`Uploaded ${uploaded} file(s).`, 'ok');
3473 await navigateTo(STATE.currentDir, STATE.currentRoot);
3474 } catch (err)
3475 {
3476 toast(err.message, 'err');
3477 } finally
3478 {
3479 STATE.uploadInProgress = false;
3480 wrap.remove();
3481 }
3482}
3483
3484async function uploadSingleFile (file, targetDir)
3485{
3486 const formData = new FormData();
3487 formData.append('files', file);
3488
3489 await new Promise((resolve, reject) =>
3490 {
3491 const xhr = new XMLHttpRequest();
3492 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
3493 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
3494 xhr.setRequestHeader('X-Fp', getFingerprint());
3495 xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
3496 xhr.onload = () => xhr.status === 200
3497 ? resolve()
3498 : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
3499 xhr.onerror = () => reject(new Error('Network error'));
3500 xhr.send(formData);
3501 });
3502}
3503
3504async function ensureServerDir (baseDir, relativeDir)
3505{
3506 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
3507 let current = baseDir;
3508 for (const part of parts)
3509 {
3510 try
3511 {
3512 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
3513 current = resp && resp.path ? resp.path : joinServerPath(current, part);
3514 } catch (err)
3515 {
3516 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
3517 current = joinServerPath(current, part);
3518 }
3519 }
3520 return current;
3521}
3522
3523async function uploadFolderInputFiles (fileList)
3524{
3525 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3526 if (!canWrite()) { toast('No write access.', 'err'); return; }
3527 if (!fileList || !fileList.length) return;
3528
3529 const files = Array.from(fileList);
3530 const total = files.length;
3531 let done = 0;
3532
3533 const wrap = document.createElement('div');
3534 wrap.className = 'upload-bar-wrap';
3535 wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
3536 document.body.appendChild(wrap);
3537 STATE.uploadInProgress = true;
3538
3539 try
3540 {
3541 const dirCache = new Map();
3542 dirCache.set('', STATE.currentDir);
3543
3544 for (const file of files)
3545 {
3546 const rel = file.webkitRelativePath || file.name;
3547 const relParts = rel.split(/[\\/]/).filter(Boolean);
3548 const relDir = relParts.slice(0, -1).join('/');
3549
3550 if (!dirCache.has(relDir))
3551 {
3552 const parentRel = relParts.slice(0, -2).join('/');
3553 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
3554 const thisName = relParts[relParts.length - 2];
3555
3556 try
3557 {
3558 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
3559 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
3560 } catch (err)
3561 {
3562 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
3563 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
3564 }
3565 }
3566
3567 const targetDir = dirCache.get(relDir) || STATE.currentDir;
3568 await uploadSingleFile(file, targetDir);
3569 done++;
3570 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
3571 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
3572 }
3573
3574 toast(`Uploaded ${total} file(s).`, 'ok');
3575 await navigateTo(STATE.currentDir, STATE.currentRoot);
3576 } catch (err)
3577 {
3578 toast(err.message, 'err');
3579 } finally
3580 {
3581 STATE.uploadInProgress = false;
3582 wrap.remove();
3583 }
3584}
3585
3586// ───────────────────────────────────────────────────────────────────────────
3587// FOLDER DRAG-AND-DROP (recursive)
3588// ───────────────────────────────────────────────────────────────────────────
3589
3590/**
3591 * Reads all readEntries batches from a DirectoryReader (browsers may return
3592 * results in chunks; we must keep calling until we get an empty array).
3593 */
3594function readAllEntries (reader)
3595{
3596 return new Promise((resolve, reject) =>
3597 {
3598 const all = [];
3599 function next ()
3600 {
3601 reader.readEntries(batch =>
3602 {
3603 if (!batch.length) { resolve(all); return; }
3604 all.push(...batch);
3605 next();
3606 }, reject);
3607 }
3608 next();
3609 });
3610}
3611
3612/**
3613 * Recursively walk a FileSystemEntry tree, creating server-side directories
3614 * on the fly and collecting { file, targetDir } pairs for upload.
3615 */
3616async function collectEntries (entry, serverDir, toUpload)
3617{
3618 if (entry.isFile)
3619 {
3620 const file = await new Promise((res, rej) => entry.file(res, rej));
3621 toUpload.push({ file, targetDir: serverDir });
3622 } else if (entry.isDirectory)
3623 {
3624 // Ask the server to create the directory; it returns the canonical path.
3625 let newServerDir;
3626 try
3627 {
3628 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
3629 newServerDir = resp.path;
3630 } catch
3631 {
3632 // Directory may already exist — reconstruct path from what we know.
3633 // The server always returns JSON with {error} on failure, so we can
3634 // still continue by falling back to a best-effort path join.
3635 // We rely on the fact that the server separator is consistent within
3636 // a session (the list/browse API already returned paths in that format).
3637 const sep = serverDir.includes('\\') ? '\\' : '/';
3638 newServerDir = serverDir + sep + entry.name;
3639 }
3640 const reader = entry.createReader();
3641 const subEntries = await readAllEntries(reader);
3642 for (const sub of subEntries)
3643 {
3644 await collectEntries(sub, newServerDir, toUpload);
3645 }
3646 }
3647}
3648
3649async function uploadEntries (entries)
3650{
3651 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
3652 if (!canWrite()) { toast('No write access.', 'err'); return; }
3653
3654 const wrap = document.createElement('div');
3655 wrap.className = 'upload-bar-wrap';
3656 wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
3657 document.body.appendChild(wrap);
3658 STATE.uploadInProgress = true;
3659
3660 try
3661 {
3662 const toUpload = [];
3663 for (const entry of entries)
3664 {
3665 await collectEntries(entry, STATE.currentDir, toUpload);
3666 }
3667
3668 if (!toUpload.length) { toast('No files found.', 'err'); return; }
3669
3670 let done = 0;
3671 const total = toUpload.length;
3672 const updateBar = () =>
3673 {
3674 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
3675 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
3676 };
3677 updateBar();
3678
3679 for (const { file, targetDir } of toUpload)
3680 {
3681 await uploadSingleFile(file, targetDir);
3682 done++;
3683 updateBar();
3684 }
3685
3686 toast(`Uploaded ${total} file(s).`, 'ok');
3687 await navigateTo(STATE.currentDir, STATE.currentRoot);
3688 } catch (err)
3689 {
3690 toast(err.message, 'err');
3691 } finally
3692 {
3693 STATE.uploadInProgress = false;
3694 wrap.remove();
3695 }
3696}
3697
3698// DRAG-AND-DROP
3699// ───────────────────────────────────────────────────────────────────────────
3700
3701function initDragDrop ()
3702{
3703 const main = document.getElementById('main-content');
3704 const dropOvl = document.getElementById('drop-overlay');
3705 let dragDepth = 0;
3706
3707 main.addEventListener('dragenter', e =>
3708 {
3709 e.preventDefault();
3710 dragDepth++;
3711 dropOvl.classList.remove('hidden');
3712 });
3713 main.addEventListener('dragleave', () =>
3714 {
3715 dragDepth--;
3716 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
3717 });
3718 main.addEventListener('dragover', e => e.preventDefault());
3719 main.addEventListener('drop', async e =>
3720 {
3721 e.preventDefault();
3722 dragDepth = 0;
3723 dropOvl.classList.add('hidden');
3724 if (!canWrite()) { toast('No write access.', 'err'); return; }
3725
3726 const items = Array.from(e.dataTransfer.items || []);
3727 // Use the FileSystem Entry API when available so we can handle folders.
3728 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
3729 {
3730 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
3731 if (entries.some(en => en.isDirectory))
3732 {
3733 await uploadEntries(entries);
3734 return;
3735 }
3736 }
3737 // Plain files only — use the fast batch path.
3738 const files = e.dataTransfer.files;
3739 if (files.length) await uploadFiles(files);
3740 });
3741}
3742
3743// ───────────────────────────────────────────────────────────────────────────
3744// RENAME
3745// ───────────────────────────────────────────────────────────────────────────
3746
3747function openRenameModal (item)
3748{
3749 const modal = document.getElementById('rename-modal');
3750 modal.classList.remove('hidden');
3751 const input = document.getElementById('rename-input');
3752 input.value = item.name;
3753 input.focus();
3754 input.select();
3755 document.getElementById('rename-error').classList.add('hidden');
3756 document.getElementById('rename-form').onsubmit = async (e) =>
3757 {
3758 e.preventDefault();
3759 const newName = input.value.trim();
3760 if (!newName) return;
3761 try
3762 {
3763 if (item._root)
3764 {
3765 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
3766 } else
3767 {
3768 await api('POST', '/files/rename', { from: item.path, to: newName });
3769 }
3770 modal.classList.add('hidden');
3771 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
3772 if (item._root)
3773 {
3774 await loadRoots({
3775 preferredDir: STATE.currentDir,
3776 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
3777 });
3778 } else
3779 {
3780 await navigateTo(STATE.currentDir, STATE.currentRoot);
3781 }
3782 } catch (err)
3783 {
3784 document.getElementById('rename-error').textContent = err.message;
3785 document.getElementById('rename-error').classList.remove('hidden');
3786 }
3787 };
3788}
3789
3790// ───────────────────────────────────────────────────────────────────────────
3791// DELETE
3792// ───────────────────────────────────────────────────────────────────────────
3793
3794async function deleteItem (item)
3795{
3796 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
3797 try
3798 {
3799 await api('POST', '/files/delete', { path: item.path });
3800 toast('Deleted.', 'ok');
3801 closeSidebar();
3802 await navigateTo(STATE.currentDir, STATE.currentRoot);
3803 } catch (err)
3804 {
3805 toast(err.message, 'err');
3806 }
3807}
3808
3809// ───────────────────────────────────────────────────────────────────────────
3810// ADMIN PANEL
3811// ───────────────────────────────────────────────────────────────────────────
3812
3813let _adminUpdateStatus = null;
3814
3815async function openAdminModal ()
3816{
3817 document.getElementById('admin-modal').classList.remove('hidden');
3818 await refreshAdminConfig();
3819 await refreshAdminUsers();
3820 void refreshAdminUpdateStatus();
3821}
3822
3823async function refreshAdminConfig ()
3824{
3825 const data = await api('GET', '/admin/config');
3826 if (!data) return;
3827
3828 const userPathInput = document.getElementById('admin-user-path');
3829 const sizeInput = document.getElementById('admin-user-size-limit');
3830 if (userPathInput) userPathInput.value = data.userPath || '';
3831 if (sizeInput)
3832 {
3833 sizeInput.value = data.userFolderSizeLimit ? formatBytes(data.userFolderSizeLimit) : '';
3834 updateAdminSizeFeedback(sizeInput.value);
3835 }
3836
3837 const container = document.getElementById('admin-paths');
3838 container.innerHTML = '';
3839 for (const p of data.paths)
3840 {
3841 const row = document.createElement('div');
3842 row.className = 'path-row';
3843 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
3844 row.querySelector('button').addEventListener('click', () =>
3845 {
3846 row.remove();
3847 });
3848 container.appendChild(row);
3849 }
3850}
3851
3852async function refreshAdminUsers ()
3853{
3854 const data = await api('GET', '/admin/users');
3855 if (!data) return;
3856 const container = document.getElementById('admin-users-list');
3857 container.innerHTML = '';
3858
3859 // Need paths for permission rows
3860 const cfg = await api('GET', '/admin/config');
3861 const paths = cfg ? (cfg.effectivePaths || []) : [];
3862
3863 for (const u of data.users)
3864 {
3865 const row = document.createElement('div');
3866 row.className = 'user-row';
3867 row.innerHTML = `
3868 <span class="user-name">${u.username}</span>
3869 ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''}
3870 <button data-id="${u.id}" data-action="edit">Edit</button>
3871 ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`}
3872 `;
3873 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
3874 openUserModal(u, paths));
3875 const deleteBtn = row.querySelector('[data-action="delete"]');
3876 if (deleteBtn) deleteBtn.addEventListener('click', async () =>
3877 {
3878 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
3879 try
3880 {
3881 await api('DELETE', `/admin/users/${u.id}`);
3882 toast('User deleted.', 'ok');
3883 await refreshAdminUsers();
3884 } catch (err) { toast(err.message, 'err'); }
3885 });
3886 container.appendChild(row);
3887 }
3888}
3889
3890async function refreshAdminUpdateStatus ()
3891{
3892 const btn = document.getElementById('admin-shutdown-btn');
3893 _adminUpdateStatus = null;
3894 btn.textContent = 'Shut down server';
3895
3896 try
3897 {
3898 const data = await api('GET', '/admin/update-status');
3899 if (!data) return;
3900 _adminUpdateStatus = data;
3901
3902 if (!data.underSystemd)
3903 {
3904 btn.textContent = 'Shut down server';
3905 }
3906 else if (data.commitsAhead.length === 0)
3907 {
3908 btn.textContent = 'Restart Server';
3909 }
3910 else
3911 {
3912 btn.textContent = 'Restart & Update';
3913 }
3914 }
3915 catch
3916 {
3917 // Not critical; button stays as "Shut down server".
3918 }
3919}
3920
3921function openUserModal (user, paths)
3922{
3923 const modal = document.getElementById('user-modal');
3924 modal.classList.remove('hidden');
3925 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
3926 document.getElementById('user-error').classList.add('hidden');
3927
3928 const usernameInput = document.getElementById('user-username');
3929 usernameInput.value = user ? user.username : '';
3930 usernameInput.readOnly = !!user;
3931
3932 document.getElementById('user-password').value = '';
3933 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
3934
3935 // Password placeholder
3936 document.getElementById('user-password').placeholder =
3937 user ? 'Leave blank to keep current' : 'Min 8 characters';
3938
3939 // Build permissions grid
3940 const permDiv = document.getElementById('user-permissions');
3941 permDiv.innerHTML = '';
3942 if (paths.length)
3943 {
3944 const heading = document.createElement('h4');
3945 heading.textContent = 'Path Permissions';
3946 permDiv.appendChild(heading);
3947
3948 const isAdminUser = !!(user && user.isAdmin);
3949 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
3950 const adminChk = document.getElementById('user-is-admin');
3951 const rebuildPermRows = (admin) =>
3952 {
3953 permDiv.querySelectorAll('.perm-row').forEach(r =>
3954 {
3955 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
3956 {
3957 cb.disabled = admin;
3958 if (admin) cb.checked = true;
3959 });
3960 r.title = admin ? 'Admins always have full access' : '';
3961 });
3962 };
3963 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
3964
3965 const syncReadWriteConstraints = (row, admin = false) =>
3966 {
3967 const readCb = row.querySelector('input[data-type="read"]');
3968 const writeCb = row.querySelector('input[data-type="write"]');
3969 if (!readCb || !writeCb) return;
3970
3971 if (admin)
3972 {
3973 readCb.checked = true;
3974 writeCb.checked = true;
3975 readCb.disabled = true;
3976 writeCb.disabled = true;
3977 return;
3978 }
3979
3980 readCb.disabled = false;
3981 if (!readCb.checked)
3982 {
3983 writeCb.checked = false;
3984 writeCb.disabled = true;
3985 }
3986 else
3987 {
3988 writeCb.disabled = false;
3989 }
3990 };
3991
3992 const syncAllReadWriteConstraints = () =>
3993 {
3994 const admin = adminChk.checked;
3995 permDiv.querySelectorAll('.perm-row').forEach((row) =>
3996 {
3997 syncReadWriteConstraints(row, admin);
3998 });
3999 };
4000
4001 for (const p of paths)
4002 {
4003 const label = p.split(/[\\/]/).pop();
4004 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
4005 const row = document.createElement('div');
4006 row.className = 'perm-row';
4007 const readChecked = isAdminUser || perms.read;
4008 const writeChecked = isAdminUser || perms.write;
4009 row.innerHTML = `
4010 <span class="perm-label">${label}</span>
4011 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label>
4012 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label>
4013 `;
4014 if (isAdminUser) row.title = 'Admins always have full access';
4015 const readCb = row.querySelector('input[data-type="read"]');
4016 if (readCb)
4017 {
4018 readCb.addEventListener('change', () =>
4019 {
4020 syncReadWriteConstraints(row, adminChk.checked);
4021 });
4022 }
4023 permDiv.appendChild(row);
4024 }
4025
4026 syncAllReadWriteConstraints();
4027 adminChk.addEventListener('change', syncAllReadWriteConstraints);
4028 }
4029
4030 document.getElementById('user-form').onsubmit = async (e) =>
4031 {
4032 e.preventDefault();
4033 const password = document.getElementById('user-password').value;
4034 const isAdmin = document.getElementById('user-is-admin').checked;
4035 const permissions = {};
4036 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
4037 {
4038 const lbl = cb.dataset.label;
4039 if (!permissions[lbl]) permissions[lbl] = {};
4040 permissions[lbl][cb.dataset.type] = cb.checked;
4041 });
4042
4043 try
4044 {
4045 if (user)
4046 {
4047 const body = { isAdmin, permissions };
4048 if (password) body.password = password;
4049 await api('PATCH', `/admin/users/${user.id}`, body);
4050 } else
4051 {
4052 const uname = document.getElementById('user-username').value.trim();
4053 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
4054 }
4055 modal.classList.add('hidden');
4056 toast('User saved.', 'ok');
4057 await refreshAdminUsers();
4058 } catch (err)
4059 {
4060 document.getElementById('user-error').textContent = err.message;
4061 document.getElementById('user-error').classList.remove('hidden');
4062 }
4063 };
4064}
4065
4066// ───────────────────────────────────────────────────────────────────────────
4067// SVG ICONS
4068// ───────────────────────────────────────────────────────────────────────────
4069
4070const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
4071const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
4072const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
4073const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
4074const 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']);
4075const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
4076const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024;
4077
4078function iconFolder (size = 52)
4079{
4080 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
4081 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
4082 <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"/>
4083 </svg>`;
4084}
4085
4086function iconFile (name, size = 52)
4087{
4088 const color = fileAccentColor(name);
4089 let symbol = '';
4090
4091 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
4092 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
4093 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
4094 <polyline points="14 2 14 8 20 8"/>
4095 </svg>`;
4096}
4097
4098// ───────────────────────────────────────────────────────────────────────────
4099// EVENT WIRING
4100// ───────────────────────────────────────────────────────────────────────────
4101
4102// ───────────────────────────────────────────────────────────────────────────
4103// THUMBNAIL PREVIEWS
4104// ───────────────────────────────────────────────────────────────────────────
4105
4106function revokeThumbnails ()
4107{
4108 STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u));
4109 STATE.thumbnailUrls = [];
4110}
4111
4112function disconnectThumbnailObserver ()
4113{
4114 if (!STATE.thumbnailObserver) return;
4115 STATE.thumbnailObserver.disconnect();
4116 STATE.thumbnailObserver = null;
4117}
4118
4119function disconnectFolderIconObserver ()
4120{
4121 if (!STATE.folderIconObserver) return;
4122 STATE.folderIconObserver.disconnect();
4123 STATE.folderIconObserver = null;
4124}
4125
4126function setThumbnailPending (iconEl, pending)
4127{
4128 if (!iconEl) return;
4129 if (pending)
4130 {
4131 iconEl.classList.add('thumb-pending');
4132 iconEl.dataset.thumbPending = '1';
4133 return;
4134 }
4135
4136 iconEl.classList.remove('thumb-pending');
4137 delete iconEl.dataset.thumbPending;
4138}
4139
4140function getThumbnailKind (name)
4141{
4142 const ext = extOf(name || '');
4143 if (IMAGE_EXTS.has(ext)) return 'image';
4144 if (CODE_EXTS.has(ext)) return 'text';
4145 return 'badge';
4146}
4147
4148function maxThumbBytesForKind (kind)
4149{
4150 if (kind === 'image') return 15 * 1024 * 1024;
4151 if (kind === 'text') return 1024 * 1024;
4152 return 0;
4153}
4154
4155function drawTokenizedLine (ctx, line, x, y)
4156{
4157 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;
4158 let last = 0;
4159 let cursor = x;
4160 for (const m of line.matchAll(tokenRe))
4161 {
4162 const i = m.index == null ? 0 : m.index;
4163 if (i > last)
4164 {
4165 const plain = line.slice(last, i);
4166 ctx.fillStyle = '#dce4ff';
4167 ctx.fillText(plain, cursor, y);
4168 cursor += ctx.measureText(plain).width;
4169 }
4170
4171 const tok = m[0];
4172 if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a';
4173 else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d';
4174 else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a';
4175 else ctx.fillStyle = '#8bb4ff';
4176
4177 ctx.fillText(tok, cursor, y);
4178 cursor += ctx.measureText(tok).width;
4179 last = i + tok.length;
4180 }
4181
4182 if (last < line.length)
4183 {
4184 const tail = line.slice(last);
4185 ctx.fillStyle = '#dce4ff';
4186 ctx.fillText(tail, cursor, y);
4187 }
4188}
4189
4190function textThumbnailDataUrl (text)
4191{
4192 const canvas = document.createElement('canvas');
4193 canvas.width = 160;
4194 canvas.height = 200;
4195 const ctx = canvas.getContext('2d');
4196 if (!ctx) return null;
4197
4198 ctx.fillStyle = '#0d111a';
4199 ctx.fillRect(0, 0, canvas.width, canvas.height);
4200 ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
4201 ctx.textBaseline = 'top';
4202
4203 const lines = String(text || '')
4204 .replace(/\r\n/g, '\n')
4205 .split('\n')
4206 .slice(0, 17);
4207
4208 let y = 8;
4209 for (const line of lines)
4210 {
4211 drawTokenizedLine(ctx, line.slice(0, 42), 6, y);
4212 y += 11;
4213 if (y > 190) break;
4214 }
4215 return canvas.toDataURL('image/png');
4216}
4217
4218function badgeThumbnailDataUrl (name, kind)
4219{
4220 const canvas = document.createElement('canvas');
4221 canvas.width = 160;
4222 canvas.height = 200;
4223 const ctx = canvas.getContext('2d');
4224 if (!ctx) return null;
4225
4226 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
4227 const color = '#5b7fff';
4228
4229 ctx.fillStyle = '#111826';
4230 ctx.fillRect(0, 0, 160, 200);
4231 ctx.fillStyle = color;
4232 ctx.fillRect(0, 0, 160, 28);
4233 ctx.fillStyle = '#ffffff';
4234 ctx.font = 'bold 12px sans-serif';
4235 ctx.textAlign = 'center';
4236 ctx.fillText(ext, 80, 8);
4237 ctx.textAlign = 'left';
4238 ctx.fillStyle = '#9fb1d8';
4239 ctx.font = '10px sans-serif';
4240 ctx.fillText('Preview', 8, 48);
4241 ctx.fillStyle = '#dce4ff';
4242 ctx.font = 'bold 11px sans-serif';
4243 ctx.fillText(ext, 8, 66);
4244 return canvas.toDataURL('image/png');
4245}
4246
4247async function buildThumbnailSource (item, blob, kind)
4248{
4249 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
4250 return badgeThumbnailDataUrl(item.name, kind);
4251}
4252
4253function observeThumbnailIcon (iconEl)
4254{
4255 if (!iconEl || !iconEl.isConnected) return;
4256 if (iconEl.dataset.thumbReady === '1') return;
4257
4258 if (!('IntersectionObserver' in window))
4259 {
4260 void loadOneThumbnail(iconEl);
4261 return;
4262 }
4263
4264 if (!STATE.thumbnailObserver)
4265 {
4266 STATE.thumbnailObserver = new IntersectionObserver((entries) =>
4267 {
4268 for (const entry of entries)
4269 {
4270 if (!entry.isIntersecting) continue;
4271 const icon = entry.target;
4272 STATE.thumbnailObserver.unobserve(icon);
4273 void loadOneThumbnail(icon);
4274 }
4275 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
4276 }
4277
4278 STATE.thumbnailObserver.observe(iconEl);
4279}
4280
4281async function loadThumbnails ()
4282{
4283 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
4284 for (const icon of icons)
4285 {
4286 observeThumbnailIcon(icon);
4287 }
4288
4289 const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]'));
4290 for (const icon of folderIcons)
4291 {
4292 observeFolderIcon(icon);
4293 }
4294}
4295
4296async function loadOneThumbnail (iconEl)
4297{
4298 if (!iconEl.isConnected || !STATE.token) return;
4299 if (iconEl.dataset.thumbReady === '1') return;
4300 const filePath = iconEl.dataset.previewPath;
4301 const item = STATE.items.find(i => i.path === filePath);
4302 if (!item) return;
4303
4304 const kind = getThumbnailKind(item.name);
4305 let srcUrl = null;
4306
4307 if (kind === 'badge')
4308 {
4309 setThumbnailPending(iconEl, false);
4310 srcUrl = badgeThumbnailDataUrl(item.name, kind);
4311 }
4312 else if (kind === 'image')
4313 {
4314 const ext = extOf(item.name || '');
4315 const useDirectSource =
4316 ext === 'ico' ||
4317 (
4318 ext === 'svg' &&
4319 typeof item.size === 'number' &&
4320 item.size > 0 &&
4321 item.size <= MAX_DIRECT_SVG_THUMB_BYTES
4322 );
4323
4324 const url = useDirectSource
4325 ? `/api/files/download?file=${encodeURIComponent(filePath)}`
4326 : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
4327
4328 let res;
4329 try
4330 {
4331 res = await fetch(url, {
4332 headers: {
4333 Authorization: `Bearer ${STATE.token}`,
4334 'X-Fp': getFingerprint(),
4335 },
4336 });
4337 } catch
4338 {
4339 return;
4340 }
4341
4342 if (!useDirectSource && res.status === 404)
4343 {
4344 setThumbnailPending(iconEl, true);
4345 return;
4346 }
4347
4348 if (!res.ok || !iconEl.isConnected) return;
4349 setThumbnailPending(iconEl, false);
4350
4351 const blob = await res.blob();
4352 srcUrl = URL.createObjectURL(blob);
4353 STATE.thumbnailUrls.push(srcUrl);
4354 }
4355 else
4356 {
4357 setThumbnailPending(iconEl, false);
4358 const maxBytes = maxThumbBytesForKind(kind);
4359 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
4360 {
4361 srcUrl = badgeThumbnailDataUrl(item.name, kind);
4362 } else
4363 {
4364 const url = `/api/files/download?file=${encodeURIComponent(filePath)}`;
4365
4366 let res;
4367 try
4368 {
4369 res = await fetch(url, {
4370 headers: {
4371 Authorization: `Bearer ${STATE.token}`,
4372 'X-Fp': getFingerprint(),
4373 },
4374 });
4375 } catch { return; }
4376 if (!res.ok || !iconEl.isConnected) return;
4377
4378 const blob = await res.blob();
4379 srcUrl = await buildThumbnailSource(item, blob, kind);
4380 }
4381 }
4382 if (!srcUrl || !iconEl.isConnected) return;
4383
4384 const svg = iconEl.querySelector('svg');
4385 if (!svg)
4386 {
4387 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
4388 return;
4389 }
4390
4391 const NS = 'http://www.w3.org/2000/svg';
4392 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
4393
4394 // clipPath matches the main file body outline exactly (viewBox 0 0 24 24)
4395 const defs = document.createElementNS(NS, 'defs');
4396 const clipPath = document.createElementNS(NS, 'clipPath');
4397 clipPath.setAttribute('id', id);
4398 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
4399 const clipShape = document.createElementNS(NS, 'path');
4400 clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z');
4401 clipPath.appendChild(clipShape);
4402 defs.appendChild(clipPath);
4403
4404 // Image fills the file bounding box; clip keeps it inside the outline
4405 const img = document.createElementNS(NS, 'image');
4406 img.setAttribute('href', srcUrl);
4407 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
4408 img.setAttribute('x', '4');
4409 img.setAttribute('y', '2');
4410 img.setAttribute('width', '16');
4411 img.setAttribute('height', '20');
4412 img.setAttribute('clip-path', `url(#${id})`);
4413 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
4414
4415 // Prepend so existing path/polyline elements (the outline) render on top
4416 svg.prepend(img);
4417 svg.prepend(defs);
4418 iconEl.dataset.thumbReady = '1';
4419}
4420
4421// ───────────────────────────────────────────────────────────────────────────
4422// FOLDER ICON THUMBNAILS
4423// ───────────────────────────────────────────────────────────────────────────
4424
4425function observeFolderIcon (iconEl)
4426{
4427 if (!iconEl || !iconEl.isConnected) return;
4428 if (iconEl.dataset.thumbReady === '1') return;
4429
4430 if (!('IntersectionObserver' in window))
4431 {
4432 void loadOneFolderIcon(iconEl);
4433 return;
4434 }
4435
4436 if (!STATE.folderIconObserver)
4437 {
4438 STATE.folderIconObserver = new IntersectionObserver((entries) =>
4439 {
4440 for (const entry of entries)
4441 {
4442 if (!entry.isIntersecting) continue;
4443 const icon = entry.target;
4444 STATE.folderIconObserver.unobserve(icon);
4445 void loadOneFolderIcon(icon);
4446 }
4447 }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 });
4448 }
4449
4450 STATE.folderIconObserver.observe(iconEl);
4451}
4452
4453async function loadOneFolderIcon (iconEl)
4454{
4455 if (!iconEl.isConnected || !STATE.token) return;
4456 if (iconEl.dataset.thumbReady === '1') return;
4457
4458 const folderPath = iconEl.dataset.folderPath;
4459 if (!folderPath) return;
4460
4461 let res;
4462 try
4463 {
4464 res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, {
4465 headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() },
4466 });
4467 } catch { return; }
4468
4469 if (!res.ok || !iconEl.isConnected) return;
4470
4471 const data = await res.json();
4472 if (!data.icon) return; // No icon available — keep plain folder SVG.
4473
4474 // Fetch the thumbnail through the auth-gated endpoint.
4475 let thumbRes;
4476 try
4477 {
4478 thumbRes = await fetch(
4479 `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`,
4480 { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } },
4481 );
4482 } catch { return; }
4483
4484 if (!thumbRes.ok || !iconEl.isConnected) return;
4485
4486 const blob = await thumbRes.blob();
4487 const srcUrl = URL.createObjectURL(blob);
4488 STATE.thumbnailUrls.push(srcUrl);
4489
4490 applyFolderThumbnail(iconEl, srcUrl);
4491}
4492
4493/**
4494 * Overlays a thumbnail image inside the folder SVG outline.
4495 * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21.
4496 */
4497function applyFolderThumbnail (iconEl, srcUrl)
4498{
4499 if (!iconEl.isConnected) return;
4500 const svg = iconEl.querySelector('svg');
4501 if (!svg)
4502 {
4503 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
4504 return;
4505 }
4506
4507 const NS = 'http://www.w3.org/2000/svg';
4508 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
4509
4510 const defs = document.createElementNS(NS, 'defs');
4511 const clipPath = document.createElementNS(NS, 'clipPath');
4512 clipPath.setAttribute('id', id);
4513 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
4514 const clipShape = document.createElementNS(NS, 'path');
4515 // Folder outline path (same as iconFolder SVG path)
4516 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');
4517 clipPath.appendChild(clipShape);
4518 defs.appendChild(clipPath);
4519
4520 // Image covers the folder body area; clip keeps it inside the outline.
4521 const img = document.createElementNS(NS, 'image');
4522 img.setAttribute('href', srcUrl);
4523 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
4524 img.setAttribute('x', '2');
4525 img.setAttribute('y', '3');
4526 img.setAttribute('width', '20');
4527 img.setAttribute('height', '18');
4528 img.setAttribute('clip-path', `url(#${id})`);
4529 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
4530
4531 // Prepend so the folder outline strokes render on top.
4532 svg.prepend(img);
4533 svg.prepend(defs);
4534 iconEl.dataset.thumbReady = '1';
4535}
4536
4537function wireEvents ()
4538{
4539 // Auth form
4540 document.getElementById('auth-form').addEventListener('submit', async (e) =>
4541 {
4542 e.preventDefault();
4543 const username = document.getElementById('auth-username').value.trim();
4544 const password = document.getElementById('auth-password').value;
4545 const isSetup = e.target.dataset.mode === 'setup';
4546 const errEl = document.getElementById('auth-error');
4547 const btn = document.getElementById('auth-submit');
4548 btn.disabled = true;
4549 btn.textContent = 'Please wait…';
4550 const err = await doLogin(username, password, isSetup);
4551 if (err)
4552 {
4553 errEl.textContent = err;
4554 errEl.classList.remove('hidden');
4555 btn.disabled = false;
4556 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
4557 }
4558 });
4559
4560 // Logout
4561 document.getElementById('btn-logout').addEventListener('click', logout);
4562
4563 // Hard refresh while keeping auth/session state.
4564 document.getElementById('btn-refresh').addEventListener('click', () =>
4565 {
4566 saveSessionState();
4567 location.reload();
4568 });
4569
4570 // Upload button
4571 document.getElementById('btn-upload').addEventListener('click', () =>
4572 {
4573 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4574 if (!canWrite()) { toast('No write access.', 'err'); return; }
4575 document.getElementById('file-input').click();
4576 });
4577
4578 document.getElementById('file-input').addEventListener('change', async (e) =>
4579 {
4580 if (e.target.files.length) await uploadFiles(e.target.files);
4581 e.target.value = '';
4582 });
4583
4584 document.getElementById('btn-upload-folder').addEventListener('click', () =>
4585 {
4586 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4587 if (!canWrite()) { toast('No write access.', 'err'); return; }
4588 document.getElementById('folder-input').click();
4589 });
4590
4591 document.getElementById('folder-input').addEventListener('change', async (e) =>
4592 {
4593 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
4594 e.target.value = '';
4595 });
4596
4597 document.getElementById('btn-new-folder').addEventListener('click', async () =>
4598 {
4599 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
4600 if (!canWrite()) { toast('No write access.', 'err'); return; }
4601
4602 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
4603 if (name == null) return;
4604 const folderName = name.trim();
4605 if (!folderName)
4606 {
4607 toast('Folder name is required.', 'err');
4608 return;
4609 }
4610
4611 try
4612 {
4613 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
4614 toast('Folder created.', 'ok');
4615 await navigateTo(STATE.currentDir, STATE.currentRoot);
4616 } catch (err)
4617 {
4618 toast(err.message, 'err');
4619 }
4620 });
4621
4622 document.getElementById('sidebar-close').addEventListener('click', (e) =>
4623 {
4624 e.stopPropagation();
4625 hideSidebarPanel();
4626 });
4627
4628 const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY);
4629 const syncSidebarForViewport = () =>
4630 {
4631 if (isMobileViewport())
4632 {
4633 hideSidebarPanel();
4634 return;
4635 }
4636
4637 if (!STATE.selectedItem) openFolderSidebar();
4638 };
4639
4640 if (typeof mobileQuery.addEventListener === 'function')
4641 {
4642 mobileQuery.addEventListener('change', syncSidebarForViewport);
4643 } else if (typeof mobileQuery.addListener === 'function')
4644 {
4645 mobileQuery.addListener(syncSidebarForViewport);
4646 }
4647
4648 // Click outside grid clears selection and returns to folder sidebar info.
4649 document.getElementById('main-content').addEventListener('click', (e) =>
4650 {
4651 if (!e.target.closest('.file-item')) closeSidebar();
4652 });
4653
4654 // Admin panel
4655 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
4656 document.getElementById('admin-modal-close').addEventListener('click', () =>
4657 document.getElementById('admin-modal').classList.add('hidden'));
4658
4659 // Add path
4660 document.getElementById('admin-add-path').addEventListener('click', () =>
4661 {
4662 const val = document.getElementById('admin-new-path').value.trim();
4663 if (!val) return;
4664 const row = document.createElement('div');
4665 row.className = 'path-row';
4666 row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`;
4667 row.querySelector('button').addEventListener('click', () => row.remove());
4668 document.getElementById('admin-paths').appendChild(row);
4669 document.getElementById('admin-new-path').value = '';
4670 });
4671
4672 // Save paths
4673 document.getElementById('admin-save-paths').addEventListener('click', async () =>
4674 {
4675 const rows = document.querySelectorAll('#admin-paths .path-row span');
4676 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
4677 try
4678 {
4679 await api('PUT', '/admin/config', { paths });
4680 toast('Paths saved.', 'ok');
4681 await loadRoots();
4682 } catch (err) { toast(err.message, 'err'); }
4683 });
4684
4685 const sizeInput = document.getElementById('admin-user-size-limit');
4686 if (sizeInput)
4687 {
4688 sizeInput.addEventListener('input', () =>
4689 {
4690 updateAdminSizeFeedback(sizeInput.value);
4691 });
4692 }
4693
4694 document.getElementById('admin-save-userpath').addEventListener('click', async () =>
4695 {
4696 const rows = document.querySelectorAll('#admin-paths .path-row span');
4697 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
4698 const userPath = document.getElementById('admin-user-path').value.trim();
4699 const rawLimit = document.getElementById('admin-user-size-limit').value.trim();
4700 const parsed = updateAdminSizeFeedback(rawLimit);
4701 if (!parsed.valid)
4702 {
4703 toast('Please enter a valid user size limit.', 'err');
4704 return;
4705 }
4706
4707 try
4708 {
4709 await api('PUT', '/admin/config', {
4710 paths,
4711 userPath: userPath || null,
4712 userFolderSizeLimit: rawLimit ? parsed.bytes : null,
4713 });
4714 toast('User folder settings saved.', 'ok');
4715 await loadRoots();
4716 await refreshAdminConfig();
4717 }
4718 catch (err)
4719 {
4720 toast(err.message, 'err');
4721 }
4722 });
4723
4724 // Shutdown / restart server
4725 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4726 {
4727 const status = _adminUpdateStatus;
4728
4729 if (!status || !status.underSystemd)
4730 {
4731 // Not running under systemd — plain shutdown (manual restart required).
4732 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
4733 }
4734 else if (status.commitsAhead.length === 0)
4735 {
4736 // Under systemd, no updates — restart only.
4737 if (!await showConfirm('Restart server', 'No update available. Would you like to restart?', { okLabel: 'Restart' })) return;
4738 }
4739 else
4740 {
4741 // Under systemd, updates available.
4742 const commitList = status.commitsAhead.map(c => escHtml(c)).join('<br/>');
4743 const msg = `Updates available:<br/><br/>${commitList}<br/><br/>Update now?`;
4744 if (!await showConfirm('Restart &amp; Update', msg, { html: true, okLabel: 'Update now' })) return;
4745 }
4746
4747 try
4748 {
4749 await api('POST', '/admin/shutdown');
4750 const toastMsg = (!status || !status.underSystemd)
4751 ? 'Server is shutting down\u2026'
4752 : status.commitsAhead.length > 0
4753 ? 'Server is updating and restarting\u2026'
4754 : 'Server is restarting\u2026';
4755 toast(toastMsg, 'ok');
4756 document.getElementById('admin-modal').classList.add('hidden');
4757 } catch
4758 {
4759 // Fetch may throw because the connection closes before a response arrives.
4760 const toastMsg = (!status || !status.underSystemd)
4761 ? 'Server is shutting down\u2026'
4762 : status.commitsAhead.length > 0
4763 ? 'Server is updating and restarting\u2026'
4764 : 'Server is restarting\u2026';
4765 toast(toastMsg, 'ok');
4766 document.getElementById('admin-modal').classList.add('hidden');
4767 }
4768 setTimeout(() => location.reload(), 3000);
4769 });
4770
4771 // New user
4772 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
4773 {
4774 const cfg = await api('GET', '/admin/config');
4775 const paths = cfg ? (cfg.effectivePaths || []) : [];
4776 openUserModal(null, paths);
4777 });
4778
4779 // User modal close
4780 document.getElementById('user-modal-close').addEventListener('click', () =>
4781 document.getElementById('user-modal').classList.add('hidden'));
4782
4783 // Rename modal close
4784 document.getElementById('rename-modal-close').addEventListener('click', () =>
4785 document.getElementById('rename-modal').classList.add('hidden'));
4786
4787 // Close modals on backdrop click
4788 document.querySelectorAll('.modal-overlay').forEach(overlay =>
4789 {
4790 overlay.addEventListener('click', e =>
4791 {
4792 if (e.target === overlay) overlay.classList.add('hidden');
4793 });
4794 });
4795}
4796
4797// ───────────────────────────────────────────────────────────────────────────
4798// BOOT
4799// ───────────────────────────────────────────────────────────────────────────
4800
4801(async function boot ()
4802{
4803 wireEvents();
4804 initDragDrop();
4805 window.addEventListener('beforeunload', () =>
4806 {
4807 saveSessionState();
4808 releaseActivePreviewVideoStreamSession({ keepalive: true });
4809 });
4810 window.addEventListener('pagehide', () =>
4811 {
4812 releaseActivePreviewVideoStreamSession({ keepalive: true });
4813 });
4814 await initAuth();
4815})();