BlueGit

timfa filemanager

userdirs

timfa Tim Falken · pushed by timfa

Authored 2026-05-13 · 6 months ago

Hash
f803c52fc678833f1a1eb271fa58e1b3c778203c
Parent
3fcdc0ca
7 files changed +729 −110
.github/technical-reference.md +26 −2
@@ -6,7 +6,7 @@
6 6 - GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
7 7
8 8 ## server/thumbnail-cache.js
9 - syncThumbnailCacheOnce() - Mirrors configured roots into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
9 - syncThumbnailCacheOnce() - Mirrors configured roots and userPath into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
10 10 - startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
11 11 - stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
12 12 - getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
@@ -41,12 +41,23 @@
41 41 ## server/routes/admin.js
42 42 - POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
43 43 - normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
44 - ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
45 - GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
46 - PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
44 47 - GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] }. Detects systemd via INVOCATION_ID env var; runs git fetch + git log to find commits ahead of HEAD. Used by the frontend to set button label (Shut down server / Restart Server / Restart & Update).
45 48
46 49 ## server/routes/files.js
47 50 - GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
51 - GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
52 - loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
53 - resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
54 - canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
55 - checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
48 56 - POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
49 57 - GET /api/files/root-access - Returns users who can access an exact configured root and their access mode (R / R+W).
58 - GET /api/files/meta - Returns file metadata and lazily computes/stores sha256 when missing.
59 - GET /api/files/duplicates - Returns accessible files that share the selected file's sha256 hash.
60 - GET /api/files/space - Returns used/free disk space and, for personal folders, user-limit fields (userLimitBytes/userFreeBytes).
50 61 - GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
51 62 - GET /api/files/folder-images - Returns images inside a directory (recursive) that already have a cached thumbnail; only thumbnailed images are included per user requirement.
52 63 - GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
@@ -58,8 +69,9 @@
58 69 - splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
59 70 - pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
60 71 - removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
61 - POST /api/files/upload - Streams multipart uploads into hidden temp files, unpipes stream writes on abort/failure, cleans temp files, and only exposes final filenames after completion.
72 - POST /api/files/upload - Streams multipart uploads into hidden temp files, computes/stores sha256, and enforces user-folder size limits.
62 73 - POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
74 - POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
63 75 - POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
64 76 - DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
65 77 - POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
@@ -98,6 +110,7 @@
98 110
99 111 ## public/index.html
100 112 - Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
113 - Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
101 114
102 115 ## public/app.js
103 116 - showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
@@ -118,6 +131,10 @@
118 131 - listDirNameSet(dir) - Fetches directory listing and returns a Set of existing names.
119 132 - cloneFileWithName(file, newName) - Creates a renamed File object for non-overwrite uploads.
120 133 - showFileConflictChoice(filename, renameTo, mode) - Dialog for single upload/move conflicts; returns overwrite/rename/cancel.
134 - parseHumanSize(input) - Parses human-readable sizes like `25 MB`/`1gb` into bytes for admin user-folder limits.
135 - updateAdminSizeFeedback(rawValue) - Validates size input and updates admin hint text/classes with parsed byte preview.
136 - relativePathFromRoot(targetPath, rootPath) - Produces a root-relative path string for sidebar folder context display.
137 - displayPathWithRootLabel(targetPath, rootPath, rootLabel) - Produces Linux-style root-relative display paths like `/Downloads/A/B` for folder context UI.
121 138 - openShareModal(item) - Opens the Delen (share) popup, calls POST /api/share/create, shows the 24-hour URL with a copy button and OK to dismiss.
122 139 - loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
123 140 - loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
@@ -160,7 +177,10 @@
160 177 - closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
161 178 - closePreview() - Closes expanded-tile preview and revokes active preview object URL.
162 179 - openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
180 - openCopyPicker(item) - Opens Copy To selector modal with the same tree and executes /api/files/copy.
181 - openDestinationPicker(item, mode) - Shared destination picker state/labels for move vs copy operations.
163 182 - moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
183 - copyWithConflictResolution(item, targetDir) - Attempts copy and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
164 184 - rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
165 185 - ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
166 186 - createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
@@ -196,6 +216,10 @@
196 216 - .preview-expand-share - Secondary action button positioned next to .preview-expand-download in expanded file preview.
197 217 - .move-modal/.move-tree/.move-node* - Move To tree picker styles with expandable/collapsible folder hierarchy.
198 218
219 ## public/style.css
220 - #sidebar-duplicates + related classes - Sidebar duplicate-file list styling with truncation and hover feedback.
221 - .admin-size-feedback(.ok/.err) - Validation feedback styling for admin user-folder size-limit input.
222
199 223 ## tests/auth.routes.test.js
200 224 - session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
201 225 - session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
@@ -6,7 +6,7 @@
6- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
6- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
7
7
8## server/thumbnail-cache.js
8## server/thumbnail-cache.js
9- syncThumbnailCacheOnce() - Mirrors configured roots into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
9- syncThumbnailCacheOnce() - Mirrors configured roots and userPath into public/thumbs and generates 99x99-max WebP thumbnails for image files; removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
10- startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
10- startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
11- stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
11- stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
12- getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
12- getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
@@ -41,12 +41,23 @@
41## server/routes/admin.js
41## server/routes/admin.js
42- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
42- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
43- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
43- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
44- ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
45- GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
46- PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
44- GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] }. Detects systemd via INVOCATION_ID env var; runs git fetch + git log to find commits ahead of HEAD. Used by the frontend to set button label (Shut down server / Restart Server / Restart & Update).
47- GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] }. Detects systemd via INVOCATION_ID env var; runs git fetch + git log to find commits ahead of HEAD. Used by the frontend to set button label (Shut down server / Restart Server / Restart & Update).
45
48
46## server/routes/files.js
49## server/routes/files.js
47- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
50- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
51- GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
52- loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
53- resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
54- canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
55- checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
48- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
56- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
49- GET /api/files/root-access - Returns users who can access an exact configured root and their access mode (R / R+W).
57- GET /api/files/root-access - Returns users who can access an exact configured root and their access mode (R / R+W).
58- GET /api/files/meta - Returns file metadata and lazily computes/stores sha256 when missing.
59- GET /api/files/duplicates - Returns accessible files that share the selected file's sha256 hash.
60- GET /api/files/space - Returns used/free disk space and, for personal folders, user-limit fields (userLimitBytes/userFreeBytes).
50- GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
61- GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
51- GET /api/files/folder-images - Returns images inside a directory (recursive) that already have a cached thumbnail; only thumbnailed images are included per user requirement.
62- GET /api/files/folder-images - Returns images inside a directory (recursive) that already have a cached thumbnail; only thumbnailed images are included per user requirement.
52- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
63- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
@@ -58,8 +69,9 @@
58- splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
69- splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
59- pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
70- pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
60- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
71- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
61- POST /api/files/upload - Streams multipart uploads into hidden temp files, unpipes stream writes on abort/failure, cleans temp files, and only exposes final filenames after completion.
72- POST /api/files/upload - Streams multipart uploads into hidden temp files, computes/stores sha256, and enforces user-folder size limits.
62- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
73- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
74- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
63- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
75- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
64- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
76- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
65- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
77- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
@@ -98,6 +110,7 @@
98
110
99## public/index.html
111## public/index.html
100- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
112- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
113- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
101
114
102## public/app.js
115## public/app.js
103- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
116- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
@@ -118,6 +131,10 @@
118- listDirNameSet(dir) - Fetches directory listing and returns a Set of existing names.
131- listDirNameSet(dir) - Fetches directory listing and returns a Set of existing names.
119- cloneFileWithName(file, newName) - Creates a renamed File object for non-overwrite uploads.
132- cloneFileWithName(file, newName) - Creates a renamed File object for non-overwrite uploads.
120- showFileConflictChoice(filename, renameTo, mode) - Dialog for single upload/move conflicts; returns overwrite/rename/cancel.
133- showFileConflictChoice(filename, renameTo, mode) - Dialog for single upload/move conflicts; returns overwrite/rename/cancel.
134- parseHumanSize(input) - Parses human-readable sizes like `25 MB`/`1gb` into bytes for admin user-folder limits.
135- updateAdminSizeFeedback(rawValue) - Validates size input and updates admin hint text/classes with parsed byte preview.
136- relativePathFromRoot(targetPath, rootPath) - Produces a root-relative path string for sidebar folder context display.
137- displayPathWithRootLabel(targetPath, rootPath, rootLabel) - Produces Linux-style root-relative display paths like `/Downloads/A/B` for folder context UI.
121- openShareModal(item) - Opens the Delen (share) popup, calls POST /api/share/create, shows the 24-hour URL with a copy button and OK to dismiss.
138- openShareModal(item) - Opens the Delen (share) popup, calls POST /api/share/create, shows the 24-hour URL with a copy button and OK to dismiss.
122- loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
139- loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
123- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
140- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
@@ -160,7 +177,10 @@
160- closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
177- closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
161- closePreview() - Closes expanded-tile preview and revokes active preview object URL.
178- closePreview() - Closes expanded-tile preview and revokes active preview object URL.
162- openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
179- openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
180- openCopyPicker(item) - Opens Copy To selector modal with the same tree and executes /api/files/copy.
181- openDestinationPicker(item, mode) - Shared destination picker state/labels for move vs copy operations.
163- moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
182- moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
183- copyWithConflictResolution(item, targetDir) - Attempts copy and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
164- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
184- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
165- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
185- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
166- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
186- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
@@ -196,6 +216,10 @@
196- .preview-expand-share - Secondary action button positioned next to .preview-expand-download in expanded file preview.
216- .preview-expand-share - Secondary action button positioned next to .preview-expand-download in expanded file preview.
197- .move-modal/.move-tree/.move-node* - Move To tree picker styles with expandable/collapsible folder hierarchy.
217- .move-modal/.move-tree/.move-node* - Move To tree picker styles with expandable/collapsible folder hierarchy.
198
218
219## public/style.css
220- #sidebar-duplicates + related classes - Sidebar duplicate-file list styling with truncation and hover feedback.
221- .admin-size-feedback(.ok/.err) - Validation feedback styling for admin user-folder size-limit input.
222
199## tests/auth.routes.test.js
223## tests/auth.routes.test.js
200- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
224- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
201- session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
225- session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
public/app.js +238 −31
@@ -578,6 +578,56 @@ function formatBytes (bytes)
578 578 return (bytes / 1073741824).toFixed(2) + ' GB';
579 579 }
580 580
581 function parseHumanSize (input)
582 {
583 const raw = String(input || '').trim();
584 if (!raw) return null;
585
586 const m = raw.match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)(?:i?b)?$/i);
587 if (!m) return null;
588
589 const value = Number(m[1]);
590 if (!Number.isFinite(value) || value <= 0) return null;
591
592 const unit = String(m[2] || '').toLowerCase();
593 const multipliers = {
594 '': 1,
595 k: 1024,
596 m: 1024 * 1024,
597 g: 1024 * 1024 * 1024,
598 t: 1024 * 1024 * 1024 * 1024,
599 };
600 return Math.floor(value * (multipliers[unit] || 1));
601 }
602
603 function updateAdminSizeFeedback (rawValue)
604 {
605 const feedback = document.getElementById('admin-user-size-feedback');
606 if (!feedback) return { bytes: null, valid: true };
607
608 const trimmed = String(rawValue || '').trim();
609 if (!trimmed)
610 {
611 feedback.textContent = '';
612 feedback.classList.add('hidden');
613 feedback.classList.remove('ok', 'err');
614 return { bytes: null, valid: true };
615 }
616
617 const bytes = parseHumanSize(trimmed);
618 feedback.classList.remove('hidden', 'ok', 'err');
619 if (bytes == null)
620 {
621 feedback.textContent = 'Invalid size. Use formats like 25 MB, 1 GB, or 500 KB.';
622 feedback.classList.add('err');
623 return { bytes: null, valid: false };
624 }
625
626 feedback.textContent = `Valid size: ${formatBytes(bytes)}`;
627 feedback.classList.add('ok');
628 return { bytes, valid: true };
629 }
630
581 631 function extOf (name)
582 632 {
583 633 const i = name.lastIndexOf('.');
@@ -610,6 +660,26 @@ function pathInside (child, root)
610 660 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
611 661 }
612 662
663 function relativePathFromRoot (targetPath, rootPath)
664 {
665 if (!targetPath || !rootPath) return String(targetPath || '');
666 if (samePath(targetPath, rootPath)) return '.';
667
668 const prefix = String(rootPath).replace(/[\\/]+$/, '');
669 const rel = String(targetPath).slice(prefix.length).replace(/^[\\/]+/, '');
670 if (!rel) return '.';
671 return rel;
672 }
673
674 function displayPathWithRootLabel (targetPath, rootPath, rootLabel)
675 {
676 const rel = relativePathFromRoot(targetPath, rootPath);
677 const safeRoot = String(rootLabel || '').replace(/^\/+|\/+$/g, '');
678 if (!safeRoot) return '/';
679 if (rel === '.') return `/${safeRoot}`;
680 return `/${safeRoot}/${String(rel).replace(/\\/g, '/')}`;
681 }
682
613 683 function splitNameExt (name)
614 684 {
615 685 const dot = String(name || '').lastIndexOf('.');
@@ -1287,14 +1357,11 @@ function renderBreadcrumb ()
1287 1357
1288 1358 if (!STATE.currentDir || !STATE.currentRoot) return;
1289 1359
1290 // Build path segments relative to the root
1360 // Build path segments relative to the root.
1291 1361 const rootPath = STATE.currentRoot.path;
1292 const relative = STATE.currentDir === rootPath
1293 ? ''
1294 : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, '');
1295
1296 const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)];
1297 let accumulated = rootPath;
1362 const relative = relativePathFromRoot(STATE.currentDir, rootPath);
1363 const segments = relative === '.' ? [] : relative.split(/[\\/]/).filter(Boolean);
1364 const parts = [STATE.currentRoot.label, ...segments];
1298 1365
1299 1366 for (let i = 0; i < parts.length; i++)
1300 1367 {
@@ -1307,8 +1374,10 @@ function renderBreadcrumb ()
1307 1374 crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : '');
1308 1375 crumb.textContent = parts[i];
1309 1376
1310 // Capture the path for this crumb
1311 const capturedPath = i === 0 ? rootPath : accumulated;
1377 // Root crumb points to rootPath; segment crumbs point to their folder.
1378 const capturedPath = i === 0
1379 ? rootPath
1380 : joinServerPath(rootPath, segments.slice(0, i).join('/'));
1312 1381 crumb.classList.add('crumb-drop-target');
1313 1382 crumb.dataset.path = capturedPath;
1314 1383 if (i < parts.length - 1)
@@ -1317,14 +1386,6 @@ function renderBreadcrumb ()
1317 1386 }
1318 1387
1319 1388 nav.appendChild(crumb);
1320
1321 // Advance accumulated path (skip for root label)
1322 if (i > 0) accumulated = accumulated + '/' + parts[i];
1323 else if (i === 0 && parts.length > 1)
1324 {
1325 // After root label, next crumb should append the next segment
1326 accumulated = rootPath;
1327 }
1328 1389 }
1329 1390 }
1330 1391
@@ -1346,8 +1407,14 @@ async function refreshFolderStats ()
1346 1407 }
1347 1408
1348 1409 const used = formatBytes(data.usedBytes);
1349 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
1350 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
1410 if (data.userFreeBytes != null)
1411 {
1412 el.textContent = `Folder usage: ${used} | Free space remaining: ${formatBytes(data.userFreeBytes)}`;
1413 } else
1414 {
1415 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
1416 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
1417 }
1351 1418 el.classList.remove('hidden');
1352 1419 }
1353 1420
@@ -1588,7 +1655,7 @@ function selectItem (el, item)
1588 1655 /**
1589 1656 * Renders (or clears) the duplicates panel at the bottom of the sidebar.
1590 1657 * @param {object|null} item — the item whose duplicates are shown; null = clear
1591 * @param {Array|null} duplicates — array of {path, name, dir}; null = loading state
1658 * @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state
1592 1659 */
1593 1660 function renderSidebarDuplicates (item, duplicates)
1594 1661 {
@@ -1626,8 +1693,8 @@ function renderSidebarDuplicates (item, duplicates)
1626 1693 const btn = document.createElement('button');
1627 1694 btn.className = 'sidebar-duplicate-entry';
1628 1695 btn.title = dup.path;
1629 // Show the full path; let CSS truncate with ellipsis if it does not fit.
1630 btn.textContent = dup.path;
1696 // Show path relative to its root; keep absolute path in the tooltip.
1697 btn.textContent = dup.relativePath || dup.path;
1631 1698 btn.addEventListener('click', () => navigateToDuplicate(dup));
1632 1699 li.appendChild(btn);
1633 1700 list.appendChild(li);
@@ -1643,6 +1710,19 @@ function renderSidebarDuplicates (item, duplicates)
1643 1710 */
1644 1711 async function navigateToDuplicate (dup)
1645 1712 {
1713 // If the duplicate lives in the folder already shown, just select it.
1714 if (STATE.currentDir && samePath(dup.dir, STATE.currentDir))
1715 {
1716 const tile = Array.from(document.querySelectorAll('.file-item'))
1717 .find((el) => el.dataset.path === dup.path);
1718 const dupItem = STATE.items.find((i) => i.path === dup.path);
1719 if (tile && dupItem)
1720 {
1721 selectItem(tile, dupItem);
1722 }
1723 return;
1724 }
1725
1646 1726 // Find the root that contains the duplicate.
1647 1727 const root = STATE.roots.find(
1648 1728 (r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'),
@@ -1715,9 +1795,18 @@ async function openSidebar (item)
1715 1795
1716 1796 // Fetch and render duplicate files.
1717 1797 renderSidebarDuplicates(item, null); // show loading state
1798 const selectedPathAtRequest = item.path;
1718 1799 api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`)
1719 .then((data) => renderSidebarDuplicates(item, data ? data.duplicates : []))
1720 .catch(() => renderSidebarDuplicates(item, []));
1800 .then((data) =>
1801 {
1802 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
1803 renderSidebarDuplicates(item, data ? data.duplicates : []);
1804 })
1805 .catch(() =>
1806 {
1807 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
1808 renderSidebarDuplicates(item, []);
1809 });
1721 1810
1722 1811 // View / download button
1723 1812 const btnDl = document.createElement('button');
@@ -1834,6 +1923,14 @@ async function openSidebar (item)
1834 1923 btnMove.textContent = 'Move to';
1835 1924 btnMove.addEventListener('click', () => openMovePicker(item));
1836 1925 actions.appendChild(btnMove);
1926
1927 if (!item.isDir)
1928 {
1929 const btnCopy = document.createElement('button');
1930 btnCopy.textContent = 'Copy to';
1931 btnCopy.addEventListener('click', () => openCopyPicker(item));
1932 actions.appendChild(btnCopy);
1933 }
1837 1934 }
1838 1935
1839 1936 const btnRen = document.createElement('button');
@@ -1864,6 +1961,7 @@ function openFolderSidebar ()
1864 1961 const dl = document.getElementById('sidebar-meta');
1865 1962 const actions = document.getElementById('sidebar-actions');
1866 1963 actions.innerHTML = '';
1964 renderSidebarDuplicates(null, null);
1867 1965
1868 1966 if (!STATE.currentDir || !STATE.currentRoot)
1869 1967 {
@@ -1881,8 +1979,9 @@ function openFolderSidebar ()
1881 1979
1882 1980 const dirs = STATE.items.filter(i => i.isDir).length;
1883 1981 const files = STATE.items.length - dirs;
1982 const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label);
1884 1983 const baseDetails = `
1885 <dt>Path</dt><dd>${STATE.currentDir}</dd>
1984 <dt>Path</dt><dd>${displayPath}</dd>
1886 1985 <dt>Folders</dt><dd>${dirs}</dd>
1887 1986 <dt>Files</dt><dd>${files}</dd>
1888 1987 `;
@@ -1980,6 +2079,7 @@ function writableRoots ()
1980 2079 if (STATE.isAdmin) return STATE.roots.slice();
1981 2080 return STATE.roots.filter((r) =>
1982 2081 {
2082 if (r.isUserFolder) return true;
1983 2083 const perm = STATE.permissions[rootPermissionLabel(r)];
1984 2084 return !!(perm && perm.write);
1985 2085 });
@@ -2019,6 +2119,40 @@ async function moveWithConflictResolution (item, targetDir)
2019 2119 }
2020 2120 }
2021 2121
2122 async function copyWithConflictResolution (item, targetDir)
2123 {
2124 try
2125 {
2126 return await api('POST', '/files/copy', { from: item.path, toDir: targetDir });
2127 }
2128 catch (err)
2129 {
2130 if (!/already exists/i.test(err.message || '')) throw err;
2131
2132 const existingNames = await listDirNameSet(targetDir);
2133 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2134 const suggestedName = nextAvailableName(desiredName, existingNames);
2135 const decision = await showFileConflictChoice(desiredName, suggestedName, 'copy');
2136 if (decision === 'cancel') return null;
2137
2138 if (decision === 'overwrite')
2139 {
2140 return api('POST', '/files/copy', {
2141 from: item.path,
2142 toDir: targetDir,
2143 conflict: 'overwrite',
2144 });
2145 }
2146
2147 return api('POST', '/files/copy', {
2148 from: item.path,
2149 toDir: targetDir,
2150 conflict: 'rename',
2151 targetName: suggestedName,
2152 });
2153 }
2154 }
2155
2022 2156 function ensureMoveModal ()
2023 2157 {
2024 2158 let overlay = document.getElementById('move-modal');
@@ -2070,17 +2204,26 @@ function ensureMoveModal ()
2070 2204
2071 2205 try
2072 2206 {
2073 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
2074 if (!moved) return;
2207 if (st.mode === 'copy')
2208 {
2209 const copied = await copyWithConflictResolution(st.item, st.selectedPath);
2210 if (!copied) return;
2211 }
2212 else
2213 {
2214 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
2215 if (!moved) return;
2216 }
2075 2217 }
2076 2218 catch (err)
2077 2219 {
2078 toast('Move failed: ' + err.message, 'err');
2220 const action = st.mode === 'copy' ? 'Copy' : 'Move';
2221 toast(`${action} failed: ${err.message}`, 'err');
2079 2222 return;
2080 2223 }
2081 2224
2082 2225 hide();
2083 if (STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2226 if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2084 2227 navigateTo(STATE.currentDir, STATE.currentRoot);
2085 2228 });
2086 2229
@@ -2165,7 +2308,7 @@ function createMoveNode (folderPath, label)
2165 2308 return node;
2166 2309 }
2167 2310
2168 function openMovePicker (item)
2311 function openDestinationPicker (item, mode)
2169 2312 {
2170 2313 if (!canWrite())
2171 2314 {
@@ -2183,8 +2326,13 @@ function openMovePicker (item)
2183 2326 const overlay = ensureMoveModal();
2184 2327 const tree = overlay.querySelector('#move-tree');
2185 2328 const caption = overlay.querySelector('#move-modal-caption');
2329 const titleEl = overlay.querySelector('h2');
2330 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2186 2331
2187 STATE.movePicker = { item, selectedPath: null };
2332 const op = mode === 'copy' ? 'copy' : 'move';
2333 STATE.movePicker = { item, selectedPath: null, mode: op };
2334 titleEl.textContent = op === 'copy' ? 'Copy To' : 'Move To';
2335 confirmBtn.textContent = op === 'copy' ? 'Copy' : 'Move';
2188 2336 caption.textContent = `Select destination folder for: ${item.name}`;
2189 2337 tree.innerHTML = '';
2190 2338
@@ -2197,6 +2345,16 @@ function openMovePicker (item)
2197 2345 overlay.classList.remove('hidden');
2198 2346 }
2199 2347
2348 function openMovePicker (item)
2349 {
2350 openDestinationPicker(item, 'move');
2351 }
2352
2353 function openCopyPicker (item)
2354 {
2355 openDestinationPicker(item, 'copy');
2356 }
2357
2200 2358 // ───────────────────────────────────────────────────────────────────────────
2201 2359 // FOLDER ICON PICKER
2202 2360 // ───────────────────────────────────────────────────────────────────────────
@@ -3649,6 +3807,16 @@ async function refreshAdminConfig ()
3649 3807 {
3650 3808 const data = await api('GET', '/admin/config');
3651 3809 if (!data) return;
3810
3811 const userPathInput = document.getElementById('admin-user-path');
3812 const sizeInput = document.getElementById('admin-user-size-limit');
3813 if (userPathInput) userPathInput.value = data.userPath || '';
3814 if (sizeInput)
3815 {
3816 sizeInput.value = data.userFolderSizeLimit ? formatBytes(data.userFolderSizeLimit) : '';
3817 updateAdminSizeFeedback(sizeInput.value);
3818 }
3819
3652 3820 const container = document.getElementById('admin-paths');
3653 3821 container.innerHTML = '';
3654 3822 for (const p of data.paths)
@@ -4497,6 +4665,45 @@ function wireEvents ()
4497 4665 } catch (err) { toast(err.message, 'err'); }
4498 4666 });
4499 4667
4668 const sizeInput = document.getElementById('admin-user-size-limit');
4669 if (sizeInput)
4670 {
4671 sizeInput.addEventListener('input', () =>
4672 {
4673 updateAdminSizeFeedback(sizeInput.value);
4674 });
4675 }
4676
4677 document.getElementById('admin-save-userpath').addEventListener('click', async () =>
4678 {
4679 const rows = document.querySelectorAll('#admin-paths .path-row span');
4680 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
4681 const userPath = document.getElementById('admin-user-path').value.trim();
4682 const rawLimit = document.getElementById('admin-user-size-limit').value.trim();
4683 const parsed = updateAdminSizeFeedback(rawLimit);
4684 if (!parsed.valid)
4685 {
4686 toast('Please enter a valid user size limit.', 'err');
4687 return;
4688 }
4689
4690 try
4691 {
4692 await api('PUT', '/admin/config', {
4693 paths,
4694 userPath: userPath || null,
4695 userFolderSizeLimit: rawLimit ? parsed.bytes : null,
4696 });
4697 toast('User folder settings saved.', 'ok');
4698 await loadRoots();
4699 await refreshAdminConfig();
4700 }
4701 catch (err)
4702 {
4703 toast(err.message, 'err');
4704 }
4705 });
4706
4500 4707 // Shutdown / restart server
4501 4708 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4502 4709 {
@@ -578,6 +578,56 @@ function formatBytes (bytes)
578 return (bytes / 1073741824).toFixed(2) + ' GB';
578 return (bytes / 1073741824).toFixed(2) + ' GB';
579}
579}
580
580
581function parseHumanSize (input)
582{
583 const raw = String(input || '').trim();
584 if (!raw) return null;
585
586 const m = raw.match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)(?:i?b)?$/i);
587 if (!m) return null;
588
589 const value = Number(m[1]);
590 if (!Number.isFinite(value) || value <= 0) return null;
591
592 const unit = String(m[2] || '').toLowerCase();
593 const multipliers = {
594 '': 1,
595 k: 1024,
596 m: 1024 * 1024,
597 g: 1024 * 1024 * 1024,
598 t: 1024 * 1024 * 1024 * 1024,
599 };
600 return Math.floor(value * (multipliers[unit] || 1));
601}
602
603function updateAdminSizeFeedback (rawValue)
604{
605 const feedback = document.getElementById('admin-user-size-feedback');
606 if (!feedback) return { bytes: null, valid: true };
607
608 const trimmed = String(rawValue || '').trim();
609 if (!trimmed)
610 {
611 feedback.textContent = '';
612 feedback.classList.add('hidden');
613 feedback.classList.remove('ok', 'err');
614 return { bytes: null, valid: true };
615 }
616
617 const bytes = parseHumanSize(trimmed);
618 feedback.classList.remove('hidden', 'ok', 'err');
619 if (bytes == null)
620 {
621 feedback.textContent = 'Invalid size. Use formats like 25 MB, 1 GB, or 500 KB.';
622 feedback.classList.add('err');
623 return { bytes: null, valid: false };
624 }
625
626 feedback.textContent = `Valid size: ${formatBytes(bytes)}`;
627 feedback.classList.add('ok');
628 return { bytes, valid: true };
629}
630
581function extOf (name)
631function extOf (name)
582{
632{
583 const i = name.lastIndexOf('.');
633 const i = name.lastIndexOf('.');
@@ -610,6 +660,26 @@ function pathInside (child, root)
610 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
660 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
611}
661}
612
662
663function relativePathFromRoot (targetPath, rootPath)
664{
665 if (!targetPath || !rootPath) return String(targetPath || '');
666 if (samePath(targetPath, rootPath)) return '.';
667
668 const prefix = String(rootPath).replace(/[\\/]+$/, '');
669 const rel = String(targetPath).slice(prefix.length).replace(/^[\\/]+/, '');
670 if (!rel) return '.';
671 return rel;
672}
673
674function displayPathWithRootLabel (targetPath, rootPath, rootLabel)
675{
676 const rel = relativePathFromRoot(targetPath, rootPath);
677 const safeRoot = String(rootLabel || '').replace(/^\/+|\/+$/g, '');
678 if (!safeRoot) return '/';
679 if (rel === '.') return `/${safeRoot}`;
680 return `/${safeRoot}/${String(rel).replace(/\\/g, '/')}`;
681}
682
613function splitNameExt (name)
683function splitNameExt (name)
614{
684{
615 const dot = String(name || '').lastIndexOf('.');
685 const dot = String(name || '').lastIndexOf('.');
@@ -1287,14 +1357,11 @@ function renderBreadcrumb ()
1287
1357
1288 if (!STATE.currentDir || !STATE.currentRoot) return;
1358 if (!STATE.currentDir || !STATE.currentRoot) return;
1289
1359
1290 // Build path segments relative to the root
1360 // Build path segments relative to the root.
1291 const rootPath = STATE.currentRoot.path;
1361 const rootPath = STATE.currentRoot.path;
1292 const relative = STATE.currentDir === rootPath
1362 const relative = relativePathFromRoot(STATE.currentDir, rootPath);
1293 ? ''
1363 const segments = relative === '.' ? [] : relative.split(/[\\/]/).filter(Boolean);
1294 : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, '');
1364 const parts = [STATE.currentRoot.label, ...segments];
1295
1296 const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)];
1297 let accumulated = rootPath;
1298
1365
1299 for (let i = 0; i < parts.length; i++)
1366 for (let i = 0; i < parts.length; i++)
1300 {
1367 {
@@ -1307,8 +1374,10 @@ function renderBreadcrumb ()
1307 crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : '');
1374 crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : '');
1308 crumb.textContent = parts[i];
1375 crumb.textContent = parts[i];
1309
1376
1310 // Capture the path for this crumb
1377 // Root crumb points to rootPath; segment crumbs point to their folder.
1311 const capturedPath = i === 0 ? rootPath : accumulated;
1378 const capturedPath = i === 0
1379 ? rootPath
1380 : joinServerPath(rootPath, segments.slice(0, i).join('/'));
1312 crumb.classList.add('crumb-drop-target');
1381 crumb.classList.add('crumb-drop-target');
1313 crumb.dataset.path = capturedPath;
1382 crumb.dataset.path = capturedPath;
1314 if (i < parts.length - 1)
1383 if (i < parts.length - 1)
@@ -1317,14 +1386,6 @@ function renderBreadcrumb ()
1317 }
1386 }
1318
1387
1319 nav.appendChild(crumb);
1388 nav.appendChild(crumb);
1320
1321 // Advance accumulated path (skip for root label)
1322 if (i > 0) accumulated = accumulated + '/' + parts[i];
1323 else if (i === 0 && parts.length > 1)
1324 {
1325 // After root label, next crumb should append the next segment
1326 accumulated = rootPath;
1327 }
1328 }
1389 }
1329}
1390}
1330
1391
@@ -1346,8 +1407,14 @@ async function refreshFolderStats ()
1346 }
1407 }
1347
1408
1348 const used = formatBytes(data.usedBytes);
1409 const used = formatBytes(data.usedBytes);
1349 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
1410 if (data.userFreeBytes != null)
1350 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
1411 {
1412 el.textContent = `Folder usage: ${used} | Free space remaining: ${formatBytes(data.userFreeBytes)}`;
1413 } else
1414 {
1415 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
1416 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
1417 }
1351 el.classList.remove('hidden');
1418 el.classList.remove('hidden');
1352}
1419}
1353
1420
@@ -1588,7 +1655,7 @@ function selectItem (el, item)
1588/**
1655/**
1589 * Renders (or clears) the duplicates panel at the bottom of the sidebar.
1656 * Renders (or clears) the duplicates panel at the bottom of the sidebar.
1590 * @param {object|null} item — the item whose duplicates are shown; null = clear
1657 * @param {object|null} item — the item whose duplicates are shown; null = clear
1591 * @param {Array|null} duplicates — array of {path, name, dir}; null = loading state
1658 * @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state
1592 */
1659 */
1593function renderSidebarDuplicates (item, duplicates)
1660function renderSidebarDuplicates (item, duplicates)
1594{
1661{
@@ -1626,8 +1693,8 @@ function renderSidebarDuplicates (item, duplicates)
1626 const btn = document.createElement('button');
1693 const btn = document.createElement('button');
1627 btn.className = 'sidebar-duplicate-entry';
1694 btn.className = 'sidebar-duplicate-entry';
1628 btn.title = dup.path;
1695 btn.title = dup.path;
1629 // Show the full path; let CSS truncate with ellipsis if it does not fit.
1696 // Show path relative to its root; keep absolute path in the tooltip.
1630 btn.textContent = dup.path;
1697 btn.textContent = dup.relativePath || dup.path;
1631 btn.addEventListener('click', () => navigateToDuplicate(dup));
1698 btn.addEventListener('click', () => navigateToDuplicate(dup));
1632 li.appendChild(btn);
1699 li.appendChild(btn);
1633 list.appendChild(li);
1700 list.appendChild(li);
@@ -1643,6 +1710,19 @@ function renderSidebarDuplicates (item, duplicates)
1643 */
1710 */
1644async function navigateToDuplicate (dup)
1711async function navigateToDuplicate (dup)
1645{
1712{
1713 // If the duplicate lives in the folder already shown, just select it.
1714 if (STATE.currentDir && samePath(dup.dir, STATE.currentDir))
1715 {
1716 const tile = Array.from(document.querySelectorAll('.file-item'))
1717 .find((el) => el.dataset.path === dup.path);
1718 const dupItem = STATE.items.find((i) => i.path === dup.path);
1719 if (tile && dupItem)
1720 {
1721 selectItem(tile, dupItem);
1722 }
1723 return;
1724 }
1725
1646 // Find the root that contains the duplicate.
1726 // Find the root that contains the duplicate.
1647 const root = STATE.roots.find(
1727 const root = STATE.roots.find(
1648 (r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'),
1728 (r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'),
@@ -1715,9 +1795,18 @@ async function openSidebar (item)
1715
1795
1716 // Fetch and render duplicate files.
1796 // Fetch and render duplicate files.
1717 renderSidebarDuplicates(item, null); // show loading state
1797 renderSidebarDuplicates(item, null); // show loading state
1798 const selectedPathAtRequest = item.path;
1718 api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`)
1799 api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`)
1719 .then((data) => renderSidebarDuplicates(item, data ? data.duplicates : []))
1800 .then((data) =>
1720 .catch(() => renderSidebarDuplicates(item, []));
1801 {
1802 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
1803 renderSidebarDuplicates(item, data ? data.duplicates : []);
1804 })
1805 .catch(() =>
1806 {
1807 if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
1808 renderSidebarDuplicates(item, []);
1809 });
1721
1810
1722 // View / download button
1811 // View / download button
1723 const btnDl = document.createElement('button');
1812 const btnDl = document.createElement('button');
@@ -1834,6 +1923,14 @@ async function openSidebar (item)
1834 btnMove.textContent = 'Move to';
1923 btnMove.textContent = 'Move to';
1835 btnMove.addEventListener('click', () => openMovePicker(item));
1924 btnMove.addEventListener('click', () => openMovePicker(item));
1836 actions.appendChild(btnMove);
1925 actions.appendChild(btnMove);
1926
1927 if (!item.isDir)
1928 {
1929 const btnCopy = document.createElement('button');
1930 btnCopy.textContent = 'Copy to';
1931 btnCopy.addEventListener('click', () => openCopyPicker(item));
1932 actions.appendChild(btnCopy);
1933 }
1837 }
1934 }
1838
1935
1839 const btnRen = document.createElement('button');
1936 const btnRen = document.createElement('button');
@@ -1864,6 +1961,7 @@ function openFolderSidebar ()
1864 const dl = document.getElementById('sidebar-meta');
1961 const dl = document.getElementById('sidebar-meta');
1865 const actions = document.getElementById('sidebar-actions');
1962 const actions = document.getElementById('sidebar-actions');
1866 actions.innerHTML = '';
1963 actions.innerHTML = '';
1964 renderSidebarDuplicates(null, null);
1867
1965
1868 if (!STATE.currentDir || !STATE.currentRoot)
1966 if (!STATE.currentDir || !STATE.currentRoot)
1869 {
1967 {
@@ -1881,8 +1979,9 @@ function openFolderSidebar ()
1881
1979
1882 const dirs = STATE.items.filter(i => i.isDir).length;
1980 const dirs = STATE.items.filter(i => i.isDir).length;
1883 const files = STATE.items.length - dirs;
1981 const files = STATE.items.length - dirs;
1982 const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label);
1884 const baseDetails = `
1983 const baseDetails = `
1885 <dt>Path</dt><dd>${STATE.currentDir}</dd>
1984 <dt>Path</dt><dd>${displayPath}</dd>
1886 <dt>Folders</dt><dd>${dirs}</dd>
1985 <dt>Folders</dt><dd>${dirs}</dd>
1887 <dt>Files</dt><dd>${files}</dd>
1986 <dt>Files</dt><dd>${files}</dd>
1888 `;
1987 `;
@@ -1980,6 +2079,7 @@ function writableRoots ()
1980 if (STATE.isAdmin) return STATE.roots.slice();
2079 if (STATE.isAdmin) return STATE.roots.slice();
1981 return STATE.roots.filter((r) =>
2080 return STATE.roots.filter((r) =>
1982 {
2081 {
2082 if (r.isUserFolder) return true;
1983 const perm = STATE.permissions[rootPermissionLabel(r)];
2083 const perm = STATE.permissions[rootPermissionLabel(r)];
1984 return !!(perm && perm.write);
2084 return !!(perm && perm.write);
1985 });
2085 });
@@ -2019,6 +2119,40 @@ async function moveWithConflictResolution (item, targetDir)
2019 }
2119 }
2020}
2120}
2021
2121
2122async function copyWithConflictResolution (item, targetDir)
2123{
2124 try
2125 {
2126 return await api('POST', '/files/copy', { from: item.path, toDir: targetDir });
2127 }
2128 catch (err)
2129 {
2130 if (!/already exists/i.test(err.message || '')) throw err;
2131
2132 const existingNames = await listDirNameSet(targetDir);
2133 const desiredName = item.name || basenameOfPath(item.path) || 'file';
2134 const suggestedName = nextAvailableName(desiredName, existingNames);
2135 const decision = await showFileConflictChoice(desiredName, suggestedName, 'copy');
2136 if (decision === 'cancel') return null;
2137
2138 if (decision === 'overwrite')
2139 {
2140 return api('POST', '/files/copy', {
2141 from: item.path,
2142 toDir: targetDir,
2143 conflict: 'overwrite',
2144 });
2145 }
2146
2147 return api('POST', '/files/copy', {
2148 from: item.path,
2149 toDir: targetDir,
2150 conflict: 'rename',
2151 targetName: suggestedName,
2152 });
2153 }
2154}
2155
2022function ensureMoveModal ()
2156function ensureMoveModal ()
2023{
2157{
2024 let overlay = document.getElementById('move-modal');
2158 let overlay = document.getElementById('move-modal');
@@ -2070,17 +2204,26 @@ function ensureMoveModal ()
2070
2204
2071 try
2205 try
2072 {
2206 {
2073 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
2207 if (st.mode === 'copy')
2074 if (!moved) return;
2208 {
2209 const copied = await copyWithConflictResolution(st.item, st.selectedPath);
2210 if (!copied) return;
2211 }
2212 else
2213 {
2214 const moved = await moveWithConflictResolution(st.item, st.selectedPath);
2215 if (!moved) return;
2216 }
2075 }
2217 }
2076 catch (err)
2218 catch (err)
2077 {
2219 {
2078 toast('Move failed: ' + err.message, 'err');
2220 const action = st.mode === 'copy' ? 'Copy' : 'Move';
2221 toast(`${action} failed: ${err.message}`, 'err');
2079 return;
2222 return;
2080 }
2223 }
2081
2224
2082 hide();
2225 hide();
2083 if (STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2226 if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2084 navigateTo(STATE.currentDir, STATE.currentRoot);
2227 navigateTo(STATE.currentDir, STATE.currentRoot);
2085 });
2228 });
2086
2229
@@ -2165,7 +2308,7 @@ function createMoveNode (folderPath, label)
2165 return node;
2308 return node;
2166}
2309}
2167
2310
2168function openMovePicker (item)
2311function openDestinationPicker (item, mode)
2169{
2312{
2170 if (!canWrite())
2313 if (!canWrite())
2171 {
2314 {
@@ -2183,8 +2326,13 @@ function openMovePicker (item)
2183 const overlay = ensureMoveModal();
2326 const overlay = ensureMoveModal();
2184 const tree = overlay.querySelector('#move-tree');
2327 const tree = overlay.querySelector('#move-tree');
2185 const caption = overlay.querySelector('#move-modal-caption');
2328 const caption = overlay.querySelector('#move-modal-caption');
2329 const titleEl = overlay.querySelector('h2');
2330 const confirmBtn = overlay.querySelector('#move-modal-confirm');
2186
2331
2187 STATE.movePicker = { item, selectedPath: null };
2332 const op = mode === 'copy' ? 'copy' : 'move';
2333 STATE.movePicker = { item, selectedPath: null, mode: op };
2334 titleEl.textContent = op === 'copy' ? 'Copy To' : 'Move To';
2335 confirmBtn.textContent = op === 'copy' ? 'Copy' : 'Move';
2188 caption.textContent = `Select destination folder for: ${item.name}`;
2336 caption.textContent = `Select destination folder for: ${item.name}`;
2189 tree.innerHTML = '';
2337 tree.innerHTML = '';
2190
2338
@@ -2197,6 +2345,16 @@ function openMovePicker (item)
2197 overlay.classList.remove('hidden');
2345 overlay.classList.remove('hidden');
2198}
2346}
2199
2347
2348function openMovePicker (item)
2349{
2350 openDestinationPicker(item, 'move');
2351}
2352
2353function openCopyPicker (item)
2354{
2355 openDestinationPicker(item, 'copy');
2356}
2357
2200// ───────────────────────────────────────────────────────────────────────────
2358// ───────────────────────────────────────────────────────────────────────────
2201// FOLDER ICON PICKER
2359// FOLDER ICON PICKER
2202// ───────────────────────────────────────────────────────────────────────────
2360// ───────────────────────────────────────────────────────────────────────────
@@ -3649,6 +3807,16 @@ async function refreshAdminConfig ()
3649{
3807{
3650 const data = await api('GET', '/admin/config');
3808 const data = await api('GET', '/admin/config');
3651 if (!data) return;
3809 if (!data) return;
3810
3811 const userPathInput = document.getElementById('admin-user-path');
3812 const sizeInput = document.getElementById('admin-user-size-limit');
3813 if (userPathInput) userPathInput.value = data.userPath || '';
3814 if (sizeInput)
3815 {
3816 sizeInput.value = data.userFolderSizeLimit ? formatBytes(data.userFolderSizeLimit) : '';
3817 updateAdminSizeFeedback(sizeInput.value);
3818 }
3819
3652 const container = document.getElementById('admin-paths');
3820 const container = document.getElementById('admin-paths');
3653 container.innerHTML = '';
3821 container.innerHTML = '';
3654 for (const p of data.paths)
3822 for (const p of data.paths)
@@ -4497,6 +4665,45 @@ function wireEvents ()
4497 } catch (err) { toast(err.message, 'err'); }
4665 } catch (err) { toast(err.message, 'err'); }
4498 });
4666 });
4499
4667
4668 const sizeInput = document.getElementById('admin-user-size-limit');
4669 if (sizeInput)
4670 {
4671 sizeInput.addEventListener('input', () =>
4672 {
4673 updateAdminSizeFeedback(sizeInput.value);
4674 });
4675 }
4676
4677 document.getElementById('admin-save-userpath').addEventListener('click', async () =>
4678 {
4679 const rows = document.querySelectorAll('#admin-paths .path-row span');
4680 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
4681 const userPath = document.getElementById('admin-user-path').value.trim();
4682 const rawLimit = document.getElementById('admin-user-size-limit').value.trim();
4683 const parsed = updateAdminSizeFeedback(rawLimit);
4684 if (!parsed.valid)
4685 {
4686 toast('Please enter a valid user size limit.', 'err');
4687 return;
4688 }
4689
4690 try
4691 {
4692 await api('PUT', '/admin/config', {
4693 paths,
4694 userPath: userPath || null,
4695 userFolderSizeLimit: rawLimit ? parsed.bytes : null,
4696 });
4697 toast('User folder settings saved.', 'ok');
4698 await loadRoots();
4699 await refreshAdminConfig();
4700 }
4701 catch (err)
4702 {
4703 toast(err.message, 'err');
4704 }
4705 });
4706
4500 // Shutdown / restart server
4707 // Shutdown / restart server
4501 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4708 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4502 {
4709 {
public/index.html +14 −2
@@ -22,11 +22,11 @@
22 22 <form id="auth-form" autocomplete="off">
23 23 <label>
24 24 Username
25 <input id="auth-username" type="text" autocomplete="username" required />
25 <input id="auth-username" name="username" type="text" autocomplete="username" required />
26 26 </label>
27 27 <label>
28 28 Password
29 <input id="auth-password" type="password" autocomplete="current-password" required />
29 <input id="auth-password" name="password" type="password" autocomplete="current-password" required />
30 30 </label>
31 31 <p id="auth-error" class="error hidden"></p>
32 32 <button type="submit" id="auth-submit">Sign In</button>
@@ -145,6 +145,18 @@
145 145 <button class="modal-close" id="admin-modal-close" aria-label="Close admin panel">✕</button>
146 146 <h2>Admin Panel</h2>
147 147
148 <section id="admin-userfolder-section">
149 <h3>User Folders</h3>
150 <label>User folder path
151 <input id="admin-user-path" type="text" placeholder="/data/userfolders" />
152 </label>
153 <label>Size limit per user
154 <input id="admin-user-size-limit" type="text" placeholder="e.g. 25 MB or 1 GB" />
155 </label>
156 <p id="admin-user-size-feedback" class="admin-size-feedback hidden"></p>
157 <button id="admin-save-userpath" class="primary">Save user folder settings</button>
158 </section>
159
148 160 <section>
149 161 <h3>Configured Paths</h3>
150 162 <div id="admin-paths"></div>
@@ -22,11 +22,11 @@
22 <form id="auth-form" autocomplete="off">
22 <form id="auth-form" autocomplete="off">
23 <label>
23 <label>
24 Username
24 Username
25 <input id="auth-username" type="text" autocomplete="username" required />
25 <input id="auth-username" name="username" type="text" autocomplete="username" required />
26 </label>
26 </label>
27 <label>
27 <label>
28 Password
28 Password
29 <input id="auth-password" type="password" autocomplete="current-password" required />
29 <input id="auth-password" name="password" type="password" autocomplete="current-password" required />
30 </label>
30 </label>
31 <p id="auth-error" class="error hidden"></p>
31 <p id="auth-error" class="error hidden"></p>
32 <button type="submit" id="auth-submit">Sign In</button>
32 <button type="submit" id="auth-submit">Sign In</button>
@@ -145,6 +145,18 @@
145 <button class="modal-close" id="admin-modal-close" aria-label="Close admin panel">✕</button>
145 <button class="modal-close" id="admin-modal-close" aria-label="Close admin panel">✕</button>
146 <h2>Admin Panel</h2>
146 <h2>Admin Panel</h2>
147
147
148 <section id="admin-userfolder-section">
149 <h3>User Folders</h3>
150 <label>User folder path
151 <input id="admin-user-path" type="text" placeholder="/data/userfolders" />
152 </label>
153 <label>Size limit per user
154 <input id="admin-user-size-limit" type="text" placeholder="e.g. 25 MB or 1 GB" />
155 </label>
156 <p id="admin-user-size-feedback" class="admin-size-feedback hidden"></p>
157 <button id="admin-save-userpath" class="primary">Save user folder settings</button>
158 </section>
159
148 <section>
160 <section>
149 <h3>Configured Paths</h3>
161 <h3>Configured Paths</h3>
150 <div id="admin-paths"></div>
162 <div id="admin-paths"></div>
public/style.css +40 −0
@@ -490,6 +490,21 @@ button.danger:hover {
490 490 background: var(--border);
491 491 }
492 492
493 .admin-size-feedback {
494 font-size: 0.82rem;
495 margin: 0.25rem 0 0.5rem;
496 padding: 0.25rem 0.5rem;
497 border-radius: var(--radius);
498 }
499
500 .admin-size-feedback.ok {
501 color: var(--accent);
502 }
503
504 .admin-size-feedback.err {
505 color: #e55;
506 }
507
493 508 /* =========================================================
494 509 MODALS
495 510 ========================================================= */
@@ -763,6 +778,31 @@ button.danger:hover {
763 778 border-color: var(--accent);
764 779 }
765 780
781 /* Admin user-folder controls use the same visual language as modal forms. */
782 #admin-userfolder-section label {
783 display: flex;
784 flex-direction: column;
785 gap: 0.3rem;
786 font-size: 0.85rem;
787 color: var(--text-muted);
788 margin-bottom: 0.9rem;
789 }
790
791 #admin-userfolder-section input[type="text"] {
792 background: var(--bg);
793 border: 1px solid var(--border);
794 border-radius: 6px;
795 padding: 0.5rem 0.75rem;
796 color: var(--text);
797 font-size: 0.95rem;
798 outline: none;
799 transition: border-color var(--transition);
800 }
801
802 #admin-userfolder-section input[type="text"]:focus {
803 border-color: var(--accent);
804 }
805
766 806 /* =========================================================
767 807 FILE PREVIEW — SHARED MEDIA STYLES
768 808 ========================================================= */
@@ -490,6 +490,21 @@ button.danger:hover {
490 background: var(--border);
490 background: var(--border);
491}
491}
492
492
493.admin-size-feedback {
494 font-size: 0.82rem;
495 margin: 0.25rem 0 0.5rem;
496 padding: 0.25rem 0.5rem;
497 border-radius: var(--radius);
498}
499
500.admin-size-feedback.ok {
501 color: var(--accent);
502}
503
504.admin-size-feedback.err {
505 color: #e55;
506}
507
493/* =========================================================
508/* =========================================================
494 MODALS
509 MODALS
495 ========================================================= */
510 ========================================================= */
@@ -763,6 +778,31 @@ button.danger:hover {
763 border-color: var(--accent);
778 border-color: var(--accent);
764}
779}
765
780
781/* Admin user-folder controls use the same visual language as modal forms. */
782#admin-userfolder-section label {
783 display: flex;
784 flex-direction: column;
785 gap: 0.3rem;
786 font-size: 0.85rem;
787 color: var(--text-muted);
788 margin-bottom: 0.9rem;
789}
790
791#admin-userfolder-section input[type="text"] {
792 background: var(--bg);
793 border: 1px solid var(--border);
794 border-radius: 6px;
795 padding: 0.5rem 0.75rem;
796 color: var(--text);
797 font-size: 0.95rem;
798 outline: none;
799 transition: border-color var(--transition);
800}
801
802#admin-userfolder-section input[type="text"]:focus {
803 border-color: var(--accent);
804}
805
766/* =========================================================
806/* =========================================================
767 FILE PREVIEW — SHARED MEDIA STYLES
807 FILE PREVIEW — SHARED MEDIA STYLES
768 ========================================================= */
808 ========================================================= */
server/routes/admin.js +77 −4
@@ -2,6 +2,7 @@
2 2
3 3 const express = require('express');
4 4 const bcrypt = require('bcrypt');
5 const fs = require('fs');
5 6 const path = require('path');
6 7 const { execFile } = require('child_process');
7 8 const { promisify } = require('util');
@@ -10,6 +11,37 @@ const router = express.Router();
10 11 const execFileAsync = promisify(execFile);
11 12 const PROJECT_ROOT = path.resolve(__dirname, '../../');
12 13
14 /**
15 * Ensures that a personal subfolder exists for each registered user under userPath.
16 * Non-fatal: logs errors but does not throw.
17 */
18 function ensureUserFolders (userPath)
19 {
20 if (!userPath) return;
21 try
22 {
23 fs.mkdirSync(userPath, { recursive: true });
24 } catch (err)
25 {
26 console.error('Failed to create user folder root:', err.message);
27 return;
28 }
29
30 const db = require('../db').getDb();
31 const users = db.prepare('SELECT username FROM users').all();
32 for (const { username } of users)
33 {
34 const folder = path.join(userPath, username);
35 try
36 {
37 fs.mkdirSync(folder, { recursive: true });
38 } catch (err)
39 {
40 console.error(`Failed to create user folder for ${username}:`, err.message);
41 }
42 }
43 }
44
13 45 const { getDb } = require('../db');
14 46 const { requireAuth, requireAdmin } = require('../auth');
15 47 const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
@@ -78,6 +110,14 @@ router.post('/users', (req, res) =>
78 110 [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)]
79 111 );
80 112
113 // Create personal folder for the new user if a userPath is configured.
114 const config = loadConfig();
115 if (config.userPath)
116 {
117 const folder = path.join(config.userPath, username);
118 try { fs.mkdirSync(folder, { recursive: true }); } catch { /* non-fatal */ }
119 }
120
81 121 res.status(201).json({ ok: true });
82 122 });
83 123
@@ -155,27 +195,34 @@ router.delete('/users/:id', (req, res) =>
155 195
156 196 // ---------------------------------------------------------------------------
157 197 // GET /api/admin/config
158 // Returns the current server config (paths, port).
198 // Returns the current server config (paths, port, userPath, userFolderSizeLimit).
159 199 // ---------------------------------------------------------------------------
160 200 router.get('/config', (req, res) =>
161 201 {
162 202 const config = loadConfig();
163 203 const effective = getEffectivePaths(config.paths || []);
164 res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective });
204 res.json({
205 port: config.port || 3000,
206 paths: config.paths || [],
207 effectivePaths: effective,
208 userPath: config.userPath || null,
209 userFolderSizeLimit: config.userFolderSizeLimit || null,
210 });
165 211 });
166 212
167 213 // ---------------------------------------------------------------------------
168 214 // PUT /api/admin/config
169 // Body: { paths: [...], port: number }
215 // Body: { paths: [...], port: number, userPath: string|null, userFolderSizeLimit: number|null }
170 216 // Saves the config.
171 217 // ---------------------------------------------------------------------------
172 218 router.put('/config', (req, res) =>
173 219 {
174 const { paths, port } = req.body;
220 const { paths, port, userPath, userFolderSizeLimit } = req.body;
175 221 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
176 222
177 223 const config = loadConfig();
178 224 config.paths = paths.map(p => p.trim()).filter(Boolean);
225
179 226 if (port !== undefined)
180 227 {
181 228 const p = parseInt(port, 10);
@@ -183,6 +230,28 @@ router.put('/config', (req, res) =>
183 230 config.port = p;
184 231 }
185 232
233 // userPath — a single directory for per-user storage.
234 // Only update when explicitly provided so path-only saves do not clear it.
235 if (userPath !== undefined)
236 {
237 const cleanUserPath = typeof userPath === 'string' ? userPath.trim() : '';
238 config.userPath = cleanUserPath || null;
239 }
240
241 // userFolderSizeLimit — stored as bytes (number) or null = unlimited.
242 // Only update when explicitly provided.
243 if (userFolderSizeLimit !== undefined)
244 {
245 if (userFolderSizeLimit === null)
246 {
247 config.userFolderSizeLimit = null;
248 } else
249 {
250 const lim = Number(userFolderSizeLimit);
251 config.userFolderSizeLimit = Number.isFinite(lim) && lim > 0 ? lim : null;
252 }
253 }
254
186 255 try
187 256 {
188 257 saveConfig(config);
@@ -190,6 +259,10 @@ router.put('/config', (req, res) =>
190 259 {
191 260 return res.status(500).json({ error: `Failed to save config: ${err.message}` });
192 261 }
262
263 // Ensure personal subfolders exist for all current users.
264 if (config.userPath) ensureUserFolders(config.userPath);
265
193 266 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
194 267 });
195 268
@@ -2,6 +2,7 @@
2
2
3const express = require('express');
3const express = require('express');
4const bcrypt = require('bcrypt');
4const bcrypt = require('bcrypt');
5const fs = require('fs');
5const path = require('path');
6const path = require('path');
6const { execFile } = require('child_process');
7const { execFile } = require('child_process');
7const { promisify } = require('util');
8const { promisify } = require('util');
@@ -10,6 +11,37 @@ const router = express.Router();
10const execFileAsync = promisify(execFile);
11const execFileAsync = promisify(execFile);
11const PROJECT_ROOT = path.resolve(__dirname, '../../');
12const PROJECT_ROOT = path.resolve(__dirname, '../../');
12
13
14/**
15 * Ensures that a personal subfolder exists for each registered user under userPath.
16 * Non-fatal: logs errors but does not throw.
17 */
18function ensureUserFolders (userPath)
19{
20 if (!userPath) return;
21 try
22 {
23 fs.mkdirSync(userPath, { recursive: true });
24 } catch (err)
25 {
26 console.error('Failed to create user folder root:', err.message);
27 return;
28 }
29
30 const db = require('../db').getDb();
31 const users = db.prepare('SELECT username FROM users').all();
32 for (const { username } of users)
33 {
34 const folder = path.join(userPath, username);
35 try
36 {
37 fs.mkdirSync(folder, { recursive: true });
38 } catch (err)
39 {
40 console.error(`Failed to create user folder for ${username}:`, err.message);
41 }
42 }
43}
44
13const { getDb } = require('../db');
45const { getDb } = require('../db');
14const { requireAuth, requireAdmin } = require('../auth');
46const { requireAuth, requireAdmin } = require('../auth');
15const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
47const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
@@ -78,6 +110,14 @@ router.post('/users', (req, res) =>
78 [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)]
110 [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)]
79 );
111 );
80
112
113 // Create personal folder for the new user if a userPath is configured.
114 const config = loadConfig();
115 if (config.userPath)
116 {
117 const folder = path.join(config.userPath, username);
118 try { fs.mkdirSync(folder, { recursive: true }); } catch { /* non-fatal */ }
119 }
120
81 res.status(201).json({ ok: true });
121 res.status(201).json({ ok: true });
82});
122});
83
123
@@ -155,27 +195,34 @@ router.delete('/users/:id', (req, res) =>
155
195
156// ---------------------------------------------------------------------------
196// ---------------------------------------------------------------------------
157// GET /api/admin/config
197// GET /api/admin/config
158// Returns the current server config (paths, port).
198// Returns the current server config (paths, port, userPath, userFolderSizeLimit).
159// ---------------------------------------------------------------------------
199// ---------------------------------------------------------------------------
160router.get('/config', (req, res) =>
200router.get('/config', (req, res) =>
161{
201{
162 const config = loadConfig();
202 const config = loadConfig();
163 const effective = getEffectivePaths(config.paths || []);
203 const effective = getEffectivePaths(config.paths || []);
164 res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective });
204 res.json({
205 port: config.port || 3000,
206 paths: config.paths || [],
207 effectivePaths: effective,
208 userPath: config.userPath || null,
209 userFolderSizeLimit: config.userFolderSizeLimit || null,
210 });
165});
211});
166
212
167// ---------------------------------------------------------------------------
213// ---------------------------------------------------------------------------
168// PUT /api/admin/config
214// PUT /api/admin/config
169// Body: { paths: [...], port: number }
215// Body: { paths: [...], port: number, userPath: string|null, userFolderSizeLimit: number|null }
170// Saves the config.
216// Saves the config.
171// ---------------------------------------------------------------------------
217// ---------------------------------------------------------------------------
172router.put('/config', (req, res) =>
218router.put('/config', (req, res) =>
173{
219{
174 const { paths, port } = req.body;
220 const { paths, port, userPath, userFolderSizeLimit } = req.body;
175 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
221 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
176
222
177 const config = loadConfig();
223 const config = loadConfig();
178 config.paths = paths.map(p => p.trim()).filter(Boolean);
224 config.paths = paths.map(p => p.trim()).filter(Boolean);
225
179 if (port !== undefined)
226 if (port !== undefined)
180 {
227 {
181 const p = parseInt(port, 10);
228 const p = parseInt(port, 10);
@@ -183,6 +230,28 @@ router.put('/config', (req, res) =>
183 config.port = p;
230 config.port = p;
184 }
231 }
185
232
233 // userPath — a single directory for per-user storage.
234 // Only update when explicitly provided so path-only saves do not clear it.
235 if (userPath !== undefined)
236 {
237 const cleanUserPath = typeof userPath === 'string' ? userPath.trim() : '';
238 config.userPath = cleanUserPath || null;
239 }
240
241 // userFolderSizeLimit — stored as bytes (number) or null = unlimited.
242 // Only update when explicitly provided.
243 if (userFolderSizeLimit !== undefined)
244 {
245 if (userFolderSizeLimit === null)
246 {
247 config.userFolderSizeLimit = null;
248 } else
249 {
250 const lim = Number(userFolderSizeLimit);
251 config.userFolderSizeLimit = Number.isFinite(lim) && lim > 0 ? lim : null;
252 }
253 }
254
186 try
255 try
187 {
256 {
188 saveConfig(config);
257 saveConfig(config);
@@ -190,6 +259,10 @@ router.put('/config', (req, res) =>
190 {
259 {
191 return res.status(500).json({ error: `Failed to save config: ${err.message}` });
260 return res.status(500).json({ error: `Failed to save config: ${err.message}` });
192 }
261 }
262
263 // Ensure personal subfolders exist for all current users.
264 if (config.userPath) ensureUserFolders(config.userPath);
265
193 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
266 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
194});
267});
195
268
server/routes/files.js +314 −70
@@ -190,6 +190,25 @@ function effectivePaths ()
190 190 return getEffectivePaths(loadConfig().paths || []);
191 191 }
192 192
193 /**
194 * Loads config and returns { config, roots } together so both are consistent
195 * and user-folder checks can be performed in route handlers.
196 */
197 function loadConfigAndRoots ()
198 {
199 const config = loadConfig();
200 return { config, roots: getEffectivePaths(config.paths || []) };
201 }
202
203 /**
204 * Returns true when absPath is accessible to the user (either via a
205 * configured root or their personal folder).
206 */
207 function isAccessiblePath (absPath, roots, user, config)
208 {
209 return resolveRootForUser(absPath, roots, user, config) !== null;
210 }
211
193 212 function rootAliasesFromConfig (config)
194 213 {
195 214 if (!config || typeof config !== 'object') return {};
@@ -268,6 +287,103 @@ function canWrite (user, pathLabel)
268 287 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
269 288 }
270 289
290 // ---------------------------------------------------------------------------
291 // User folder helpers
292 // ---------------------------------------------------------------------------
293
294 /**
295 * Returns the absolute path of the user's personal folder, or null.
296 * e.g. /data/userfolders/<username>
297 */
298 function getUserFolderPath (config, username)
299 {
300 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
301 if (!base) return null;
302 return path.join(base, String(username));
303 }
304
305 /**
306 * Resolves a request path against both the configured roots AND the user's
307 * personal folder. Returns { root, label, isUserFolder } or null.
308 * - isUserFolder: true when the path is inside the user's personal folder.
309 */
310 function resolveRootForUser (absPath, roots, user, config)
311 {
312 // Regular configured roots first.
313 const matched = getAllowedRoot(absPath, roots);
314 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
315
316 // Check user personal folder.
317 if (!user || !user.username) return null;
318 const userFolder = getUserFolderPath(config, user.username);
319 if (!userFolder) return null;
320
321 const resolved = path.resolve(absPath);
322 const resolvedFolder = path.resolve(userFolder);
323 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
324 {
325 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
326 }
327
328 return null;
329 }
330
331 /**
332 * Checks whether the user has READ access to the resolved root info object
333 * returned by resolveRootForUser.
334 */
335 function canReadInfo (user, info)
336 {
337 if (!info) return false;
338 if (info.isUserFolder) return true; // owner always has full access
339 return canRead(user, info.label);
340 }
341
342 /**
343 * Checks whether the user has WRITE access to the resolved root info object.
344 */
345 function canWriteInfo (user, info)
346 {
347 if (!info) return false;
348 if (info.isUserFolder) return true;
349 return canWrite(user, info.label);
350 }
351
352 /**
353 * Returns the size limit (bytes) for the user's personal folder, or null = unlimited.
354 */
355 function getUserFolderSizeLimit (config)
356 {
357 const lim = Number(config.userFolderSizeLimit);
358 return Number.isFinite(lim) && lim > 0 ? lim : null;
359 }
360
361 /**
362 * Returns an error message if adding `addedBytes` to the user's folder would
363 * exceed the size limit, or null if within limits.
364 */
365 function checkUserFolderSizeLimit (config, username, addedBytes)
366 {
367 const limit = getUserFolderSizeLimit(config);
368 if (!limit) return null;
369 const userFolder = getUserFolderPath(config, username);
370 if (!userFolder) return null;
371 const currentSize = getRecursiveSize(userFolder);
372 if (currentSize + addedBytes > limit)
373 {
374 return `Your personal folder is full (limit ${formatBytesServer(limit)}, used ${formatBytesServer(currentSize)}).`;
375 }
376 return null;
377 }
378
379 function formatBytesServer (bytes)
380 {
381 if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
382 if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
383 if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
384 return `${bytes} B`;
385 }
386
271 387 /**
272 388 * Given an absolute path and the effective-paths list, return
273 389 * { root, label } where label is the base-name of the root, or null.
@@ -395,6 +511,7 @@ function removePathRecursive (targetPath)
395 511 // ---------------------------------------------------------------------------
396 512 // GET /api/files/roots
397 513 // Returns the effective configured paths the user can read.
514 // Also injects the user's personal folder when userPath is configured.
398 515 // ---------------------------------------------------------------------------
399 516 router.get('/roots', requireAuth, (req, res) =>
400 517 {
@@ -415,6 +532,24 @@ router.get('/roots', requireAuth, (req, res) =>
415 532 alias: alias || null,
416 533 };
417 534 });
535
536 // Inject the user's personal folder when a userPath is configured.
537 if (req.user && req.user.username)
538 {
539 const userFolder = getUserFolderPath(config, req.user.username);
540 if (userFolder)
541 {
542 try { fs.mkdirSync(userFolder, { recursive: true }); } catch { /* non-fatal */ }
543 readable.unshift({
544 label: 'My Folder',
545 path: userFolder,
546 originalName: req.user.username,
547 alias: 'My Folder',
548 isUserFolder: true,
549 });
550 }
551 }
552
418 553 res.json({ roots: readable });
419 554 });
420 555
@@ -552,10 +687,9 @@ router.get('/list', requireAuth, (req, res) =>
552 687 const dir = req.query.dir;
553 688 if (!dir) return res.status(400).json({ error: 'dir is required.' });
554 689
555 const roots = effectivePaths();
556 const info = resolveRoot(dir, roots);
557 if (!info) return res.status(403).json({ error: 'Access denied.' });
558 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
690 const { config, roots } = loadConfigAndRoots();
691 const info = resolveRootForUser(dir, roots, req.user, config);
692 if (!info || !canReadInfo(req.user, info)) return res.status(403).json({ error: 'Access denied.' });
559 693
560 694 let entries;
561 695 try
@@ -599,9 +733,9 @@ router.get('/meta', requireAuth, async (req, res) =>
599 733 const file = req.query.file;
600 734 if (!file) return res.status(400).json({ error: 'file is required.' });
601 735
602 const roots = effectivePaths();
603 const info = resolveRoot(file, roots);
604 if (!info || !canRead(req.user, info.label))
736 const { config, roots } = loadConfigAndRoots();
737 const info = resolveRootForUser(file, roots, req.user, config);
738 if (!info || !canReadInfo(req.user, info))
605 739 {
606 740 return res.status(403).json({ error: 'Access denied.' });
607 741 }
@@ -660,9 +794,9 @@ router.get('/duplicates', requireAuth, (req, res) =>
660 794 const file = req.query.file;
661 795 if (!file) return res.status(400).json({ error: 'file is required.' });
662 796
663 const roots = effectivePaths();
664 const info = resolveRoot(file, roots);
665 if (!info || !canRead(req.user, info.label))
797 const { config, roots } = loadConfigAndRoots();
798 const info = resolveRootForUser(file, roots, req.user, config);
799 if (!info || !canReadInfo(req.user, info))
666 800 {
667 801 return res.status(403).json({ error: 'Access denied.' });
668 802 }
@@ -680,21 +814,23 @@ router.get('/duplicates', requireAuth, (req, res) =>
680 814 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
681 815 ).all([hash, file]);
682 816
683 const readable = roots.filter((r) => canRead(req.user, path.basename(r)));
684
685 817 const duplicates = [];
686 818 for (const { file_path } of candidates)
687 819 {
688 820 // Only return files inside a root the user can access and that still exist on disk.
689 const allowedRoot = readable.find(
690 (r) => file_path === r || (file_path.startsWith(r) && (file_path[r.length] === path.sep || file_path[r.length] === '/')),
691 );
692 if (!allowedRoot) continue;
821 const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
822 if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue;
693 823 if (!fs.existsSync(file_path)) continue;
824
825 const rel = path.relative(dupInfo.root, file_path);
826 const relativePath = rel && rel !== '' ? rel : path.basename(file_path);
827
694 828 duplicates.push({
695 829 path: file_path,
696 830 name: path.basename(file_path),
697 831 dir: path.dirname(file_path),
832 rootPath: dupInfo.root,
833 relativePath,
698 834 });
699 835 }
700 836
@@ -710,9 +846,9 @@ router.get('/space', requireAuth, (req, res) =>
710 846 const dir = req.query.dir;
711 847 if (!dir) return res.status(400).json({ error: 'dir is required.' });
712 848
713 const roots = effectivePaths();
714 const info = resolveRoot(dir, roots);
715 if (!info || !canRead(req.user, info.label))
849 const { config, roots } = loadConfigAndRoots();
850 const info = resolveRootForUser(dir, roots, req.user, config);
851 if (!info || !canReadInfo(req.user, info))
716 852 {
717 853 return res.status(403).json({ error: 'Access denied.' });
718 854 }
@@ -724,9 +860,13 @@ router.get('/space', requireAuth, (req, res) =>
724 860
725 861 const usedBytes = getRecursiveSize(dir);
726 862 const freeBytes = getFreeBytes(info.root);
863 const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null;
864 const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes);
727 865 res.json({
728 866 usedBytes,
729 867 freeBytes,
868 userLimitBytes,
869 userFreeBytes,
730 870 rootPath: info.root,
731 871 rootLabel: info.label,
732 872 });
@@ -741,9 +881,9 @@ router.get('/download', requireAuth, (req, res) =>
741 881 const file = req.query.file;
742 882 if (!file) return res.status(400).json({ error: 'file is required.' });
743 883
744 const roots = effectivePaths();
745 const info = resolveRoot(file, roots);
746 if (!info || !canRead(req.user, info.label))
884 const { config, roots } = loadConfigAndRoots();
885 const info = resolveRootForUser(file, roots, req.user, config);
886 if (!info || !canReadInfo(req.user, info))
747 887 {
748 888 return res.status(403).json({ error: 'Access denied.' });
749 889 }
@@ -791,9 +931,9 @@ router.post('/watch-progress', requireAuth, (req, res) =>
791 931 return res.json({ ok: true, updated: false });
792 932 }
793 933
794 const roots = effectivePaths();
795 const info = resolveRoot(filePath, roots);
796 if (!info || !canRead(req.user, info.label))
934 const { config, roots } = loadConfigAndRoots();
935 const info = resolveRootForUser(filePath, roots, req.user, config);
936 if (!info || !canReadInfo(req.user, info))
797 937 {
798 938 return res.status(403).json({ error: 'Access denied.' });
799 939 }
@@ -838,9 +978,9 @@ router.post('/video-stream', requireAuth, async (req, res, next) =>
838 978 const filePath = String(req.body?.filePath || '').trim();
839 979 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
840 980
841 const roots = effectivePaths();
842 const info = resolveRoot(filePath, roots);
843 if (!info || !canRead(req.user, info.label))
981 const { config, roots } = loadConfigAndRoots();
982 const info = resolveRootForUser(filePath, roots, req.user, config);
983 if (!info || !canReadInfo(req.user, info))
844 984 {
845 985 return res.status(403).json({ error: 'Access denied.' });
846 986 }
@@ -906,9 +1046,9 @@ router.get('/download-zip', requireAuth, async (req, res) =>
906 1046 const dir = req.query.dir;
907 1047 if (!dir) return res.status(400).json({ error: 'dir is required.' });
908 1048
909 const roots = effectivePaths();
910 const info = resolveRoot(dir, roots);
911 if (!info || !canRead(req.user, info.label))
1049 const { config, roots } = loadConfigAndRoots();
1050 const info = resolveRootForUser(dir, roots, req.user, config);
1051 if (!info || !canReadInfo(req.user, info))
912 1052 {
913 1053 return res.status(403).json({ error: 'Access denied.' });
914 1054 }
@@ -940,9 +1080,9 @@ router.get('/thumbnail', requireAuth, async (req, res) =>
940 1080 const file = req.query.file;
941 1081 if (!file) return res.status(400).json({ error: 'file is required.' });
942 1082
943 const roots = effectivePaths();
944 const info = resolveRoot(file, roots);
945 if (!info || !canRead(req.user, info.label))
1083 const { config, roots } = loadConfigAndRoots();
1084 const info = resolveRootForUser(file, roots, req.user, config);
1085 if (!info || !canReadInfo(req.user, info))
946 1086 {
947 1087 return res.status(403).json({ error: 'Access denied.' });
948 1088 }
@@ -972,9 +1112,9 @@ router.post('/upload', requireAuth, (req, res, next) =>
972 1112 const dir = req.query.dir;
973 1113 if (!dir) return res.status(400).json({ error: 'dir is required.' });
974 1114
975 const roots = effectivePaths();
976 const info = resolveRoot(dir, roots);
977 if (!info || !canWrite(req.user, info.label))
1115 const { config, roots } = loadConfigAndRoots();
1116 const info = resolveRootForUser(dir, roots, req.user, config);
1117 if (!info || !canWriteInfo(req.user, info))
978 1118 {
979 1119 return res.status(403).json({ error: 'Access denied.' });
980 1120 }
@@ -998,6 +1138,14 @@ router.post('/upload', requireAuth, (req, res, next) =>
998 1138 }
999 1139 }
1000 1140
1141 // Enforce per-user folder size limit when uploading to a user folder.
1142 if (info.isUserFolder)
1143 {
1144 const addBytes = announcedSize > 0 ? announcedSize : 0;
1145 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1146 if (limitError) return res.status(413).json({ error: limitError });
1147 }
1148
1001 1149 req._uploadDir = dir;
1002 1150
1003 1151 upload.array('files')(req, res, async (err) =>
@@ -1048,17 +1196,17 @@ router.post('/rename', requireAuth, (req, res) =>
1048 1196 return res.status(400).json({ error: 'Invalid name.' });
1049 1197 }
1050 1198
1051 const roots = effectivePaths();
1052 const info = resolveRoot(from, roots);
1053 if (!info || !canWrite(req.user, info.label))
1199 const { config, roots } = loadConfigAndRoots();
1200 const info = resolveRootForUser(from, roots, req.user, config);
1201 if (!info || !canWriteInfo(req.user, info))
1054 1202 {
1055 1203 return res.status(403).json({ error: 'Access denied.' });
1056 1204 }
1057 1205
1058 1206 const dest = path.join(path.dirname(from), to);
1059 1207
1060 // Ensure dest is still inside the same root
1061 if (!getAllowedRoot(dest, roots))
1208 // Ensure dest is still inside the same accessible root or user folder.
1209 if (!isAccessiblePath(dest, roots, req.user, config))
1062 1210 {
1063 1211 return res.status(403).json({ error: 'Access denied.' });
1064 1212 }
@@ -1098,11 +1246,11 @@ router.post('/move', requireAuth, (req, res) =>
1098 1246 return res.status(400).json({ error: 'Invalid targetName.' });
1099 1247 }
1100 1248
1101 const roots = effectivePaths();
1102 const fromInfo = resolveRoot(from, roots);
1103 const toInfo = resolveRoot(toDir, roots);
1249 const { config, roots } = loadConfigAndRoots();
1250 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1251 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1104 1252 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1105 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
1253 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1106 1254 {
1107 1255 return res.status(403).json({ error: 'Access denied.' });
1108 1256 }
@@ -1122,7 +1270,15 @@ router.post('/move', requireAuth, (req, res) =>
1122 1270
1123 1271 const requestedName = targetName || path.basename(from);
1124 1272 const requestedDest = path.join(toDir, requestedName);
1125 if (!getAllowedRoot(requestedDest, roots)) return res.status(403).json({ error: 'Access denied.' });
1273 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1274
1275 // Enforce per-user folder size limit when moving into a user folder.
1276 if (toInfo.isUserFolder)
1277 {
1278 const sourceSize = getRecursiveSize(from);
1279 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
1280 if (limitError) return res.status(413).json({ error: limitError });
1281 }
1126 1282 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1127 1283 {
1128 1284 return res.status(400).json({ error: 'Cannot move onto itself.' });
@@ -1192,15 +1348,15 @@ router.post('/mkdir', requireAuth, (req, res) =>
1192 1348 return res.status(400).json({ error: 'Invalid folder name.' });
1193 1349 }
1194 1350
1195 const roots = effectivePaths();
1196 const info = resolveRoot(dir, roots);
1197 if (!info || !canWrite(req.user, info.label))
1351 const { config, roots } = loadConfigAndRoots();
1352 const info = resolveRootForUser(dir, roots, req.user, config);
1353 if (!info || !canWriteInfo(req.user, info))
1198 1354 {
1199 1355 return res.status(403).json({ error: 'Access denied.' });
1200 1356 }
1201 1357
1202 1358 const newDir = path.join(dir, name);
1203 if (!getAllowedRoot(newDir, roots))
1359 if (!isAccessiblePath(newDir, roots, req.user, config))
1204 1360 {
1205 1361 return res.status(403).json({ error: 'Access denied.' });
1206 1362 }
@@ -1225,9 +1381,9 @@ router.post('/delete', requireAuth, (req, res) =>
1225 1381 const target = req.body.path;
1226 1382 if (!target) return res.status(400).json({ error: 'path is required.' });
1227 1383
1228 const roots = effectivePaths();
1229 const info = resolveRoot(target, roots);
1230 if (!info || !canWrite(req.user, info.label))
1384 const { config, roots } = loadConfigAndRoots();
1385 const info = resolveRootForUser(target, roots, req.user, config);
1386 if (!info || !canWriteInfo(req.user, info))
1231 1387 {
1232 1388 return res.status(403).json({ error: 'Access denied.' });
1233 1389 }
@@ -1271,9 +1427,9 @@ router.get('/folder-images', requireAuth, async (req, res) =>
1271 1427 const dir = String(req.query.dir || '').trim();
1272 1428 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1273 1429
1274 const roots = effectivePaths();
1275 const info = resolveRoot(dir, roots);
1276 if (!info || !canRead(req.user, info.label))
1430 const { config, roots } = loadConfigAndRoots();
1431 const info = resolveRootForUser(dir, roots, req.user, config);
1432 if (!info || !canReadInfo(req.user, info))
1277 1433 {
1278 1434 return res.status(403).json({ error: 'Access denied.' });
1279 1435 }
@@ -1284,8 +1440,8 @@ router.get('/folder-images', requireAuth, async (req, res) =>
1284 1440 }
1285 1441
1286 1442 const images = await getImagesWithThumbnailsInDir(dir);
1287 // Filter out any that escaped to a different root (safety check).
1288 const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));
1443 // Filter out any that escaped to a different accessible root (safety check).
1444 const filtered = images.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
1289 1445
1290 1446 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1291 1447 });
@@ -1299,9 +1455,9 @@ router.get('/folder-icon', requireAuth, async (req, res) =>
1299 1455 const dir = String(req.query.dir || '').trim();
1300 1456 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1301 1457
1302 const roots = effectivePaths();
1303 const info = resolveRoot(dir, roots);
1304 if (!info || !canRead(req.user, info.label))
1458 const { config, roots } = loadConfigAndRoots();
1459 const info = resolveRootForUser(dir, roots, req.user, config);
1460 if (!info || !canReadInfo(req.user, info))
1305 1461 {
1306 1462 return res.status(403).json({ error: 'Access denied.' });
1307 1463 }
@@ -1309,8 +1465,8 @@ router.get('/folder-icon', requireAuth, async (req, res) =>
1309 1465 const sourceFile = await getFolderIconSourceFile(dir);
1310 1466 if (!sourceFile) return res.json({ icon: null });
1311 1467
1312 // Verify the source is still accessible within a configured root.
1313 if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });
1468 // Verify the source is still accessible within a configured root or user folder.
1469 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
1314 1470
1315 1471 res.json({ icon: { filePath: sourceFile } });
1316 1472 });
@@ -1327,9 +1483,9 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1327 1483
1328 1484 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1329 1485
1330 const roots = effectivePaths();
1331 const info = resolveRoot(folderPath, roots);
1332 if (!info || !canWrite(req.user, info.label))
1486 const { config, roots } = loadConfigAndRoots();
1487 const info = resolveRootForUser(folderPath, roots, req.user, config);
1488 if (!info || !canWriteInfo(req.user, info))
1333 1489 {
1334 1490 return res.status(403).json({ error: 'Access denied.' });
1335 1491 }
@@ -1341,9 +1497,8 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1341 1497
1342 1498 if (rawImage !== null)
1343 1499 {
1344 // Verify the image is inside a readable root.
1345 const imageRoot = getAllowedRoot(rawImage, roots);
1346 if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });
1500 // Verify the image is inside a readable root or user folder.
1501 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
1347 1502
1348 1503 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1349 1504 const thumb = await getCachedThumbnailInfo(rawImage);
@@ -1354,4 +1509,93 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1354 1509 res.json({ ok: true });
1355 1510 });
1356 1511
1512 // ---------------------------------------------------------------------------
1513 // POST /api/files/copy
1514 // Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1515 // Copies a file (not a directory) to the destination folder.
1516 // Supports conflict: 'error' (default) | 'overwrite' | 'rename'
1517 // ---------------------------------------------------------------------------
1518 router.post('/copy', requireAuth, (req, res) =>
1519 {
1520 const { from, toDir } = req.body;
1521 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1522 const targetName = req.body && req.body.targetName != null
1523 ? String(req.body.targetName).trim()
1524 : '';
1525 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1526 if (!['error', 'overwrite', 'rename'].includes(conflict))
1527 {
1528 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1529 }
1530
1531 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1532 {
1533 return res.status(400).json({ error: 'Invalid targetName.' });
1534 }
1535
1536 const { config, roots } = loadConfigAndRoots();
1537 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1538 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1539 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1540 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1541 {
1542 return res.status(403).json({ error: 'Access denied.' });
1543 }
1544
1545 let sourceStat;
1546 try { sourceStat = fs.statSync(from); }
1547 catch { return res.status(404).json({ error: 'Source not found.' }); }
1548
1549 if (sourceStat.isDirectory())
1550 {
1551 return res.status(400).json({ error: 'Copying directories is not supported.' });
1552 }
1553
1554 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
1555 {
1556 return res.status(404).json({ error: 'Destination directory not found.' });
1557 }
1558
1559 const requestedName = targetName || path.basename(from);
1560 const requestedDest = path.join(toDir, requestedName);
1561 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1562
1563 // Enforce per-user folder size limit when copying into a user folder.
1564 if (toInfo.isUserFolder)
1565 {
1566 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
1567 if (limitError) return res.status(413).json({ error: limitError });
1568 }
1569
1570 let dest = requestedDest;
1571 let resolvedConflict = 'none';
1572
1573 if (fs.existsSync(requestedDest))
1574 {
1575 if (conflict === 'error')
1576 {
1577 return res.status(409).json({ error: 'Destination already exists.' });
1578 }
1579 if (conflict === 'rename')
1580 {
1581 dest = pickNumberedPath(toDir, requestedName);
1582 resolvedConflict = 'rename';
1583 }
1584 if (conflict === 'overwrite')
1585 {
1586 resolvedConflict = 'overwrite';
1587 }
1588 }
1589
1590 try
1591 {
1592 fs.copyFileSync(from, dest);
1593 } catch (err)
1594 {
1595 return res.status(500).json({ error: err.message });
1596 }
1597
1598 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1599 });
1600
1357 1601 module.exports = router;
@@ -190,6 +190,25 @@ function effectivePaths ()
190 return getEffectivePaths(loadConfig().paths || []);
190 return getEffectivePaths(loadConfig().paths || []);
191}
191}
192
192
193/**
194 * Loads config and returns { config, roots } together so both are consistent
195 * and user-folder checks can be performed in route handlers.
196 */
197function loadConfigAndRoots ()
198{
199 const config = loadConfig();
200 return { config, roots: getEffectivePaths(config.paths || []) };
201}
202
203/**
204 * Returns true when absPath is accessible to the user (either via a
205 * configured root or their personal folder).
206 */
207function isAccessiblePath (absPath, roots, user, config)
208{
209 return resolveRootForUser(absPath, roots, user, config) !== null;
210}
211
193function rootAliasesFromConfig (config)
212function rootAliasesFromConfig (config)
194{
213{
195 if (!config || typeof config !== 'object') return {};
214 if (!config || typeof config !== 'object') return {};
@@ -268,6 +287,103 @@ function canWrite (user, pathLabel)
268 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
287 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
269}
288}
270
289
290// ---------------------------------------------------------------------------
291// User folder helpers
292// ---------------------------------------------------------------------------
293
294/**
295 * Returns the absolute path of the user's personal folder, or null.
296 * e.g. /data/userfolders/<username>
297 */
298function getUserFolderPath (config, username)
299{
300 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
301 if (!base) return null;
302 return path.join(base, String(username));
303}
304
305/**
306 * Resolves a request path against both the configured roots AND the user's
307 * personal folder. Returns { root, label, isUserFolder } or null.
308 * - isUserFolder: true when the path is inside the user's personal folder.
309 */
310function resolveRootForUser (absPath, roots, user, config)
311{
312 // Regular configured roots first.
313 const matched = getAllowedRoot(absPath, roots);
314 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
315
316 // Check user personal folder.
317 if (!user || !user.username) return null;
318 const userFolder = getUserFolderPath(config, user.username);
319 if (!userFolder) return null;
320
321 const resolved = path.resolve(absPath);
322 const resolvedFolder = path.resolve(userFolder);
323 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
324 {
325 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
326 }
327
328 return null;
329}
330
331/**
332 * Checks whether the user has READ access to the resolved root info object
333 * returned by resolveRootForUser.
334 */
335function canReadInfo (user, info)
336{
337 if (!info) return false;
338 if (info.isUserFolder) return true; // owner always has full access
339 return canRead(user, info.label);
340}
341
342/**
343 * Checks whether the user has WRITE access to the resolved root info object.
344 */
345function canWriteInfo (user, info)
346{
347 if (!info) return false;
348 if (info.isUserFolder) return true;
349 return canWrite(user, info.label);
350}
351
352/**
353 * Returns the size limit (bytes) for the user's personal folder, or null = unlimited.
354 */
355function getUserFolderSizeLimit (config)
356{
357 const lim = Number(config.userFolderSizeLimit);
358 return Number.isFinite(lim) && lim > 0 ? lim : null;
359}
360
361/**
362 * Returns an error message if adding `addedBytes` to the user's folder would
363 * exceed the size limit, or null if within limits.
364 */
365function checkUserFolderSizeLimit (config, username, addedBytes)
366{
367 const limit = getUserFolderSizeLimit(config);
368 if (!limit) return null;
369 const userFolder = getUserFolderPath(config, username);
370 if (!userFolder) return null;
371 const currentSize = getRecursiveSize(userFolder);
372 if (currentSize + addedBytes > limit)
373 {
374 return `Your personal folder is full (limit ${formatBytesServer(limit)}, used ${formatBytesServer(currentSize)}).`;
375 }
376 return null;
377}
378
379function formatBytesServer (bytes)
380{
381 if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
382 if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
383 if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
384 return `${bytes} B`;
385}
386
271/**
387/**
272 * Given an absolute path and the effective-paths list, return
388 * Given an absolute path and the effective-paths list, return
273 * { root, label } where label is the base-name of the root, or null.
389 * { root, label } where label is the base-name of the root, or null.
@@ -395,6 +511,7 @@ function removePathRecursive (targetPath)
395// ---------------------------------------------------------------------------
511// ---------------------------------------------------------------------------
396// GET /api/files/roots
512// GET /api/files/roots
397// Returns the effective configured paths the user can read.
513// Returns the effective configured paths the user can read.
514// Also injects the user's personal folder when userPath is configured.
398// ---------------------------------------------------------------------------
515// ---------------------------------------------------------------------------
399router.get('/roots', requireAuth, (req, res) =>
516router.get('/roots', requireAuth, (req, res) =>
400{
517{
@@ -415,6 +532,24 @@ router.get('/roots', requireAuth, (req, res) =>
415 alias: alias || null,
532 alias: alias || null,
416 };
533 };
417 });
534 });
535
536 // Inject the user's personal folder when a userPath is configured.
537 if (req.user && req.user.username)
538 {
539 const userFolder = getUserFolderPath(config, req.user.username);
540 if (userFolder)
541 {
542 try { fs.mkdirSync(userFolder, { recursive: true }); } catch { /* non-fatal */ }
543 readable.unshift({
544 label: 'My Folder',
545 path: userFolder,
546 originalName: req.user.username,
547 alias: 'My Folder',
548 isUserFolder: true,
549 });
550 }
551 }
552
418 res.json({ roots: readable });
553 res.json({ roots: readable });
419});
554});
420
555
@@ -552,10 +687,9 @@ router.get('/list', requireAuth, (req, res) =>
552 const dir = req.query.dir;
687 const dir = req.query.dir;
553 if (!dir) return res.status(400).json({ error: 'dir is required.' });
688 if (!dir) return res.status(400).json({ error: 'dir is required.' });
554
689
555 const roots = effectivePaths();
690 const { config, roots } = loadConfigAndRoots();
556 const info = resolveRoot(dir, roots);
691 const info = resolveRootForUser(dir, roots, req.user, config);
557 if (!info) return res.status(403).json({ error: 'Access denied.' });
692 if (!info || !canReadInfo(req.user, info)) return res.status(403).json({ error: 'Access denied.' });
558 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
559
693
560 let entries;
694 let entries;
561 try
695 try
@@ -599,9 +733,9 @@ router.get('/meta', requireAuth, async (req, res) =>
599 const file = req.query.file;
733 const file = req.query.file;
600 if (!file) return res.status(400).json({ error: 'file is required.' });
734 if (!file) return res.status(400).json({ error: 'file is required.' });
601
735
602 const roots = effectivePaths();
736 const { config, roots } = loadConfigAndRoots();
603 const info = resolveRoot(file, roots);
737 const info = resolveRootForUser(file, roots, req.user, config);
604 if (!info || !canRead(req.user, info.label))
738 if (!info || !canReadInfo(req.user, info))
605 {
739 {
606 return res.status(403).json({ error: 'Access denied.' });
740 return res.status(403).json({ error: 'Access denied.' });
607 }
741 }
@@ -660,9 +794,9 @@ router.get('/duplicates', requireAuth, (req, res) =>
660 const file = req.query.file;
794 const file = req.query.file;
661 if (!file) return res.status(400).json({ error: 'file is required.' });
795 if (!file) return res.status(400).json({ error: 'file is required.' });
662
796
663 const roots = effectivePaths();
797 const { config, roots } = loadConfigAndRoots();
664 const info = resolveRoot(file, roots);
798 const info = resolveRootForUser(file, roots, req.user, config);
665 if (!info || !canRead(req.user, info.label))
799 if (!info || !canReadInfo(req.user, info))
666 {
800 {
667 return res.status(403).json({ error: 'Access denied.' });
801 return res.status(403).json({ error: 'Access denied.' });
668 }
802 }
@@ -680,21 +814,23 @@ router.get('/duplicates', requireAuth, (req, res) =>
680 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
814 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
681 ).all([hash, file]);
815 ).all([hash, file]);
682
816
683 const readable = roots.filter((r) => canRead(req.user, path.basename(r)));
684
685 const duplicates = [];
817 const duplicates = [];
686 for (const { file_path } of candidates)
818 for (const { file_path } of candidates)
687 {
819 {
688 // Only return files inside a root the user can access and that still exist on disk.
820 // Only return files inside a root the user can access and that still exist on disk.
689 const allowedRoot = readable.find(
821 const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
690 (r) => file_path === r || (file_path.startsWith(r) && (file_path[r.length] === path.sep || file_path[r.length] === '/')),
822 if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue;
691 );
692 if (!allowedRoot) continue;
693 if (!fs.existsSync(file_path)) continue;
823 if (!fs.existsSync(file_path)) continue;
824
825 const rel = path.relative(dupInfo.root, file_path);
826 const relativePath = rel && rel !== '' ? rel : path.basename(file_path);
827
694 duplicates.push({
828 duplicates.push({
695 path: file_path,
829 path: file_path,
696 name: path.basename(file_path),
830 name: path.basename(file_path),
697 dir: path.dirname(file_path),
831 dir: path.dirname(file_path),
832 rootPath: dupInfo.root,
833 relativePath,
698 });
834 });
699 }
835 }
700
836
@@ -710,9 +846,9 @@ router.get('/space', requireAuth, (req, res) =>
710 const dir = req.query.dir;
846 const dir = req.query.dir;
711 if (!dir) return res.status(400).json({ error: 'dir is required.' });
847 if (!dir) return res.status(400).json({ error: 'dir is required.' });
712
848
713 const roots = effectivePaths();
849 const { config, roots } = loadConfigAndRoots();
714 const info = resolveRoot(dir, roots);
850 const info = resolveRootForUser(dir, roots, req.user, config);
715 if (!info || !canRead(req.user, info.label))
851 if (!info || !canReadInfo(req.user, info))
716 {
852 {
717 return res.status(403).json({ error: 'Access denied.' });
853 return res.status(403).json({ error: 'Access denied.' });
718 }
854 }
@@ -724,9 +860,13 @@ router.get('/space', requireAuth, (req, res) =>
724
860
725 const usedBytes = getRecursiveSize(dir);
861 const usedBytes = getRecursiveSize(dir);
726 const freeBytes = getFreeBytes(info.root);
862 const freeBytes = getFreeBytes(info.root);
863 const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null;
864 const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes);
727 res.json({
865 res.json({
728 usedBytes,
866 usedBytes,
729 freeBytes,
867 freeBytes,
868 userLimitBytes,
869 userFreeBytes,
730 rootPath: info.root,
870 rootPath: info.root,
731 rootLabel: info.label,
871 rootLabel: info.label,
732 });
872 });
@@ -741,9 +881,9 @@ router.get('/download', requireAuth, (req, res) =>
741 const file = req.query.file;
881 const file = req.query.file;
742 if (!file) return res.status(400).json({ error: 'file is required.' });
882 if (!file) return res.status(400).json({ error: 'file is required.' });
743
883
744 const roots = effectivePaths();
884 const { config, roots } = loadConfigAndRoots();
745 const info = resolveRoot(file, roots);
885 const info = resolveRootForUser(file, roots, req.user, config);
746 if (!info || !canRead(req.user, info.label))
886 if (!info || !canReadInfo(req.user, info))
747 {
887 {
748 return res.status(403).json({ error: 'Access denied.' });
888 return res.status(403).json({ error: 'Access denied.' });
749 }
889 }
@@ -791,9 +931,9 @@ router.post('/watch-progress', requireAuth, (req, res) =>
791 return res.json({ ok: true, updated: false });
931 return res.json({ ok: true, updated: false });
792 }
932 }
793
933
794 const roots = effectivePaths();
934 const { config, roots } = loadConfigAndRoots();
795 const info = resolveRoot(filePath, roots);
935 const info = resolveRootForUser(filePath, roots, req.user, config);
796 if (!info || !canRead(req.user, info.label))
936 if (!info || !canReadInfo(req.user, info))
797 {
937 {
798 return res.status(403).json({ error: 'Access denied.' });
938 return res.status(403).json({ error: 'Access denied.' });
799 }
939 }
@@ -838,9 +978,9 @@ router.post('/video-stream', requireAuth, async (req, res, next) =>
838 const filePath = String(req.body?.filePath || '').trim();
978 const filePath = String(req.body?.filePath || '').trim();
839 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
979 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
840
980
841 const roots = effectivePaths();
981 const { config, roots } = loadConfigAndRoots();
842 const info = resolveRoot(filePath, roots);
982 const info = resolveRootForUser(filePath, roots, req.user, config);
843 if (!info || !canRead(req.user, info.label))
983 if (!info || !canReadInfo(req.user, info))
844 {
984 {
845 return res.status(403).json({ error: 'Access denied.' });
985 return res.status(403).json({ error: 'Access denied.' });
846 }
986 }
@@ -906,9 +1046,9 @@ router.get('/download-zip', requireAuth, async (req, res) =>
906 const dir = req.query.dir;
1046 const dir = req.query.dir;
907 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1047 if (!dir) return res.status(400).json({ error: 'dir is required.' });
908
1048
909 const roots = effectivePaths();
1049 const { config, roots } = loadConfigAndRoots();
910 const info = resolveRoot(dir, roots);
1050 const info = resolveRootForUser(dir, roots, req.user, config);
911 if (!info || !canRead(req.user, info.label))
1051 if (!info || !canReadInfo(req.user, info))
912 {
1052 {
913 return res.status(403).json({ error: 'Access denied.' });
1053 return res.status(403).json({ error: 'Access denied.' });
914 }
1054 }
@@ -940,9 +1080,9 @@ router.get('/thumbnail', requireAuth, async (req, res) =>
940 const file = req.query.file;
1080 const file = req.query.file;
941 if (!file) return res.status(400).json({ error: 'file is required.' });
1081 if (!file) return res.status(400).json({ error: 'file is required.' });
942
1082
943 const roots = effectivePaths();
1083 const { config, roots } = loadConfigAndRoots();
944 const info = resolveRoot(file, roots);
1084 const info = resolveRootForUser(file, roots, req.user, config);
945 if (!info || !canRead(req.user, info.label))
1085 if (!info || !canReadInfo(req.user, info))
946 {
1086 {
947 return res.status(403).json({ error: 'Access denied.' });
1087 return res.status(403).json({ error: 'Access denied.' });
948 }
1088 }
@@ -972,9 +1112,9 @@ router.post('/upload', requireAuth, (req, res, next) =>
972 const dir = req.query.dir;
1112 const dir = req.query.dir;
973 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1113 if (!dir) return res.status(400).json({ error: 'dir is required.' });
974
1114
975 const roots = effectivePaths();
1115 const { config, roots } = loadConfigAndRoots();
976 const info = resolveRoot(dir, roots);
1116 const info = resolveRootForUser(dir, roots, req.user, config);
977 if (!info || !canWrite(req.user, info.label))
1117 if (!info || !canWriteInfo(req.user, info))
978 {
1118 {
979 return res.status(403).json({ error: 'Access denied.' });
1119 return res.status(403).json({ error: 'Access denied.' });
980 }
1120 }
@@ -998,6 +1138,14 @@ router.post('/upload', requireAuth, (req, res, next) =>
998 }
1138 }
999 }
1139 }
1000
1140
1141 // Enforce per-user folder size limit when uploading to a user folder.
1142 if (info.isUserFolder)
1143 {
1144 const addBytes = announcedSize > 0 ? announcedSize : 0;
1145 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1146 if (limitError) return res.status(413).json({ error: limitError });
1147 }
1148
1001 req._uploadDir = dir;
1149 req._uploadDir = dir;
1002
1150
1003 upload.array('files')(req, res, async (err) =>
1151 upload.array('files')(req, res, async (err) =>
@@ -1048,17 +1196,17 @@ router.post('/rename', requireAuth, (req, res) =>
1048 return res.status(400).json({ error: 'Invalid name.' });
1196 return res.status(400).json({ error: 'Invalid name.' });
1049 }
1197 }
1050
1198
1051 const roots = effectivePaths();
1199 const { config, roots } = loadConfigAndRoots();
1052 const info = resolveRoot(from, roots);
1200 const info = resolveRootForUser(from, roots, req.user, config);
1053 if (!info || !canWrite(req.user, info.label))
1201 if (!info || !canWriteInfo(req.user, info))
1054 {
1202 {
1055 return res.status(403).json({ error: 'Access denied.' });
1203 return res.status(403).json({ error: 'Access denied.' });
1056 }
1204 }
1057
1205
1058 const dest = path.join(path.dirname(from), to);
1206 const dest = path.join(path.dirname(from), to);
1059
1207
1060 // Ensure dest is still inside the same root
1208 // Ensure dest is still inside the same accessible root or user folder.
1061 if (!getAllowedRoot(dest, roots))
1209 if (!isAccessiblePath(dest, roots, req.user, config))
1062 {
1210 {
1063 return res.status(403).json({ error: 'Access denied.' });
1211 return res.status(403).json({ error: 'Access denied.' });
1064 }
1212 }
@@ -1098,11 +1246,11 @@ router.post('/move', requireAuth, (req, res) =>
1098 return res.status(400).json({ error: 'Invalid targetName.' });
1246 return res.status(400).json({ error: 'Invalid targetName.' });
1099 }
1247 }
1100
1248
1101 const roots = effectivePaths();
1249 const { config, roots } = loadConfigAndRoots();
1102 const fromInfo = resolveRoot(from, roots);
1250 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1103 const toInfo = resolveRoot(toDir, roots);
1251 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1104 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1252 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1105 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
1253 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1106 {
1254 {
1107 return res.status(403).json({ error: 'Access denied.' });
1255 return res.status(403).json({ error: 'Access denied.' });
1108 }
1256 }
@@ -1122,7 +1270,15 @@ router.post('/move', requireAuth, (req, res) =>
1122
1270
1123 const requestedName = targetName || path.basename(from);
1271 const requestedName = targetName || path.basename(from);
1124 const requestedDest = path.join(toDir, requestedName);
1272 const requestedDest = path.join(toDir, requestedName);
1125 if (!getAllowedRoot(requestedDest, roots)) return res.status(403).json({ error: 'Access denied.' });
1273 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1274
1275 // Enforce per-user folder size limit when moving into a user folder.
1276 if (toInfo.isUserFolder)
1277 {
1278 const sourceSize = getRecursiveSize(from);
1279 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
1280 if (limitError) return res.status(413).json({ error: limitError });
1281 }
1126 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1282 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1127 {
1283 {
1128 return res.status(400).json({ error: 'Cannot move onto itself.' });
1284 return res.status(400).json({ error: 'Cannot move onto itself.' });
@@ -1192,15 +1348,15 @@ router.post('/mkdir', requireAuth, (req, res) =>
1192 return res.status(400).json({ error: 'Invalid folder name.' });
1348 return res.status(400).json({ error: 'Invalid folder name.' });
1193 }
1349 }
1194
1350
1195 const roots = effectivePaths();
1351 const { config, roots } = loadConfigAndRoots();
1196 const info = resolveRoot(dir, roots);
1352 const info = resolveRootForUser(dir, roots, req.user, config);
1197 if (!info || !canWrite(req.user, info.label))
1353 if (!info || !canWriteInfo(req.user, info))
1198 {
1354 {
1199 return res.status(403).json({ error: 'Access denied.' });
1355 return res.status(403).json({ error: 'Access denied.' });
1200 }
1356 }
1201
1357
1202 const newDir = path.join(dir, name);
1358 const newDir = path.join(dir, name);
1203 if (!getAllowedRoot(newDir, roots))
1359 if (!isAccessiblePath(newDir, roots, req.user, config))
1204 {
1360 {
1205 return res.status(403).json({ error: 'Access denied.' });
1361 return res.status(403).json({ error: 'Access denied.' });
1206 }
1362 }
@@ -1225,9 +1381,9 @@ router.post('/delete', requireAuth, (req, res) =>
1225 const target = req.body.path;
1381 const target = req.body.path;
1226 if (!target) return res.status(400).json({ error: 'path is required.' });
1382 if (!target) return res.status(400).json({ error: 'path is required.' });
1227
1383
1228 const roots = effectivePaths();
1384 const { config, roots } = loadConfigAndRoots();
1229 const info = resolveRoot(target, roots);
1385 const info = resolveRootForUser(target, roots, req.user, config);
1230 if (!info || !canWrite(req.user, info.label))
1386 if (!info || !canWriteInfo(req.user, info))
1231 {
1387 {
1232 return res.status(403).json({ error: 'Access denied.' });
1388 return res.status(403).json({ error: 'Access denied.' });
1233 }
1389 }
@@ -1271,9 +1427,9 @@ router.get('/folder-images', requireAuth, async (req, res) =>
1271 const dir = String(req.query.dir || '').trim();
1427 const dir = String(req.query.dir || '').trim();
1272 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1428 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1273
1429
1274 const roots = effectivePaths();
1430 const { config, roots } = loadConfigAndRoots();
1275 const info = resolveRoot(dir, roots);
1431 const info = resolveRootForUser(dir, roots, req.user, config);
1276 if (!info || !canRead(req.user, info.label))
1432 if (!info || !canReadInfo(req.user, info))
1277 {
1433 {
1278 return res.status(403).json({ error: 'Access denied.' });
1434 return res.status(403).json({ error: 'Access denied.' });
1279 }
1435 }
@@ -1284,8 +1440,8 @@ router.get('/folder-images', requireAuth, async (req, res) =>
1284 }
1440 }
1285
1441
1286 const images = await getImagesWithThumbnailsInDir(dir);
1442 const images = await getImagesWithThumbnailsInDir(dir);
1287 // Filter out any that escaped to a different root (safety check).
1443 // Filter out any that escaped to a different accessible root (safety check).
1288 const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));
1444 const filtered = images.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
1289
1445
1290 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1446 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1291});
1447});
@@ -1299,9 +1455,9 @@ router.get('/folder-icon', requireAuth, async (req, res) =>
1299 const dir = String(req.query.dir || '').trim();
1455 const dir = String(req.query.dir || '').trim();
1300 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1456 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1301
1457
1302 const roots = effectivePaths();
1458 const { config, roots } = loadConfigAndRoots();
1303 const info = resolveRoot(dir, roots);
1459 const info = resolveRootForUser(dir, roots, req.user, config);
1304 if (!info || !canRead(req.user, info.label))
1460 if (!info || !canReadInfo(req.user, info))
1305 {
1461 {
1306 return res.status(403).json({ error: 'Access denied.' });
1462 return res.status(403).json({ error: 'Access denied.' });
1307 }
1463 }
@@ -1309,8 +1465,8 @@ router.get('/folder-icon', requireAuth, async (req, res) =>
1309 const sourceFile = await getFolderIconSourceFile(dir);
1465 const sourceFile = await getFolderIconSourceFile(dir);
1310 if (!sourceFile) return res.json({ icon: null });
1466 if (!sourceFile) return res.json({ icon: null });
1311
1467
1312 // Verify the source is still accessible within a configured root.
1468 // Verify the source is still accessible within a configured root or user folder.
1313 if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });
1469 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
1314
1470
1315 res.json({ icon: { filePath: sourceFile } });
1471 res.json({ icon: { filePath: sourceFile } });
1316});
1472});
@@ -1327,9 +1483,9 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1327
1483
1328 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1484 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1329
1485
1330 const roots = effectivePaths();
1486 const { config, roots } = loadConfigAndRoots();
1331 const info = resolveRoot(folderPath, roots);
1487 const info = resolveRootForUser(folderPath, roots, req.user, config);
1332 if (!info || !canWrite(req.user, info.label))
1488 if (!info || !canWriteInfo(req.user, info))
1333 {
1489 {
1334 return res.status(403).json({ error: 'Access denied.' });
1490 return res.status(403).json({ error: 'Access denied.' });
1335 }
1491 }
@@ -1341,9 +1497,8 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1341
1497
1342 if (rawImage !== null)
1498 if (rawImage !== null)
1343 {
1499 {
1344 // Verify the image is inside a readable root.
1500 // Verify the image is inside a readable root or user folder.
1345 const imageRoot = getAllowedRoot(rawImage, roots);
1501 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
1346 if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });
1347
1502
1348 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1503 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1349 const thumb = await getCachedThumbnailInfo(rawImage);
1504 const thumb = await getCachedThumbnailInfo(rawImage);
@@ -1354,4 +1509,93 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1354 res.json({ ok: true });
1509 res.json({ ok: true });
1355});
1510});
1356
1511
1512// ---------------------------------------------------------------------------
1513// POST /api/files/copy
1514// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1515// Copies a file (not a directory) to the destination folder.
1516// Supports conflict: 'error' (default) | 'overwrite' | 'rename'
1517// ---------------------------------------------------------------------------
1518router.post('/copy', requireAuth, (req, res) =>
1519{
1520 const { from, toDir } = req.body;
1521 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1522 const targetName = req.body && req.body.targetName != null
1523 ? String(req.body.targetName).trim()
1524 : '';
1525 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1526 if (!['error', 'overwrite', 'rename'].includes(conflict))
1527 {
1528 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1529 }
1530
1531 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1532 {
1533 return res.status(400).json({ error: 'Invalid targetName.' });
1534 }
1535
1536 const { config, roots } = loadConfigAndRoots();
1537 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1538 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1539 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1540 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1541 {
1542 return res.status(403).json({ error: 'Access denied.' });
1543 }
1544
1545 let sourceStat;
1546 try { sourceStat = fs.statSync(from); }
1547 catch { return res.status(404).json({ error: 'Source not found.' }); }
1548
1549 if (sourceStat.isDirectory())
1550 {
1551 return res.status(400).json({ error: 'Copying directories is not supported.' });
1552 }
1553
1554 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
1555 {
1556 return res.status(404).json({ error: 'Destination directory not found.' });
1557 }
1558
1559 const requestedName = targetName || path.basename(from);
1560 const requestedDest = path.join(toDir, requestedName);
1561 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1562
1563 // Enforce per-user folder size limit when copying into a user folder.
1564 if (toInfo.isUserFolder)
1565 {
1566 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
1567 if (limitError) return res.status(413).json({ error: limitError });
1568 }
1569
1570 let dest = requestedDest;
1571 let resolvedConflict = 'none';
1572
1573 if (fs.existsSync(requestedDest))
1574 {
1575 if (conflict === 'error')
1576 {
1577 return res.status(409).json({ error: 'Destination already exists.' });
1578 }
1579 if (conflict === 'rename')
1580 {
1581 dest = pickNumberedPath(toDir, requestedName);
1582 resolvedConflict = 'rename';
1583 }
1584 if (conflict === 'overwrite')
1585 {
1586 resolvedConflict = 'overwrite';
1587 }
1588 }
1589
1590 try
1591 {
1592 fs.copyFileSync(from, dest);
1593 } catch (err)
1594 {
1595 return res.status(500).json({ error: err.message });
1596 }
1597
1598 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1599});
1600
1357module.exports = router;
1601module.exports = router;
server/thumbnail-cache.js +20 −1
@@ -207,7 +207,26 @@ async function generateImageThumb (sourceFile, thumbPath)
207 207
208 208 function effectiveRoots ()
209 209 {
210 return getEffectivePaths(loadConfig().paths || []);
210 const config = loadConfig();
211 const roots = getEffectivePaths(config.paths || []);
212
213 // Include the personal-user root tree so thumbnails are generated for
214 // files stored under userPath/<username>/... as well.
215 const userPath = typeof config.userPath === 'string' ? config.userPath.trim() : '';
216 if (userPath) roots.push(userPath);
217
218 // De-duplicate roots by resolved absolute path.
219 const seen = new Set();
220 const deduped = [];
221 for (const root of roots)
222 {
223 const key = path.resolve(root);
224 if (seen.has(key)) continue;
225 seen.add(key);
226 deduped.push(root);
227 }
228
229 return deduped;
211 230 }
212 231
213 232 function pathInsideOrEqualResolved (targetPath, rootPath)
@@ -207,7 +207,26 @@ async function generateImageThumb (sourceFile, thumbPath)
207
207
208function effectiveRoots ()
208function effectiveRoots ()
209{
209{
210 return getEffectivePaths(loadConfig().paths || []);
210 const config = loadConfig();
211 const roots = getEffectivePaths(config.paths || []);
212
213 // Include the personal-user root tree so thumbnails are generated for
214 // files stored under userPath/<username>/... as well.
215 const userPath = typeof config.userPath === 'string' ? config.userPath.trim() : '';
216 if (userPath) roots.push(userPath);
217
218 // De-duplicate roots by resolved absolute path.
219 const seen = new Set();
220 const deduped = [];
221 for (const root of roots)
222 {
223 const key = path.resolve(root);
224 if (seen.has(key)) continue;
225 seen.add(key);
226 deduped.push(root);
227 }
228
229 return deduped;
211}
230}
212
231
213function pathInsideOrEqualResolved (targetPath, rootPath)
232function pathInsideOrEqualResolved (targetPath, rootPath)