BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

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