aboutsummaryrefslogtreecommitdiffstats
path: root/src/web
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-05-17 10:55:31 -0500
committerGitHub <noreply@github.com>2022-05-17 10:55:31 -0500
commit8ea2d8a4d88180a103081cce7a425c2bb6172b03 (patch)
tree7292443fa34f2cca21c432ed338d9013aa240d84 /src/web
parent978d0d08ab34a9e5dd0211de1d242a264b17577e (diff)
parentdaf5e72ad63109978eeef2d0c4377b942f6209cb (diff)
downloadslskd-8ea2d8a4d88180a103081cce7a425c2bb6172b03.tar.gz
Merge branch 'master' into dependabot/npm_and_yarn/src/web/ejs-3.1.8
Diffstat (limited to 'src/web')
-rw-r--r--src/web/src/components/App.css14
-rw-r--r--src/web/src/components/App.js6
-rw-r--r--src/web/src/components/Search/Detail/SearchDetail.js214
-rw-r--r--src/web/src/components/Search/Detail/SearchDetailHeader.js72
-rw-r--r--src/web/src/components/Search/List/SearchActionIcon.js27
-rw-r--r--src/web/src/components/Search/List/SearchList.js76
-rw-r--r--src/web/src/components/Search/List/SearchListRow.js60
-rw-r--r--src/web/src/components/Search/Response.js7
-rw-r--r--src/web/src/components/Search/Search.css46
-rw-r--r--src/web/src/components/Search/Search.js306
-rw-r--r--src/web/src/components/Search/SearchStatusIcon.js35
-rw-r--r--src/web/src/components/Search/Searches.js209
-rw-r--r--src/web/src/components/Shared/LoaderSegment.js11
-rw-r--r--src/web/src/components/Shared/Switch.js11
-rw-r--r--src/web/src/config.js2
-rw-r--r--src/web/src/lib/hubFactory.js6
-rw-r--r--src/web/src/lib/searches.js (renamed from src/web/src/lib/search.js)14
-rw-r--r--src/web/src/lib/searches.test.js (renamed from src/web/src/lib/search.test.js)2
-rw-r--r--src/web/src/lib/util.js4
19 files changed, 804 insertions, 318 deletions
diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css
index 6244cdf8..1f52554c 100644
--- a/src/web/src/components/App.css
+++ b/src/web/src/components/App.css
@@ -31,7 +31,11 @@ body {
width: 100% !important;
}
-.result-card:last-child, .transfer-card:last-child {
+.search-list-card {
+ width: 100% !important;
+}
+
+.result-card:last-child, .transfer-card:last-child, .search-list-card:last-child {
margin-bottom: 17px !important;
}
@@ -56,7 +60,7 @@ body {
margin-top: 20px !important;
}
-.filelist-selector, .transferlist-selector {
+.filelist-selector, .transferlist-selector, .list-selector {
width: 40px;
}
@@ -141,4 +145,8 @@ body {
.menu-icon-no-shadow {
font-size: 1rem !important;
text-shadow: unset !important;
-} \ No newline at end of file
+}
+
+.loader-segment.ui.placeholder > :before {
+ background-color: transparent !important;
+}
diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js
index 09f3f742..9654c2ff 100644
--- a/src/web/src/components/App.js
+++ b/src/web/src/components/App.js
@@ -8,7 +8,7 @@ import { urlBase } from '../config';
import { createApplicationHubConnection } from '../lib/hubFactory';
import './App.css';
-import Search from './Search/Search';
+import Searches from './Search/Searches';
import Browse from './Browse/Browse';
import Users from './Users/Users';
import Transfers from './Transfers/Transfers';
@@ -243,7 +243,7 @@ class App extends Component {
</Sidebar>
<Sidebar.Pusher className='app-content'>
<Switch>
- <Route path={`${urlBase}/searches`} render={(props) => this.withTokenCheck(<Search {...props}/>)}/>
+ <Route path={`${urlBase}/searches/:id?`} render={(props) => this.withTokenCheck(<div className='search-container'><Searches {...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}/>)}/>
@@ -259,4 +259,4 @@ class App extends Component {
};
};
-export default App;
+export default App; \ No newline at end of file
diff --git a/src/web/src/components/Search/Detail/SearchDetail.js b/src/web/src/components/Search/Detail/SearchDetail.js
new file mode 100644
index 00000000..880d5cd0
--- /dev/null
+++ b/src/web/src/components/Search/Detail/SearchDetail.js
@@ -0,0 +1,214 @@
+import React, { useEffect, useState, useMemo } from 'react';
+
+import {
+ Checkbox,
+ Input,
+ Segment,
+ Dropdown,
+ Button,
+} from 'semantic-ui-react';
+
+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 SearchDetailHeader from './SearchDetailHeader';
+
+const sortDropdownOptions = [
+ { 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, onCreate, onStop, onRemove }) => {
+ const { id, state, isComplete, fileCount, lockedFileCount, responseCount } = search;
+
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(undefined);
+
+ const [results, setResults] = useState([]);
+
+ // filters and sorting options
+ const [hiddenResults, setHiddenResults] = useState([]);
+ const [resultSort, setResultSort] = useState('uploadSpeed');
+ const [hideLocked, setHideLocked] = useState(true);
+ const [hideNoFreeSlots, setHideNoFreeSlots] = useState(false);
+ const [foldResults, setFoldResults] = useState(false);
+ const [resultFilters, setResultFilters] = useState('');
+ const [displayCount, setDisplayCount] = useState(5);
+
+ // when the search transitions from !isComplete -> isComplete,
+ // fetch the results from the server
+ useEffect(() => {
+ const get = async () => {
+ try {
+ setLoading(true);
+
+ // 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);
+ } catch (error) {
+ setError(error);
+ setLoading(false);
+ }
+ }
+
+ if (isComplete) {
+ get();
+ }
+ }, [id, isComplete])
+
+ // apply sorting and filters. this can take a while for larger result
+ // sets, so memoize it.
+ const sortedAndFilteredResults = useMemo(() => {
+ const sortOptions = {
+ uploadSpeed: { field: 'uploadSpeed', order: 'desc' },
+ queueLength: { field: 'queueLength', order: 'asc' }
+ }
+
+ const { field, order } = sortOptions[resultSort];
+
+ const filters = parseFiltersFromString(resultFilters);
+
+ return results
+ .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.freeUploadSlots === 0))
+ .sort((a, b) => {
+ if (order === 'asc') {
+ return a[field] - b[field];
+ }
+
+ return b[field] - a[field];
+ });
+
+ }, [results, hideLocked, hideNoFreeSlots, resultFilters, resultSort, hiddenResults])
+
+ // 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
+ const reset = () => {
+ setLoading(false);
+ setError(undefined);
+ setResults([]);
+ setHiddenResults([]);
+ setDisplayCount(5);
+ }
+
+ const create = async ({ search, navigate }) => {
+ reset();
+ onCreate({ search, navigate })
+ }
+
+ const remove = async () => {
+ reset();
+ onRemove(search);
+ }
+
+ const filteredCount = results?.length - sortedAndFilteredResults.length;
+ const remainingCount = sortedAndFilteredResults.length - displayCount;
+ const loaded = (!removing && !creating && !loading && results && results.length > 0)
+
+ if (error) {
+ return (<ErrorSegment caption={error?.message ?? error}/>)
+ }
+
+ return (
+ <>
+ <SearchDetailHeader
+ loading={loading}
+ loaded={loaded}
+ removing={removing}
+ stopping={stopping}
+ creating={creating}
+ search={search}
+ onCreate={create}
+ onStop={onStop}
+ onRemove={remove}
+ />
+ <Switch
+ 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>
+ <Dropdown
+ button
+ className='search-options-sort icon'
+ floating
+ labeled
+ icon='sort'
+ options={sortDropdownOptions}
+ onChange={(e, { value }) => setResultSort(value)}
+ text={sortDropdownOptions.find(o => o.value === resultSort).text}
+ />
+ <div className='search-option-toggles'>
+ <Checkbox
+ className='search-options-hide-locked'
+ toggle
+ onChange={() => setHideLocked(!hideLocked)}
+ checked={hideLocked}
+ label='Hide Locked Results'
+ />
+ <Checkbox
+ className='search-options-hide-no-slots'
+ toggle
+ onChange={() => setHideNoFreeSlots(!hideNoFreeSlots)}
+ checked={hideNoFreeSlots}
+ label='Hide Results with No Free Slots'
+ />
+ <Checkbox
+ className='search-options-fold-results'
+ toggle
+ onChange={() => setFoldResults(!foldResults)}
+ checked={foldResults}
+ label='Fold Results'
+ />
+ </div>
+ <Input
+ className='search-filter'
+ placeholder='lackluster container -bothersome iscbr|isvbr islossless|islossy minbitrate:320 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}
+ 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> : '')}
+ </Switch>
+ </>
+ )
+}
+
+export default SearchDetail; \ No newline at end of file
diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.js b/src/web/src/components/Search/Detail/SearchDetailHeader.js
new file mode 100644
index 00000000..d31f8a49
--- /dev/null
+++ b/src/web/src/components/Search/Detail/SearchDetailHeader.js
@@ -0,0 +1,72 @@
+import React from 'react';
+import { useMediaQuery } from 'react-responsive';
+
+import {
+ Segment,
+ Button,
+ Header,
+ Icon,
+} from 'semantic-ui-react';
+import SearchStatusIcon from '../SearchStatusIcon';
+
+const SearchDetailHeader = ({ search, loading, loaded, creating, removing, stopping, onCreate, onStop, onRemove }) => {
+ const isSmallScreen = useMediaQuery({ query: '(max-width: 899px)' });
+ const isTinyScreen = useMediaQuery({ query: '(max-width: 684px)'});
+
+ const { searchText, isComplete, state } = search;
+ const working = loading || creating || removing || stopping;
+
+ const stopOrRemove = () => {
+ if (isComplete) {
+ onRemove(search);
+ } else {
+ onStop(search);
+ }
+ }
+
+ const RefreshButton = () => loaded &&
+ <Button
+ disabled={working}
+ icon={isSmallScreen && !isTinyScreen}
+ onClick={() => onCreate({ search: searchText, navigate: true })}
+ loading={creating}
+ >
+ <Icon name='refresh'/>{(!isSmallScreen || isTinyScreen) && 'Search Again'}
+ </Button>
+
+ const StopOrDeleteButton = () =>
+ <Button
+ negative
+ disabled={working}
+ onClick={stopOrRemove}
+ loading={removing || stopping}
+ floated={isTinyScreen ? 'right' : undefined}
+ icon={isSmallScreen && !isTinyScreen}
+ >
+ <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-segment' raised>
+ <Header className='search-detail-header'>
+ <SearchStatusIcon state={state}/>{searchText}
+ </Header>
+ {!isTinyScreen && <div className='search-detail-action-button'>
+ <RefreshButton/>
+ <StopOrDeleteButton/>
+ </div>}
+ </Segment>
+ {isTinyScreen && <Segment>
+ <RefreshButton/>
+ <StopOrDeleteButton/>
+ </Segment>}
+ </>
+ )
+};
+
+export default SearchDetailHeader; \ No newline at end of file
diff --git a/src/web/src/components/Search/List/SearchActionIcon.js b/src/web/src/components/Search/List/SearchActionIcon.js
new file mode 100644
index 00000000..98455241
--- /dev/null
+++ b/src/web/src/components/Search/List/SearchActionIcon.js
@@ -0,0 +1,27 @@
+import React from 'react';
+
+import { Icon } from 'semantic-ui-react';
+
+const SearchActionIcon = ({ search, loading, onRemove, onStop,...props }) => {
+ if (loading) {
+ return (<Icon name='spinner' loading {...props}/>)
+ }
+
+ if (search.state.includes('Completed')) {
+ return (<Icon
+ name="trash alternate"
+ color='red'
+ onClick={() => onRemove()}
+ style={{ cursor: 'pointer' }}
+ />)
+ }
+
+ return (<Icon
+ name="stop circle"
+ color="red"
+ onClick={() => onStop()}
+ style={{ cursor: 'pointer' }}
+ />)
+};
+
+export default SearchActionIcon; \ No newline at end of file
diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js
new file mode 100644
index 00000000..c65c949d
--- /dev/null
+++ b/src/web/src/components/Search/List/SearchList.js
@@ -0,0 +1,76 @@
+import React, { useMemo } from 'react';
+
+import SearchListRow from './SearchListRow';
+import ErrorSegment from '../../Shared/ErrorSegment';
+import Switch from '../../Shared/Switch';
+
+import {
+ Card,
+ Table,
+ Icon,
+ Loader,
+ Segment,
+ Header,
+ List
+} from 'semantic-ui-react';
+
+const SearchList = ({ connecting = false, error = undefined, searches = {}, onRemove = () => {}, onStop = () => {} }) => {
+ const searchCount = useMemo(() => {
+ return Object.values(searches).length
+ }, [searches])
+
+ return (
+ <Card className='search-list-card' raised>
+ <Card.Content>
+ <div style={{marginTop: -20 }}>
+ <Switch
+ connecting={connecting && <Loader active inline='centered' size='small'/>}
+ error={error && <ErrorSegment caption={error} />}
+ >
+ <Header size='small' className='filelist-header'>
+ <div>
+ <Icon size='large' name='search'/>
+ Searches
+ </div>
+ </Header>
+ <List>
+ <List.Item>
+ <Switch
+ noSearches={!searchCount &&
+ <Segment basic style={{opacity: .5}} textAlign='center'>No searches to display</Segment>
+ }
+ >
+ <Table 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.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}
+ />)}
+ </Table.Body>
+ </Table>
+ </Switch>
+ </List.Item>
+ </List>
+ </Switch>
+ </div>
+ </Card.Content>
+ </Card>
+ )
+};
+
+export default SearchList; \ No newline at end of file
diff --git a/src/web/src/components/Search/List/SearchListRow.js b/src/web/src/components/Search/List/SearchListRow.js
new file mode 100644
index 00000000..c2552892
--- /dev/null
+++ b/src/web/src/components/Search/List/SearchListRow.js
@@ -0,0 +1,60 @@
+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';
+
+const SearchListRow = ({ search, onRemove, onStop }) => {
+ const [working, setWorking] = useState(false);
+ const match = useRouteMatch();
+
+ const invoke = async (func) => {
+ setWorking(true);
+
+ try {
+ await func();
+ } catch (error) {
+ console.error(error);
+ } finally {
+ setWorking(false);
+ }
+ }
+
+ return (
+ <Table.Row
+ disabled={working}
+ style={{ cursor: working ? 'wait' : undefined }}
+ >
+ <Table.Cell>
+ <SearchStatusIcon
+ state={search.state}
+ />
+ </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>{search.responseCount}</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))}
+ style={{ cursor: 'pointer' }}
+ />
+ </Table.Cell>
+ </Table.Row>
+ )
+}
+
+export default SearchListRow; \ No newline at end of file
diff --git a/src/web/src/components/Search/Response.js b/src/web/src/components/Search/Response.js
index 8d134047..7ffb70d4 100644
--- a/src/web/src/components/Search/Response.js
+++ b/src/web/src/components/Search/Response.js
@@ -86,6 +86,13 @@ class Response extends Component {
/>
<Icon name='circle' color={free ? 'green' : 'yellow'}/>
{response.username}
+ <Icon
+ className='close-button'
+ name='close'
+ color='red'
+ link
+ onClick={() => this.props.onHide()}
+ />
</Card.Header>
<Card.Meta className='result-meta'>
<span>Upload Speed: {formatBytes(response.uploadSpeed)}/s, Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength}</span>
diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css
index 750c5c2d..42912ed5 100644
--- a/src/web/src/components/Search/Search.css
+++ b/src/web/src/components/Search/Search.css
@@ -15,6 +15,12 @@
height: 78px !important;
}
+.search-card {
+ width: 1200px !important;
+ margin-left: auto !important;
+ margin-right: auto !important;
+}
+
@media only screen and (min-width: 991px) {
.search-options-hide-no-slots, .search-options-hide-locked, .search-options-fold-results {
margin-left: 1rem;
@@ -25,7 +31,7 @@
}
}
-@media only screen and (max-width: 685px) {
+@media only screen and (max-width: 684px) {
.search-options-sort {
width: 100%;
}
@@ -63,4 +69,42 @@
.search-filter {
width: 100%;
margin-top: 1rem;
+}
+
+.search-list-icon {
+ width: 40px !important;
+}
+
+.search-list-phrase {
+ word-wrap: break-word !important;
+}
+
+.search-list-responses {
+ width: 30px !important;
+}
+
+.search-list-files {
+ width: 80px !important;
+}
+
+.search-list-locked {
+ width: 100px !important;
+}
+
+.search-list-started {
+ width: 120px !important;
+}
+
+.search-list-action {
+ width: 5px !important;
+}
+
+.search-detail-header {
+ font-weight: normal !important;
+ margin-top: 12px !important;
+}
+
+.search-detail-action-button {
+ float: right;
+ margin-top: -48px !important;
} \ No newline at end of file
diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js
deleted file mode 100644
index 3dbcc939..00000000
--- a/src/web/src/components/Search/Search.js
+++ /dev/null
@@ -1,306 +0,0 @@
-import { v4 as uuidv4 } from 'uuid';
-import React, { Component } from 'react';
-import * as search from '../../lib/search';
-
-import './Search.css';
-
-import Response from './Response';
-import PlaceholderSegment from '../Shared/PlaceholderSegment';
-
-import {
- Segment,
- Input,
- Loader,
- Button,
- Dropdown,
- Checkbox
-} from 'semantic-ui-react';
-
-const initialState = {
- searchPhrase: '',
- searchId: undefined,
- searchState: 'idle',
- searchStatus: {
- responseCount: 0,
- fileCount: 0
- },
- results: [],
- interval: undefined,
- displayCount: 5,
- resultSort: 'uploadSpeed',
- hideNoFreeSlots: true,
- hiddenResults: [],
- hideLocked: true,
- fetching: false,
- resultFilters: '',
- foldResults: false,
-};
-
-const sortOptions = {
- uploadSpeed: { field: 'uploadSpeed', order: 'desc' },
- queueLength: { field: 'queueLength', order: 'asc' }
-}
-
-const sortDropdownOptions = [
- { key: 'uploadSpeed', text: 'Upload Speed (Fastest to Slowest)', value: 'uploadSpeed' },
- { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' }
-];
-
-class Search extends Component {
- state = initialState;
-
- search = () => {
- const searchPhrase = this.inputtext.inputRef.current.value;
- const searchId = uuidv4();
-
- this.setState({ searchPhrase, searchId, searchState: 'pending' }, async () => {
- this.saveState();
- search.search({ id: searchId, searchText: searchPhrase });
- });
- }
-
- clear = () => {
- this.setState(initialState, () => {
- this.saveState();
- this.setSearchText();
- this.inputtext.focus();
- });
- }
-
- keyUp = (event) => event.key === 'Escape' ? this.clear() : '';
-
- onSearchPhraseChange = (event, data) => {
- this.setState({ searchPhrase: data.value });
- }
-
- onResultFilterChange = (event, data) => {
- this.setState({ resultFilters: data.value }, () => this.saveState());
- }
-
- clearResultFilter = () => {
- this.setState({ resultFilters: '' }, () => this.saveState());
- }
-
- saveState = () => {
- try {
- localStorage.setItem('soulseek-example-search-state', JSON.stringify({ ...this.state, results: [] }));
- } catch(error) {
- console.log(error);
- }
- }
-
- loadState = () => {
- return new Promise((resolve) =>
- this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState, resolve));
- }
-
- componentDidMount = async () => {
- await this.loadState();
- this.fetchResults();
- this.setState({
- interval: window.setInterval(this.fetchStatus, 500)
- }, () => this.setSearchText());
-
- document.addEventListener("keyup", this.keyUp, false);
- }
-
- setSearchText = () => {
- this.inputtext.inputRef.current.value = this.state.searchPhrase;
- this.inputtext.inputRef.current.disabled = this.state.searchState !== 'idle';
- }
-
- componentWillUnmount = () => {
- clearInterval(this.state.interval);
- this.setState({ interval: undefined });
- document.removeEventListener("keyup", this.keyUp, false);
- }
-
- fetchResults = async () => {
- const { searchId } = this.state;
-
- if (!!searchId) {
- this.setState({ fetching: true }, async () => {
- try {
- const responses = await search.getResponses({ id: searchId });
-
- this.setState({
- results: responses,
- fetching: false
- }, this.saveState);
- } catch (error) {
- console.log(error);
- this.clear();
- }
- });
- }
- }
-
- fetchStatus = async () => {
- const { searchState, searchId } = this.state;
-
- if (searchState === 'pending') {
- this.setState({ fetching: true }, async () => {
- const response = await search.getStatus({ id: searchId });
-
- if (response.isComplete) {
- this.setState({
- searchState: 'complete'
- }, this.fetchResults);
- } else {
- this.setState({
- searchStatus: response,
- fetching: false
- }, this.saveState);
- }
- });
- }
- }
-
- showMore = () => {
- this.setState({ displayCount: this.state.displayCount + 5 }, () => this.saveState());
- }
-
- sortAndFilterResults = () => {
- const { results = [], hideNoFreeSlots, resultSort, resultFilters = '', hideLocked, hiddenResults = [] } = this.state;
- const { field, order } = sortOptions[resultSort];
-
- const filters = search.parseFiltersFromString(resultFilters);
-
- return results
- .filter(r => !hiddenResults.includes(r.username))
- .map(r => {
- if (hideLocked) {
- return { ...r, lockedFileCount: 0, lockedFiles: [] }
- }
- return r;
- })
- .map(response => search.filterResponse({ response, filters }))
- .filter(r => r.fileCount + r.lockedFileCount > 0)
- .filter(r => !(hideNoFreeSlots && r.freeUploadSlots === 0))
- .sort((a, b) => {
- if (order === 'asc') {
- return a[field] - b[field];
- }
-
- return b[field] - a[field];
- });
- }
-
- hideResult = (result) => {
- this.setState({ hiddenResults: [...this.state.hiddenResults, result.username]}, () => {
- if (this.state.hiddenResults.length === this.state.results.length) {
- this.clear();
- } else {
- this.saveState();
- }
- });
- }
-
- render = () => {
- let { searchState, searchStatus, results = [], displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults = [], fetching, resultFilters, foldResults } = this.state;
- let pending = fetching || searchState === 'pending';
-
- const sortedAndFilteredResults = this.sortAndFilterResults();
-
- const remainingCount = sortedAndFilteredResults.length - displayCount;
- const showMoreCount = remainingCount >= 5 ? 5 : remainingCount;
- const hiddenCount = results.length - hiddenResults.length - sortedAndFilteredResults.length;
-
- return (
- <div className='search-container'>
- <Segment className='search-segment' raised>
- <Input
- input={<input placeholder="Search phrase" type="search" data-lpignore="true"></input>}
- size='big'
- ref={input => this.inputtext = input}
- loading={pending}
- disabled={pending}
- className='search-input'
- placeholder="Search phrase"
- action={!pending && (searchState === 'idle' ? { icon: 'search', onClick: this.search } : { icon: 'x', color: 'red', onClick: this.clear })}
- onKeyUp={(e) => e.key === 'Enter' ? this.search() : ''}
- />
- </Segment>
- {pending ?
- <Loader
- className='search-loader'
- active
- inline='centered'
- size='big'
- >
- {searchState === 'pending' ? <span>Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users</span>
- : 'Loading results...'}
- </Loader>
- :
- <div>
- {(results && results.length > 0) ?
- <Segment className='search-options' raised>
- <Dropdown
- button
- className='search-options-sort icon'
- floating
- labeled
- icon='sort'
- options={sortDropdownOptions}
- onChange={(e, { value }) => this.setState({ resultSort: value }, () => this.saveState())}
- text={sortDropdownOptions.find(o => o.value === resultSort).text}
- />
- <div className='search-option-toggles'>
- <Checkbox
- className='search-options-hide-locked'
- toggle
- onChange={() => this.setState({ hideLocked: !hideLocked }, () => this.saveState())}
- checked={hideLocked}
- label='Hide Locked Results'
- />
- <Checkbox
- className='search-options-hide-no-slots'
- toggle
- onChange={() => this.setState({ hideNoFreeSlots: !hideNoFreeSlots }, () => this.saveState())}
- checked={hideNoFreeSlots}
- label='Hide Results with No Free Slots'
- />
- <Checkbox
- className='search-options-fold-results'
- toggle
- onChange={() => this.setState({ foldResults: !foldResults }, () => this.saveState())}
- checked={foldResults}
- label='Fold Results'
- />
- </div>
- <Input
- className='search-filter'
- placeholder='lackluster container -bothersome iscbr|isvbr islossless|islossy minbitrate:320 minfilesize:10 minfilesinfolder:8 minlength:5000'
- label={{ icon: 'filter', content: 'Filter' }}
- value={resultFilters}
- onChange={this.onResultFilterChange}
- action={!!resultFilters && { icon: 'x', color: 'red', onClick: this.clearResultFilter }}
- />
- </Segment> : <PlaceholderSegment icon='search'/>
- }
- {sortedAndFilteredResults.slice(0, displayCount).map((r, i) =>
- <Response
- key={i}
- response={r}
- onDownload={this.props.onDownload}
- onHide={() => this.hideResult(r)}
- isInitiallyFolded={foldResults}
- />
- )}
- {remainingCount > 0 ?
- <Button
- className='showmore-button'
- size='large'
- fluid
- primary
- onClick={() => this.showMore()}>
- Show {showMoreCount} More Results {remainingCount > 5 ? `(${remainingCount} remaining, ${hiddenCount} hidden by filter(s))` : ''}
- </Button>
- : ''}
- </div>}
- </div>
- )
- }
-}
-
-export default Search; \ No newline at end of file
diff --git a/src/web/src/components/Search/SearchStatusIcon.js b/src/web/src/components/Search/SearchStatusIcon.js
new file mode 100644
index 00000000..9ade1daf
--- /dev/null
+++ b/src/web/src/components/Search/SearchStatusIcon.js
@@ -0,0 +1,35 @@
+import React from 'react';
+
+import { Icon, Popup } from 'semantic-ui-react';
+
+// as of 4.5.2, states are:
+// transient:
+// None, Requested, InProgress
+// terminal:
+// good: Completed, [TimedOut | ResponseLimitReached | FileLimitReached]
+// bad: Completed, [Errored | Cancelled]
+
+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}/>
+ }
+}
+
+const SearchStatusIcon = ({ state, ...props }) =>
+ <Popup content={state} trigger={getIcon({ state, ...props })}/>
+
+export default SearchStatusIcon; \ No newline at end of file
diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js
new file mode 100644
index 00000000..b21f62b6
--- /dev/null
+++ b/src/web/src/components/Search/Searches.js
@@ -0,0 +1,209 @@
+import React, { useState, useEffect, useRef } from 'react';
+import { v4 as uuidv4 } from 'uuid';
+import { useParams, useHistory, useRouteMatch } from 'react-router-dom';
+
+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,
+} from 'semantic-ui-react';
+
+import SearchDetail from './Detail/SearchDetail';
+import ErrorSegment from '../Shared/ErrorSegment';
+
+const Searches = () => {
+ const [connecting, setConnecting] = useState(true);
+ const [error, setError] = useState(undefined);
+ const [searches, setSearches] = useState({});
+
+ const [removing, setRemoving] = useState(false);
+ const [stopping, setStopping] = useState(false);
+ const [creating, setCreating] = useState(false);
+
+ const inputRef = useRef();
+
+ const { id: searchId } = useParams();
+ const history = useHistory();
+ const match = useRouteMatch();
+
+ const onConnecting = () => { setConnecting(true); }
+ const onConnected = () => { setConnecting(false); setError(undefined); }
+ const onConnectionError = (error) => { setConnecting(false); setError(error); }
+
+ const onUpdate = (update) => {
+ onConnected();
+ setSearches(update);
+ }
+
+ useEffect(() => {
+ onConnecting();
+
+ const searchHub = createSearchHubConnection();
+
+ searchHub.on('list', searches => {
+ onUpdate(searches.reduce((acc, search) => {
+ acc[search.id] = search;
+ return acc;
+ }, {}));
+ onConnected();
+ })
+
+ searchHub.on('update', search => {
+ onUpdate(old => ({ ...old, [search.id]: search }));
+ });
+
+ searchHub.on('delete', search => {
+ onUpdate(old => {
+ delete old[search.id];
+ return { ...old }
+ });
+ });
+
+ searchHub.on('create', () => {});
+
+ searchHub.onreconnecting((error) => onConnectionError(error?.message ?? 'Disconnected'));
+ searchHub.onreconnected(() => onConnected());
+ searchHub.onclose((error) => onConnectionError(error?.message ?? 'Disconnected'));
+
+ const connect = async () => {
+ try {
+ onConnecting();
+ await searchHub.start();
+ } catch (error) {
+ onConnectionError(error?.message ?? 'Failed to connect')
+ }
+ }
+
+ connect();
+
+ return () => {
+ searchHub.stop();
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // 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 searchText = search || inputRef.current.inputRef.current.value;
+ const id = uuidv4();
+
+ try {
+ setCreating(true)
+ await lib.create({ id, searchText })
+
+ try {
+ inputRef.current.inputRef.current.value = '';
+ } 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)
+ setCreating(false)
+ }
+ }
+
+ // delete a search
+ const remove = async (search) => {
+ try {
+ setRemoving(true);
+
+ await lib.remove({ id: search.id })
+ setSearches(old => {
+ delete old[search.id];
+ return { ...old }
+ });
+
+ setRemoving(false);
+ } catch (err) {
+ console.error(err);
+ setRemoving(false);
+ }
+ };
+
+ // stop an in-progress search
+ const stop = async (search) => {
+ try {
+ setStopping(true);
+ await lib.stop({ id: search.id })
+ setStopping(false);
+ } catch (error) {
+ console.error(error);
+ setStopping(false);
+ }
+ }
+
+ if (connecting) {
+ return <LoaderSegment/>
+ }
+
+ if (error) {
+ return <ErrorSegment caption={error?.message ?? error}/>;
+ }
+
+ // if searchId is not null, there's an id in the route.
+ // display the details for the search, if there is one
+ if (searchId) {
+ if (searches[searchId]) {
+ return (
+ <SearchDetail
+ search={searches[searchId]}
+ creating={creating}
+ stopping={stopping}
+ removing={removing}
+ onCreate={create}
+ onStop={stop}
+ onRemove={remove}
+ />
+ );
+ }
+
+ // if the searchId doesn't match a search we know about, chop
+ // the id off of the url and force navigation back to the list
+ history.replace(match.url.replace(`/${searchId}`, ''));
+ }
+
+ return (
+ <>
+ <Segment className='search-segment' raised>
+ <Input
+ input={<input placeholder="Search phrase" type="search" data-lpignore="true"></input>}
+ size='big'
+ ref={inputRef}
+ loading={creating}
+ disabled={creating}
+ className='search-input'
+ placeholder="Search phrase"
+ action={<>
+ <Button icon='plus' onClick={create}/>
+ <Button icon='search' onClick={() => create({ navigate: true })}/>
+ </>}
+ onKeyUp={(e) => e.key === 'Enter' ? create() : ''}
+ />
+ </Segment>
+ <SearchList
+ connecting={connecting}
+ error={error}
+ searches={searches}
+ onRemove={remove}
+ onStop={stop}
+ />
+ </>
+ )
+};
+
+export default Searches; \ No newline at end of file
diff --git a/src/web/src/components/Shared/LoaderSegment.js b/src/web/src/components/Shared/LoaderSegment.js
new file mode 100644
index 00000000..cc3d598c
--- /dev/null
+++ b/src/web/src/components/Shared/LoaderSegment.js
@@ -0,0 +1,11 @@
+import React from '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>
+ </Segment>
+);
+
+export default LoaderSegment; \ No newline at end of file
diff --git a/src/web/src/components/Shared/Switch.js b/src/web/src/components/Shared/Switch.js
new file mode 100644
index 00000000..9b8e4beb
--- /dev/null
+++ b/src/web/src/components/Shared/Switch.js
@@ -0,0 +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];
+ }
+
+ return children;
+}
+
+export default Switch; \ No newline at end of file
diff --git a/src/web/src/config.js b/src/web/src/config.js
index 8f0ac901..b9dedf38 100644
--- a/src/web/src/config.js
+++ b/src/web/src/config.js
@@ -17,5 +17,5 @@ export {
tokenPassthroughValue,
activeChatKey,
activeRoomKey,
- activeUserInfoKey
+ activeUserInfoKey,
};
diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js
index 246e9d03..8b41226e 100644
--- a/src/web/src/lib/hubFactory.js
+++ b/src/web/src/lib/hubFactory.js
@@ -13,11 +13,13 @@ export const createHubConnection = ({ url }) =>
withCredentials: true,
accessTokenFactory: session.isPassthroughEnabled() ? undefined : session.getToken
})
- .withAutomaticReconnect([0, 500, 1000, 3000, 5000, 5000, 5000, 5000, 5000])
+ .withAutomaticReconnect([0, 100, 250, 500, 1000, 2000, 3000, 5000, 5000, 5000, 5000, 5000])
.withHubProtocol(new JsonHubProtocol())
.configureLogging(LogLevel.Warning)
.build();
export const createApplicationHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/application` });
-export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` }); \ No newline at end of file
+export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` });
+
+export const createSearchHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/search`})
diff --git a/src/web/src/lib/search.js b/src/web/src/lib/searches.js
index 306c7041..9561ab40 100644
--- a/src/web/src/lib/search.js
+++ b/src/web/src/lib/searches.js
@@ -1,6 +1,18 @@
import api from './api';
-export const search = ({ id, searchText }) => {
+export const getAll = async () => {
+ return (await api.get('/searches')).data;
+}
+
+export const stop = ({ id }) => {
+ return api.put(`/searches/${encodeURIComponent(id)}`)
+}
+
+export const remove = ({ id }) => {
+ return api.delete(`/searches/${encodeURIComponent(id)}`)
+}
+
+export const create = ({ id, searchText }) => {
return api.post(`/searches`, { id, searchText });
};
diff --git a/src/web/src/lib/search.test.js b/src/web/src/lib/searches.test.js
index 68afe91c..737843ed 100644
--- a/src/web/src/lib/search.test.js
+++ b/src/web/src/lib/searches.test.js
@@ -1,4 +1,4 @@
-import * as search from './search';
+import * as search from './searches';
describe('filterResponse', () => {
it('removes VBR files if "iscbr" is specified', () => {
diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js
index 9721fbeb..1704a990 100644
--- a/src/web/src/lib/util.js
+++ b/src/web/src/lib/util.js
@@ -48,6 +48,10 @@ export const formatAttributes = ({ bitRate, isVariableBitRate, bitDepth, sampleR
return bitRate ? `${bitRate} Kbps` : ''
}
+export const sleep = (milliseconds) => {
+ return new Promise(resolve => setTimeout(resolve, milliseconds))
+}
+
/* https://www.npmjs.com/package/js-file-download
*
* Copyright 2017 Kenneth Jiang