Merge branch 'feature/sha256-duplicates'
@@ -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.
@@ -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
@@ -1585,6 +1652,101 @@ function selectItem (el, item)
1585
1652
// SIDEBAR
1586
1653
// ───────────────────────────────────────────────────────────────────────────
1587
1654
1655
/**
1656
* Renders (or clears) the duplicates panel at the bottom of the sidebar.
1657
* @param {object|null} item — the item whose duplicates are shown; null = clear
1658
* @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state
1659
*/
1660
function renderSidebarDuplicates (item, duplicates)
1661
{
1662
const panel = document.getElementById('sidebar-duplicates');
1663
if (!panel) return;
1664
1665
// Clear / hide when no item or no duplicates.
1666
if (!item || (Array.isArray(duplicates) && duplicates.length === 0))
1667
{
1668
panel.classList.add('hidden');
1669
panel.innerHTML = '';
1670
return;
1671
}
1672
1673
// Loading state.
1674
if (duplicates === null)
1675
{
1676
panel.classList.add('hidden');
1677
panel.innerHTML = '';
1678
return;
1679
}
1680
1681
panel.innerHTML = '';
1682
const heading = document.createElement('p');
1683
heading.className = 'sidebar-duplicates-heading';
1684
heading.textContent = `Duplicates (${duplicates.length})`;
1685
panel.appendChild(heading);
1686
1687
const list = document.createElement('ul');
1688
list.className = 'sidebar-duplicates-list';
1689
1690
for (const dup of duplicates)
1691
{
1692
const li = document.createElement('li');
1693
const btn = document.createElement('button');
1694
btn.className = 'sidebar-duplicate-entry';
1695
btn.title = dup.path;
1696
// Show path relative to its root; keep absolute path in the tooltip.
1697
btn.textContent = dup.relativePath || dup.path;
1698
btn.addEventListener('click', () => navigateToDuplicate(dup));
1699
li.appendChild(btn);
1700
list.appendChild(li);
1701
}
1702
1703
panel.appendChild(list);
1704
panel.classList.remove('hidden');
1705
}
1706
1707
/**
1708
* Navigates to the folder containing a duplicate file and then auto-opens it.
1709
* @param {{ path: string, name: string, dir: string }} dup
1710
*/
1711
async function navigateToDuplicate (dup)
1712
{
1713
// If the duplicate lives in the folder already shown, just select it.
1714
if (STATE.currentDir && samePath(dup.dir, STATE.currentDir))
1715
{
1716
const tile = Array.from(document.querySelectorAll('.file-item'))
1717
.find((el) => el.dataset.path === dup.path);
1718
const dupItem = STATE.items.find((i) => i.path === dup.path);
1719
if (tile && dupItem)
1720
{
1721
selectItem(tile, dupItem);
1722
}
1723
return;
1724
}
1725
1726
// Find the root that contains the duplicate.
1727
const root = STATE.roots.find(
1728
(r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'),
1729
);
1730
if (!root)
1731
{
1732
toast('Cannot navigate to duplicate: root not accessible.', 'err');
1733
return;
1734
}
1735
1736
await navigateTo(dup.dir, root);
1737
1738
// After navigation, find and select the file tile to open it.
1739
const tile = Array.from(document.querySelectorAll('.file-item'))
1740
.find((el) => el.dataset.path === dup.path);
1741
const dupItem = STATE.items.find((i) => i.path === dup.path);
1742
1743
if (tile && dupItem)
1744
{
1745
selectItem(tile, dupItem);
1746
}
1747
}
1748
// ───────────────────────────────────────────────────────────────────────────
1749
1588
1750
async function openSidebar (item)
1589
1751
{
1590
1752
const sidebar = document.getElementById('sidebar');
@@ -1608,6 +1770,9 @@ async function openSidebar (item)
1608
1770
const actions = document.getElementById('sidebar-actions');
1609
1771
actions.innerHTML = '';
1610
1772
1773
// Reset duplicates panel whenever a new item is opened.
1774
renderSidebarDuplicates(null, null);
1775
1611
1776
if (!item.isDir)
1612
1777
{
1613
1778
const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
@@ -1628,6 +1793,21 @@ async function openSidebar (item)
1628
1793
`;
1629
1794
}
1630
1795
1796
// Fetch and render duplicate files.
1797
renderSidebarDuplicates(item, null); // show loading state
1798
const selectedPathAtRequest = item.path;
1799
api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`)
1800
.then((data) =>
1801
{
1802
if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
1803
renderSidebarDuplicates(item, data ? data.duplicates : []);
1804
})
1805
.catch(() =>
1806
{
1807
if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;
1808
renderSidebarDuplicates(item, []);
1809
});
1810
1631
1811
// View / download button
1632
1812
const btnDl = document.createElement('button');
1633
1813
btnDl.textContent = 'View / Download';
@@ -1743,6 +1923,14 @@ async function openSidebar (item)
1743
1923
btnMove.textContent = 'Move to';
1744
1924
btnMove.addEventListener('click', () => openMovePicker(item));
1745
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
}
1746
1934
}
1747
1935
1748
1936
const btnRen = document.createElement('button');
@@ -1773,6 +1961,7 @@ function openFolderSidebar ()
1773
1961
const dl = document.getElementById('sidebar-meta');
1774
1962
const actions = document.getElementById('sidebar-actions');
1775
1963
actions.innerHTML = '';
1964
renderSidebarDuplicates(null, null);
1776
1965
1777
1966
if (!STATE.currentDir || !STATE.currentRoot)
1778
1967
{
@@ -1790,8 +1979,9 @@ function openFolderSidebar ()
1790
1979
1791
1980
const dirs = STATE.items.filter(i => i.isDir).length;
1792
1981
const files = STATE.items.length - dirs;
1982
const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label);
1793
1983
const baseDetails = `
1794
<dt>Path</dt><dd>${STATE.currentDir}</dd>
1984
<dt>Path</dt><dd>${displayPath}</dd>
1795
1985
<dt>Folders</dt><dd>${dirs}</dd>
1796
1986
<dt>Files</dt><dd>${files}</dd>
1797
1987
`;
@@ -1889,6 +2079,7 @@ function writableRoots ()
1889
2079
if (STATE.isAdmin) return STATE.roots.slice();
1890
2080
return STATE.roots.filter((r) =>
1891
2081
{
2082
if (r.isUserFolder) return true;
1892
2083
const perm = STATE.permissions[rootPermissionLabel(r)];
1893
2084
return !!(perm && perm.write);
1894
2085
});
@@ -1928,6 +2119,40 @@ async function moveWithConflictResolution (item, targetDir)
1928
2119
}
1929
2120
}
1930
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
1931
2156
function ensureMoveModal ()
1932
2157
{
1933
2158
let overlay = document.getElementById('move-modal');
@@ -1979,17 +2204,26 @@ function ensureMoveModal ()
1979
2204
1980
2205
try
1981
2206
{
1982
const moved = await moveWithConflictResolution(st.item, st.selectedPath);
1983
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
}
1984
2217
}
1985
2218
catch (err)
1986
2219
{
1987
toast('Move failed: ' + err.message, 'err');
2220
const action = st.mode === 'copy' ? 'Copy' : 'Move';
2221
toast(`${action} failed: ${err.message}`, 'err');
1988
2222
return;
1989
2223
}
1990
2224
1991
2225
hide();
1992
if (STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
2226
if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();
1993
2227
navigateTo(STATE.currentDir, STATE.currentRoot);
1994
2228
});
1995
2229
@@ -2074,7 +2308,7 @@ function createMoveNode (folderPath, label)
2074
2308
return node;
2075
2309
}
2076
2310
2077
function openMovePicker (item)
2311
function openDestinationPicker (item, mode)
2078
2312
{
2079
2313
if (!canWrite())
2080
2314
{
@@ -2092,8 +2326,13 @@ function openMovePicker (item)
2092
2326
const overlay = ensureMoveModal();
2093
2327
const tree = overlay.querySelector('#move-tree');
2094
2328
const caption = overlay.querySelector('#move-modal-caption');
2329
const titleEl = overlay.querySelector('h2');
2330
const confirmBtn = overlay.querySelector('#move-modal-confirm');
2095
2331
2096
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';
2097
2336
caption.textContent = `Select destination folder for: ${item.name}`;
2098
2337
tree.innerHTML = '';
2099
2338
@@ -2106,6 +2345,16 @@ function openMovePicker (item)
2106
2345
overlay.classList.remove('hidden');
2107
2346
}
2108
2347
2348
function openMovePicker (item)
2349
{
2350
openDestinationPicker(item, 'move');
2351
}
2352
2353
function openCopyPicker (item)
2354
{
2355
openDestinationPicker(item, 'copy');
2356
}
2357
2109
2358
// ───────────────────────────────────────────────────────────────────────────
2110
2359
// FOLDER ICON PICKER
2111
2360
// ───────────────────────────────────────────────────────────────────────────
@@ -3558,6 +3807,16 @@ async function refreshAdminConfig ()
3558
3807
{
3559
3808
const data = await api('GET', '/admin/config');
3560
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
3561
3820
const container = document.getElementById('admin-paths');
3562
3821
container.innerHTML = '';
3563
3822
for (const p of data.paths)
@@ -4406,6 +4665,45 @@ function wireEvents ()
4406
4665
} catch (err) { toast(err.message, 'err'); }
4407
4666
});
4408
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
4409
4707
// Shutdown / restart server
4410
4708
document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4411
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
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
function extOf (name)631
function 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
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
function splitNameExt (name)683
function 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 root1360
// Build path segments relative to the root.1291
const rootPath = STATE.currentRoot.path;1361
const rootPath = STATE.currentRoot.path;1292
const relative = STATE.currentDir === rootPath1362
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 crumb1377
// Root crumb points to rootPath; segment crumbs point to their folder.1311
const capturedPath = i === 0 ? rootPath : accumulated;1378
const capturedPath = i === 01379
? rootPath1380
: 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 segment1326
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
} else1414
{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
@@ -1585,6 +1652,101 @@ function selectItem (el, item)1585
// SIDEBAR1652
// SIDEBAR1586
// ───────────────────────────────────────────────────────────────────────────1653
// ───────────────────────────────────────────────────────────────────────────1587
1654
1655
/**1656
* Renders (or clears) the duplicates panel at the bottom of the sidebar.1657
* @param {object|null} item — the item whose duplicates are shown; null = clear1658
* @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state1659
*/1660
function renderSidebarDuplicates (item, duplicates)1661
{1662
const panel = document.getElementById('sidebar-duplicates');1663
if (!panel) return;1664
1665
// Clear / hide when no item or no duplicates.1666
if (!item || (Array.isArray(duplicates) && duplicates.length === 0))1667
{1668
panel.classList.add('hidden');1669
panel.innerHTML = '';1670
return;1671
}1672
1673
// Loading state.1674
if (duplicates === null)1675
{1676
panel.classList.add('hidden');1677
panel.innerHTML = '';1678
return;1679
}1680
1681
panel.innerHTML = '';1682
const heading = document.createElement('p');1683
heading.className = 'sidebar-duplicates-heading';1684
heading.textContent = `Duplicates (${duplicates.length})`;1685
panel.appendChild(heading);1686
1687
const list = document.createElement('ul');1688
list.className = 'sidebar-duplicates-list';1689
1690
for (const dup of duplicates)1691
{1692
const li = document.createElement('li');1693
const btn = document.createElement('button');1694
btn.className = 'sidebar-duplicate-entry';1695
btn.title = dup.path;1696
// Show path relative to its root; keep absolute path in the tooltip.1697
btn.textContent = dup.relativePath || dup.path;1698
btn.addEventListener('click', () => navigateToDuplicate(dup));1699
li.appendChild(btn);1700
list.appendChild(li);1701
}1702
1703
panel.appendChild(list);1704
panel.classList.remove('hidden');1705
}1706
1707
/**1708
* Navigates to the folder containing a duplicate file and then auto-opens it.1709
* @param {{ path: string, name: string, dir: string }} dup1710
*/1711
async function navigateToDuplicate (dup)1712
{1713
// If the duplicate lives in the folder already shown, just select it.1714
if (STATE.currentDir && samePath(dup.dir, STATE.currentDir))1715
{1716
const tile = Array.from(document.querySelectorAll('.file-item'))1717
.find((el) => el.dataset.path === dup.path);1718
const dupItem = STATE.items.find((i) => i.path === dup.path);1719
if (tile && dupItem)1720
{1721
selectItem(tile, dupItem);1722
}1723
return;1724
}1725
1726
// Find the root that contains the duplicate.1727
const root = STATE.roots.find(1728
(r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'),1729
);1730
if (!root)1731
{1732
toast('Cannot navigate to duplicate: root not accessible.', 'err');1733
return;1734
}1735
1736
await navigateTo(dup.dir, root);1737
1738
// After navigation, find and select the file tile to open it.1739
const tile = Array.from(document.querySelectorAll('.file-item'))1740
.find((el) => el.dataset.path === dup.path);1741
const dupItem = STATE.items.find((i) => i.path === dup.path);1742
1743
if (tile && dupItem)1744
{1745
selectItem(tile, dupItem);1746
}1747
}1748
// ───────────────────────────────────────────────────────────────────────────1749
1588
async function openSidebar (item)1750
async function openSidebar (item)1589
{1751
{1590
const sidebar = document.getElementById('sidebar');1752
const sidebar = document.getElementById('sidebar');@@ -1608,6 +1770,9 @@ async function openSidebar (item)1608
const actions = document.getElementById('sidebar-actions');1770
const actions = document.getElementById('sidebar-actions');1609
actions.innerHTML = '';1771
actions.innerHTML = '';1610
1772
1773
// Reset duplicates panel whenever a new item is opened.1774
renderSidebarDuplicates(null, null);1775
1611
if (!item.isDir)1776
if (!item.isDir)1612
{1777
{1613
const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);1778
const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);@@ -1628,6 +1793,21 @@ async function openSidebar (item)1628
`;1793
`;1629
}1794
}1630
1795
1796
// Fetch and render duplicate files.1797
renderSidebarDuplicates(item, null); // show loading state1798
const selectedPathAtRequest = item.path;1799
api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`)1800
.then((data) =>1801
{1802
if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;1803
renderSidebarDuplicates(item, data ? data.duplicates : []);1804
})1805
.catch(() =>1806
{1807
if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return;1808
renderSidebarDuplicates(item, []);1809
});1810
1631
// View / download button1811
// View / download button1632
const btnDl = document.createElement('button');1812
const btnDl = document.createElement('button');1633
btnDl.textContent = 'View / Download';1813
btnDl.textContent = 'View / Download';@@ -1743,6 +1923,14 @@ async function openSidebar (item)1743
btnMove.textContent = 'Move to';1923
btnMove.textContent = 'Move to';1744
btnMove.addEventListener('click', () => openMovePicker(item));1924
btnMove.addEventListener('click', () => openMovePicker(item));1745
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
}1746
}1934
}1747
1935
1748
const btnRen = document.createElement('button');1936
const btnRen = document.createElement('button');@@ -1773,6 +1961,7 @@ function openFolderSidebar ()1773
const dl = document.getElementById('sidebar-meta');1961
const dl = document.getElementById('sidebar-meta');1774
const actions = document.getElementById('sidebar-actions');1962
const actions = document.getElementById('sidebar-actions');1775
actions.innerHTML = '';1963
actions.innerHTML = '';1964
renderSidebarDuplicates(null, null);1776
1965
1777
if (!STATE.currentDir || !STATE.currentRoot)1966
if (!STATE.currentDir || !STATE.currentRoot)1778
{1967
{@@ -1790,8 +1979,9 @@ function openFolderSidebar ()1790
1979
1791
const dirs = STATE.items.filter(i => i.isDir).length;1980
const dirs = STATE.items.filter(i => i.isDir).length;1792
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);1793
const baseDetails = `1983
const baseDetails = `1794
<dt>Path</dt><dd>${STATE.currentDir}</dd>1984
<dt>Path</dt><dd>${displayPath}</dd>1795
<dt>Folders</dt><dd>${dirs}</dd>1985
<dt>Folders</dt><dd>${dirs}</dd>1796
<dt>Files</dt><dd>${files}</dd>1986
<dt>Files</dt><dd>${files}</dd>1797
`;1987
`;@@ -1889,6 +2079,7 @@ function writableRoots ()1889
if (STATE.isAdmin) return STATE.roots.slice();2079
if (STATE.isAdmin) return STATE.roots.slice();1890
return STATE.roots.filter((r) =>2080
return STATE.roots.filter((r) =>1891
{2081
{2082
if (r.isUserFolder) return true;1892
const perm = STATE.permissions[rootPermissionLabel(r)];2083
const perm = STATE.permissions[rootPermissionLabel(r)];1893
return !!(perm && perm.write);2084
return !!(perm && perm.write);1894
});2085
});@@ -1928,6 +2119,40 @@ async function moveWithConflictResolution (item, targetDir)1928
}2119
}1929
}2120
}1930
2121
2122
async function copyWithConflictResolution (item, targetDir)2123
{2124
try2125
{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
1931
function ensureMoveModal ()2156
function ensureMoveModal ()1932
{2157
{1933
let overlay = document.getElementById('move-modal');2158
let overlay = document.getElementById('move-modal');@@ -1979,17 +2204,26 @@ function ensureMoveModal ()1979
2204
1980
try2205
try1981
{2206
{1982
const moved = await moveWithConflictResolution(st.item, st.selectedPath);2207
if (st.mode === 'copy')1983
if (!moved) return;2208
{2209
const copied = await copyWithConflictResolution(st.item, st.selectedPath);2210
if (!copied) return;2211
}2212
else2213
{2214
const moved = await moveWithConflictResolution(st.item, st.selectedPath);2215
if (!moved) return;2216
}1984
}2217
}1985
catch (err)2218
catch (err)1986
{2219
{1987
toast('Move failed: ' + err.message, 'err');2220
const action = st.mode === 'copy' ? 'Copy' : 'Move';2221
toast(`${action} failed: ${err.message}`, 'err');1988
return;2222
return;1989
}2223
}1990
2224
1991
hide();2225
hide();1992
if (STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();2226
if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar();1993
navigateTo(STATE.currentDir, STATE.currentRoot);2227
navigateTo(STATE.currentDir, STATE.currentRoot);1994
});2228
});1995
2229
@@ -2074,7 +2308,7 @@ function createMoveNode (folderPath, label)2074
return node;2308
return node;2075
}2309
}2076
2310
2077
function openMovePicker (item)2311
function openDestinationPicker (item, mode)2078
{2312
{2079
if (!canWrite())2313
if (!canWrite())2080
{2314
{@@ -2092,8 +2326,13 @@ function openMovePicker (item)2092
const overlay = ensureMoveModal();2326
const overlay = ensureMoveModal();2093
const tree = overlay.querySelector('#move-tree');2327
const tree = overlay.querySelector('#move-tree');2094
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');2095
2331
2096
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';2097
caption.textContent = `Select destination folder for: ${item.name}`;2336
caption.textContent = `Select destination folder for: ${item.name}`;2098
tree.innerHTML = '';2337
tree.innerHTML = '';2099
2338
@@ -2106,6 +2345,16 @@ function openMovePicker (item)2106
overlay.classList.remove('hidden');2345
overlay.classList.remove('hidden');2107
}2346
}2108
2347
2348
function openMovePicker (item)2349
{2350
openDestinationPicker(item, 'move');2351
}2352
2353
function openCopyPicker (item)2354
{2355
openDestinationPicker(item, 'copy');2356
}2357
2109
// ───────────────────────────────────────────────────────────────────────────2358
// ───────────────────────────────────────────────────────────────────────────2110
// FOLDER ICON PICKER2359
// FOLDER ICON PICKER2111
// ───────────────────────────────────────────────────────────────────────────2360
// ───────────────────────────────────────────────────────────────────────────@@ -3558,6 +3807,16 @@ async function refreshAdminConfig ()3558
{3807
{3559
const data = await api('GET', '/admin/config');3808
const data = await api('GET', '/admin/config');3560
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
3561
const container = document.getElementById('admin-paths');3820
const container = document.getElementById('admin-paths');3562
container.innerHTML = '';3821
container.innerHTML = '';3563
for (const p of data.paths)3822
for (const p of data.paths)@@ -4406,6 +4665,45 @@ function wireEvents ()4406
} catch (err) { toast(err.message, 'err'); }4665
} catch (err) { toast(err.message, 'err'); }4407
});4666
});4408
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
try4691
{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
4409
// Shutdown / restart server4707
// Shutdown / restart server4410
document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>4708
document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>4411
{4709
{@@ -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>
@@ -132,6 +132,7 @@
132
132
<h2 id="sidebar-name"></h2>
133
133
<dl id="sidebar-meta"></dl>
134
134
<div id="sidebar-actions"></div>
135
<div id="sidebar-duplicates" class="hidden"></div>
135
136
</aside>
136
137
137
138
</div>
@@ -144,6 +145,18 @@
144
145
<button class="modal-close" id="admin-modal-close" aria-label="Close admin panel">✕</button>
145
146
<h2>Admin Panel</h2>
146
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
147
160
<section>
148
161
<h3>Configured Paths</h3>
149
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
Username24
Username25
<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
Password28
Password29
<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>@@ -132,6 +132,7 @@132
<h2 id="sidebar-name"></h2>132
<h2 id="sidebar-name"></h2>133
<dl id="sidebar-meta"></dl>133
<dl id="sidebar-meta"></dl>134
<div id="sidebar-actions"></div>134
<div id="sidebar-actions"></div>135
<div id="sidebar-duplicates" class="hidden"></div>135
</aside>136
</aside>136
137
137
</div>138
</div>@@ -144,6 +145,18 @@144
<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>145
<h2>Admin Panel</h2>146
<h2>Admin Panel</h2>146
147
148
<section id="admin-userfolder-section">149
<h3>User Folders</h3>150
<label>User folder path151
<input id="admin-user-path" type="text" placeholder="/data/userfolders" />152
</label>153
<label>Size limit per user154
<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
147
<section>160
<section>148
<h3>Configured Paths</h3>161
<h3>Configured Paths</h3>149
<div id="admin-paths"></div>162
<div id="admin-paths"></div>@@ -446,6 +446,65 @@ button.danger:hover {
446
446
color: var(--danger);
447
447
}
448
448
449
/* ─── Duplicates panel ─────────────────────────────────── */
450
#sidebar-duplicates {
451
margin-top: 1rem;
452
border-top: 1px solid var(--border);
453
padding-top: 0.75rem;
454
}
455
456
.sidebar-duplicates-heading {
457
font-size: 0.75rem;
458
font-weight: 600;
459
text-transform: uppercase;
460
letter-spacing: 0.05em;
461
color: var(--text-muted, #888);
462
margin: 0 0 0.4rem;
463
}
464
465
.sidebar-duplicates-list {
466
list-style: none;
467
margin: 0;
468
padding: 0;
469
display: flex;
470
flex-direction: column;
471
gap: 0.25rem;
472
}
473
474
.sidebar-duplicate-entry {
475
display: block;
476
width: 100%;
477
background: var(--surface2);
478
color: var(--text);
479
padding: 0.35rem 0.6rem;
480
text-align: left;
481
font-size: 0.8rem;
482
white-space: nowrap;
483
overflow: hidden;
484
text-overflow: ellipsis;
485
border-radius: var(--radius);
486
cursor: pointer;
487
}
488
489
.sidebar-duplicate-entry:hover {
490
background: var(--border);
491
}
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
449
508
/* =========================================================
450
509
MODALS
451
510
========================================================= */
@@ -719,6 +778,31 @@ button.danger:hover {
719
778
border-color: var(--accent);
720
779
}
721
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
722
806
/* =========================================================
723
807
FILE PREVIEW — SHARED MEDIA STYLES
724
808
========================================================= */
@@ -446,6 +446,65 @@ button.danger:hover {446
color: var(--danger);
446
color: var(--danger);
447
}
447
}
448
448
449
/* ─── Duplicates panel ─────────────────────────────────── */
450
#sidebar-duplicates {
451
margin-top: 1rem;
452
border-top: 1px solid var(--border);
453
padding-top: 0.75rem;
454
}
455
456
.sidebar-duplicates-heading {
457
font-size: 0.75rem;
458
font-weight: 600;
459
text-transform: uppercase;
460
letter-spacing: 0.05em;
461
color: var(--text-muted, #888);
462
margin: 0 0 0.4rem;
463
}
464
465
.sidebar-duplicates-list {
466
list-style: none;
467
margin: 0;
468
padding: 0;
469
display: flex;
470
flex-direction: column;
471
gap: 0.25rem;
472
}
473
474
.sidebar-duplicate-entry {
475
display: block;
476
width: 100%;
477
background: var(--surface2);
478
color: var(--text);
479
padding: 0.35rem 0.6rem;
480
text-align: left;
481
font-size: 0.8rem;
482
white-space: nowrap;
483
overflow: hidden;
484
text-overflow: ellipsis;
485
border-radius: var(--radius);
486
cursor: pointer;
487
}
488
489
.sidebar-duplicate-entry:hover {
490
background: var(--border);
491
}
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
449
/* =========================================================
508
/* =========================================================
450
MODALS
509
MODALS
451
========================================================= */
510
========================================================= */
@@ -719,6 +778,31 @@ button.danger:hover {719
border-color: var(--accent);
778
border-color: var(--accent);
720
}
779
}
721
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
722
/* =========================================================
806
/* =========================================================
723
FILE PREVIEW — SHARED MEDIA STYLES
807
FILE PREVIEW — SHARED MEDIA STYLES
724
========================================================= */
808
========================================================= */
@@ -64,11 +64,21 @@ function initDb ()
64
64
`);
65
65
66
66
const fileMetaCols = d.prepare('PRAGMA table_info(file_meta)').all();
67
const hasWatchedBy = fileMetaCols.some((col) => String(col.name || '') === 'watched_by');
68
if (!hasWatchedBy)
67
const colNames = fileMetaCols.map((col) => String(col.name || ''));
68
69
if (!colNames.includes('watched_by'))
69
70
{
70
71
d.exec("ALTER TABLE file_meta ADD COLUMN watched_by TEXT NOT NULL DEFAULT '{}'");
71
72
}
73
74
if (!colNames.includes('sha256'))
75
{
76
d.exec('ALTER TABLE file_meta ADD COLUMN sha256 TEXT');
77
d.exec('CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256)');
78
} else
79
{
80
d.exec('CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256)');
81
}
72
82
}
73
83
74
84
function closeDb ()
@@ -64,11 +64,21 @@ function initDb ()64
`);64
`);65
65
66
const fileMetaCols = d.prepare('PRAGMA table_info(file_meta)').all();66
const fileMetaCols = d.prepare('PRAGMA table_info(file_meta)').all();67
const hasWatchedBy = fileMetaCols.some((col) => String(col.name || '') === 'watched_by');67
const colNames = fileMetaCols.map((col) => String(col.name || ''));68
if (!hasWatchedBy)68
69
if (!colNames.includes('watched_by'))69
{70
{70
d.exec("ALTER TABLE file_meta ADD COLUMN watched_by TEXT NOT NULL DEFAULT '{}'");71
d.exec("ALTER TABLE file_meta ADD COLUMN watched_by TEXT NOT NULL DEFAULT '{}'");71
}72
}73
74
if (!colNames.includes('sha256'))75
{76
d.exec('ALTER TABLE file_meta ADD COLUMN sha256 TEXT');77
d.exec('CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256)');78
} else79
{80
d.exec('CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256)');81
}72
}82
}73
83
74
function closeDb ()84
function closeDb ()@@ -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
3
const express = require('express');3
const express = require('express');4
const bcrypt = require('bcrypt');4
const bcrypt = require('bcrypt');5
const fs = require('fs');5
const path = require('path');6
const path = require('path');6
const { execFile } = require('child_process');7
const { execFile } = require('child_process');7
const { promisify } = require('util');8
const { promisify } = require('util');@@ -10,6 +11,37 @@ const router = express.Router();10
const execFileAsync = promisify(execFile);11
const execFileAsync = promisify(execFile);11
const PROJECT_ROOT = path.resolve(__dirname, '../../');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
try22
{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
try36
{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
const { getDb } = require('../db');45
const { getDb } = require('../db');14
const { requireAuth, requireAdmin } = require('../auth');46
const { requireAuth, requireAdmin } = require('../auth');15
const { loadConfig, saveConfig, getEffectivePaths } = require('../config');47
const { 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/config197
// GET /api/admin/config158
// Returns the current server config (paths, port).198
// Returns the current server config (paths, port, userPath, userFolderSizeLimit).159
// ---------------------------------------------------------------------------199
// ---------------------------------------------------------------------------160
router.get('/config', (req, res) =>200
router.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/config214
// PUT /api/admin/config169
// 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
// ---------------------------------------------------------------------------172
router.put('/config', (req, res) =>218
router.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
} else249
{250
const lim = Number(userFolderSizeLimit);251
config.userFolderSizeLimit = Number.isFinite(lim) && lim > 0 ? lim : null;252
}253
}254
186
try255
try187
{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
@@ -14,6 +14,28 @@ const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourc
14
14
const { buildZip } = require('./share');
15
15
const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
16
16
17
// ---------------------------------------------------------------------------
18
// SHA-256 hashing helper
19
// ---------------------------------------------------------------------------
20
21
/**
22
* Computes the SHA-256 hex digest of the file at `filePath`.
23
* Streams the file so it works for large files without loading them into memory.
24
* @param {string} filePath
25
* @returns {Promise<string>} hex digest
26
*/
27
function computeFileSha256 (filePath)
28
{
29
return new Promise((resolve, reject) =>
30
{
31
const hash = crypto.createHash('sha256');
32
const stream = fs.createReadStream(filePath);
33
stream.on('error', reject);
34
stream.on('data', (chunk) => hash.update(chunk));
35
stream.on('end', () => resolve(hash.digest('hex')));
36
});
37
}
38
17
39
// ---------------------------------------------------------------------------
18
40
// Multer storage — files are staged into temporary files and only promoted
19
41
// to their final names after the full stream arrives.
@@ -168,6 +190,25 @@ function effectivePaths ()
168
190
return getEffectivePaths(loadConfig().paths || []);
169
191
}
170
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
171
212
function rootAliasesFromConfig (config)
172
213
{
173
214
if (!config || typeof config !== 'object') return {};
@@ -246,6 +287,103 @@ function canWrite (user, pathLabel)
246
287
return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
247
288
}
248
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
249
387
/**
250
388
* Given an absolute path and the effective-paths list, return
251
389
* { root, label } where label is the base-name of the root, or null.
@@ -271,19 +409,20 @@ function pathInsideResolved (child, root)
271
409
function rewriteMetaPaths (fromPath, toPath)
272
410
{
273
411
const db = getDb();
274
const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
412
const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by, sha256 FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
275
413
.all([fromPath, fromPath + path.sep + '%']);
276
414
277
415
if (!rows.length) return;
278
416
279
417
const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
280
418
const upsert = db.prepare(`
281
INSERT INTO file_meta (file_path, uploader, downloaders, watched_by)
282
VALUES (?, ?, ?, ?)
419
INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, sha256)
420
VALUES (?, ?, ?, ?, ?)
283
421
ON CONFLICT(file_path) DO UPDATE SET
284
422
uploader = excluded.uploader,
285
423
downloaders = excluded.downloaders,
286
watched_by = excluded.watched_by
424
watched_by = excluded.watched_by,
425
sha256 = excluded.sha256
287
426
`);
288
427
289
428
for (const row of rows)
@@ -292,7 +431,7 @@ function rewriteMetaPaths (fromPath, toPath)
292
431
? toPath
293
432
: toPath + row.file_path.slice(fromPath.length);
294
433
del.run([row.file_path]);
295
upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}']);
434
upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}', row.sha256 || null]);
296
435
}
297
436
}
298
437
@@ -372,6 +511,7 @@ function removePathRecursive (targetPath)
372
511
// ---------------------------------------------------------------------------
373
512
// GET /api/files/roots
374
513
// Returns the effective configured paths the user can read.
514
// Also injects the user's personal folder when userPath is configured.
375
515
// ---------------------------------------------------------------------------
376
516
router.get('/roots', requireAuth, (req, res) =>
377
517
{
@@ -392,6 +532,24 @@ router.get('/roots', requireAuth, (req, res) =>
392
532
alias: alias || null,
393
533
};
394
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
395
553
res.json({ roots: readable });
396
554
});
397
555
@@ -529,10 +687,9 @@ router.get('/list', requireAuth, (req, res) =>
529
687
const dir = req.query.dir;
530
688
if (!dir) return res.status(400).json({ error: 'dir is required.' });
531
689
532
const roots = effectivePaths();
533
const info = resolveRoot(dir, roots);
534
if (!info) return res.status(403).json({ error: 'Access denied.' });
535
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.' });
536
693
537
694
let entries;
538
695
try
@@ -569,16 +726,16 @@ router.get('/list', requireAuth, (req, res) =>
569
726
570
727
// ---------------------------------------------------------------------------
571
728
// GET /api/files/meta?file=<absolute-path>
572
// Returns file metadata from the DB.
729
// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
573
730
// ---------------------------------------------------------------------------
574
router.get('/meta', requireAuth, (req, res) =>
731
router.get('/meta', requireAuth, async (req, res) =>
575
732
{
576
733
const file = req.query.file;
577
734
if (!file) return res.status(400).json({ error: 'file is required.' });
578
735
579
const roots = effectivePaths();
580
const info = resolveRoot(file, roots);
581
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))
582
739
{
583
740
return res.status(403).json({ error: 'Access denied.' });
584
741
}
@@ -593,7 +750,29 @@ router.get('/meta', requireAuth, (req, res) =>
593
750
}
594
751
595
752
const db = getDb();
596
const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
753
let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
754
755
// Lazily compute and persist the SHA-256 hash when it is absent.
756
let sha256 = meta ? (meta.sha256 || null) : null;
757
if (!sha256 && !stat.isDirectory())
758
{
759
try
760
{
761
sha256 = await computeFileSha256(file);
762
if (meta)
763
{
764
db.prepare('UPDATE file_meta SET sha256 = ? WHERE file_path = ?').run([sha256, file]);
765
} else
766
{
767
db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
768
.run([file, '', '[]', sha256]);
769
meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
770
}
771
} catch
772
{
773
// Non-fatal — hash will be retried next time.
774
}
775
}
597
776
598
777
res.json({
599
778
name: path.basename(file),
@@ -602,9 +781,62 @@ router.get('/meta', requireAuth, (req, res) =>
602
781
uploader: meta ? meta.uploader : '',
603
782
downloaders: meta ? parseJsonArray(meta.downloaders) : [],
604
783
watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
784
sha256: sha256 || null,
605
785
});
606
786
});
607
787
788
// ---------------------------------------------------------------------------
789
// GET /api/files/duplicates?file=<absolute-path>
790
// Returns other files with the same SHA-256 hash that the user can access.
791
// ---------------------------------------------------------------------------
792
router.get('/duplicates', requireAuth, (req, res) =>
793
{
794
const file = req.query.file;
795
if (!file) return res.status(400).json({ error: 'file is required.' });
796
797
const { config, roots } = loadConfigAndRoots();
798
const info = resolveRootForUser(file, roots, req.user, config);
799
if (!info || !canReadInfo(req.user, info))
800
{
801
return res.status(403).json({ error: 'Access denied.' });
802
}
803
804
const db = getDb();
805
const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);
806
const hash = row ? (row.sha256 || null) : null;
807
if (!hash)
808
{
809
return res.json({ duplicates: [] });
810
}
811
812
// All other files sharing the same hash.
813
const candidates = db.prepare(
814
'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
815
).all([hash, file]);
816
817
const duplicates = [];
818
for (const { file_path } of candidates)
819
{
820
// Only return files inside a root the user can access and that still exist on disk.
821
const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
822
if (!dupInfo || !canReadInfo(req.user, dupInfo)) 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
828
duplicates.push({
829
path: file_path,
830
name: path.basename(file_path),
831
dir: path.dirname(file_path),
832
rootPath: dupInfo.root,
833
relativePath,
834
});
835
}
836
837
res.json({ duplicates });
838
});
839
608
840
// ---------------------------------------------------------------------------
609
841
// GET /api/files/space?dir=<absolute-path>
610
842
// Returns recursive used bytes for dir and available bytes on its root fs.
@@ -614,9 +846,9 @@ router.get('/space', requireAuth, (req, res) =>
614
846
const dir = req.query.dir;
615
847
if (!dir) return res.status(400).json({ error: 'dir is required.' });
616
848
617
const roots = effectivePaths();
618
const info = resolveRoot(dir, roots);
619
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))
620
852
{
621
853
return res.status(403).json({ error: 'Access denied.' });
622
854
}
@@ -628,9 +860,13 @@ router.get('/space', requireAuth, (req, res) =>
628
860
629
861
const usedBytes = getRecursiveSize(dir);
630
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);
631
865
res.json({
632
866
usedBytes,
633
867
freeBytes,
868
userLimitBytes,
869
userFreeBytes,
634
870
rootPath: info.root,
635
871
rootLabel: info.label,
636
872
});
@@ -645,9 +881,9 @@ router.get('/download', requireAuth, (req, res) =>
645
881
const file = req.query.file;
646
882
if (!file) return res.status(400).json({ error: 'file is required.' });
647
883
648
const roots = effectivePaths();
649
const info = resolveRoot(file, roots);
650
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))
651
887
{
652
888
return res.status(403).json({ error: 'Access denied.' });
653
889
}
@@ -695,9 +931,9 @@ router.post('/watch-progress', requireAuth, (req, res) =>
695
931
return res.json({ ok: true, updated: false });
696
932
}
697
933
698
const roots = effectivePaths();
699
const info = resolveRoot(filePath, roots);
700
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))
701
937
{
702
938
return res.status(403).json({ error: 'Access denied.' });
703
939
}
@@ -742,9 +978,9 @@ router.post('/video-stream', requireAuth, async (req, res, next) =>
742
978
const filePath = String(req.body?.filePath || '').trim();
743
979
if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
744
980
745
const roots = effectivePaths();
746
const info = resolveRoot(filePath, roots);
747
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))
748
984
{
749
985
return res.status(403).json({ error: 'Access denied.' });
750
986
}
@@ -810,9 +1046,9 @@ router.get('/download-zip', requireAuth, async (req, res) =>
810
1046
const dir = req.query.dir;
811
1047
if (!dir) return res.status(400).json({ error: 'dir is required.' });
812
1048
813
const roots = effectivePaths();
814
const info = resolveRoot(dir, roots);
815
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))
816
1052
{
817
1053
return res.status(403).json({ error: 'Access denied.' });
818
1054
}
@@ -844,9 +1080,9 @@ router.get('/thumbnail', requireAuth, async (req, res) =>
844
1080
const file = req.query.file;
845
1081
if (!file) return res.status(400).json({ error: 'file is required.' });
846
1082
847
const roots = effectivePaths();
848
const info = resolveRoot(file, roots);
849
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))
850
1086
{
851
1087
return res.status(403).json({ error: 'Access denied.' });
852
1088
}
@@ -876,9 +1112,9 @@ router.post('/upload', requireAuth, (req, res, next) =>
876
1112
const dir = req.query.dir;
877
1113
if (!dir) return res.status(400).json({ error: 'dir is required.' });
878
1114
879
const roots = effectivePaths();
880
const info = resolveRoot(dir, roots);
881
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))
882
1118
{
883
1119
return res.status(403).json({ error: 'Access denied.' });
884
1120
}
@@ -902,9 +1138,17 @@ router.post('/upload', requireAuth, (req, res, next) =>
902
1138
}
903
1139
}
904
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
905
1149
req._uploadDir = dir;
906
1150
907
upload.array('files')(req, res, (err) =>
1151
upload.array('files')(req, res, async (err) =>
908
1152
{
909
1153
if (err) return res.status(500).json({ error: err.message });
910
1154
@@ -912,15 +1156,25 @@ router.post('/upload', requireAuth, (req, res, next) =>
912
1156
for (const f of (req.files || []))
913
1157
{
914
1158
const filePath = path.join(dir, f.originalname);
1159
1160
let sha256 = null;
1161
try
1162
{
1163
sha256 = await computeFileSha256(filePath);
1164
} catch
1165
{
1166
// Non-fatal — hash can be computed lazily when the file is accessed.
1167
}
1168
915
1169
const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
916
1170
if (existing)
917
1171
{
918
db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
919
.run([req.user.username, filePath]);
1172
db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ? WHERE file_path = ?')
1173
.run([req.user.username, sha256, filePath]);
920
1174
} else
921
1175
{
922
db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
923
.run([filePath, req.user.username, '[]']);
1176
db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1177
.run([filePath, req.user.username, '[]', sha256]);
924
1178
}
925
1179
}
926
1180
res.json({ uploaded: (req.files || []).map(f => f.originalname) });
@@ -942,17 +1196,17 @@ router.post('/rename', requireAuth, (req, res) =>
942
1196
return res.status(400).json({ error: 'Invalid name.' });
943
1197
}
944
1198
945
const roots = effectivePaths();
946
const info = resolveRoot(from, roots);
947
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))
948
1202
{
949
1203
return res.status(403).json({ error: 'Access denied.' });
950
1204
}
951
1205
952
1206
const dest = path.join(path.dirname(from), to);
953
1207
954
// Ensure dest is still inside the same root
955
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))
956
1210
{
957
1211
return res.status(403).json({ error: 'Access denied.' });
958
1212
}
@@ -992,11 +1246,11 @@ router.post('/move', requireAuth, (req, res) =>
992
1246
return res.status(400).json({ error: 'Invalid targetName.' });
993
1247
}
994
1248
995
const roots = effectivePaths();
996
const fromInfo = resolveRoot(from, roots);
997
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);
998
1252
if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
999
if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
1253
if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1000
1254
{
1001
1255
return res.status(403).json({ error: 'Access denied.' });
1002
1256
}
@@ -1016,7 +1270,15 @@ router.post('/move', requireAuth, (req, res) =>
1016
1270
1017
1271
const requestedName = targetName || path.basename(from);
1018
1272
const requestedDest = path.join(toDir, requestedName);
1019
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
}
1020
1282
if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1021
1283
{
1022
1284
return res.status(400).json({ error: 'Cannot move onto itself.' });
@@ -1086,15 +1348,15 @@ router.post('/mkdir', requireAuth, (req, res) =>
1086
1348
return res.status(400).json({ error: 'Invalid folder name.' });
1087
1349
}
1088
1350
1089
const roots = effectivePaths();
1090
const info = resolveRoot(dir, roots);
1091
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))
1092
1354
{
1093
1355
return res.status(403).json({ error: 'Access denied.' });
1094
1356
}
1095
1357
1096
1358
const newDir = path.join(dir, name);
1097
if (!getAllowedRoot(newDir, roots))
1359
if (!isAccessiblePath(newDir, roots, req.user, config))
1098
1360
{
1099
1361
return res.status(403).json({ error: 'Access denied.' });
1100
1362
}
@@ -1119,9 +1381,9 @@ router.post('/delete', requireAuth, (req, res) =>
1119
1381
const target = req.body.path;
1120
1382
if (!target) return res.status(400).json({ error: 'path is required.' });
1121
1383
1122
const roots = effectivePaths();
1123
const info = resolveRoot(target, roots);
1124
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))
1125
1387
{
1126
1388
return res.status(403).json({ error: 'Access denied.' });
1127
1389
}
@@ -1165,9 +1427,9 @@ router.get('/folder-images', requireAuth, async (req, res) =>
1165
1427
const dir = String(req.query.dir || '').trim();
1166
1428
if (!dir) return res.status(400).json({ error: 'dir is required.' });
1167
1429
1168
const roots = effectivePaths();
1169
const info = resolveRoot(dir, roots);
1170
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))
1171
1433
{
1172
1434
return res.status(403).json({ error: 'Access denied.' });
1173
1435
}
@@ -1178,8 +1440,8 @@ router.get('/folder-images', requireAuth, async (req, res) =>
1178
1440
}
1179
1441
1180
1442
const images = await getImagesWithThumbnailsInDir(dir);
1181
// Filter out any that escaped to a different root (safety check).
1182
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));
1183
1445
1184
1446
res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1185
1447
});
@@ -1193,9 +1455,9 @@ router.get('/folder-icon', requireAuth, async (req, res) =>
1193
1455
const dir = String(req.query.dir || '').trim();
1194
1456
if (!dir) return res.status(400).json({ error: 'dir is required.' });
1195
1457
1196
const roots = effectivePaths();
1197
const info = resolveRoot(dir, roots);
1198
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))
1199
1461
{
1200
1462
return res.status(403).json({ error: 'Access denied.' });
1201
1463
}
@@ -1203,8 +1465,8 @@ router.get('/folder-icon', requireAuth, async (req, res) =>
1203
1465
const sourceFile = await getFolderIconSourceFile(dir);
1204
1466
if (!sourceFile) return res.json({ icon: null });
1205
1467
1206
// Verify the source is still accessible within a configured root.
1207
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 });
1208
1470
1209
1471
res.json({ icon: { filePath: sourceFile } });
1210
1472
});
@@ -1221,9 +1483,9 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1221
1483
1222
1484
if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1223
1485
1224
const roots = effectivePaths();
1225
const info = resolveRoot(folderPath, roots);
1226
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))
1227
1489
{
1228
1490
return res.status(403).json({ error: 'Access denied.' });
1229
1491
}
@@ -1235,9 +1497,8 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1235
1497
1236
1498
if (rawImage !== null)
1237
1499
{
1238
// Verify the image is inside a readable root.
1239
const imageRoot = getAllowedRoot(rawImage, roots);
1240
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.' });
1241
1502
1242
1503
// Must already have a cached thumbnail — only thumbnailed images can be selected.
1243
1504
const thumb = await getCachedThumbnailInfo(rawImage);
@@ -1248,4 +1509,93 @@ router.post('/folder-icon', requireAuth, async (req, res) =>
1248
1509
res.json({ ok: true });
1249
1510
});
1250
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
1251
1601
module.exports = router;
@@ -14,6 +14,28 @@ const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourc14
const { buildZip } = require('./share');14
const { buildZip } = require('./share');15
const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');15
const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');16
16
17
// ---------------------------------------------------------------------------18
// SHA-256 hashing helper19
// ---------------------------------------------------------------------------20
21
/**22
* Computes the SHA-256 hex digest of the file at `filePath`.23
* Streams the file so it works for large files without loading them into memory.24
* @param {string} filePath25
* @returns {Promise<string>} hex digest26
*/27
function computeFileSha256 (filePath)28
{29
return new Promise((resolve, reject) =>30
{31
const hash = crypto.createHash('sha256');32
const stream = fs.createReadStream(filePath);33
stream.on('error', reject);34
stream.on('data', (chunk) => hash.update(chunk));35
stream.on('end', () => resolve(hash.digest('hex')));36
});37
}38
17
// ---------------------------------------------------------------------------39
// ---------------------------------------------------------------------------18
// Multer storage — files are staged into temporary files and only promoted40
// Multer storage — files are staged into temporary files and only promoted19
// to their final names after the full stream arrives.41
// to their final names after the full stream arrives.@@ -168,6 +190,25 @@ function effectivePaths ()168
return getEffectivePaths(loadConfig().paths || []);190
return getEffectivePaths(loadConfig().paths || []);169
}191
}170
192
193
/**194
* Loads config and returns { config, roots } together so both are consistent195
* 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 a205
* 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
171
function rootAliasesFromConfig (config)212
function rootAliasesFromConfig (config)172
{213
{173
if (!config || typeof config !== 'object') return {};214
if (!config || typeof config !== 'object') return {};@@ -246,6 +287,103 @@ function canWrite (user, pathLabel)246
return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);287
return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);247
}288
}248
289
290
// ---------------------------------------------------------------------------291
// User folder helpers292
// ---------------------------------------------------------------------------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's307
* 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 object333
* 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 access339
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 would363
* 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
249
/**387
/**250
* Given an absolute path and the effective-paths list, return388
* Given an absolute path and the effective-paths list, return251
* { 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.@@ -271,19 +409,20 @@ function pathInsideResolved (child, root)271
function rewriteMetaPaths (fromPath, toPath)409
function rewriteMetaPaths (fromPath, toPath)272
{410
{273
const db = getDb();411
const db = getDb();274
const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by FROM file_meta WHERE file_path = ? OR file_path LIKE ?')412
const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by, sha256 FROM file_meta WHERE file_path = ? OR file_path LIKE ?')275
.all([fromPath, fromPath + path.sep + '%']);413
.all([fromPath, fromPath + path.sep + '%']);276
414
277
if (!rows.length) return;415
if (!rows.length) return;278
416
279
const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');417
const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');280
const upsert = db.prepare(`418
const upsert = db.prepare(`281
INSERT INTO file_meta (file_path, uploader, downloaders, watched_by)419
INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, sha256)282
VALUES (?, ?, ?, ?)420
VALUES (?, ?, ?, ?, ?)283
ON CONFLICT(file_path) DO UPDATE SET421
ON CONFLICT(file_path) DO UPDATE SET284
uploader = excluded.uploader,422
uploader = excluded.uploader,285
downloaders = excluded.downloaders,423
downloaders = excluded.downloaders,286
watched_by = excluded.watched_by424
watched_by = excluded.watched_by,425
sha256 = excluded.sha256287
`);426
`);288
427
289
for (const row of rows)428
for (const row of rows)@@ -292,7 +431,7 @@ function rewriteMetaPaths (fromPath, toPath)292
? toPath431
? toPath293
: toPath + row.file_path.slice(fromPath.length);432
: toPath + row.file_path.slice(fromPath.length);294
del.run([row.file_path]);433
del.run([row.file_path]);295
upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}']);434
upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}', row.sha256 || null]);296
}435
}297
}436
}298
437
@@ -372,6 +511,7 @@ function removePathRecursive (targetPath)372
// ---------------------------------------------------------------------------511
// ---------------------------------------------------------------------------373
// GET /api/files/roots512
// GET /api/files/roots374
// 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.375
// ---------------------------------------------------------------------------515
// ---------------------------------------------------------------------------376
router.get('/roots', requireAuth, (req, res) =>516
router.get('/roots', requireAuth, (req, res) =>377
{517
{@@ -392,6 +532,24 @@ router.get('/roots', requireAuth, (req, res) =>392
alias: alias || null,532
alias: alias || null,393
};533
};394
});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
395
res.json({ roots: readable });553
res.json({ roots: readable });396
});554
});397
555
@@ -529,10 +687,9 @@ router.get('/list', requireAuth, (req, res) =>529
const dir = req.query.dir;687
const dir = req.query.dir;530
if (!dir) return res.status(400).json({ error: 'dir is required.' });688
if (!dir) return res.status(400).json({ error: 'dir is required.' });531
689
532
const roots = effectivePaths();690
const { config, roots } = loadConfigAndRoots();533
const info = resolveRoot(dir, roots);691
const info = resolveRootForUser(dir, roots, req.user, config);534
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.' });535
if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });536
693
537
let entries;694
let entries;538
try695
try@@ -569,16 +726,16 @@ router.get('/list', requireAuth, (req, res) =>569
726
570
// ---------------------------------------------------------------------------727
// ---------------------------------------------------------------------------571
// GET /api/files/meta?file=<absolute-path>728
// GET /api/files/meta?file=<absolute-path>572
// Returns file metadata from the DB.729
// Returns file metadata from the DB. Lazily computes SHA-256 when missing.573
// ---------------------------------------------------------------------------730
// ---------------------------------------------------------------------------574
router.get('/meta', requireAuth, (req, res) =>731
router.get('/meta', requireAuth, async (req, res) =>575
{732
{576
const file = req.query.file;733
const file = req.query.file;577
if (!file) return res.status(400).json({ error: 'file is required.' });734
if (!file) return res.status(400).json({ error: 'file is required.' });578
735
579
const roots = effectivePaths();736
const { config, roots } = loadConfigAndRoots();580
const info = resolveRoot(file, roots);737
const info = resolveRootForUser(file, roots, req.user, config);581
if (!info || !canRead(req.user, info.label))738
if (!info || !canReadInfo(req.user, info))582
{739
{583
return res.status(403).json({ error: 'Access denied.' });740
return res.status(403).json({ error: 'Access denied.' });584
}741
}@@ -593,7 +750,29 @@ router.get('/meta', requireAuth, (req, res) =>593
}750
}594
751
595
const db = getDb();752
const db = getDb();596
const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);753
let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);754
755
// Lazily compute and persist the SHA-256 hash when it is absent.756
let sha256 = meta ? (meta.sha256 || null) : null;757
if (!sha256 && !stat.isDirectory())758
{759
try760
{761
sha256 = await computeFileSha256(file);762
if (meta)763
{764
db.prepare('UPDATE file_meta SET sha256 = ? WHERE file_path = ?').run([sha256, file]);765
} else766
{767
db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')768
.run([file, '', '[]', sha256]);769
meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);770
}771
} catch772
{773
// Non-fatal — hash will be retried next time.774
}775
}597
776
598
res.json({777
res.json({599
name: path.basename(file),778
name: path.basename(file),@@ -602,9 +781,62 @@ router.get('/meta', requireAuth, (req, res) =>602
uploader: meta ? meta.uploader : '',781
uploader: meta ? meta.uploader : '',603
downloaders: meta ? parseJsonArray(meta.downloaders) : [],782
downloaders: meta ? parseJsonArray(meta.downloaders) : [],604
watchedBy: meta ? parseJsonObject(meta.watched_by) : {},783
watchedBy: meta ? parseJsonObject(meta.watched_by) : {},784
sha256: sha256 || null,605
});785
});606
});786
});607
787
788
// ---------------------------------------------------------------------------789
// GET /api/files/duplicates?file=<absolute-path>790
// Returns other files with the same SHA-256 hash that the user can access.791
// ---------------------------------------------------------------------------792
router.get('/duplicates', requireAuth, (req, res) =>793
{794
const file = req.query.file;795
if (!file) return res.status(400).json({ error: 'file is required.' });796
797
const { config, roots } = loadConfigAndRoots();798
const info = resolveRootForUser(file, roots, req.user, config);799
if (!info || !canReadInfo(req.user, info))800
{801
return res.status(403).json({ error: 'Access denied.' });802
}803
804
const db = getDb();805
const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);806
const hash = row ? (row.sha256 || null) : null;807
if (!hash)808
{809
return res.json({ duplicates: [] });810
}811
812
// All other files sharing the same hash.813
const candidates = db.prepare(814
'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',815
).all([hash, file]);816
817
const duplicates = [];818
for (const { file_path } of candidates)819
{820
// Only return files inside a root the user can access and that still exist on disk.821
const dupInfo = resolveRootForUser(file_path, roots, req.user, config);822
if (!dupInfo || !canReadInfo(req.user, dupInfo)) 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
828
duplicates.push({829
path: file_path,830
name: path.basename(file_path),831
dir: path.dirname(file_path),832
rootPath: dupInfo.root,833
relativePath,834
});835
}836
837
res.json({ duplicates });838
});839
608
// ---------------------------------------------------------------------------840
// ---------------------------------------------------------------------------609
// GET /api/files/space?dir=<absolute-path>841
// GET /api/files/space?dir=<absolute-path>610
// Returns recursive used bytes for dir and available bytes on its root fs.842
// Returns recursive used bytes for dir and available bytes on its root fs.@@ -614,9 +846,9 @@ router.get('/space', requireAuth, (req, res) =>614
const dir = req.query.dir;846
const dir = req.query.dir;615
if (!dir) return res.status(400).json({ error: 'dir is required.' });847
if (!dir) return res.status(400).json({ error: 'dir is required.' });616
848
617
const roots = effectivePaths();849
const { config, roots } = loadConfigAndRoots();618
const info = resolveRoot(dir, roots);850
const info = resolveRootForUser(dir, roots, req.user, config);619
if (!info || !canRead(req.user, info.label))851
if (!info || !canReadInfo(req.user, info))620
{852
{621
return res.status(403).json({ error: 'Access denied.' });853
return res.status(403).json({ error: 'Access denied.' });622
}854
}@@ -628,9 +860,13 @@ router.get('/space', requireAuth, (req, res) =>628
860
629
const usedBytes = getRecursiveSize(dir);861
const usedBytes = getRecursiveSize(dir);630
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);631
res.json({865
res.json({632
usedBytes,866
usedBytes,633
freeBytes,867
freeBytes,868
userLimitBytes,869
userFreeBytes,634
rootPath: info.root,870
rootPath: info.root,635
rootLabel: info.label,871
rootLabel: info.label,636
});872
});@@ -645,9 +881,9 @@ router.get('/download', requireAuth, (req, res) =>645
const file = req.query.file;881
const file = req.query.file;646
if (!file) return res.status(400).json({ error: 'file is required.' });882
if (!file) return res.status(400).json({ error: 'file is required.' });647
883
648
const roots = effectivePaths();884
const { config, roots } = loadConfigAndRoots();649
const info = resolveRoot(file, roots);885
const info = resolveRootForUser(file, roots, req.user, config);650
if (!info || !canRead(req.user, info.label))886
if (!info || !canReadInfo(req.user, info))651
{887
{652
return res.status(403).json({ error: 'Access denied.' });888
return res.status(403).json({ error: 'Access denied.' });653
}889
}@@ -695,9 +931,9 @@ router.post('/watch-progress', requireAuth, (req, res) =>695
return res.json({ ok: true, updated: false });931
return res.json({ ok: true, updated: false });696
}932
}697
933
698
const roots = effectivePaths();934
const { config, roots } = loadConfigAndRoots();699
const info = resolveRoot(filePath, roots);935
const info = resolveRootForUser(filePath, roots, req.user, config);700
if (!info || !canRead(req.user, info.label))936
if (!info || !canReadInfo(req.user, info))701
{937
{702
return res.status(403).json({ error: 'Access denied.' });938
return res.status(403).json({ error: 'Access denied.' });703
}939
}@@ -742,9 +978,9 @@ router.post('/video-stream', requireAuth, async (req, res, next) =>742
const filePath = String(req.body?.filePath || '').trim();978
const filePath = String(req.body?.filePath || '').trim();743
if (!filePath) return res.status(400).json({ error: 'filePath is required.' });979
if (!filePath) return res.status(400).json({ error: 'filePath is required.' });744
980
745
const roots = effectivePaths();981
const { config, roots } = loadConfigAndRoots();746
const info = resolveRoot(filePath, roots);982
const info = resolveRootForUser(filePath, roots, req.user, config);747
if (!info || !canRead(req.user, info.label))983
if (!info || !canReadInfo(req.user, info))748
{984
{749
return res.status(403).json({ error: 'Access denied.' });985
return res.status(403).json({ error: 'Access denied.' });750
}986
}@@ -810,9 +1046,9 @@ router.get('/download-zip', requireAuth, async (req, res) =>810
const dir = req.query.dir;1046
const dir = req.query.dir;811
if (!dir) return res.status(400).json({ error: 'dir is required.' });1047
if (!dir) return res.status(400).json({ error: 'dir is required.' });812
1048
813
const roots = effectivePaths();1049
const { config, roots } = loadConfigAndRoots();814
const info = resolveRoot(dir, roots);1050
const info = resolveRootForUser(dir, roots, req.user, config);815
if (!info || !canRead(req.user, info.label))1051
if (!info || !canReadInfo(req.user, info))816
{1052
{817
return res.status(403).json({ error: 'Access denied.' });1053
return res.status(403).json({ error: 'Access denied.' });818
}1054
}@@ -844,9 +1080,9 @@ router.get('/thumbnail', requireAuth, async (req, res) =>844
const file = req.query.file;1080
const file = req.query.file;845
if (!file) return res.status(400).json({ error: 'file is required.' });1081
if (!file) return res.status(400).json({ error: 'file is required.' });846
1082
847
const roots = effectivePaths();1083
const { config, roots } = loadConfigAndRoots();848
const info = resolveRoot(file, roots);1084
const info = resolveRootForUser(file, roots, req.user, config);849
if (!info || !canRead(req.user, info.label))1085
if (!info || !canReadInfo(req.user, info))850
{1086
{851
return res.status(403).json({ error: 'Access denied.' });1087
return res.status(403).json({ error: 'Access denied.' });852
}1088
}@@ -876,9 +1112,9 @@ router.post('/upload', requireAuth, (req, res, next) =>876
const dir = req.query.dir;1112
const dir = req.query.dir;877
if (!dir) return res.status(400).json({ error: 'dir is required.' });1113
if (!dir) return res.status(400).json({ error: 'dir is required.' });878
1114
879
const roots = effectivePaths();1115
const { config, roots } = loadConfigAndRoots();880
const info = resolveRoot(dir, roots);1116
const info = resolveRootForUser(dir, roots, req.user, config);881
if (!info || !canWrite(req.user, info.label))1117
if (!info || !canWriteInfo(req.user, info))882
{1118
{883
return res.status(403).json({ error: 'Access denied.' });1119
return res.status(403).json({ error: 'Access denied.' });884
}1120
}@@ -902,9 +1138,17 @@ router.post('/upload', requireAuth, (req, res, next) =>902
}1138
}903
}1139
}904
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
905
req._uploadDir = dir;1149
req._uploadDir = dir;906
1150
907
upload.array('files')(req, res, (err) =>1151
upload.array('files')(req, res, async (err) =>908
{1152
{909
if (err) return res.status(500).json({ error: err.message });1153
if (err) return res.status(500).json({ error: err.message });910
1154
@@ -912,15 +1156,25 @@ router.post('/upload', requireAuth, (req, res, next) =>912
for (const f of (req.files || []))1156
for (const f of (req.files || []))913
{1157
{914
const filePath = path.join(dir, f.originalname);1158
const filePath = path.join(dir, f.originalname);1159
1160
let sha256 = null;1161
try1162
{1163
sha256 = await computeFileSha256(filePath);1164
} catch1165
{1166
// Non-fatal — hash can be computed lazily when the file is accessed.1167
}1168
915
const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);1169
const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);916
if (existing)1170
if (existing)917
{1171
{918
db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')1172
db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ? WHERE file_path = ?')919
.run([req.user.username, filePath]);1173
.run([req.user.username, sha256, filePath]);920
} else1174
} else921
{1175
{922
db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')1176
db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')923
.run([filePath, req.user.username, '[]']);1177
.run([filePath, req.user.username, '[]', sha256]);924
}1178
}925
}1179
}926
res.json({ uploaded: (req.files || []).map(f => f.originalname) });1180
res.json({ uploaded: (req.files || []).map(f => f.originalname) });@@ -942,17 +1196,17 @@ router.post('/rename', requireAuth, (req, res) =>942
return res.status(400).json({ error: 'Invalid name.' });1196
return res.status(400).json({ error: 'Invalid name.' });943
}1197
}944
1198
945
const roots = effectivePaths();1199
const { config, roots } = loadConfigAndRoots();946
const info = resolveRoot(from, roots);1200
const info = resolveRootForUser(from, roots, req.user, config);947
if (!info || !canWrite(req.user, info.label))1201
if (!info || !canWriteInfo(req.user, info))948
{1202
{949
return res.status(403).json({ error: 'Access denied.' });1203
return res.status(403).json({ error: 'Access denied.' });950
}1204
}951
1205
952
const dest = path.join(path.dirname(from), to);1206
const dest = path.join(path.dirname(from), to);953
1207
954
// Ensure dest is still inside the same root1208
// Ensure dest is still inside the same accessible root or user folder.955
if (!getAllowedRoot(dest, roots))1209
if (!isAccessiblePath(dest, roots, req.user, config))956
{1210
{957
return res.status(403).json({ error: 'Access denied.' });1211
return res.status(403).json({ error: 'Access denied.' });958
}1212
}@@ -992,11 +1246,11 @@ router.post('/move', requireAuth, (req, res) =>992
return res.status(400).json({ error: 'Invalid targetName.' });1246
return res.status(400).json({ error: 'Invalid targetName.' });993
}1247
}994
1248
995
const roots = effectivePaths();1249
const { config, roots } = loadConfigAndRoots();996
const fromInfo = resolveRoot(from, roots);1250
const fromInfo = resolveRootForUser(from, roots, req.user, config);997
const toInfo = resolveRoot(toDir, roots);1251
const toInfo = resolveRootForUser(toDir, roots, req.user, config);998
if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });1252
if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });999
if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))1253
if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))1000
{1254
{1001
return res.status(403).json({ error: 'Access denied.' });1255
return res.status(403).json({ error: 'Access denied.' });1002
}1256
}@@ -1016,7 +1270,15 @@ router.post('/move', requireAuth, (req, res) =>1016
1270
1017
const requestedName = targetName || path.basename(from);1271
const requestedName = targetName || path.basename(from);1018
const requestedDest = path.join(toDir, requestedName);1272
const requestedDest = path.join(toDir, requestedName);1019
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
}1020
if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))1282
if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))1021
{1283
{1022
return res.status(400).json({ error: 'Cannot move onto itself.' });1284
return res.status(400).json({ error: 'Cannot move onto itself.' });@@ -1086,15 +1348,15 @@ router.post('/mkdir', requireAuth, (req, res) =>1086
return res.status(400).json({ error: 'Invalid folder name.' });1348
return res.status(400).json({ error: 'Invalid folder name.' });1087
}1349
}1088
1350
1089
const roots = effectivePaths();1351
const { config, roots } = loadConfigAndRoots();1090
const info = resolveRoot(dir, roots);1352
const info = resolveRootForUser(dir, roots, req.user, config);1091
if (!info || !canWrite(req.user, info.label))1353
if (!info || !canWriteInfo(req.user, info))1092
{1354
{1093
return res.status(403).json({ error: 'Access denied.' });1355
return res.status(403).json({ error: 'Access denied.' });1094
}1356
}1095
1357
1096
const newDir = path.join(dir, name);1358
const newDir = path.join(dir, name);1097
if (!getAllowedRoot(newDir, roots))1359
if (!isAccessiblePath(newDir, roots, req.user, config))1098
{1360
{1099
return res.status(403).json({ error: 'Access denied.' });1361
return res.status(403).json({ error: 'Access denied.' });1100
}1362
}@@ -1119,9 +1381,9 @@ router.post('/delete', requireAuth, (req, res) =>1119
const target = req.body.path;1381
const target = req.body.path;1120
if (!target) return res.status(400).json({ error: 'path is required.' });1382
if (!target) return res.status(400).json({ error: 'path is required.' });1121
1383
1122
const roots = effectivePaths();1384
const { config, roots } = loadConfigAndRoots();1123
const info = resolveRoot(target, roots);1385
const info = resolveRootForUser(target, roots, req.user, config);1124
if (!info || !canWrite(req.user, info.label))1386
if (!info || !canWriteInfo(req.user, info))1125
{1387
{1126
return res.status(403).json({ error: 'Access denied.' });1388
return res.status(403).json({ error: 'Access denied.' });1127
}1389
}@@ -1165,9 +1427,9 @@ router.get('/folder-images', requireAuth, async (req, res) =>1165
const dir = String(req.query.dir || '').trim();1427
const dir = String(req.query.dir || '').trim();1166
if (!dir) return res.status(400).json({ error: 'dir is required.' });1428
if (!dir) return res.status(400).json({ error: 'dir is required.' });1167
1429
1168
const roots = effectivePaths();1430
const { config, roots } = loadConfigAndRoots();1169
const info = resolveRoot(dir, roots);1431
const info = resolveRootForUser(dir, roots, req.user, config);1170
if (!info || !canRead(req.user, info.label))1432
if (!info || !canReadInfo(req.user, info))1171
{1433
{1172
return res.status(403).json({ error: 'Access denied.' });1434
return res.status(403).json({ error: 'Access denied.' });1173
}1435
}@@ -1178,8 +1440,8 @@ router.get('/folder-images', requireAuth, async (req, res) =>1178
}1440
}1179
1441
1180
const images = await getImagesWithThumbnailsInDir(dir);1442
const images = await getImagesWithThumbnailsInDir(dir);1181
// Filter out any that escaped to a different root (safety check).1443
// Filter out any that escaped to a different accessible root (safety check).1182
const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));1444
const filtered = images.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));1183
1445
1184
res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });1446
res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });1185
});1447
});@@ -1193,9 +1455,9 @@ router.get('/folder-icon', requireAuth, async (req, res) =>1193
const dir = String(req.query.dir || '').trim();1455
const dir = String(req.query.dir || '').trim();1194
if (!dir) return res.status(400).json({ error: 'dir is required.' });1456
if (!dir) return res.status(400).json({ error: 'dir is required.' });1195
1457
1196
const roots = effectivePaths();1458
const { config, roots } = loadConfigAndRoots();1197
const info = resolveRoot(dir, roots);1459
const info = resolveRootForUser(dir, roots, req.user, config);1198
if (!info || !canRead(req.user, info.label))1460
if (!info || !canReadInfo(req.user, info))1199
{1461
{1200
return res.status(403).json({ error: 'Access denied.' });1462
return res.status(403).json({ error: 'Access denied.' });1201
}1463
}@@ -1203,8 +1465,8 @@ router.get('/folder-icon', requireAuth, async (req, res) =>1203
const sourceFile = await getFolderIconSourceFile(dir);1465
const sourceFile = await getFolderIconSourceFile(dir);1204
if (!sourceFile) return res.json({ icon: null });1466
if (!sourceFile) return res.json({ icon: null });1205
1467
1206
// Verify the source is still accessible within a configured root.1468
// Verify the source is still accessible within a configured root or user folder.1207
if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });1469
if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });1208
1470
1209
res.json({ icon: { filePath: sourceFile } });1471
res.json({ icon: { filePath: sourceFile } });1210
});1472
});@@ -1221,9 +1483,9 @@ router.post('/folder-icon', requireAuth, async (req, res) =>1221
1483
1222
if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });1484
if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });1223
1485
1224
const roots = effectivePaths();1486
const { config, roots } = loadConfigAndRoots();1225
const info = resolveRoot(folderPath, roots);1487
const info = resolveRootForUser(folderPath, roots, req.user, config);1226
if (!info || !canWrite(req.user, info.label))1488
if (!info || !canWriteInfo(req.user, info))1227
{1489
{1228
return res.status(403).json({ error: 'Access denied.' });1490
return res.status(403).json({ error: 'Access denied.' });1229
}1491
}@@ -1235,9 +1497,8 @@ router.post('/folder-icon', requireAuth, async (req, res) =>1235
1497
1236
if (rawImage !== null)1498
if (rawImage !== null)1237
{1499
{1238
// Verify the image is inside a readable root.1500
// Verify the image is inside a readable root or user folder.1239
const imageRoot = getAllowedRoot(rawImage, roots);1501
if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });1240
if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });1241
1502
1242
// 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.1243
const thumb = await getCachedThumbnailInfo(rawImage);1504
const thumb = await getCachedThumbnailInfo(rawImage);@@ -1248,4 +1509,93 @@ router.post('/folder-icon', requireAuth, async (req, res) =>1248
res.json({ ok: true });1509
res.json({ ok: true });1249
});1510
});1250
1511
1512
// ---------------------------------------------------------------------------1513
// POST /api/files/copy1514
// 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 != null1523
? 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
try1591
{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
1251
module.exports = router;1601
module.exports = router;@@ -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
208
function effectiveRoots ()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 for214
// 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
function pathInsideOrEqualResolved (targetPath, rootPath)232
function pathInsideOrEqualResolved (targetPath, rootPath)@@ -39,8 +39,10 @@ jest.mock('../server/db', () =>
39
39
file_path TEXT PRIMARY KEY,
40
40
uploader TEXT NOT NULL DEFAULT '',
41
41
downloaders TEXT NOT NULL DEFAULT '[]',
42
watched_by TEXT NOT NULL DEFAULT '{}'
42
watched_by TEXT NOT NULL DEFAULT '{}',
43
sha256 TEXT
43
44
);
45
CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256);
44
46
`);
45
47
}
46
48
return db;
@@ -773,3 +775,115 @@ describe('video streaming routes', () =>
773
775
expect(result.body.watchedBy).toEqual({ admin: 'fully' });
774
776
});
775
777
});
778
779
describe('SHA-256 hashing and duplicate detection', () =>
780
{
781
test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>
782
{
783
const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
784
{ name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
785
]);
786
expect(status).toBe(200);
787
788
const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
789
.get([path.join(rootDir, 'hashme.txt')]);
790
expect(meta).toBeTruthy();
791
// SHA-256 is a 64-char hex string.
792
expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
793
});
794
795
test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>
796
{
797
const filePath = path.join(rootDir, 'lazy.txt');
798
fs.writeFileSync(filePath, 'lazy content');
799
800
// Insert a row without a hash to simulate a pre-existing file.
801
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
802
.run([filePath, 'admin', '[]']);
803
804
const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
805
expect(status).toBe(200);
806
expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
807
808
// Verify it was persisted.
809
const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
810
expect(row.sha256).toBe(body.sha256);
811
});
812
813
test('GET /api/files/duplicates returns other files with the same hash', async () =>
814
{
815
const content = 'duplicate content';
816
const fileA = path.join(rootDir, 'dup-a.txt');
817
const fileB = path.join(rootDir, 'dup-b.txt');
818
fs.writeFileSync(fileA, content);
819
fs.writeFileSync(fileB, content);
820
821
// Compute the expected hash.
822
const crypto = require('crypto');
823
const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
824
825
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
826
.run([fileA, 'admin', '[]', expectedHash]);
827
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
828
.run([fileB, 'admin', '[]', expectedHash]);
829
830
const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
831
expect(status).toBe(200);
832
expect(body.duplicates).toHaveLength(1);
833
expect(body.duplicates[0].path).toBe(fileB);
834
expect(body.duplicates[0].name).toBe('dup-b.txt');
835
});
836
837
test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
838
{
839
const filePath = path.join(rootDir, 'nohash.txt');
840
fs.writeFileSync(filePath, 'no hash yet');
841
842
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
843
.run([filePath, 'admin', '[]']);
844
845
const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
846
expect(status).toBe(200);
847
expect(body.duplicates).toEqual([]);
848
});
849
850
test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
851
{
852
const content = 'secret dupe';
853
const accessible = path.join(rootDir, 'visible.txt');
854
const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
855
fs.writeFileSync(accessible, content);
856
857
const crypto = require('crypto');
858
const hash = crypto.createHash('sha256').update(content).digest('hex');
859
860
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
861
.run([accessible, 'admin', '[]', hash]);
862
// Insert a row for a path that is NOT inside any configured root.
863
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
864
.run([outsideRoot, 'admin', '[]', hash]);
865
866
const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
867
expect(status).toBe(200);
868
expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
869
});
870
871
test('POST /api/files/move preserves sha256 after rename', async () =>
872
{
873
const from = path.join(rootDir, 'withHash.txt');
874
const toDir = path.join(rootDir, 'subfolder');
875
fs.writeFileSync(from, 'content');
876
fs.mkdirSync(toDir);
877
878
const hash = 'a'.repeat(64);
879
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
880
.run([from, 'admin', '[]', hash]);
881
882
const { status } = await req('POST', '/api/files/move', { from, toDir });
883
expect(status).toBe(200);
884
885
const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
886
.get([path.join(toDir, 'withHash.txt')]);
887
expect(meta.sha256).toBe(hash);
888
});
889
});
@@ -39,8 +39,10 @@ jest.mock('../server/db', () =>39
file_path TEXT PRIMARY KEY,39
file_path TEXT PRIMARY KEY,40
uploader TEXT NOT NULL DEFAULT '',40
uploader TEXT NOT NULL DEFAULT '',41
downloaders TEXT NOT NULL DEFAULT '[]',41
downloaders TEXT NOT NULL DEFAULT '[]',42
watched_by TEXT NOT NULL DEFAULT '{}'42
watched_by TEXT NOT NULL DEFAULT '{}',43
sha256 TEXT43
);44
);45
CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256);44
`);46
`);45
}47
}46
return db;48
return db;@@ -773,3 +775,115 @@ describe('video streaming routes', () =>773
expect(result.body.watchedBy).toEqual({ admin: 'fully' });775
expect(result.body.watchedBy).toEqual({ admin: 'fully' });774
});776
});775
});777
});778
779
describe('SHA-256 hashing and duplicate detection', () =>780
{781
test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>782
{783
const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [784
{ name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },785
]);786
expect(status).toBe(200);787
788
const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')789
.get([path.join(rootDir, 'hashme.txt')]);790
expect(meta).toBeTruthy();791
// SHA-256 is a 64-char hex string.792
expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);793
});794
795
test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>796
{797
const filePath = path.join(rootDir, 'lazy.txt');798
fs.writeFileSync(filePath, 'lazy content');799
800
// Insert a row without a hash to simulate a pre-existing file.801
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')802
.run([filePath, 'admin', '[]']);803
804
const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);805
expect(status).toBe(200);806
expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);807
808
// Verify it was persisted.809
const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);810
expect(row.sha256).toBe(body.sha256);811
});812
813
test('GET /api/files/duplicates returns other files with the same hash', async () =>814
{815
const content = 'duplicate content';816
const fileA = path.join(rootDir, 'dup-a.txt');817
const fileB = path.join(rootDir, 'dup-b.txt');818
fs.writeFileSync(fileA, content);819
fs.writeFileSync(fileB, content);820
821
// Compute the expected hash.822
const crypto = require('crypto');823
const expectedHash = crypto.createHash('sha256').update(content).digest('hex');824
825
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')826
.run([fileA, 'admin', '[]', expectedHash]);827
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')828
.run([fileB, 'admin', '[]', expectedHash]);829
830
const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);831
expect(status).toBe(200);832
expect(body.duplicates).toHaveLength(1);833
expect(body.duplicates[0].path).toBe(fileB);834
expect(body.duplicates[0].name).toBe('dup-b.txt');835
});836
837
test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>838
{839
const filePath = path.join(rootDir, 'nohash.txt');840
fs.writeFileSync(filePath, 'no hash yet');841
842
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')843
.run([filePath, 'admin', '[]']);844
845
const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);846
expect(status).toBe(200);847
expect(body.duplicates).toEqual([]);848
});849
850
test('GET /api/files/duplicates excludes files outside accessible roots', async () =>851
{852
const content = 'secret dupe';853
const accessible = path.join(rootDir, 'visible.txt');854
const outsideRoot = path.join(os.tmpdir(), 'outside.txt');855
fs.writeFileSync(accessible, content);856
857
const crypto = require('crypto');858
const hash = crypto.createHash('sha256').update(content).digest('hex');859
860
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')861
.run([accessible, 'admin', '[]', hash]);862
// Insert a row for a path that is NOT inside any configured root.863
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')864
.run([outsideRoot, 'admin', '[]', hash]);865
866
const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);867
expect(status).toBe(200);868
expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);869
});870
871
test('POST /api/files/move preserves sha256 after rename', async () =>872
{873
const from = path.join(rootDir, 'withHash.txt');874
const toDir = path.join(rootDir, 'subfolder');875
fs.writeFileSync(from, 'content');876
fs.mkdirSync(toDir);877
878
const hash = 'a'.repeat(64);879
getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')880
.run([from, 'admin', '[]', hash]);881
882
const { status } = await req('POST', '/api/files/move', { from, toDir });883
expect(status).toBe(200);884
885
const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')886
.get([path.join(toDir, 'withHash.txt')]);887
expect(meta.sha256).toBe(hash);888
});889
});