Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

feat: add the ability to browse storage files

towfiqi39314e948a55
diff --git a/backend/__tests__/controllers/RestoreController.test.ts b/backend/__tests__/controllers/RestoreController.test.ts
index c0e4bc8..1494f7e 100644
--- a/backend/__tests__/controllers/RestoreController.test.ts
+++ b/backend/__tests__/controllers/RestoreController.test.ts
@@ -252,6 +252,9 @@ describe('RestoreController', () => {
includes: ['file1.txt'],
excludes: ['*.tmp'],
delete: false,
+ storageId: undefined,
+ replicationId: undefined,
+ fromStorage: false,
});
expect(mockStatus).toHaveBeenCalledWith(200);
expect(mockJson).toHaveBeenCalledWith({
@@ -277,6 +280,9 @@ describe('RestoreController', () => {
includes: [],
excludes: [],
delete: false,
+ storageId: undefined,
+ replicationId: undefined,
+ fromStorage: false,
});
});
@@ -331,6 +337,9 @@ describe('RestoreController', () => {
includes: [],
excludes: [],
delete: false,
+ storageId: undefined,
+ replicationId: undefined,
+ fromStorage: false,
});
expect(mockStatus).toHaveBeenCalledWith(200);
expect(mockJson).toHaveBeenCalledWith({
diff --git a/backend/src/controllers/RestoreController.ts b/backend/src/controllers/RestoreController.ts
index 2d20317..7a857b1 100644
--- a/backend/src/controllers/RestoreController.ts
+++ b/backend/src/controllers/RestoreController.ts
@@ -11,6 +11,7 @@ type RestorePayload = {
delete?: boolean;
storageId?: string;
replicationId?: string;
+ fromStorage?: boolean;
};
export class RestoreController {
@@ -97,6 +98,7 @@ export class RestoreController {
delete: restorePayload.delete || false,
storageId: restorePayload.storageId || undefined,
replicationId: restorePayload.replicationId || undefined,
+ fromStorage: restorePayload.fromStorage || false,
});
res.status(200).json({
success: true,
@@ -129,6 +131,7 @@ export class RestoreController {
delete: restorePayload.delete || false,
storageId: restorePayload.storageId || undefined,
replicationId: restorePayload.replicationId || undefined,
+ fromStorage: restorePayload.fromStorage || false,
});
res.status(200).json({
diff --git a/backend/src/controllers/StorageController.ts b/backend/src/controllers/StorageController.ts
index ea99ca9..32505db 100644
--- a/backend/src/controllers/StorageController.ts
+++ b/backend/src/controllers/StorageController.ts
@@ -40,6 +40,24 @@ export class StorageController {
}
}
+ async browseStorage(req: Request, res: Response): Promise<void> {
+ if (!req.params.id) {
+ res.status(400).json({ success: false, error: 'Storage ID is required' });
+ return;
+ }
+ try {
+ const requestedPath = req.query.path ? decodeURIComponent(req.query.path as string) : '';
+ const result = await this.storageService.browseStorage(req.params.id, requestedPath);
+ res.json({ success: true, result });
+ } catch (error: any) {
+ console.log('Error browsing storage:', error);
+ res.status(error?.statusCode || 500).json({
+ success: false,
+ error: error?.message || 'Failed to read storage contents',
+ });
+ }
+ }
+
async createStorage(req: Request, res: Response): Promise<void> {
try {
if (!req.body.name || !req.body.type || !req.body.settings || !req.body.credentials) {
diff --git a/backend/src/routes/storages.ts b/backend/src/routes/storages.ts
index 6c3af25..827d577 100644
--- a/backend/src/routes/storages.ts
+++ b/backend/src/routes/storages.ts
@@ -10,6 +10,7 @@ export function createStorageRouter(
router.get('/', authM, controller.listStorages.bind(controller));
router.get('/available', authM, controller.listAvailableStorageTypes.bind(controller));
router.get('/:id', authM, controller.getStorage.bind(controller));
+ router.get('/:id/browse', authM, controller.browseStorage.bind(controller));
router.put('/:id', authM, controller.updateStorage.bind(controller));
router.delete('/:id', authM, controller.deleteStorage.bind(controller));
router.post('/verify/:id', authM, controller.verifyStorage.bind(controller));
diff --git a/backend/src/services/RestoreService.ts b/backend/src/services/RestoreService.ts
index 33ba3df..9f88dc8 100644
--- a/backend/src/services/RestoreService.ts
+++ b/backend/src/services/RestoreService.ts
@@ -109,6 +109,7 @@ export class RestoreService {
includes: restoreConfig.includes,
excludes: restoreConfig.excludes,
replicationId: restoreConfig.replicationId,
+ fromStorage: restoreConfig.fromStorage,
sources: plan.sourceConfig?.includes || [],
}
);
@@ -170,6 +171,8 @@ export class RestoreService {
includes: restoreConfig.includes || [],
excludes: restoreConfig.excludes || [],
delete: restoreConfig.delete || false,
+ replicationId: restoreConfig.replicationId,
+ fromStorage: restoreConfig.fromStorage,
sources: plan.sourceConfig.includes || [],
performanceSettings,
});
diff --git a/backend/src/services/StorageService.ts b/backend/src/services/StorageService.ts
index c28e21e..6e2d9b6 100644
--- a/backend/src/services/StorageService.ts
+++ b/backend/src/services/StorageService.ts
@@ -1,3 +1,4 @@
+import path from 'path';
import { Storage, storageInsertSchema, storageUpdateSchema } from '../db/schema/storages';
import { providers } from '../utils/providers';
import { PlanStore } from '../stores/PlanStore';
@@ -11,7 +12,8 @@ import {
LocalStrategy as LocalSystemStrategy,
SystemStrategy,
} from '../strategies/system';
-import { generateUID } from '../utils/helpers';
+import { generateUID, normalizeStorageName } from '../utils/helpers';
+import { sanitizeStoragePath } from '../utils/sanitizeStoragePath';
import { BaseSystemManager } from '../managers/BaseSystemManager';
import { configService } from './ConfigService';
import { AppError, NotFoundError } from '../utils/AppError';
@@ -19,8 +21,29 @@ import {
spawnRcloneAuthorize,
RcloneAuthSession,
RcloneAuthSessionStatus,
+ rcloneLsJson,
+ rcloneErrorMessage,
} from '../utils/rclone/helpers';
+export interface StorageBrowseItem {
+ name: string;
+ path: string;
+ type: 'directory' | 'file';
+ isDirectory: boolean;
+ size: number;
+ modifiedAt: string;
+ owner: string;
+ permissions: string;
+}
+
+export interface ResolvedStorageTarget {
+ storage: Storage;
+ remote: string;
+ isLocal: boolean;
+ cleaned: string;
+ target: string;
+}
+
/**
* A class for managing storage operations.
*/
@@ -73,6 +96,103 @@ export class StorageService {
}
}
+ /**
+ * Resolves a storage id plus a user-supplied path into an rclone target.
+ * The path is sanitized here, so callers never build a target from raw input.
+ */
+ protected async resolveStorageTarget(
+ id: string,
+ requestedPath: string
+ ): Promise<ResolvedStorageTarget> {
+ const storage = await this.storageStore.getById(id);
+ if (!storage) {
+ throw new NotFoundError('Storage not found');
+ }
+
+ const remote = storage.id === 'local' ? 'local' : normalizeStorageName(storage.name);
+ const isLocal = storage.type === 'local';
+ const trimmed = (requestedPath || '').trim();
+
+ if (isLocal) {
+ this.assertLocalBrowseAllowed(trimmed);
+ if (!trimmed) {
+ throw new AppError(400, 'A folder path is required to browse the local storage.');
+ }
+ }
+
+ const cleaned = trimmed
+ ? sanitizeStoragePath(trimmed, storage.type as string).replace(/\\/g, '/')
+ : '';
+
+ return { storage, remote, isLocal, cleaned, target: `${remote}:${cleaned}` };
+ }
+
+ /**
+ * The local storage reads the host filesystem, so it obeys the same file browser
+ * limits as the device browser.
+ */
+ protected assertLocalBrowseAllowed(requestedPath: string): void {
+ if (configService.config.ALLOW_FILE_BROWSER === false) {
+ throw new AppError(403, 'File browser is disabled');
+ }
+
+ const browserRoot = configService.config.FILE_BROWSER_ROOT;
+ if (browserRoot && requestedPath) {
+ const resolved = path.resolve(requestedPath);
+ const resolvedRoot = path.resolve(browserRoot);
+ if (!resolved.startsWith(resolvedRoot)) {
+ throw new AppError(403, 'Access denied: path outside allowed root');
+ }
+ }
+ }
+
+ async browseStorage(
+ id: string,
+ requestedPath: string
+ ): Promise<{ path: string; items: StorageBrowseItem[] }> {
+ const storage = await this.storageStore.getById(id);
+ if (!storage) {
+ throw new NotFoundError('Storage not found');
+ }
+
+ // The local storage has no bucket to list, so an empty path means the host's drives.
+ if (storage.type === 'local' && !(requestedPath || '').trim()) {
+ this.assertLocalBrowseAllowed('');
+ const response = await this.getSystemStrategy('main').getBrowsePath('');
+ if (!response.success) {
+ throw new AppError(500, 'Failed to read the local drives');
+ }
+ const result = response.result as unknown as { path: string; items: StorageBrowseItem[] };
+ return { path: '', items: result.items || [] };
+ }
+
+ const { cleaned, target } = await this.resolveStorageTarget(id, requestedPath);
+
+ let entries;
+ try {
+ entries = await rcloneLsJson(target);
+ } catch (error: any) {
+ throw new AppError(400, rcloneErrorMessage(error) || 'Failed to read this storage.');
+ }
+ const items: StorageBrowseItem[] = entries.map(entry => ({
+ name: entry.Name,
+ path: cleaned ? `${cleaned}/${entry.Path}` : entry.Path,
+ type: entry.IsDir ? 'directory' : 'file',
+ isDirectory: entry.IsDir,
+ size: entry.Size < 0 ? 0 : entry.Size,
+ modifiedAt: entry.ModTime || '',
+ owner: '',
+ permissions: '',
+ }));
+
+ items.sort((a, b) => {
+ if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
+ return a.name.localeCompare(b.name);
+ });
+
+ return { path: cleaned, items };
+ }
+
async getAvailableStorageTypes(): Promise<Record<string, any>> {
const providersWithoutLocal = { ...providers };
delete providersWithoutLocal['local'];
diff --git a/backend/src/types/restores.ts b/backend/src/types/restores.ts
index 493c07a..5a1fde8 100644
--- a/backend/src/types/restores.ts
+++ b/backend/src/types/restores.ts
@@ -30,6 +30,7 @@ export interface RestoreConfig {
storageId?: string;
replicationId?: string;
sources?: string[];
+ fromStorage?: boolean; // Reads the selected files from the live storage for sync plans
}
export interface RestoreStats {
diff --git a/backend/src/utils/rclone/helpers.ts b/backend/src/utils/rclone/helpers.ts
index e10378d..d483163 100644
--- a/backend/src/utils/rclone/helpers.ts
+++ b/backend/src/utils/rclone/helpers.ts
@@ -60,6 +60,21 @@ export async function rcloneDeleteFile(
await runRcloneCommand(['deletefile', target], env, opts);
}
+/**
+ * Rclone reports failures as timestamped log lines. This returns just the message
+ * of the first ERROR line, so the UI shows a user-friendly error message.
+ */
+export function rcloneErrorMessage(error: any): string {
+ const raw = (error?.message || '').trim();
+ if (!raw) return '';
+ const lines: string[] = raw
+ .split('\n')
+ .map((line: string) => line.trim())
+ .filter(Boolean);
+ const line = lines.find((l: string) => /\s(ERROR|CRITICAL)\s*:/.test(l)) || lines[0];
+ return line.replace(/^.*?\s(?:ERROR|CRITICAL|NOTICE|INFO)\s*:\s*/, '').trim() || raw;
+}
+
/**
* List a remote path as JSON.
*/
diff --git a/frontend/src/components/Plan/PlanStats/PlanStats.tsx b/frontend/src/components/Plan/PlanStats/PlanStats.tsx
index e7ac429..2cba3b1 100644
--- a/frontend/src/components/Plan/PlanStats/PlanStats.tsx
+++ b/frontend/src/components/Plan/PlanStats/PlanStats.tsx
@@ -1,3 +1,4 @@
+import { ReactNode } from 'react';
import Icon from '../../common/Icon/Icon';
import StorageIcon from '../../common/Icon/StorageIcon';
import { Plan } from '../../../@types/plans';
@@ -13,9 +14,10 @@ interface PlanStatsProps {
plan: Plan;
isSync: boolean;
lastBackupItem: any;
+ storageAction?: ReactNode;
}
-const PlanStats = ({ plan, isSync, lastBackupItem }: PlanStatsProps) => {
+const PlanStats = ({ plan, isSync, lastBackupItem, storageAction }: PlanStatsProps) => {
const { sourceConfig, storage, storagePath, isActive, settings } = plan;
const { interval } = settings;
const isStorageSource = plan.sourceType === 'storage';
@@ -67,6 +69,7 @@ const PlanStats = ({ plan, isSync, lastBackupItem }: PlanStatsProps) => {
replicationSettings={plan.settings.replication}
storage={storage}
storagePath={storagePath}
+ action={storageAction}
/>
</div>
</div>
diff --git a/frontend/src/components/Plan/PlanStorageInfo/PlanStorageInfo.module.scss b/frontend/src/components/Plan/PlanStorageInfo/PlanStorageInfo.module.scss
index db35961..5d2823b 100644
--- a/frontend/src/components/Plan/PlanStorageInfo/PlanStorageInfo.module.scss
+++ b/frontend/src/components/Plan/PlanStorageInfo/PlanStorageInfo.module.scss
@@ -1,4 +1,26 @@
.planStorages {
+ position: relative;
+ .storageAction {
+ position: absolute;
+ margin-top: -4px;
+ z-index: 111;
+ opacity: 0;
+ transition: opacity 0.15s linear;
+ button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 5px 6px;
+ border-radius: 50%;
+ cursor: pointer;
+ color: var(--primary-color);
+ background: var(--content-background-color);
+ border: 1px solid var(--line-color);
+ }
+ }
+ &:hover .storageAction {
+ opacity: 1;
+ }
.storageWithReplications {
display: flex;
flex-direction: column;
@@ -40,4 +62,16 @@
display: inline-block;
}
}
+ &.withReplications {
+ &:hover {
+ .storageWithReplications {
+ filter: blur(2px);
+ }
+ }
+
+ .storageAction {
+ margin-top: 0px;
+ left: 27px;
+ }
+ }
}
diff --git a/frontend/src/components/Plan/PlanStorageInfo/PlanStorageInfo.tsx b/frontend/src/components/Plan/PlanStorageInfo/PlanStorageInfo.tsx
index 5cc1b56..a70778f 100644
--- a/frontend/src/components/Plan/PlanStorageInfo/PlanStorageInfo.tsx
+++ b/frontend/src/components/Plan/PlanStorageInfo/PlanStorageInfo.tsx
@@ -1,3 +1,4 @@
+import { ReactNode } from 'react';
import { PlanReplicationSettings } from '../../../@types';
import classes from './PlanStorageInfo.module.scss';
@@ -7,15 +8,16 @@ interface PlanStorageInfoProps {
replicationSettings?: PlanReplicationSettings;
disableTooltip?: boolean;
inline?: boolean;
+ action?: ReactNode;
}
-const PlanStorageInfo = ({ replicationSettings, storage, storagePath, disableTooltip = true, inline = true }: PlanStorageInfoProps) => {
- console.log('replicationSettings :', replicationSettings);
+const PlanStorageInfo = ({ replicationSettings, storage, storagePath, disableTooltip = true, inline = true, action }: PlanStorageInfoProps) => {
+ const storageWithReplications = replicationSettings && replicationSettings.enabled && replicationSettings.storages.length > 0;
return (
<>
- {replicationSettings && replicationSettings.enabled && replicationSettings.storages.length > 0 ? (
+ {storageWithReplications ? (
<div
- className={`${classes.planStorages} ${inline ? classes.inline : ''}`}
+ className={`${classes.planStorages} ${inline ? classes.inline : ''} ${storageWithReplications ? classes.withReplications : ''}`}
data-tooltip-hidden={disableTooltip}
data-tooltip-id="htmlToolTip"
data-tooltip-place="top"
@@ -55,6 +57,7 @@ const PlanStorageInfo = ({ replicationSettings, storage, storagePath, disableToo
</div>
<div className={classes.storageName}>{replicationSettings.storages.length + 1} Storages</div>
</div>
+ {action && <div className={classes.storageAction}>{action}</div>}
</div>
) : (
<div
@@ -74,6 +77,7 @@ const PlanStorageInfo = ({ replicationSettings, storage, storagePath, disableToo
>
<img src={`/providers/${storage?.type}.png`} />
<div className={classes.storageName}>{storage?.name}</div>
+ {action && <div className={classes.storageAction}>{action}</div>}
</div>
)}
</>
diff --git a/frontend/src/components/Storage/StorageFileBrowser/StorageFileBrowser.module.scss b/frontend/src/components/Storage/StorageFileBrowser/StorageFileBrowser.module.scss
new file mode 100644
index 0000000..3852303
--- /dev/null
+++ b/frontend/src/components/Storage/StorageFileBrowser/StorageFileBrowser.module.scss
@@ -0,0 +1,279 @@
+.browserModal {
+ position: fixed;
+ width: 100%;
+ height: 100vh;
+ top: 0;
+ left: 0;
+ z-index: 99999999;
+ background: var(--modal-shadow-color-light);
+ .browserModalInner {
+ position: absolute;
+ width: 70%;
+ max-width: 1000px;
+ background: var(--content-background-color);
+ color: var(--content-text-color);
+ border-radius: 8px;
+ border: 1px solid var(--content-shadow-color);
+ margin: 0 auto;
+ left: 0;
+ right: 0;
+ top: 10%;
+ box-sizing: border-box;
+ box-shadow: 0 0 20px var(--modal-shadow-color);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ max-height: 80vh;
+ }
+}
+
+.browserHeader {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 15px;
+ border-bottom: 1px solid var(--line-color);
+ h4 {
+ margin: 0;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ img {
+ width: 20px;
+ height: 20px;
+ }
+ }
+ button {
+ padding: 10px;
+ cursor: pointer;
+ background: transparent;
+ color: var(--content-text-color);
+ opacity: 0.5;
+ transition: all 0.2s linear;
+ &:hover {
+ opacity: 1;
+ transform: rotate(90deg);
+ }
+ }
+}
+
+.navigationBar {
+ display: flex;
+ align-items: center;
+ padding: 12px;
+ border-bottom: 1px solid var(--line-color);
+ gap: 12px;
+
+ button {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 5px 10px;
+ border-radius: 4px;
+ border: 1px solid var(--line-color);
+ background: transparent;
+ cursor: pointer;
+ color: var(--icon-color);
+
+ &:hover {
+ background: var(--light-grey);
+ color: var(--content-color);
+ }
+
+ &:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ }
+}
+
+.currentPath {
+ flex: 1;
+ padding: 6px 12px;
+ background: var(--light-grey);
+ border-radius: 4px;
+ font-family: inherit;
+ height: 21px;
+ color: inherit;
+ cursor: text;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ &:hover {
+ background: var(--line-color);
+ color: var(--content-text-color);
+ }
+ input {
+ background-color: transparent;
+ border: none;
+ width: 100%;
+ outline: none;
+ color: var(--content-text-color);
+ }
+ button {
+ background: none;
+ border: none;
+ padding: 2px 0px;
+ cursor: pointer;
+ font-family: inherit;
+ display: inline-block;
+ border-radius: 0;
+ color: inherit;
+ &:hover {
+ color: var(--primary-color);
+ text-decoration: underline;
+ }
+ }
+}
+
+.fileListContainer {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ overflow: hidden;
+}
+
+.fileHeader {
+ display: grid;
+ grid-template-columns: 3fr 1fr 1fr;
+ padding: 8px 12px;
+ background: var(--light-grey);
+ border-bottom: 1px solid var(--line-color);
+ font-weight: 500;
+ text-align: center;
+ div {
+ cursor: pointer;
+ user-select: none;
+ }
+ div:first-child {
+ text-align: left;
+ }
+}
+
+.fileList {
+ flex: 1;
+ overflow-y: auto;
+ min-height: 300px;
+}
+
+.fileRow {
+ display: grid;
+ grid-template-columns: 3fr 1fr 1fr;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--line-color);
+ box-sizing: border-box;
+ cursor: pointer;
+ text-align: center;
+ color: var(--content-text-color-light);
+
+ &:hover {
+ background: var(--light-grey);
+ }
+ &:last-child {
+ border-bottom: none;
+ }
+}
+
+.fileName {
+ display: flex;
+ align-items: center;
+ text-align: left;
+ word-break: break-all;
+ gap: 6px;
+ min-width: 0;
+ color: var(--content-text-color);
+ .fileNameText {
+ display: inline-block;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+}
+
+.fileActions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ margin-left: auto;
+ padding-left: 10px;
+ opacity: 0;
+ transition: opacity 0.15s linear;
+ button {
+ cursor: pointer;
+ background: transparent;
+ color: var(--icon-color);
+ opacity: 0.7;
+ &:hover {
+ opacity: 1;
+ color: var(--primary-color);
+ }
+ }
+}
+
+.fileRow:hover .fileActions {
+ opacity: 1;
+}
+
+.fileSize {
+ max-width: 90px;
+}
+
+.fileDate {
+ max-width: 160px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.message {
+ text-align: center;
+ width: 100%;
+ padding: 8%;
+ box-sizing: border-box;
+ color: var(--content-text-color-light);
+}
+
+@media only screen and (max-width: 768px) {
+ .browserModal {
+ .browserModalInner {
+ width: 100%;
+ top: 0;
+ max-height: 100vh;
+ height: 100vh;
+ border-radius: 0;
+ }
+ }
+ .fileHeader {
+ display: none;
+ }
+ .fileList {
+ height: 100% !important;
+ }
+ .fileRow {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ .fileName {
+ width: 100%;
+ margin-bottom: 5px;
+ }
+ .mobileFileInfo {
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-start;
+ width: 100%;
+ padding-left: 24px;
+ box-sizing: border-box;
+ & > div {
+ padding: 0 10px;
+ }
+ }
+ }
+ .fileActions {
+ opacity: 1;
+ }
+}
diff --git a/frontend/src/components/Storage/StorageFileBrowser/StorageFileBrowser.tsx b/frontend/src/components/Storage/StorageFileBrowser/StorageFileBrowser.tsx
new file mode 100644
index 0000000..ad150c2
--- /dev/null
+++ b/frontend/src/components/Storage/StorageFileBrowser/StorageFileBrowser.tsx
@@ -0,0 +1,213 @@
+import { ReactNode, useMemo, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { FixedSizeList as List } from 'react-window';
+import Icon from '../../common/Icon/Icon';
+import FileIcon from '../../common/FileIcon/FileIcon';
+import { useBrowseStorage } from '../../../services/storage';
+import { formatBytes, formatDateTime, isMobile, sortFileItems } from '../../../utils/helpers';
+import { FileItem } from '../../../@types/system';
+import classes from './StorageFileBrowser.module.scss';
+
+export interface StorageFileBrowserProps {
+ title: string;
+ storageId: string;
+ storageType?: string;
+ /** Where the browser opens. Ignored when `rootPath` is set. */
+ defaultPath?: string;
+ /** Lowest path the user can reach. Navigation never goes above it. */
+ rootPath?: string;
+ /** Per-file controls, shown on row hover. Core passes none, so core is read-only. */
+ renderFileActions?: (item: FileItem) => ReactNode;
+ close: () => void;
+}
+
+type SortField = 'name' | 'size' | 'modifiedAt' | null;
+type SortOrder = 'asc' | 'desc';
+const isMobileDevice = isMobile();
+const ITEM_HEIGHT = isMobileDevice ? 68 : 38;
+
+const StorageFileBrowser = ({ title, storageId, storageType, defaultPath, rootPath, renderFileActions, close }: StorageFileBrowserProps) => {
+ const homePath = rootPath ?? '';
+ const [currentPath, setCurrentPath] = useState(() => rootPath ?? defaultPath ?? '');
+ const [showPathInput, setShowPathInput] = useState(false);
+ const [customPath, setCustomPath] = useState('');
+ const [sortField, setSortField] = useState<SortField>(null);
+ const [sortOrder, setSortOrder] = useState<SortOrder>('asc');
+
+ const { data, isLoading, error, refetch } = useBrowseStorage({ storageId, path: currentPath });
+
+ const isInsideRoot = (path: string) => !rootPath || path === rootPath || path.startsWith(rootPath + '/');
+
+ const navigateToPath = (path: string) => {
+ setCurrentPath(isInsideRoot(path) ? path : homePath);
+ };
+
+ const navigateUp = () => {
+ if (currentPath === homePath) return;
+ if (!currentPath.includes('/')) {
+ setCurrentPath(homePath);
+ return;
+ }
+ const parentPath = currentPath.split('/').slice(0, -1).join('/');
+ setCurrentPath(isInsideRoot(parentPath) ? parentPath : homePath);
+ };
+
+ const handleSort = (field: SortField) => {
+ if (sortField === field) {
+ setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
+ } else {
+ setSortField(field);
+ setSortOrder('asc');
+ }
+ };
+
+ const sortedItems: FileItem[] = useMemo(() => {
+ const items: FileItem[] = data?.result?.items || [];
+ if (!sortField) return items;
+
+ const directories = items.filter((item) => item.isDirectory);
+ const files = items.filter((item) => !item.isDirectory);
+ return [...sortFileItems([...directories], sortField, sortOrder), ...sortFileItems([...files], sortField, sortOrder)];
+ }, [data, sortField, sortOrder]);
+
+ const getSortIcon = (field: SortField) => {
+ if (sortField !== field) return null;
+ return sortOrder === 'asc' ? ' ↑' : ' ↓';
+ };
+
+ const renderPathBreadcrumbs = () => {
+ if (!currentPath) return 'Storage Root';
+
+ const allSegments = currentPath.split('/').filter(Boolean);
+ // Nothing above the jail root is reachable, so those segments are not shown.
+ const rootDepth = rootPath ? rootPath.split('/').filter(Boolean).length : 0;
+ const segments = allSegments.slice(rootDepth === 0 ? 0 : rootDepth - 1);
+ const offset = allSegments.length - segments.length;
+
+ return segments.map((segment, index) => {
+ const path = allSegments.slice(0, offset + index + 1).join('/');
+ return (
+ <span key={path}>
+ <button onClick={() => navigateToPath(path)}>{segment}</button>
+ {index < segments.length - 1 && ' > '}
+ </span>
+ );
+ });
+ };
+
+ const FileRow = ({ index, style }: { index: number; style: React.CSSProperties }) => {
+ const item = sortedItems[index];
+
+ return (
+ <div style={style} className={classes.fileRow} onClick={() => item.isDirectory && navigateToPath(item.path)}>
+ <div className={classes.fileName}>
+ {item.isDirectory ? <Icon type="fm-directory" size={18} /> : <FileIcon filename={item.name} />}
+ <span className={classes.fileNameText} title={item.name}>
+ {item.name}
+ </span>
+ {renderFileActions && <div className={classes.fileActions}>{renderFileActions(item)}</div>}
+ </div>
+ {isMobileDevice ? (
+ <div className={classes.mobileFileInfo}>
+ {!item.isDirectory && <div className={classes.fileSize}>{item.size ? formatBytes(item.size) : '-'}</div>}
+ <div className={classes.fileDate}>{item.modifiedAt ? formatDateTime(item.modifiedAt) : '-'}</div>
+ </div>
+ ) : (
+ <>
+ <div className={classes.fileSize}>{item.size ? formatBytes(item.size) : '-'}</div>
+ <div className={classes.fileDate}>{item.modifiedAt ? formatDateTime(item.modifiedAt) : '-'}</div>
+ </>
+ )}
+ </div>
+ );
+ };
+
+ const closeOnBGClick = (e: React.SyntheticEvent) => {
+ e.stopPropagation();
+ e.nativeEvent.stopImmediatePropagation();
+ if (e.target === e.currentTarget) {
+ close();
+ }
+ };
+
+ return createPortal(
+ <div className={classes.browserModal} onClick={closeOnBGClick}>
+ <div className={classes.browserModalInner}>
+ <div className={classes.browserHeader}>
+ <h4 title={title}>
+ {storageType && <img src={`/providers/${storageType}.png`} />}
+ {title}
+ </h4>
+ <button onClick={() => close()}>
+ <Icon type="close" size={20} />
+ </button>
+ </div>
+
+ <div className={classes.navigationBar}>
+ <button onClick={navigateUp} disabled={currentPath === homePath} title="Move Up">
+ <Icon type="arrow-up" size={18} />
+ </button>
+ <button onClick={() => setCurrentPath(homePath)} disabled={currentPath === homePath} title="Home">
+ <Icon type="home" size={18} />
+ </button>
+ <button onClick={() => refetch()} title="Refresh">
+ <Icon type="reload" size={18} />
+ </button>
+ <div
+ className={classes.currentPath}
+ onClick={() => {
+ setCustomPath(currentPath);
+ setShowPathInput(true);
+ }}
+ >
+ {showPathInput ? (
+ <input
+ value={customPath}
+ onChange={(e) => setCustomPath(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ navigateToPath(customPath);
+ setShowPathInput(false);
+ }
+ }}
+ onBlur={() => setShowPathInput(false)}
+ autoFocus
+ />
+ ) : (
+ renderPathBreadcrumbs()
+ )}
+ </div>
+ </div>
+
+ <div className={classes.fileListContainer}>
+ <div className={classes.fileHeader}>
+ <div onClick={() => handleSort('name')}>Name {getSortIcon('name')}</div>
+ <div onClick={() => handleSort('size')}>Size {getSortIcon('size')}</div>
+ <div onClick={() => handleSort('modifiedAt')}>Modified {getSortIcon('modifiedAt')}</div>
+ </div>
+
+ {isLoading ? (
+ <div className={classes.message}>Loading...</div>
+ ) : error ? (
+ <div className={classes.message}>{(error as Error)?.message || 'Failed to read this storage.'}</div>
+ ) : sortedItems.length === 0 ? (
+ <div className={classes.message}>No files or folders found</div>
+ ) : (
+ <List
+ height={window.innerHeight - 320}
+ itemCount={sortedItems.length}
+ itemSize={ITEM_HEIGHT}
+ width="100%"
+ className={`${classes.fileList} styled__scrollbar`}
+ >
+ {FileRow}
+ </List>
+ )}
+ </div>
+ </div>
+ </div>,
+ document.body,
+ );
+};
+
+export default StorageFileBrowser;
diff --git a/frontend/src/components/Storage/StorageItem/StorageItem.module.scss b/frontend/src/components/Storage/StorageItem/StorageItem.module.scss
index 0deefef..61b2ed3 100644
--- a/frontend/src/components/Storage/StorageItem/StorageItem.module.scss
+++ b/frontend/src/components/Storage/StorageItem/StorageItem.module.scss
@@ -106,6 +106,17 @@
}
}
+.browseBtn {
+ color: var(--content-text-color-light);
+ padding: 3px 6px;
+ border-radius: 4px;
+ cursor: pointer;
+ &:hover {
+ background-color: var(--primary-color-light);
+ color: var(--primary-color);
+ }
+}
+
.settings {
position: absolute;
z-index: 99;
@@ -195,7 +206,7 @@
padding: 6px 10px;
box-sizing: border-box;
background: var(--primary-color-lighter);
- .moreBtn {
+ .browseBtn {
margin-left: auto;
}
}
diff --git a/frontend/src/components/Storage/StorageItem/StorageItem.tsx b/frontend/src/components/Storage/StorageItem/StorageItem.tsx
index 1e84ffb..ef3bcd4 100644
--- a/frontend/src/components/Storage/StorageItem/StorageItem.tsx
+++ b/frontend/src/components/Storage/StorageItem/StorageItem.tsx
@@ -8,6 +8,8 @@ import EditStorage from '../EditStorage/EditStorage';
import Modal from '../../common/Modal/Modal';
import { useDeleteStorage, useVerifyStorage } from '../../../services/storage';
import ActionModal from '../../common/ActionModal/ActionModal';
+import StorageFileBrowser from '../StorageFileBrowser/StorageFileBrowser';
+import { useComponentOverride } from '../../../context/ComponentOverrideContext';
interface StorageItemProps {
storage: Storage;
@@ -19,11 +21,13 @@ const StorageItem = ({ storage, layout }: StorageItemProps) => {
const [showEditModal, setShowEditModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showVerifyModal, setShowVerifyModal] = useState(false);
- const { id, name, type, plans = [], usedSize = 200, storageTypeName, settings = {} } = storage;
+ const [showBrowser, setShowBrowser] = useState(false);
+ const { id, name, type, plans = [], usedSize = 200, storageTypeName, settings = {}, defaultPath } = storage;
const deleteStorageMutation = useDeleteStorage();
const verifyStorageMutation = useVerifyStorage();
const isLocalStorage = id === 'local';
const description = settings.description as string;
+ const Browser = useComponentOverride('StorageFileBrowser', StorageFileBrowser);
const removeStorage = () => {
deleteStorageMutation.mutate(storage.id, {
@@ -68,6 +72,15 @@ const StorageItem = ({ storage, layout }: StorageItemProps) => {
<div className={classes.info}>
<Icon type="disk" size={14} /> <i>{formatBytes(usedSize)}</i>
</div>
+ <button
+ className={classes.browseBtn}
+ onClick={() => setShowBrowser(true)}
+ data-tooltip-id="appTooltip"
+ data-tooltip-content="Browse Files"
+ data-tooltip-place="top"
+ >
+ <Icon type="folder-open" size={14} />
+ </button>
<button
className={`${classes.moreBtn} ${showSettings ? classes.moreBtnActive : ''}`}
onClick={() => setShowSettings(!showSettings)}
@@ -109,6 +122,15 @@ const StorageItem = ({ storage, layout }: StorageItemProps) => {
)}
</div>
)}
+ {showBrowser && (
+ <Browser
+ title={`${name} - File Browser`}
+ storageId={id}
+ storageType={type}
+ defaultPath={defaultPath && defaultPath !== '/' ? defaultPath : undefined}
+ close={() => setShowBrowser(false)}
+ />
+ )}
{showEditModal && <EditStorage close={() => setShowEditModal(false)} storage={storage} />}
{showVerifyModal && (
<Modal
diff --git a/frontend/src/components/common/Icon/Icon.tsx b/frontend/src/components/common/Icon/Icon.tsx
index 036c4c7..0003666 100644
--- a/frontend/src/components/common/Icon/Icon.tsx
+++ b/frontend/src/components/common/Icon/Icon.tsx
@@ -752,7 +752,15 @@ const Icon = ({ type, color = 'currentColor', size = 16, title = '', classes = '
></path>
</IconWrapper>
)}
-
+ {type === 'folder-open' && (
+ <IconWrapper size={size} viewBox="0 0 576 512">
+ <path d="M0 0h576v512H0z" fill="none" />
+ <path
+ fill={color}
+ d="M527.9 224H480v-48c0-26.5-21.5-48-48-48H272l-64-64H48C21.5 64 0 85.5 0 112v288c0 26.5 21.5 48 48 48h400c16.5 0 31.9-8.5 40.7-22.6l79.9-128c20-31.9-3-73.4-40.7-73.4M48 118c0-3.3 2.7-6 6-6h134.1l64 64H426c3.3 0 6 2.7 6 6v42H152c-16.8 0-32.4 8.8-41.1 23.2L48 351.4zm400 282H72l77.2-128H528z"
+ />
+ </IconWrapper>
+ )}
{type === 'folders' && (
<IconWrapper size={size} viewBox="0 0 24 24">
<g fill="none" stroke={color} strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}>
diff --git a/frontend/src/components/index.ts b/frontend/src/components/index.ts
index bbb3a48..e3a4596 100644
--- a/frontend/src/components/index.ts
+++ b/frontend/src/components/index.ts
@@ -130,6 +130,8 @@ export { default as SkeletonItems } from './Skeleton/SkeletonItems';
export { default as AddStorage } from './Storage/AddStorage/AddStorage';
export { default as EditStorage } from './Storage/EditStorage/EditStorage';
export { default as StorageAuthSettings } from './Storage/StorageAuthSettings/StorageAuthSettings';
+export { default as StorageFileBrowser } from './Storage/StorageFileBrowser/StorageFileBrowser';
+export type { StorageFileBrowserProps } from './Storage/StorageFileBrowser/StorageFileBrowser';
export { default as StorageItem } from './Storage/StorageItem/StorageItem';
export { default as StorageSettings } from './Storage/StorageSettings/StorageSettings';
diff --git a/frontend/src/services/restores.ts b/frontend/src/services/restores.ts
index a406c33..9b188c2 100644
--- a/frontend/src/services/restores.ts
+++ b/frontend/src/services/restores.ts
@@ -91,6 +91,7 @@ export async function restoreBackup({
deleteOption,
storageId,
replicationId,
+ fromStorage,
}: {
backupId: string;
planId: string;
@@ -101,13 +102,14 @@ export async function restoreBackup({
deleteOption: boolean;
storageId?: string;
replicationId?: string;
+ fromStorage?: boolean;
}) {
const header = new Headers({ 'Content-Type': 'application/json', Accept: 'application/json' });
const res = await fetch(`${API_URL}/restores/action/restore`, {
method: 'POST',
credentials: 'include',
headers: header,
- body: JSON.stringify({ backupId, planId, target, overwrite, includes, excludes, delete: deleteOption, storageId, replicationId }),
+ body: JSON.stringify({ backupId, planId, target, overwrite, includes, excludes, delete: deleteOption, storageId, replicationId, fromStorage }),
});
const data = await res.json();
if (!data.success) {
diff --git a/frontend/src/services/storage.ts b/frontend/src/services/storage.ts
index 730b48f..d1a71ff 100644
--- a/frontend/src/services/storage.ts
+++ b/frontend/src/services/storage.ts
@@ -234,6 +234,34 @@ export async function getStorageAuthorizeStatus(sessionId: string): Promise<{
return data.result;
}
+// Browse Storage
+export async function browseStorage(payload: { storageId: string; path?: string }) {
+ const url = new URL(`${API_URL}/storages/${payload.storageId}/browse`);
+ if (payload.path) {
+ url.searchParams.append('path', encodeURIComponent(payload.path));
+ }
+
+ const res = await fetch(url.toString(), {
+ method: 'GET',
+ credentials: 'include',
+ });
+ const data = await res.json();
+ if (!data.success) {
+ throw new Error(data.error);
+ }
+ return data;
+}
+
+export function useBrowseStorage(payload: { storageId: string; path?: string }, enabled: boolean = true) {
+ return useQuery({
+ queryKey: ['storageBrowse', payload.storageId, payload.path],
+ queryFn: () => browseStorage(payload),
+ refetchOnMount: true,
+ retry: false,
+ enabled,
+ });
+}
+
export async function cancelStorageAuthorize(sessionId: string): Promise<void> {
const header = new Headers({ 'Content-Type': 'application/json', Accept: 'application/json' });
const res = await fetch(`${API_URL}/storages/authorize/cancel`, {