aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJoshua May <git@hotdog.horse>2024-02-11 01:16:17 +0100
committerJoshua May <git@hotdog.horse>2024-02-11 01:16:36 +0100
commit8c01716b0d1539a62accdbc38d79a84c9c19c4ac (patch)
treec9c8140c20ba9192b93ba50d3cf0dfd21c050393 /src
parent43d3fe7fed71774817faeb402de7e3fe50e171cf (diff)
downloadslskd-8c01716b0d1539a62accdbc38d79a84c9c19c4ac.tar.gz
eslint --fix
Diffstat (limited to 'src')
-rw-r--r--src/web/craco.config.js6
-rw-r--r--src/web/package.json54
-rw-r--r--src/web/src/components/App.jsx679
-rw-r--r--src/web/src/components/AppContext.js2
-rw-r--r--src/web/src/components/Browse/Browse.jsx364
-rw-r--r--src/web/src/components/Browse/Directory.jsx147
-rw-r--r--src/web/src/components/Browse/DirectoryTree.jsx38
-rw-r--r--src/web/src/components/Chat/Chat.jsx259
-rw-r--r--src/web/src/components/Chat/ChatMenu.jsx52
-rw-r--r--src/web/src/components/Chat/SendMessageModal.jsx29
-rw-r--r--src/web/src/components/LoginForm.jsx147
-rw-r--r--src/web/src/components/Rooms/RoomJoinModal.jsx115
-rw-r--r--src/web/src/components/Rooms/RoomMenu.jsx41
-rw-r--r--src/web/src/components/Rooms/RoomUserList.jsx51
-rw-r--r--src/web/src/components/Rooms/Rooms.jsx301
-rw-r--r--src/web/src/components/Search/Detail/SearchDetail.jsx234
-rw-r--r--src/web/src/components/Search/Detail/SearchDetailHeader.jsx95
-rw-r--r--src/web/src/components/Search/List/SearchActionIcon.jsx41
-rw-r--r--src/web/src/components/Search/List/SearchList.jsx83
-rw-r--r--src/web/src/components/Search/List/SearchListRow.jsx46
-rw-r--r--src/web/src/components/Search/Response.jsx234
-rw-r--r--src/web/src/components/Search/SearchStatusIcon.jsx77
-rw-r--r--src/web/src/components/Search/Searches.jsx181
-rw-r--r--src/web/src/components/Shared/CodeEditor.jsx24
-rw-r--r--src/web/src/components/Shared/Div.jsx6
-rw-r--r--src/web/src/components/Shared/ErrorSegment.jsx21
-rw-r--r--src/web/src/components/Shared/FileList.jsx168
-rw-r--r--src/web/src/components/Shared/LoaderSegment.jsx21
-rw-r--r--src/web/src/components/Shared/Logo.jsx10
-rw-r--r--src/web/src/components/Shared/Nbsp.jsx2
-rw-r--r--src/web/src/components/Shared/PlaceholderSegment.jsx22
-rw-r--r--src/web/src/components/Shared/ShrinkableButton.jsx20
-rw-r--r--src/web/src/components/Shared/ShrinkableDropdownButton.jsx45
-rw-r--r--src/web/src/components/Shared/Switch.jsx6
-rw-r--r--src/web/src/components/Shared/index.js2
-rw-r--r--src/web/src/components/System/Data/index.jsx35
-rw-r--r--src/web/src/components/System/Files/Explorer.jsx256
-rw-r--r--src/web/src/components/System/Files/index.jsx37
-rw-r--r--src/web/src/components/System/Info/index.jsx107
-rw-r--r--src/web/src/components/System/Logs/index.jsx66
-rw-r--r--src/web/src/components/System/Options/DebugModal.jsx46
-rw-r--r--src/web/src/components/System/Options/EditModal.jsx118
-rw-r--r--src/web/src/components/System/Options/index.jsx92
-rw-r--r--src/web/src/components/System/Shares/ContentsModal.jsx65
-rw-r--r--src/web/src/components/System/Shares/ExclusionTable.jsx45
-rw-r--r--src/web/src/components/System/Shares/ShareTable.jsx66
-rw-r--r--src/web/src/components/System/Shares/index.jsx151
-rw-r--r--src/web/src/components/System/System.jsx174
-rw-r--r--src/web/src/components/Transfers/TransferGroup.jsx191
-rw-r--r--src/web/src/components/Transfers/TransferList.jsx215
-rw-r--r--src/web/src/components/Transfers/Transfers.jsx98
-rw-r--r--src/web/src/components/Transfers/TransfersHeader.jsx185
-rw-r--r--src/web/src/components/Users/User.jsx89
-rw-r--r--src/web/src/components/Users/Users.jsx119
-rw-r--r--src/web/src/config.js17
-rw-r--r--src/web/src/index.jsx8
-rw-r--r--src/web/src/lib/api.js43
-rw-r--r--src/web/src/lib/application.js5
-rw-r--r--src/web/src/lib/chat.js7
-rw-r--r--src/web/src/lib/files.js13
-rw-r--r--src/web/src/lib/hubFactory.js26
-rw-r--r--src/web/src/lib/options.js2
-rw-r--r--src/web/src/lib/relay.js2
-rw-r--r--src/web/src/lib/rooms.js15
-rw-r--r--src/web/src/lib/searches.js182
-rw-r--r--src/web/src/lib/searches.test.js140
-rw-r--r--src/web/src/lib/server.js6
-rw-r--r--src/web/src/lib/session.js19
-rw-r--r--src/web/src/lib/shares.js2
-rw-r--r--src/web/src/lib/transfers.js25
-rw-r--r--src/web/src/lib/users.js8
-rw-r--r--src/web/src/lib/util.js94
-rw-r--r--src/web/src/lib/util.test.js6
73 files changed, 3865 insertions, 2533 deletions
diff --git a/src/web/craco.config.js b/src/web/craco.config.js
index 54024b07..26ffce2b 100644
--- a/src/web/craco.config.js
+++ b/src/web/craco.config.js
@@ -1,3 +1,5 @@
+const CracoLessPlugin = require('@semantic-ui-react/craco-less');
+
module.exports = {
- plugins: [{ plugin: require('@semantic-ui-react/craco-less') }],
-} \ No newline at end of file
+ plugins: [{ plugin: CracoLessPlugin }],
+};
diff --git a/src/web/package.json b/src/web/package.json
index 7a438a28..49990771 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -1,17 +1,17 @@
{
- "name": "web",
- "version": "0.1.0",
- "private": true,
- "homepage": ".",
- "scripts": {
- "start": "craco start",
- "build": "craco build",
- "test": "craco test",
- "test-unattended": "craco test --watchAll false --passWithNoTests",
- "eject": "craco eject",
- "postinstall": "semantic-ui-css-patch",
- "lint": "eslint .",
- "lint:fix": "eslint --fix ."
+ "browserslist": {
+ "development": [
+ ">0.3%",
+ "not ie 11",
+ "not dead",
+ "not op_mini all"
+ ],
+ "production": [
+ ">0.3%",
+ "not ie 11",
+ "not dead",
+ "not op_mini all"
+ ]
},
"dependencies": {
"@codemirror/language": "^6.0.0",
@@ -40,23 +40,23 @@
"eslint-config-canonical": "^42.8.1",
"react-scripts": "^5.0.0"
},
+ "homepage": ".",
+ "name": "web",
"overrides": {
"@craco/craco": "^7.0.0",
"css-select": "^3.1.0",
"css-what": "^5.0.1"
},
- "browserslist": {
- "production": [
- ">0.3%",
- "not ie 11",
- "not dead",
- "not op_mini all"
- ],
- "development": [
- ">0.3%",
- "not ie 11",
- "not dead",
- "not op_mini all"
- ]
- }
+ "private": true,
+ "scripts": {
+ "build": "craco build",
+ "eject": "craco eject",
+ "lint": "eslint .",
+ "lint:fix": "eslint --fix .",
+ "postinstall": "semantic-ui-css-patch",
+ "start": "craco start",
+ "test": "craco test",
+ "test-unattended": "craco test --watchAll false --passWithNoTests"
+ },
+ "version": "0.1.0"
}
diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx
index 6231fdac..cb906871 100644
--- a/src/web/src/components/App.jsx
+++ b/src/web/src/components/App.jsx
@@ -1,96 +1,104 @@
-import React, { Component } from 'react';
-import { Route, Link, Switch, Redirect } from 'react-router-dom';
-
-import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
-
-import * as session from '../lib/session';
-import * as relayAPI from '../lib/relay';
-import { connect, disconnect } from '../lib/server';
+import './App.css';
import { urlBase } from '../config';
-
import { createApplicationHubConnection } from '../lib/hubFactory';
-
-import './App.css';
-import Searches from './Search/Searches';
+import * as relayAPI from '../lib/relay';
+import { connect, disconnect } from '../lib/server';
+import * as session from '../lib/session';
+import AppContext from './AppContext';
import Browse from './Browse/Browse';
-import Users from './Users/Users';
-import Transfers from './Transfers/Transfers';
import Chat from './Chat/Chat';
-import System from './System/System';
import LoginForm from './LoginForm';
-
-import AppContext from './AppContext';
-
-import {
- Sidebar,
- Segment,
- Menu,
- Icon,
- Modal,
- Header,
+import Rooms from './Rooms/Rooms';
+import Searches from './Search/Searches';
+import ErrorSegment from './Shared/ErrorSegment';
+import System from './System/System';
+import Transfers from './Transfers/Transfers';
+import Users from './Users/Users';
+import React, { Component } from 'react';
+import { Link, Redirect, Route, Switch } from 'react-router-dom';
+import { ToastContainer } from 'react-toastify';
+import {
Button,
+ Header,
+ Icon,
Loader,
+ Menu,
+ Modal,
+ Segment,
+ Sidebar,
} from 'semantic-ui-react';
-import Rooms from './Rooms/Rooms';
-import ErrorSegment from './Shared/ErrorSegment';
const initialState = {
+ applicationOptions: {},
+ applicationState: {},
+ error: false,
+ initialized: false,
login: {
- pending: false,
error: undefined,
+ pending: false,
},
- applicationState: {},
- applicationOptions: {},
- initialized: false,
- error: false,
retriesExhausted: false,
};
class App extends Component {
state = initialState;
- componentDidMount = () => {
- window.matchMedia('(prefers-color-scheme: dark)')
- .addEventListener('change', (e) => e.matches && this.setState({theme: 'dark'}));
- window.matchMedia('(prefers-color-scheme: light)')
- .addEventListener('change', (e) => e.matches && this.setState({theme:'light'}));
+ componentDidMount() {
+ window
+ .matchMedia('(prefers-color-scheme: dark)')
+ .addEventListener(
+ 'change',
+ (e) => e.matches && this.setState({ theme: 'dark' }),
+ );
+ window
+ .matchMedia('(prefers-color-scheme: light)')
+ .addEventListener(
+ 'change',
+ (e) => e.matches && this.setState({ theme: 'light' }),
+ );
this.init();
- };
+ }
init = async () => {
this.setState({ initialized: false }, async () => {
try {
const securityEnabled = await session.getSecurityEnabled();
-
+
if (!securityEnabled) {
console.debug('application security is not enabled, per api call');
session.enablePassthrough();
}
-
+
if (await session.check()) {
const appHub = createApplicationHubConnection();
appHub.on('state', (state) => {
this.setState({ applicationState: state });
});
-
+
appHub.on('options', (options) => {
this.setState({ applicationOptions: options });
});
- appHub.onreconnecting(() => this.setState({ error: true, retriesExhausted: false }));
- appHub.onclose(() => this.setState({ error: true, retriesExhausted: true }));
- appHub.onreconnected(() => this.setState({ error: false, retriesExhausted: false }));
+ appHub.onreconnecting(() =>
+ this.setState({ error: true, retriesExhausted: false }),
+ );
+ appHub.onclose(() =>
+ this.setState({ error: true, retriesExhausted: true }),
+ );
+ appHub.onreconnected(() =>
+ this.setState({ error: false, retriesExhausted: false }),
+ );
await appHub.start();
}
-
+
this.setState({
error: false,
});
- } catch (err) {
- console.error(err);
+ } catch (error) {
+ console.error(error);
this.setState({ error: true, retriesExhausted: true });
} finally {
this.setState({ initialized: true });
@@ -99,19 +107,27 @@ class App extends Component {
};
login = (username, password, rememberMe) => {
- this.setState({ login: { ...this.state.login, pending: true, error: undefined }}, async () => {
- try {
- await session.login({ username, password, rememberMe });
- this.setState({ login: { ...this.state.login, pending: false, error: false }}, () => this.init());
- } catch (error) {
- this.setState({ login: { ...this.state.login, pending: false, error }});
- }
- });
+ this.setState(
+ { login: { ...this.state.login, error: undefined, pending: true } },
+ async () => {
+ try {
+ await session.login({ password, rememberMe, username });
+ this.setState(
+ { login: { ...this.state.login, error: false, pending: false } },
+ () => this.init(),
+ );
+ } catch (error) {
+ this.setState({
+ login: { ...this.state.login, error, pending: false },
+ });
+ }
+ },
+ );
};
-
+
logout = () => {
session.logout();
- this.setState({ login: { ...initialState.login }});
+ this.setState({ login: { ...initialState.login } });
};
withTokenCheck = (component) => {
@@ -119,98 +135,147 @@ class App extends Component {
return { ...component };
};
- render = () => {
- const {
- login,
- applicationState = {},
- applicationOptions = {},
- error,
- initialized,
- retriesExhausted,
- theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light',
+ render() {
+ const {
+ applicationOptions = {},
+ applicationState = {},
+ error,
+ initialized,
+ login,
+ retriesExhausted,
+ theme = window.matchMedia('(prefers-color-scheme: dark)').matches
+ ? 'dark'
+ : 'light',
} = this.state;
- const {
- version = {},
- relay = {},
- server,
+ const {
pendingReconnect,
pendingRestart,
+ relay = {},
+ server,
shares = {},
user,
+ version = {},
} = applicationState;
- const { isUpdateAvailable, current, latest } = version;
+ const { current, isUpdateAvailable, latest } = version;
const { scanPending: pendingShareRescan } = shares;
- const { mode, controller } = relay;
+ const { controller, mode } = relay;
if (!initialized) {
- return <Loader active size='big'/>;
+ return (
+ <Loader
+ active
+ size="big"
+ />
+ );
}
if (error) {
- return <ErrorSegment
- suppressPrefix
- icon='attention'
- caption={
- <>
- <span>
- Lost connection to slskd</span><br /><span>{(retriesExhausted ? 'Refresh to reconnect' : 'Retrying...')}
- </span>
- </>
- }/>;
+ return (
+ <ErrorSegment
+ caption={
+ <>
+ <span>Lost connection to slskd</span>
+ <br />
+ <span>
+ {retriesExhausted ? 'Refresh to reconnect' : 'Retrying...'}
+ </span>
+ </>
+ }
+ icon="attention"
+ suppressPrefix
+ />
+ );
}
if (!session.isLoggedIn() && !session.isPassthroughEnabled()) {
return (
- <LoginForm
- onLoginAttempt={this.login}
- initialized={login.initialized}
- loading={login.pending}
+ <LoginForm
error={login.error}
+ initialized={login.initialized}
+ loading={login.pending}
+ onLoginAttempt={this.login}
/>
);
}
-
- const ModeSpecificConnectButton = ({ mode, server, controller = {} }) => {
+
+ const ModeSpecificConnectButton = ({ controller = {}, mode, server }) => {
if (mode === 'Agent') {
const isConnected = controller?.state === 'Connected';
- const isTransitioning = ['Connecting', 'Reconnecting'].includes(controller?.state);
+ const isTransitioning = ['Connecting', 'Reconnecting'].includes(
+ controller?.state,
+ );
- return <>
+ return (
<Menu.Item
- onClick={() => isConnected ? relayAPI.disconnect() : relayAPI.connect()}
+ onClick={() =>
+ isConnected ? relayAPI.disconnect() : relayAPI.connect()
+ }
>
- <Icon.Group className='menu-icon-group'>
- <Icon
- name='plug'
- color={controller?.state === 'Connected'
- ? 'green'
- : isTransitioning ? 'yellow' : 'grey'}
+ <Icon.Group className="menu-icon-group">
+ <Icon
+ color={
+ controller?.state === 'Connected'
+ ? 'green'
+ : isTransitioning
+ ? 'yellow'
+ : 'grey'
+ }
+ name="plug"
/>
- {!isConnected && <Icon name='close' color='red' corner='bottom right' className='menu-icon-no-shadow'/>}
- </Icon.Group>Controller {controller?.state}
+ {!isConnected && (
+ <Icon
+ className="menu-icon-no-shadow"
+ color="red"
+ corner="bottom right"
+ name="close"
+ />
+ )}
+ </Icon.Group>
+ Controller {controller?.state}
</Menu.Item>
- </>;
+ );
} else {
- return <>
- {server?.isConnected && <Menu.Item
- onClick={() => disconnect()}
- >
- <Icon.Group className='menu-icon-group'>
- <Icon name='plug' color={pendingReconnect ? 'yellow' : 'green'}/>
- {user?.privileges?.isPrivileged &&
- <Icon name='star' color='yellow' corner className='menu-icon-no-shadow'/>}
- </Icon.Group>Connected
- </Menu.Item>}
- {(!server?.isConnected) && <Menu.Item
- onClick={() => connect()}
- >
- <Icon.Group className='menu-icon-group'>
- <Icon name='plug' color='grey'/>
- <Icon name='close' color='red' corner='bottom right' className='menu-icon-no-shadow'/>
- </Icon.Group>Disconnected
- </Menu.Item>}
- </>;
+ return (
+ <>
+ {server?.isConnected && (
+ <Menu.Item onClick={() => disconnect()}>
+ <Icon.Group className="menu-icon-group">
+ <Icon
+ color={pendingReconnect ? 'yellow' : 'green'}
+ name="plug"
+ />
+ {user?.privileges?.isPrivileged && (
+ <Icon
+ className="menu-icon-no-shadow"
+ color="yellow"
+ corner
+ name="star"
+ />
+ )}
+ </Icon.Group>
+ Connected
+ </Menu.Item>
+ )}
+ {!server?.isConnected && (
+ <Menu.Item onClick={() => connect()}>
+ <Icon.Group className="menu-icon-group">
+ <Icon
+ color="grey"
+ name="plug"
+ />
+ <Icon
+ className="menu-icon-no-shadow"
+ color="red"
+ corner="bottom right"
+ name="close"
+ />
+ </Icon.Group>
+ Disconnected
+ </Menu.Item>
+ )}
+ </>
+ );
}
};
@@ -224,178 +289,314 @@ class App extends Component {
return (
<>
- <Sidebar.Pushable as={Segment} className='app'>
+ <Sidebar.Pushable
+ as={Segment}
+ className="app"
+ >
<Sidebar
- className='navigation'
- as={Menu}
- animation='overlay'
- icon='labeled'
- inverted
- horizontal='true'
- direction='top'
- visible width='thin'
+ animation="overlay"
+ as={Menu}
+ className="navigation"
+ direction="top"
+ horizontal="true"
+ icon="labeled"
+ inverted
+ visible
+ width="thin"
>
- {version.isCanary && <Menu.Item>
- <Icon name='flask' color='yellow'/>Canary
- </Menu.Item>}
- {isAgent ? <Menu.Item>
- <Icon name='detective'/>Agent Mode
- </Menu.Item> :
+ {version.isCanary && (
+ <Menu.Item>
+ <Icon
+ color="yellow"
+ name="flask"
+ />
+ Canary
+ </Menu.Item>
+ )}
+ {isAgent ? (
+ <Menu.Item>
+ <Icon name="detective" />
+ Agent Mode
+ </Menu.Item>
+ ) : (
<>
<Link to={`${urlBase}/searches`}>
<Menu.Item>
- <Icon name='search'/>Search
+ <Icon name="search" />
+ Search
</Menu.Item>
</Link>
<Link to={`${urlBase}/downloads`}>
<Menu.Item>
- <Icon name='download'/>Downloads
+ <Icon name="download" />
+ Downloads
</Menu.Item>
</Link>
<Link to={`${urlBase}/uploads`}>
<Menu.Item>
- <Icon name='upload'/>Uploads
+ <Icon name="upload" />
+ Uploads
</Menu.Item>
</Link>
<Link to={`${urlBase}/rooms`}>
<Menu.Item>
- <Icon name='comments'/>Rooms
+ <Icon name="comments" />
+ Rooms
</Menu.Item>
</Link>
<Link to={`${urlBase}/chat`}>
<Menu.Item>
- <Icon name='comment'/>Chat
+ <Icon name="comment" />
+ Chat
</Menu.Item>
</Link>
<Link to={`${urlBase}/users`}>
<Menu.Item>
- <Icon name='users'/>Users
+ <Icon name="users" />
+ Users
</Menu.Item>
</Link>
<Link to={`${urlBase}/browse`}>
<Menu.Item>
- <Icon name='folder open'/>Browse
+ <Icon name="folder open" />
+ Browse
</Menu.Item>
</Link>
- </>}
- <Menu className='right' inverted>
- <Menu.Item onClick={() => this.setState({'theme': theme === 'dark' ? 'light' : 'dark'})}>
- <Icon name='theme'/>Theme
- </Menu.Item>
- <ModeSpecificConnectButton mode={mode} server={server} controller={controller} />
- {(pendingReconnect || pendingRestart || pendingShareRescan) && <Menu.Item position='right'>
- <Icon.Group className='menu-icon-group'>
- <Link to={`${urlBase}/system/info`}>
- <Icon name='exclamation circle' color='yellow'/>
- </Link>
- </Icon.Group>Pending Action
- </Menu.Item>}
- {isUpdateAvailable && <Modal
- trigger={<Menu.Item position='right'>
- <Icon.Group className='menu-icon-group'>
- <Icon name='bullhorn' color='yellow'/>
- </Icon.Group>New Version!
- </Menu.Item>}
- centered
- closeIcon
- size='mini'
+ </>
+ )}
+ <Menu
+ className="right"
+ inverted
+ >
+ <Menu.Item
+ onClick={() =>
+ this.setState({ theme: theme === 'dark' ? 'light' : 'dark' })
+ }
>
- <Modal.Header>New Version!</Modal.Header>
- <Modal.Content>
- <p>
- You are currently running version <strong>{current}</strong>
- while version <strong>{latest}</strong> is available.
- </p>
- </Modal.Content>
- <Modal.Actions>
- <Button
- style={{marginLeft: 0}}
- primary
- fluid
- href="https://github.com/slskd/slskd/releases">See Release Notes</Button>
- </Modal.Actions>
- </Modal>}
+ <Icon name="theme" />
+ Theme
+ </Menu.Item>
+ <ModeSpecificConnectButton
+ controller={controller}
+ mode={mode}
+ server={server}
+ />
+ {(pendingReconnect || pendingRestart || pendingShareRescan) && (
+ <Menu.Item position="right">
+ <Icon.Group className="menu-icon-group">
+ <Link to={`${urlBase}/system/info`}>
+ <Icon
+ color="yellow"
+ name="exclamation circle"
+ />
+ </Link>
+ </Icon.Group>
+ Pending Action
+ </Menu.Item>
+ )}
+ {isUpdateAvailable && (
+ <Modal
+ centered
+ closeIcon
+ size="mini"
+ trigger={
+ <Menu.Item position="right">
+ <Icon.Group className="menu-icon-group">
+ <Icon
+ color="yellow"
+ name="bullhorn"
+ />
+ </Icon.Group>
+ New Version!
+ </Menu.Item>
+ }
+ >
+ <Modal.Header>New Version!</Modal.Header>
+ <Modal.Content>
+ <p>
+ You are currently running version{' '}
+ <strong>{current}</strong>
+ while version <strong>{latest}</strong> is available.
+ </p>
+ </Modal.Content>
+ <Modal.Actions>
+ <Button
+ fluid
+ href="https://github.com/slskd/slskd/releases"
+ primary
+ style={{ marginLeft: 0 }}
+ >
+ See Release Notes
+ </Button>
+ </Modal.Actions>
+ </Modal>
+ )}
<Link to={`${urlBase}/system`}>
<Menu.Item>
- <Icon name='cogs'/>System
+ <Icon name="cogs" />
+ System
</Menu.Item>
</Link>
- {session.isLoggedIn() && <Modal
- trigger={
- <Menu.Item>
- <Icon name='sign-out'/>Log Out
- </Menu.Item>
- }
- centered
- size='mini'
- header={<Header icon='sign-out' content='Confirm Log Out' />}
- content='Are you sure you want to log out?'
- actions={['Cancel', { key: 'done', content: 'Log Out', negative: true, onClick: this.logout }]}
- />}
+ {session.isLoggedIn() && (
+ <Modal
+ actions={[
+ 'Cancel',
+ {
+ content: 'Log Out',
+ key: 'done',
+ negative: true,
+ onClick: this.logout,
+ },
+ ]}
+ centered
+ content="Are you sure you want to log out?"
+ header={
+ <Header
+ content="Confirm Log Out"
+ icon="sign-out"
+ />
+ }
+ size="mini"
+ trigger={
+ <Menu.Item>
+ <Icon name="sign-out" />
+ Log Out
+ </Menu.Item>
+ }
+ />
+ )}
</Menu>
</Sidebar>
- <Sidebar.Pusher className='app-content'>
- <AppContext.Provider value={{ state: applicationState, options: applicationOptions }}>
- {isAgent ? <Switch>
- <Route path={`${urlBase}/system/:tab?`} render={
- (props) => this.withTokenCheck(
- <System {...props} state={applicationState} options={applicationOptions} />
- )
- }/>
- <Redirect from='*' to={`${urlBase}/system`}/>
- </Switch> :
+ <Sidebar.Pusher className="app-content">
+ <AppContext.Provider
+ value={{ options: applicationOptions, state: applicationState }}
+ >
+ {isAgent ? (
<Switch>
- <Route path={`${urlBase}/searches/:id?`} render={(props) =>
- this.withTokenCheck(<div className='view'>
- <Searches
- server={applicationState.server}
- {...props}
- />
- </div>)}
+ <Route
+ path={`${urlBase}/system/:tab?`}
+ render={(props) =>
+ this.withTokenCheck(
+ <System
+ {...props}
+ options={applicationOptions}
+ state={applicationState}
+ />,
+ )
+ }
+ />
+ <Redirect
+ from="*"
+ to={`${urlBase}/system`}
+ />
+ </Switch>
+ ) : (
+ <Switch>
+ <Route
+ path={`${urlBase}/searches/:id?`}
+ render={(props) =>
+ this.withTokenCheck(
+ <div className="view">
+ <Searches
+ server={applicationState.server}
+ {...props}
+ />
+ </div>,
+ )
+ }
+ />
+ <Route
+ path={`${urlBase}/browse`}
+ render={(props) =>
+ this.withTokenCheck(<Browse {...props} />)
+ }
+ />
+ <Route
+ path={`${urlBase}/users`}
+ render={(props) =>
+ this.withTokenCheck(<Users {...props} />)
+ }
+ />
+ <Route
+ path={`${urlBase}/chat`}
+ render={(props) =>
+ this.withTokenCheck(
+ <Chat
+ {...props}
+ state={applicationState}
+ />,
+ )
+ }
/>
- <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/>
- <Route path={`${urlBase}/users`} render={(props) =>
- this.withTokenCheck(<Users {...props}/>)}
+ <Route
+ path={`${urlBase}/rooms`}
+ render={(props) =>
+ this.withTokenCheck(<Rooms {...props} />)
+ }
/>
- <Route path={`${urlBase}/chat`} render={(props) =>
- this.withTokenCheck(<Chat {...props} state={applicationState}/>)}
+ <Route
+ path={`${urlBase}/uploads`}
+ render={(props) =>
+ this.withTokenCheck(
+ <div className="view">
+ <Transfers
+ {...props}
+ direction="upload"
+ />
+ </div>,
+ )
+ }
+ />
+ <Route
+ path={`${urlBase}/downloads`}
+ render={(props) =>
+ this.withTokenCheck(
+ <div className="view">
+ <Transfers
+ {...props}
+ direction="download"
+ server={applicationState.server}
+ />
+ </div>,
+ )
+ }
+ />
+ <Route
+ path={`${urlBase}/system/:tab?`}
+ render={(props) =>
+ this.withTokenCheck(
+ <System
+ {...props}
+ options={applicationOptions}
+ state={applicationState}
+ theme={theme}
+ />,
+ )
+ }
+ />
+ <Redirect
+ from="*"
+ to={`${urlBase}/searches`}
/>
- <Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/>
- <Route path={`${urlBase}/uploads`} render={
- (props) =>
- this.withTokenCheck(<div className='view'><Transfers {...props} direction='upload'/></div>)
- }/>
- <Route path={`${urlBase}/downloads`} render={
- (props) =>
- this.withTokenCheck(<div className='view'>
- <Transfers {...props} direction='download' server={applicationState.server}/>
- </div>)
- }/>
- <Route path={`${urlBase}/system/:tab?`} render={
- (props) => this.withTokenCheck(
- <System {...props} theme={theme} state={applicationState} options={applicationOptions} />
- )
- }/>
- <Redirect from='*' to={`${urlBase}/searches`}/>
</Switch>
- }
+ )}
</AppContext.Provider>
</Sidebar.Pusher>
</Sidebar.Pushable>
<ToastContainer
- position="bottom-center"
- autoClose={5000}
+ autoClose={5_000}
+ closeOnClick
+ draggable={false}
hideProgressBar={false}
newestOnTop
- closeOnClick
- rtl={false}
pauseOnFocusLoss
- draggable={false}
pauseOnHover
+ position="bottom-center"
+ rtl={false}
/>
</>
);
- };
+ }
}
-export default App; \ No newline at end of file
+export default App;
diff --git a/src/web/src/components/AppContext.js b/src/web/src/components/AppContext.js
index 2095b2ab..e4dab109 100644
--- a/src/web/src/components/AppContext.js
+++ b/src/web/src/components/AppContext.js
@@ -2,4 +2,4 @@ import React from 'react';
const AppContext = React.createContext();
-export default AppContext; \ No newline at end of file
+export default AppContext;
diff --git a/src/web/src/components/Browse/Browse.jsx b/src/web/src/components/Browse/Browse.jsx
index e090851b..412dd7e2 100644
--- a/src/web/src/components/Browse/Browse.jsx
+++ b/src/web/src/components/Browse/Browse.jsx
@@ -1,86 +1,92 @@
-import React, { Component } from 'react';
-import * as lzString from 'lz-string';
-import * as users from '../../lib/users';
-
import './Browse.css';
-
-import DirectoryTree from './DirectoryTree';
-
-import {
- Segment,
- Input,
- Loader,
- Card,
- Icon,
-} from 'semantic-ui-react';
-
-import Directory from './Directory';
+import * as users from '../../lib/users';
import PlaceholderSegment from '../Shared/PlaceholderSegment';
+import Directory from './Directory';
+import DirectoryTree from './DirectoryTree';
+import * as lzString from 'lz-string';
+import React, { Component } from 'react';
+import { Card, Icon, Input, Loader, Segment } from 'semantic-ui-react';
-const initialState = {
- username: '',
- browseState: 'idle',
- browseStatus: 0,
+const initialState = {
browseError: undefined,
- interval: undefined,
- selectedDirectory: {},
- selectedFiles: [],
- tree: [],
- separator: '\\',
+ browseState: 'idle',
+ browseStatus: 0,
info: {
directories: 0,
files: 0,
lockedDirectories: 0,
lockedFiles: 0,
},
+ interval: undefined,
+ selectedDirectory: {},
+ selectedFiles: [],
+ separator: '\\',
+ tree: [],
+ username: '',
};
class Browse extends Component {
state = initialState;
browse = () => {
- let username = this.inputtext.inputRef.current.value;
-
- this.setState({ username , browseState: 'pending', browseError: undefined }, () => {
- users.browse({ username })
- .then(response => {
- let { directories, lockedDirectories } = response;
-
- // we need to know the directory separator. assume it is \ to start
- let separator = undefined;
-
- const directoryCount = directories.length;
- const fileCount = directories.reduce((acc, dir) => {
- // examine each directory as we process it to see if it contains \ or /, and set separator accordingly
- if (!separator) {
- if (dir.name.includes('\\')) separator = '\\';
- else if (dir.name.includes('/')) separator = '/';
- }
+ const username = this.inputtext.inputRef.current.value;
- return acc += dir.fileCount;
- }, 0);
-
- const lockedDirectoryCount = lockedDirectories.length;
- const lockedFileCount = lockedDirectories.reduce((acc, dir) => acc += dir.fileCount, 0);
-
- directories = directories.concat(lockedDirectories.map(d => ({ ...d, locked: true })));
-
- this.setState({
- tree: this.getDirectoryTree({ directories, separator }),
- separator,
- info: {
- directories: directoryCount,
- files: fileCount,
- lockedDirectories: lockedDirectoryCount,
- lockedFiles: lockedFileCount,
- },
- });
- })
- .then(() => this.setState({ browseState: 'complete', browseError: undefined }, () => {
- this.saveState();
- }))
- .catch(err => this.setState({ browseState: 'error', browseError: err }));
- });
+ this.setState(
+ { browseError: undefined, browseState: 'pending', username },
+ () => {
+ users
+ .browse({ username })
+ .then((response) => {
+ let { directories, lockedDirectories } = response;
+
+ // we need to know the directory separator. assume it is \ to start
+ let separator;
+
+ const directoryCount = directories.length;
+ const fileCount = directories.reduce((accumulator, dir) => {
+ // examine each directory as we process it to see if it contains \ or /, and set separator accordingly
+ if (!separator) {
+ if (dir.name.includes('\\')) separator = '\\';
+ else if (dir.name.includes('/')) separator = '/';
+ }
+
+ return (accumulator += dir.fileCount);
+ }, 0);
+
+ const lockedDirectoryCount = lockedDirectories.length;
+ const lockedFileCount = lockedDirectories.reduce(
+ (accumulator, dir) => (accumulator += dir.fileCount),
+ 0,
+ );
+
+ directories = directories.concat(
+ lockedDirectories.map((d) => ({ ...d, locked: true })),
+ );
+
+ this.setState({
+ info: {
+ directories: directoryCount,
+ files: fileCount,
+ lockedDirectories: lockedDirectoryCount,
+ lockedFiles: lockedFileCount,
+ },
+ separator,
+ tree: this.getDirectoryTree({ directories, separator }),
+ });
+ })
+ .then(() =>
+ this.setState(
+ { browseError: undefined, browseState: 'complete' },
+ () => {
+ this.saveState();
+ },
+ ),
+ )
+ .catch((error) =>
+ this.setState({ browseError: error, browseState: 'error' }),
+ );
+ },
+ );
};
clear = () => {
@@ -90,7 +96,7 @@ class Browse extends Component {
});
};
- keyUp = (event) => event.key === 'Escape' ? this.clear() : '';
+ keyUp = (event) => (event.key === 'Escape' ? this.clear() : '');
onUsernameChange = (event, data) => {
this.setState({ username: data.value });
@@ -98,15 +104,20 @@ class Browse extends Component {
saveState = () => {
this.inputtext.inputRef.current.value = this.state.username;
- this.inputtext.inputRef.current.disabled = this.state.browseState !== 'idle';
+ this.inputtext.inputRef.current.disabled =
+ this.state.browseState !== 'idle';
const storeToLocalStorage = () => {
try {
- localStorage.setItem('soulseek-example-browse-state', lzString.compress(JSON.stringify(this.state)));
+ 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) {
@@ -118,36 +129,45 @@ class Browse extends Component {
loadState = () => {
this.setState(
- JSON.parse(lzString.decompress(localStorage.getItem('soulseek-example-browse-state') || '')) || initialState);
+ JSON.parse(
+ lzString.decompress(
+ localStorage.getItem('soulseek-example-browse-state') || '',
+ ),
+ ) || initialState,
+ );
};
- componentDidMount = () => {
+ componentDidMount() {
this.fetchStatus();
this.loadState();
- this.setState({
- interval: window.setInterval(this.fetchStatus, 500),
- }, () => this.saveState());
-
+ this.setState(
+ {
+ interval: window.setInterval(this.fetchStatus, 500),
+ },
+ () => this.saveState(),
+ );
+
document.addEventListener('keyup', this.keyUp, false);
- };
-
- componentWillUnmount = () => {
+ }
+
+ componentWillUnmount() {
clearInterval(this.state.interval);
this.setState({ interval: undefined });
document.removeEventListener('keyup', this.keyUp, false);
- };
+ }
fetchStatus = () => {
const { browseState, username } = this.state;
if (browseState === 'pending') {
- users.getBrowseStatus({ username })
- .then(response => this.setState({
+ users.getBrowseStatus({ username }).then((response) =>
+ this.setState({
browseStatus: response.data,
- }));
+ }),
+ );
}
};
- getDirectoryTree = ({directories, separator}) => {
+ getDirectoryTree = ({ directories, separator }) => {
if (directories.length === 0 || directories[0].name === undefined) {
return [];
}
@@ -157,114 +177,176 @@ class Browse extends Component {
// - do the split once
// - future look ups are done from the Map
const depthMap = new Map();
- directories.forEach(d => {
+ for (const d of directories) {
const depth = d.name.split(separator).length;
if (!depthMap.has(depth)) {
depthMap.set(depth, []);
}
+
depthMap.get(depth).push(d);
- });
+ }
const depth = Math.min.apply(Math, Array.from(depthMap.keys()));
- return depthMap.get(depth).map(directory => this.getChildDirectories(depthMap, directory, separator, depth + 1));
+ return depthMap
+ .get(depth)
+ .map((directory) =>
+ this.getChildDirectories(depthMap, directory, separator, depth + 1),
+ );
};
getChildDirectories = (depthMap, root, separator, depth) => {
if (!depthMap.has(depth)) {
- return { ...root, children: []};
+ return { ...root, children: [] };
}
- const children = depthMap.get(depth).filter(d => d.name.startsWith(root.name));
- return { ...root, children: children.map(c => this.getChildDirectories(depthMap, c, separator, depth + 1)) };
+ const children = depthMap
+ .get(depth)
+ .filter((d) => d.name.startsWith(root.name));
+
+ return {
+ ...root,
+ children: children.map((c) =>
+ this.getChildDirectories(depthMap, c, separator, depth + 1),
+ ),
+ };
};
selectDirectory = (directory) => {
- this.setState({ selectedDirectory: { ...directory, children: [] }}, () => this.saveState());
+ this.setState({ selectedDirectory: { ...directory, children: [] } }, () =>
+ this.saveState(),
+ );
};
deselectDirectory = () => {
- this.setState({ selectedDirectory: initialState.selectedDirectory }, () => this.saveState());
+ this.setState({ selectedDirectory: initialState.selectedDirectory }, () =>
+ this.saveState(),
+ );
};
- render = () => {
- const { browseState, browseStatus, browseError, tree, separator, selectedDirectory, username, info } = this.state;
- const { name, locked } = selectedDirectory;
+ render() {
+ const {
+ browseError,
+ browseState,
+ browseStatus,
+ info,
+ selectedDirectory,
+ separator,
+ tree,
+ username,
+ } = this.state;
+ const { locked, name } = selectedDirectory;
const pending = browseState === 'pending';
const emptyTree = !(tree && tree.length > 0);
- const files = (selectedDirectory.files || [])
- .map(f => ({ ...f, filename: `${name}${separator}${f.filename}` }));
+ const files = (selectedDirectory.files || []).map((f) => ({
+ ...f,
+ filename: `${name}${separator}${f.filename}`,
+ }));
return (
- <div className='search-container'>
- <Segment className='browse-segment' raised>
- <div className="browse-segment-icon"><Icon name="folder open" size="big"/></div>
+ <div className="search-container">
+ <Segment
+ className="browse-segment"
+ raised
+ >
+ <div className="browse-segment-icon">
+ <Icon
+ name="folder open"
+ size="big"
+ />
+ </div>
<Input
- input={<input placeholder="Username" type="search" data-lpignore="true"></input>}
- size='big'
- ref={input => this.inputtext = input}
- loading={pending}
+ action={
+ !pending &&
+ (browseState === 'idle'
+ ? { icon: 'search', onClick: this.browse }
+ : { color: 'red', icon: 'x', onClick: this.clear })
+ }
+ className="search-input"
disabled={pending}
- className='search-input'
+ input={
+ <input
+ data-lpignore="true"
+ placeholder="Username"
+ type="search"
+ />
+ }
+ loading={pending}
+ onKeyUp={(e) => (e.key === 'Enter' ? this.browse() : '')}
placeholder="Username"
- action={!pending && (browseState === 'idle'
- ? { icon: 'search', onClick: this.browse }
- : { icon: 'x', color: 'red', onClick: this.clear })}
- onKeyUp={(e) => e.key === 'Enter' ? this.browse() : ''}
+ ref={(input) => (this.inputtext = input)}
+ size="big"
/>
</Segment>
- {pending ?
- <Loader
- className='search-loader'
- active
- inline='centered'
- size='big'
+ {pending ? (
+ <Loader
+ active
+ className="search-loader"
+ inline="centered"
+ size="big"
>
- Downloaded {Math.round(browseStatus.percentComplete || 0)}% of Response
+ Downloaded {Math.round(browseStatus.percentComplete || 0)}% of
+ Response
</Loader>
- :
+ ) : (
<div>
- {browseError ?
- <span className='browse-error'>Failed to browse {username}</span> :
- <div className='browse-container'>
- {emptyTree ?
- <PlaceholderSegment icon='folder open' caption='No user share to display'/> :
- <Card className='browse-tree-card' raised>
+ {browseError ? (
+ <span className="browse-error">Failed to browse {username}</span>
+ ) : (
+ <div className="browse-container">
+ {emptyTree ? (
+ <PlaceholderSegment
+ caption="No user share to display"
+ icon="folder open"
+ />
+ ) : (
+ <Card
+ className="browse-tree-card"
+ raised
+ >
<Card.Content>
<Card.Header>
- <Icon name='circle' color='green'/>
+ <Icon
+ color="green"
+ name="circle"
+ />
{username}
</Card.Header>
- <Card.Meta className='browse-meta'>
+ <Card.Meta className="browse-meta">
<span>
- {`${info.files + info.lockedFiles} files in ${info.directories + info.lockedDirectories} directories (including ${info.lockedFiles} files in ${info.lockedDirectories} locked directories)`} {/* eslint-disable-line max-len */}
+ {`${info.files + info.lockedFiles} files in ${info.directories + info.lockedDirectories} directories (including ${info.lockedFiles} files in ${info.lockedDirectories} locked directories)`}{' '}
+ {/* eslint-disable-line max-len */}
</span>
</Card.Meta>
- <Segment className='browse-folderlist'>
- <DirectoryTree
- tree={tree}
- selectedDirectoryName={name}
+ <Segment className="browse-folderlist">
+ <DirectoryTree
onSelect={(_, value) => this.selectDirectory(value)}
+ selectedDirectoryName={name}
+ tree={tree}
/>
</Segment>
</Card.Content>
- </Card>}
- {name && <Directory
- marginTop={-20}
- name={name}
- locked={locked}
- files={files}
- username={username}
- onClose={this.deselectDirectory}
- />}
+ </Card>
+ )}
+ {name && (
+ <Directory
+ files={files}
+ locked={locked}
+ marginTop={-20}
+ name={name}
+ onClose={this.deselectDirectory}
+ username={username}
+ />
+ )}
</div>
- }
- </div>}
+ )}
+ </div>
+ )}
</div>
);
- };
+ }
}
export default Browse;
diff --git a/src/web/src/components/Browse/Directory.jsx b/src/web/src/components/Browse/Directory.jsx
index ed179e87..891db608 100644
--- a/src/web/src/components/Browse/Directory.jsx
+++ b/src/web/src/components/Browse/Directory.jsx
@@ -1,101 +1,132 @@
-import React, { Component } from 'react';
import * as transfers from '../../lib/transfers';
-
import { formatBytes } from '../../lib/util';
-
import FileList from '../Shared/FileList';
-
-import {
- Button,
- Card,
- Icon,
- Label,
-} from 'semantic-ui-react';
+import React, { Component } from 'react';
+import { Button, Card, Icon, Label } from 'semantic-ui-react';
const initialState = {
- downloadRequest: undefined,
downloadError: '',
+ downloadRequest: undefined,
};
class Directory extends Component {
- state = {
+ state = {
...initialState,
- files: this.props.files.map(f => ({ selected: false, ...f })),
+ files: this.props.files.map((f) => ({ selected: false, ...f })),
};
onFileSelectionChange = (file, state) => {
file.selected = state;
- this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' });
+ this.setState({
+ downloadError: '',
+ downloadRequest: undefined,
+ tree: this.state.tree,
+ });
};
download = (username, files) => {
this.setState({ downloadRequest: 'inProgress' }, async () => {
try {
- const requests = (files || []).map(({ filename, size }) => ({ filename, size }));
- await transfers.download({ username, files: requests });
+ const requests = (files || []).map(({ filename, size }) => ({
+ filename,
+ size,
+ }));
+ await transfers.download({ files: requests, username });
this.setState({ downloadRequest: 'complete' });
- } catch (err) {
- this.setState({ downloadRequest: 'error', downloadError: err.response });
+ } catch (error) {
+ this.setState({
+ downloadError: error.response,
+ downloadRequest: 'error',
+ });
}
});
};
- componentDidUpdate = (prevProps) => {
- if (this.props.name !== prevProps.name) {
- this.setState({ 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 })),
+ });
}
- };
+ }
- render = () => {
- let { username, name, locked, marginTop, onClose } = this.props;
- let { files, downloadRequest, downloadError } = this.state;
+ render() {
+ const { locked, marginTop, name, onClose, username } = this.props;
+ const { downloadError, downloadRequest, files } = this.state;
- let selectedFiles = files
- .filter(f => f.selected);
+ const selectedFiles = files.filter((f) => f.selected);
- let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0));
+ const selectedSize = formatBytes(
+ selectedFiles.reduce((total, f) => total + f.size, 0),
+ );
return (
- <Card className='result-card' raised>
+ <Card
+ className="result-card"
+ raised
+ >
<Card.Content>
- <div style={{marginTop: marginTop || 0}}>
- <FileList
+ <div style={{ marginTop: marginTop || 0 }}>
+ <FileList
directoryName={name}
- locked={locked}
- files={files}
disabled={downloadRequest === 'inProgress'}
- onSelectionChange={this.onFileSelectionChange}
+ files={files}
+ locked={locked}
onClose={onClose}
+ onSelectionChange={this.onFileSelectionChange}
/>
</div>
</Card.Content>
- {selectedFiles.length > 0 && <Card.Content extra>
- <span>
- <Button
- color='green'
- content='Download'
- icon='download'
- label={{
- as: 'a',
- basic: false,
- content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${selectedSize}`,
- }}
- labelPosition='right'
- onClick={() => this.download(username, selectedFiles)}
- disabled={downloadRequest === 'inProgress'}
- />
- {downloadRequest === 'inProgress' && <Icon loading name='circle notch' size='large'/>}
- {downloadRequest === 'complete' && <Icon name='checkmark' color='green' size='large'/>}
- {downloadRequest === 'error' && <span>
- <Icon name='x' color='red' size='large'/>
- <Label>{downloadError.data + ` (HTTP ${downloadError.status} ${downloadError.statusText})`}</Label>
- </span>}
- </span>
- </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/DirectoryTree.jsx b/src/web/src/components/Browse/DirectoryTree.jsx
index 4cd10d1e..af90ad5a 100644
--- a/src/web/src/components/Browse/DirectoryTree.jsx
+++ b/src/web/src/components/Browse/DirectoryTree.jsx
@@ -1,8 +1,5 @@
import React from 'react';
-
-import {
- List,
-} from 'semantic-ui-react';
+import { List } from 'semantic-ui-react';
const subtree = (root, selectedDirectoryName, onSelect) => {
return (root || []).map((d, index) => {
@@ -10,15 +7,28 @@ const subtree = (root, selectedDirectoryName, onSelect) => {
// const dimIfLocked = { opacity: d.locked ? 0.5 : 1 };
return (
- <List key={index} className='browse-folderlist-list'>
+ <List
+ className="browse-folderlist-list"
+ key={index}
+ >
<List.Item>
- <List.Icon
- className={'browse-folderlist-icon' + (selected ? ' selected' : '') + (d.locked ? ' locked' : '')}
- name={d.locked === true ? 'lock' : selected ? 'folder open' : 'folder'}
+ <List.Icon
+ className={
+ 'browse-folderlist-icon' +
+ (selected ? ' selected' : '') +
+ (d.locked ? ' locked' : '')
+ }
+ name={
+ d.locked === true ? 'lock' : selected ? 'folder open' : 'folder'
+ }
/>
<List.Content>
- <List.Header
- className={'browse-folderlist-header' + (selected ? ' selected' : '') + (d.locked ? ' locked' : '')}
+ <List.Header
+ className={
+ 'browse-folderlist-header' +
+ (selected ? ' selected' : '') +
+ (d.locked ? ' locked' : '')
+ }
onClick={(event) => onSelect(event, d)}
>
{d.name.split('\\').pop().split('/').pop()}
@@ -28,10 +38,12 @@ const subtree = (root, selectedDirectoryName, onSelect) => {
</List.List>
</List.Content>
</List.Item>
- </List>);
+ </List>
+ );
});
};
-const DirectoryTree = ({ tree, selectedDirectoryName, onSelect }) => subtree(tree, selectedDirectoryName, onSelect);
+const DirectoryTree = ({ onSelect, selectedDirectoryName, tree }) =>
+ subtree(tree, selectedDirectoryName, onSelect);
-export default DirectoryTree; \ No newline at end of file
+export default DirectoryTree;
diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx
index e9ff0be9..b071ed55 100644
--- a/src/web/src/components/Chat/Chat.jsx
+++ b/src/web/src/components/Chat/Chat.jsx
@@ -1,15 +1,20 @@
-import React, { Component, createRef } from 'react';
+import './Chat.css';
import { activeChatKey } from '../../config';
import * as chat from '../../lib/chat';
-import './Chat.css';
+import PlaceholderSegment from '../Shared/PlaceholderSegment';
+import ChatMenu from './ChatMenu';
+import React, { Component, createRef } from 'react';
import {
+ Card,
+ Dimmer,
+ Icon,
+ Input,
+ List,
+ Loader,
+ Ref,
Segment,
- List, Input, Card, Icon, Ref, Dimmer, Loader,
} from 'semantic-ui-react';
-import ChatMenu from './ChatMenu';
-import PlaceholderSegment from '../Shared/PlaceholderSegment';
-
const initialState = {
active: '',
conversations: {},
@@ -19,33 +24,40 @@ const initialState = {
class Chat extends Component {
state = initialState;
+
messageRef = undefined;
+
listRef = createRef();
- componentDidMount = async () => {
- this.setState({
- interval: window.setInterval(this.fetchConversations, 5000),
- active: sessionStorage.getItem(activeChatKey) || '',
- }, async () => {
- await this.fetchConversations();
- this.selectConversation(this.state.active || this.getFirstConversation());
- });
- };
+ componentDidMount() {
+ this.setState(
+ {
+ active: sessionStorage.getItem(activeChatKey) || '',
+ interval: window.setInterval(this.fetchConversations, 5_000),
+ },
+ async () => {
+ await this.fetchConversations();
+ this.selectConversation(
+ this.state.active || this.getFirstConversation(),
+ );
+ },
+ );
+ }
- componentWillUnmount = () => {
+ componentWillUnmount() {
clearInterval(this.state.interval);
this.setState({ interval: undefined });
- };
+ }
getFirstConversation = () => {
- const names = [...Object.keys(this.state.conversations)];
+ const names = Object.keys(this.state.conversations);
return names.length > 0 ? names[0] : '';
};
fetchConversations = async () => {
// fetch all of the active conversations (but no messages)
let conversations = await chat.getAll();
-
+
// turn into a map, keyed by username
// if there are no active conversations, set to an empty map
if (conversations.length === 0) {
@@ -56,7 +68,7 @@ class Chat extends Component {
return map;
}, {});
}
-
+
const { active } = this.state;
const activeConversation = conversations[active];
@@ -65,11 +77,11 @@ class Chat extends Component {
if (activeConversation) {
console.log('active?', activeConversation);
// *before* fetching messages, ack any unacked messages
- // for the active chat
+ // for the active chat
if (activeConversation.hasUnAcknowledgedMessages === true) {
await this.acknowledgeMessages(active);
}
-
+
conversations = {
...conversations,
[active]: await chat.get({ username: active }),
@@ -92,7 +104,7 @@ class Chat extends Component {
sendMessage = async (username, message) => {
if (!username || !message || username === '') return;
- await chat.send({ username, message });
+ await chat.send({ message, username });
};
sendReply = async () => {
@@ -112,8 +124,13 @@ class Chat extends Component {
};
validInput = () =>
- (this.state.active || '').length > 0
- && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0;
+ (this.state.active || '').length > 0 &&
+ (
+ (this.messageRef &&
+ this.messageRef.current &&
+ this.messageRef.current.value) ||
+ ''
+ ).length > 0;
focusInput = () => {
this.messageRef.current.focus();
@@ -121,41 +138,50 @@ class Chat extends Component {
formatTimestamp = (timestamp) => {
const date = new Date(timestamp);
- const dtfUS = new Intl.DateTimeFormat('en', {
- month: 'numeric',
+ const dtfUS = new Intl.DateTimeFormat('en', {
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
+ month: 'numeric',
});
return dtfUS.format(date);
};
selectConversation = (username) => {
- this.setState({
- active: username,
- loading: true,
- }, async () => {
- const { active, conversations } = this.state;
-
- sessionStorage.setItem(activeChatKey, active);
-
- this.setState({
- loading: false,
- conversations: active === '' ? conversations : {
- ...conversations,
- [active]: await chat.get({ username: active }),
- },
- }, () => {
- try {
- this.listRef.current.lastChild.scrollIntoView();
- } catch {
- // no-op
- }
- });
- });
+ this.setState(
+ {
+ active: username,
+ loading: true,
+ },
+ async () => {
+ const { active, conversations } = this.state;
+
+ sessionStorage.setItem(activeChatKey, active);
+
+ this.setState(
+ {
+ conversations:
+ active === ''
+ ? conversations
+ : {
+ ...conversations,
+ [active]: await chat.get({ username: active }),
+ },
+ loading: false,
+ },
+ () => {
+ try {
+ this.listRef.current.lastChild.scrollIntoView();
+ } catch {
+ // no-op
+ }
+ },
+ );
+ },
+ );
};
-
+
initiateConversation = async (username, message) => {
await this.sendMessage(username, message);
await this.fetchConversations();
@@ -168,80 +194,131 @@ class Chat extends Component {
this.selectConversation(this.getFirstConversation());
};
- render = () => {
- const { conversations = [], active, loading } = this.state;
+ render() {
+ const { active, conversations = [], loading } = this.state;
const messages = conversations[active]?.messages || [];
const { user } = this.props.state;
return (
- <div className='chats'>
- <Segment className='chat-segment' raised>
- <div className="chat-segment-icon"><Icon name="comment" size="big"/></div>
+ <div className="chats">
+ <Segment
+ className="chat-segment"
+ raised
+ >
+ <div className="chat-segment-icon">
+ <Icon
+ name="comment"
+ size="big"
+ />
+ </div>
<ChatMenu
- conversations={conversations}
active={active}
- onConversationChange={(name) => this.selectConversation(name)}
+ conversations={conversations}
initiateConversation={this.initiateConversation}
+ onConversationChange={(name) => this.selectConversation(name)}
/>
</Segment>
- {!active ?
- <PlaceholderSegment icon='comment' caption='No chats to display'/> :
- <Card className='chat-active-card' raised>
+ {!active ? (
+ <PlaceholderSegment
+ caption="No chats to display"
+ icon="comment"
+ />
+ ) : (
+ <Card
+ className="chat-active-card"
+ raised
+ >
<Card.Content onClick={() => this.focusInput()}>
<Card.Header>
- <Icon name='circle' color='green'/>
+ <Icon
+ color="green"
+ name="circle"
+ />
{active}
- <Icon
- className='close-button'
- name='close'
- color='red'
+ <Icon
+ className="close-button"
+ color="red"
link
+ name="close"
onClick={() => this.deleteConversation(active)}
/>
</Card.Header>
- <div className='chat'>
- {loading ? <Dimmer active inverted><Loader inverted/></Dimmer> :
+ <div className="chat">
+ {loading ? (
+ <Dimmer
+ active
+ inverted
+ >
+ <Loader inverted />
+ </Dimmer>
+ ) : (
<Segment.Group>
- <Segment className='chat-history'>
+ <Segment className="chat-history">
<Ref innerRef={this.listRef}>
<List>
- {messages.map((message, index) =>
- <List.Content
- key={index}
+ {messages.map((message, index) => (
+ <List.Content
className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`}
+ key={index}
>
- <span className='chat-message-time'>{this.formatTimestamp(message.timestamp)}</span>
- <span className='chat-message-name'>
- {message.direction === 'Out' ? user.username : message.username}: </span>
- <span className='chat-message-message'>{message.message}</span>
+ <span className="chat-message-time">
+ {this.formatTimestamp(message.timestamp)}
+ </span>
+ <span className="chat-message-name">
+ {message.direction === 'Out'
+ ? user.username
+ : message.username}
+ :{' '}
+ </span>
+ <span className="chat-message-message">
+ {message.message}
+ </span>
</List.Content>
- )}
- <List.Content id='chat-history-scroll-anchor'/>
+ ))}
+ <List.Content id="chat-history-scroll-anchor" />
</List>
</Ref>
</Segment>
- <Segment className='chat-input'>
+ <Segment className="chat-input">
<Input
- fluid
- transparent
- input={
- <input id='chat-message-input' type="text" data-lpignore="true" autoComplete="off"></input>}
- ref={input => this.messageRef = input && input.inputRef}
- action={{
- icon: <Icon name='send' color='green'/>,
- className: 'chat-message-button', onClick: this.sendMessage,
+ action={{
+ className: 'chat-message-button',
disabled: !this.validInput(),
+ icon: (
+ <Icon
+ color="green"
+ name="send"
+ />
+ ),
+ onClick: this.sendMessage,
}}
- onKeyUp={(e) => e.key === 'Enter' ? this.sendReply() : ''}
+ fluid
+ input={
+ <input
+ autoComplete="off"
+ data-lpignore="true"
+ id="chat-message-input"
+ type="text"
+ />
+ }
+ onKeyUp={(e) =>
+ e.key === 'Enter' ? this.sendReply() : ''
+ }
+ ref={(input) =>
+ (this.messageRef = input && input.inputRef)
+ }
+ transparent
/>
</Segment>
- </Segment.Group>}
+ </Segment.Group>
+ )}
</div>
</Card.Content>
- </Card>}
+ </Card>
+ )}
</div>
);
- };
+ }
}
-export default Chat; \ No newline at end of file
+export default Chat;
diff --git a/src/web/src/components/Chat/ChatMenu.jsx b/src/web/src/components/Chat/ChatMenu.jsx
index 3dd91763..8317605c 100644
--- a/src/web/src/components/Chat/ChatMenu.jsx
+++ b/src/web/src/components/Chat/ChatMenu.jsx
@@ -1,39 +1,53 @@
-import React from 'react';
import './Chat.css';
-
-import {
- Icon, Button, Label, Menu,
-} from 'semantic-ui-react';
import SendMessageModal from './SendMessageModal';
+import React from 'react';
+import { Button, Icon, Label, Menu } from 'semantic-ui-react';
-const ChatMenu = ({ conversations, active, onConversationChange, ...rest }) => {
+const ChatMenu = ({ active, conversations, onConversationChange, ...rest }) => {
const names = Object.keys(conversations);
const isActive = (name) => active === name;
return (
- <Menu className='conversation-menu' size='large'>
- {names.map((name, index) =>
+ <Menu
+ className="conversation-menu"
+ size="large"
+ >
+ {names.map((name, index) => (
<Menu.Item
+ active={isActive(name)}
className={`menu-item ${isActive(name) ? 'menu-active' : ''}`}
key={index}
name={name}
- active={isActive(name)}
onClick={() => onConversationChange(name)}
>
- <Icon name='circle' size='tiny' color='green'/>
+ <Icon
+ color="green"
+ name="circle"
+ size="tiny"
+ />
{name}
- {conversations[name].hasUnAcknowledgedMessages &&
- <Label size='tiny' color='red'>{conversations[name].unAcknowledgedMessageCount}</Label>
- }
+ {conversations[name].hasUnAcknowledgedMessages && (
+ <Label
+ color="red"
+ size="tiny"
+ >
+ {conversations[name].unAcknowledgedMessageCount}
+ </Label>
+ )}
</Menu.Item>
- )}
- <Menu.Menu position='right'>
+ ))}
+ <Menu.Menu position="right">
<SendMessageModal
+ centered
+ size="small"
trigger={
- <Button icon className='add-button'><Icon name='plus'/></Button>
+ <Button
+ className="add-button"
+ icon
+ >
+ <Icon name="plus" />
+ </Button>
}
- centered
- size='small'
{...rest}
/>
</Menu.Menu>
@@ -41,4 +55,4 @@ const ChatMenu = ({ conversations, active, onConversationChange, ...rest }) => {
);
};
-export default ChatMenu; \ No newline at end of file
+export default ChatMenu;
diff --git a/src/web/src/components/Chat/SendMessageModal.jsx b/src/web/src/components/Chat/SendMessageModal.jsx
index 45b85d23..8effb05e 100644
--- a/src/web/src/components/Chat/SendMessageModal.jsx
+++ b/src/web/src/components/Chat/SendMessageModal.jsx
@@ -1,9 +1,6 @@
-import React, { useEffect } from 'react';
import './Chat.css';
-
-import {
- Icon, Button, Modal, Form, Header, Input,
-} from 'semantic-ui-react';
+import React, { useEffect } from 'react';
+import { Button, Form, Header, Icon, Input, Modal } from 'semantic-ui-react';
const usernameRef = React.createRef();
@@ -34,42 +31,44 @@ const SendMessageModal = ({ initiateConversation, ...rest }) => {
return (
<Modal
- open={open}
onClose={() => setOpen(false)}
onOpen={() => setOpen(true)}
+ open={open}
{...rest}
>
<Header>
- <Icon name='send'/>
+ <Icon name="send" />
<Modal.Content>Send Private Message</Modal.Content>
</Header>
<Modal.Content>
<Form>
<Form.Field>
<Input
- ref={usernameRef}
- placeholder='Username'
onChange={(e, data) => setUsername(data.value)}
+ placeholder="Username"
+ ref={usernameRef}
/>
</Form.Field>
<Form.Field>
<Input
- placeholder='Message'
onChange={(e, data) => setMessage(data.value)}
+ placeholder="Message"
/>
</Form.Field>
</Form>
</Modal.Content>
<Modal.Actions>
<Button onClick={() => setOpen(false)}>Cancel</Button>
- <Button
- positive
- onClick={() => sendMessage()}
+ <Button
disabled={!validInput()}
- >Send</Button>
+ onClick={() => sendMessage()}
+ positive
+ >
+ Send
+ </Button>
</Modal.Actions>
</Modal>
);
};
-export default SendMessageModal; \ No newline at end of file
+export default SendMessageModal;
diff --git a/src/web/src/components/LoginForm.jsx b/src/web/src/components/LoginForm.jsx
index faa0fc93..978e1417 100644
--- a/src/web/src/components/LoginForm.jsx
+++ b/src/web/src/components/LoginForm.jsx
@@ -1,19 +1,31 @@
-import React, { useState, useEffect, useMemo, useRef } from 'react';
-import { Button, Form, Input, Grid, Header, Icon, Segment, Checkbox, Message } from 'semantic-ui-react';
-
import Logos from './Shared/Logo';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
+import {
+ Button,
+ Checkbox,
+ Form,
+ Grid,
+ Header,
+ Icon,
+ Input,
+ Message,
+ Segment,
+} from 'semantic-ui-react';
const initialState = {
- username: '',
password: '',
rememberMe: true,
+ username: '',
};
-const LoginForm = ({ onLoginAttempt, loading, error }) => {
+const LoginForm = ({ error, loading, onLoginAttempt }) => {
const usernameInput = useRef();
const [state, setState] = useState(initialState);
const [ready, setReady] = useState(false);
- const logo = useMemo(() => Logos[Math.floor(Math.random() * Logos.length)], []);
+ const logo = useMemo(
+ () => Logos[Math.floor(Math.random() * Logos.length)],
+ [],
+ );
useEffect(() => {
if (state.username !== '' && state.password !== '') {
@@ -34,68 +46,81 @@ const LoginForm = ({ onLoginAttempt, loading, error }) => {
});
};
- const { username, password, rememberMe } = state;
+ const { password, rememberMe, username } = state;
return (
- <>
- <Grid textAlign='center' style={{ height: '100vh' }} verticalAlign='middle'>
- <Grid.Column style={{ maxWidth: 372 }}>
- <Header as='h2' textAlign='center' style={{
- whiteSpace: 'pre',
+ <Grid
+ style={{ height: '100vh' }}
+ textAlign="center"
+ verticalAlign="middle"
+ >
+ <Grid.Column style={{ maxWidth: 372 }}>
+ <Header
+ as="h2"
+ style={{
fontFamily: 'monospace',
- lineHeight: 1.1,
fontSize: 'inherit',
letterSpacing: -1,
- }}>
- {logo}
- </Header>
- <Form size='large'>
- <Segment raised>
- <Input
- fluid icon='user'
- iconPosition='left'
- placeholder='Username'
- onChange={(event) => handleChange('username', event.target.value)}
- disabled={loading}
- ref={usernameInput}
- />
- <Form.Input
- fluid
- icon='lock'
- iconPosition='left'
- placeholder='Password'
- type='password'
- onChange={(event) => handleChange('password', event.target.value)}
- disabled={loading}
- />
- <Checkbox
- label='Remember Me'
- onChange={() => handleChange('rememberMe', !rememberMe)}
- checked={rememberMe}
- disabled={loading}
- />
- </Segment>
- <Button
- primary
- fluid
- size='large'
- className='login-button'
- loading={loading}
- disabled={!ready || loading}
- onClick={() => onLoginAttempt(username, password, rememberMe)}
+ lineHeight: 1.1,
+ whiteSpace: 'pre',
+ }}
+ textAlign="center"
+ >
+ {logo}
+ </Header>
+ <Form size="large">
+ <Segment raised>
+ <Input
+ disabled={loading}
+ fluid
+ icon="user"
+ iconPosition="left"
+ onChange={(event) => handleChange('username', event.target.value)}
+ placeholder="Username"
+ ref={usernameInput}
+ />
+ <Form.Input
+ disabled={loading}
+ fluid
+ icon="lock"
+ iconPosition="left"
+ onChange={(event) => handleChange('password', event.target.value)}
+ placeholder="Password"
+ type="password"
+ />
+ <Checkbox
+ checked={rememberMe}
+ disabled={loading}
+ label="Remember Me"
+ onChange={() => handleChange('rememberMe', !rememberMe)}
+ />
+ </Segment>
+ <Button
+ className="login-button"
+ disabled={!ready || loading}
+ fluid
+ loading={loading}
+ onClick={() => onLoginAttempt(username, password, rememberMe)}
+ primary
+ size="large"
+ >
+ <Icon name="sign in" />
+ Login
+ </Button>
+ {error && (
+ <Message
+ className="login-failure"
+ floating
+ negative
>
- <Icon name='sign in'/>
- Login
- </Button>
- {error && <Message className='login-failure' negative floating>
- <Icon name='x' />
+ <Icon name="x" />
{error.message}
- </Message>}
- </Form>
- </Grid.Column>
- </Grid>
- </>
+ </Message>
+ )}
+ </Form>
+ </Grid.Column>
+ </Grid>
);
};
-export default LoginForm; \ No newline at end of file
+export default LoginForm;
diff --git a/src/web/src/components/Rooms/RoomJoinModal.jsx b/src/web/src/components/Rooms/RoomJoinModal.jsx
index f1c8aad4..34e3dd78 100644
--- a/src/web/src/components/Rooms/RoomJoinModal.jsx
+++ b/src/web/src/components/Rooms/RoomJoinModal.jsx
@@ -1,9 +1,15 @@
-import React, { useEffect, useState, useMemo } from 'react';
-import * as rooms from '../../lib/rooms';
import './Rooms.css';
-
+import * as rooms from '../../lib/rooms';
+import React, { useEffect, useMemo, useState } from 'react';
import {
- Icon, Button, Modal, Table, Header, Input, Loader, Dimmer,
+ Button,
+ Dimmer,
+ Header,
+ Icon,
+ Input,
+ Loader,
+ Modal,
+ Table,
} from 'semantic-ui-react';
const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => {
@@ -27,26 +33,26 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => {
}, [open]);
const sortedAvailable = useMemo(() => {
- const sorted = [...available].filter(room => room.name.includes(filter));
+ const sorted = [...available].filter((room) => room.name.includes(filter));
sorted.sort((a, b) => {
if (sortOrder === 'asc') {
- if (typeof(a[sortBy]) === 'string') {
+ if (typeof a[sortBy] === 'string') {
return b[sortBy].localeCompare(a[sortBy]);
}
return a[sortBy] - b[sortBy];
}
- if (typeof(a[sortBy]) === 'string') {
+ if (typeof a[sortBy] === 'string') {
return a[sortBy].localeCompare(b[sortBy]);
}
return b[sortBy] - a[sortBy];
});
-
+
return sorted;
- }, [available, sortBy, sortOrder, filter]);
+ }, [available, filter, sortBy, sortOrder]);
const joinRoom = async () => {
await parentJoinRoom(selected);
@@ -66,77 +72,108 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => {
return (
<Modal
- className='join-room-modal'
- open={open}
+ className="join-room-modal"
onClose={() => close()}
onOpen={() => setOpen(true)}
+ open={open}
{...modalOptions}
>
<Header>
- <Icon name='comments'/>
+ <Icon name="comments" />
<Modal.Content>Join Room</Modal.Content>
</Header>
<Modal.Content scrolling>
- {loading ? <Dimmer active inverted><Loader inverted content='Loading Room List' /></Dimmer> :
+ {loading ? (
+ <Dimmer
+ active
+ inverted
+ >
+ <Loader
+ content="Loading Room List"
+ inverted
+ />
+ </Dimmer>
+ ) : (
<>
- <Input
- fluid
+ <Input
+ fluid
+ icon="filter"
onChange={(_, e) => setFilter(e.value)}
- placeholder='Room Filter'
- icon='filter'
+ placeholder="Room Filter"
/>
- <Table celled selectable>
+ <Table
+ celled
+ selectable
+ >
<Table.Header>
<Table.Row>
<Table.HeaderCell onClick={() => setSortBy('name')}>
- Name
- <Icon
+ Name
+ <Icon
link={sortBy === 'name'}
- name={sortBy === 'name' && (sortOrder === 'asc' ? 'chevron up' : 'chevron down')}
- onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
+ name={
+ sortBy === 'name' &&
+ (sortOrder === 'asc' ? 'chevron up' : 'chevron down')
+ }
+ onClick={() =>
+ setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
+ }
/>
</Table.HeaderCell>
<Table.HeaderCell onClick={() => setSortBy('userCount')}>
- Users
- <Icon
+ Users
+ <Icon
link={sortBy === 'userCount'}
- name={sortBy === 'userCount' && (sortOrder === 'asc' ? 'chevron up' : 'chevron down')}
- onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
+ name={
+ sortBy === 'userCount' &&
+ (sortOrder === 'asc' ? 'chevron up' : 'chevron down')
+ }
+ onClick={() =>
+ setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
+ }
/>
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
- {sortedAvailable.map((room, index) =>
+ {sortedAvailable.map((room, index) => (
<Table.Row
key={index}
- style={isSelected(room) ? {fontWeight: 'bold'} : {}}
onClick={() => setSelected(room.name)}
+ style={isSelected(room) ? { fontWeight: 'bold' } : {}}
>
<Table.Cell>
- {isSelected(room) && <Icon name='check' color='green'/>}
- {room.isPrivate && <Icon name='lock'/>}
- {room.isOwned && <Icon name='chess queen'/>}
- {room.isModerated && <Icon name='gavel'/>}
+ {isSelected(room) && (
+ <Icon
+ color="green"
+ name="check"
+ />
+ )}
+ {room.isPrivate && <Icon name="lock" />}
+ {room.isOwned && <Icon name="chess queen" />}
+ {room.isModerated && <Icon name="gavel" />}
{room.name}
</Table.Cell>
<Table.Cell>{room.userCount}</Table.Cell>
</Table.Row>
- )}
+ ))}
</Table.Body>
</Table>
- </>}
+ </>
+ )}
</Modal.Content>
<Modal.Actions>
<Button onClick={() => setOpen(false)}>Cancel</Button>
- <Button
- positive
- onClick={() => joinRoom()}
+ <Button
disabled={!selected}
- >Join</Button>
+ onClick={() => joinRoom()}
+ positive
+ >
+ Join
+ </Button>
</Modal.Actions>
</Modal>
);
};
-export default RoomJoinModal; \ No newline at end of file
+export default RoomJoinModal;
diff --git a/src/web/src/components/Rooms/RoomMenu.jsx b/src/web/src/components/Rooms/RoomMenu.jsx
index b785c66c..d76afdaa 100644
--- a/src/web/src/components/Rooms/RoomMenu.jsx
+++ b/src/web/src/components/Rooms/RoomMenu.jsx
@@ -1,36 +1,45 @@
-import React from 'react';
import './Rooms.css';
-
-import {
- Icon, Button, Menu,
-} from 'semantic-ui-react';
import RoomJoinModal from './RoomJoinModal';
+import React from 'react';
+import { Button, Icon, Menu } from 'semantic-ui-react';
-const RoomMenu = ({ joined, active, onRoomChange, ...rest }) => {
+const RoomMenu = ({ active, joined, onRoomChange, ...rest }) => {
const names = [...joined];
const isActive = (name) => active === name;
return (
- <Menu className='room-menu' size='large'>
- {names.map((name, index) =>
+ <Menu
+ className="room-menu"
+ size="large"
+ >
+ {names.map((name, index) => (
<Menu.Item
+ active={isActive(name)}
className={`menu-item ${isActive(name) ? 'menu-active' : ''}`}
key={index}
name={name}
- active={isActive(name)}
onClick={() => onRoomChange(name)}
>
- <Icon name='circle' size='tiny' color='green'/>
+ <Icon
+ color="green"
+ name="circle"
+ size="tiny"
+ />
{name}
</Menu.Item>
- )}
- <Menu.Menu position='right'>
+ ))}
+ <Menu.Menu position="right">
<RoomJoinModal
+ centered
+ size="small"
trigger={
- <Button icon className='add-button'><Icon name='plus'/></Button>
+ <Button
+ className="add-button"
+ icon
+ >
+ <Icon name="plus" />
+ </Button>
}
- centered
- size='small'
{...rest}
/>
</Menu.Menu>
@@ -38,4 +47,4 @@ const RoomMenu = ({ joined, active, onRoomChange, ...rest }) => {
);
};
-export default RoomMenu; \ No newline at end of file
+export default RoomMenu;
diff --git a/src/web/src/components/Rooms/RoomUserList.jsx b/src/web/src/components/Rooms/RoomUserList.jsx
index 663961e8..fc37625b 100644
--- a/src/web/src/components/Rooms/RoomUserList.jsx
+++ b/src/web/src/components/Rooms/RoomUserList.jsx
@@ -1,15 +1,18 @@
-import React, { useMemo } from 'react';
import './Rooms.css';
-
-import {
- Icon, Flag, List, Popup,
-} from 'semantic-ui-react';
+import React, { useMemo } from 'react';
+import { Flag, Icon, List, Popup } from 'semantic-ui-react';
const RoomUserList = ({ users }) => {
const getFlag = (user) => {
- if (!(user || {}).countryCode) return <Icon className='unknown-user-flag' name='question'/>;
-
- return <Flag name={user.countryCode.toLowerCase()}/>;
+ if (!(user || {}).countryCode)
+ return (
+ <Icon
+ className="unknown-user-flag"
+ name="question"
+ />
+ );
+
+ return <Flag name={user.countryCode.toLowerCase()} />;
};
const getDetails = (user) => {
@@ -19,26 +22,38 @@ const RoomUserList = ({ users }) => {
const sortedUsers = useMemo(() => {
const filtered = [...users]
.sort((a, b) => a.username.localeCompare(b.username))
- .reduce((acc, user) => {
- (user.status === 'Online' ? acc.online : acc.offline).push(user);
- return acc;
- }, { online: [], offline: []});
+ .reduce(
+ (accumulator, user) => {
+ (user.status === 'Online'
+ ? accumulator.online
+ : accumulator.offline
+ ).push(user);
+ return accumulator;
+ },
+ { offline: [], online: [] },
+ );
return [...filtered.online, ...filtered.offline];
}, [users]);
return (
<List>
- {sortedUsers.map((user, index) =>
- <List.Item key={index} className={user.self ? 'room-user-self' : ''}>
- <List.Content style={{ opacity: user.status === 'Online' ? 1 : .5}}>
- <Popup content={getDetails(user)} trigger={getFlag(user)}/>
+ {sortedUsers.map((user, index) => (
+ <List.Item
+ className={user.self ? 'room-user-self' : ''}
+ key={index}
+ >
+ <List.Content style={{ opacity: user.status === 'Online' ? 1 : 0.5 }}>
+ <Popup
+ content={getDetails(user)}
+ trigger={getFlag(user)}
+ />
{user.username}
</List.Content>
</List.Item>
- )}
+ ))}
</List>
);
};
-export default RoomUserList; \ No newline at end of file
+export default RoomUserList;
diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx
index 066c0ab1..e4d17d7c 100644
--- a/src/web/src/components/Rooms/Rooms.jsx
+++ b/src/web/src/components/Rooms/Rooms.jsx
@@ -1,53 +1,65 @@
-import React, { Component, createRef } from 'react';
-import * as rooms from '../../lib/rooms';
import { activeRoomKey } from '../../config';
-
-import { Segment, Card, Icon, Input, Ref, List, Loader, Dimmer } from 'semantic-ui-react';
-
+import * as rooms from '../../lib/rooms';
+import PlaceholderSegment from '../Shared/PlaceholderSegment';
import RoomMenu from './RoomMenu';
import RoomUserList from './RoomUserList';
-import PlaceholderSegment from '../Shared/PlaceholderSegment';
+import React, { Component, createRef } from 'react';
+import {
+ Card,
+ Dimmer,
+ Icon,
+ Input,
+ List,
+ Loader,
+ Ref,
+ Segment,
+} from 'semantic-ui-react';
const initialState = {
active: '',
+ intervals: {
+ messages: undefined,
+ rooms: undefined,
+ },
joined: [],
+ loading: false,
room: {
messages: [],
users: [],
},
- intervals: {
- rooms: undefined,
- messages: undefined,
- },
- loading: false,
};
class Rooms extends Component {
state = initialState;
+
messageRef = undefined;
+
listRef = createRef();
- componentDidMount = async () => {
- this.setState({
- intervals: {
- rooms: window.setInterval(this.fetchJoinedRooms, 500),
- messages: window.setInterval(this.fetchActiveRoom, 1000),
+ componentDidMount() {
+ this.setState(
+ {
+ active: sessionStorage.getItem(activeRoomKey) || '',
+ intervals: {
+ messages: window.setInterval(this.fetchActiveRoom, 1_000),
+ rooms: window.setInterval(this.fetchJoinedRooms, 500),
+ },
},
- active: sessionStorage.getItem(activeRoomKey) || '',
- }, async () => {
- await this.fetchJoinedRooms();
- this.selectRoom(this.state.active || this.getFirstRoom());
- });
- };
+ async () => {
+ await this.fetchJoinedRooms();
+ this.selectRoom(this.state.active || this.getFirstRoom());
+ },
+ );
+ }
- componentWillUnmount = () => {
- const { rooms, messages } = this.state.intervals;
+ componentWillUnmount() {
+ const { messages, rooms } = this.state.intervals;
clearInterval(rooms);
clearInterval(messages);
this.setState({ intervals: initialState.intervals });
- };
+ }
getFirstRoom = () => {
return this.state.joined.length > 0 ? this.state.joined[0] : '';
@@ -55,13 +67,16 @@ class Rooms extends Component {
fetchJoinedRooms = async () => {
const joined = await rooms.getJoined();
- this.setState({
- joined,
- }, () => {
- if (!this.state.joined.includes(this.state.active)) {
- this.selectRoom(this.getFirstRoom());
- }
- });
+ this.setState(
+ {
+ joined,
+ },
+ () => {
+ if (!this.state.joined.includes(this.state.active)) {
+ this.selectRoom(this.getFirstRoom());
+ }
+ },
+ );
};
fetchActiveRoom = async () => {
@@ -74,31 +89,34 @@ class Rooms extends Component {
this.setState({
room: {
- users,
messages,
+ users,
},
});
};
selectRoom = async (roomName) => {
- this.setState({
- active: roomName,
- room: initialState.room,
- loading: true,
- }, async () => {
- const { active } = this.state;
-
- sessionStorage.setItem(activeRoomKey, active);
-
- await this.fetchActiveRoom();
- this.setState({ loading: false }, () => {
- try {
- this.listRef.current.lastChild.scrollIntoView();
- } catch {
- // no-op
- }
- });
- });
+ this.setState(
+ {
+ active: roomName,
+ loading: true,
+ room: initialState.room,
+ },
+ async () => {
+ const { active } = this.state;
+
+ sessionStorage.setItem(activeRoomKey, active);
+
+ await this.fetchActiveRoom();
+ this.setState({ loading: false }, () => {
+ try {
+ this.listRef.current.lastChild.scrollIntoView();
+ } catch {
+ // no-op
+ }
+ });
+ },
+ );
};
joinRoom = async (roomName) => {
@@ -114,20 +132,25 @@ class Rooms extends Component {
};
validInput = () =>
- (this.state.active || '').length > 0
- && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0;
-
+ (this.state.active || '').length > 0 &&
+ (
+ (this.messageRef &&
+ this.messageRef.current &&
+ this.messageRef.current.value) ||
+ ''
+ ).length > 0;
+
focusInput = () => {
this.messageRef.current.focus();
};
formatTimestamp = (timestamp) => {
const date = new Date(timestamp);
- const dtfUS = new Intl.DateTimeFormat('en', {
- month: 'numeric',
+ const dtfUS = new Intl.DateTimeFormat('en', {
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
+ month: 'numeric',
});
return dtfUS.format(date);
@@ -141,85 +164,135 @@ class Rooms extends Component {
return;
}
- await rooms.sendMessage({ roomName: active, message });
+ await rooms.sendMessage({ message, roomName: active });
this.messageRef.current.value = '';
};
- render = () => {
- const { joined = [], active = [], room, loading } = this.state;
+ render() {
+ const { active = [], joined = [], loading, room } = this.state;
return (
- <div className='rooms'>
- <Segment className='rooms-segment' raised>
- <div className="rooms-segment-icon"><Icon name="comments" size="big"/></div>
+ <div className="rooms">
+ <Segment
+ className="rooms-segment"
+ raised
+ >
+ <div className="rooms-segment-icon">
+ <Icon
+ name="comments"
+ size="big"
+ />
+ </div>
<RoomMenu
- joined={joined}
active={active}
- onRoomChange={(name) => this.selectRoom(name)}
joinRoom={this.joinRoom}
+ joined={joined}
+ onRoomChange={(name) => this.selectRoom(name)}
/>
</Segment>
- {!active ?
- <PlaceholderSegment icon='comments' caption='No rooms to display'/> :
- <Card className='room-active-card' raised>
+ {!active ? (
+ <PlaceholderSegment
+ caption="No rooms to display"
+ icon="comments"
+ />
+ ) : (
+ <Card
+ className="room-active-card"
+ raised
+ >
<Card.Content onClick={() => this.focusInput()}>
<Card.Header>
- <Icon name='circle' color='green'/>
+ <Icon
+ color="green"
+ name="circle"
+ />
{active}
- <Icon
- className='close-button'
- name='close'
- color='red'
+ <Icon
+ className="close-button"
+ color="red"
link
+ name="close"
onClick={() => this.leaveRoom(active)}
/>
</Card.Header>
- <div className='room'>
- {loading ? <Dimmer active inverted><Loader inverted/></Dimmer> : <>
- <Segment.Group>
- <Segment className='room-history'>
- <Ref innerRef={this.listRef}>
- <List>
- {room.messages.map((message, index) =>
- <List.Content
- key={index}
- className={`room-message ${message.self ? 'room-message-self' : ''}`}
- >
- <span className='room-message-time'>{this.formatTimestamp(message.timestamp)}</span>
- <span className='room-message-name'>{message.username}: </span>
- <span className='room-message-message'>{message.message}</span>
- </List.Content>
- )}
- <List.Content id='room-history-scroll-anchor'/>
- </List>
- </Ref>
- </Segment>
- <Segment className='room-input'>
- <Input
- fluid
- transparent
- input={
- <input id='room-message-input' type="text" data-lpignore="true" autoComplete="off"></input>}
- ref={input => this.messageRef = input && input.inputRef}
- action={{
- icon: <Icon name='send' color='green'/>,
- className: 'room-message-button', onClick: this.sendMessage,
- disabled: !this.validInput(),
- }}
- onKeyUp={(e) => e.key === 'Enter' ? this.sendMessage() : ''}
- />
+ <div className="room">
+ {loading ? (
+ <Dimmer
+ active
+ inverted
+ >
+ <Loader inverted />
+ </Dimmer>
+ ) : (
+ <>
+ <Segment.Group>
+ <Segment className="room-history">
+ <Ref innerRef={this.listRef}>
+ <List>
+ {room.messages.map((message, index) => (
+ <List.Content
+ className={`room-message ${message.self ? 'room-message-self' : ''}`}
+ key={index}
+ >
+ <span className="room-message-time">
+ {this.formatTimestamp(message.timestamp)}
+ </span>
+ <span className="room-message-name">
+ {message.username}:{' '}
+ </span>
+ <span className="room-message-message">
+ {message.message}
+ </span>
+ </List.Content>
+ ))}
+ <List.Content id="room-history-scroll-anchor" />
+ </List>
+ </Ref>
+ </Segment>
+ <Segment className="room-input">
+ <Input
+ action={{
+ className: 'room-message-button',
+ disabled: !this.validInput(),
+ icon: (
+ <Icon
+ color="green"
+ name="send"
+ />
+ ),
+ onClick: this.sendMessage,
+ }}
+ fluid
+ input={
+ <input
+ autoComplete="off"
+ data-lpignore="true"
+ id="room-message-input"
+ type="text"
+ />
+ }
+ onKeyUp={(e) =>
+ e.key === 'Enter' ? this.sendMessage() : ''
+ }
+ ref={(input) =>
+ (this.messageRef = input && input.inputRef)
+ }
+ transparent
+ />
+ </Segment>
+ </Segment.Group>
+ <Segment className="room-users">
+ <RoomUserList users={room.users} />
</Segment>
- </Segment.Group>
- <Segment className='room-users'>
- <RoomUserList users={room.users}/>
- </Segment>
- </>}
+ </>
+ )}
</div>
</Card.Content>
- </Card>}
+ </Card>
+ )}
</div>
);
- };
+ }
}
-export default Rooms; \ No newline at end of file
+export default Rooms;
diff --git a/src/web/src/components/Search/Detail/SearchDetail.jsx b/src/web/src/components/Search/Detail/SearchDetail.jsx
index 99175bd0..488affc3 100644
--- a/src/web/src/components/Search/Detail/SearchDetail.jsx
+++ b/src/web/src/components/Search/Detail/SearchDetail.jsx
@@ -1,28 +1,42 @@
-import React, { useEffect, useState, useMemo } from 'react';
-
import {
- Checkbox,
- Input,
- Segment,
- Dropdown,
- Button,
-} from 'semantic-ui-react';
-
+ filterResponse,
+ getResponses,
+ parseFiltersFromString,
+} from '../../../lib/searches';
import { sleep } from '../../../lib/util';
-import Switch from '../../Shared/Switch';
import ErrorSegment from '../../Shared/ErrorSegment';
-import Response from '../Response';
-import { getResponses, parseFiltersFromString, filterResponse } from '../../../lib/searches';
import LoaderSegment from '../../Shared/LoaderSegment';
+import Switch from '../../Shared/Switch';
+import Response from '../Response';
import SearchDetailHeader from './SearchDetailHeader';
+import React, { useEffect, useMemo, useState } from 'react';
+import { Button, Checkbox, Dropdown, Input, Segment } from 'semantic-ui-react';
const sortDropdownOptions = [
- { key: 'uploadSpeed', text: 'Upload Speed (Fastest to Slowest)', value: 'uploadSpeed' },
- { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' },
+ {
+ key: 'uploadSpeed',
+ text: 'Upload Speed (Fastest to Slowest)',
+ value: 'uploadSpeed',
+ },
+ {
+ key: 'queueLength',
+ text: 'Queue Depth (Least to Most)',
+ value: 'queueLength',
+ },
];
-const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate, onStop, onRemove }) => {
- const { id, state, isComplete, fileCount, lockedFileCount, responseCount } = search;
+const SearchDetail = ({
+ creating,
+ disabled,
+ onCreate,
+ onRemove,
+ onStop,
+ removing,
+ search,
+ stopping,
+}) => {
+ const { fileCount, id, isComplete, lockedFileCount, responseCount, state } =
+ search;
const [loading, setLoading] = useState(false);
const [error, setError] = useState(undefined);
@@ -48,7 +62,7 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
// the results may not be ready yet. this is very rare, but
// if it happens the search will complete with no results.
await sleep(500);
-
+
const responses = await getResponses({ id });
setResults(responses);
setLoading(false);
@@ -67,8 +81,8 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
// sets, so memoize it.
const sortedAndFilteredResults = useMemo(() => {
const sortOptions = {
- uploadSpeed: { field: 'uploadSpeed', order: 'desc' },
queueLength: { field: 'queueLength', order: 'asc' },
+ uploadSpeed: { field: 'uploadSpeed', order: 'desc' },
};
const { field, order } = sortOptions[resultSort];
@@ -76,16 +90,17 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
const filters = parseFiltersFromString(resultFilters);
return results
- .filter(r => !hiddenResults.includes(r.username))
- .map(r => {
+ .filter((r) => !hiddenResults.includes(r.username))
+ .map((r) => {
if (hideLocked) {
return { ...r, lockedFileCount: 0, lockedFiles: [] };
}
+
return r;
})
- .map(response => filterResponse({ response, filters }))
- .filter(r => r.fileCount + r.lockedFileCount > 0)
- .filter(r => !(hideNoFreeSlots && !r.hasFreeUploadSlot))
+ .map((response) => filterResponse({ filters, response }))
+ .filter((r) => r.fileCount + r.lockedFileCount > 0)
+ .filter((r) => !(hideNoFreeSlots && !r.hasFreeUploadSlot))
.sort((a, b) => {
if (order === 'asc') {
return a[field] - b[field];
@@ -93,8 +108,14 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
return b[field] - a[field];
});
-
- }, [results, hideLocked, hideNoFreeSlots, resultFilters, resultSort, hiddenResults]);
+ }, [
+ hiddenResults,
+ hideLocked,
+ hideNoFreeSlots,
+ resultFilters,
+ resultSort,
+ results,
+ ]);
// when a user uses the action buttons, we will *probably* re-use this component,
// but with a new search ID. clear everything to prepare for the transition
@@ -106,9 +127,9 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
setDisplayCount(5);
};
- const create = async ({ search, navigate }) => {
- reset();
- onCreate({ search, navigate });
+ const create = async ({ navigate, search }) => {
+ reset();
+ onCreate({ navigate, search });
};
const remove = async () => {
@@ -118,109 +139,136 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
const filteredCount = results?.length - sortedAndFilteredResults.length;
const remainingCount = sortedAndFilteredResults.length - displayCount;
- const loaded = (!removing && !creating && !loading && results);
+ const loaded = !removing && !creating && !loading && results;
if (error) {
- return (<ErrorSegment caption={error?.message ?? error}/>);
+ return <ErrorSegment caption={error?.message ?? error} />;
}
return (
<>
<SearchDetailHeader
- loading={loading}
- loaded={loaded}
- removing={removing}
- stopping={stopping}
creating={creating}
disabled={disabled}
- search={search}
+ loaded={loaded}
+ loading={loading}
onCreate={create}
- onStop={onStop}
onRemove={remove}
+ onStop={onStop}
+ removing={removing}
+ search={search}
+ stopping={stopping}
/>
- <Switch
- searching={!isComplete &&
- <LoaderSegment>
- {state === 'InProgress'
- ? `Found ${fileCount} files ${lockedFileCount > 0
- ? `(plus ${lockedFileCount} locked) `
- : ''}from ${responseCount} users`
- : 'Loading results...'}
- </LoaderSegment>
+ <Switch
+ loading={loading && <LoaderSegment />}
+ searching={
+ !isComplete && (
+ <LoaderSegment>
+ {state === 'InProgress'
+ ? `Found ${fileCount} files ${
+ lockedFileCount > 0
+ ? `(plus ${lockedFileCount} locked) `
+ : ''
+ }from ${responseCount} users`
+ : 'Loading results...'}
+ </LoaderSegment>
+ )
}
- loading={loading && <LoaderSegment/>}
>
- {loaded &&
- <Segment className='search-options' raised>
+ {loaded && (
+ <Segment
+ className="search-options"
+ raised
+ >
<Dropdown
button
- className='search-options-sort icon'
+ className="search-options-sort icon"
floating
+ icon="sort"
labeled
- icon='sort'
- options={sortDropdownOptions}
onChange={(e, { value }) => setResultSort(value)}
- text={sortDropdownOptions.find(o => o.value === resultSort).text}
+ options={sortDropdownOptions}
+ text={
+ sortDropdownOptions.find((o) => o.value === resultSort).text
+ }
/>
- <div className='search-option-toggles'>
+ <div className="search-option-toggles">
<Checkbox
- className='search-options-hide-locked'
- toggle
- onChange={() => setHideLocked(!hideLocked)}
checked={hideLocked}
- label='Hide Locked Results'
+ className="search-options-hide-locked"
+ label="Hide Locked Results"
+ onChange={() => setHideLocked(!hideLocked)}
+ toggle
/>
<Checkbox
- className='search-options-hide-no-slots'
- toggle
- onChange={() => setHideNoFreeSlots(!hideNoFreeSlots)}
checked={hideNoFreeSlots}
- label='Hide Results with No Free Slots'
+ className="search-options-hide-no-slots"
+ label="Hide Results with No Free Slots"
+ onChange={() => setHideNoFreeSlots(!hideNoFreeSlots)}
+ toggle
/>
<Checkbox
- className='search-options-fold-results'
- toggle
- onChange={() => setFoldResults(!foldResults)}
checked={foldResults}
- label='Fold Results'
+ className="search-options-fold-results"
+ label="Fold Results"
+ onChange={() => setFoldResults(!foldResults)}
+ toggle
/>
</div>
- <Input
- className='search-filter'
- placeholder='
+ <Input
+ action={
+ Boolean(resultFilters) && {
+ color: 'red',
+ icon: 'x',
+ onClick: () => setResultFilters(''),
+ }
+ }
+ className="search-filter"
+ label={{ content: 'Filter', icon: 'filter' }}
+ onChange={(e, data) => setResultFilters(data.value)}
+ placeholder="
lackluster container -bothersome iscbr|isvbr islossless|islossy
minbitrate:320 minbitdepth:24 minfilesize:10 minfilesinfolder:8 minlength:5000
- '
- label={{ icon: 'filter', content: 'Filter' }}
+ "
value={resultFilters}
- onChange={(e, data) => setResultFilters(data.value)}
- action={!!resultFilters && { icon: 'x', color: 'red', onClick: () => setResultFilters('')}}
/>
</Segment>
- }
- {loaded && sortedAndFilteredResults.slice(0, displayCount).map((r, i) =>
- <Response
- key={i}
- response={r}
- disabled={disabled}
- onHide={() => setHiddenResults([...hiddenResults, r.username])}
- isInitiallyFolded={foldResults}
- />
)}
- {loaded && (remainingCount > 0 ?
- <Button className='showmore-button' size='large' fluid primary
- onClick={() => setDisplayCount(displayCount + 5)}>
- Show {remainingCount > 5
- ? 5
- : remainingCount} More Results {`(${remainingCount} remaining, ${filteredCount} hidden by filter(s))`}
- </Button>
- : filteredCount > 0 ?
- <Button className='showmore-button' size='large' fluid disabled>{
- `All results shown. ${filteredCount} results hidden by filter(s)`
- }</Button> : '')}
+ {loaded &&
+ sortedAndFilteredResults.slice(0, displayCount).map((r, index) => (
+ <Response
+ disabled={disabled}
+ isInitiallyFolded={foldResults}
+ key={index}
+ onHide={() => setHiddenResults([...hiddenResults, r.username])}
+ response={r}
+ />
+ ))}
+ {loaded &&
+ (remainingCount > 0 ? (
+ <Button
+ className="showmore-button"
+ fluid
+ onClick={() => setDisplayCount(displayCount + 5)}
+ primary
+ size="large"
+ >
+ Show {remainingCount > 5 ? 5 : remainingCount} More Results{' '}
+ {`(${remainingCount} remaining, ${filteredCount} hidden by filter(s))`}
+ </Button>
+ ) : filteredCount > 0 ? (
+ <Button
+ className="showmore-button"
+ disabled
+ fluid
+ size="large"
+ >{`All results shown. ${filteredCount} results hidden by filter(s)`}</Button>
+ ) : (
+ ''
+ ))}
</Switch>
</>
);
};
-export default SearchDetail; \ No newline at end of file
+export default SearchDetail;
diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.jsx b/src/web/src/components/Search/Detail/SearchDetailHeader.jsx
index 2071540f..25c5789b 100644
--- a/src/web/src/components/Search/Detail/SearchDetailHeader.jsx
+++ b/src/web/src/components/Search/Detail/SearchDetailHeader.jsx
@@ -1,30 +1,24 @@
+import SearchStatusIcon from '../SearchStatusIcon';
import React from 'react';
import { useMediaQuery } from 'react-responsive';
-
-import {
- Segment,
- Button,
- Header,
- Icon,
-} from 'semantic-ui-react';
-import SearchStatusIcon from '../SearchStatusIcon';
+import { Button, Header, Icon, Segment } from 'semantic-ui-react';
const SearchDetailHeader = ({
- search,
- loading,
- loaded,
creating,
- removing,
- stopping,
disabled,
+ loaded,
+ loading,
onCreate,
- onStop,
onRemove,
+ onStop,
+ removing,
+ search,
+ stopping,
}) => {
const isSmallScreen = useMediaQuery({ query: '(max-width: 899px)' });
- const isTinyScreen = useMediaQuery({ query: '(max-width: 684px)'});
+ const isTinyScreen = useMediaQuery({ query: '(max-width: 684px)' });
- const { searchText, isComplete, state } = search;
+ const { isComplete, searchText, state } = search;
const working = loading || creating || removing || stopping;
const stopOrRemove = () => {
@@ -35,49 +29,62 @@ const SearchDetailHeader = ({
}
};
- const RefreshButton = () => loaded &&
- <Button
- disabled={disabled || working}
- icon={isSmallScreen && !isTinyScreen}
- onClick={() => onCreate({ search: searchText, navigate: true })}
- loading={creating}
- >
- <Icon name='refresh'/>{(!isSmallScreen || isTinyScreen) && 'Search Again'}
- </Button>;
+ const RefreshButton = () =>
+ loaded && (
+ <Button
+ disabled={disabled || working}
+ icon={isSmallScreen && !isTinyScreen}
+ loading={creating}
+ onClick={() => onCreate({ navigate: true, search: searchText })}
+ >
+ <Icon name="refresh" />
+ {(!isSmallScreen || isTinyScreen) && 'Search Again'}
+ </Button>
+ );
- const StopOrDeleteButton = () =>
- <Button
- negative
+ const StopOrDeleteButton = () => (
+ <Button
disabled={working}
- onClick={stopOrRemove}
- loading={removing || stopping}
floated={isTinyScreen ? 'right' : undefined}
icon={isSmallScreen && !isTinyScreen}
+ loading={removing || stopping}
+ negative
+ onClick={stopOrRemove}
>
- <Icon name={isComplete ? 'trash alternate' : 'stop circle'}/>
- {(!isSmallScreen || isTinyScreen) && ((loaded && isComplete) ? 'Delete' : 'Stop')}
- </Button>;
+ <Icon name={isComplete ? 'trash alternate' : 'stop circle'} />
+ {(!isSmallScreen || isTinyScreen) &&
+ (loaded && isComplete ? 'Delete' : 'Stop')}
+ </Button>
+ );
// if the screen is full width, display the header and action buttons in the same segment, with full
// button text. if the screen is between 684 and 899 pixels, display the buttons with no text.
// if the screen is less than 684 pixels, display the action buttons in a new segment, with full text.
return (
<>
- <Segment className='search-detail-header-segment' raised>
+ <Segment
+ className="search-detail-header-segment"
+ raised
+ >
<Header>
- <SearchStatusIcon state={state}/>{searchText}
+ <SearchStatusIcon state={state} />
+ {searchText}
</Header>
- {!isTinyScreen && <div className='search-detail-header-buttons'>
- <RefreshButton/>
- <StopOrDeleteButton/>
- </div>}
+ {!isTinyScreen && (
+ <div className="search-detail-header-buttons">
+ <RefreshButton />
+ <StopOrDeleteButton />
+ </div>
+ )}
</Segment>
- {isTinyScreen && <Segment>
- <RefreshButton/>
- <StopOrDeleteButton/>
- </Segment>}
+ {isTinyScreen && (
+ <Segment>
+ <RefreshButton />
+ <StopOrDeleteButton />
+ </Segment>
+ )}
</>
);
};
-export default SearchDetailHeader; \ No newline at end of file
+export default SearchDetailHeader;
diff --git a/src/web/src/components/Search/List/SearchActionIcon.jsx b/src/web/src/components/Search/List/SearchActionIcon.jsx
index baec2ccc..59a59987 100644
--- a/src/web/src/components/Search/List/SearchActionIcon.jsx
+++ b/src/web/src/components/Search/List/SearchActionIcon.jsx
@@ -1,27 +1,36 @@
import React from 'react';
-
import { Icon } from 'semantic-ui-react';
-const SearchActionIcon = ({ search, loading, onRemove, onStop,...props }) => {
+const SearchActionIcon = ({ loading, onRemove, onStop, search, ...props }) => {
if (loading) {
- return (<Icon name='spinner' loading {...props}/>);
+ return (
+ <Icon
+ loading
+ name="spinner"
+ {...props}
+ />
+ );
}
if (search.state.includes('Completed')) {
- return (<Icon
- name="trash alternate"
- color='red'
- onClick={() => onRemove()}
- style={{ cursor: 'pointer' }}
- />);
+ return (
+ <Icon
+ color="red"
+ name="trash alternate"
+ onClick={() => onRemove()}
+ style={{ cursor: 'pointer' }}
+ />
+ );
}
- return (<Icon
- name="stop circle"
- color="red"
- onClick={() => onStop()}
- style={{ cursor: 'pointer' }}
- />);
+ return (
+ <Icon
+ color="red"
+ name="stop circle"
+ onClick={() => onStop()}
+ style={{ cursor: 'pointer' }}
+ />
+ );
};
-export default SearchActionIcon; \ No newline at end of file
+export default SearchActionIcon;
diff --git a/src/web/src/components/Search/List/SearchList.jsx b/src/web/src/components/Search/List/SearchList.jsx
index b78c7919..e5843972 100644
--- a/src/web/src/components/Search/List/SearchList.jsx
+++ b/src/web/src/components/Search/List/SearchList.jsx
@@ -1,52 +1,73 @@
-import React from 'react';
-
-import SearchListRow from './SearchListRow';
import ErrorSegment from '../../Shared/ErrorSegment';
import Switch from '../../Shared/Switch';
-
-import {
- Card,
- Table,
- Icon,
- Loader,
-} from 'semantic-ui-react';
+import SearchListRow from './SearchListRow';
+import React from 'react';
+import { Card, Icon, Loader, Table } from 'semantic-ui-react';
const SearchList = ({
connecting = false,
error = undefined,
+ onRemove = () => {},
+ onStop = () => {},
searches = {},
- onRemove = () => { },
- onStop = () => { },
}) => {
return (
- <Card className='search-list-card' raised>
+ <Card
+ className="search-list-card"
+ raised
+ >
<Card.Content>
- <div className='search-list-wrapper'>
+ <div className="search-list-wrapper">
<Switch
- connecting={connecting && <Loader active inline='centered' size='small'/>}
+ connecting={
+ connecting && (
+ <Loader
+ active
+ inline="centered"
+ size="small"
+ />
+ )
+ }
error={error && <ErrorSegment caption={error} />}
>
- <Table size='large' className='unstackable'>
+ <Table
+ className="unstackable"
+ size="large"
+ >
<Table.Header>
<Table.Row>
- <Table.HeaderCell className="search-list-action"><Icon name="info circle"/></Table.HeaderCell>
- <Table.HeaderCell className="search-list-phrase">Search</Table.HeaderCell>
- <Table.HeaderCell className="search-list-files">Files</Table.HeaderCell>
- <Table.HeaderCell className="search-list-locked">Locked</Table.HeaderCell>
- <Table.HeaderCell className="search-list-responses">Responses</Table.HeaderCell>
- <Table.HeaderCell className="search-list-started">Ended</Table.HeaderCell>
- <Table.HeaderCell className="search-list-action"></Table.HeaderCell>
+ <Table.HeaderCell className="search-list-action">
+ <Icon name="info circle" />
+ </Table.HeaderCell>
+ <Table.HeaderCell className="search-list-phrase">
+ Search
+ </Table.HeaderCell>
+ <Table.HeaderCell className="search-list-files">
+ Files
+ </Table.HeaderCell>
+ <Table.HeaderCell className="search-list-locked">
+ Locked
+ </Table.HeaderCell>
+ <Table.HeaderCell className="search-list-responses">
+ Responses
+ </Table.HeaderCell>
+ <Table.HeaderCell className="search-list-started">
+ Ended
+ </Table.HeaderCell>
+ <Table.HeaderCell className="search-list-action" />
</Table.Row>
</Table.Header>
<Table.Body>
{Object.values(searches)
- .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt)))
- .map((search, index) => <SearchListRow
- search={search}
- key={index}
- onRemove={onRemove}
- onStop={onStop}
- />)}
+ .sort((a, b) => new Date(b.startedAt) - new Date(a.startedAt))
+ .map((search, index) => (
+ <SearchListRow
+ key={index}
+ onRemove={onRemove}
+ onStop={onStop}
+ search={search}
+ />
+ ))}
</Table.Body>
</Table>
</Switch>
@@ -56,4 +77,4 @@ const SearchList = ({
);
};
-export default SearchList; \ No newline at end of file
+export default SearchList;
diff --git a/src/web/src/components/Search/List/SearchListRow.jsx b/src/web/src/components/Search/List/SearchListRow.jsx
index feffdcea..32b21797 100644
--- a/src/web/src/components/Search/List/SearchListRow.jsx
+++ b/src/web/src/components/Search/List/SearchListRow.jsx
@@ -1,27 +1,18 @@
-import React, { useState } from 'react';
-
-import {
- Link,
- useRouteMatch,
-} from 'react-router-dom';
-
-import {
- Table,
- Icon,
-} from 'semantic-ui-react';
-
import SearchStatusIcon from '../SearchStatusIcon';
import SearchActionIcon from './SearchActionIcon';
+import React, { useState } from 'react';
+import { Link, useRouteMatch } from 'react-router-dom';
+import { Icon, Table } from 'semantic-ui-react';
-const SearchListRow = ({ search, onRemove, onStop }) => {
+const SearchListRow = ({ onRemove, onStop, search }) => {
const [working, setWorking] = useState(false);
const match = useRouteMatch();
- const invoke = async (func) => {
+ const invoke = async (function_) => {
setWorking(true);
try {
- await func();
+ await function_();
} catch (error) {
console.error(error);
} finally {
@@ -35,21 +26,30 @@ const SearchListRow = ({ search, onRemove, onStop }) => {
style={{ cursor: working ? 'wait' : undefined }}
>
<Table.Cell>
- <SearchStatusIcon
- state={search.state}
- />
+ <SearchStatusIcon state={search.state} />
+ </Table.Cell>
+ <Table.Cell>
+ <Link to={`${match.url}/${search.id}`}>{search.searchText}</Link>
</Table.Cell>
- <Table.Cell><Link to={`${match.url}/${search.id}`}>{search.searchText}</Link></Table.Cell>
<Table.Cell>{search.fileCount}</Table.Cell>
- <Table.Cell><Icon name="lock" color="yellow" size="small"/>{search.lockedFileCount}</Table.Cell>
+ <Table.Cell>
+ <Icon
+ color="yellow"
+ name="lock"
+ size="small"
+ />
+ {search.lockedFileCount}
+ </Table.Cell>
<Table.Cell>{search.responseCount}</Table.Cell>
- <Table.Cell>{search.endedAt ? new Date(search.endedAt).toLocaleTimeString() : '-'}</Table.Cell>
+ <Table.Cell>
+ {search.endedAt ? new Date(search.endedAt).toLocaleTimeString() : '-'}
+ </Table.Cell>
<Table.Cell>
<SearchActionIcon
- search={search}
loading={working}
onRemove={() => invoke(() => onRemove(search))}
onStop={() => invoke(() => onStop(search))}
+ search={search}
style={{ cursor: 'pointer' }}
/>
</Table.Cell>
@@ -57,4 +57,4 @@ const SearchListRow = ({ search, onRemove, onStop }) => {
);
};
-export default SearchListRow; \ No newline at end of file
+export default SearchListRow;
diff --git a/src/web/src/components/Search/Response.jsx b/src/web/src/components/Search/Response.jsx
index babfc22b..ce857bf3 100644
--- a/src/web/src/components/Search/Response.jsx
+++ b/src/web/src/components/Search/Response.jsx
@@ -1,63 +1,70 @@
-import React, { Component } from 'react';
import * as transfers from '../../lib/transfers';
-import { toast } from 'react-toastify';
-
+import { getDirectoryContents } from '../../lib/users';
import { formatBytes, getDirectoryName } from '../../lib/util';
-
import FileList from '../Shared/FileList';
-
-import {
- Button,
- Card,
- Icon,
- Label,
-} from 'semantic-ui-react';
-import { getDirectoryContents } from '../../lib/users';
+import React, { Component } from 'react';
+import { toast } from 'react-toastify';
+import { Button, Card, Icon, Label } from 'semantic-ui-react';
const buildTree = (response) => {
let { files = [], lockedFiles = [] } = response;
- files = files.concat(lockedFiles.map(file => ({ ...file, locked: true })));
+ files = files.concat(lockedFiles.map((file) => ({ ...file, locked: true })));
return files.reduce((dict, file) => {
- let dir = getDirectoryName(file.filename);
- let selectable = { selected: false, ...file };
- dict[dir] = dict[dir] === undefined ? [ selectable ] : dict[dir].concat(selectable);
+ const dir = getDirectoryName(file.filename);
+ const selectable = { selected: false, ...file };
+ dict[dir] =
+ dict[dir] === undefined ? [selectable] : dict[dir].concat(selectable);
return dict;
}, {});
};
class Response extends Component {
- state = {
- tree: buildTree(this.props.response),
- downloadRequest: undefined,
+ state = {
downloadError: '',
+ downloadRequest: undefined,
fetchingDirectoryContents: false,
isFolded: this.props.isInitiallyFolded,
+ tree: buildTree(this.props.response),
};
- componentDidUpdate = (prevProps) => {
- if (JSON.stringify(this.props.response) !== JSON.stringify(prevProps.response)) {
+ componentDidUpdate(previousProps) {
+ if (
+ JSON.stringify(this.props.response) !==
+ JSON.stringify(previousProps.response)
+ ) {
this.setState({ tree: buildTree(this.props.response) });
}
- if (this.props.isInitiallyFolded !== prevProps.isInitiallyFolded) {
+
+ if (this.props.isInitiallyFolded !== previousProps.isInitiallyFolded) {
this.setState({ isFolded: this.props.isInitiallyFolded });
}
- };
+ }
onFileSelectionChange = (file, state) => {
file.selected = state;
- this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' });
+ this.setState({
+ downloadError: '',
+ downloadRequest: undefined,
+ tree: this.state.tree,
+ });
};
download = (username, files) => {
this.setState({ downloadRequest: 'inProgress' }, async () => {
try {
- const requests = (files || []).map(({ filename, size }) => ({ filename, size }));
- await transfers.download({ username, files: requests });
+ const requests = (files || []).map(({ filename, size }) => ({
+ filename,
+ size,
+ }));
+ await transfers.download({ files: requests, username });
this.setState({ downloadRequest: 'complete' });
- } catch (err) {
- this.setState({ downloadRequest: 'error', downloadError: err.response });
+ } catch (error) {
+ this.setState({
+ downloadError: error.response,
+ downloadRequest: 'error',
+ });
}
});
};
@@ -69,15 +76,20 @@ class Response extends Component {
const oldTree = { ...this.state.tree };
const oldFiles = oldTree[directory];
- const { name, files } = await getDirectoryContents({ username, directory });
+ const { files, name } = await getDirectoryContents({
+ directory,
+ username,
+ });
// the api returns file names only, so we need to prepend the directory
// to make it look like a search result. we also need to preserve
// any file selections, so check the old files and assign accordingly
- const fixedFiles = files.map(file => ({
+ const fixedFiles = files.map((file) => ({
...file,
filename: `${directory}\\${file.filename}`,
- selected: oldFiles.find(f => f.filename === `${directory}\\${file.filename}`)?.selected ?? false,
+ selected:
+ oldFiles.find((f) => f.filename === `${directory}\\${file.filename}`)
+ ?.selected ?? false,
}));
oldTree[name] = fixedFiles;
@@ -94,20 +106,31 @@ class Response extends Component {
this.setState({ isFolded: !this.state.isFolded });
};
- render = () => {
- let {response} = this.props;
- let free = response.hasFreeUploadSlot;
+ render() {
+ const { response } = this.props;
+ const free = response.hasFreeUploadSlot;
- let { tree, downloadRequest, downloadError, isFolded, fetchingDirectoryContents } = this.state;
+ const {
+ downloadError,
+ downloadRequest,
+ fetchingDirectoryContents,
+ isFolded,
+ tree,
+ } = this.state;
- let selectedFiles = Object.keys(tree)
+ const selectedFiles = Object.keys(tree)
.reduce((list, dict) => list.concat(tree[dict]), [])
- .filter(f => f.selected);
+ .filter((f) => f.selected);
- let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0));
+ const selectedSize = formatBytes(
+ selectedFiles.reduce((total, f) => total + f.size, 0),
+ );
return (
- <Card className='result-card' raised>
+ <Card
+ className="result-card"
+ raised
+ >
<Card.Content>
<Card.Header>
<Icon
@@ -115,66 +138,105 @@ class Response extends Component {
name={isFolded ? 'chevron right' : 'chevron down'}
onClick={this.toggleFolded}
/>
- <Icon name='circle' color={free ? 'green' : 'yellow'}/>
+ <Icon
+ color={free ? 'green' : 'yellow'}
+ name="circle"
+ />
{response.username}
- <Icon
- className='close-button'
- name='close'
- color='red'
+ <Icon
+ className="close-button"
+ color="red"
link
+ name="close"
onClick={() => this.props.onHide()}
/>
</Card.Header>
- <Card.Meta className='result-meta'>
+ <Card.Meta className="result-meta">
<span>
- Upload Speed: {formatBytes(response.uploadSpeed)}/s,
- Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength}</span>
+ Upload Speed: {formatBytes(response.uploadSpeed)}/s, Free Upload
+ Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength}
+ </span>
</Card.Meta>
- {((!isFolded && Object.keys(tree)) || []).map((dir, i) =>
- <FileList
- key={i}
+ {((!isFolded && Object.keys(tree)) || []).map((dir, index) => (
+ <FileList
directoryName={dir}
- locked={tree[dir].find(file => file.locked)}
- files={tree[dir]}
disabled={downloadRequest === 'inProgress'}
+ files={tree[dir]}
+ footer={
+ <button
+ disabled={fetchingDirectoryContents}
+ onClick={() => this.getFullDirectory(response.username, dir)}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ width: '100%',
+ }}
+ >
+ <Icon
+ loading={fetchingDirectoryContents}
+ name={fetchingDirectoryContents ? 'circle notch' : 'folder'}
+ />
+ Get Full Directory Contents
+ </button>
+ }
+ key={index}
+ locked={tree[dir].find((file) => file.locked)}
onSelectionChange={this.onFileSelectionChange}
- footer={<button
- disabled={fetchingDirectoryContents}
- onClick={() => this.getFullDirectory(response.username, dir)}
- style={{ cursor: 'pointer', width: '100%', backgroundColor: 'transparent', border: 'none' }}>
- <Icon
- name={fetchingDirectoryContents ? 'circle notch' : 'folder'}
- loading={fetchingDirectoryContents}/>Get Full Directory Contents
- </button>}
/>
- )}
+ ))}
</Card.Content>
- {selectedFiles.length > 0 && <Card.Content extra>
- <span>
- <Button
- color='green'
- content='Download'
- icon='download'
- label={{
- as: 'a',
- basic: false,
- content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${selectedSize}`,
- }}
- labelPosition='right'
- onClick={() => this.download(response.username, selectedFiles)}
- disabled={this.props.disabled || downloadRequest === 'inProgress'}
- />
- {downloadRequest === 'inProgress' && <Icon loading name='circle notch' size='large'/>}
- {downloadRequest === 'complete' && <Icon name='checkmark' color='green' size='large'/>}
- {downloadRequest === 'error' && <span>
- <Icon name='x' color='red' size='large'/>
- <Label>{downloadError.data + ` (HTTP ${downloadError.status} ${downloadError.statusText})`}</Label>
- </span>}
- </span>
- </Card.Content>}
+ {selectedFiles.length > 0 && (
+ <Card.Content extra>
+ <span>
+ <Button
+ color="green"
+ content="Download"
+ disabled={
+ this.props.disabled || downloadRequest === 'inProgress'
+ }
+ icon="download"
+ label={{
+ as: 'a',
+ basic: false,
+ content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${selectedSize}`,
+ }}
+ labelPosition="right"
+ onClick={() => this.download(response.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 Response; \ No newline at end of file
+export default Response;
diff --git a/src/web/src/components/Search/SearchStatusIcon.jsx b/src/web/src/components/Search/SearchStatusIcon.jsx
index 0b1bfb16..9658b626 100644
--- a/src/web/src/components/Search/SearchStatusIcon.jsx
+++ b/src/web/src/components/Search/SearchStatusIcon.jsx
@@ -1,5 +1,4 @@
import React from 'react';
-
import { Icon, Popup } from 'semantic-ui-react';
// as of 4.5.2, states are:
@@ -11,25 +10,65 @@ import { Icon, Popup } from 'semantic-ui-react';
const getIcon = ({ state, ...props }) => {
switch (state) {
- case 'None':
- case 'Requested':
- return <Icon name='time' {...props}/>;
- case 'InProgress':
- return <Icon name='circle notch' loading color='green' {...props}/>;
- case 'Completed, TimedOut':
- case 'Completed, ResponseLimitReached':
- case 'Completed, FileLimitReached':
- return <Icon name='check' color='green' {...props}/>;
- case 'Completed, Cancelled':
- return <Icon name='stop circle' color='green' {...props}/>;
- case 'Completed, Errored':
- return <Icon name='x' color='red' {...props}/>;
- default:
- return <Icon name='question circle' color='yellow' {...props}/>;
+ case 'None':
+ case 'Requested':
+ return (
+ <Icon
+ name="time"
+ {...props}
+ />
+ );
+ case 'InProgress':
+ return (
+ <Icon
+ color="green"
+ loading
+ name="circle notch"
+ {...props}
+ />
+ );
+ case 'Completed, TimedOut':
+ case 'Completed, ResponseLimitReached':
+ case 'Completed, FileLimitReached':
+ return (
+ <Icon
+ color="green"
+ name="check"
+ {...props}
+ />
+ );
+ case 'Completed, Cancelled':
+ return (
+ <Icon
+ color="green"
+ name="stop circle"
+ {...props}
+ />
+ );
+ case 'Completed, Errored':
+ return (
+ <Icon
+ color="red"
+ name="x"
+ {...props}
+ />
+ );
+ default:
+ return (
+ <Icon
+ color="yellow"
+ name="question circle"
+ {...props}
+ />
+ );
}
};
-const SearchStatusIcon = ({ state, ...props }) =>
- <Popup content={state} trigger={getIcon({ state, ...props })}/>;
+const SearchStatusIcon = ({ state, ...props }) => (
+ <Popup
+ content={state}
+ trigger={getIcon({ state, ...props })}
+ />
+);
-export default SearchStatusIcon; \ No newline at end of file
+export default SearchStatusIcon;
diff --git a/src/web/src/components/Search/Searches.jsx b/src/web/src/components/Search/Searches.jsx
index 179915ea..b7c67bf1 100644
--- a/src/web/src/components/Search/Searches.jsx
+++ b/src/web/src/components/Search/Searches.jsx
@@ -1,26 +1,16 @@
-import React, { useState, useEffect, useRef } from 'react';
-import { v4 as uuidv4 } from 'uuid';
-import { useParams, useHistory, useRouteMatch } from 'react-router-dom';
-import { toast } from 'react-toastify';
-
-import * as lib from '../../lib/searches';
-import { createSearchHubConnection } from '../../lib/hubFactory';
-
-import LoaderSegment from '../Shared/LoaderSegment';
-import SearchList from './List/SearchList';
-
import './Search.css';
-
-import {
- Input,
- Segment,
- Button,
- Icon,
-} from 'semantic-ui-react';
-
-import SearchDetail from './Detail/SearchDetail';
+import { createSearchHubConnection } from '../../lib/hubFactory';
+import * as library from '../../lib/searches';
import ErrorSegment from '../Shared/ErrorSegment';
+import LoaderSegment from '../Shared/LoaderSegment';
import PlaceholderSegment from '../Shared/PlaceholderSegment';
+import SearchDetail from './Detail/SearchDetail';
+import SearchList from './List/SearchList';
+import React, { useEffect, useRef, useState } from 'react';
+import { useHistory, useParams, useRouteMatch } from 'react-router-dom';
+import { toast } from 'react-toastify';
+import { Button, Icon, Input, Segment } from 'semantic-ui-react';
+import { v4 as uuidv4 } from 'uuid';
const Searches = ({ server } = {}) => {
const [connecting, setConnecting] = useState(true);
@@ -37,9 +27,19 @@ const Searches = ({ server } = {}) => {
const history = useHistory();
const match = useRouteMatch();
- const onConnecting = () => { setConnecting(true); };
- const onConnected = () => { setConnecting(false); setError(undefined); };
- const onConnectionError = (error) => { setConnecting(false); setError(error); };
+ const onConnecting = () => {
+ setConnecting(true);
+ };
+
+ const onConnected = () => {
+ setConnecting(false);
+ setError(undefined);
+ };
+
+ const onConnectionError = (error) => {
+ setConnecting(false);
+ setError(error);
+ };
const onUpdate = (update) => {
setSearches(update);
@@ -48,23 +48,25 @@ const Searches = ({ server } = {}) => {
useEffect(() => {
onConnecting();
-
+
const searchHub = createSearchHubConnection();
- searchHub.on('list', searches => {
- onUpdate(searches.reduce((acc, search) => {
- acc[search.id] = search;
- return acc;
- }, {}));
+ searchHub.on('list', (searches) => {
+ onUpdate(
+ searches.reduce((accumulator, search) => {
+ accumulator[search.id] = search;
+ return accumulator;
+ }, {}),
+ );
onConnected();
});
- searchHub.on('update', search => {
- onUpdate(old => ({ ...old, [search.id]: search }));
+ searchHub.on('update', (search) => {
+ onUpdate((old) => ({ ...old, [search.id]: search }));
});
- searchHub.on('delete', search => {
- onUpdate(old => {
+ searchHub.on('delete', (search) => {
+ onUpdate((old) => {
delete old[search.id];
return { ...old };
});
@@ -72,9 +74,13 @@ const Searches = ({ server } = {}) => {
searchHub.on('create', () => {});
- searchHub.onreconnecting((error) => onConnectionError(error?.message ?? 'Disconnected'));
+ searchHub.onreconnecting((error) =>
+ onConnectionError(error?.message ?? 'Disconnected'),
+ );
searchHub.onreconnected(() => onConnected());
- searchHub.onclose((error) => onConnectionError(error?.message ?? 'Disconnected'));
+ searchHub.onclose((error) =>
+ onConnectionError(error?.message ?? 'Disconnected'),
+ );
const connect = async () => {
try {
@@ -95,29 +101,29 @@ const Searches = ({ server } = {}) => {
// create a new search, and optionally navigate to it to display the details
// we do this if the user clicks the search icon, or repeats an existing search
- const create = async ({ search, navigate = false } = {}) => {
+ const create = async ({ navigate = false, search } = {}) => {
const ref = inputRef?.current?.inputRef?.current;
const searchText = search || ref.value;
const id = uuidv4();
-
+
try {
setCreating(true);
- await lib.create({ id, searchText });
-
+ await library.create({ id, searchText });
+
try {
ref.value = '';
ref.focus();
} catch {
// we are probably repeating an existing search; the input isn't mounted. no-op.
}
-
+
setCreating(false);
if (navigate) {
history.push(`${match.url.replace(`/${searchId}`, '')}/${id}`);
}
} catch (error) {
- console.error(error);
+ console.error(error);
toast.error(error?.response?.data ?? error?.message ?? error);
setCreating(false);
}
@@ -128,15 +134,15 @@ const Searches = ({ server } = {}) => {
try {
setRemoving(true);
- await lib.remove({ id: search.id });
- setSearches(old => {
+ await library.remove({ id: search.id });
+ setSearches((old) => {
delete old[search.id];
return { ...old };
});
setRemoving(false);
- } catch (err) {
- console.error(err);
+ } catch (error_) {
+ console.error(error_);
toast.error(error?.response?.data ?? error?.message ?? error);
setRemoving(false);
}
@@ -146,7 +152,7 @@ const Searches = ({ server } = {}) => {
const stop = async (search) => {
try {
setStopping(true);
- await lib.stop({ id: search.id });
+ await library.stop({ id: search.id });
setStopping(false);
} catch (error) {
console.error(error);
@@ -156,11 +162,11 @@ const Searches = ({ server } = {}) => {
};
if (connecting) {
- return <LoaderSegment/>;
+ return <LoaderSegment />;
}
if (error) {
- return <ErrorSegment caption={error?.message ?? error}/>;
+ return <ErrorSegment caption={error?.message ?? error} />;
}
// if searchId is not null, there's an id in the route.
@@ -169,14 +175,14 @@ const Searches = ({ server } = {}) => {
if (searches[searchId]) {
return (
<SearchDetail
- search={searches[searchId]}
creating={creating}
- stopping={stopping}
- removing={removing}
disabled={!server?.isConnected}
onCreate={create}
- onStop={stop}
onRemove={remove}
+ onStop={stop}
+ removing={removing}
+ search={searches[searchId]}
+ stopping={stopping}
/>
);
}
@@ -190,44 +196,67 @@ const Searches = ({ server } = {}) => {
return (
<>
- <Segment className='search-segment' raised>
- <div className="search-segment-icon"><Icon name="search" size="big"/></div>
+ <Segment
+ className="search-segment"
+ raised
+ >
+ <div className="search-segment-icon">
+ <Icon
+ name="search"
+ size="big"
+ />
+ </div>
<Input
+ action={
+ <>
+ <Button
+ disabled={creating || !server.isConnected}
+ icon="plus"
+ onClick={create}
+ />
+ <Button
+ disabled={creating || !server.isConnected}
+ icon="search"
+ onClick={() => create({ navigate: true })}
+ />
+ </>
+ }
+ className="search-input"
+ disabled={creating || !server.isConnected}
input={
<input
- placeholder={server.isConnected ? 'Search phrase' : 'Connect to server to perform a search'}
- type="search"
data-lpignore="true"
- ></input>}
- size='big'
- ref={inputRef}
+ placeholder={
+ server.isConnected
+ ? 'Search phrase'
+ : 'Connect to server to perform a search'
+ }
+ type="search"
+ />
+ }
loading={creating}
- disabled={creating || !server.isConnected}
- className='search-input'
+ onKeyUp={(e) => (e.key === 'Enter' ? create() : '')}
placeholder="Search phrase"
- action={<>
- <Button icon='plus' disabled={creating || !server.isConnected} onClick={create}/>
- <Button
- icon='search'
- disabled={creating || !server.isConnected}
- onClick={() => create({ navigate: true })}
- />
- </>}
- onKeyUp={(e) => e.key === 'Enter' ? create() : ''}
+ ref={inputRef}
+ size="big"
/>
</Segment>
- {Object.keys(searches).length === 0
- ? <PlaceholderSegment icon="search" caption="No searches to display"/>
- : <SearchList
+ {Object.keys(searches).length === 0 ? (
+ <PlaceholderSegment
+ caption="No searches to display"
+ icon="search"
+ />
+ ) : (
+ <SearchList
connecting={connecting}
error={error}
- searches={searches}
onRemove={remove}
onStop={stop}
+ searches={searches}
/>
- }
+ )}
</>
);
};
-export default Searches; \ No newline at end of file
+export default Searches;
diff --git a/src/web/src/components/Shared/CodeEditor.jsx b/src/web/src/components/Shared/CodeEditor.jsx
index d4211c78..53915153 100644
--- a/src/web/src/components/Shared/CodeEditor.jsx
+++ b/src/web/src/components/Shared/CodeEditor.jsx
@@ -1,23 +1,27 @@
-import React from 'react';
-
-import CodeMirror from '@uiw/react-codemirror';
-import { StreamLanguage, syntaxHighlighting, defaultHighlightStyle } from '@codemirror/language';
+import {
+ defaultHighlightStyle,
+ StreamLanguage,
+ syntaxHighlighting,
+} from '@codemirror/language';
import { yaml } from '@codemirror/legacy-modes/mode/yaml';
+import CodeMirror from '@uiw/react-codemirror';
+import React from 'react';
-const CodeEditor = ({ value, theme, onChange = () => {}, ...rest}) => {
+const CodeEditor = ({ onChange = () => {}, theme, value, ...rest }) => {
console.log(defaultHighlightStyle);
return (
<CodeMirror
- value={value}
extensions={[
- StreamLanguage.define(yaml),
- syntaxHighlighting(defaultHighlightStyle, {fallback: true})]}
+ StreamLanguage.define(yaml),
+ syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
+ ]}
onChange={(value, _) => onChange(value)}
theme={theme}
- { ...rest}
+ value={value}
+ {...rest}
/>
);
};
-export default CodeEditor; \ No newline at end of file
+export default CodeEditor;
diff --git a/src/web/src/components/Shared/Div.jsx b/src/web/src/components/Shared/Div.jsx
index c26a40fd..c88e646e 100644
--- a/src/web/src/components/Shared/Div.jsx
+++ b/src/web/src/components/Shared/Div.jsx
@@ -1,11 +1,11 @@
import React from 'react';
-const Div = ({ hidden, children, ...rest }) => {
+const Div = ({ children, hidden, ...rest }) => {
if (hidden) {
return <></>;
}
- return (<div {...rest}>{children}</div>);
+ return <div {...rest}>{children}</div>;
};
-export default Div; \ No newline at end of file
+export default Div;
diff --git a/src/web/src/components/Shared/ErrorSegment.jsx b/src/web/src/components/Shared/ErrorSegment.jsx
index dd5528de..b0d8b338 100644
--- a/src/web/src/components/Shared/ErrorSegment.jsx
+++ b/src/web/src/components/Shared/ErrorSegment.jsx
@@ -1,14 +1,21 @@
import React from 'react';
+import { Header, Icon, Segment } from 'semantic-ui-react';
-import { Segment, Header, Icon } from 'semantic-ui-react';
-
-const ErrorSegment = ({ icon = 'x', caption, suppressPrefix = false }) => (
- <Segment className='error-segment' placeholder basic>
+const ErrorSegment = ({ caption, icon = 'x', suppressPrefix = false }) => (
+ <Segment
+ basic
+ className="error-segment"
+ placeholder
+ >
<Header icon>
- <Icon name={icon} color='red'/>
- {!suppressPrefix && 'Error: '}{caption}
+ <Icon
+ color="red"
+ name={icon}
+ />
+ {!suppressPrefix && 'Error: '}
+ {caption}
</Header>
</Segment>
);
-export default ErrorSegment; \ No newline at end of file
+export default ErrorSegment;
diff --git a/src/web/src/components/Shared/FileList.jsx b/src/web/src/components/Shared/FileList.jsx
index 3e171baf..977748dd 100644
--- a/src/web/src/components/Shared/FileList.jsx
+++ b/src/web/src/components/Shared/FileList.jsx
@@ -1,99 +1,121 @@
-import React, { useState } from 'react';
-
-import { formatSeconds, formatBytes, getFileName, formatAttributes } from '../../lib/util';
-
import {
- Header,
- Table,
- Icon,
- List,
- Checkbox,
-} from 'semantic-ui-react';
-
+ formatAttributes,
+ formatBytes,
+ formatSeconds,
+ getFileName,
+} from '../../lib/util';
+import React, { useState } from 'react';
+import { Checkbox, Header, Icon, List, Table } from 'semantic-ui-react';
-const FileList = ({
- directoryName,
- files,
- locked,
- onSelectionChange,
- disabled,
- onClose,
+const FileList = ({
+ directoryName,
+ disabled,
+ files,
footer,
+ locked,
+ onClose,
+ onSelectionChange,
}) => {
const [folded, setFolded] = useState(false);
return (
<div style={{ opacity: locked ? 0.5 : 1 }}>
<Header
- size='small'
- className='filelist-header'
+ className="filelist-header"
+ size="small"
>
<div>
<Icon
- size='large'
link={!locked}
name={locked ? 'lock' : folded ? 'folder' : 'folder open'}
- onClick={() => !locked && setFolded(!folded)}/>
+ onClick={() => !locked && setFolded(!folded)}
+ size="large"
+ />
{directoryName}
- {!!onClose && <Icon
- className='close-button'
- name='close'
- color='red'
- link
- onClick={() => onClose()}
- />}
+ {Boolean(onClose) && (
+ <Icon
+ className="close-button"
+ color="red"
+ link
+ name="close"
+ onClick={() => onClose()}
+ />
+ )}
</div>
</Header>
- {!folded && files && files.length > 0 && <List>
- <List.Item>
- <Table>
- <Table.Header>
- <Table.Row>
- <Table.HeaderCell className='filelist-selector'>
- <Checkbox
- fitted
- onChange={(event, data) => files.map(f => onSelectionChange(f, data.checked))}
- checked={files.filter(f => !f.selected).length === 0}
- disabled={disabled}
- />
- </Table.HeaderCell>
- <Table.HeaderCell className='filelist-filename'>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>
- {files.sort((a, b) => a.filename > b.filename ? 1 : -1).map((f, i) =>
- <Table.Row key={i}>
- <Table.Cell className='filelist-selector'>
+ {!folded && files && files.length > 0 && (
+ <List>
+ <List.Item>
+ <Table>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell className="filelist-selector">
<Checkbox
- fitted
- onChange={(event, data) => onSelectionChange(f, data.checked)}
- checked={f.selected}
+ checked={files.filter((f) => !f.selected).length === 0}
disabled={disabled}
+ fitted
+ onChange={(event, data) =>
+ files.map((f) => onSelectionChange(f, data.checked))
+ }
/>
- </Table.Cell>
- <Table.Cell className='filelist-filename'>
- {locked ? <Icon name='lock' /> : ''}{getFileName(f.filename)}
- </Table.Cell>
- <Table.Cell className='filelist-size'>{formatBytes(f.size)}</Table.Cell>
- <Table.Cell className='filelist-attributes'>{formatAttributes(f)}</Table.Cell>
- <Table.Cell className='filelist-length'>{formatSeconds(f.length)}</Table.Cell>
+ </Table.HeaderCell>
+ <Table.HeaderCell className="filelist-filename">
+ 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>
+ {files
+ .sort((a, b) => (a.filename > b.filename ? 1 : -1))
+ .map((f, index) => (
+ <Table.Row key={index}>
+ <Table.Cell className="filelist-selector">
+ <Checkbox
+ checked={f.selected}
+ disabled={disabled}
+ fitted
+ onChange={(event, data) =>
+ onSelectionChange(f, data.checked)
+ }
+ />
+ </Table.Cell>
+ <Table.Cell className="filelist-filename">
+ {locked ? <Icon name="lock" /> : ''}
+ {getFileName(f.filename)}
+ </Table.Cell>
+ <Table.Cell className="filelist-size">
+ {formatBytes(f.size)}
+ </Table.Cell>
+ <Table.Cell className="filelist-attributes">
+ {formatAttributes(f)}
+ </Table.Cell>
+ <Table.Cell className="filelist-length">
+ {formatSeconds(f.length)}
+ </Table.Cell>
+ </Table.Row>
+ ))}
+ </Table.Body>
+ {footer && (
+ <Table.Footer fullWidth>
+ <Table.Row>
+ <Table.HeaderCell colSpan="5">{footer}</Table.HeaderCell>
+ </Table.Row>
+ </Table.Footer>
)}
- </Table.Body>
- {footer && <Table.Footer fullWidth>
- <Table.Row>
- <Table.HeaderCell colSpan='5'>
- {footer}
- </Table.HeaderCell>
- </Table.Row>
- </Table.Footer>}
- </Table>
- </List.Item>
- </List>}
+ </Table>
+ </List.Item>
+ </List>
+ )}
</div>
);
};
diff --git a/src/web/src/components/Shared/LoaderSegment.jsx b/src/web/src/components/Shared/LoaderSegment.jsx
index cc3d598c..e78dd91f 100644
--- a/src/web/src/components/Shared/LoaderSegment.jsx
+++ b/src/web/src/components/Shared/LoaderSegment.jsx
@@ -1,11 +1,20 @@
import React from 'react';
+import { Loader, Segment } from 'semantic-ui-react';
-import { Segment, Loader } from 'semantic-ui-react';
-
-const LoaderSegment = ({ size = 'big', children, ...props }) => (
- <Segment className='loader-segment' placeholder basic>
- <Loader active size={size} {...props}>{children}</Loader>
+const LoaderSegment = ({ children, size = 'big', ...props }) => (
+ <Segment
+ basic
+ className="loader-segment"
+ placeholder
+ >
+ <Loader
+ active
+ size={size}
+ {...props}
+ >
+ {children}
+ </Loader>
</Segment>
);
-export default LoaderSegment; \ No newline at end of file
+export default LoaderSegment;
diff --git a/src/web/src/components/Shared/Logo.jsx b/src/web/src/components/Shared/Logo.jsx
index aff7cea6..e9ee9d52 100644
--- a/src/web/src/components/Shared/Logo.jsx
+++ b/src/web/src/components/Shared/Logo.jsx
@@ -1,14 +1,16 @@
-const Logos = [`
+const Logos = [
+ `
â–„â–„â–„â–„ â–„â–„â–„â–„ â–„â–„â–„â–„
▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
â–ˆ__ --â–ˆ â–ˆ__ --â–ˆ â—„â–ˆ - â–ˆ
█▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
`,
-`
+ `
â–„â–„â–„â–„ â–„â–„â–„â–„ â–„â–„â–„â–„
▄▄▄▄▄▄▄ █ █ ▄▄▄▄▄▄▄ █ █▄▄▄ ▄▄▄█ █
â–ˆ__ --â–ˆ â–ˆ â–ˆ â–ˆ__ --â–ˆ â–ˆ â—„â–ˆ â–ˆ - â–ˆ
█▄▄▄▄▄█ █▄▄█ █▄▄▄▄▄█ █▄▄█▄▄█ █▄▄▄▄▄█
-`];
+`,
+];
-export default Logos; \ No newline at end of file
+export default Logos;
diff --git a/src/web/src/components/Shared/Nbsp.jsx b/src/web/src/components/Shared/Nbsp.jsx
index 24f725fa..c1ba31c3 100644
--- a/src/web/src/components/Shared/Nbsp.jsx
+++ b/src/web/src/components/Shared/Nbsp.jsx
@@ -2,4 +2,4 @@ const Nbsp = () => {
return ' ';
};
-export default Nbsp; \ No newline at end of file
+export default Nbsp;
diff --git a/src/web/src/components/Shared/PlaceholderSegment.jsx b/src/web/src/components/Shared/PlaceholderSegment.jsx
index 31ac8e9e..c2b204f0 100644
--- a/src/web/src/components/Shared/PlaceholderSegment.jsx
+++ b/src/web/src/components/Shared/PlaceholderSegment.jsx
@@ -1,17 +1,23 @@
import React from 'react';
+import { Header, Icon, Segment } from 'semantic-ui-react';
-import { Segment, Header, Icon } from 'semantic-ui-react';
-
-const PlaceholderSegment = ({ icon, caption, size, ...rest }) => {
- const className = size === 'small' ? 'placeholder-segment-small' : 'placeholder-segment';
+const PlaceholderSegment = ({ caption, icon, size, ...rest }) => {
+ const className =
+ size === 'small' ? 'placeholder-segment-small' : 'placeholder-segment';
return (
- <Segment className={className} placeholder basic {...rest}>
+ <Segment
+ basic
+ className={className}
+ placeholder
+ {...rest}
+ >
<Header icon>
- <Icon name={icon}/>
+ <Icon name={icon} />
{caption}
</Header>
- </Segment>);
+ </Segment>
+ );
};
-export default PlaceholderSegment; \ No newline at end of file
+export default PlaceholderSegment;
diff --git a/src/web/src/components/Shared/ShrinkableButton.jsx b/src/web/src/components/Shared/ShrinkableButton.jsx
index 67c9f660..7c11fe6f 100644
--- a/src/web/src/components/Shared/ShrinkableButton.jsx
+++ b/src/web/src/components/Shared/ShrinkableButton.jsx
@@ -1,15 +1,17 @@
import React from 'react';
-
import { useMediaQuery } from 'react-responsive';
import { Button, Icon, Popup } from 'semantic-ui-react';
-const ShrinkableButton = ({ icon, loading, mediaQuery, children, ...rest }) => {
+const ShrinkableButton = ({ children, icon, loading, mediaQuery, ...rest }) => {
const shouldShrink = useMediaQuery({ query: mediaQuery });
if (!shouldShrink) {
return (
<Button {...rest}>
- <Icon name={icon} loading={loading}/>
+ <Icon
+ loading={loading}
+ name={icon}
+ />
{children}
</Button>
);
@@ -19,12 +21,18 @@ const ShrinkableButton = ({ icon, loading, mediaQuery, children, ...rest }) => {
<Popup
content={children}
trigger={
- <Button icon {...rest}>
- <Icon name={icon} loading={loading}/>
+ <Button
+ icon
+ {...rest}
+ >
+ <Icon
+ loading={loading}
+ name={icon}
+ />
</Button>
}
/>
);
};
-export default ShrinkableButton; \ No newline at end of file
+export default ShrinkableButton;
diff --git a/src/web/src/components/Shared/ShrinkableDropdownButton.jsx b/src/web/src/components/Shared/ShrinkableDropdownButton.jsx
index bdf6b3a1..008e93bd 100644
--- a/src/web/src/components/Shared/ShrinkableDropdownButton.jsx
+++ b/src/web/src/components/Shared/ShrinkableDropdownButton.jsx
@@ -1,23 +1,18 @@
-import React from 'react';
-
-import {
- Button,
- Dropdown,
-} from 'semantic-ui-react';
-
import ShrinkableButton from './ShrinkableButton';
+import React from 'react';
+import { Button, Dropdown } from 'semantic-ui-react';
-const ShrinkableDropdownButton = ({
- color,
- icon,
- mediaQuery,
- disabled,
- loading,
- options,
- onClick,
- onChange,
- hidden,
+const ShrinkableDropdownButton = ({
children,
+ color,
+ disabled,
+ hidden,
+ icon,
+ loading,
+ mediaQuery,
+ onChange,
+ onClick,
+ options,
}) => {
if (hidden) {
return <></>;
@@ -26,21 +21,23 @@ const ShrinkableDropdownButton = ({
return (
<Button.Group color={color}>
<ShrinkableButton
- icon={icon}
- onClick={onClick}
- mediaQuery={mediaQuery}
disabled={disabled}
+ icon={icon}
loading={loading}
- >{children}</ShrinkableButton>
+ mediaQuery={mediaQuery}
+ onClick={onClick}
+ >
+ {children}
+ </ShrinkableButton>
<Dropdown
+ className="button icon"
disabled={disabled}
- className='button icon'
- options={options}
onChange={onChange}
+ options={options}
trigger={<></>}
/>
</Button.Group>
);
};
-export default ShrinkableDropdownButton; \ No newline at end of file
+export default ShrinkableDropdownButton;
diff --git a/src/web/src/components/Shared/Switch.jsx b/src/web/src/components/Shared/Switch.jsx
index 7dad342f..d0c0f1f3 100644
--- a/src/web/src/components/Shared/Switch.jsx
+++ b/src/web/src/components/Shared/Switch.jsx
@@ -1,11 +1,11 @@
const Switch = ({ children, ...rest }) => {
const values = Object.values(rest);
- for (let i = 0; i < values.length; i++) {
- if (values[i]) return values[i];
+ for (const value of values) {
+ if (value) return value;
}
return children;
};
-export default Switch; \ No newline at end of file
+export default Switch;
diff --git a/src/web/src/components/Shared/index.js b/src/web/src/components/Shared/index.js
index e9c9128d..0e36bc48 100644
--- a/src/web/src/components/Shared/index.js
+++ b/src/web/src/components/Shared/index.js
@@ -7,4 +7,4 @@ export { default as Nbsp } from './Nbsp';
export { default as PlaceholderSegment } from './PlaceholderSegment';
export { default as ShrinkableButton } from './ShrinkableButton';
export { default as ShrinkableDropdownButton } from './ShrinkableDropdownButton';
-export { default as Switch } from './Switch'; \ No newline at end of file
+export { default as Switch } from './Switch';
diff --git a/src/web/src/components/System/Data/index.jsx b/src/web/src/components/System/Data/index.jsx
index 742aa309..1df4f981 100644
--- a/src/web/src/components/System/Data/index.jsx
+++ b/src/web/src/components/System/Data/index.jsx
@@ -1,8 +1,7 @@
+import { clearCompleted } from '../../../lib/transfers';
import React, { useState } from 'react';
-import { Button, Divider, Header, Icon } from 'semantic-ui-react';
import { toast } from 'react-toastify';
-
-import { clearCompleted } from '../../../lib/transfers';
+import { Button, Divider, Header, Icon } from 'semantic-ui-react';
const Data = () => {
const [up, setUp] = useState(false);
@@ -17,30 +16,38 @@ const Data = () => {
return (
<div>
- <Header as='h3' className='transfer-header'>Transfer Data</Header>
- <Divider/>
- <p><span>
- The Uploads and Downloads pages can become unresponsive if too many transfers are displayed. If you're having
- trouble with either page, try using the buttons below to remove completed transfers.
- </span></p>
+ <Header
+ as="h3"
+ className="transfer-header"
+ >
+ Transfer Data
+ </Header>
+ <Divider />
+ <p>
+ <span>
+ The Uploads and Downloads pages can become unresponsive if too many
+ transfers are displayed. If you're having trouble with either page,
+ try using the buttons below to remove completed transfers.
+ </span>
+ </p>
<Button
- primary
loading={up}
onClick={() => clear({ direction: 'upload', setState: setUp })}
+ primary
>
- <Icon name='trash alternate'/>
+ <Icon name="trash alternate" />
Clear All Completed Uploads
</Button>
<Button
- primary
loading={down}
onClick={() => clear({ direction: 'download', setState: setDown })}
+ primary
>
- <Icon name='trash alternate'/>
+ <Icon name="trash alternate" />
Clear All Completed Downloads
</Button>
</div>
);
};
-export default Data; \ No newline at end of file
+export default Data;
diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx
index 77b2f958..6b677144 100644
--- a/src/web/src/components/System/Files/Explorer.jsx
+++ b/src/web/src/components/System/Files/Explorer.jsx
@@ -1,25 +1,18 @@
-import React, { useState, useEffect } from 'react';
-
-import {
- Table,
- Icon,
- Modal,
- Header,
-} from 'semantic-ui-react';
-
-import { list, deleteDirectory, deleteFile } from '../../../lib/files';
+import { deleteDirectory, deleteFile, list } from '../../../lib/files';
import { formatBytes, formatDate } from '../../../lib/util';
import { LoaderSegment } from '../../Shared';
+import React, { useEffect, useState } from 'react';
+import { Header, Icon, Modal, Table } from 'semantic-ui-react';
-const Explorer = ({ root, remoteFileManagement }) => {
- const [directory, setDirectory] = useState({ files: [], directories: [] });
+const Explorer = ({ remoteFileManagement, root }) => {
+ const [directory, setDirectory] = useState({ directories: [], files: [] });
const [subdirectory, setSubdirectory] = useState([]);
const [loading, setLoading] = useState(false);
-
+
useEffect(() => {
fetch();
}, [subdirectory]); // eslint-disable-line react-hooks/exhaustive-deps
-
+
useEffect(() => {
setSubdirectory([]);
}, [root]);
@@ -41,115 +34,188 @@ const Explorer = ({ root, remoteFileManagement }) => {
setSubdirectory(copy);
};
- const FileRow = ({ name, fullName, modifiedAt, length }) => <Table.Row key={fullName}>
- <Table.Cell><Icon name='file outline'/>{name}</Table.Cell>
- <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell>
- <Table.Cell>{length ? formatBytes(length) : ''}</Table.Cell>
- <Table.Cell>
- {remoteFileManagement
- ? <Modal
- trigger={
- <Icon name="trash alternate" color="red" style={{ cursor: 'pointer' }}/>
- }
- centered
- size='small'
- header={<Header icon='trash alternate' content='Confirm File Delete' />}
- content={`Are you sure you want to delete file '${fullName}'?`}
- actions={[
- 'Cancel',
- {
- key: 'done',
- content: 'Delete',
- negative: true,
- onClick: async () => {
- await deleteFile({ root, path: `${subdirectory.join('/')}/${fullName}`});
- fetch();
+ const FileRow = ({ fullName, length, modifiedAt, name }) => (
+ <Table.Row key={fullName}>
+ <Table.Cell>
+ <Icon name="file outline" />
+ {name}
+ </Table.Cell>
+ <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell>
+ <Table.Cell>{length ? formatBytes(length) : ''}</Table.Cell>
+ <Table.Cell>
+ {remoteFileManagement ? (
+ <Modal
+ actions={[
+ 'Cancel',
+ {
+ content: 'Delete',
+ key: 'done',
+ negative: true,
+ onClick: async () => {
+ await deleteFile({
+ path: `${subdirectory.join('/')}/${fullName}`,
+ root,
+ });
+ fetch();
+ },
},
- },
- ]}/>
- : <></>}
- </Table.Cell>
- </Table.Row>;
+ ]}
+ centered
+ content={`Are you sure you want to delete file '${fullName}'?`}
+ header={
+ <Header
+ content="Confirm File Delete"
+ icon="trash alternate"
+ />
+ }
+ size="small"
+ trigger={
+ <Icon
+ color="red"
+ name="trash alternate"
+ style={{ cursor: 'pointer' }}
+ />
+ }
+ />
+ ) : (
+ <></>
+ )}
+ </Table.Cell>
+ </Table.Row>
+ );
const DirectoryRow = ({
- name,
+ deletable = true,
fullName,
modifiedAt,
+ name,
onClick = () => {},
- deletable = true,
- }) => <Table.Row key={name}>
- <Table.Cell
- style={{ cursor: 'pointer' }}
- onClick={onClick}
- ><Icon name='folder'/>{name}</Table.Cell>
- <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell>
- <Table.Cell></Table.Cell>
- <Table.Cell>
- {remoteFileManagement && deletable
- ? <Modal
- trigger={
- <Icon name="trash alternate" color="red" style={{ cursor: 'pointer' }}/>
- }
- centered
- size='small'
- header={<Header icon='trash alternate' content='Confirm Directory Delete' />}
- content={`Are you sure you want to delete directory '${fullName}'?`}
- actions={[
- 'Cancel',
- {
- key: 'done',
- content: 'Delete',
- negative: true,
- onClick: async () => {
- await deleteDirectory({ root, path: `${subdirectory.join('/')}/${fullName}`});
- fetch();
+ }) => (
+ <Table.Row key={name}>
+ <Table.Cell
+ onClick={onClick}
+ style={{ cursor: 'pointer' }}
+ >
+ <Icon name="folder" />
+ {name}
+ </Table.Cell>
+ <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell>
+ <Table.Cell />
+ <Table.Cell>
+ {remoteFileManagement && deletable ? (
+ <Modal
+ actions={[
+ 'Cancel',
+ {
+ content: 'Delete',
+ key: 'done',
+ negative: true,
+ onClick: async () => {
+ await deleteDirectory({
+ path: `${subdirectory.join('/')}/${fullName}`,
+ root,
+ });
+ fetch();
+ },
},
- },
- ]}
- />
- : ''}
- </Table.Cell>
- </Table.Row>;
+ ]}
+ centered
+ content={`Are you sure you want to delete directory '${fullName}'?`}
+ header={
+ <Header
+ content="Confirm Directory Delete"
+ icon="trash alternate"
+ />
+ }
+ size="small"
+ trigger={
+ <Icon
+ color="red"
+ name="trash alternate"
+ style={{ cursor: 'pointer' }}
+ />
+ }
+ />
+ ) : (
+ ''
+ )}
+ </Table.Cell>
+ </Table.Row>
+ );
if (loading) {
- return <LoaderSegment/>;
+ return <LoaderSegment />;
}
const total = directory?.directories?.length + directory?.files?.length ?? 0;
return (
<>
- <Header size='small' className='explorer-working-directory'>
- <Icon name='folder open'/>{'/' + root + '/' + subdirectory.join('/')}
+ <Header
+ className="explorer-working-directory"
+ size="small"
+ >
+ <Icon name="folder open" />
+ {'/' + root + '/' + subdirectory.join('/')}
</Header>
- <Table size='large' className='unstackable'>
+ <Table
+ className="unstackable"
+ size="large"
+ >
<Table.Header>
<Table.Row>
- <Table.HeaderCell className="explorer-list-name">Name</Table.HeaderCell>
- <Table.HeaderCell className="explorer-list-date">Date Modified</Table.HeaderCell>
- <Table.HeaderCell className="explorer-list-size">Size</Table.HeaderCell>
- <Table.HeaderCell className="explorer-list-action"></Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-name">
+ Name
+ </Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-date">
+ Date Modified
+ </Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-size">
+ Size
+ </Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-action" />
</Table.Row>
</Table.Header>
<Table.Body>
- {total === 0
- ? <Table.Row>
- <Table.Cell colSpan={99} style={{ opacity: .5, padding: '10px !important', textAlign: 'center' }}>
+ {total === 0 ? (
+ <Table.Row>
+ <Table.Cell
+ colSpan={99}
+ style={{
+ opacity: 0.5,
+ padding: '10px !important',
+ textAlign: 'center',
+ }}
+ >
No files or directories
</Table.Cell>
</Table.Row>
- : <>
- {subdirectory.length > 0
- && <DirectoryRow name=".." fullName=".." onClick={upOneSubdirectory} deletable={false}/>}
- {directory?.directories?.map(d => <DirectoryRow
- key={d.name} onClick={() => select({ path: d.name })} {...d}/>)}
- {directory?.files?.map(f => <FileRow {...f}/>)}
+ ) : (
+ <>
+ {subdirectory.length > 0 && (
+ <DirectoryRow
+ deletable={false}
+ fullName=".."
+ name=".."
+ onClick={upOneSubdirectory}
+ />
+ )}
+ {directory?.directories?.map((d) => (
+ <DirectoryRow
+ key={d.name}
+ onClick={() => select({ path: d.name })}
+ {...d}
+ />
+ ))}
+ {directory?.files?.map((f) => (
+ <FileRow {...f} />
+ ))}
</>
- }
+ )}
</Table.Body>
</Table>
</>
);
};
-export default Explorer; \ No newline at end of file
+export default Explorer;
diff --git a/src/web/src/components/System/Files/index.jsx b/src/web/src/components/System/Files/index.jsx
index a7a90aba..5b177452 100644
--- a/src/web/src/components/System/Files/index.jsx
+++ b/src/web/src/components/System/Files/index.jsx
@@ -1,32 +1,43 @@
-import React from 'react';
-import { Tab } from 'semantic-ui-react';
-
import './Files.css';
import Explorer from './Explorer';
+import React from 'react';
+import { Tab } from 'semantic-ui-react';
const Files = ({ options } = {}) => {
const { remoteFileManagement } = options;
const panes = [
- {
- route: 'downloads',
+ {
menuItem: 'Downloads',
- render: () => <Tab.Pane><Explorer root={'downloads'} remoteFileManagement={remoteFileManagement}/></Tab.Pane>,
+ render: () => (
+ <Tab.Pane>
+ <Explorer
+ remoteFileManagement={remoteFileManagement}
+ root="downloads"
+ />
+ </Tab.Pane>
+ ),
+ route: 'downloads',
},
- {
- route: 'incomplete',
+ {
menuItem: 'Incomplete',
- render: () => <Tab.Pane><Explorer root={'incomplete'} remoteFileManagement={remoteFileManagement}/></Tab.Pane>,
+ render: () => (
+ <Tab.Pane>
+ <Explorer
+ remoteFileManagement={remoteFileManagement}
+ root="incomplete"
+ />
+ </Tab.Pane>
+ ),
+ route: 'incomplete',
},
];
return (
<div>
- <Tab
- panes={panes}
- />
+ <Tab panes={panes} />
</div>
);
};
-export default Files; \ No newline at end of file
+export default Files;
diff --git a/src/web/src/components/System/Info/index.jsx b/src/web/src/components/System/Info/index.jsx
index 2793ee0d..8672b5df 100644
--- a/src/web/src/components/System/Info/index.jsx
+++ b/src/web/src/components/System/Info/index.jsx
@@ -1,23 +1,22 @@
-import React, { useState, useEffect } from 'react';
-import YAML from 'yaml';
-
-import { restart, shutdown, getVersion } from '../../../lib/application';
-
-import { Modal, Header, Divider } from 'semantic-ui-react';
-
+import { getVersion, restart, shutdown } from '../../../lib/application';
import {
CodeEditor,
LoaderSegment,
ShrinkableButton,
Switch,
} from '../../Shared';
+import React, { useEffect, useState } from 'react';
+import { Divider, Header, Modal } from 'semantic-ui-react';
+import YAML from 'yaml';
const Info = ({ state, theme }) => {
const [contents, setContents] = useState();
useEffect(() => {
setTimeout(() => {
- setContents(YAML.stringify(state, { simpleKeys: true, sortMapEntries: false }));
+ setContents(
+ YAML.stringify(state, { simpleKeys: true, sortMapEntries: false }),
+ );
}, 250);
}, [state]);
@@ -25,77 +24,105 @@ const Info = ({ state, theme }) => {
return (
<>
- <div className='header-buttons'>
- <div style={{float: 'left'}}>
+ <div className="header-buttons">
+ <div style={{ float: 'left' }}>
<ShrinkableButton
- icon='refresh'
- mediaQuery='(max-width: 686px)'
- primary
disabled={!contents}
+ icon="refresh"
+ mediaQuery="(max-width: 686px)"
onClick={() => getVersion({ forceCheck: true })}
+ primary
>
Check for Updates
</ShrinkableButton>
<ShrinkableButton
- icon='star'
- mediaQuery='(max-width: 686px)'
- color='yellow'
+ color="yellow"
disabled={!contents}
- onClick={() =>
- window.open(`http://www.slsknet.org/qtlogin.php?username=${state?.user?.username}`, '_blank')}
+ icon="star"
+ mediaQuery="(max-width: 686px)"
+ onClick={() =>
+ window.open(
+ `http://www.slsknet.org/qtlogin.php?username=${state?.user?.username}`,
+ '_blank',
+ )
+ }
>
Get Privileges
</ShrinkableButton>
</div>
<Modal
+ actions={[
+ 'Cancel',
+ {
+ content: 'Shut Down',
+ key: 'done',
+ negative: true,
+ onClick: shutdown,
+ },
+ ]}
+ centered
+ content="Are you sure you want to shut the application down? You'll need to manually start it again."
+ header={
+ <Header
+ content="Confirm Shutdown"
+ icon="redo"
+ />
+ }
+ size="mini"
trigger={
<ShrinkableButton
- icon='shutdown'
- mediaQuery='(max-width: 686px)'
- negative
disabled={!contents}
+ icon="shutdown"
+ mediaQuery="(max-width: 686px)"
+ negative
>
Shut Down
</ShrinkableButton>
}
- centered
- size='mini'
- header={<Header icon='redo' content='Confirm Shutdown' />}
- content="Are you sure you want to shut the application down? You'll need to manually start it again."
- actions={['Cancel', { key: 'done', content: 'Shut Down', negative: true, onClick: shutdown }]}
/>
<Modal
+ actions={[
+ 'Cancel',
+ {
+ content: 'Restart',
+ key: 'done',
+ negative: true,
+ onClick: restart,
+ },
+ ]}
+ centered
+ content="Are you sure you want restart the application?"
+ header={
+ <Header
+ content="Confirm Restart"
+ icon="redo"
+ />
+ }
+ size="mini"
trigger={
<ShrinkableButton
- icon='redo'
- mediaQuery='(max-width: 686px)'
- negative={!pendingRestart}
color={pendingRestart ? 'yellow' : undefined}
disabled={!contents}
+ icon="redo"
+ mediaQuery="(max-width: 686px)"
+ negative={!pendingRestart}
>
Restart
</ShrinkableButton>
}
- centered
- size='mini'
- header={<Header icon='redo' content='Confirm Restart' />}
- content='Are you sure you want restart the application?'
- actions={['Cancel', { key: 'done', content: 'Restart', negative: true, onClick: restart }]}
/>
</div>
- <Divider/>
- <Switch
- loading={!contents && <LoaderSegment/>}
- >
+ <Divider />
+ <Switch loading={!contents && <LoaderSegment />}>
<CodeEditor
- value={contents}
basicSetup={false}
editable={false}
theme={theme}
+ value={contents}
/>
</Switch>
</>
);
};
-export default Info; \ No newline at end of file
+export default Info;
diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx
index b30b0a43..3c199f42 100644
--- a/src/web/src/components/System/Logs/index.jsx
+++ b/src/web/src/components/System/Logs/index.jsx
@@ -1,21 +1,19 @@
-import React, { Component } from 'react';
-import { Table } from 'semantic-ui-react';
-
+import '../System.css';
import { createLogsHubConnection } from '../../../lib/hubFactory';
import { LoaderSegment } from '../../Shared';
-
-import '../System.css';
+import React, { Component } from 'react';
+import { Table } from 'semantic-ui-react';
const initialState = {
- logs: [],
connected: false,
+ logs: [],
};
const levels = {
- 'Debug': 'DBG',
- 'Warning': 'WRN',
- 'Error': 'ERR',
- 'Information': 'INF',
+ Debug: 'DBG',
+ Error: 'ERR',
+ Information: 'INF',
+ Warning: 'WRN',
};
const maxLogs = 500;
@@ -23,15 +21,21 @@ const maxLogs = 500;
class Logs extends Component {
state = initialState;
- componentDidMount = () => {
+ componentDidMount() {
const logsHub = createLogsHubConnection();
logsHub.on('buffer', (buffer) => {
- this.setState({ connected: true, logs: buffer.reverse().slice(0, maxLogs) });
+ this.setState({
+ connected: true,
+ logs: buffer.reverse().slice(0, maxLogs),
+ });
});
logsHub.on('log', (log) => {
- this.setState({ connected: true, logs: [log].concat(this.state.logs).slice(0, maxLogs) });
+ this.setState({
+ connected: true,
+ logs: [log].concat(this.state.logs).slice(0, maxLogs),
+ });
});
logsHub.onreconnecting(() => this.setState({ connected: false }));
@@ -39,21 +43,24 @@ class Logs extends Component {
logsHub.onreconnected(() => this.setState({ connected: true }));
logsHub.start();
- };
+ }
formatTimestamp = (timestamp) => {
const date = new Date(timestamp);
return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len
};
- render = () => {
+ render() {
const { connected, logs } = this.state;
return (
- <div className='logs'>
- {!connected && <LoaderSegment/>}
- {connected &&
- <Table compact='very' className='logs-table'>
+ <div className="logs">
+ {!connected && <LoaderSegment />}
+ {connected && (
+ <Table
+ className="logs-table"
+ compact="very"
+ >
<Table.Header>
<Table.Row>
<Table.HeaderCell>Timestamp</Table.HeaderCell>
@@ -61,24 +68,27 @@ class Logs extends Component {
<Table.HeaderCell>Message</Table.HeaderCell>
</Table.Row>
</Table.Header>
- <Table.Body className='logs-table-body'>
- {logs.map((log, index) =>
+ <Table.Body className="logs-table-body">
+ {logs.map((log, index) => (
<Table.Row
- key={index}
disabled={log.level === 'Debug'}
- warning={log.level === 'Warning'}
+ key={index}
negative={log.level === 'Error'}
+ warning={log.level === 'Warning'}
>
<Table.Cell>{this.formatTimestamp(log.timestamp)}</Table.Cell>
<Table.Cell>{levels[log.level] || log.level}</Table.Cell>
- <Table.Cell className='logs-table-message'>{log.message}</Table.Cell>
- </Table.Row>)}
+ <Table.Cell className="logs-table-message">
+ {log.message}
+ </Table.Cell>
+ </Table.Row>
+ ))}
</Table.Body>
</Table>
- }
+ )}
</div>
);
- };
+ }
}
-export default Logs; \ No newline at end of file
+export default Logs;
diff --git a/src/web/src/components/System/Options/DebugModal.jsx b/src/web/src/components/System/Options/DebugModal.jsx
index 02551f1b..2a1b8c5f 100644
--- a/src/web/src/components/System/Options/DebugModal.jsx
+++ b/src/web/src/components/System/Options/DebugModal.jsx
@@ -1,16 +1,10 @@
-import React, { useState, useEffect } from 'react';
-import { toast } from 'react-toastify';
-
-import {
- Modal,
- Button,
- Icon,
-} from 'semantic-ui-react';
-
import { getCurrentDebugView } from '../../../lib/options';
import { CodeEditor, PlaceholderSegment, Switch } from '../../Shared';
+import React, { useEffect, useState } from 'react';
+import { toast } from 'react-toastify';
+import { Button, Icon, Modal } from 'semantic-ui-react';
-const DebugModal = ({ open, theme, onClose }) => {
+const DebugModal = ({ onClose, open, theme }) => {
const [loading, setLoading] = useState(true);
const [debugView, setDebugView] = useState();
@@ -32,36 +26,36 @@ const DebugModal = ({ open, theme, onClose }) => {
setLoading(false);
}
};
-
- return (
+
+ return (
<Modal
- size='large'
- open={open}
onClose={onClose}
+ open={open}
+ size="large"
>
<Modal.Header>
- <Icon name='bug'/>
+ <Icon name="bug" />
Options (Debug View)
</Modal.Header>
- <Modal.Content className='debug-view-content' scrolling>
- <Switch
- loading={loading && <PlaceholderSegment loading={true} />}
- >
+ <Modal.Content
+ className="debug-view-content"
+ scrolling
+ >
+ <Switch loading={loading && <PlaceholderSegment loading />}>
<CodeEditor
- style={{minHeight: 500}}
- value={debugView}
basicSetup={false}
editable={false}
+ style={{ minHeight: 500 }}
theme={theme}
+ value={debugView}
/>
</Switch>
</Modal.Content>
<Modal.Actions>
- <Button onClick={onClose}>
- Close
- </Button>
+ <Button onClick={onClose}>Close</Button>
</Modal.Actions>
- </Modal>);
+ </Modal>
+ );
};
-export default DebugModal; \ No newline at end of file
+export default DebugModal;
diff --git a/src/web/src/components/System/Options/EditModal.jsx b/src/web/src/components/System/Options/EditModal.jsx
index c3f54114..f2a23e4a 100644
--- a/src/web/src/components/System/Options/EditModal.jsx
+++ b/src/web/src/components/System/Options/EditModal.jsx
@@ -1,18 +1,24 @@
-import React, { useState, useEffect } from 'react';
-
-import { Button, Icon, Message, Modal } from 'semantic-ui-react';
-import CodeEditor from '../../Shared/CodeEditor';
-
-import { getYamlLocation, getYaml, validateYaml, updateYaml } from '../../../lib/options';
import {
- PlaceholderSegment,
- Switch,
- Div,
-} from '../../Shared';
+ getYaml,
+ getYamlLocation,
+ updateYaml,
+ validateYaml,
+} from '../../../lib/options';
+import { Div, PlaceholderSegment, Switch } from '../../Shared';
+import CodeEditor from '../../Shared/CodeEditor';
+import React, { useEffect, useState } from 'react';
+import { Button, Icon, Message, Modal } from 'semantic-ui-react';
-const EditModal = ({ open, theme, onClose }) => {
- const [{ loading, error }, setLoading] = useState({ loading: true, error: false });
- const [{ location, yaml, isDirty }, setYaml] = useState({ location: undefined, yaml: undefined, isDirty: false });
+const EditModal = ({ onClose, open, theme }) => {
+ const [{ error, loading }, setLoading] = useState({
+ error: false,
+ loading: true,
+ });
+ const [{ isDirty, location, yaml }, setYaml] = useState({
+ isDirty: false,
+ location: undefined,
+ yaml: undefined,
+ });
const [yamlError, setYamlError] = useState();
const [updateError, setUpdateError] = useState();
@@ -23,20 +29,23 @@ const EditModal = ({ open, theme, onClose }) => {
}, [open]);
const get = async () => {
- setLoading({ loading: true, error: false });
+ setLoading({ error: false, loading: true });
try {
- const [location, yaml] = await Promise.all([getYamlLocation(), getYaml()]);
+ const [location, yaml] = await Promise.all([
+ getYamlLocation(),
+ getYaml(),
+ ]);
- setYaml({ location, yaml, isDirty: false });
- setLoading({ loading: false, error: false });
+ setYaml({ isDirty: false, location, yaml });
+ setLoading({ error: false, loading: false });
} catch (error) {
- setLoading({ loading: false, error: error.message });
+ setLoading({ error: error.message, loading: false });
}
};
const update = async (yaml) => {
- setYaml({ location, yaml, isDirty: true });
+ setYaml({ isDirty: true, location, yaml });
validate(yaml);
};
@@ -52,8 +61,7 @@ const EditModal = ({ open, theme, onClose }) => {
try {
await updateYaml({ yaml });
onClose();
- }
- catch (error) {
+ } catch (error) {
setUpdateError(error.response.data);
}
}
@@ -61,46 +69,76 @@ const EditModal = ({ open, theme, onClose }) => {
return (
<Modal
- size='large'
- open={open}
onClose={onClose}
+ open={open}
+ size="large"
>
<Modal.Header>
- <Icon name='edit'/>
+ <Icon name="edit" />
Edit Options
<Div hidden={loading}>
- <Message className='no-grow edit-code-header' warning>
- <Icon name='warning sign'/>Editing {location}
+ <Message
+ className="no-grow edit-code-header"
+ warning
+ >
+ <Icon name="warning sign" />
+ Editing {location}
</Message>
</Div>
</Modal.Header>
- <Modal.Content className='edit-code-content' scrolling>
+ <Modal.Content
+ className="edit-code-content"
+ scrolling
+ >
<Switch
- loading={loading && <PlaceholderSegment loading={true}/>}
- error={error && <PlaceholderSegment icon='close'/>}
+ error={error && <PlaceholderSegment icon="close" />}
+ loading={loading && <PlaceholderSegment loading />}
>
- <div
- {...{ className: (yamlError || updateError) ? 'edit-code-container-error' : 'edit-code-container' }}
+ <div
+ {...{
+ className:
+ yamlError || updateError
+ ? 'edit-code-container-error'
+ : 'edit-code-container',
+ }}
>
<CodeEditor
- style={{minHeight: 500}}
- value={yaml}
onChange={(value) => update(value)}
+ style={{ minHeight: 500 }}
theme={theme}
+ value={yaml}
/>
</div>
</Switch>
</Modal.Content>
<Modal.Actions>
- {(yamlError || updateError) &&
- <Message className='no-grow left-align' negative>
- <Icon name='x' />{(yamlError ?? '') + (updateError ?? '')}
- </Message>}
- <Button primary disabled={!isDirty} onClick={() => save(yaml)}><Icon name='save'/>Save</Button>
- <Button negative onClick={onClose}><Icon name='close'/>Cancel</Button>
+ {(yamlError || updateError) && (
+ <Message
+ className="no-grow left-align"
+ negative
+ >
+ <Icon name="x" />
+ {(yamlError ?? '') + (updateError ?? '')}
+ </Message>
+ )}
+ <Button
+ disabled={!isDirty}
+ onClick={() => save(yaml)}
+ primary
+ >
+ <Icon name="save" />
+ Save
+ </Button>
+ <Button
+ negative
+ onClick={onClose}
+ >
+ <Icon name="close" />
+ Cancel
+ </Button>
</Modal.Actions>
</Modal>
);
};
-export default EditModal; \ No newline at end of file
+export default EditModal;
diff --git a/src/web/src/components/System/Options/index.jsx b/src/web/src/components/System/Options/index.jsx
index cf6f49ab..9e842fc9 100644
--- a/src/web/src/components/System/Options/index.jsx
+++ b/src/web/src/components/System/Options/index.jsx
@@ -1,16 +1,14 @@
-import React, { useState, useEffect } from 'react';
-import YAML from 'yaml';
-
-import DebugModal from './DebugModal';
-import EditModal from './EditModal';
-
-import { Divider } from 'semantic-ui-react';
import {
CodeEditor,
LoaderSegment,
ShrinkableButton,
Switch,
} from '../../Shared';
+import DebugModal from './DebugModal';
+import EditModal from './EditModal';
+import React, { useEffect, useState } from 'react';
+import { Divider } from 'semantic-ui-react';
+import YAML from 'yaml';
const Index = ({ options, theme }) => {
const [debugModal, setDebugModal] = useState(false);
@@ -19,72 +17,82 @@ const Index = ({ options, theme }) => {
useEffect(() => {
setTimeout(() => {
- setContents(YAML.stringify(options, { simpleKeys: true, sortMapEntries: false }));
+ setContents(
+ YAML.stringify(options, { simpleKeys: true, sortMapEntries: false }),
+ );
}, 250);
}, [options]);
-
- const { remoteConfiguration, debug } = options;
+
+ const { debug, remoteConfiguration } = options;
const DebugButton = ({ ...props }) => {
if (!remoteConfiguration || !debug) return <></>;
-
- return <ShrinkableButton
- icon='bug'
- mediaQuery='(max-width: 516px)'
- onClick={() => setDebugModal(true)}
- {...props}
- >
- Debug View
- </ShrinkableButton>;
+
+ return (
+ <ShrinkableButton
+ icon="bug"
+ mediaQuery="(max-width: 516px)"
+ onClick={() => setDebugModal(true)}
+ {...props}
+ >
+ Debug View
+ </ShrinkableButton>
+ );
};
const EditButton = ({ ...props }) => {
if (!remoteConfiguration) {
- return <ShrinkableButton
- disabled
- icon='lock'
- mediaQuery='(max-width: 516px)'
- >Remote Configuration Disabled</ShrinkableButton>;
+ return (
+ <ShrinkableButton
+ disabled
+ icon="lock"
+ mediaQuery="(max-width: 516px)"
+ >
+ Remote Configuration Disabled
+ </ShrinkableButton>
+ );
}
- return <ShrinkableButton
- primary
- icon='edit'
- mediaQuery='(max-width: 516px)'
- onClick={() => setEditModal(true)}
- {...props}
- >Edit</ShrinkableButton>;
+ return (
+ <ShrinkableButton
+ icon="edit"
+ mediaQuery="(max-width: 516px)"
+ onClick={() => setEditModal(true)}
+ primary
+ {...props}
+ >
+ Edit
+ </ShrinkableButton>
+ );
};
return (
<>
- <div className='header-buttons'>
- <DebugButton disabled={!contents}/>
- <EditButton disabled={!contents}/>
+ <div className="header-buttons">
+ <DebugButton disabled={!contents} />
+ <EditButton disabled={!contents} />
</div>
- <Divider/>
- <Switch
- loading={!contents && <LoaderSegment/>}
- >
+ <Divider />
+ <Switch loading={!contents && <LoaderSegment />}>
<CodeEditor
- value={contents}
basicSetup={false}
editable={false}
theme={theme}
+ value={contents}
/>
</Switch>
<DebugModal
+ onClose={() => setDebugModal(false)}
open={debugModal}
theme={theme}
- onClose={() => setDebugModal(false)}
/>
<EditModal
+ onClose={() => setEditModal(false)}
open={editModal}
theme={theme}
- onClose={() => setEditModal(false)}
/>
</>
);
};
-export default Index; \ No newline at end of file
+export default Index;
diff --git a/src/web/src/components/System/Shares/ContentsModal.jsx b/src/web/src/components/System/Shares/ContentsModal.jsx
index f0642ef8..45030672 100644
--- a/src/web/src/components/System/Shares/ContentsModal.jsx
+++ b/src/web/src/components/System/Shares/ContentsModal.jsx
@@ -1,19 +1,10 @@
-import React, { useEffect, useState } from 'react';
-import { orderBy } from 'lodash';
-
import { browse } from '../../../lib/shares';
+import { CodeEditor, LoaderSegment, Switch } from '../../Shared';
+import { orderBy } from 'lodash';
+import React, { useEffect, useState } from 'react';
+import { Button, Icon, Modal } from 'semantic-ui-react';
-import {
- Modal,
- Button,
- Icon,
-} from 'semantic-ui-react';
-
-import {
- CodeEditor, LoaderSegment, Switch,
-} from '../../Shared';
-
-const ContentsModal = ({ share, onClose, theme }) => {
+const ContentsModal = ({ onClose, share, theme }) => {
const [loading, setLoading] = useState(true);
const [contents, setContents] = useState();
@@ -22,21 +13,21 @@ const ContentsModal = ({ share, onClose, theme }) => {
useEffect(() => {
const fetch = async () => {
setLoading(true);
-
+
const contents = await browse({ id });
-
- var directories = contents.map(directory => {
+
+ const directories = contents.map((directory) => {
const lines = [directory.name.replace(remotePath, localPath)];
-
- orderBy(directory.files, 'filename').forEach(file => {
+
+ for (const file of orderBy(directory.files, 'filename')) {
lines.push('\t' + file.filename.replace(remotePath, ''));
- });
-
+ }
+
lines.push('');
-
+
return lines.join('\n');
});
-
+
setContents(directories.join('\n'));
setLoading(false);
};
@@ -51,31 +42,33 @@ const ContentsModal = ({ share, onClose, theme }) => {
return (
<Modal
- size='large'
- open={share}
onClose={onClose}
+ open={share}
+ size="large"
>
- <Modal.Header><Icon name='folder'/>{localPath}</Modal.Header>
- <Modal.Content scrolling className='share-ls-content'>
- <Switch
- loading={loading && <LoaderSegment className="modal-loader"/>}
- >
+ <Modal.Header>
+ <Icon name="folder" />
+ {localPath}
+ </Modal.Header>
+ <Modal.Content
+ className="share-ls-content"
+ scrolling
+ >
+ <Switch loading={loading && <LoaderSegment className="modal-loader" />}>
<CodeEditor
- style={{minHeight: 500}}
- value={contents || ''}
basicSetup={false}
editable={false}
+ style={{ minHeight: 500 }}
theme={theme}
+ value={contents || ''}
/>
</Switch>
</Modal.Content>
<Modal.Actions>
- <Button onClick={onClose}>
- Close
- </Button>
+ <Button onClick={onClose}>Close</Button>
</Modal.Actions>
</Modal>
);
};
-export default ContentsModal; \ No newline at end of file
+export default ContentsModal;
diff --git a/src/web/src/components/System/Shares/ExclusionTable.jsx b/src/web/src/components/System/Shares/ExclusionTable.jsx
index 5e010e30..dc94e98d 100644
--- a/src/web/src/components/System/Shares/ExclusionTable.jsx
+++ b/src/web/src/components/System/Shares/ExclusionTable.jsx
@@ -1,11 +1,6 @@
-import React from 'react';
-
-import {
- Table,
- Icon,
-} from 'semantic-ui-react';
-
import { Switch } from '../../Shared';
+import React from 'react';
+import { Icon, Table } from 'semantic-ui-react';
const ExclusionTable = ({ exclusions = [] } = {}) => {
return (
@@ -17,19 +12,37 @@ const ExclusionTable = ({ exclusions = [] } = {}) => {
</Table.Header>
<Table.Body>
<Switch
- empty={exclusions.length === 0 && <Table.Row>
- <Table.Cell style={{ opacity: .5, padding: '10px !important', textAlign: 'center' }}>
- No exclusions configured
- </Table.Cell>
- </Table.Row>}
+ empty={
+ exclusions.length === 0 && (
+ <Table.Row>
+ <Table.Cell
+ style={{
+ opacity: 0.5,
+ padding: '10px !important',
+ textAlign: 'center',
+ }}
+ >
+ No exclusions configured
+ </Table.Cell>
+ </Table.Row>
+ )
+ }
>
- {exclusions.map((share, index) => (<Table.Row key={index}>
- <Table.Cell><Icon name='x' color='red'/>{share.localPath}</Table.Cell>
- </Table.Row>))}
+ {exclusions.map((share, index) => (
+ <Table.Row key={index}>
+ <Table.Cell>
+ <Icon
+ color="red"
+ name="x"
+ />
+ {share.localPath}
+ </Table.Cell>
+ </Table.Row>
+ ))}
</Switch>
</Table.Body>
</Table>
);
};
-export default ExclusionTable; \ No newline at end of file
+export default ExclusionTable;
diff --git a/src/web/src/components/System/Shares/ShareTable.jsx b/src/web/src/components/System/Shares/ShareTable.jsx
index eed7a148..18d0f06b 100644
--- a/src/web/src/components/System/Shares/ShareTable.jsx
+++ b/src/web/src/components/System/Shares/ShareTable.jsx
@@ -1,49 +1,61 @@
+import { Switch } from '../../Shared';
import React from 'react';
-
-import {
- Table,
- Icon,
-} from 'semantic-ui-react';
-
import { Link } from 'react-router-dom';
-import { Switch } from '../../Shared';
+import { Icon, Table } from 'semantic-ui-react';
-const ShareTable = ({ shares, onClick }) => {
+const ShareTable = ({ onClick, shares }) => {
return (
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Host</Table.HeaderCell>
<Table.HeaderCell>Local Path</Table.HeaderCell>
- <Table.HeaderCell className='share-count-column'>Directories</Table.HeaderCell>
- <Table.HeaderCell className='share-count-column'>Files</Table.HeaderCell>
+ <Table.HeaderCell className="share-count-column">
+ Directories
+ </Table.HeaderCell>
+ <Table.HeaderCell className="share-count-column">
+ Files
+ </Table.HeaderCell>
<Table.HeaderCell>Alias</Table.HeaderCell>
<Table.HeaderCell>Remote Path</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Switch
- empty={shares.length === 0 && <Table.Row>
- <Table.Cell colSpan={6} style={{ opacity: .5, padding: '10px !important', textAlign: 'center' }}>
- No shares configured
- </Table.Cell>
- </Table.Row>}
+ empty={
+ shares.length === 0 && (
+ <Table.Row>
+ <Table.Cell
+ colSpan={6}
+ style={{
+ opacity: 0.5,
+ padding: '10px !important',
+ textAlign: 'center',
+ }}
+ >
+ No shares configured
+ </Table.Cell>
+ </Table.Row>
+ )
+ }
>
- {shares.map((share, index) => (<Table.Row key={index}>
- <Table.Cell>{share.host}</Table.Cell>
- <Table.Cell onClick={() => onClick(share)}>
- <Icon name='folder'/>
- <Link to='#'>{share.localPath}</Link>
- </Table.Cell>
- <Table.Cell>{share.directories ?? '?'}</Table.Cell>
- <Table.Cell>{share.files ?? '?'}</Table.Cell>
- <Table.Cell>{share.alias}</Table.Cell>
- <Table.Cell>{share.remotePath}</Table.Cell>
- </Table.Row>))}
+ {shares.map((share, index) => (
+ <Table.Row key={index}>
+ <Table.Cell>{share.host}</Table.Cell>
+ <Table.Cell onClick={() => onClick(share)}>
+ <Icon name="folder" />
+ <Link to="#">{share.localPath}</Link>
+ </Table.Cell>
+ <Table.Cell>{share.directories ?? '?'}</Table.Cell>
+ <Table.Cell>{share.files ?? '?'}</Table.Cell>
+ <Table.Cell>{share.alias}</Table.Cell>
+ <Table.Cell>{share.remotePath}</Table.Cell>
+ </Table.Row>
+ ))}
</Switch>
</Table.Body>
</Table>
);
};
-export default ShareTable; \ No newline at end of file
+export default ShareTable;
diff --git a/src/web/src/components/System/Shares/index.jsx b/src/web/src/components/System/Shares/index.jsx
index 3d5b1858..d629230e 100644
--- a/src/web/src/components/System/Shares/index.jsx
+++ b/src/web/src/components/System/Shares/index.jsx
@@ -1,21 +1,11 @@
-import React, { useState, useEffect } from 'react';
-import { toast } from 'react-toastify';
-
-import * as sharesLib from '../../../lib/shares';
-import {
- LoaderSegment,
- ShrinkableButton,
- Switch,
-} from '../../Shared';
-
+import * as sharesLibrary from '../../../lib/shares';
+import { LoaderSegment, ShrinkableButton, Switch } from '../../Shared';
import ContentsModal from './ContentsModal';
-
-import {
- Divider,
-} from 'semantic-ui-react';
-
import ExclusionTable from './ExclusionTable';
import ShareTable from './ShareTable';
+import React, { useEffect, useState } from 'react';
+import { toast } from 'react-toastify';
+import { Divider } from 'semantic-ui-react';
const Index = ({ state = {} } = {}) => {
const [loading, setLoading] = useState(true);
@@ -23,7 +13,7 @@ const Index = ({ state = {} } = {}) => {
const [shares, setShares] = useState([]);
const [modal, setModal] = useState(false);
- const { scanning, scanProgress, scanPending, directories, files } = state;
+ const { directories, files, scanPending, scanProgress, scanning } = state;
useEffect(() => {
getAll();
@@ -33,21 +23,26 @@ const Index = ({ state = {} } = {}) => {
getAll({ quiet: true });
if (!scanning) {
- // the state change out of scanning can fire before
+ // the state change out of scanning can fire before
// shares are updated, which leaves them stale. wait a second
// and fetch again.
- setTimeout(() => getAll({ quiet: true }), 1000);
+ setTimeout(() => getAll({ quiet: true }), 1_000);
}
- }, [scanning, scanPending]);
+ }, [scanPending, scanning]);
const getAll = async ({ quiet } = { quiet: false }) => {
try {
if (!quiet) setLoading(true);
- const sharesByHost = await sharesLib.getAll();
- const flattened = Object.entries(sharesByHost).reduce((acc, [host, shares]) => {
- return acc.concat(shares.map(share => ({ host, ...share })));
- }, []);
+ const sharesByHost = await sharesLibrary.getAll();
+ const flattened = Object.entries(sharesByHost).reduce(
+ (accumulator, [host, shares]) => {
+ return accumulator.concat(
+ shares.map((share) => ({ host, ...share })),
+ );
+ },
+ [],
+ );
setShares(flattened);
} catch (error) {
@@ -61,7 +56,7 @@ const Index = ({ state = {} } = {}) => {
const rescan = async () => {
try {
setWorking(true);
- await sharesLib.rescan();
+ await sharesLibrary.rescan();
} catch (error) {
console.error(error);
toast.error(error?.response?.data ?? error?.message ?? error);
@@ -73,63 +68,83 @@ const Index = ({ state = {} } = {}) => {
const cancel = async () => {
try {
setWorking(true);
- await sharesLib.cancel();
+ await sharesLibrary.cancel();
} catch (error) {
console.error(error);
- toast.error(error?.response?.data ?? error?.message ?? error ?? 'Failed to cancel the scan');
+ toast.error(
+ error?.response?.data ??
+ error?.message ??
+ error ??
+ 'Failed to cancel the scan',
+ );
} finally {
- setWorking(false);
+ setWorking(false);
}
};
- const ScanButton = () => <ShrinkableButton
- primary={!scanPending}
- color={scanPending ? 'yellow' : undefined}
- icon='refresh'
- loading={working}
- disabled={working}
- mediaQuery={'(max-width: 516px)'}
- onClick={() => rescan()}
- >Rescan Shares</ShrinkableButton>;
+ const ScanButton = () => (
+ <ShrinkableButton
+ color={scanPending ? 'yellow' : undefined}
+ disabled={working}
+ icon="refresh"
+ loading={working}
+ mediaQuery="(max-width: 516px)"
+ onClick={() => rescan()}
+ primary={!scanPending}
+ >
+ Rescan Shares
+ </ShrinkableButton>
+ );
- const CancelButton = () => <ShrinkableButton
- color='red'
- icon='x'
- disabled={working}
- mediaQuery={'(max-width: 516px)'}
- onClick={() => cancel()}
- >Cancel Scan</ShrinkableButton>;
+ const CancelButton = () => (
+ <ShrinkableButton
+ color="red"
+ disabled={working}
+ icon="x"
+ mediaQuery="(max-width: 516px)"
+ onClick={() => cancel()}
+ >
+ Cancel Scan
+ </ShrinkableButton>
+ );
- const shared = shares.filter(share => !share.isExcluded);
- const excluded = shares.filter(share => share.isExcluded);
+ const shared = shares.filter((share) => !share.isExcluded);
+ const excluded = shares.filter((share) => share.isExcluded);
return (
- <>
+ <Switch loading={loading && <LoaderSegment />}>
+ <div className="header-buttons">
+ <Switch scanning={scanning && <CancelButton />}>
+ <ScanButton />
+ </Switch>
+ </div>
+ <Divider />
<Switch
- loading={loading && <LoaderSegment/>}
+ filling={
+ scanning && (
+ <LoaderSegment>
+ <div>
+ <div>{Math.round(scanProgress * 100)}%</div>
+ <div className="share-scan-detail">
+ Found {files} files in {directories} directories
+ </div>
+ </div>
+ </LoaderSegment>
+ )
+ }
>
- <div className="header-buttons">
- <Switch
- scanning={scanning && <CancelButton/>}
- >
- <ScanButton/>
- </Switch>
- </div>
- <Divider/>
- <Switch
- filling={scanning && <LoaderSegment>
- <div>
- <div>{Math.round(scanProgress * 100)}%</div>
- <div className='share-scan-detail'>Found {files} files in {directories} directories</div>
- </div></LoaderSegment>}
- >
- <ShareTable shares={shared} onClick={setModal}/>
- <ExclusionTable exclusions={excluded}/>
- </Switch>
- <ContentsModal share={modal} onClose={() => setModal(false)}/>
+ <ShareTable
+ onClick={setModal}
+ shares={shared}
+ />
+ <ExclusionTable exclusions={excluded} />
</Switch>
- </>
+ <ContentsModal
+ onClose={() => setModal(false)}
+ share={modal}
+ />
+ </Switch>
);
};
-export default Index; \ No newline at end of file
+export default Index;
diff --git a/src/web/src/components/System/System.jsx b/src/web/src/components/System/System.jsx
index 2baba767..02420d9c 100644
--- a/src/web/src/components/System/System.jsx
+++ b/src/web/src/components/System/System.jsx
@@ -1,107 +1,161 @@
-import React from 'react';
-import { useRouteMatch, useHistory, Redirect } from 'react-router-dom';
-
-import { Segment, Tab, Menu, Icon } from 'semantic-ui-react';
-
import './System.css';
-
import { Switch } from '../Shared';
+import Data from './Data';
+import Files from './Files';
import Info from './Info';
import Logs from './Logs';
import Options from './Options';
import Shares from './Shares';
-import Files from './Files';
-import Data from './Data';
+import React from 'react';
+import { Redirect, useHistory, useRouteMatch } from 'react-router-dom';
+import { Icon, Menu, Segment, Tab } from 'semantic-ui-react';
-const System = ({ state = {}, theme, options = {} }) => {
- const { params: { tab }, ...route } = useRouteMatch();
+const System = ({ options = {}, state = {}, theme }) => {
+ const {
+ params: { tab },
+ ...route
+ } = useRouteMatch();
const history = useHistory();
const panes = [
- {
+ {
+ menuItem: (
+ <Menu.Item key="info">
+ <Switch
+ pending={
+ ((state?.pendingRestart ?? false) ||
+ (state?.pendingReconnect ?? false)) && (
+ <Icon
+ color="yellow"
+ name="exclamation circle"
+ />
+ )
+ }
+ >
+ <Icon name="info circle" />
+ </Switch>
+ Info
+ </Menu.Item>
+ ),
+ render: () => (
+ <Tab.Pane>
+ <Info
+ state={state}
+ theme={theme}
+ />
+ </Tab.Pane>
+ ),
route: 'info',
- menuItem: (<Menu.Item key='info'>
- <Switch
- pending={((state?.pendingRestart ?? false) || (state?.pendingReconnect ?? false))
- && <Icon name='exclamation circle' color='yellow'/>}
- >
- <Icon name='info circle'/>
- </Switch>
- Info
- </Menu.Item>),
- render: () => <Tab.Pane><Info state={state} theme={theme}/></Tab.Pane>,
},
{
- route: 'options',
- menuItem: {
- key: 'options',
- icon: 'options',
- content: 'Options',
- },
- render: () => <Tab.Pane className='full-height'><Options options={options} theme={theme}/></Tab.Pane>,
+ menuItem: {
+ content: 'Options',
+ icon: 'options',
+ key: 'options',
+ },
+ render: () => (
+ <Tab.Pane className="full-height">
+ <Options
+ options={options}
+ theme={theme}
+ />
+ </Tab.Pane>
+ ),
+ route: 'options',
},
{
- route: 'shares',
- menuItem: (<Menu.Item key='shares'>
- <Switch
- scanPending={(state?.shares?.scanPending ?? false) && <Icon name='exclamation circle' color='yellow'/>}
- >
- <Icon name='share external'/>
- </Switch>
- Shares
- </Menu.Item>),
- render: () => <Tab.Pane><Shares state={state.shares} theme={theme}/></Tab.Pane>,
+ menuItem: (
+ <Menu.Item key="shares">
+ <Switch
+ scanPending={
+ (state?.shares?.scanPending ?? false) && (
+ <Icon
+ color="yellow"
+ name="exclamation circle"
+ />
+ )
+ }
+ >
+ <Icon name="share external" />
+ </Switch>
+ Shares
+ </Menu.Item>
+ ),
+ render: () => (
+ <Tab.Pane>
+ <Shares
+ state={state.shares}
+ theme={theme}
+ />
+ </Tab.Pane>
+ ),
+ route: 'shares',
},
{
- route: 'files',
menuItem: {
- key: 'files',
- icon: 'folder open',
content: 'Files',
+ icon: 'folder open',
+ key: 'files',
},
- render: () => <Tab.Pane className='full-height'><Files options={options} theme={theme}/></Tab.Pane>,
+ render: () => (
+ <Tab.Pane className="full-height">
+ <Files
+ options={options}
+ theme={theme}
+ />
+ </Tab.Pane>
+ ),
+ route: 'files',
},
{
- route: 'data',
menuItem: {
- key: 'data',
- icon: 'database',
content: 'Data',
+ icon: 'database',
+ key: 'data',
},
- render: () => <Tab.Pane className='full-height'><Data theme={theme}/></Tab.Pane>,
+ render: () => (
+ <Tab.Pane className="full-height">
+ <Data theme={theme} />
+ </Tab.Pane>
+ ),
+ route: 'data',
},
- {
- route: 'logs',
- menuItem: {
- key: 'logs',
- icon: 'file outline',
- content: 'Logs',
- },
- render: () => <Tab.Pane><Logs/></Tab.Pane>,
+ {
+ menuItem: {
+ content: 'Logs',
+ icon: 'file outline',
+ key: 'logs',
+ },
+ render: () => (
+ <Tab.Pane>
+ <Logs />
+ </Tab.Pane>
+ ),
+ route: 'logs',
},
];
- const activeIndex = panes.findIndex(pane => pane.route === tab);
+ const activeIndex = panes.findIndex((pane) => pane.route === tab);
const onTabChange = (e, { activeIndex }) => {
history.push(panes[activeIndex].route);
};
if (tab === undefined) {
- return <Redirect to={`${route.url}/${panes[0].route}`}/>;
+ return <Redirect to={`${route.url}/${panes[0].route}`} />;
}
return (
- <div className='system'>
+ <div className="system">
<Segment raised>
<Tab
- activeIndex={activeIndex > -1 ? activeIndex : 0}
- panes={panes}
+ activeIndex={activeIndex > -1 ? activeIndex : 0}
onTabChange={onTabChange}
+ panes={panes}
/>
</Segment>
</div>
);
};
-export default System; \ No newline at end of file
+export default System;
diff --git a/src/web/src/components/Transfers/TransferGroup.jsx b/src/web/src/components/Transfers/TransferGroup.jsx
index ad4ab969..4f2dbb7c 100644
--- a/src/web/src/components/Transfers/TransferGroup.jsx
+++ b/src/web/src/components/Transfers/TransferGroup.jsx
@@ -1,48 +1,49 @@
-import React, { Component } from 'react';
import * as transfers from '../../lib/transfers';
-
-import {
- Card,
- Button,
- Icon,
-} from 'semantic-ui-react';
-
import TransferList from './TransferList';
+import React, { Component } from 'react';
+import { Button, Card, Icon } from 'semantic-ui-react';
class TransferGroup extends Component {
state = {
- selections: new Set(),
isFolded: false,
+ selections: new Set(),
};
onSelectionChange = (directoryName, file, selected) => {
- const {selections} = this.state;
- const obj = JSON.stringify({ directory: directoryName, filename: file.filename });
- selected ? selections.add(obj) : selections.delete(obj);
+ const { selections } = this.state;
+ const object = JSON.stringify({
+ directory: directoryName,
+ filename: file.filename,
+ });
+ selected ? selections.add(object) : selections.delete(object);
this.setState({ selections });
};
- isSelected = (directoryName, file) =>
- this.state.selections.has(JSON.stringify({ directory: directoryName, filename: file.filename }));
+ isSelected = (directoryName, file) =>
+ this.state.selections.has(
+ JSON.stringify({ directory: directoryName, filename: file.filename }),
+ );
getSelectedFiles = () => {
const { user } = this.props;
-
+
return Array.from(this.state.selections)
- .map(s => JSON.parse(s))
- .map(s => user.directories
- .find(d => d.directory === s.directory)
- .files.find(f => f.filename === s.filename)
- ).filter(s => s !== undefined);
+ .map((s) => JSON.parse(s))
+ .map((s) =>
+ user.directories
+ .find((d) => d.directory === s.directory)
+ .files.find((f) => f.filename === s.filename),
+ )
+ .filter((s) => s !== undefined);
};
removeFileSelection = (file) => {
- const {selections} = this.state;
+ const { selections } = this.state;
const match = Array.from(selections)
- .map(s => JSON.parse(s))
- .find(s => s.filename === file.filename);
+ .map((s) => JSON.parse(s))
+ .find((s) => s.filename === file.filename);
if (match) {
selections.delete(JSON.stringify(match));
@@ -51,56 +52,74 @@ class TransferGroup extends Component {
};
retryAll = async (selected) => {
- await Promise.all(selected.map(file => this.retry(file)));
+ await Promise.all(selected.map((file) => this.retry(file)));
};
cancelAll = async (direction, username, selected) => {
- await Promise.all(selected.map(file => transfers.cancel({ direction, username, id: file.id})));
+ await Promise.all(
+ selected.map((file) =>
+ transfers.cancel({ direction, id: file.id, username }),
+ ),
+ );
};
removeAll = async (direction, username, selected) => {
- await Promise.all(selected.map(file =>
- transfers.cancel({ direction, username, id: file.id, remove: true })
- .then(() => this.removeFileSelection(file))));
+ await Promise.all(
+ selected.map((file) =>
+ transfers
+ .cancel({ direction, id: file.id, remove: true, username })
+ .then(() => this.removeFileSelection(file)),
+ ),
+ );
};
retry = async (file) => {
- const { username, filename, size } = file;
-
+ const { filename, size, username } = file;
+
try {
- await transfers.download({username, files: [{filename, size }] });
+ await transfers.download({ files: [{ filename, size }], username });
} catch (error) {
console.error(error);
}
};
fetchPlaceInQueue = async (file) => {
- const { username, id } = file;
+ const { id, username } = file;
try {
- await transfers.getPlaceInQueue({ username, id });
+ await transfers.getPlaceInQueue({ id, username });
} catch (error) {
console.error(error);
}
};
toggleFolded = () => {
- this.setState({'isFolded': !this.state.isFolded});
+ this.setState({ isFolded: !this.state.isFolded });
};
- render = () => {
- const { user, direction } = this.props;
- const {isFolded} = this.state;
+ render() {
+ const { direction, user } = this.props;
+ const { isFolded } = this.state;
const selected = this.getSelectedFiles();
const all = selected.length > 1 ? ' Selected' : '';
-
- const allRetryable = selected.filter(f => transfers.isStateRetryable(f.state)).length === selected.length;
- const anyCancellable = selected.filter(f => transfers.isStateCancellable(f.state)).length > 0;
- const allRemovable = selected.filter(f => transfers.isStateRemovable(f.state)).length === selected.length;
+
+ const allRetryable =
+ selected.filter((f) => transfers.isStateRetryable(f.state)).length ===
+ selected.length;
+ const anyCancellable = selected.some((f) =>
+ transfers.isStateCancellable(f.state),
+ );
+ const allRemovable =
+ selected.filter((f) => transfers.isStateRemovable(f.state)).length ===
+ selected.length;
return (
- <Card key={user.username} className='transfer-card' raised>
+ <Card
+ className="transfer-card"
+ key={user.username}
+ raised
+ >
<Card.Content>
<Card.Header>
<Icon
@@ -110,50 +129,64 @@ class TransferGroup extends Component {
/>
{user.username}
</Card.Header>
- {user.directories && !isFolded && user.directories
- .map((dir, index) =>
- <TransferList
- key={index}
- username={user.username}
- directoryName={dir.directory}
- files={(dir.files || []).map(f => ({ ...f, selected: this.isSelected(dir.directory, f) }))}
- onSelectionChange={this.onSelectionChange}
+ {user.directories &&
+ !isFolded &&
+ user.directories.map((dir, index) => (
+ <TransferList
direction={this.props.direction}
+ directoryName={dir.directory}
+ files={(dir.files || []).map((f) => ({
+ ...f,
+ selected: this.isSelected(dir.directory, f),
+ }))}
+ key={index}
onPlaceInQueueRequested={this.fetchPlaceInQueue}
onRetryRequested={this.retry}
+ onSelectionChange={this.onSelectionChange}
+ username={user.username}
/>
- )}
+ ))}
</Card.Content>
- {selected && selected.length > 0 &&
- <Card.Content extra>
- {<Button.Group>
- {allRetryable &&
- <Button
- icon='redo'
- color='green'
- content={`Retry${all}`}
- onClick={() => this.retryAll(selected)}
- />}
- {allRetryable && anyCancellable && <Button.Or/>}
- {anyCancellable &&
- <Button
- icon='x'
- color='red'
- content={`Cancel${all}`}
- onClick={() => this.cancelAll(direction, user.username, selected)}
- />}
- {(allRetryable || anyCancellable) && allRemovable && <Button.Or/>}
- {allRemovable &&
- <Button
- icon='trash alternate'
- content={`Remove${all}`}
- onClick={() => this.removeAll(direction, user.username, selected)}
- />}
- </Button.Group>}
- </Card.Content>}
+ {selected && selected.length > 0 && (
+ <Card.Content extra>
+ <Button.Group>
+ {allRetryable && (
+ <Button
+ color="green"
+ content={`Retry${all}`}
+ icon="redo"
+ onClick={() => this.retryAll(selected)}
+ />
+ )}
+ {allRetryable && anyCancellable && <Button.Or />}
+ {anyCancellable && (
+ <Button
+ color="red"
+ content={`Cancel${all}`}
+ icon="x"
+ onClick={() =>
+ this.cancelAll(direction, user.username, selected)
+ }
+ />
+ )}
+ {(allRetryable || anyCancellable) && allRemovable && (
+ <Button.Or />
+ )}
+ {allRemovable && (
+ <Button
+ content={`Remove${all}`}
+ icon="trash alternate"
+ onClick={() =>
+ this.removeAll(direction, user.username, selected)
+ }
+ />
+ )}
+ </Button.Group>
+ </Card.Content>
+ )}
</Card>
);
- };
+ }
}
export default TransferGroup;
diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx
index 1efe5900..b55ada1b 100644
--- a/src/web/src/components/Transfers/TransferList.jsx
+++ b/src/web/src/components/Transfers/TransferList.jsx
@@ -1,147 +1,188 @@
+import { formatBytes, formatBytesAsUnit, getFileName } from '../../lib/util';
import React, { Component } from 'react';
-
import {
+ Button,
Checkbox,
-} from 'semantic-ui-react';
-
-import { formatBytes, formatBytesAsUnit, getFileName } from '../../lib/util';
-
-import {
- Header,
- Table,
- Icon,
- List,
+ Header,
+ Icon,
+ List,
Progress,
- Button,
+ Table,
} from 'semantic-ui-react';
const getColor = (state) => {
- switch(state) {
- case 'InProgress':
- return { color: 'blue' };
- case 'Completed, Succeeded':
- return { color: 'green' };
- case 'Requested':
- case 'Queued, Locally':
- case 'Queued, Remotely':
- case 'Queued':
- return {};
- case 'Initializing':
- return { color: 'teal' };
- default:
- return { color: 'red' };
+ switch (state) {
+ case 'InProgress':
+ return { color: 'blue' };
+ case 'Completed, Succeeded':
+ return { color: 'green' };
+ case 'Requested':
+ case 'Queued, Locally':
+ case 'Queued, Remotely':
+ case 'Queued':
+ return {};
+ case 'Initializing':
+ return { color: 'teal' };
+ default:
+ return { color: 'red' };
}
};
const isRetryableState = (state) => getColor(state).color === 'red';
const isQueuedState = (state) => state.includes('Queued');
-const formatBytesTransferred = ({ transferred, size }) => {
- const [s, sExt] = formatBytes(size, 1).split(' ');
- const t = formatBytesAsUnit(transferred, 1, sExt);
+const formatBytesTransferred = ({ size, transferred }) => {
+ const [s, sExtension] = formatBytes(size, 1).split(' ');
+ const t = formatBytesAsUnit(transferred, 1, sExtension);
- return `${t}/${s} ${sExt}`;
+ return `${t}/${s} ${sExtension}`;
};
class TransferList extends Component {
state = {
isFolded: false,
};
+
handleClick = (file) => {
- const { state, direction } = file;
+ const { direction, state } = file;
if (direction === 'Download') {
if (isRetryableState(state)) {
return this.props.onRetryRequested(file);
}
-
+
if (isQueuedState(state)) {
return this.props.onPlaceInQueueRequested(file);
}
- }
+ }
};
toggleFolded = () => {
- this.setState({'isFolded': !this.state.isFolded});
+ this.setState({ isFolded: !this.state.isFolded });
};
- render = () => {
- const { directoryName, onSelectionChange, files } = this.props;
- const {isFolded} = this.state;
+ render() {
+ const { directoryName, files, onSelectionChange } = this.props;
+ const { isFolded } = this.state;
return (
<div>
- <Header
- size='small'
- className='filelist-header'
+ <Header
+ className="filelist-header"
+ size="small"
>
- <Icon name={isFolded ? 'folder' : 'folder open'}
+ <Icon
link
- onClick={() => this.toggleFolded()}/>{directoryName}
+ name={isFolded ? 'folder' : 'folder open'}
+ onClick={() => this.toggleFolded()}
+ />
+ {directoryName}
</Header>
- {!isFolded ?
+ {!isFolded ? (
<List>
<List.Item>
<Table>
<Table.Header>
<Table.Row>
- <Table.HeaderCell className='transferlist-selector'>
- <Checkbox
- fitted
- checked={files.filter(f => !f.selected).length === 0}
+ <Table.HeaderCell className="transferlist-selector">
+ <Checkbox
+ checked={files.filter((f) => !f.selected).length === 0}
+ fitted
onChange={(event, data) =>
- files.map(file => onSelectionChange(directoryName, file, data.checked))}
+ files.map((file) =>
+ onSelectionChange(
+ directoryName,
+ file,
+ data.checked,
+ ),
+ )
+ }
/>
</Table.HeaderCell>
- <Table.HeaderCell className='transferlist-filename'>File</Table.HeaderCell>
- <Table.HeaderCell className='transferlist-progress'>Progress</Table.HeaderCell>
- <Table.HeaderCell className='transferlist-size'>Size</Table.HeaderCell>
+ <Table.HeaderCell className="transferlist-filename">
+ File
+ </Table.HeaderCell>
+ <Table.HeaderCell className="transferlist-progress">
+ Progress
+ </Table.HeaderCell>
+ <Table.HeaderCell className="transferlist-size">
+ Size
+ </Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
- {files.sort((a, b) => getFileName(a.filename).localeCompare(getFileName(b.filename))).map((f, i) =>
- <Table.Row key={i}>
- <Table.Cell className='transferlist-selector'>
- <Checkbox
- fitted
- checked={f.selected}
- onChange={(event, data) => onSelectionChange(directoryName, f, data.checked)}
- />
- </Table.Cell>
- <Table.Cell className='transferlist-filename'>{getFileName(f.filename)}</Table.Cell>
- <Table.Cell className='transferlist-progress'>
- {f.state === 'InProgress' ?
- <Progress
- style={{ margin: 0 }}
- percent={Math.round(f.percentComplete)}
- progress color={getColor(f.state).color}
- /> :
- <Button
- fluid
- size='mini'
- style={{ margin: 0, padding: 7, cursor: f.direction === 'Upload' ? 'unset' : '' }}
- {...getColor(f.state)}
- onClick={() => this.handleClick(f)}
- active={f.direction === 'Upload'}
- >
- {f.direction === 'Download' && isQueuedState(f.state) && <Icon name='refresh'/>}
- {f.direction === 'Download' && isRetryableState(f.state) && <Icon name='redo'/>}
- {f.state}{f.placeInQueue ? ` (#${f.placeInQueue})` : ''}
- </Button>}
- </Table.Cell>
- <Table.Cell className='transferlist-size'>
- {formatBytesTransferred({ transferred: f.bytesTransferred, size: f.size })}
- </Table.Cell>
- </Table.Row>
- )}
+ {files
+ .sort((a, b) =>
+ getFileName(a.filename).localeCompare(
+ getFileName(b.filename),
+ ),
+ )
+ .map((f, index) => (
+ <Table.Row key={index}>
+ <Table.Cell className="transferlist-selector">
+ <Checkbox
+ checked={f.selected}
+ fitted
+ onChange={(event, data) =>
+ onSelectionChange(directoryName, f, data.checked)
+ }
+ />
+ </Table.Cell>
+ <Table.Cell className="transferlist-filename">
+ {getFileName(f.filename)}
+ </Table.Cell>
+ <Table.Cell className="transferlist-progress">
+ {f.state === 'InProgress' ? (
+ <Progress
+ color={getColor(f.state).color}
+ percent={Math.round(f.percentComplete)}
+ progress
+ style={{ margin: 0 }}
+ />
+ ) : (
+ <Button
+ fluid
+ size="mini"
+ style={{
+ cursor: f.direction === 'Upload' ? 'unset' : '',
+ margin: 0,
+ padding: 7,
+ }}
+ {...getColor(f.state)}
+ active={f.direction === 'Upload'}
+ onClick={() => this.handleClick(f)}
+ >
+ {f.direction === 'Download' &&
+ isQueuedState(f.state) && (
+ <Icon name="refresh" />
+ )}
+ {f.direction === 'Download' &&
+ isRetryableState(f.state) && (
+ <Icon name="redo" />
+ )}
+ {f.state}
+ {f.placeInQueue ? ` (#${f.placeInQueue})` : ''}
+ </Button>
+ )}
+ </Table.Cell>
+ <Table.Cell className="transferlist-size">
+ {formatBytesTransferred({
+ size: f.size,
+ transferred: f.bytesTransferred,
+ })}
+ </Table.Cell>
+ </Table.Row>
+ ))}
</Table.Body>
</Table>
</List.Item>
</List>
- : ''}
+ ) : (
+ ''
+ )}
</div>
);
- };
+ }
}
export default TransferList;
diff --git a/src/web/src/components/Transfers/Transfers.jsx b/src/web/src/components/Transfers/Transfers.jsx
index 7820400e..876cc14b 100644
--- a/src/web/src/components/Transfers/Transfers.jsx
+++ b/src/web/src/components/Transfers/Transfers.jsx
@@ -1,16 +1,10 @@
-import React, { useState, useEffect, useMemo } from 'react';
-import * as transfersLib from '../../lib/transfers';
-import { toast } from 'react-toastify';
-
-import {
- LoaderSegment,
- PlaceholderSegment,
-} from '../Shared';
-
+import './Transfers.css';
+import * as transfersLibrary from '../../lib/transfers';
+import { LoaderSegment, PlaceholderSegment } from '../Shared';
import TransferGroup from './TransferGroup';
import TransfersHeader from './TransfersHeader';
-
-import './Transfers.css';
+import React, { useEffect, useMemo, useState } from 'react';
+import { toast } from 'react-toastify';
const Transfers = ({ direction, server }) => {
const [connecting, setConnecting] = useState(true);
@@ -29,8 +23,8 @@ const Transfers = ({ direction, server }) => {
};
init();
- const interval = window.setInterval(fetch, 1000);
-
+ const interval = window.setInterval(fetch, 1_000);
+
return () => {
clearInterval(interval);
};
@@ -39,7 +33,7 @@ const Transfers = ({ direction, server }) => {
useMemo(() => {
// this is used to prevent weird update issues if switching
// between uploads and downloads. useEffect fires _after_ the
- // prop 'direction' updates, meaning there's a flash where the
+ // prop 'direction' updates, meaning there's a flash where the
// screen contents switch to the new direction for a brief moment
// before the connecting animation shows. this memo fires the instant
// the direction prop changes, preventing this flash.
@@ -48,7 +42,7 @@ const Transfers = ({ direction, server }) => {
const fetch = async () => {
try {
- const response = await transfersLib.getAll({ direction });
+ const response = await transfersLibrary.getAll({ direction });
setTransfers(response);
} catch (error) {
console.error(error);
@@ -57,11 +51,14 @@ const Transfers = ({ direction, server }) => {
};
const retry = async ({ file, suppressStateChange = false }) => {
- const { username, filename, size } = file;
-
+ const { filename, size, username } = file;
+
try {
if (!suppressStateChange) setRetrying(true);
- await transfersLib.download({username, files: [{filename, size }] });
+ await transfersLibrary.download({
+ files: [{ filename, size }],
+ username,
+ });
if (!suppressStateChange) setRetrying(false);
} catch (error) {
console.error(error);
@@ -72,16 +69,18 @@ const Transfers = ({ direction, server }) => {
const retryAll = async (transfers) => {
setRetrying(true);
- await Promise.all(transfers.map(file => retry({ file, suppressStateChange: true })));
+ await Promise.all(
+ transfers.map((file) => retry({ file, suppressStateChange: true })),
+ );
setRetrying(false);
};
const cancel = async ({ file, suppressStateChange = false }) => {
- const { username, id } = file;
-
+ const { id, username } = file;
+
try {
if (!suppressStateChange) setCancelling(true);
- await transfersLib.cancel({ direction, username, id });
+ await transfersLibrary.cancel({ direction, id, username });
if (!suppressStateChange) setCancelling(false);
} catch (error) {
console.error(error);
@@ -92,16 +91,18 @@ const Transfers = ({ direction, server }) => {
const cancelAll = async (transfers) => {
setCancelling(true);
- await Promise.all(transfers.map(file => cancel({ file, suppressStateChange: true })));
+ await Promise.all(
+ transfers.map((file) => cancel({ file, suppressStateChange: true })),
+ );
setCancelling(false);
};
const remove = async ({ file, suppressStateChange = false }) => {
- const { username, id } = file;
+ const { id, username } = file;
try {
if (!suppressStateChange) setRemoving(true);
- await transfersLib.cancel({ direction, username, id, remove: true });
+ await transfersLibrary.cancel({ direction, id, remove: true, username });
if (!suppressStateChange) setRemoving(false);
} catch (error) {
console.error(error);
@@ -112,44 +113,51 @@ const Transfers = ({ direction, server }) => {
const removeAll = async (transfers) => {
setRemoving(true);
- await Promise.all(transfers.map(file => remove({ file, suppressStateChange: true })));
+ await Promise.all(
+ transfers.map((file) => remove({ file, suppressStateChange: true })),
+ );
setRemoving(false);
};
if (connecting) {
- return <LoaderSegment/>;
+ return <LoaderSegment />;
}
return (
<>
- <TransfersHeader
- direction={direction}
- transfers={transfers}
- server={server}
- onRetryAll={retryAll}
- retrying={retrying}
- onCancelAll={cancelAll}
+ <TransfersHeader
cancelling={cancelling}
+ direction={direction}
+ onCancelAll={cancelAll}
onRemoveAll={removeAll}
+ onRetryAll={retryAll}
removing={removing}
+ retrying={retrying}
+ server={server}
+ transfers={transfers}
/>
- {transfers.length === 0
- ? <PlaceholderSegment icon={direction} caption={`No ${direction}s to display`}/>
- : transfers.map((user, index) =>
- <TransferGroup
- key={index}
- direction={direction}
- user={user}
- retry={retry}
- retryAll={retryAll}
+ {transfers.length === 0 ? (
+ <PlaceholderSegment
+ caption={`No ${direction}s to display`}
+ icon={direction}
+ />
+ ) : (
+ transfers.map((user, index) => (
+ <TransferGroup
cancel={cancel}
cancelAll={cancelAll}
+ direction={direction}
+ key={index}
remove={remove}
removeAll={removeAll}
+ retry={retry}
+ retryAll={retryAll}
+ user={user}
/>
- )}
+ ))
+ )}
</>
);
};
-export default Transfers; \ No newline at end of file
+export default Transfers;
diff --git a/src/web/src/components/Transfers/TransfersHeader.jsx b/src/web/src/components/Transfers/TransfersHeader.jsx
index bb130d11..2e61bab1 100644
--- a/src/web/src/components/Transfers/TransfersHeader.jsx
+++ b/src/web/src/components/Transfers/TransfersHeader.jsx
@@ -1,149 +1,166 @@
-import React, { useState, useMemo } from 'react';
-
-import {
- Segment,
- Icon,
-} from 'semantic-ui-react';
-
-import {
- Div,
- Nbsp,
-} from '../Shared';
-
-import ShrinkableDropdownButton from '../Shared/ShrinkableDropdownButton';
import { isStateCancellable, isStateRetryable } from '../../lib/transfers';
+import { Div, Nbsp } from '../Shared';
+import ShrinkableDropdownButton from '../Shared/ShrinkableDropdownButton';
+import React, { useMemo, useState } from 'react';
+import { Icon, Segment } from 'semantic-ui-react';
const getRetryableFiles = ({ files, retryOption }) => {
switch (retryOption) {
- case 'Errored':
- return files.filter(file =>
- ['Completed, TimedOut',
- 'Completed, Errored',
- 'Completed, Rejected'].includes(file.state));
- case 'Cancelled':
- return files.filter(file => file.state === 'Completed, Cancelled');
- case 'All':
- return files.filter(file => isStateRetryable(file.state));
- default:
- return [];
+ case 'Errored':
+ return files.filter((file) =>
+ [
+ 'Completed, TimedOut',
+ 'Completed, Errored',
+ 'Completed, Rejected',
+ ].includes(file.state),
+ );
+ case 'Cancelled':
+ return files.filter((file) => file.state === 'Completed, Cancelled');
+ case 'All':
+ return files.filter((file) => isStateRetryable(file.state));
+ default:
+ return [];
}
};
-const getCancellableFiles = ({ files, cancelOption }) => {
+const getCancellableFiles = ({ cancelOption, files }) => {
switch (cancelOption) {
- case 'All':
- return files.filter(file => isStateCancellable(file.state));
- case 'Queued':
- return files.filter(file => ['Queued, Locally', 'Queued, Remotely'].includes(file.state));
- case 'In Progress':
- return files.filter(file => file.state === 'InProgress');
- default:
- return [];
+ case 'All':
+ return files.filter((file) => isStateCancellable(file.state));
+ case 'Queued':
+ return files.filter((file) =>
+ ['Queued, Locally', 'Queued, Remotely'].includes(file.state),
+ );
+ case 'In Progress':
+ return files.filter((file) => file.state === 'InProgress');
+ default:
+ return [];
}
};
const getRemovableFiles = ({ files, removeOption }) => {
switch (removeOption) {
- case 'Succeeded':
- return files.filter(file => file.state === 'Completed, Succeeded');
- case 'Errored':
- return files.filter(file =>
- ['Completed, TimedOut',
- 'Completed, Errored',
- 'Completed, Rejected'].includes(file.state));
- case 'Cancelled':
- return files.filter(file => file.state === 'Completed, Cancelled');
- case 'Completed':
- return files.filter(file => file.state.includes('Completed'));
- default:
- return [];
+ case 'Succeeded':
+ return files.filter((file) => file.state === 'Completed, Succeeded');
+ case 'Errored':
+ return files.filter((file) =>
+ [
+ 'Completed, TimedOut',
+ 'Completed, Errored',
+ 'Completed, Rejected',
+ ].includes(file.state),
+ );
+ case 'Cancelled':
+ return files.filter((file) => file.state === 'Completed, Cancelled');
+ case 'Completed':
+ return files.filter((file) => file.state.includes('Completed'));
+ default:
+ return [];
}
};
-const TransfersHeader = ({
- direction,
- transfers,
- server = { isConnected: true },
- onRetryAll,
- retrying = false,
+const TransfersHeader = ({
+ cancelling = false,
+ direction,
onCancelAll,
- cancelling = false,
onRemoveAll,
+ onRetryAll,
removing = false,
+ retrying = false,
+ server = { isConnected: true },
+ transfers,
}) => {
const [removeOption, setRemoveOption] = useState('Succeeded');
const [cancelOption, setCancelOption] = useState('All');
const [retryOption, setRetryOption] = useState('Errored');
const files = useMemo(() => {
- const files = transfers.reduce((acc, username) => {
- const allUserFiles = username.directories.reduce((acc, directory) => {
- acc = acc.concat(directory.files);
- return acc;
- }, []);
-
- acc = acc.concat(allUserFiles);
- return acc;
+ const files = transfers.reduce((accumulator, username) => {
+ const allUserFiles = username.directories.reduce(
+ (accumulator_, directory) => {
+ accumulator_ = accumulator_.concat(directory.files);
+ return accumulator_;
+ },
+ [],
+ );
+
+ accumulator = accumulator.concat(allUserFiles);
+ return accumulator;
}, []);
- return files.filter(file => file.direction.toLowerCase() === direction);
- }, [transfers, direction]);
+ return files.filter((file) => file.direction.toLowerCase() === direction);
+ }, [direction, transfers]);
const empty = files.length === 0;
const working = retrying || cancelling || removing;
return (
- <Segment className='transfers-header-segment' raised>
- <div className="transfers-segment-icon"><Icon name={direction} size="big"/></div>
- <Div hidden={empty} className="transfers-header-buttons">
+ <Segment
+ className="transfers-header-segment"
+ raised
+ >
+ <div className="transfers-segment-icon">
+ <Icon
+ name={direction}
+ size="big"
+ />
+ </div>
+ <Div
+ className="transfers-header-buttons"
+ hidden={empty}
+ >
<ShrinkableDropdownButton
- hidden={direction === 'upload'}
- color='green'
- icon='redo'
- mediaQuery='(max-width: 715px)'
- onClick={() => onRetryAll(getRetryableFiles({ files, retryOption }))}
+ color="green"
disabled={working || empty || !server.isConnected}
+ hidden={direction === 'upload'}
+ icon="redo"
loading={retrying}
+ mediaQuery="(max-width: 715px)"
+ onChange={(_, data) => setRetryOption(data.value)}
+ onClick={() => onRetryAll(getRetryableFiles({ files, retryOption }))}
options={[
{ key: 'errored', text: 'Errored', value: 'Errored' },
{ key: 'cancelled', text: 'Cancelled', value: 'Cancelled' },
{ key: 'all', text: 'All', value: 'All' },
]}
- onChange={(_, data) => setRetryOption(data.value)}
>
{`Retry ${retryOption === 'All' ? retryOption : `All ${retryOption}`}`}
</ShrinkableDropdownButton>
- <Nbsp/>
+ <Nbsp />
<ShrinkableDropdownButton
- color='red'
- icon='x'
- mediaQuery='(max-width: 715px)'
- onClick={() => onCancelAll(getCancellableFiles({ files, cancelOption }))}
+ color="red"
disabled={working || empty}
+ icon="x"
loading={cancelling}
+ mediaQuery="(max-width: 715px)"
+ onChange={(_, data) => setCancelOption(data.value)}
+ onClick={() =>
+ onCancelAll(getCancellableFiles({ cancelOption, files }))
+ }
options={[
{ key: 'all', text: 'All', value: 'All' },
{ key: 'queued', text: 'Queued', value: 'Queued' },
{ key: 'inProgress', text: 'In Progress', value: 'In Progress' },
]}
- onChange={(_, data) => setCancelOption(data.value)}
>
{`Cancel ${cancelOption === 'All' ? cancelOption : `All ${cancelOption}`}`}
</ShrinkableDropdownButton>
- <Nbsp/>
+ <Nbsp />
<ShrinkableDropdownButton
- icon='trash alternate'
- mediaQuery='(max-width: 715px)'
- onClick={() => onRemoveAll(getRemovableFiles({ files, removeOption }))}
disabled={working || empty}
+ icon="trash alternate"
loading={removing}
+ mediaQuery="(max-width: 715px)"
+ onChange={(_, data) => setRemoveOption(data.value)}
+ onClick={() =>
+ onRemoveAll(getRemovableFiles({ files, removeOption }))
+ }
options={[
{ key: 'succeeded', text: 'Succeeded', value: 'Succeeded' },
{ key: 'errored', text: 'Errored', value: 'Errored' },
{ key: 'cancelled', text: 'Cancelled', value: 'Cancelled' },
{ key: 'completed', text: 'Completed', value: 'Completed' },
]}
- onChange={(_, data) => setRemoveOption(data.value)}
>
{`Remove All ${removeOption}`}
</ShrinkableDropdownButton>
@@ -152,4 +169,4 @@ const TransfersHeader = ({
);
};
-export default TransfersHeader; \ No newline at end of file
+export default TransfersHeader;
diff --git a/src/web/src/components/Users/User.jsx b/src/web/src/components/Users/User.jsx
index d4da80ee..41581db0 100644
--- a/src/web/src/components/Users/User.jsx
+++ b/src/web/src/components/Users/User.jsx
@@ -1,10 +1,13 @@
-import {
- Item,
- Icon,
-} from 'semantic-ui-react';
+import { Icon, Item } from 'semantic-ui-react';
-const ImagePlaceholder = () =>
- (<div className='users-picture-placeholder ui small image'><Icon name='camera' size='big'/></div>);
+const ImagePlaceholder = () => (
+ <div className="users-picture-placeholder ui small image">
+ <Icon
+ name="camera"
+ size="big"
+ />
+ </div>
+);
const Presence = ({ presence }) => {
const colors = {
@@ -12,48 +15,58 @@ const Presence = ({ presence }) => {
Online: 'green',
};
- return <Icon name='circle' color={colors[presence] || 'grey'}/>;
+ return (
+ <Icon
+ color={colors[presence] || 'grey'}
+ name="circle"
+ />
+ );
};
const FreeUploadSlot = ({ hasFreeUploadSlot }) => (
- <Icon
- name={hasFreeUploadSlot ? 'check' : 'close'}
+ <Icon
color={hasFreeUploadSlot ? 'green' : 'red'}
+ name={hasFreeUploadSlot ? 'check' : 'close'}
/>
);
-const User = ({
- username,
- description,
- hasFreeUploadSlot,
- hasPicture,
- picture,
- queueLength,
- uploadSlots,
- updatedAt,
- isPrivileged,
- presence,
+const User = ({
address,
+ description,
+ hasFreeUploadSlot,
+ hasPicture,
+ isPrivileged,
+ picture,
port,
+ presence,
+ queueLength,
+ updatedAt,
+ uploadSlots,
+ username,
}) => (
- <>
- <Item>
- {hasPicture ?
- <Item.Image size='small' src={`data:image;base64,${picture}`} />
- : <ImagePlaceholder/>}
+ <Item>
+ {hasPicture ? (
+ <Item.Image
+ size="small"
+ src={`data:image;base64,${picture}`}
+ />
+ ) : (
+ <ImagePlaceholder />
+ )}
- <Item.Content>
- <Item.Header as='a'><Presence presence={presence}/>{username}</Item.Header>
- <Item.Meta>
- Free Upload Slot: <FreeUploadSlot hasFreeUploadSlot />,
- Total Upload Slots: {uploadSlots}, Queue Length: {queueLength}, IP Address: {address}, Port: {port}
- </Item.Meta>
- <Item.Description>
- {description || 'No user info.'}
- </Item.Description>
- </Item.Content>
- </Item>
- </>
+ <Item.Content>
+ <Item.Header as="a">
+ <Presence presence={presence} />
+ {username}
+ </Item.Header>
+ <Item.Meta>
+ Free Upload Slot: <FreeUploadSlot hasFreeUploadSlot />, Total Upload
+ Slots: {uploadSlots}, Queue Length: {queueLength}, IP Address: {address}
+ , Port: {port}
+ </Item.Meta>
+ <Item.Description>{description || 'No user info.'}</Item.Description>
+ </Item.Content>
+ </Item>
);
-export default User; \ No newline at end of file
+export default User;
diff --git a/src/web/src/components/Users/Users.jsx b/src/web/src/components/Users/Users.jsx
index b887d962..5639e3cc 100644
--- a/src/web/src/components/Users/Users.jsx
+++ b/src/web/src/components/Users/Users.jsx
@@ -1,25 +1,20 @@
-import React, { useState, useEffect, useLayoutEffect, useRef } from 'react';
-import {
- Item,
- Segment,
- Loader,
- Input,
- Icon,
-} from 'semantic-ui-react';
-
-import User from './User';
+import './Users.css';
import { activeUserInfoKey } from '../../config';
import * as users from '../../lib/users';
-
-import './Users.css';
import PlaceholderSegment from '../Shared/PlaceholderSegment';
+import User from './User';
+import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { Icon, Input, Item, Loader, Segment } from 'semantic-ui-react';
const Users = (props) => {
const inputRef = useRef();
const [user, setUser] = useState();
const [usernameInput, setUsernameInput] = useState();
const [selectedUsername, setSelectedUsername] = useState(undefined);
- const [{ fetching, error }, setStatus] = useState({ fetching: false, error: undefined });
+ const [{ error, fetching }, setStatus] = useState({
+ error: undefined,
+ fetching: false,
+ });
useEffect(() => {
document.addEventListener('keyup', keyUp, false);
@@ -42,7 +37,7 @@ const Users = (props) => {
return;
}
- setStatus({ fetching: true, error: undefined });
+ setStatus({ error: undefined, fetching: true });
try {
const [info, status, endpoint] = await Promise.all([
@@ -50,12 +45,12 @@ const Users = (props) => {
users.getStatus({ username: selectedUsername }),
users.getEndpoint({ username: selectedUsername }),
]);
-
+
localStorage.setItem(activeUserInfoKey, selectedUsername);
setUser({ ...info.data, ...status.data, ...endpoint.data });
- setStatus({ fetching: false, error: undefined });
+ setStatus({ error: undefined, fetching: false });
} catch (error) {
- setStatus({ fetching: false, error: error });
+ setStatus({ error, fetching: false });
}
};
@@ -78,44 +73,80 @@ const Users = (props) => {
inputRef.current.focus();
};
- const keyUp = (e) => e.key === 'Escape' ? clear() : '';
+ const keyUp = (e) => (e.key === 'Escape' ? clear() : '');
return (
- <div className='users-container'>
- <Segment className='users-segment' raised>
- <div className="users-segment-icon"><Icon name="users" size="big"/></div>
+ <div className="users-container">
+ <Segment
+ className="users-segment"
+ raised
+ >
+ <div className="users-segment-icon">
+ <Icon
+ name="users"
+ size="big"
+ />
+ </div>
<Input
+ action={
+ !fetching &&
+ (!user
+ ? {
+ icon: 'search',
+ onClick: () => setSelectedUsername(usernameInput),
+ }
+ : { color: 'red', icon: 'x', onClick: clear })
+ }
+ className="users-input"
+ disabled={fetching}
input={
- <input placeholder="Username" type="search" data-lpignore="true" disabled={!!user || fetching}></input>}
- size='big'
+ <input
+ data-lpignore="true"
+ disabled={Boolean(user) || fetching}
+ placeholder="Username"
+ type="search"
+ />
+ }
loading={fetching}
- disabled={fetching}
- ref={inputRef}
- className='users-input'
- placeholder="Username"
onChange={(e) => setUsernameInput(e.target.value)}
- action={!fetching && (!user
- ? { icon: 'search', onClick: () => setSelectedUsername(usernameInput) }
- : { icon: 'x', color: 'red', onClick: clear })}
- onKeyUp={(e) => e.key === 'Enter' ? setSelectedUsername(usernameInput) : ''}
+ onKeyUp={(e) =>
+ e.key === 'Enter' ? setSelectedUsername(usernameInput) : ''
+ }
+ placeholder="Username"
+ ref={inputRef}
+ size="big"
/>
</Segment>
- {fetching ?
- <Loader className='search-loader' active inline='centered' size='big'/> :
+ {fetching ? (
+ <Loader
+ active
+ className="search-loader"
+ inline="centered"
+ size="big"
+ />
+ ) : (
<div>
- {error ?
- <span>Failed to retrieve information for {selectedUsername}</span> :
- !user ?
- <PlaceholderSegment icon='users' caption='No user info to display'/> :
- <Segment className='users-user' raised>
- <Item.Group>
- <User {...user}/>
- </Item.Group>
- </Segment>}
+ {error ? (
+ <span>Failed to retrieve information for {selectedUsername}</span>
+ ) : !user ? (
+ <PlaceholderSegment
+ caption="No user info to display"
+ icon="users"
+ />
+ ) : (
+ <Segment
+ className="users-user"
+ raised
+ >
+ <Item.Group>
+ <User {...user} />
+ </Item.Group>
+ </Segment>
+ )}
</div>
- }
+ )}
</div>
);
};
-export default Users; \ No newline at end of file
+export default Users;
diff --git a/src/web/src/config.js b/src/web/src/config.js
index 9dc19b5c..5f808e9b 100644
--- a/src/web/src/config.js
+++ b/src/web/src/config.js
@@ -1,6 +1,9 @@
const urlBase = (window.urlBase === '/' ? '' : window.urlBase) || '';
-const devPort = window.port ?? 5030;
-const rootUrl = process.env.NODE_ENV === 'production' ? urlBase : `http://localhost:${devPort}${urlBase}`;
+const developmentPort = window.port ?? 5_030;
+const rootUrl =
+ process.env.NODE_ENV === 'production'
+ ? urlBase
+ : `http://localhost:${developmentPort}${urlBase}`;
const apiBaseUrl = `${rootUrl}/api/v0`;
const hubBaseUrl = `${rootUrl}/hub`;
const tokenKey = 'slskd-token';
@@ -10,13 +13,13 @@ const activeRoomKey = 'slskd-active-room';
const activeUserInfoKey = 'slskd-active-user';
export {
- urlBase,
- rootUrl,
+ activeChatKey,
+ activeRoomKey,
+ activeUserInfoKey,
apiBaseUrl,
hubBaseUrl,
+ rootUrl,
tokenKey,
tokenPassthroughValue,
- activeChatKey,
- activeRoomKey,
- activeUserInfoKey,
+ urlBase,
};
diff --git a/src/web/src/index.jsx b/src/web/src/index.jsx
index 0a2df315..537b5e62 100644
--- a/src/web/src/index.jsx
+++ b/src/web/src/index.jsx
@@ -1,10 +1,12 @@
+import 'semantic-ui-less/semantic.less';
+import App from './components/App';
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
-import 'semantic-ui-less/semantic.less';
-import App from './components/App';
ReactDOM.render(
<Router>
<App />
- </Router>, document.getElementById('root')); \ No newline at end of file
+ </Router>,
+ document.querySelector('#root'),
+);
diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js
index 0de23c11..8f3a4c90 100644
--- a/src/web/src/lib/api.js
+++ b/src/web/src/lib/api.js
@@ -1,6 +1,6 @@
-import axios from 'axios';
import { apiBaseUrl } from '../config';
import * as session from './session';
+import axios from 'axios';
axios.defaults.baseURL = apiBaseUrl;
@@ -8,7 +8,7 @@ const api = axios.create({
withCredentials: true,
});
-api.interceptors.request.use(config => {
+api.interceptors.request.use((config) => {
const token = session.getToken();
config.headers['Content-Type'] = 'application/json';
@@ -20,19 +20,26 @@ api.interceptors.request.use(config => {
return config;
});
-api.interceptors.response.use(response => {
- return response;
-}, error => {
- if (error.response.status === 401 && !['/session', '/server', '/application'].includes(error.response.config.url)) {
- console.debug('received 401 from api route, logging out');
- session.logout();
- window.location.reload(true);
-
- return Promise.reject(error);
- }
- else {
- return Promise.reject(error);
- }
-});
-
-export default api; \ No newline at end of file
+api.interceptors.response.use(
+ (response) => {
+ return response;
+ },
+ (error) => {
+ if (
+ error.response.status === 401 &&
+ !['/session', '/server', '/application'].includes(
+ error.response.config.url,
+ )
+ ) {
+ console.debug('received 401 from api route, logging out');
+ session.logout();
+ window.location.reload(true);
+
+ return Promise.reject(error);
+ } else {
+ return Promise.reject(error);
+ }
+ },
+);
+
+export default api;
diff --git a/src/web/src/lib/application.js b/src/web/src/lib/application.js
index 20260d9b..1a80b2a9 100644
--- a/src/web/src/lib/application.js
+++ b/src/web/src/lib/application.js
@@ -13,5 +13,6 @@ export const shutdown = async () => {
};
export const getVersion = async ({ forceCheck = false }) => {
- return (await api.get(`/application/version/latest?forceCheck=${forceCheck}`)).data;
-}; \ No newline at end of file
+ return (await api.get(`/application/version/latest?forceCheck=${forceCheck}`))
+ .data;
+};
diff --git a/src/web/src/lib/chat.js b/src/web/src/lib/chat.js
index 31edcc8b..428ab031 100644
--- a/src/web/src/lib/chat.js
+++ b/src/web/src/lib/chat.js
@@ -13,9 +13,12 @@ export const acknowledge = ({ username }) => {
};
export const send = ({ username, message }) => {
- return api.post(`/conversations/${encodeURIComponent(username)}`, JSON.stringify(message));
+ return api.post(
+ `/conversations/${encodeURIComponent(username)}`,
+ JSON.stringify(message),
+ );
};
export const remove = ({ username }) => {
return api.delete(`/conversations/${encodeURIComponent(username)}`);
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/files.js b/src/web/src/lib/files.js
index 9284fb1b..99a82b2c 100644
--- a/src/web/src/lib/files.js
+++ b/src/web/src/lib/files.js
@@ -1,22 +1,21 @@
import api from './api';
export const list = async ({ root, subdirectory = '' }) => {
- subdirectory = btoa(subdirectory);
- const response = (await api.get(`/files/${root}/directories/${subdirectory}`)).data;
+ const response = (
+ await api.get(`/files/${root}/directories/${btoa(subdirectory)}`)
+ ).data;
return response;
};
export const deleteDirectory = async ({ root, path }) => {
- path = btoa(path);
- const response = (await api.delete(`/files/${root}/directories/${path}`));
+ const response = await api.delete(`/files/${root}/directories/${btoa(path)}`);
return response;
};
export const deleteFile = async ({ root, path }) => {
- path = btoa(path);
- const response = (await api.delete(`/files/${root}/files/${path}`));
+ const response = await api.delete(`/files/${root}/files/${btoa(path)}`);
return response;
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js
index 7d84864e..b764ed4a 100644
--- a/src/web/src/lib/hubFactory.js
+++ b/src/web/src/lib/hubFactory.js
@@ -1,25 +1,31 @@
+import { hubBaseUrl } from '../config';
+import * as session from './session';
import {
- JsonHubProtocol,
HubConnectionBuilder,
+ JsonHubProtocol,
LogLevel,
} from '@microsoft/signalr';
-import { hubBaseUrl } from '../config';
-import * as session from '../lib/session';
-
-export const createHubConnection = ({ url }) =>
+export const createHubConnection = ({ url }) =>
new HubConnectionBuilder()
.withUrl(url, {
+ accessTokenFactory: session.isPassthroughEnabled()
+ ? undefined
+ : session.getToken,
withCredentials: true,
- accessTokenFactory: session.isPassthroughEnabled() ? undefined : session.getToken,
})
- .withAutomaticReconnect([0, 100, 250, 500, 1000, 2000, 3000, 5000, 5000, 5000, 5000, 5000])
+ .withAutomaticReconnect([
+ 0, 100, 250, 500, 1_000, 2_000, 3_000, 5_000, 5_000, 5_000, 5_000, 5_000,
+ ])
.withHubProtocol(new JsonHubProtocol())
.configureLogging(LogLevel.Warning)
.build();
-export const createApplicationHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/application` });
+export const createApplicationHubConnection = () =>
+ createHubConnection({ url: `${hubBaseUrl}/application` });
-export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` });
+export const createLogsHubConnection = () =>
+ createHubConnection({ url: `${hubBaseUrl}/logs` });
-export const createSearchHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/search`});
+export const createSearchHubConnection = () =>
+ createHubConnection({ url: `${hubBaseUrl}/search` });
diff --git a/src/web/src/lib/options.js b/src/web/src/lib/options.js
index 32e48534..620be946 100644
--- a/src/web/src/lib/options.js
+++ b/src/web/src/lib/options.js
@@ -22,4 +22,4 @@ export const validateYaml = async ({ yaml }) => {
export const updateYaml = async ({ yaml }) => {
return (await api.post('/options/yaml', yaml)).data;
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/relay.js b/src/web/src/lib/relay.js
index b20d0af2..35149f02 100644
--- a/src/web/src/lib/relay.js
+++ b/src/web/src/lib/relay.js
@@ -6,4 +6,4 @@ export const connect = () => {
export const disconnect = () => {
return api.delete('/relay');
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/rooms.js b/src/web/src/lib/rooms.js
index 96b01446..35da6701 100644
--- a/src/web/src/lib/rooms.js
+++ b/src/web/src/lib/rooms.js
@@ -23,7 +23,9 @@ export const getJoined = async () => {
};
export const getMessages = async ({ roomName }) => {
- const response = (await api.get(`/rooms/joined/${encodeURIComponent(roomName)}/messages`)).data;
+ const response = (
+ await api.get(`/rooms/joined/${encodeURIComponent(roomName)}/messages`)
+ ).data;
if (!Array.isArray(response)) {
console.warn('got non-array response from rooms API', response);
@@ -34,7 +36,9 @@ export const getMessages = async ({ roomName }) => {
};
export const getUsers = async ({ roomName }) => {
- const response = (await api.get(`/rooms/joined/${encodeURIComponent(roomName)}/users`)).data;
+ const response = (
+ await api.get(`/rooms/joined/${encodeURIComponent(roomName)}/users`)
+ ).data;
if (!Array.isArray(response)) {
console.warn('got non-array response from rooms API', response);
@@ -53,5 +57,8 @@ export const leave = async ({ roomName }) => {
};
export const sendMessage = async ({ roomName, message }) => {
- return api.post(`/rooms/joined/${encodeURIComponent(roomName)}/messages`, JSON.stringify(message));
-}; \ No newline at end of file
+ return api.post(
+ `/rooms/joined/${encodeURIComponent(roomName)}/messages`,
+ JSON.stringify(message),
+ );
+};
diff --git a/src/web/src/lib/searches.js b/src/web/src/lib/searches.js
index a0e97820..5fbe257f 100644
--- a/src/web/src/lib/searches.js
+++ b/src/web/src/lib/searches.js
@@ -17,11 +17,17 @@ export const create = ({ id, searchText }) => {
};
export const getStatus = async ({ id, includeResponses = false }) => {
- return (await api.get(`/searches/${encodeURIComponent(id)}?includeResponses=${includeResponses}`)).data;
+ return (
+ await api.get(
+ `/searches/${encodeURIComponent(id)}?includeResponses=${includeResponses}`,
+ )
+ ).data;
};
export const getResponses = async ({ id }) => {
- const response = (await api.get(`/searches/${encodeURIComponent(id)}/responses`)).data;
+ const response = (
+ await api.get(`/searches/${encodeURIComponent(id)}/responses`)
+ ).data;
if (!Array.isArray(response)) {
console.warn('got non-array response from searches API', response);
@@ -33,106 +39,148 @@ export const getResponses = async ({ id }) => {
export const parseFiltersFromString = (string) => {
const filters = {
- minBitRate: 0,
- minBitDepth: 0,
- minFileSize: 0,
- minLength: 0,
- minFilesInFolder: 0,
- include: [],
exclude: [],
- isVBR: false,
+ include: [],
isCBR: false,
isLossless: false,
isLossy: false,
+ isVBR: false,
+ minBitDepth: 0,
+ minBitRate: 0,
+ minFilesInFolder: 0,
+ minFileSize: 0,
+ minLength: 0,
};
const getNthMatch = (string, regex, n) => {
const match = string.match(regex);
-
+
if (match) {
- return parseInt(match[n], 10);
+ return Number.parseInt(match[n], 10);
}
};
- filters.minBitRate = getNthMatch(string, /(minbr|minbitrate):([0-9]+)/i, 2) || filters.minBitRate;
- filters.minBitDepth = getNthMatch(string, /(minbd|minbitdepth):([0-9]+)/i, 2) || filters.minBitDepth;
- filters.minFileSize = getNthMatch(string, /(minfs|minfilesize):([0-9]+)/i, 2) || filters.minFileSize;
- filters.minLength = getNthMatch(string, /(minlen|minlength):([0-9]+)/i, 2) || filters.minLength;
- filters.minFilesInFolder = getNthMatch(string, /(minfif|minfilesinfolder):([0-9]+)/i, 2) || filters.minFilesInFolder;
-
- filters.isVBR = !!string.match(/isvbr/i);
- filters.isCBR = !!string.match(/iscbr/i);
- filters.isLossless = !!string.match(/islossless/i);
- filters.isLossy = !!string.match(/islossy/i);
-
- let terms = string.toLowerCase().split(' ')
- .filter(term =>
- !term.includes(':') && term !== 'isvbr' && term !== 'iscbr' && term !== 'islossless' && term !== 'islossy');
-
- filters.include = terms.filter(term => !term.startsWith('-'));
- filters.exclude = terms.filter(term => term.startsWith('-')).map(term => term.slice(1));
+ filters.minBitRate =
+ getNthMatch(string, /(minbr|minbitrate):(\d+)/i, 2) || filters.minBitRate;
+ filters.minBitDepth =
+ getNthMatch(string, /(minbd|minbitdepth):(\d+)/i, 2) || filters.minBitDepth;
+ filters.minFileSize =
+ getNthMatch(string, /(minfs|minfilesize):(\d+)/i, 2) || filters.minFileSize;
+ filters.minLength =
+ getNthMatch(string, /(minlen|minlength):(\d+)/i, 2) || filters.minLength;
+ filters.minFilesInFolder =
+ getNthMatch(string, /(minfif|minfilesinfolder):(\d+)/i, 2) ||
+ filters.minFilesInFolder;
+
+ filters.isVBR = Boolean(/isvbr/i.test(string));
+ filters.isCBR = Boolean(/iscbr/i.test(string));
+ filters.isLossless = Boolean(/islossless/i.test(string));
+ filters.isLossy = Boolean(/islossy/i.test(string));
+
+ const terms = string
+ .toLowerCase()
+ .split(' ')
+ .filter(
+ (term) =>
+ !term.includes(':') &&
+ term !== 'isvbr' &&
+ term !== 'iscbr' &&
+ term !== 'islossless' &&
+ term !== 'islossy',
+ );
+
+ filters.include = terms.filter((term) => !term.startsWith('-'));
+ filters.exclude = terms
+ .filter((term) => term.startsWith('-'))
+ .map((term) => term.slice(1));
return filters;
};
-export const filterResponse = ({
+export const filterResponse = ({
filters = {
- minBitRate: 0,
- minBitDepth: 0,
- minFileSize: 0,
- minLength: 0,
- include: [],
exclude: [],
- isVBR: false,
+ include: [],
isCBR: false,
isLossless: false,
isLossy: false,
+ isVBR: false,
+ minBitDepth: 0,
+ minBitRate: 0,
+ minFileSize: 0,
+ minLength: 0,
},
- response = {
+ response = {
files: [],
lockedFiles: [],
- },
+ },
}) => {
- let { files = [], lockedFiles = [] } = response;
+ const { files = [], lockedFiles = [] } = response;
- if (response.fileCount + response.lockedFileCount < filters.minFilesInFolder) {
+ if (
+ response.fileCount + response.lockedFileCount <
+ filters.minFilesInFolder
+ ) {
return { ...response, files: [] };
}
- const filterFiles = (files) => files.filter(file => {
- const { bitRate, size, length, filename, sampleRate, bitDepth, isVariableBitRate } = file;
- const {
- isCBR, isVBR, isLossless, isLossy,
- minBitRate, minBitDepth, minFileSize, minLength,
- include = [], exclude = [],
- } = filters;
-
- if (isCBR && (isVariableBitRate === undefined || isVariableBitRate)) return false;
- if (isVBR && (isVariableBitRate === undefined || !isVariableBitRate)) return false;
- if (isLossless && (!sampleRate || !bitDepth)) return false;
- if (isLossy && (sampleRate || bitDepth)) return false;
- if (bitRate < minBitRate) return false;
- if (bitDepth < minBitDepth) return false;
- if (size < minFileSize) return false;
- if (length < minLength) return false;
-
- if (include.length > 0 && include.filter(term => filename.toLowerCase().includes(term)).length !== include.length) {
- return false;
- }
-
- if (exclude.length > 0 && exclude.filter(term => filename.toLowerCase().includes(term)).length !== 0) return false;
-
- return true;
- });
+ const filterFiles = (files) =>
+ files.filter((file) => {
+ const {
+ bitRate,
+ size,
+ length,
+ filename,
+ sampleRate,
+ bitDepth,
+ isVariableBitRate,
+ } = file;
+ const {
+ isCBR,
+ isVBR,
+ isLossless,
+ isLossy,
+ minBitRate,
+ minBitDepth,
+ minFileSize,
+ minLength,
+ include = [],
+ exclude = [],
+ } = filters;
+
+ if (isCBR && (isVariableBitRate === undefined || isVariableBitRate))
+ return false;
+ if (isVBR && (isVariableBitRate === undefined || !isVariableBitRate))
+ return false;
+ if (isLossless && (!sampleRate || !bitDepth)) return false;
+ if (isLossy && (sampleRate || bitDepth)) return false;
+ if (bitRate < minBitRate) return false;
+ if (bitDepth < minBitDepth) return false;
+ if (size < minFileSize) return false;
+ if (length < minLength) return false;
+
+ if (
+ include.length > 0 &&
+ include.filter((term) => filename.toLowerCase().includes(term))
+ .length !== include.length
+ ) {
+ return false;
+ }
+
+ if (exclude.some((term) => filename.toLowerCase().includes(term)))
+ return false;
+
+ return true;
+ });
const filteredFiles = filterFiles(files);
const filteredLockedFiles = filterFiles(lockedFiles);
- return {
+ return {
...response,
fileCount: filteredFiles.length,
+ files: filteredFiles,
lockedFileCount: filteredLockedFiles.length,
- files: filteredFiles,
lockedFiles: filteredLockedFiles,
};
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/searches.test.js b/src/web/src/lib/searches.test.js
index 8baf02ab..925c3025 100644
--- a/src/web/src/lib/searches.test.js
+++ b/src/web/src/lib/searches.test.js
@@ -11,10 +11,8 @@ describe('filterResponse', () => {
const filters = { isCBR: true };
- expect(search.filterResponse({ response, filters })).toMatchObject({
- files: [
- { bitRate: 320, isVariableBitRate: false },
- ],
+ expect(search.filterResponse({ filters, response })).toMatchObject({
+ files: [{ bitRate: 320, isVariableBitRate: false }],
});
});
@@ -28,24 +26,19 @@ describe('filterResponse', () => {
const filters = { isVBR: true };
- expect(search.filterResponse({ response, filters })).toMatchObject({
- files: [
- { bitRate: 123, isVariableBitRate: true },
- ],
+ expect(search.filterResponse({ filters, response })).toMatchObject({
+ files: [{ bitRate: 123, isVariableBitRate: true }],
});
});
it('removes all files if "iscbr" and "isvbr" are both specified', () => {
const response = {
- files: [
- { isVariableBitrate: true },
- { isVariableBitrate: false },
- ],
+ files: [{ isVariableBitrate: true }, { isVariableBitrate: false }],
};
const filters = { isCBR: true, isVBR: true };
- expect(search.filterResponse({ response, filters })).toMatchObject({
+ expect(search.filterResponse({ filters, response })).toMatchObject({
files: [],
});
});
@@ -53,85 +46,66 @@ describe('filterResponse', () => {
it('removes lossy files if "islossless" is specified', () => {
const response = {
files: [
- { sampleRate: 41000, bitDepth: 16 },
+ { bitDepth: 16, sampleRate: 41_000 },
{ bitRate: 320, isVariableBitRate: false },
],
};
const filters = { isLossless: true };
- expect(search.filterResponse({ response, filters })).toMatchObject({
- files: [
- { sampleRate: 41000, bitDepth: 16 },
- ],
+ expect(search.filterResponse({ filters, response })).toMatchObject({
+ files: [{ bitDepth: 16, sampleRate: 41_000 }],
});
});
it('removes lossless files if "islossy" is specified', () => {
const response = {
files: [
- { sampleRate: 41000, bitDepth: 16 },
+ { bitDepth: 16, sampleRate: 41_000 },
{ bitRate: 320, isVariableBitRate: false },
],
};
const filters = { isLossy: true };
- expect(search.filterResponse({ response, filters })).toMatchObject({
- files: [
- { bitRate: 320, isVariableBitRate: false },
- ],
+ expect(search.filterResponse({ filters, response })).toMatchObject({
+ files: [{ bitRate: 320, isVariableBitRate: false }],
});
});
it('removes files with bitRate less than minBitRate', () => {
const response = {
- files: [
- { bitRate: 100 },
- { bitRate: 99 },
- ],
+ files: [{ bitRate: 100 }, { bitRate: 99 }],
};
const filters = { minBitRate: 100 };
- expect(search.filterResponse({ response, filters })).toMatchObject({
- files: [
- { bitRate: 100 },
- ],
+ expect(search.filterResponse({ filters, response })).toMatchObject({
+ files: [{ bitRate: 100 }],
});
});
it('removes files with size less than minFileSize', () => {
const response = {
- files: [
- { size: 100 },
- { size: 99 },
- ],
+ files: [{ size: 100 }, { size: 99 }],
};
const filters = { minFileSize: 100 };
- expect(search.filterResponse({ response, filters })).toMatchObject({
- files: [
- { size: 100 },
- ],
+ expect(search.filterResponse({ filters, response })).toMatchObject({
+ files: [{ size: 100 }],
});
});
it('removes files with length less than minLength', () => {
const response = {
- files: [
- { length: 100 },
- { length: 99 },
- ],
+ files: [{ length: 100 }, { length: 99 }],
};
const filters = { minLength: 100 };
- expect(search.filterResponse({ response, filters })).toMatchObject({
- files: [
- { length: 100 },
- ],
+ expect(search.filterResponse({ filters, response })).toMatchObject({
+ files: [{ length: 100 }],
});
});
@@ -149,18 +123,16 @@ describe('filterResponse', () => {
it('removes files with filenames not containing included phrases', () => {
const filters = { include: ['path', 'to', '.nfo'] };
-
- expect(search.filterResponse({ response, filters })).toMatchObject({
- files: [
- { filename: '/path/to/info.nfo' },
- ],
+
+ expect(search.filterResponse({ filters, response })).toMatchObject({
+ files: [{ filename: '/path/to/info.nfo' }],
});
});
-
+
it('removes files with filenames containing excluded phrases', () => {
const filters = { exclude: ['bar', 'jpg', 'qux'] };
-
- expect(search.filterResponse({ response, filters })).toMatchObject({
+
+ expect(search.filterResponse({ filters, response })).toMatchObject({
files: [
{ filename: '/path/to/foo.mp3' },
{ filename: '/path/to/baz.mp3' },
@@ -168,14 +140,14 @@ describe('filterResponse', () => {
],
});
});
-
+
it('removes a mix of includes and excludes', () => {
- const filters = {
+ const filters = {
+ exclude: ['foo', 'bar'],
include: ['path', '.mp3'],
- exclude: ['foo', 'bar'],
};
-
- expect(search.filterResponse({ response, filters })).toMatchObject({
+
+ expect(search.filterResponse({ filters, response })).toMatchObject({
files: [
{ filename: '/path/to/baz.mp3' },
{ filename: '/path/to/qux.mp3' },
@@ -191,7 +163,9 @@ describe('parseFiltersFromString', () => {
minBitRate: 42,
});
- expect(search.parseFiltersFromString('foo minbitrate:123 bar')).toMatchObject({
+ expect(
+ search.parseFiltersFromString('foo minbitrate:123 bar'),
+ ).toMatchObject({
minBitRate: 123,
});
});
@@ -201,7 +175,9 @@ describe('parseFiltersFromString', () => {
minFileSize: 42,
});
- expect(search.parseFiltersFromString('foo minfilesize:123 bar')).toMatchObject({
+ expect(
+ search.parseFiltersFromString('foo minfilesize:123 bar'),
+ ).toMatchObject({
minFileSize: 123,
});
});
@@ -211,7 +187,9 @@ describe('parseFiltersFromString', () => {
minLength: 42,
});
- expect(search.parseFiltersFromString('foo minlength:123 bar')).toMatchObject({
+ expect(
+ search.parseFiltersFromString('foo minlength:123 bar'),
+ ).toMatchObject({
minLength: 123,
});
});
@@ -221,37 +199,39 @@ describe('parseFiltersFromString', () => {
minFilesInFolder: 42,
});
- expect(search.parseFiltersFromString('foo minfilesinfolder:123 bar')).toMatchObject({
+ expect(
+ search.parseFiltersFromString('foo minfilesinfolder:123 bar'),
+ ).toMatchObject({
minFilesInFolder: 123,
});
});
it('returns correct list of terms', () => {
expect(search.parseFiltersFromString('foo minbr:42 bar')).toMatchObject({
- include: [ 'foo', 'bar'],
+ include: ['foo', 'bar'],
});
expect(search.parseFiltersFromString('foo iscbr isvbr bar')).toMatchObject({
- include: [ 'foo', 'bar'],
+ include: ['foo', 'bar'],
});
expect(search.parseFiltersFromString('foo some:thing bar')).toMatchObject({
- include: [ 'foo', 'bar'],
+ include: ['foo', 'bar'],
});
expect(search.parseFiltersFromString('foo -bar')).toMatchObject({
- include: [ 'foo' ],
- exclude: [ 'bar' ],
+ exclude: ['bar'],
+ include: ['foo'],
});
expect(search.parseFiltersFromString('-foo -bar -baz qux')).toMatchObject({
- exclude: [ 'foo', 'bar', 'baz' ],
- include: [ 'qux' ],
+ exclude: ['foo', 'bar', 'baz'],
+ include: ['qux'],
});
expect(search.parseFiltersFromString('foo bar baz -qux')).toMatchObject({
- include: [ 'foo', 'bar', 'baz' ],
- exclude: [ 'qux' ],
+ exclude: ['qux'],
+ include: ['foo', 'bar', 'baz'],
});
});
@@ -266,12 +246,16 @@ describe('parseFiltersFromString', () => {
});
it('returns expected filters given a bit of everything', () => {
- expect(search.parseFiltersFromString('big -mix of:everything isvbr iscbr minbr:42')).toMatchObject({
- include: [ 'big' ],
- exclude: [ 'mix' ],
- isVBR: true,
+ expect(
+ search.parseFiltersFromString(
+ 'big -mix of:everything isvbr iscbr minbr:42',
+ ),
+ ).toMatchObject({
+ exclude: ['mix'],
+ include: ['big'],
isCBR: true,
+ isVBR: true,
minBitRate: 42,
});
});
-}); \ No newline at end of file
+});
diff --git a/src/web/src/lib/server.js b/src/web/src/lib/server.js
index 13881df7..a8190859 100644
--- a/src/web/src/lib/server.js
+++ b/src/web/src/lib/server.js
@@ -8,6 +8,8 @@ export const connect = () => {
return api.put('/server');
};
-export const disconnect = ({ message = 'client disconnected from web UI' } = {}) => {
+export const disconnect = ({
+ message = 'client disconnected from web UI',
+} = {}) => {
return api.delete('/server', { data: JSON.stringify(message) });
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/session.js b/src/web/src/lib/session.js
index c46c5eb7..01f2ab61 100644
--- a/src/web/src/lib/session.js
+++ b/src/web/src/lib/session.js
@@ -1,7 +1,8 @@
-import api from './api';
import { tokenKey, tokenPassthroughValue } from '../config';
+import api from './api';
-export const getToken = () => sessionStorage.getItem(tokenKey) || localStorage.getItem(tokenKey);
+export const getToken = () =>
+ sessionStorage.getItem(tokenKey) || localStorage.getItem(tokenKey);
const setToken = (storage, token) => storage.setItem(tokenKey, token);
export const getSecurityEnabled = async () => {
@@ -9,7 +10,9 @@ export const getSecurityEnabled = async () => {
};
export const enablePassthrough = () => {
- console.debug('enabling token passthrough. api calls will not be authenticated');
+ console.debug(
+ 'enabling token passthrough. api calls will not be authenticated',
+ );
setToken(sessionStorage, tokenPassthroughValue);
};
@@ -17,11 +20,13 @@ export const isPassthroughEnabled = () => getToken() === tokenPassthroughValue;
export const isLoggedIn = () => {
const token = getToken();
- return token !== undefined && token !== null && token !== tokenPassthroughValue;
-};
+ return (
+ token !== undefined && token !== null && token !== tokenPassthroughValue
+ );
+};
export const login = async ({ username, password, rememberMe = false }) => {
- const { token } = (await api.post('/session', { username, password })).data;
+ const { token } = (await api.post('/session', { password, username })).data;
setToken(rememberMe ? localStorage : sessionStorage, token);
return token;
};
@@ -45,4 +50,4 @@ export const check = async () => {
throw error;
}
}
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/shares.js b/src/web/src/lib/shares.js
index c400e08e..8e3d3600 100644
--- a/src/web/src/lib/shares.js
+++ b/src/web/src/lib/shares.js
@@ -24,4 +24,4 @@ export const rescan = async () => {
export const cancel = async () => {
return (await api.delete('/shares')).data;
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/transfers.js b/src/web/src/lib/transfers.js
index c95f8f76..7fa58fc3 100644
--- a/src/web/src/lib/transfers.js
+++ b/src/web/src/lib/transfers.js
@@ -1,7 +1,9 @@
import api from './api';
export const getAll = async ({ direction }) => {
- const response = (await api.get(`/transfers/${encodeURIComponent(direction)}s`)).data;
+ const response = (
+ await api.get(`/transfers/${encodeURIComponent(direction)}s`)
+ ).data;
if (!Array.isArray(response)) {
console.warn('got non-array response from transfers API', response);
@@ -12,12 +14,16 @@ export const getAll = async ({ direction }) => {
};
export const download = ({ username, files = [] }) => {
- return api.post(`/transfers/downloads/${encodeURIComponent(username)}`, files);
+ return api.post(
+ `/transfers/downloads/${encodeURIComponent(username)}`,
+ files,
+ );
};
export const cancel = ({ direction, username, id, remove = false }) => {
return api.delete(
- `/transfers/${direction}s/${encodeURIComponent(username)}/${encodeURIComponent(id)}?remove=${remove}`);
+ `/transfers/${direction}s/${encodeURIComponent(username)}/${encodeURIComponent(id)}?remove=${remove}`,
+ );
};
export const clearCompleted = ({ direction }) => {
@@ -36,13 +42,22 @@ export const clearCompleted = ({ direction }) => {
// 'Completed, Rejected'
export const getPlaceInQueue = ({ username, id }) => {
- return api.get(`/transfers/downloads/${encodeURIComponent(username)}/${encodeURIComponent(id)}/position`);
+ return api.get(
+ `/transfers/downloads/${encodeURIComponent(username)}/${encodeURIComponent(id)}/position`,
+ );
};
export const isStateRetryable = (state) =>
state.includes('Completed') && state !== 'Completed, Succeeded';
export const isStateCancellable = (state) =>
- ['InProgress', 'Requested', 'Queued', 'Queued, Remotely', 'Queued, Locally', 'Initializing'].find(s => s === state);
+ [
+ 'InProgress',
+ 'Requested',
+ 'Queued',
+ 'Queued, Remotely',
+ 'Queued, Locally',
+ 'Initializing',
+ ].find((s) => s === state);
export const isStateRemovable = (state) => state.includes('Completed');
diff --git a/src/web/src/lib/users.js b/src/web/src/lib/users.js
index 4545310f..abfa6b5b 100644
--- a/src/web/src/lib/users.js
+++ b/src/web/src/lib/users.js
@@ -21,5 +21,9 @@ export const getBrowseStatus = ({ username }) => {
};
export const getDirectoryContents = async ({ username, directory }) => {
- return (await api.post(`/users/${encodeURIComponent(username)}/directory`, { directory })).data;
-}; \ No newline at end of file
+ return (
+ await api.post(`/users/${encodeURIComponent(username)}/directory`, {
+ directory,
+ })
+ ).data;
+};
diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js
index dbd8f482..1da9e864 100644
--- a/src/web/src/lib/util.js
+++ b/src/web/src/lib/util.js
@@ -1,34 +1,36 @@
-export const formatSeconds = (seconds) =>
-{
+export const formatSeconds = (seconds) => {
if (isNaN(seconds)) return '';
- var date = new Date(1970,0,1);
+ const date = new Date(1_970, 0, 1);
date.setSeconds(seconds);
- if (seconds >= 3600) {
+ if (seconds >= 3_600) {
return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, '$1');
}
+
return date.toTimeString().replace(/.*(\d{2}:\d{2}).*/, '$1');
};
export const formatBytesAsUnit = (bytes, decimals = 2, unit) => {
if (unit === 'B') return bytes + ' ' + unit;
- const k = 1024;
+ const k = 1_024;
const dm = decimals < 0 ? 0 : decimals;
- const sizes = {'KB': 1, 'MB': 2, 'GB': 3, 'TB': 4, 'PB': 5, 'EB': 6, 'ZB': 7, 'YB': 8};
+ const sizes = { EB: 6, GB: 3, KB: 1, MB: 2, PB: 5, TB: 4, YB: 8, ZB: 7 };
- return parseFloat((bytes / Math.pow(k, sizes[unit])).toFixed(dm));
+ return Number.parseFloat((bytes / k ** sizes[unit]).toFixed(dm));
};
export const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '0 B';
- const k = 1024;
+ const k = 1_024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
+ const index = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
+ return (
+ Number.parseFloat((bytes / k ** index).toFixed(dm)) + ' ' + sizes[index]
+ );
};
export const formatDate = (date) => {
@@ -42,20 +44,27 @@ export const getFileName = (fullPath) => {
export const getDirectoryName = (fullPath) => {
let path = fullPath;
- if (path.lastIndexOf('\\') > 0)
- {path = path.substring(0, path.lastIndexOf('\\'));}
+ if (path.lastIndexOf('\\') > 0) {
+ path = path.slice(0, Math.max(0, path.lastIndexOf('\\')));
+ }
- if (path.lastIndexOf('/') > 0)
- {path = path.substring(0, path.lastIndexOf('/'));}
+ if (path.lastIndexOf('/') > 0) {
+ path = path.slice(0, Math.max(0, path.lastIndexOf('/')));
+ }
return path;
};
-export const formatAttributes = ({ bitRate, isVariableBitRate, bitDepth, sampleRate }) => {
- const isLossless = !!sampleRate && !!bitDepth;
+export const formatAttributes = ({
+ bitRate,
+ isVariableBitRate,
+ bitDepth,
+ sampleRate,
+}) => {
+ const isLossless = Boolean(sampleRate) && Boolean(bitDepth);
if (isLossless) {
- return `${bitDepth}/${sampleRate/1000}kHz`;
+ return `${bitDepth}/${sampleRate / 1_000}kHz`;
}
if (isVariableBitRate) {
@@ -66,54 +75,53 @@ export const formatAttributes = ({ bitRate, isVariableBitRate, bitDepth, sampleR
};
export const sleep = (milliseconds) => {
- return new Promise(resolve => setTimeout(resolve, milliseconds));
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
};
/* https://www.npmjs.com/package/js-file-download
- *
+ *
* Copyright 2017 Kenneth Jiang
*
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
- * The above copyright notice and this permission notice shall be included in all copies or substantial portions
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE
*/
export const downloadFile = (data, filename, mime) => {
- var blob = new Blob([data], {type: mime || 'application/octet-stream'});
+ const blob = new Blob([data], { type: mime || 'application/octet-stream' });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
- // IE workaround for "HTML7007: One or more blob URLs were
- // revoked by closing the blob for which they were created.
- // These URLs will no longer resolve as the data backing
+ // IE workaround for "HTML7007: One or more blob URLs were
+ // revoked by closing the blob for which they were created.
+ // These URLs will no longer resolve as the data backing
// the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
- }
- else {
- var blobURL = window.URL.createObjectURL(blob);
- var tempLink = document.createElement('a');
- tempLink.style.display = 'none';
- tempLink.href = blobURL;
- tempLink.setAttribute('download', filename);
-
+ } else {
+ const blobURL = window.URL.createObjectURL(blob);
+ const temporaryLink = document.createElement('a');
+ temporaryLink.style.display = 'none';
+ temporaryLink.href = blobURL;
+ temporaryLink.setAttribute('download', filename);
+
// Safari thinks _blank anchor are pop ups. We only want to set _blank
// target if the browser does not support the HTML5 download attribute.
- // This allows you to download files in desktop safari if pop up blocking
+ // This allows you to download files in desktop safari if pop up blocking
// is enabled.
- if (typeof tempLink.download === 'undefined') {
- tempLink.setAttribute('target', '_blank');
+ if (typeof temporaryLink.download === 'undefined') {
+ temporaryLink.setAttribute('target', '_blank');
}
-
- document.body.appendChild(tempLink);
- tempLink.click();
- document.body.removeChild(tempLink);
+
+ document.body.append(temporaryLink);
+ temporaryLink.click();
+ temporaryLink.remove();
window.URL.revokeObjectURL(blobURL);
}
-}; \ No newline at end of file
+};
diff --git a/src/web/src/lib/util.test.js b/src/web/src/lib/util.test.js
index 5fe92af7..0507cb56 100644
--- a/src/web/src/lib/util.test.js
+++ b/src/web/src/lib/util.test.js
@@ -1,5 +1,5 @@
import * as utils from './util';
-it('converts bytes to specified unit', () => {
- expect(utils.formatBytesAsUnit(1234567, 2, 'MB')).toBe(1.18);
-}); \ No newline at end of file
+test('converts bytes to specified unit', () => {
+ expect(utils.formatBytesAsUnit(1_234_567, 2, 'MB')).toBe(1.18);
+});