BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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