BlueGit

timfa filemanager

Files

filemanager / public / app.js

app.js

app.js 80.2 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
47 // Preview overlay state
48 previewObjectUrl: null,
49};
50
51const SESSION_KEY = 'filemanager.session.v1';
52const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
53const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
54
55// ───────────────────────────────────────────────────────────────────────────
56// CRYPTO HELPERS (Web Crypto API)
57// ───────────────────────────────────────────────────────────────────────────
58
59async function generateClientKeyPair ()
60{
61 if (!hasWebCrypto()) return;
62 const kp = await crypto.subtle.generateKey(
63 { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
64 true,
65 ['encrypt', 'decrypt'],
66 );
67 STATE.clientPrivateKey = kp.privateKey;
68 STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey);
69}
70
71/**
72 * Hybrid-encrypt a JS object using the server's RSA public key.
73 * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.
74 */
75async function hybridEncryptForServer (obj)
76{
77 if (!hasWebCrypto() || !STATE.serverPublicKeyJwk)
78 {
79 return { plaintext: obj };
80 }
81
82 const serverPub = await crypto.subtle.importKey(
83 'jwk', STATE.serverPublicKeyJwk,
84 { name: 'RSA-OAEP', hash: 'SHA-256' },
85 false, ['encrypt'],
86 );
87
88 const plaintext = new TextEncoder().encode(JSON.stringify(obj));
89 const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
90 const iv = crypto.getRandomValues(new Uint8Array(12));
91 const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext);
92
93 // gcmResult = ciphertext || tag (last 16 bytes are auth tag)
94 const gcmBytes = new Uint8Array(gcmResult);
95 const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16);
96 const tag = gcmBytes.slice(gcmBytes.length - 16);
97
98 const rawAes = await crypto.subtle.exportKey('raw', aesKey);
99 const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes);
100
101 return {
102 encryptedKey: b64(encryptedKey),
103 iv: b64(iv),
104 ciphertext: b64(ciphertext),
105 tag: b64(tag),
106 };
107}
108
109/**
110 * Hybrid-decrypt a payload encrypted by the server for us (using our public key).
111 */
112async function hybridDecryptFromServer (payload)
113{
114 if (!payload) return null;
115 if (payload.token) return payload.token;
116 if (!hasWebCrypto()) return null;
117
118 const encryptedKey = unb64(payload.encryptedKey);
119 const iv = unb64(payload.iv);
120 const ciphertext = unb64(payload.ciphertext);
121 const tag = unb64(payload.tag);
122
123 const rawAes = await crypto.subtle.decrypt(
124 { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey,
125 );
126
127 const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']);
128
129 // Recombine ciphertext + tag for AES-GCM
130 const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength);
131 combined.set(new Uint8Array(ciphertext));
132 combined.set(new Uint8Array(tag), ciphertext.byteLength);
133
134 const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined);
135 return new TextDecoder().decode(plain);
136}
137
138// ───────────────────────────────────────────────────────────────────────────
139// UTIL
140// ───────────────────────────────────────────────────────────────────────────
141
142function b64 (buf)
143{
144 return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));
145}
146
147function hasWebCrypto ()
148{
149 return !!(window.crypto && window.crypto.subtle);
150}
151
152function unb64 (str)
153{
154 const binary = atob(str);
155 const buf = new Uint8Array(binary.length);
156 for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);
157 return buf.buffer;
158}
159
160/** Stable browser fingerprint (not stored, derived fresh each load) */
161function getFingerprint ()
162{
163 const binding = getOrCreateClientBindingId();
164 const nav = navigator;
165
166 // Keep this stable: avoid viewport/screen metrics that can change when
167 // devtools opens, orientation changes, or window state changes.
168 return [
169 binding,
170 nav.userAgent || '',
171 nav.language,
172 nav.platform || nav.userAgentData?.platform || '',
173 Intl.DateTimeFormat().resolvedOptions().timeZone,
174 ].join('|');
175}
176
177function randomIdHex (bytes = 16)
178{
179 const arr = new Uint8Array(bytes);
180 if (window.crypto && typeof window.crypto.getRandomValues === 'function')
181 {
182 window.crypto.getRandomValues(arr);
183 } else
184 {
185 for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);
186 }
187 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
188}
189
190function getOrCreateClientBindingId ()
191{
192 if (STATE.clientBindingId) return STATE.clientBindingId;
193
194 try
195 {
196 const existing = localStorage.getItem(CLIENT_BINDING_KEY);
197 if (existing && typeof existing === 'string')
198 {
199 STATE.clientBindingId = existing;
200 return existing;
201 }
202 } catch
203 {
204 // Ignore storage read errors.
205 }
206
207 const created = randomIdHex(16);
208 STATE.clientBindingId = created;
209
210 try
211 {
212 localStorage.setItem(CLIENT_BINDING_KEY, created);
213 } catch
214 {
215 // Ignore storage write errors; in-memory fallback still keeps this stable
216 // for the current page session.
217 }
218
219 return created;
220}
221
222function formatBytes (bytes)
223{
224 if (bytes == null) return '—';
225 if (bytes < 1024) return bytes + ' B';
226 if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
227 if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
228 return (bytes / 1073741824).toFixed(2) + ' GB';
229}
230
231function extOf (name)
232{
233 const i = name.lastIndexOf('.');
234 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
235}
236
237function getPathSep (basePath)
238{
239 return basePath && basePath.includes('\\') ? '\\' : '/';
240}
241
242function joinServerPath (basePath, segment)
243{
244 const sep = getPathSep(basePath);
245 const base = String(basePath || '').replace(/[\\/]+$/, '');
246 return base + sep + segment;
247}
248
249function samePath (a, b)
250{
251 if (!a || !b) return false;
252 return String(a).toLowerCase() === String(b).toLowerCase();
253}
254
255function pathInside (child, root)
256{
257 if (!child || !root) return false;
258 if (samePath(child, root)) return true;
259 const sep = getPathSep(root);
260 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
261}
262
263function saveSessionState ()
264{
265 if (!STATE.token) return;
266 const now = Date.now();
267 STATE.lastOperationAt = now;
268 const payload = {
269 token: STATE.token,
270 dir: STATE.currentDir || null,
271 rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,
272 lastOperationAt: STATE.lastOperationAt,
273 };
274 try
275 {
276 localStorage.setItem(SESSION_KEY, JSON.stringify(payload));
277 } catch
278 {
279 // Ignore storage errors (private mode/full quota).
280 }
281}
282
283function loadSessionState ()
284{
285 try
286 {
287 const raw = localStorage.getItem(SESSION_KEY);
288 if (!raw) return null;
289 const parsed = JSON.parse(raw);
290 if (!parsed || typeof parsed.token !== 'string') return null;
291 if (!Number.isFinite(parsed.lastOperationAt)) return null;
292
293 if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS)
294 {
295 clearSessionState();
296 return null;
297 }
298
299 return parsed;
300 } catch
301 {
302 return null;
303 }
304}
305
306function clearSessionState ()
307{
308 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
309}
310
311// ───────────────────────────────────────────────────────────────────────────
312// API
313// ───────────────────────────────────────────────────────────────────────────
314
315async function api (method, path, body, opts = {})
316{
317 const headers = { 'Content-Type': 'application/json' };
318 const noAutoLogout = !!opts.noAutoLogout;
319 if (STATE.token)
320 {
321 headers['Authorization'] = 'Bearer ' + STATE.token;
322 headers['X-Fp'] = getFingerprint();
323 }
324 const fetchOpts = { ...opts };
325 delete fetchOpts.noAutoLogout;
326 const res = await fetch('/api' + path, {
327 method,
328 headers,
329 body: body != null ? JSON.stringify(body) : undefined,
330 ...fetchOpts,
331 });
332 if (!res.ok)
333 {
334 const j = await res.json().catch(() => ({}));
335 // Session-expired → force re-login
336 if (res.status === 401)
337 {
338 if (!noAutoLogout) logout();
339 return null;
340 }
341 throw new Error(j.error || res.statusText);
342 }
343 if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed'))
344 {
345 saveSessionState();
346 }
347 return res.json();
348}
349
350// ───────────────────────────────────────────────────────────────────────────
351// TOAST
352// ───────────────────────────────────────────────────────────────────────────
353
354function toast (msg, type = '')
355{
356 const el = document.createElement('div');
357 el.className = 'toast-msg' + (type ? ' ' + type : '');
358 el.textContent = msg;
359 document.getElementById('toast').appendChild(el);
360 setTimeout(() => el.remove(), 3500);
361}
362
363// ───────────────────────────────────────────────────────────────────────────
364// DIALOG MODALS — centralised replacements for alert / confirm / prompt
365// ───────────────────────────────────────────────────────────────────────────
366
367/**
368 * Show a confirmation dialog.
369 * @param {string} title
370 * @param {string} message
371 * @returns {Promise<boolean>} true = OK, false = Cancel
372 */
373function showConfirm (title, message)
374{
375 return new Promise((resolve) =>
376 {
377 const overlay = document.getElementById('confirm-modal');
378 document.getElementById('confirm-modal-title').textContent = title;
379 document.getElementById('confirm-modal-message').textContent = message;
380 overlay.classList.remove('hidden');
381
382 const ok = document.getElementById('confirm-modal-ok');
383 const cancel = document.getElementById('confirm-modal-cancel');
384
385 function finish (result)
386 {
387 overlay.classList.add('hidden');
388 ok.removeEventListener('click', onOk);
389 cancel.removeEventListener('click', onCancel);
390 resolve(result);
391 }
392 function onOk () { finish(true); }
393 function onCancel () { finish(false); }
394
395 ok.addEventListener('click', onOk);
396 cancel.addEventListener('click', onCancel);
397 ok.focus();
398 });
399}
400
401/**
402 * Show a text-input dialog.
403 * @param {string} title
404 * @param {string} [message] — optional helper text shown above the input
405 * @param {string} [defaultValue] — pre-filled value
406 * @returns {Promise<string|null>} string = submitted value, null = cancelled
407 */
408function showPrompt (title, message = '', defaultValue = '')
409{
410 return new Promise((resolve) =>
411 {
412 const overlay = document.getElementById('prompt-modal');
413 const msgEl = document.getElementById('prompt-modal-message');
414 const input = document.getElementById('prompt-modal-input');
415 const errorEl = document.getElementById('prompt-modal-error');
416 const form = document.getElementById('prompt-modal-form');
417 const cancel = document.getElementById('prompt-modal-cancel');
418
419 document.getElementById('prompt-modal-title').textContent = title;
420 msgEl.textContent = message;
421 msgEl.classList.toggle('hidden', !message);
422 input.value = defaultValue;
423 errorEl.classList.add('hidden');
424 overlay.classList.remove('hidden');
425 input.focus();
426 input.select();
427
428 function finish (result)
429 {
430 overlay.classList.add('hidden');
431 form.removeEventListener('submit', onSubmit);
432 cancel.removeEventListener('click', onCancel);
433 resolve(result);
434 }
435 function onSubmit (e)
436 {
437 e.preventDefault();
438 finish(input.value);
439 }
440 function onCancel () { finish(null); }
441
442 form.addEventListener('submit', onSubmit);
443 cancel.addEventListener('click', onCancel);
444 });
445}
446
447/**
448 * Show an overwrite-decision dialog for a single file conflict.
449 * @param {string} filename
450 * @returns {Promise<'yes'|'no'|'all'|'none'>}
451 */
452function showOverwrite (filename)
453{
454 return new Promise((resolve) =>
455 {
456 const overlay = document.getElementById('overwrite-modal');
457 document.getElementById('overwrite-modal-filename').textContent = filename;
458 overlay.classList.remove('hidden');
459
460 const btnYes = document.getElementById('overwrite-modal-yes');
461 const btnNo = document.getElementById('overwrite-modal-no');
462 const btnAll = document.getElementById('overwrite-modal-all');
463 const btnSkipAll = document.getElementById('overwrite-modal-skip-all');
464
465 function finish (result)
466 {
467 overlay.classList.add('hidden');
468 btnYes.removeEventListener('click', onYes);
469 btnNo.removeEventListener('click', onNo);
470 btnAll.removeEventListener('click', onAll);
471 btnSkipAll.removeEventListener('click', onSkipAll);
472 resolve(result);
473 }
474 function onYes () { finish('yes'); }
475 function onNo () { finish('no'); }
476 function onAll () { finish('all'); }
477 function onSkipAll () { finish('none'); }
478
479 btnYes.addEventListener('click', onYes);
480 btnNo.addEventListener('click', onNo);
481 btnAll.addEventListener('click', onAll);
482 btnSkipAll.addEventListener('click', onSkipAll);
483 btnNo.focus();
484 });
485}
486
487// ───────────────────────────────────────────────────────────────────────────
488// AUTH FLOW
489// ───────────────────────────────────────────────────────────────────────────
490
491function showAuthOverlay (setupMode = false)
492{
493 document.getElementById('app').classList.add('hidden');
494 const overlay = document.getElementById('auth-overlay');
495 overlay.classList.remove('hidden');
496 document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';
497 document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);
498 const submitBtn = document.getElementById('auth-submit');
499 submitBtn.disabled = false;
500 submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';
501 document.getElementById('auth-error').classList.add('hidden');
502 document.getElementById('auth-username').value = '';
503 document.getElementById('auth-password').value = '';
504 document.getElementById('auth-username').focus();
505 document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';
506}
507
508function showApp ()
509{
510 document.getElementById('auth-overlay').classList.add('hidden');
511 document.getElementById('app').classList.remove('hidden');
512 document.getElementById('app').classList.add('sidebar-open');
513 document.getElementById('sidebar').classList.remove('hidden');
514 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
515 startAutoRefresh();
516}
517
518async function initAuth ()
519{
520 // Always generate a fresh key pair so each page-load session is independent
521 await generateClientKeyPair().catch(() =>
522 {
523 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
524 });
525
526 // Fetch server public key
527 const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null }));
528 if (publicKey) STATE.serverPublicKeyJwk = publicKey;
529 if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; }
530 STATE.serverPublicKeyJwk = publicKey;
531
532 // Check whether first-run setup is needed
533 const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));
534
535 if (!needed)
536 {
537 const saved = loadSessionState();
538 if (saved && saved.token)
539 {
540 STATE.token = saved.token;
541 STATE.restoreDir = saved.dir || null;
542 STATE.restoreRootPath = saved.rootPath || null;
543 STATE.lastOperationAt = saved.lastOperationAt;
544
545 const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);
546 if (me)
547 {
548 STATE.username = me.username;
549 STATE.isAdmin = me.isAdmin;
550 STATE.permissions = me.permissions;
551 showApp();
552 await loadRoots({
553 preferredDir: STATE.restoreDir,
554 preferredRootPath: STATE.restoreRootPath,
555 });
556 return;
557 }
558
559 STATE.token = null;
560 clearSessionState();
561 }
562 }
563
564 showAuthOverlay(needed);
565}
566
567async function doLogin (username, password, isSetup)
568{
569 const encrypted = await hybridEncryptForServer({ username, password });
570 const endpoint = isSetup ? '/auth/setup' : '/auth/login';
571
572 let data;
573 try
574 {
575 data = await api('POST', endpoint, {
576 encrypted,
577 clientPublicKey: STATE.clientPublicKeyJwk,
578 fingerprint: getFingerprint(),
579 });
580 } catch (err)
581 {
582 return err.message;
583 }
584
585 if (!data) return 'Login failed.';
586
587 // Decrypt the token sent back by the server
588 const token = await hybridDecryptFromServer(data.encrypted || data);
589 if (!token) return 'Login failed.';
590 STATE.token = token;
591
592 // Load user info
593 const me = await api('GET', '/auth/me');
594 if (!me) return 'Session error.';
595
596 STATE.username = me.username;
597 STATE.isAdmin = me.isAdmin;
598 STATE.permissions = me.permissions;
599
600 saveSessionState();
601 showApp();
602 await loadRoots();
603 return null; // no error
604}
605
606function logout ()
607{
608 void performLogout();
609}
610
611async function performLogout ()
612{
613 const tokenAtStart = STATE.token;
614 stopAutoRefresh();
615
616 if (tokenAtStart)
617 {
618 try
619 {
620 await api('POST', '/auth/logout', {}, { noAutoLogout: true });
621 } catch
622 {
623 // Ignore network errors while logging out locally.
624 }
625 }
626
627 STATE.token = null;
628 STATE.username = null;
629 STATE.isAdmin = false;
630 STATE.permissions = {};
631 STATE.currentDir = null;
632 STATE.currentRoot = null;
633 STATE.items = [];
634 STATE.restoreDir = null;
635 STATE.restoreRootPath = null;
636 STATE.lastOperationAt = null;
637 clearSessionState();
638 closePreview();
639 closeSidebar();
640 await initAuth();
641}
642
643// ───────────────────────────────────────────────────────────────────────────
644// NAVIGATION
645// ───────────────────────────────────────────────────────────────────────────
646
647async function loadRoots (opts = {})
648{
649 const data = await api('GET', '/files/roots');
650 if (!data) return;
651 STATE.roots = data.roots;
652
653 const preferredDir = opts.preferredDir || null;
654 const preferredRootPath = opts.preferredRootPath || null;
655
656 if (preferredDir && preferredRootPath)
657 {
658 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
659 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
660 {
661 try
662 {
663 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
664 return;
665 } catch
666 {
667 // Fall back to default root behavior.
668 }
669 }
670 }
671
672 if (STATE.roots.length === 1)
673 {
674 // Single root → open it directly
675 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
676 } else
677 {
678 renderRootsView();
679 }
680}
681
682function renderRootsView ()
683{
684 STATE.currentDir = null;
685 STATE.currentRoot = null;
686 saveSessionState();
687 renderBreadcrumb();
688 const grid = document.getElementById('file-grid');
689 grid.innerHTML = '';
690 document.getElementById('empty-notice').classList.add('hidden');
691 document.getElementById('folder-stats').classList.add('hidden');
692 closeSidebar();
693
694 for (const root of STATE.roots)
695 {
696 const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root });
697 grid.appendChild(el);
698 }
699}
700
701async function navigateTo (absPath, root, opts = {})
702{
703 if (root) STATE.currentRoot = root;
704 STATE.currentDir = absPath;
705
706 const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`);
707 if (!data) return;
708
709 STATE.items = data.items;
710 saveSessionState();
711 renderBreadcrumb();
712 renderFileGrid();
713 await refreshFolderStats();
714 closeSidebar();
715}
716
717function renderBreadcrumb ()
718{
719 const nav = document.getElementById('breadcrumb');
720 nav.innerHTML = '';
721
722 // "Home" crumb
723 const home = document.createElement('span');
724 home.className = 'crumb' + (STATE.currentDir == null ? ' active' : '');
725 home.textContent = 'Home';
726 home.addEventListener('click', () =>
727 {
728 if (STATE.roots.length === 1)
729 {
730 navigateTo(STATE.roots[0].path, STATE.roots[0]);
731 } else
732 {
733 renderRootsView();
734 }
735 });
736 nav.appendChild(home);
737
738 if (!STATE.currentDir || !STATE.currentRoot) return;
739
740 // Build path segments relative to the root
741 const rootPath = STATE.currentRoot.path;
742 const relative = STATE.currentDir === rootPath
743 ? ''
744 : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, '');
745
746 const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)];
747 let accumulated = rootPath;
748
749 for (let i = 0; i < parts.length; i++)
750 {
751 const sep = document.createElement('span');
752 sep.className = 'sep';
753 sep.textContent = ' / ';
754 nav.appendChild(sep);
755
756 const crumb = document.createElement('span');
757 crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : '');
758 crumb.textContent = parts[i];
759
760 // Capture the path for this crumb
761 const capturedPath = i === 0 ? rootPath : accumulated;
762 if (i < parts.length - 1)
763 {
764 crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot));
765 }
766
767 nav.appendChild(crumb);
768
769 // Advance accumulated path (skip for root label)
770 if (i > 0) accumulated = accumulated + '/' + parts[i];
771 else if (i === 0 && parts.length > 1)
772 {
773 // After root label, next crumb should append the next segment
774 accumulated = rootPath;
775 }
776 }
777}
778
779async function refreshFolderStats ()
780{
781 const el = document.getElementById('folder-stats');
782 if (!STATE.currentDir)
783 {
784 el.classList.add('hidden');
785 return;
786 }
787
788 const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
789 if (!data)
790 {
791 el.classList.add('hidden');
792 return;
793 }
794
795 const used = formatBytes(data.usedBytes);
796 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
797 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
798 el.classList.remove('hidden');
799}
800
801function itemsSignature (items)
802{
803 return JSON.stringify(
804 (items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
805 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
806 );
807}
808
809async function incrementalRefreshCurrentDir ()
810{
811 if (!STATE.currentDir || STATE.uploadInProgress) return;
812 closeSidebar();
813 if (!data) return;
814
815 const oldSig = itemsSignature(STATE.items);
816 const newSig = itemsSignature(data.items);
817 if (oldSig !== newSig)
818 {
819 const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;
820 STATE.items = data.items;
821 renderFileGrid();
822
823 if (selectedPath)
824 {
825 const match = STATE.items.find(i => i.path === selectedPath);
826 if (match)
827 {
828 const selectedEl = Array.from(document.querySelectorAll('.file-item'))
829 .find(el => el.dataset.path === selectedPath);
830 if (selectedEl) selectItem(selectedEl, match);
831 } else
832 {
833 closeSidebar();
834 }
835 }
836 }
837
838 await refreshFolderStats();
839}
840
841function startAutoRefresh ()
842{
843 stopAutoRefresh();
844 STATE.autoRefreshTimer = setInterval(() =>
845 {
846 if (document.hidden) return;
847 incrementalRefreshCurrentDir();
848 }, 5000);
849}
850
851function stopAutoRefresh ()
852{
853 if (STATE.autoRefreshTimer)
854 {
855 clearInterval(STATE.autoRefreshTimer);
856 STATE.autoRefreshTimer = null;
857 }
858}
859
860// ───────────────────────────────────────────────────────────────────────────
861// FILE GRID RENDERING
862// ───────────────────────────────────────────────────────────────────────────
863
864function renderFileGrid ()
865{
866 revokeThumbnails();
867 const grid = document.getElementById('file-grid');
868 grid.innerHTML = '';
869 const empty = document.getElementById('empty-notice');
870
871 const sorted = [...STATE.items].sort((a, b) =>
872 {
873 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
874 return a.name.localeCompare(b.name);
875 });
876
877 empty.classList.toggle('hidden', sorted.length > 0);
878
879 for (const item of sorted)
880 {
881 grid.appendChild(makeFileItem(item));
882 }
883
884 loadThumbnails();
885}
886
887function makeFileItem (item)
888{
889 const el = document.createElement('div');
890 el.className = 'file-item';
891 el.dataset.path = item.path;
892
893 const icon = document.createElement('div');
894 icon.className = 'icon';
895 icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name);
896 if (!item.isDir)
897 {
898 icon.dataset.previewPath = item.path;
899 }
900 el.appendChild(icon);
901
902 const name = document.createElement('div');
903 name.className = 'name';
904 name.textContent = item.name;
905 el.appendChild(name);
906
907 // Single-click: open sidebar
908 el.addEventListener('click', (e) =>
909 {
910 e.stopPropagation();
911 if (item._root)
912 {
913 // Clicking a root tile goes straight in
914 navigateTo(item.path, item._root);
915 return;
916 }
917 selectItem(el, item);
918 });
919
920 // Double-click: enter folder or view/download file
921 el.addEventListener('dblclick', (e) =>
922 {
923 e.stopPropagation();
924 if (item.isDir)
925 {
926 navigateTo(item.path, STATE.currentRoot);
927 } else
928 {
929 downloadOrView(item, icon.querySelector('svg'));
930 }
931 });
932
933 return el;
934}
935
936function selectItem (el, item)
937{
938 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
939 el.classList.add('selected');
940 STATE.selectedItem = item;
941 openSidebar(item);
942}
943
944// ───────────────────────────────────────────────────────────────────────────
945// SIDEBAR
946// ───────────────────────────────────────────────────────────────────────────
947
948async function openSidebar (item)
949{
950 const sidebar = document.getElementById('sidebar');
951 sidebar.classList.remove('hidden');
952 document.getElementById('app').classList.add('sidebar-open');
953
954 document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64);
955 document.getElementById('sidebar-name').textContent = item.name;
956
957 // Load metadata
958 const dl = document.getElementById('sidebar-meta');
959 dl.innerHTML = '<dt>Loading…</dt><dd></dd>';
960
961 const actions = document.getElementById('sidebar-actions');
962 actions.innerHTML = '';
963
964 if (!item.isDir)
965 {
966 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
967 if (meta)
968 {
969 dl.innerHTML = `
970 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
971 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
972 <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd>
973 <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd>
974 `;
975 }
976
977 // View / download button
978 const btnDl = document.createElement('button');
979 btnDl.textContent = 'View / Download';
980 btnDl.addEventListener('click', () =>
981 {
982 const tile = Array.from(document.querySelectorAll('.file-item')).find(node => node.dataset.path === item.path);
983 const source = (tile ? tile.querySelector('.icon svg') : null) || document.querySelector('#sidebar-icon svg');
984 downloadOrView(item, source);
985 });
986 actions.appendChild(btnDl);
987 } else
988 {
989 dl.innerHTML = `<dt>Type</dt><dd>Folder</dd>`;
990 const btnOpen = document.createElement('button');
991 btnOpen.textContent = 'Open folder';
992 btnOpen.addEventListener('click', () => navigateTo(item.path, STATE.currentRoot));
993 actions.appendChild(btnOpen);
994 }
995
996 // Rename button (write access required)
997 if (canWrite())
998 {
999 const btnRen = document.createElement('button');
1000 btnRen.textContent = 'Rename';
1001 btnRen.addEventListener('click', () => openRenameModal(item));
1002 actions.appendChild(btnRen);
1003
1004 const btnDel = document.createElement('button');
1005 btnDel.textContent = 'Delete';
1006 btnDel.className = 'danger';
1007 btnDel.addEventListener('click', () => deleteItem(item));
1008 actions.appendChild(btnDel);
1009 }
1010}
1011
1012function openFolderSidebar ()
1013{
1014 const sidebar = document.getElementById('sidebar');
1015 sidebar.classList.remove('hidden');
1016 document.getElementById('app').classList.add('sidebar-open');
1017
1018 document.getElementById('sidebar-icon').innerHTML = iconFolder(64);
1019
1020 const nameEl = document.getElementById('sidebar-name');
1021 const dl = document.getElementById('sidebar-meta');
1022 const actions = document.getElementById('sidebar-actions');
1023 actions.innerHTML = '';
1024
1025 if (!STATE.currentDir || !STATE.currentRoot)
1026 {
1027 nameEl.textContent = 'Storage Roots';
1028 dl.innerHTML = `
1029 <dt>Type</dt><dd>Root overview</dd>
1030 <dt>Roots</dt><dd>${STATE.roots.length}</dd>
1031 `;
1032 return;
1033 }
1034
1035 const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean);
1036 const fallback = STATE.currentRoot.label || 'Folder';
1037 nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback;
1038
1039 const dirs = STATE.items.filter(i => i.isDir).length;
1040 const files = STATE.items.length - dirs;
1041 dl.innerHTML = `
1042 <dt>Path</dt><dd>${STATE.currentDir}</dd>
1043 <dt>Folders</dt><dd>${dirs}</dd>
1044 <dt>Files</dt><dd>${files}</dd>
1045 `;
1046}
1047
1048function closeSidebar ()
1049{
1050 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
1051 STATE.selectedItem = null;
1052 openFolderSidebar();
1053}
1054
1055// ───────────────────────────────────────────────────────────────────────────
1056// DOWNLOAD / VIEW
1057// ───────────────────────────────────────────────────────────────────────────
1058
1059function isInlinePreviewableBlob (blob, name)
1060{
1061 const mime = String(blob.type || '').toLowerCase();
1062 if (/^(image|video|audio)\//.test(mime)) return true;
1063 if (/^text\//.test(mime)) return true;
1064 if (mime === 'application/pdf') return true;
1065 if (mime === 'application/json') return true;
1066 if (mime === 'application/xml') return true;
1067 if (mime === 'application/javascript') return true;
1068
1069 // Fallback by extension when MIME is missing or generic.
1070 const ext = extOf(name || '');
1071 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true;
1072 if (CODE_EXTS.has(ext)) return true;
1073 return false;
1074}
1075
1076function isTextLikeBlob (blob, name)
1077{
1078 const mime = String(blob.type || '').toLowerCase();
1079 if (/^text\//.test(mime)) return true;
1080 if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true;
1081 const ext = extOf(name || '');
1082 return CODE_EXTS.has(ext);
1083}
1084
1085function detectCodeLanguage (name, mime)
1086{
1087 const ext = extOf(name || '');
1088 const m = String(mime || '').toLowerCase();
1089 if (m.includes('json') || ext === 'json') return 'json';
1090 if (m.includes('xml') || ext === 'xml') return 'xml';
1091 if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html';
1092 if (m.includes('css') || ext === 'css') return 'css';
1093 if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js';
1094 if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts';
1095 if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh';
1096 if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain';
1097 return CODE_EXTS.has(ext) ? 'js' : 'plain';
1098}
1099
1100function prettyPrintMarkup (raw)
1101{
1102 const src = String(raw || '')
1103 .replace(/>\s+</g, '><')
1104 .replace(/\r\n/g, '\n');
1105
1106 const lines = src.replace(/></g, '>\n<').split('\n');
1107 let indent = 0;
1108 const out = [];
1109
1110 for (const ln of lines)
1111 {
1112 const line = ln.trim();
1113 if (!line) continue;
1114 const isClose = /^<\//.test(line);
1115 const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line);
1116 const isOpen = /^<[^!?/][^>]*>$/.test(line);
1117
1118 if (isClose) indent = Math.max(0, indent - 1);
1119 out.push(' '.repeat(indent) + line);
1120 if (isOpen && !isSelf) indent += 1;
1121 }
1122
1123 return out.join('\n');
1124}
1125
1126function prettyPrintBraces (raw)
1127{
1128 const lines = String(raw || '')
1129 .replace(/\r\n/g, '\n')
1130 .split('\n');
1131 let indent = 0;
1132 const out = [];
1133
1134 for (const ln of lines)
1135 {
1136 const line = ln.trim();
1137 if (!line)
1138 {
1139 out.push('');
1140 continue;
1141 }
1142 if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1);
1143 out.push(' '.repeat(indent) + line);
1144 if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1;
1145 }
1146 return out.join('\n');
1147}
1148
1149function prettyPrintCode (raw, lang)
1150{
1151 const text = String(raw || '').replace(/\r\n/g, '\n');
1152 if (lang === 'json')
1153 {
1154 try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; }
1155 }
1156 if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text);
1157 if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text);
1158 return text;
1159}
1160
1161function escapeHtml (s)
1162{
1163 return String(s)
1164 .replace(/&/g, '&amp;')
1165 .replace(/</g, '&lt;')
1166 .replace(/>/g, '&gt;');
1167}
1168
1169function highlightCode (raw, lang)
1170{
1171 if (lang === 'plain') return escapeHtml(raw);
1172
1173 let html = escapeHtml(raw);
1174 const stash = [];
1175 const keep = (regex, cls) =>
1176 {
1177 html = html.replace(regex, (m) =>
1178 {
1179 const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1;
1180 return `@@TOK${idx}@@`;
1181 });
1182 };
1183
1184 if (lang === 'json')
1185 {
1186 html = html
1187 .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:')
1188 .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>')
1189 .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>')
1190 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
1191 return html;
1192 }
1193
1194 if (lang === 'xml' || lang === 'html')
1195 {
1196 html = html
1197 .replace(/(&lt;\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>')
1198 .replace(/([a-zA-Z0-9:_-]+)=(&quot;[^&]*&quot;|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>');
1199 return html;
1200 }
1201
1202 if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment');
1203 else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment');
1204 keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string');
1205
1206 html = html
1207 .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>')
1208 .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>');
1209
1210 html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || '');
1211 return html;
1212}
1213
1214function clearPreviewObjectUrl ()
1215{
1216 if (!STATE.previewObjectUrl) return;
1217 URL.revokeObjectURL(STATE.previewObjectUrl);
1218 STATE.previewObjectUrl = null;
1219}
1220
1221function fileAccentColor (name)
1222{
1223 const ext = extOf(name || '');
1224 if (IMAGE_EXTS.has(ext)) return '#3fcf8e';
1225 if (VIDEO_EXTS.has(ext)) return '#e05c6e';
1226 if (AUDIO_EXTS.has(ext)) return '#c084fc';
1227 if (DOC_EXTS.has(ext)) return '#f97316';
1228 if (CODE_EXTS.has(ext)) return '#38bdf8';
1229 if (ARCHIVE_EXTS.has(ext)) return '#facc15';
1230 return '#7880a0';
1231}
1232
1233function animatePreviewOpen (sourceSvgEl, sheetEl)
1234{
1235 if (!sourceSvgEl || !sheetEl || !sourceSvgEl.isConnected) return Promise.resolve();
1236
1237 const start = sourceSvgEl.getBoundingClientRect();
1238 const end = sheetEl.getBoundingClientRect();
1239 if (!start.width || !start.height || !end.width || !end.height) return Promise.resolve();
1240
1241 const ghost = document.createElement('div');
1242 ghost.className = 'preview-ghost';
1243 ghost.style.left = `${start.left}px`;
1244 ghost.style.top = `${start.top}px`;
1245 ghost.style.width = `${start.width}px`;
1246 ghost.style.height = `${start.height}px`;
1247
1248 const clone = sourceSvgEl.cloneNode(true);
1249 clone.style.width = '100%';
1250 clone.style.height = '100%';
1251 clone.style.display = 'block';
1252 ghost.appendChild(clone);
1253 document.body.appendChild(ghost);
1254
1255 return new Promise((resolve) =>
1256 {
1257 const anim = ghost.animate([
1258 {
1259 left: `${start.left}px`,
1260 top: `${start.top}px`,
1261 width: `${start.width}px`,
1262 height: `${start.height}px`,
1263 opacity: 1,
1264 borderRadius: '8px',
1265 },
1266 {
1267 left: `${end.left}px`,
1268 top: `${end.top}px`,
1269 width: `${end.width}px`,
1270 height: `${end.height}px`,
1271 opacity: 0.18,
1272 borderRadius: '12px',
1273 },
1274 ], {
1275 duration: 260,
1276 easing: 'cubic-bezier(0.2, 0.9, 0.2, 1)',
1277 fill: 'forwards',
1278 });
1279
1280 anim.onfinish = () =>
1281 {
1282 ghost.remove();
1283 resolve();
1284 };
1285 anim.oncancel = () =>
1286 {
1287 ghost.remove();
1288 resolve();
1289 };
1290 });
1291}
1292
1293function closePreview ()
1294{
1295 const overlay = document.getElementById('preview-overlay');
1296 const body = document.getElementById('preview-body');
1297 if (!overlay || !body) return;
1298 overlay.classList.add('hidden');
1299 body.innerHTML = '';
1300 clearPreviewObjectUrl();
1301}
1302
1303async function fetchFileBlob (item)
1304{
1305 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
1306 try
1307 {
1308 const res = await fetch(url, {
1309 headers: {
1310 Authorization: 'Bearer ' + STATE.token,
1311 'X-Fp': getFingerprint(),
1312 },
1313 });
1314 if (!res.ok) throw new Error('Download failed.');
1315 return await res.blob();
1316 } catch
1317 {
1318 return null;
1319 }
1320}
1321
1322function triggerDownload (filename, objectUrl)
1323{
1324 const a = document.createElement('a');
1325 a.href = objectUrl;
1326 a.download = filename;
1327 a.click();
1328}
1329
1330async function renderPreviewBody (item, blob, objectUrl)
1331{
1332 const body = document.getElementById('preview-body');
1333 body.innerHTML = '';
1334
1335 const mime = String(blob.type || '').toLowerCase();
1336 const previewable = isInlinePreviewableBlob(blob, item.name);
1337
1338 if (!previewable)
1339 {
1340 const msg = document.createElement('p');
1341 msg.className = 'preview-unsupported';
1342 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
1343 body.appendChild(msg);
1344 return;
1345 }
1346
1347 if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name)))
1348 {
1349 const img = document.createElement('img');
1350 img.className = 'preview-media';
1351 img.src = objectUrl;
1352 img.alt = item.name;
1353 body.appendChild(img);
1354 return;
1355 }
1356
1357 if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name)))
1358 {
1359 const video = document.createElement('video');
1360 video.className = 'preview-media';
1361 video.src = objectUrl;
1362 video.controls = true;
1363 video.preload = 'metadata';
1364 body.appendChild(video);
1365 return;
1366 }
1367
1368 if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name)))
1369 {
1370 const audio = document.createElement('audio');
1371 audio.className = 'preview-audio';
1372 audio.src = objectUrl;
1373 audio.controls = true;
1374 body.appendChild(audio);
1375 return;
1376 }
1377
1378 if (mime === 'application/pdf')
1379 {
1380 const frame = document.createElement('iframe');
1381 frame.className = 'preview-frame';
1382 frame.src = objectUrl;
1383 frame.title = item.name;
1384 body.appendChild(frame);
1385 return;
1386 }
1387
1388 if (isTextLikeBlob(blob, item.name))
1389 {
1390 const text = await blob.text();
1391 const lang = detectCodeLanguage(item.name, mime);
1392 const formatted = prettyPrintCode(text, lang);
1393 const pre = document.createElement('pre');
1394 pre.className = 'preview-text preview-code';
1395 pre.innerHTML = highlightCode(formatted, lang);
1396 body.appendChild(pre);
1397 return;
1398 }
1399
1400 const msg = document.createElement('p');
1401 msg.className = 'preview-unsupported';
1402 msg.textContent = 'This file cannot be previewed, but you can download it with the button below.';
1403 body.appendChild(msg);
1404}
1405
1406async function downloadOrView (item, sourceSvgEl = null)
1407{
1408 const blob = await fetchFileBlob(item);
1409 if (!blob)
1410 {
1411 toast('Download failed.', 'err');
1412 return;
1413 }
1414
1415 clearPreviewObjectUrl();
1416 const objectUrl = URL.createObjectURL(blob);
1417 STATE.previewObjectUrl = objectUrl;
1418
1419 const overlay = document.getElementById('preview-overlay');
1420 const sheet = document.getElementById('preview-sheet');
1421 const title = document.getElementById('preview-title');
1422 const dlBtn = document.getElementById('preview-download');
1423
1424 sheet.style.setProperty('--preview-accent', fileAccentColor(item.name));
1425 title.textContent = item.name;
1426 dlBtn.onclick = () => triggerDownload(item.name, objectUrl);
1427 await renderPreviewBody(item, blob, objectUrl);
1428
1429 overlay.classList.add('preview-prep');
1430 overlay.classList.remove('hidden');
1431 await animatePreviewOpen(sourceSvgEl, sheet);
1432 overlay.classList.remove('preview-prep');
1433}
1434
1435// ───────────────────────────────────────────────────────────────────────────
1436// UPLOAD
1437// ───────────────────────────────────────────────────────────────────────────
1438
1439function canWrite ()
1440{
1441 if (STATE.isAdmin) return true;
1442 if (!STATE.currentRoot) return false;
1443 const p = STATE.permissions[STATE.currentRoot.label];
1444 return p && p.write;
1445}
1446
1447async function uploadFiles (fileList)
1448{
1449 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1450 if (!canWrite()) { toast('No write access.', 'err'); return; }
1451
1452 const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
1453 const formData = new FormData();
1454 for (const f of fileList) formData.append('files', f);
1455
1456 // Show upload bar
1457 const wrap = document.createElement('div');
1458 wrap.className = 'upload-bar-wrap';
1459 wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
1460 document.body.appendChild(wrap);
1461 STATE.uploadInProgress = true;
1462
1463 try
1464 {
1465 const xhr = new XMLHttpRequest();
1466 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
1467 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
1468 xhr.setRequestHeader('X-Fp', getFingerprint());
1469 xhr.setRequestHeader('X-Upload-Size', String(totalSize));
1470 xhr.upload.addEventListener('progress', e =>
1471 {
1472 if (e.lengthComputable)
1473 {
1474 wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%';
1475 }
1476 });
1477
1478 await new Promise((resolve, reject) =>
1479 {
1480 xhr.onload = () =>
1481 {
1482 if (xhr.status === 200) resolve();
1483 else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
1484 };
1485 xhr.onerror = () => reject(new Error('Network error'));
1486 xhr.send(formData);
1487 });
1488
1489 toast(`Uploaded ${fileList.length} file(s).`, 'ok');
1490 await navigateTo(STATE.currentDir, STATE.currentRoot);
1491 } catch (err)
1492 {
1493 toast(err.message, 'err');
1494 } finally
1495 {
1496 STATE.uploadInProgress = false;
1497 wrap.remove();
1498 }
1499}
1500
1501async function uploadSingleFile (file, targetDir)
1502{
1503 const formData = new FormData();
1504 formData.append('files', file);
1505
1506 await new Promise((resolve, reject) =>
1507 {
1508 const xhr = new XMLHttpRequest();
1509 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
1510 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
1511 xhr.setRequestHeader('X-Fp', getFingerprint());
1512 xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
1513 xhr.onload = () => xhr.status === 200
1514 ? resolve()
1515 : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
1516 xhr.onerror = () => reject(new Error('Network error'));
1517 xhr.send(formData);
1518 });
1519}
1520
1521async function ensureServerDir (baseDir, relativeDir)
1522{
1523 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
1524 let current = baseDir;
1525 for (const part of parts)
1526 {
1527 try
1528 {
1529 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
1530 current = resp && resp.path ? resp.path : joinServerPath(current, part);
1531 } catch (err)
1532 {
1533 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1534 current = joinServerPath(current, part);
1535 }
1536 }
1537 return current;
1538}
1539
1540async function uploadFolderInputFiles (fileList)
1541{
1542 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1543 if (!canWrite()) { toast('No write access.', 'err'); return; }
1544 if (!fileList || !fileList.length) return;
1545
1546 const files = Array.from(fileList);
1547 const total = files.length;
1548 let done = 0;
1549
1550 const wrap = document.createElement('div');
1551 wrap.className = 'upload-bar-wrap';
1552 wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
1553 document.body.appendChild(wrap);
1554 STATE.uploadInProgress = true;
1555
1556 try
1557 {
1558 const dirCache = new Map();
1559 dirCache.set('', STATE.currentDir);
1560
1561 for (const file of files)
1562 {
1563 const rel = file.webkitRelativePath || file.name;
1564 const relParts = rel.split(/[\\/]/).filter(Boolean);
1565 const relDir = relParts.slice(0, -1).join('/');
1566
1567 if (!dirCache.has(relDir))
1568 {
1569 const parentRel = relParts.slice(0, -2).join('/');
1570 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
1571 const thisName = relParts[relParts.length - 2];
1572
1573 try
1574 {
1575 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
1576 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
1577 } catch (err)
1578 {
1579 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1580 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
1581 }
1582 }
1583
1584 const targetDir = dirCache.get(relDir) || STATE.currentDir;
1585 await uploadSingleFile(file, targetDir);
1586 done++;
1587 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
1588 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
1589 }
1590
1591 toast(`Uploaded ${total} file(s).`, 'ok');
1592 await navigateTo(STATE.currentDir, STATE.currentRoot);
1593 } catch (err)
1594 {
1595 toast(err.message, 'err');
1596 } finally
1597 {
1598 STATE.uploadInProgress = false;
1599 wrap.remove();
1600 }
1601}
1602
1603// ───────────────────────────────────────────────────────────────────────────
1604// FOLDER DRAG-AND-DROP (recursive)
1605// ───────────────────────────────────────────────────────────────────────────
1606
1607/**
1608 * Reads all readEntries batches from a DirectoryReader (browsers may return
1609 * results in chunks; we must keep calling until we get an empty array).
1610 */
1611function readAllEntries (reader)
1612{
1613 return new Promise((resolve, reject) =>
1614 {
1615 const all = [];
1616 function next ()
1617 {
1618 reader.readEntries(batch =>
1619 {
1620 if (!batch.length) { resolve(all); return; }
1621 all.push(...batch);
1622 next();
1623 }, reject);
1624 }
1625 next();
1626 });
1627}
1628
1629/**
1630 * Recursively walk a FileSystemEntry tree, creating server-side directories
1631 * on the fly and collecting { file, targetDir } pairs for upload.
1632 */
1633async function collectEntries (entry, serverDir, toUpload)
1634{
1635 if (entry.isFile)
1636 {
1637 const file = await new Promise((res, rej) => entry.file(res, rej));
1638 toUpload.push({ file, targetDir: serverDir });
1639 } else if (entry.isDirectory)
1640 {
1641 // Ask the server to create the directory; it returns the canonical path.
1642 let newServerDir;
1643 try
1644 {
1645 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
1646 newServerDir = resp.path;
1647 } catch
1648 {
1649 // Directory may already exist — reconstruct path from what we know.
1650 // The server always returns JSON with {error} on failure, so we can
1651 // still continue by falling back to a best-effort path join.
1652 // We rely on the fact that the server separator is consistent within
1653 // a session (the list/browse API already returned paths in that format).
1654 const sep = serverDir.includes('\\') ? '\\' : '/';
1655 newServerDir = serverDir + sep + entry.name;
1656 }
1657 const reader = entry.createReader();
1658 const subEntries = await readAllEntries(reader);
1659 for (const sub of subEntries)
1660 {
1661 await collectEntries(sub, newServerDir, toUpload);
1662 }
1663 }
1664}
1665
1666async function uploadEntries (entries)
1667{
1668 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1669 if (!canWrite()) { toast('No write access.', 'err'); return; }
1670
1671 const wrap = document.createElement('div');
1672 wrap.className = 'upload-bar-wrap';
1673 wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
1674 document.body.appendChild(wrap);
1675 STATE.uploadInProgress = true;
1676
1677 try
1678 {
1679 const toUpload = [];
1680 for (const entry of entries)
1681 {
1682 await collectEntries(entry, STATE.currentDir, toUpload);
1683 }
1684
1685 if (!toUpload.length) { toast('No files found.', 'err'); return; }
1686
1687 let done = 0;
1688 const total = toUpload.length;
1689 const updateBar = () =>
1690 {
1691 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
1692 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
1693 };
1694 updateBar();
1695
1696 for (const { file, targetDir } of toUpload)
1697 {
1698 await uploadSingleFile(file, targetDir);
1699 done++;
1700 updateBar();
1701 }
1702
1703 toast(`Uploaded ${total} file(s).`, 'ok');
1704 await navigateTo(STATE.currentDir, STATE.currentRoot);
1705 } catch (err)
1706 {
1707 toast(err.message, 'err');
1708 } finally
1709 {
1710 STATE.uploadInProgress = false;
1711 wrap.remove();
1712 }
1713}
1714
1715// DRAG-AND-DROP
1716// ───────────────────────────────────────────────────────────────────────────
1717
1718function initDragDrop ()
1719{
1720 const main = document.getElementById('main-content');
1721 const dropOvl = document.getElementById('drop-overlay');
1722 let dragDepth = 0;
1723
1724 main.addEventListener('dragenter', e =>
1725 {
1726 e.preventDefault();
1727 dragDepth++;
1728 dropOvl.classList.remove('hidden');
1729 });
1730 main.addEventListener('dragleave', () =>
1731 {
1732 dragDepth--;
1733 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
1734 });
1735 main.addEventListener('dragover', e => e.preventDefault());
1736 main.addEventListener('drop', async e =>
1737 {
1738 e.preventDefault();
1739 dragDepth = 0;
1740 dropOvl.classList.add('hidden');
1741 if (!canWrite()) { toast('No write access.', 'err'); return; }
1742
1743 const items = Array.from(e.dataTransfer.items || []);
1744 // Use the FileSystem Entry API when available so we can handle folders.
1745 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
1746 {
1747 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
1748 if (entries.some(en => en.isDirectory))
1749 {
1750 await uploadEntries(entries);
1751 return;
1752 }
1753 }
1754 // Plain files only — use the fast batch path.
1755 const files = e.dataTransfer.files;
1756 if (files.length) await uploadFiles(files);
1757 });
1758}
1759
1760// ───────────────────────────────────────────────────────────────────────────
1761// RENAME
1762// ───────────────────────────────────────────────────────────────────────────
1763
1764function openRenameModal (item)
1765{
1766 const modal = document.getElementById('rename-modal');
1767 modal.classList.remove('hidden');
1768 const input = document.getElementById('rename-input');
1769 input.value = item.name;
1770 input.focus();
1771 input.select();
1772 document.getElementById('rename-error').classList.add('hidden');
1773 document.getElementById('rename-form').onsubmit = async (e) =>
1774 {
1775 e.preventDefault();
1776 const newName = input.value.trim();
1777 if (!newName) return;
1778 try
1779 {
1780 await api('POST', '/files/rename', { from: item.path, to: newName });
1781 modal.classList.add('hidden');
1782 toast('Renamed.', 'ok');
1783 await navigateTo(STATE.currentDir, STATE.currentRoot);
1784 } catch (err)
1785 {
1786 document.getElementById('rename-error').textContent = err.message;
1787 document.getElementById('rename-error').classList.remove('hidden');
1788 }
1789 };
1790}
1791
1792// ───────────────────────────────────────────────────────────────────────────
1793// DELETE
1794// ───────────────────────────────────────────────────────────────────────────
1795
1796async function deleteItem (item)
1797{
1798 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
1799 try
1800 {
1801 await api('POST', '/files/delete', { path: item.path });
1802 toast('Deleted.', 'ok');
1803 closeSidebar();
1804 await navigateTo(STATE.currentDir, STATE.currentRoot);
1805 } catch (err)
1806 {
1807 toast(err.message, 'err');
1808 }
1809}
1810
1811// ───────────────────────────────────────────────────────────────────────────
1812// ADMIN PANEL
1813// ───────────────────────────────────────────────────────────────────────────
1814
1815async function openAdminModal ()
1816{
1817 document.getElementById('admin-modal').classList.remove('hidden');
1818 await refreshAdminConfig();
1819 await refreshAdminUsers();
1820}
1821
1822async function refreshAdminConfig ()
1823{
1824 const data = await api('GET', '/admin/config');
1825 if (!data) return;
1826 const container = document.getElementById('admin-paths');
1827 container.innerHTML = '';
1828 for (const p of data.paths)
1829 {
1830 const row = document.createElement('div');
1831 row.className = 'path-row';
1832 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
1833 row.querySelector('button').addEventListener('click', () =>
1834 {
1835 row.remove();
1836 });
1837 container.appendChild(row);
1838 }
1839}
1840
1841async function refreshAdminUsers ()
1842{
1843 const data = await api('GET', '/admin/users');
1844 if (!data) return;
1845 const container = document.getElementById('admin-users-list');
1846 container.innerHTML = '';
1847
1848 // Need paths for permission rows
1849 const cfg = await api('GET', '/admin/config');
1850 const paths = cfg ? (cfg.effectivePaths || []) : [];
1851
1852 for (const u of data.users)
1853 {
1854 const row = document.createElement('div');
1855 row.className = 'user-row';
1856 row.innerHTML = `
1857 <span class="user-name">${u.username}</span>
1858 ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''}
1859 <button data-id="${u.id}" data-action="edit">Edit</button>
1860 ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`}
1861 `;
1862 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
1863 openUserModal(u, paths));
1864 const deleteBtn = row.querySelector('[data-action="delete"]');
1865 if (deleteBtn) deleteBtn.addEventListener('click', async () =>
1866 {
1867 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
1868 try
1869 {
1870 await api('DELETE', `/admin/users/${u.id}`);
1871 toast('User deleted.', 'ok');
1872 await refreshAdminUsers();
1873 } catch (err) { toast(err.message, 'err'); }
1874 });
1875 container.appendChild(row);
1876 }
1877}
1878
1879function openUserModal (user, paths)
1880{
1881 const modal = document.getElementById('user-modal');
1882 modal.classList.remove('hidden');
1883 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
1884 document.getElementById('user-error').classList.add('hidden');
1885
1886 const usernameInput = document.getElementById('user-username');
1887 usernameInput.value = user ? user.username : '';
1888 usernameInput.readOnly = !!user;
1889
1890 document.getElementById('user-password').value = '';
1891 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
1892
1893 // Password placeholder
1894 document.getElementById('user-password').placeholder =
1895 user ? 'Leave blank to keep current' : 'Min 8 characters';
1896
1897 // Build permissions grid
1898 const permDiv = document.getElementById('user-permissions');
1899 permDiv.innerHTML = '';
1900 if (paths.length)
1901 {
1902 const heading = document.createElement('h4');
1903 heading.textContent = 'Path Permissions';
1904 permDiv.appendChild(heading);
1905
1906 const isAdminUser = !!(user && user.isAdmin);
1907 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
1908 const adminChk = document.getElementById('user-is-admin');
1909 const rebuildPermRows = (admin) =>
1910 {
1911 permDiv.querySelectorAll('.perm-row').forEach(r =>
1912 {
1913 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
1914 {
1915 cb.disabled = admin;
1916 if (admin) cb.checked = true;
1917 });
1918 r.title = admin ? 'Admins always have full access' : '';
1919 });
1920 };
1921 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
1922
1923 for (const p of paths)
1924 {
1925 const label = p.split(/[\\/]/).pop();
1926 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
1927 const row = document.createElement('div');
1928 row.className = 'perm-row';
1929 const readChecked = isAdminUser || perms.read;
1930 const writeChecked = isAdminUser || perms.write;
1931 row.innerHTML = `
1932 <span class="perm-label">${label}</span>
1933 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label>
1934 <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label>
1935 `;
1936 if (isAdminUser) row.title = 'Admins always have full access';
1937 permDiv.appendChild(row);
1938 }
1939 }
1940
1941 document.getElementById('user-form').onsubmit = async (e) =>
1942 {
1943 e.preventDefault();
1944 const password = document.getElementById('user-password').value;
1945 const isAdmin = document.getElementById('user-is-admin').checked;
1946 const permissions = {};
1947 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
1948 {
1949 const lbl = cb.dataset.label;
1950 if (!permissions[lbl]) permissions[lbl] = {};
1951 permissions[lbl][cb.dataset.type] = cb.checked;
1952 });
1953
1954 try
1955 {
1956 if (user)
1957 {
1958 const body = { isAdmin, permissions };
1959 if (password) body.password = password;
1960 await api('PATCH', `/admin/users/${user.id}`, body);
1961 } else
1962 {
1963 const uname = document.getElementById('user-username').value.trim();
1964 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
1965 }
1966 modal.classList.add('hidden');
1967 toast('User saved.', 'ok');
1968 await refreshAdminUsers();
1969 } catch (err)
1970 {
1971 document.getElementById('user-error').textContent = err.message;
1972 document.getElementById('user-error').classList.remove('hidden');
1973 }
1974 };
1975}
1976
1977// ───────────────────────────────────────────────────────────────────────────
1978// SVG ICONS
1979// ───────────────────────────────────────────────────────────────────────────
1980
1981const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
1982const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
1983const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
1984const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
1985const 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']);
1986const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
1987
1988function iconFolder (size = 52)
1989{
1990 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
1991 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
1992 <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"/>
1993 </svg>`;
1994}
1995
1996function iconFile (name, size = 52)
1997{
1998 const color = fileAccentColor(name);
1999 let symbol = '';
2000
2001 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
2002 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
2003 <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
2004 <polyline points="14 2 14 8 20 8"/>
2005 </svg>`;
2006}
2007
2008// ───────────────────────────────────────────────────────────────────────────
2009// EVENT WIRING
2010// ───────────────────────────────────────────────────────────────────────────
2011
2012// ───────────────────────────────────────────────────────────────────────────
2013// THUMBNAIL PREVIEWS
2014// ───────────────────────────────────────────────────────────────────────────
2015
2016function revokeThumbnails ()
2017{
2018 STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u));
2019 STATE.thumbnailUrls = [];
2020}
2021
2022function getThumbnailKind (name)
2023{
2024 const ext = extOf(name || '');
2025 if (IMAGE_EXTS.has(ext)) return 'image';
2026 if (VIDEO_EXTS.has(ext)) return 'video';
2027 if (CODE_EXTS.has(ext)) return 'text';
2028 if (AUDIO_EXTS.has(ext)) return 'audio';
2029 if (ext === 'pdf') return 'pdf';
2030 return 'badge';
2031}
2032
2033function maxThumbBytesForKind (kind)
2034{
2035 if (kind === 'image') return 15 * 1024 * 1024;
2036 if (kind === 'video') return 25 * 1024 * 1024;
2037 if (kind === 'text') return 1024 * 1024;
2038 return 0;
2039}
2040
2041function drawTokenizedLine (ctx, line, x, y)
2042{
2043 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;
2044 let last = 0;
2045 let cursor = x;
2046 for (const m of line.matchAll(tokenRe))
2047 {
2048 const i = m.index == null ? 0 : m.index;
2049 if (i > last)
2050 {
2051 const plain = line.slice(last, i);
2052 ctx.fillStyle = '#dce4ff';
2053 ctx.fillText(plain, cursor, y);
2054 cursor += ctx.measureText(plain).width;
2055 }
2056
2057 const tok = m[0];
2058 if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a';
2059 else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d';
2060 else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a';
2061 else ctx.fillStyle = '#8bb4ff';
2062
2063 ctx.fillText(tok, cursor, y);
2064 cursor += ctx.measureText(tok).width;
2065 last = i + tok.length;
2066 }
2067
2068 if (last < line.length)
2069 {
2070 const tail = line.slice(last);
2071 ctx.fillStyle = '#dce4ff';
2072 ctx.fillText(tail, cursor, y);
2073 }
2074}
2075
2076function textThumbnailDataUrl (text)
2077{
2078 const canvas = document.createElement('canvas');
2079 canvas.width = 160;
2080 canvas.height = 200;
2081 const ctx = canvas.getContext('2d');
2082 if (!ctx) return null;
2083
2084 ctx.fillStyle = '#0d111a';
2085 ctx.fillRect(0, 0, canvas.width, canvas.height);
2086 ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
2087 ctx.textBaseline = 'top';
2088
2089 const lines = String(text || '')
2090 .replace(/\r\n/g, '\n')
2091 .split('\n')
2092 .slice(0, 17);
2093
2094 let y = 8;
2095 for (const line of lines)
2096 {
2097 drawTokenizedLine(ctx, line.slice(0, 42), 6, y);
2098 y += 11;
2099 if (y > 190) break;
2100 }
2101 return canvas.toDataURL('image/png');
2102}
2103
2104function badgeThumbnailDataUrl (name, kind)
2105{
2106 const canvas = document.createElement('canvas');
2107 canvas.width = 160;
2108 canvas.height = 200;
2109 const ctx = canvas.getContext('2d');
2110 if (!ctx) return null;
2111
2112 const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5);
2113 const color = kind === 'audio' ? '#c084fc'
2114 : kind === 'pdf' ? '#f97316'
2115 : '#5b7fff';
2116
2117 ctx.fillStyle = '#111826';
2118 ctx.fillRect(0, 0, 160, 200);
2119 ctx.fillStyle = color;
2120 ctx.fillRect(0, 0, 160, 28);
2121 ctx.fillStyle = '#ffffff';
2122 ctx.font = 'bold 12px sans-serif';
2123 ctx.textAlign = 'center';
2124 ctx.fillText(ext, 80, 8);
2125 ctx.textAlign = 'left';
2126 ctx.fillStyle = '#9fb1d8';
2127 ctx.font = '10px sans-serif';
2128 ctx.fillText('Preview', 8, 48);
2129 ctx.fillStyle = '#dce4ff';
2130 ctx.font = 'bold 11px sans-serif';
2131 ctx.fillText(ext, 8, 66);
2132 return canvas.toDataURL('image/png');
2133}
2134
2135async function videoThumbnailDataUrl (blob)
2136{
2137 const src = URL.createObjectURL(blob);
2138 try
2139 {
2140 const video = document.createElement('video');
2141 video.src = src;
2142 video.muted = true;
2143 video.preload = 'metadata';
2144
2145 await new Promise((resolve, reject) =>
2146 {
2147 const fail = () => reject(new Error('video load failed'));
2148 video.addEventListener('error', fail, { once: true });
2149 video.addEventListener('loadeddata', resolve, { once: true });
2150 });
2151
2152 const targetTime = Number.isFinite(video.duration) && video.duration > 1 ? 1 : 0;
2153 await new Promise((resolve) =>
2154 {
2155 video.currentTime = targetTime;
2156 video.addEventListener('seeked', resolve, { once: true });
2157 });
2158
2159 const canvas = document.createElement('canvas');
2160 canvas.width = 160;
2161 canvas.height = 200;
2162 const ctx = canvas.getContext('2d');
2163 if (!ctx) return null;
2164
2165 ctx.fillStyle = '#0d111a';
2166 ctx.fillRect(0, 0, canvas.width, canvas.height);
2167 const rw = video.videoWidth || 1;
2168 const rh = video.videoHeight || 1;
2169 const scale = Math.max(canvas.width / rw, canvas.height / rh);
2170 const dw = rw * scale;
2171 const dh = rh * scale;
2172 ctx.drawImage(video, (canvas.width - dw) / 2, (canvas.height - dh) / 2, dw, dh);
2173
2174 // subtle play badge
2175 ctx.fillStyle = 'rgba(0,0,0,0.45)';
2176 ctx.beginPath();
2177 ctx.arc(80, 100, 18, 0, Math.PI * 2);
2178 ctx.fill();
2179 ctx.fillStyle = '#ffffff';
2180 ctx.beginPath();
2181 ctx.moveTo(75, 90);
2182 ctx.lineTo(75, 110);
2183 ctx.lineTo(90, 100);
2184 ctx.closePath();
2185 ctx.fill();
2186
2187 return canvas.toDataURL('image/png');
2188 } catch
2189 {
2190 return null;
2191 } finally
2192 {
2193 URL.revokeObjectURL(src);
2194 }
2195}
2196
2197async function buildThumbnailSource (item, blob, kind)
2198{
2199 if (kind === 'image') return URL.createObjectURL(blob);
2200 if (kind === 'video') return await videoThumbnailDataUrl(blob);
2201 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
2202 return badgeThumbnailDataUrl(item.name, kind);
2203}
2204
2205async function loadThumbnails ()
2206{
2207 const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]'));
2208 if (!icons.length) return;
2209
2210 const queue = [...icons];
2211 async function worker ()
2212 {
2213 while (queue.length)
2214 {
2215 await loadOneThumbnail(queue.shift());
2216 }
2217 }
2218 // Four concurrent fetches — keeps the Pi's network from flooding
2219 await Promise.all(Array.from({ length: Math.min(4, icons.length) }, worker));
2220}
2221
2222async function loadOneThumbnail (iconEl)
2223{
2224 if (!iconEl.isConnected || !STATE.token) return;
2225 if (iconEl.dataset.thumbReady === '1') return;
2226 const filePath = iconEl.dataset.previewPath;
2227 const item = STATE.items.find(i => i.path === filePath);
2228 if (!item) return;
2229
2230 const kind = getThumbnailKind(item.name);
2231 let srcUrl = null;
2232
2233 if (kind === 'badge' || kind === 'audio' || kind === 'pdf')
2234 {
2235 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2236 } else
2237 {
2238 const maxBytes = maxThumbBytesForKind(kind);
2239 if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes)
2240 {
2241 srcUrl = badgeThumbnailDataUrl(item.name, kind);
2242 } else
2243 {
2244 const url = `/api/files/download?file=${encodeURIComponent(filePath)}`;
2245
2246 let res;
2247 try
2248 {
2249 res = await fetch(url, {
2250 headers: {
2251 Authorization: `Bearer ${STATE.token}`,
2252 'X-Fp': getFingerprint(),
2253 },
2254 });
2255 } catch { return; }
2256 if (!res.ok || !iconEl.isConnected) return;
2257
2258 const blob = await res.blob();
2259 srcUrl = await buildThumbnailSource(item, blob, kind);
2260 if (kind === 'image' && srcUrl) STATE.thumbnailUrls.push(srcUrl);
2261 }
2262 }
2263 if (!srcUrl || !iconEl.isConnected) return;
2264
2265 const svg = iconEl.querySelector('svg');
2266 if (!svg)
2267 {
2268 if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl);
2269 return;
2270 }
2271
2272 const NS = 'http://www.w3.org/2000/svg';
2273 const id = `fcp-${Math.random().toString(36).slice(2, 9)}`;
2274
2275 // clipPath matches the main file body outline exactly (viewBox 0 0 24 24)
2276 const defs = document.createElementNS(NS, 'defs');
2277 const clipPath = document.createElementNS(NS, 'clipPath');
2278 clipPath.setAttribute('id', id);
2279 clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse');
2280 const clipShape = document.createElementNS(NS, 'path');
2281 clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z');
2282 clipPath.appendChild(clipShape);
2283 defs.appendChild(clipPath);
2284
2285 // Image fills the file bounding box; clip keeps it inside the outline
2286 const img = document.createElementNS(NS, 'image');
2287 img.setAttribute('href', srcUrl);
2288 img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl);
2289 img.setAttribute('x', '4');
2290 img.setAttribute('y', '2');
2291 img.setAttribute('width', '16');
2292 img.setAttribute('height', '20');
2293 img.setAttribute('clip-path', `url(#${id})`);
2294 img.setAttribute('preserveAspectRatio', 'xMidYMid slice');
2295
2296 // Prepend so existing path/polyline elements (the outline) render on top
2297 svg.prepend(img);
2298 svg.prepend(defs);
2299 iconEl.dataset.thumbReady = '1';
2300}
2301
2302function wireEvents ()
2303{
2304 // Auth form
2305 document.getElementById('auth-form').addEventListener('submit', async (e) =>
2306 {
2307 e.preventDefault();
2308 const username = document.getElementById('auth-username').value.trim();
2309 const password = document.getElementById('auth-password').value;
2310 const isSetup = e.target.dataset.mode === 'setup';
2311 const errEl = document.getElementById('auth-error');
2312 const btn = document.getElementById('auth-submit');
2313 btn.disabled = true;
2314 btn.textContent = 'Please wait…';
2315 const err = await doLogin(username, password, isSetup);
2316 if (err)
2317 {
2318 errEl.textContent = err;
2319 errEl.classList.remove('hidden');
2320 btn.disabled = false;
2321 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
2322 }
2323 });
2324
2325 // Logout
2326 document.getElementById('btn-logout').addEventListener('click', logout);
2327
2328 // Hard refresh while keeping auth/session state.
2329 document.getElementById('btn-refresh').addEventListener('click', () =>
2330 {
2331 saveSessionState();
2332 location.reload();
2333 });
2334
2335 // Upload button
2336 document.getElementById('btn-upload').addEventListener('click', () =>
2337 {
2338 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2339 if (!canWrite()) { toast('No write access.', 'err'); return; }
2340 document.getElementById('file-input').click();
2341 });
2342
2343 document.getElementById('file-input').addEventListener('change', async (e) =>
2344 {
2345 if (e.target.files.length) await uploadFiles(e.target.files);
2346 e.target.value = '';
2347 });
2348
2349 document.getElementById('btn-upload-folder').addEventListener('click', () =>
2350 {
2351 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2352 if (!canWrite()) { toast('No write access.', 'err'); return; }
2353 document.getElementById('folder-input').click();
2354 });
2355
2356 document.getElementById('folder-input').addEventListener('change', async (e) =>
2357 {
2358 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
2359 e.target.value = '';
2360 });
2361
2362 document.getElementById('btn-new-folder').addEventListener('click', async () =>
2363 {
2364 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
2365 if (!canWrite()) { toast('No write access.', 'err'); return; }
2366
2367 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
2368 if (name == null) return;
2369 const folderName = name.trim();
2370 if (!folderName)
2371 {
2372 toast('Folder name is required.', 'err');
2373 return;
2374 }
2375
2376 try
2377 {
2378 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
2379 toast('Folder created.', 'ok');
2380 await navigateTo(STATE.currentDir, STATE.currentRoot);
2381 } catch (err)
2382 {
2383 toast(err.message, 'err');
2384 }
2385 });
2386
2387 // Sidebar is persistent; close button is intentionally disabled.
2388
2389 // Click outside grid clears selection and returns to folder sidebar info.
2390 document.getElementById('main-content').addEventListener('click', (e) =>
2391 {
2392 if (!e.target.closest('.file-item')) closeSidebar();
2393 });
2394
2395 // Admin panel
2396 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
2397 document.getElementById('admin-modal-close').addEventListener('click', () =>
2398 document.getElementById('admin-modal').classList.add('hidden'));
2399
2400 // Add path
2401 document.getElementById('admin-add-path').addEventListener('click', () =>
2402 {
2403 const val = document.getElementById('admin-new-path').value.trim();
2404 if (!val) return;
2405 const row = document.createElement('div');
2406 row.className = 'path-row';
2407 row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`;
2408 row.querySelector('button').addEventListener('click', () => row.remove());
2409 document.getElementById('admin-paths').appendChild(row);
2410 document.getElementById('admin-new-path').value = '';
2411 });
2412
2413 // Save paths
2414 document.getElementById('admin-save-paths').addEventListener('click', async () =>
2415 {
2416 const rows = document.querySelectorAll('#admin-paths .path-row span');
2417 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
2418 try
2419 {
2420 await api('PUT', '/admin/config', { paths });
2421 toast('Paths saved.', 'ok');
2422 await loadRoots();
2423 } catch (err) { toast(err.message, 'err'); }
2424 });
2425
2426 // Shutdown server
2427 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
2428 {
2429 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
2430 try
2431 {
2432 await api('POST', '/admin/shutdown');
2433 toast('Server is shutting down…', 'ok');
2434 document.getElementById('admin-modal').classList.add('hidden');
2435 } catch
2436 {
2437 // Fetch may throw because the connection closes before a response arrives.
2438 toast('Server is shutting down…', 'ok');
2439 document.getElementById('admin-modal').classList.add('hidden');
2440 }
2441 });
2442
2443 // New user
2444 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
2445 {
2446 const cfg = await api('GET', '/admin/config');
2447 const paths = cfg ? (cfg.effectivePaths || []) : [];
2448 openUserModal(null, paths);
2449 });
2450
2451 // User modal close
2452 document.getElementById('user-modal-close').addEventListener('click', () =>
2453 document.getElementById('user-modal').classList.add('hidden'));
2454
2455 // Rename modal close
2456 document.getElementById('rename-modal-close').addEventListener('click', () =>
2457 document.getElementById('rename-modal').classList.add('hidden'));
2458
2459 // Preview close
2460 document.getElementById('preview-close').addEventListener('click', closePreview);
2461 document.getElementById('preview-overlay').addEventListener('click', (e) =>
2462 {
2463 if (e.target.id === 'preview-overlay') closePreview();
2464 });
2465
2466 document.addEventListener('keydown', (e) =>
2467 {
2468 if (e.key === 'Escape' && !document.getElementById('preview-overlay').classList.contains('hidden'))
2469 {
2470 closePreview();
2471 }
2472 });
2473
2474 // Close modals on backdrop click
2475 document.querySelectorAll('.modal-overlay').forEach(overlay =>
2476 {
2477 overlay.addEventListener('click', e =>
2478 {
2479 if (e.target === overlay) overlay.classList.add('hidden');
2480 });
2481 });
2482}
2483
2484// ───────────────────────────────────────────────────────────────────────────
2485// BOOT
2486// ───────────────────────────────────────────────────────────────────────────
2487
2488(async function boot ()
2489{
2490 wireEvents();
2491 initDragDrop();
2492 window.addEventListener('beforeunload', saveSessionState);
2493 await initAuth();
2494})();