BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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