aboutsummaryrefslogtreecommitdiffstats
path: root/src/web
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-07-13 09:56:35 -0500
committerGitHub <noreply@github.com>2026-07-13 09:56:35 -0500
commit16e5d86ec9a91120f3ef40b85cb22036566b788a (patch)
tree03ad0c38a485ee6db78480e6eef365367a29707f /src/web
parent30b14cd21f9f9c32a4505df6ba8d7537a77c518d (diff)
parentcf8e0836c99e387753d1d95f8703bbeba2ca1477 (diff)
downloadslskd-16e5d86ec9a91120f3ef40b85cb22036566b788a.tar.gz
Merge pull request #1788 from slskd/folders
Allow selection (and downloading) of subdirectories recursively on the Browse screen
Diffstat (limited to 'src/web')
-rw-r--r--src/web/.eslintrc.js1
-rw-r--r--src/web/src/components/Browse/Browse.jsx187
-rw-r--r--src/web/src/components/Browse/Directory.jsx136
-rw-r--r--src/web/src/components/Browse/FileBrowser.jsx441
-rw-r--r--src/web/src/components/Browse/Selection.jsx222
-rw-r--r--src/web/src/lib/transfers.js61
6 files changed, 854 insertions, 194 deletions
diff --git a/src/web/.eslintrc.js b/src/web/.eslintrc.js
index 0b0f9fb6..a39caf8e 100644
--- a/src/web/.eslintrc.js
+++ b/src/web/.eslintrc.js
@@ -8,6 +8,7 @@ const overrides = {
'react/prop-types': 'off', // noisy
'canonical/sort-keys': 'off', // noisy
'unicorn/no-array-reduce': 'off', // noisy
+ 'unicorn/prevent-abbreviations': 'off',
};
/** @type {import('eslint').Linter.Config} */
diff --git a/src/web/src/components/Browse/Browse.jsx b/src/web/src/components/Browse/Browse.jsx
index 4f36dfe7..fd4731d2 100644
--- a/src/web/src/components/Browse/Browse.jsx
+++ b/src/web/src/components/Browse/Browse.jsx
@@ -2,8 +2,8 @@
import './Browse.css';
import * as users from '../../lib/users';
import PlaceholderSegment from '../Shared/PlaceholderSegment';
-import Directory from './Directory';
import DirectoryTree from './DirectoryTree';
+import Selection from './Selection';
import * as lzString from 'lz-string';
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
@@ -20,8 +20,7 @@ const initialState = {
lockedFiles: 0,
},
interval: undefined,
- selectedDirectory: {},
- selectedFiles: [],
+ selected: null,
separator: '\\',
tree: [],
username: '',
@@ -107,6 +106,7 @@ class Browse extends Component {
this.setState(
{ browseError: undefined, browseState: 'complete' },
() => {
+ this.saveTree();
this.saveState();
},
),
@@ -120,6 +120,7 @@ class Browse extends Component {
clear = () => {
this.setState(initialState, () => {
+ this.saveTree();
this.saveState();
this.inputtext.focus();
});
@@ -127,41 +128,67 @@ class Browse extends Component {
keyUp = (event) => (event.key === 'Escape' ? this.clear() : '');
+ saveTree = () => {
+ try {
+ localStorage.setItem(
+ 'slskd-browse-tree',
+ lzString.compress(JSON.stringify(this.state.tree)),
+ );
+ } catch (error) {
+ console.error(error);
+ }
+ };
+
saveState = () => {
this.inputtext.inputRef.current.value = this.state.username;
this.inputtext.inputRef.current.disabled =
this.state.browseState !== 'idle';
- const storeToLocalStorage = () => {
- try {
- localStorage.setItem(
- 'soulseek-example-browse-state',
- lzString.compress(JSON.stringify(this.state)),
- );
- } catch (error) {
- console.error(error);
- }
- };
-
- // Shifting the compression and safe out of the current render loop to speed up responsiveness
- // requestIdleCallback is not supported in Safari hence we push to next tick using Promise.resolve
- if (window.requestIdleCallback) {
- window.requestIdleCallback(storeToLocalStorage);
- } else {
- Promise.resolve().then(storeToLocalStorage);
+ try {
+ const { browseError, browseState, info, selected, separator, username } =
+ this.state;
+ localStorage.setItem(
+ 'slskd-browse-state',
+ lzString.compress(
+ JSON.stringify({
+ browseError,
+ browseState,
+ info,
+ selected,
+ separator,
+ username,
+ }),
+ ),
+ );
+ } catch (error) {
+ console.error(error);
}
};
loadState = () => {
- this.setState(
- (!this.props.location.state?.user &&
- JSON.parse(
- lzString.decompress(
- localStorage.getItem('soulseek-example-browse-state') || '',
- ),
- )) ||
- initialState,
- );
+ if (this.props.location.state?.user) {
+ return;
+ }
+
+ const treeStr = localStorage.getItem('slskd-browse-tree');
+ const metaStr = localStorage.getItem('slskd-browse-state');
+
+ let savedState = null;
+ if (treeStr || metaStr) {
+ const tree = treeStr
+ ? JSON.parse(lzString.decompress(treeStr) || 'null')
+ : null;
+ const meta = metaStr
+ ? JSON.parse(lzString.decompress(metaStr) || 'null')
+ : null;
+ savedState = { ...meta, tree: tree || [] };
+ }
+
+ if (savedState?.tree) {
+ savedState.tree = savedState.tree.map(this.annotateWithCounts);
+ }
+
+ this.setState(savedState || initialState);
};
fetchStatus = () => {
@@ -175,6 +202,20 @@ class Browse extends Component {
}
};
+ annotateWithCounts = (node) => {
+ const children = (node.children || []).map(this.annotateWithCounts);
+ return {
+ ...node,
+ children,
+ totalDirectoryCount:
+ children.length +
+ children.reduce((sum, c) => sum + c.totalDirectoryCount, 0),
+ totalFileCount:
+ (node.files || []).length +
+ children.reduce((sum, c) => sum + c.totalFileCount, 0),
+ };
+ };
+
getDirectoryTree = ({ directories, separator }) => {
if (directories.length === 0 || directories[0].name === undefined) {
return [];
@@ -199,7 +240,9 @@ class Browse extends Component {
return depthMap
.get(depth)
.map((directory) =>
- this.getChildDirectories(depthMap, directory, separator, depth + 1),
+ this.annotateWithCounts(
+ this.getChildDirectories(depthMap, directory, separator, depth + 1),
+ ),
);
};
@@ -220,39 +263,84 @@ class Browse extends Component {
};
};
+ findDirectoryByPath = (path, nodes) => {
+ for (const node of nodes) {
+ if (node.name === path) {
+ return node;
+ }
+
+ const found = this.findDirectoryByPath(path, node.children || []);
+
+ if (found) {
+ return found;
+ }
+ }
+
+ return null;
+ };
+
selectDirectory = (directory) => {
- this.setState({ selectedDirectory: { ...directory, children: [] } }, () =>
- this.saveState(),
+ this.setState(
+ {
+ selected: {
+ directoryName: directory.name,
+ files: [],
+ subdirectory: directory.children?.[0]?.name ?? null,
+ },
+ },
+ () => this.saveState(),
);
};
- handleDeselectDirectory = () => {
- this.setState({ selectedDirectory: initialState.selectedDirectory }, () =>
- this.saveState(),
+ handleStateChange = ({ files, subdirectory }) => {
+ this.setState(
+ (prevState) => ({
+ selected: { ...prevState.selected, files, subdirectory },
+ }),
+ () => this.saveState(),
);
};
+ handleDirectoryNavigate = (path) => {
+ const directory = this.findDirectoryByPath(path, this.state.tree);
+
+ if (directory) {
+ this.selectDirectory(directory);
+ }
+ };
+
+ renderDirectoryAction = (dir) => (
+ <Icon
+ link
+ name="share"
+ onClick={() => this.handleDirectoryNavigate(dir.name)}
+ title="Navigate to this directory"
+ />
+ );
+
+ handleDeselectDirectory = () => {
+ this.setState({ selected: null }, () => this.saveState());
+ };
+
render() {
const {
browseError,
browseState,
browseStatus,
info,
- selectedDirectory,
+ selected,
separator,
tree,
username,
} = this.state;
- const { locked, name } = selectedDirectory;
+ const selectedDirectory = selected
+ ? this.findDirectoryByPath(selected.directoryName, tree)
+ : null;
+ const locked = selectedDirectory?.locked;
const pending = browseState === 'pending';
const emptyTree = !(tree && tree.length > 0);
- const files = (selectedDirectory.files || []).map((f) => ({
- ...f,
- filename: `${name}${separator}${f.filename}`,
- }));
-
return (
<div className="search-container">
<Segment
@@ -331,20 +419,25 @@ class Browse extends Component {
<Segment className="browse-folderlist">
<DirectoryTree
onSelect={(_, value) => this.selectDirectory(value)}
- selectedDirectoryName={name}
+ selectedDirectoryName={selected?.directoryName}
tree={tree}
/>
</Segment>
</Card.Content>
</Card>
)}
- {name && (
- <Directory
- files={files}
+ {selectedDirectory && (
+ <Selection
+ defaultSelectedFiles={selected.files}
+ defaultSubdirectory={selected.subdirectory}
+ directorySuffix={this.renderDirectoryAction}
locked={locked}
marginTop={-20}
- name={name}
+ name={selected.directoryName}
+ node={selectedDirectory}
onClose={this.handleDeselectDirectory}
+ onStateChange={this.handleStateChange}
+ separator={separator}
username={username}
/>
)}
diff --git a/src/web/src/components/Browse/Directory.jsx b/src/web/src/components/Browse/Directory.jsx
deleted file mode 100644
index ed88f131..00000000
--- a/src/web/src/components/Browse/Directory.jsx
+++ /dev/null
@@ -1,136 +0,0 @@
-import * as transfers from '../../lib/transfers';
-import { formatBytes } from '../../lib/util';
-import FileList from '../Shared/FileList';
-import React, { Component } from 'react';
-import { Button, Card, Icon, Label } from 'semantic-ui-react';
-
-const initialState = {
- downloadError: '',
- downloadRequest: undefined,
-};
-
-class Directory extends Component {
- constructor(props) {
- super(props);
-
- this.state = {
- ...initialState,
- files: this.props.files.map((f) => ({ selected: false, ...f })),
- };
- }
-
- componentDidUpdate(previousProps) {
- if (this.props.name !== previousProps.name) {
- this.setState({
- files: this.props.files.map((f) => ({ selected: false, ...f })),
- });
- }
- }
-
- handleFileSelectionChange = (file, state) => {
- file.selected = state;
- this.setState((previousState) => ({
- downloadError: '',
- downloadRequest: undefined,
- tree: previousState.tree,
- }));
- };
-
- download = (username, files) => {
- this.setState({ downloadRequest: 'inProgress' }, async () => {
- try {
- const requests = (files || []).map(({ filename, size }) => ({
- filename,
- size,
- }));
- await transfers.download({ files: requests, username });
-
- this.setState({ downloadRequest: 'complete' });
- } catch (error) {
- this.setState({
- downloadError: error.response,
- downloadRequest: 'error',
- });
- }
- });
- };
-
- render() {
- const { locked, marginTop, name, onClose, username } = this.props;
- const { downloadError, downloadRequest, files } = this.state;
-
- const selectedFiles = files.filter((f) => f.selected);
-
- const selectedSize = formatBytes(
- selectedFiles.reduce((total, f) => total + f.size, 0),
- );
-
- return (
- <Card
- className="result-card"
- raised
- >
- <Card.Content>
- <div style={{ marginTop: marginTop || 0 }}>
- <FileList
- directoryName={name}
- disabled={downloadRequest === 'inProgress'}
- files={files}
- locked={locked}
- onClose={onClose}
- onSelectionChange={this.handleFileSelectionChange}
- />
- </div>
- </Card.Content>
- {selectedFiles.length > 0 && (
- <Card.Content extra>
- <span>
- <Button
- color="green"
- content="Download"
- disabled={downloadRequest === 'inProgress'}
- icon="download"
- label={{
- as: 'a',
- basic: false,
- content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${selectedSize}`,
- }}
- labelPosition="right"
- onClick={() => this.download(username, selectedFiles)}
- />
- {downloadRequest === 'inProgress' && (
- <Icon
- loading
- name="circle notch"
- size="large"
- />
- )}
- {downloadRequest === 'complete' && (
- <Icon
- color="green"
- name="checkmark"
- size="large"
- />
- )}
- {downloadRequest === 'error' && (
- <span>
- <Icon
- color="red"
- name="x"
- size="large"
- />
- <Label>
- {downloadError.data +
- ` (HTTP ${downloadError.status} ${downloadError.statusText})`}
- </Label>
- </span>
- )}
- </span>
- </Card.Content>
- )}
- </Card>
- );
- }
-}
-
-export default Directory;
diff --git a/src/web/src/components/Browse/FileBrowser.jsx b/src/web/src/components/Browse/FileBrowser.jsx
new file mode 100644
index 00000000..0f84a3cc
--- /dev/null
+++ b/src/web/src/components/Browse/FileBrowser.jsx
@@ -0,0 +1,441 @@
+import {
+ formatAttributes,
+ formatBytes,
+ formatSeconds,
+ getFileName,
+} from '../../lib/util';
+import React, { useMemo, useState } from 'react';
+import { Checkbox, Header, Icon, Table } from 'semantic-ui-react';
+
+const formatDirCaption = (fileCount, dirCount) => {
+ const parts = [];
+ if (fileCount > 0) {
+ parts.push(`${fileCount} file${fileCount === 1 ? '' : 's'}`);
+ }
+
+ if (dirCount > 0) {
+ parts.push(`${dirCount} director${dirCount === 1 ? 'y' : 'ies'}`);
+ }
+
+ return parts.length > 0 ? parts.join(', ') : '0 files';
+};
+
+const AUDIO_EXTENSIONS = new Set([
+ 'aac',
+ 'aif',
+ 'aiff',
+ 'alac',
+ 'ape',
+ 'flac',
+ 'm4a',
+ 'mp3',
+ 'ogg',
+ 'opus',
+ 'wav',
+ 'wma',
+]);
+const VIDEO_EXTENSIONS = new Set([
+ 'avi',
+ 'flv',
+ 'm4v',
+ 'mkv',
+ 'mov',
+ 'mp4',
+ 'webm',
+ 'wmv',
+]);
+
+const getFileIcon = (filename) => {
+ const ext = filename.split('.').pop()?.toLowerCase();
+
+ if (AUDIO_EXTENSIONS.has(ext)) return 'file audio outline';
+ if (VIDEO_EXTENSIONS.has(ext)) return 'file video outline';
+ return 'file outline';
+};
+
+const getAttributes = (files) => {
+ if (!files || files.length === 0) return '';
+ if (files.every((f) => f.isVariableBitRate)) return 'VBR';
+ if (files.some((f) => f.isVariableBitRate)) return 'Mixed';
+
+ const bitRates = new Set(files.map((f) => f.bitRate).filter(Boolean));
+
+ if (bitRates.size === 1) return `${[...bitRates][0]} Kbps`;
+ if (bitRates.size > 1) return 'Mixed';
+ return '';
+};
+
+const File = ({ disabled, file, indent, locked, onSelectionChange }) => (
+ <Table.Row>
+ <Table.Cell className="filelist-selector">
+ {onSelectionChange != null && (
+ <Checkbox
+ checked={file.selected || false}
+ disabled={disabled}
+ fitted
+ onChange={(_, data) => onSelectionChange(file, data.checked)}
+ />
+ )}
+ </Table.Cell>
+ <Table.Cell
+ className="filelist-filename"
+ style={indent ? { paddingLeft: '2em' } : undefined}
+ >
+ {locked ? (
+ <Icon name="lock" />
+ ) : (
+ <Icon name={getFileIcon(file.filename)} />
+ )}
+ {getFileName(file.filename)}
+ </Table.Cell>
+ <Table.Cell className="filelist-size">{formatBytes(file.size)}</Table.Cell>
+ <Table.Cell className="filelist-attributes">
+ {formatAttributes(file)}
+ </Table.Cell>
+ <Table.Cell className="filelist-length">
+ {formatSeconds(file.length)}
+ </Table.Cell>
+ </Table.Row>
+);
+
+// childFiles is pre-filtered by the caller; no filtering happens here
+const DirectoryRow = ({
+ childFiles,
+ dir,
+ directorySuffix,
+ disabled,
+ indent,
+ isExpanded,
+ onExpand,
+ onSelectionChange,
+ sep,
+}) => {
+ const totalSize = childFiles.reduce((sum, f) => sum + (f.size || 0), 0);
+ const totalLength = childFiles.reduce((sum, f) => sum + (f.length || 0), 0);
+ const allChildSelected =
+ childFiles.length > 0 && childFiles.every((f) => f.selected);
+ const dirName = dir.name.split(sep).pop();
+ const interactive = onExpand != null;
+ const folderIcon = indent
+ ? 'folder outline'
+ : isExpanded
+ ? 'folder open'
+ : 'folder';
+
+ return (
+ <Table.Row
+ onClick={interactive ? () => onExpand(dir.name) : undefined}
+ style={interactive ? { cursor: 'pointer' } : undefined}
+ >
+ <Table.Cell
+ className="filelist-selector"
+ onClick={interactive ? (e) => e.stopPropagation() : undefined}
+ >
+ {onSelectionChange != null && (
+ <Checkbox
+ checked={allChildSelected}
+ disabled={disabled}
+ fitted
+ onChange={(_, data) => onSelectionChange(childFiles, data.checked)}
+ />
+ )}
+ </Table.Cell>
+ <Table.Cell
+ className="filelist-filename"
+ style={indent ? { paddingLeft: '2em' } : undefined}
+ >
+ <Icon name={folderIcon} />
+ {dirName}
+ <span
+ style={{
+ fontSize: '0.8em',
+ marginLeft: '0.5em',
+ opacity: 0.5,
+ }}
+ >
+ {formatDirCaption(dir.totalFileCount, dir.totalDirectoryCount)}
+ </span>
+ {directorySuffix &&
+ (interactive ? (
+ <span
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ role="presentation"
+ style={{ float: 'right' }}
+ >
+ {directorySuffix(dir)}
+ </span>
+ ) : (
+ <span style={{ float: 'right' }}>{directorySuffix(dir)}</span>
+ ))}
+ </Table.Cell>
+ <Table.Cell className="filelist-size">
+ {formatBytes(totalSize)}
+ </Table.Cell>
+ <Table.Cell className="filelist-attributes">
+ {getAttributes(childFiles)}
+ </Table.Cell>
+ <Table.Cell className="filelist-length">
+ {totalLength > 0 ? formatSeconds(totalLength) : ''}
+ </Table.Cell>
+ </Table.Row>
+ );
+};
+
+// childFiles contains all files in dir and its subdirs, pre-filtered by the parent
+const Directory = ({
+ childFiles,
+ dir,
+ directorySuffix,
+ disabled,
+ isExpanded,
+ onExpand,
+ onSelectionChange,
+ sep,
+}) => (
+ <>
+ <DirectoryRow
+ childFiles={childFiles}
+ dir={dir}
+ directorySuffix={directorySuffix}
+ disabled={disabled}
+ isExpanded={isExpanded}
+ onExpand={onExpand}
+ onSelectionChange={onSelectionChange}
+ sep={sep}
+ />
+ {isExpanded && (
+ <>
+ {(dir.children || []).map((subChild) => {
+ const subPrefix = subChild.name + sep;
+ const subChildFiles = childFiles.filter((f) =>
+ f.filename.startsWith(subPrefix),
+ );
+ return (
+ <DirectoryRow
+ childFiles={subChildFiles}
+ dir={subChild}
+ directorySuffix={directorySuffix}
+ indent
+ key={subChild.name}
+ sep={sep}
+ />
+ );
+ })}
+ {(dir.files || [])
+ .slice()
+ .sort((a, b) => a.filename.localeCompare(b.filename))
+ .map((f) => {
+ const fullFilename = `${dir.name}${sep}${f.filename}`;
+ return (
+ <File
+ file={{ ...f, filename: fullFilename }}
+ indent
+ key={fullFilename}
+ />
+ );
+ })}
+ </>
+ )}
+ </>
+);
+
+const FileBrowser = ({
+ directorySuffix,
+ disabled,
+ expandedDirectory,
+ files,
+ footer,
+ locked,
+ onClose,
+ onExpandedDirectoryChange,
+ onSelectionChange,
+ rootDirectory,
+ separator,
+}) => {
+ const [folded, setFolded] = useState(false);
+
+ // flatten the list of files that we've been given and turn it into a map
+ // keyed on the fully qualified name of the file and with a value of the file object
+ const fileMap = useMemo(() => {
+ const map = new Map();
+ for (const f of files || []) {
+ map.set(f.filename, f);
+ }
+
+ return map;
+ }, [files]);
+
+ const directoryName = rootDirectory?.name || '';
+ const sep = separator || '\\';
+
+ const filesInRoot = useMemo(
+ () =>
+ (rootDirectory?.files || [])
+ .map((f) => ({
+ ...f,
+ fullFilename: `${directoryName}${sep}${f.filename}`,
+ }))
+ .sort((a, b) => a.filename.localeCompare(b.filename)),
+ [directoryName, rootDirectory, sep],
+ );
+
+ const childDirs = useMemo(
+ () => rootDirectory?.children || [],
+ [rootDirectory],
+ );
+
+ // Group all files by their direct child directory in a single O(N) pass,
+ // so each DirectoryRow receives a pre-filtered slice instead of scanning
+ // the full list itself (which would be O(N_dirs × N_files)).
+ const filesByDir = useMemo(() => {
+ if (!directoryName) return new Map();
+ const map = new Map();
+ const parentPrefix = directoryName + sep;
+ for (const f of files || []) {
+ const rest = f.filename.startsWith(parentPrefix)
+ ? f.filename.slice(parentPrefix.length)
+ : null;
+ if (rest === null) continue;
+ const sepIdx = rest.indexOf(sep);
+ if (sepIdx === -1) continue; // direct file in rootDirectory, not in a subdir
+ const childDirName = parentPrefix + rest.slice(0, sepIdx);
+ let group = map.get(childDirName);
+ if (!group) {
+ group = [];
+ map.set(childDirName, group);
+ }
+
+ group.push(f);
+ }
+
+ return map;
+ }, [directoryName, files, sep]);
+
+ const allSelected =
+ (files?.length ?? 0) > 0 && files.every((f) => f.selected);
+
+ const handleSelectAll = (_, data) => {
+ onSelectionChange(data.checked ? (files || []).map((f) => f.filename) : []);
+ };
+
+ const handleFileToggle = (file, checked) => {
+ const result = [];
+ for (const f of files || []) {
+ if (f === file ? checked : f.selected) result.push(f.filename);
+ }
+
+ onSelectionChange(result);
+ };
+
+ const handleDirToggle = (childFiles, checked) => {
+ const childSet = new Set(childFiles.map((f) => f.filename));
+ const result = [];
+ for (const f of files || []) {
+ if (childSet.has(f.filename) ? checked : f.selected)
+ result.push(f.filename);
+ }
+
+ onSelectionChange(result);
+ };
+
+ const handleExpandDirectory = (name) => {
+ onExpandedDirectoryChange(expandedDirectory === name ? null : name);
+ };
+
+ const hasContent = filesInRoot.length > 0 || childDirs.length > 0;
+
+ return (
+ <div style={{ opacity: locked ? 0.5 : 1 }}>
+ <Header
+ className="filelist-header"
+ size="small"
+ >
+ <div>
+ <Icon
+ link={!locked}
+ name={locked ? 'lock' : folded ? 'folder' : 'folder open'}
+ onClick={() => !locked && setFolded(!folded)}
+ size="large"
+ />
+ {directoryName}
+ {Boolean(onClose) && (
+ <Icon
+ className="close-button"
+ color="red"
+ link
+ name="close"
+ onClick={() => onClose()}
+ />
+ )}
+ </div>
+ </Header>
+ {!folded && hasContent && (
+ <Table>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell className="filelist-selector">
+ <Checkbox
+ checked={allSelected}
+ disabled={disabled}
+ fitted
+ onChange={handleSelectAll}
+ />
+ </Table.HeaderCell>
+ <Table.HeaderCell className="filelist-filename">
+ {childDirs.length > 0 ? 'Name' : 'File'}
+ </Table.HeaderCell>
+ <Table.HeaderCell className="filelist-size">
+ Size
+ </Table.HeaderCell>
+ <Table.HeaderCell className="filelist-attributes">
+ Attributes
+ </Table.HeaderCell>
+ <Table.HeaderCell className="filelist-length">
+ Length
+ </Table.HeaderCell>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {childDirs.map((child) => (
+ <Directory
+ childFiles={filesByDir.get(child.name) || []}
+ dir={child}
+ directorySuffix={directorySuffix}
+ disabled={disabled}
+ isExpanded={expandedDirectory === child.name}
+ key={child.name}
+ onExpand={handleExpandDirectory}
+ onSelectionChange={handleDirToggle}
+ sep={sep}
+ />
+ ))}
+ {filesInRoot.map((f) => {
+ const flatFile = fileMap.get(f.fullFilename);
+ return (
+ <File
+ disabled={disabled}
+ file={flatFile || f}
+ key={f.fullFilename}
+ locked={locked}
+ onSelectionChange={flatFile ? handleFileToggle : undefined}
+ />
+ );
+ })}
+ </Table.Body>
+ {footer && (
+ <Table.Footer fullWidth>
+ <Table.Row>
+ <Table.HeaderCell colSpan="5">
+ {footer(files || [])}
+ </Table.HeaderCell>
+ </Table.Row>
+ </Table.Footer>
+ )}
+ </Table>
+ )}
+ </div>
+ );
+};
+
+export default React.memo(FileBrowser);
diff --git a/src/web/src/components/Browse/Selection.jsx b/src/web/src/components/Browse/Selection.jsx
new file mode 100644
index 00000000..2a5539b6
--- /dev/null
+++ b/src/web/src/components/Browse/Selection.jsx
@@ -0,0 +1,222 @@
+import * as transfers from '../../lib/transfers';
+import { formatBytes } from '../../lib/util';
+import FileBrowser from './FileBrowser';
+import React, { Component } from 'react';
+import { Button, Card, Icon, Label } from 'semantic-ui-react';
+
+const initialState = {
+ downloadError: '',
+ downloadRequest: undefined,
+ files: [],
+};
+
+const getAllFilesFromNode = (node, separator) => {
+ const direct = (node.files || []).map((f) => ({
+ ...f,
+ filename: `${node.name}${separator}${f.filename}`,
+ }));
+ return [
+ ...direct,
+ ...(node.children || []).flatMap((child) =>
+ getAllFilesFromNode(child, separator),
+ ),
+ ];
+};
+
+class Selection extends Component {
+ constructor(props) {
+ super(props);
+ const selectedFilenames = new Set(props.defaultSelectedFiles || []);
+ this.state = {
+ ...initialState,
+ expandedDirectory: props.defaultSubdirectory ?? null,
+ files: getAllFilesFromNode(props.node, props.separator).map((f) => ({
+ selected: selectedFilenames.has(f.filename),
+ ...f,
+ })),
+ };
+ }
+
+ componentDidUpdate(previousProps) {
+ if (this.props.node?.name !== previousProps.node?.name) {
+ this.setState({
+ ...initialState,
+ expandedDirectory: this.props.node?.children?.[0]?.name ?? null,
+ files: getAllFilesFromNode(this.props.node, this.props.separator).map(
+ (f) => ({ selected: false, ...f }),
+ ),
+ });
+ }
+ }
+
+ handleSelectionChange = (selectedFilenames) => {
+ const selectedSet = new Set(selectedFilenames);
+ this.setState(
+ (prevState) => ({
+ downloadError: '',
+ downloadRequest: undefined,
+ files: prevState.files.map((f) => ({
+ ...f,
+ selected: selectedSet.has(f.filename),
+ })),
+ }),
+ () =>
+ this.props.onStateChange?.({
+ files: selectedFilenames,
+ subdirectory: this.state.expandedDirectory,
+ }),
+ );
+ };
+
+ handleExpandedDirectoryChange = (name) => {
+ this.setState({ expandedDirectory: name }, () =>
+ this.props.onStateChange?.({
+ files: this.state.files
+ .filter((f) => f.selected)
+ .map((f) => f.filename),
+ subdirectory: this.state.expandedDirectory,
+ }),
+ );
+ };
+
+ handleDownload = () => {
+ const { name, separator, username } = this.props;
+ const selectedFiles = this.state.files.filter((f) => f.selected);
+ const parent = name.split(separator).slice(0, -1).join(separator);
+ const prefix = name + separator;
+
+ this.setState({ downloadRequest: 'inProgress' }, async () => {
+ try {
+ const groups = new Map();
+ for (const file of selectedFiles) {
+ const relative = file.filename.startsWith(prefix)
+ ? file.filename.slice(prefix.length)
+ : file.filename;
+ const parts = relative.split(separator).filter(Boolean);
+ const group = parts.length > 1 ? parts[0] : '';
+ if (!groups.has(group)) {
+ groups.set(group, []);
+ }
+
+ groups.get(group).push(file);
+ }
+
+ const rootFiles = groups.get('') || [];
+ if (rootFiles.length > 0) {
+ await transfers.download({
+ files: rootFiles.map(({ filename, size }) => ({ filename, size })),
+ username,
+ });
+ }
+
+ for (const [dirName, dirFiles] of groups) {
+ if (dirName === '') {
+ continue;
+ }
+
+ const destination = (prefix + dirName)
+ .slice(parent.length > 0 ? parent.length + 1 : 0)
+ .split(separator)
+ .join('/');
+ await transfers.enqueueBatch({
+ files: dirFiles.map(({ filename, size }) => ({ filename, size })),
+ options: { destination },
+ username,
+ });
+ }
+
+ this.setState({ downloadRequest: 'complete' });
+ } catch (error) {
+ this.setState({
+ downloadError: error.response,
+ downloadRequest: 'error',
+ });
+ }
+ });
+ };
+
+ render() {
+ const { directorySuffix, locked, marginTop, node, onClose, separator } =
+ this.props;
+ const { downloadError, downloadRequest, expandedDirectory, files } =
+ this.state;
+
+ const selectedFiles = files.filter((f) => f.selected);
+ const totalSize = formatBytes(
+ selectedFiles.reduce((sum, f) => sum + (f.size || 0), 0),
+ );
+
+ return (
+ <Card
+ className="result-card"
+ raised
+ >
+ <Card.Content>
+ <div style={{ marginTop: marginTop || 0 }}>
+ <FileBrowser
+ directorySuffix={directorySuffix}
+ disabled={downloadRequest === 'inProgress'}
+ expandedDirectory={expandedDirectory}
+ files={files}
+ locked={locked}
+ onClose={onClose}
+ onExpandedDirectoryChange={this.handleExpandedDirectoryChange}
+ onSelectionChange={this.handleSelectionChange}
+ rootDirectory={node}
+ separator={separator}
+ />
+ </div>
+ </Card.Content>
+ {selectedFiles.length > 0 && (
+ <Card.Content extra>
+ <span>
+ <Button
+ color="green"
+ content="Download"
+ disabled={downloadRequest === 'inProgress'}
+ icon="download"
+ label={{
+ as: 'a',
+ basic: false,
+ content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${totalSize}`,
+ }}
+ labelPosition="right"
+ onClick={this.handleDownload}
+ />
+ {downloadRequest === 'inProgress' && (
+ <Icon
+ loading
+ name="circle notch"
+ size="large"
+ />
+ )}
+ {downloadRequest === 'complete' && (
+ <Icon
+ color="green"
+ name="checkmark"
+ size="large"
+ />
+ )}
+ {downloadRequest === 'error' && (
+ <span>
+ <Icon
+ color="red"
+ name="x"
+ size="large"
+ />
+ <Label>
+ {downloadError?.data
+ ? `${downloadError.data} (HTTP ${downloadError.status} ${downloadError.statusText})`
+ : 'Download failed'}
+ </Label>
+ </span>
+ )}
+ </span>
+ </Card.Content>
+ )}
+ </Card>
+ );
+ }
+}
+
+export default Selection;
diff --git a/src/web/src/lib/transfers.js b/src/web/src/lib/transfers.js
index 7fa58fc3..361926ae 100644
--- a/src/web/src/lib/transfers.js
+++ b/src/web/src/lib/transfers.js
@@ -20,6 +20,42 @@ export const download = ({ username, files = [] }) => {
);
};
+/**
+ * Enqueues a batch of downloads.
+ * @param {object} params
+ * @param {string} params.username - The user to download from.
+ * @param {{ filename: string, size: number }[]} [params.files] - Files to enqueue.
+ * @param {string} [params.id] - Optional batch GUID. Generated server-side if omitted.
+ * @param {string} [params.searchId] - Optional GUID of an associated search.
+ * @param {{ destination?: string, externalId?: string }} [params.options] - `destination`: path relative to the configured download directory; `externalId`: optional external identifier for the batch.
+ * @returns {Promise} Resolves with the axios response.
+ * - 201: all files enqueued successfully
+ * - 200: batch created, but every file failed to enqueue — check `response.data.failures`
+ * - 207: partial — some enqueued, some failed — check `response.data.failures`
+ * @throws On error responses:
+ * - 400: validation failure (username/files required; duplicate filenames; id or searchId not a valid GUID)
+ * - 403: forbidden — running as relay agent
+ * - 404: user is offline
+ * - 409: a batch with the supplied id already exists
+ * - 429: a concurrent enqueue request is already in progress
+ * - 500: unexpected server error
+ */
+export const enqueueBatch = ({
+ username,
+ files = [],
+ id,
+ searchId,
+ options = { destination: undefined, externalId: undefined },
+}) => {
+ return api.post('/transfers/downloads/batches', {
+ files,
+ id,
+ options,
+ searchId,
+ username,
+ });
+};
+
export const cancel = ({ direction, username, id, remove = false }) => {
return api.delete(
`/transfers/${direction}s/${encodeURIComponent(username)}/${encodeURIComponent(id)}?remove=${remove}`,
@@ -30,23 +66,26 @@ export const clearCompleted = ({ direction }) => {
return api.delete(`/transfers/${direction}s/all/completed`);
};
-// 'Requested'
-// 'Queued, Remotely'
-// 'Queued, Locally'
-// 'Initializing'
-// 'InProgress'
-// 'Completed, Succeeded'
-// 'Completed, Cancelled'
-// 'Completed, TimedOut'
-// 'Completed, Errored'
-// 'Completed, Rejected'
-
export const getPlaceInQueue = ({ username, id }) => {
return api.get(
`/transfers/downloads/${encodeURIComponent(username)}/${encodeURIComponent(id)}/position`,
);
};
+/*
+ states:
+
+ 'Requested'
+ 'Queued, Remotely'
+ 'Queued, Locally'
+ 'Initializing'
+ 'InProgress'
+ 'Completed, Succeeded'
+ 'Completed, Cancelled'
+ 'Completed, TimedOut'
+ 'Completed, Errored'
+ 'Completed, Rejected'
+*/
export const isStateRetryable = (state) =>
state.includes('Completed') && state !== 'Completed, Succeeded';