From c4ed5c09f5d07e9b5b837590686c4b9e96f9a869 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Apr 2022 18:01:42 -0500 Subject: add DeleteAsync() --- src/slskd/Search/ISearchService.cs | 7 +++++ src/slskd/Search/SearchService.cs | 54 +++++++++++++++++++++++++------------- 2 files changed, 43 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/ISearchService.cs b/src/slskd/Search/ISearchService.cs index d696617d..d2cac32e 100644 --- a/src/slskd/Search/ISearchService.cs +++ b/src/slskd/Search/ISearchService.cs @@ -40,6 +40,13 @@ namespace slskd.Search /// The completed search. Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); + /// + /// Deletes the specified ssearch. + /// + /// The search to delete. + /// The operation context. + Task DeleteAsync(Search search); + /// /// Finds a single search matching the specified . /// diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 1eb92bc2..44919ab9 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -67,14 +67,15 @@ namespace slskd.Search Log = log; } + private IApplication Application { get; } + private ConcurrentDictionary CancellationTokens { get; } - = new ConcurrentDictionary(); + = new ConcurrentDictionary(); - private IOptionsMonitor OptionsMonitor { get; } - private IApplication Application { get; } private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } private ILogger Log { get; set; } + private IOptionsMonitor OptionsMonitor { get; } private IHubContext SearchHub { get; set; } /// @@ -144,6 +145,23 @@ namespace slskd.Search } } + /// + /// Deletes the specified ssearch. + /// + /// The search to delete. + /// The operation context. + public async Task DeleteAsync(Search search) + { + if (search == default) + { + throw new ArgumentNullException(nameof(search)); + } + + using var context = ContextFactory.CreateDbContext(); + context.Searches.Remove(search); + await context.SaveChangesAsync(); + } + /// /// Finds a single search matching the specified . /// @@ -198,18 +216,11 @@ namespace slskd.Search return false; } - private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) + private void SaveSearchState(Search search) { - if (CancellationTokens.ContainsKey(search.Id)) - { - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - - SearchHub.BroadcastUpdateAsync(search); - SaveSearchState(search); - } + var context = ContextFactory.CreateDbContext(); + context.Update(search); + context.SaveChanges(); } private void UpdateSearchResponses(Search search, SoulseekSearch soulseekSearch, Soulseek.SearchResponse response) @@ -221,11 +232,18 @@ namespace slskd.Search } } - private void SaveSearchState(Search search) + private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) { - var context = ContextFactory.CreateDbContext(); - context.Update(search); - context.SaveChanges(); + if (CancellationTokens.ContainsKey(search.Id)) + { + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + + SearchHub.BroadcastUpdateAsync(search); + SaveSearchState(search); + } } } } \ No newline at end of file -- cgit v1.2.3 From 976fcca2e6dfa0b5f5c8872ac3c6ec8f24b54a29 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Apr 2022 18:02:07 -0500 Subject: add endpoints to stop/cancel a search and delete a search record --- .../Search/API/Controllers/SearchesController.cs | 55 +++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 5f740044..ae0f6570 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -129,7 +129,60 @@ namespace slskd.Search.API [Authorize] public async Task GetAll() { - return Ok(await Searches.ListAsync()); + var searches = await Searches.ListAsync(); + return Ok(searches); + } + + /// + /// Stops the search corresponding to the specified . + /// + /// The unique id of the search. + /// The search was stopped. + /// The search was not in progress. + /// + [HttpPut("{id}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(304)] + public async Task Cancel([FromRoute] Guid id) + { + var search = await Searches.FindAsync(search => search.Id == id); + + if (search == default) + { + return NotFound(); + } + + if (Searches.TryCancel(id)) + { + return Ok(); + } + + return StatusCode(304); + } + + /// + /// Deletes the search corresponding to the specified . + /// + /// The unique id of the search. + /// The search was deleted. + /// A search with the specified id could not be found. + /// + [HttpDelete("{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public async Task Delete([FromRoute] Guid id) + { + var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); + + if (search == default) + { + return NotFound(); + } + + await Searches.DeleteAsync(search); + return NoContent(); } } } -- cgit v1.2.3 From 0247358ad4067ba68b758d875e4bf1a1b2fb604c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Apr 2022 18:02:17 -0500 Subject: wip searches UI --- src/web/src/components/App.js | 2 + src/web/src/components/Search/Search.css | 6 ++ src/web/src/components/Search/SearchIcon.js | 35 ++++++++ src/web/src/components/Search/Searches.js | 131 ++++++++++++++++++++++++++++ src/web/src/lib/search.js | 4 + 5 files changed, 178 insertions(+) create mode 100644 src/web/src/components/Search/SearchIcon.js create mode 100644 src/web/src/components/Search/Searches.js (limited to 'src') diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 3a22e0c8..8fa6bcaa 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -8,6 +8,7 @@ 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'; @@ -242,6 +243,7 @@ class App extends Component { + this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css index 7c91a08b..3fe76b80 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: 851px) { .search-options-hide-no-slots, .search-options-hide-locked { margin-left: 1rem; diff --git a/src/web/src/components/Search/SearchIcon.js b/src/web/src/components/Search/SearchIcon.js new file mode 100644 index 00000000..b31bd860 --- /dev/null +++ b/src/web/src/components/Search/SearchIcon.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) => { + switch (state) { + case 'None': + case 'Requested': + return + case 'InProgress': + return + case 'Completed, TimedOut': + case 'Completed, ResponseLimitReached': + case 'Completed, FileLimitReached': + return + case 'Completed, Cancelled': + return + case 'Completed, Errored': + return + default: + return + } +} + +const SearchIcon = ({ state, ...props }) => + + +export default SearchIcon; \ 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..f6dd3ee2 --- /dev/null +++ b/src/web/src/components/Search/Searches.js @@ -0,0 +1,131 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { v4 as uuidv4 } from 'uuid'; + +import * as search from '../../lib/search'; + +import './Search.css'; + +import { + Input, + Segment, + Card, + Table, + Icon +} from 'semantic-ui-react'; +import SearchIcon from './SearchIcon'; + +const Searches = () => { + const [{ loading, loadError }, setLoading] = useState({ loading: true, loadError: false }); + const [{ creating, createError }, setCreating] = useState({ creating: false, createError: false }) + const [searches, setSearches] = useState([]); + const inputRef = useRef(); + + useEffect(() => { + get(); + }, []); + + const create = async () => { + const searchText = inputRef.current.inputRef.current.value; + const id = uuidv4(); + + try { + setCreating({ creating: true, createError: false }) + await search.search({ id, searchText }) + setCreating({ creating: false, createError: false }) + inputRef.current.inputRef.current.value = ''; + window.location.reload(); + } catch (error) { + setCreating({ creating: false, createError: error.message }) + } + } + + const get = async () => { + setLoading({ loading: true, error: false }); + + try { + const searches = await search.getAll(); + + console.log(searches) + + setSearches(searches); + setLoading({ loading: false, error: false }) + } catch (error) { + setLoading({ loading: false, error: error.message }) + } + } + + const cancelAndDeleteAll = () => { + // todo + } + + return ( +
+ + } + size='big' + ref={inputRef} + loading={creating} + disabled={creating} + className='search-input' + placeholder="Search phrase" + action={{ icon: 'search', onClick: create }} + onKeyUp={(e) => e.key === 'Enter' ? create() : ''} + /> + + + + + + Searches + + cancelAndDeleteAll()} + /> + + + + cancelAndDeleteAll()} + /> + + + + + + + + Started + Search Phrase + Responses + Files (Locked) + + + + + {searches.map((search, index) => + + {search.startedAt} + {search.searchText} + {search.responseCount} + {search.fileCount} ({search.lockedFileCount}) + {search.state.includes('Completed') ? + : + } + + )} + +
+
+
+
+ ) +}; + +export default Searches; \ No newline at end of file diff --git a/src/web/src/lib/search.js b/src/web/src/lib/search.js index 306c7041..362487bf 100644 --- a/src/web/src/lib/search.js +++ b/src/web/src/lib/search.js @@ -1,5 +1,9 @@ import api from './api'; +export const getAll = async () => { + return (await api.get('/searches')).data; +} + export const search = ({ id, searchText }) => { return api.post(`/searches`, { id, searchText }); }; -- cgit v1.2.3 From 4be8762f8700f22ece610a208cfc04df742316fd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Apr 2022 22:51:22 -0500 Subject: use DateTime.Now --- src/slskd/Search/Domain/Search.cs | 2 +- src/slskd/Search/SearchService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/Domain/Search.cs b/src/slskd/Search/Domain/Search.cs index b93c62cb..52f97075 100644 --- a/src/slskd/Search/Domain/Search.cs +++ b/src/slskd/Search/Domain/Search.cs @@ -53,7 +53,7 @@ namespace slskd.Search } public string SearchText { get; init; } - public DateTime StartedAt { get; init; } = DateTime.UtcNow; + public DateTime StartedAt { get; init; } = DateTime.Now; public SearchStates State { get; set; } public int Token { get; init; } } diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 44919ab9..ef094008 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -97,7 +97,7 @@ namespace slskd.Search Token = token, Id = id, State = SearchStates.Requested, - StartedAt = DateTime.UtcNow, + StartedAt = DateTime.Now, }; options ??= new SearchOptions(); -- cgit v1.2.3 From 02a0bed8c36128a80b1075ee6c216492aec35836 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Apr 2022 22:51:50 -0500 Subject: rename search lib --- src/web/src/lib/search.js | 118 ----------------------------------------- src/web/src/lib/searches.js | 126 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 118 deletions(-) delete mode 100644 src/web/src/lib/search.js create mode 100644 src/web/src/lib/searches.js (limited to 'src') diff --git a/src/web/src/lib/search.js b/src/web/src/lib/search.js deleted file mode 100644 index 362487bf..00000000 --- a/src/web/src/lib/search.js +++ /dev/null @@ -1,118 +0,0 @@ -import api from './api'; - -export const getAll = async () => { - return (await api.get('/searches')).data; -} - -export const search = ({ id, searchText }) => { - return api.post(`/searches`, { id, searchText }); -}; - -export const getStatus = async ({ id, includeResponses = false }) => { - 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; - - if (!Array.isArray(response)) { - console.warn('got non-array response from searches API', response) - return undefined; - } - - return response; -}; - -export const parseFiltersFromString = (string) => { - const filters = { - minBitRate: 0, - minFileSize: 0, - minLength: 0, - minFilesInFolder: 0, - include: [], - exclude: [], - isVBR: false, - isCBR: false, - isLossless: false, - isLossy: false, - }; - - const getNthMatch = (string, regex, n) => { - const match = string.match(regex); - - if (match) { - return parseInt(match[n], 10); - } - } - - filters.minBitRate = getNthMatch(string, /(minbr|minbitrate):([0-9]+)/i, 2) || filters.minBitRate; - 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)); - - return filters; -}; - -export const filterResponse = ({ - filters = { - minBitRate: 0, - minFileSize: 0, - minLength: 0, - include: [], - exclude: [], - isVBR: false, - isCBR: false, - isLossless: false, - isLossy: false, - }, - response = { - files: [], - lockedFiles: [] - } -}) => { - let { files = [], lockedFiles = [] } = response; - - 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, 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 (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 filteredFiles = filterFiles(files); - const filteredLockedFiles = filterFiles(lockedFiles); - - return { - ...response, - fileCount: filteredFiles.length, - lockedFileCount: filteredLockedFiles.length, - files: filteredFiles, - lockedFiles: filteredLockedFiles - }; -}; \ No newline at end of file diff --git a/src/web/src/lib/searches.js b/src/web/src/lib/searches.js new file mode 100644 index 00000000..9561ab40 --- /dev/null +++ b/src/web/src/lib/searches.js @@ -0,0 +1,126 @@ +import api from './api'; + +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 }); +}; + +export const getStatus = async ({ id, includeResponses = false }) => { + 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; + + if (!Array.isArray(response)) { + console.warn('got non-array response from searches API', response) + return undefined; + } + + return response; +}; + +export const parseFiltersFromString = (string) => { + const filters = { + minBitRate: 0, + minFileSize: 0, + minLength: 0, + minFilesInFolder: 0, + include: [], + exclude: [], + isVBR: false, + isCBR: false, + isLossless: false, + isLossy: false, + }; + + const getNthMatch = (string, regex, n) => { + const match = string.match(regex); + + if (match) { + return parseInt(match[n], 10); + } + } + + filters.minBitRate = getNthMatch(string, /(minbr|minbitrate):([0-9]+)/i, 2) || filters.minBitRate; + 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)); + + return filters; +}; + +export const filterResponse = ({ + filters = { + minBitRate: 0, + minFileSize: 0, + minLength: 0, + include: [], + exclude: [], + isVBR: false, + isCBR: false, + isLossless: false, + isLossy: false, + }, + response = { + files: [], + lockedFiles: [] + } +}) => { + let { files = [], lockedFiles = [] } = response; + + 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, 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 (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 filteredFiles = filterFiles(files); + const filteredLockedFiles = filterFiles(lockedFiles); + + return { + ...response, + fileCount: filteredFiles.length, + lockedFileCount: filteredLockedFiles.length, + files: filteredFiles, + lockedFiles: filteredLockedFiles + }; +}; \ No newline at end of file -- cgit v1.2.3 From e1a6603c50b8e53aa1766b179be094822a36aea0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Apr 2022 22:52:12 -0500 Subject: rename search lib --- src/web/src/components/Search/Search.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index 713bfe26..6e90a443 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from 'uuid'; import React, { Component } from 'react'; -import * as search from '../../lib/search'; +import * as searches from '../../lib/searches'; import './Search.css'; @@ -54,7 +54,7 @@ class Search extends Component { this.setState({ searchPhrase, searchId, searchState: 'pending' }, async () => { this.saveState(); - search.search({ id: searchId, searchText: searchPhrase }); + searches.create({ id: searchId, searchText: searchPhrase }); }); } @@ -120,7 +120,7 @@ class Search extends Component { if (!!searchId) { this.setState({ fetching: true }, async () => { try { - const responses = await search.getResponses({ id: searchId }); + const responses = await searches.getResponses({ id: searchId }); this.setState({ results: responses, @@ -139,7 +139,7 @@ class Search extends Component { if (searchState === 'pending') { this.setState({ fetching: true }, async () => { - const response = await search.getStatus({ id: searchId }); + const response = await searches.getStatus({ id: searchId }); if (response.isComplete) { this.setState({ @@ -163,7 +163,7 @@ class Search extends Component { const { results = [], hideNoFreeSlots, resultSort, resultFilters = '', hideLocked, hiddenResults = [] } = this.state; const { field, order } = sortOptions[resultSort]; - const filters = search.parseFiltersFromString(resultFilters); + const filters = searches.parseFiltersFromString(resultFilters); return results .filter(r => !hiddenResults.includes(r.username)) @@ -173,7 +173,7 @@ class Search extends Component { } return r; }) - .map(response => search.filterResponse({ response, filters })) + .map(response => searches.filterResponse({ response, filters })) .filter(r => r.fileCount + r.lockedFileCount > 0) .filter(r => !(hideNoFreeSlots && r.freeUploadSlots === 0)) .sort((a, b) => { -- cgit v1.2.3 From ef4060eb9dba304f173c64753075a412d4d889ac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Apr 2022 22:52:25 -0500 Subject: add searches hub --- src/web/src/lib/hubFactory.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js index a64c5c40..e0205ec9 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: `${rootUrl}hub/application` }); -export const createLogsHubConnection = () => createHubConnection({ url: `${rootUrl}hub/logs` }); \ No newline at end of file +export const createLogsHubConnection = () => createHubConnection({ url: `${rootUrl}hub/logs` }); + +export const createSearchLogHubConnection = () => createHubConnection({ url: `${rootUrl}hub/search` }); \ No newline at end of file -- cgit v1.2.3 From 823ee6d70dde6a579d12c2d173102ad1870a95df Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Apr 2022 22:52:29 -0500 Subject: more wip --- src/web/src/components/Search/Searches.js | 80 ++++++++++++++++++++++++------- 1 file changed, 62 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index f6dd3ee2..789be02f 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -1,7 +1,10 @@ +import { orderBy } from 'lodash'; import React, { useState, useEffect, useRef } from 'react'; import { v4 as uuidv4 } from 'uuid'; -import * as search from '../../lib/search'; + +import * as lib from '../../lib/searches'; +import { createSearchLogHubConnection } from '../../lib/hubFactory'; import './Search.css'; @@ -16,12 +19,37 @@ import SearchIcon from './SearchIcon'; const Searches = () => { const [{ loading, loadError }, setLoading] = useState({ loading: true, loadError: false }); - const [{ creating, createError }, setCreating] = useState({ creating: false, createError: false }) + const [{ creating, createError }, setCreating] = useState({ creating: false, createError: false }); + const [connected, setConnected] = useState(false); const [searches, setSearches] = useState([]); const inputRef = useRef(); useEffect(() => { get(); + + const searchHub = createSearchLogHubConnection(); + + searchHub.on('update', search => { + setConnected(true); + setSearches(old => { + const idx = old.findIndex(s => s.id === search.id); + + if (idx < 0) { + return [search, ...old] + } else { + old[idx] = search + return [...old]; + } + }) + }); + + searchHub.on('response', () => { }); + + searchHub.onreconnecting(() => setConnected(false)); + searchHub.onclose(() => setConnected(false)); + searchHub.onreconnected(() => setConnected(true)); + + searchHub.start(); }, []); const create = async () => { @@ -30,10 +58,9 @@ const Searches = () => { try { setCreating({ creating: true, createError: false }) - await search.search({ id, searchText }) + lib.create({ id, searchText }) setCreating({ creating: false, createError: false }) inputRef.current.inputRef.current.value = ''; - window.location.reload(); } catch (error) { setCreating({ creating: false, createError: error.message }) } @@ -43,17 +70,29 @@ const Searches = () => { setLoading({ loading: true, error: false }); try { - const searches = await search.getAll(); - - console.log(searches) - - setSearches(searches); + const all = await lib.getAll(); + setSearches(all); setLoading({ loading: false, error: false }) } catch (error) { setLoading({ loading: false, error: error.message }) } } + const remove = async (search) => { + console.log('remove', searches) + try { + await lib.remove({ id: search.id }) + setSearches(old => old.filter(s => s.id !== search.id)) + } catch (err) { + console.error(err) + // noop + } + } + + const stop = async (search) => { + await lib.stop({ id: search.id }) + } + const cancelAndDeleteAll = () => { // todo } @@ -109,15 +148,20 @@ const Searches = () => { - {searches.map((search, index) => - - {search.startedAt} - {search.searchText} - {search.responseCount} - {search.fileCount} ({search.lockedFileCount}) - {search.state.includes('Completed') ? - : - } + {searches + .sort((a, b) => { + //console.log(new Date(b.startedAt), new Date(a.startedAt)) + return new Date(b.startedAt) - new Date(a.startedAt) + }) + .map((s, index) => + + {s.startedAt} + {s.searchText} + {s.responseCount} + {s.fileCount} ({s.lockedFileCount}) + {s.state.includes('Completed') ? + remove(s)}/> : + stop(s)}/>} )} -- cgit v1.2.3 From 483df13b252ba8e64e63640414b132ebbc1177a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 Apr 2022 09:33:36 -0500 Subject: layout wip --- src/web/src/components/Search/List/SearchList.js | 151 ++++++++++++++++++ .../src/components/Search/List/SearchListAlt.js | 168 +++++++++++++++++++++ .../src/components/Search/List/SearchListRow.js | 54 +++++++ src/web/src/components/Search/Searches.js | 62 +------- 4 files changed, 378 insertions(+), 57 deletions(-) create mode 100644 src/web/src/components/Search/List/SearchList.js create mode 100644 src/web/src/components/Search/List/SearchListAlt.js create mode 100644 src/web/src/components/Search/List/SearchListRow.js (limited to 'src') 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..9e206e42 --- /dev/null +++ b/src/web/src/components/Search/List/SearchList.js @@ -0,0 +1,151 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { v4 as uuidv4 } from 'uuid'; + + +import * as lib from '../../../lib/searches'; +import { createSearchLogHubConnection } from '../../../lib/hubFactory'; + +import SearchListRow from './SearchListRow'; + +import { + Card, + Table, + Icon +} from 'semantic-ui-react'; +import SearchIcon from '../SearchIcon'; + +const SearchList = () => { + const [{ loading, loadError }, setLoading] = useState({ loading: true, loadError: false }); + const [{ creating, createError }, setCreating] = useState({ creating: false, createError: false }); + const [connected, setConnected] = useState(false); + const [searches, setSearches] = useState([]); + const inputRef = useRef(); + + useEffect(() => { + get(); + + const searchHub = createSearchLogHubConnection(); + + searchHub.on('update', search => { + setConnected(true); + setSearches(old => { + const idx = old.findIndex(s => s.id === search.id); + + if (idx < 0) { + return [search, ...old] + } else { + old[idx] = search + return [...old]; + } + }) + }); + + searchHub.on('response', () => { }); + + searchHub.onreconnecting(() => setConnected(false)); + searchHub.onclose(() => setConnected(false)); + searchHub.onreconnected(() => setConnected(true)); + + searchHub.start(); + }, []); + + const create = async () => { + const searchText = inputRef.current.inputRef.current.value; + const id = uuidv4(); + + try { + setCreating({ creating: true, createError: false }) + lib.create({ id, searchText }) + setCreating({ creating: false, createError: false }) + inputRef.current.inputRef.current.value = ''; + } catch (error) { + setCreating({ creating: false, createError: error.message }) + } + } + + const get = async () => { + setLoading({ loading: true, error: false }); + + try { + const all = await lib.getAll(); + setSearches(all); + setLoading({ loading: false, error: false }) + } catch (error) { + setLoading({ loading: false, error: error.message }) + } + } + + const remove = async (search) => { + console.log('remove', searches) + try { + await lib.remove({ id: search.id }) + setSearches(old => old.filter(s => s.id !== search.id)) + } catch (err) { + console.error(err) + // noop + } + } + + const stop = async (search) => { + await lib.stop({ id: search.id }) + } + + const cancelAndDeleteAll = () => { + // todo + } + + return ( + <> + + + + + Searches + + cancelAndDeleteAll()} + /> + + + + cancelAndDeleteAll()} + /> + + + + + + + + Started + Search Phrase + Responses + Files (Locked) + + + + + {searches + .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) + .map((search, index) => )} + +
+
+
+ + ) +}; + +export default SearchList; \ No newline at end of file diff --git a/src/web/src/components/Search/List/SearchListAlt.js b/src/web/src/components/Search/List/SearchListAlt.js new file mode 100644 index 00000000..0ef0fca0 --- /dev/null +++ b/src/web/src/components/Search/List/SearchListAlt.js @@ -0,0 +1,168 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { v4 as uuidv4 } from 'uuid'; + + +import * as lib from '../../../lib/searches'; +import { createSearchLogHubConnection } from '../../../lib/hubFactory'; + +import SearchListRow from './SearchListRow'; + +import { + Card, + Item, + Icon, + Button, + Label, + Table, + Statistic +} from 'semantic-ui-react'; +import SearchIcon from '../SearchIcon'; + +const SearchListAlt = () => { + const [{ loading, loadError }, setLoading] = useState({ loading: true, loadError: false }); + const [{ creating, createError }, setCreating] = useState({ creating: false, createError: false }); + const [connected, setConnected] = useState(false); + const [searches, setSearches] = useState([]); + const inputRef = useRef(); + + useEffect(() => { + get(); + + const searchHub = createSearchLogHubConnection(); + + searchHub.on('update', search => { + setConnected(true); + setSearches(old => { + const idx = old.findIndex(s => s.id === search.id); + + if (idx < 0) { + return [search, ...old] + } else { + old[idx] = search + return [...old]; + } + }) + }); + + searchHub.on('response', () => { }); + + searchHub.onreconnecting(() => setConnected(false)); + searchHub.onclose(() => setConnected(false)); + searchHub.onreconnected(() => setConnected(true)); + + searchHub.start(); + }, []); + + const create = async () => { + const searchText = inputRef.current.inputRef.current.value; + const id = uuidv4(); + + try { + setCreating({ creating: true, createError: false }) + lib.create({ id, searchText }) + setCreating({ creating: false, createError: false }) + inputRef.current.inputRef.current.value = ''; + } catch (error) { + setCreating({ creating: false, createError: error.message }) + } + } + + const get = async () => { + setLoading({ loading: true, error: false }); + + try { + const all = await lib.getAll(); + setSearches(all); + setLoading({ loading: false, error: false }) + } catch (error) { + setLoading({ loading: false, error: error.message }) + } + } + + const remove = async (search) => { + console.log('remove', searches) + try { + await lib.remove({ id: search.id }) + setSearches(old => old.filter(s => s.id !== search.id)) + } catch (err) { + console.error(err) + // noop + } + } + + const stop = async (search) => { + await lib.stop({ id: search.id }) + } + + const cancelAndDeleteAll = () => { + // todo + } + + return ( + + + + + Searches + + cancelAndDeleteAll()} + /> + + + + cancelAndDeleteAll()} + /> + + + + + {searches + .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) + .map((search, index) => + + {/* */} + + + {search.searchText} + + Basic Search | {search.state} + + + + + + {search.responseCount} + Responses + + + {search.fileCount} + Files + + + {search.lockedFileCount} + + Locked + + + + + + + + ) + } + + + + ) +}; + +export default SearchListAlt; \ 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..1c6b4ae6 --- /dev/null +++ b/src/web/src/components/Search/List/SearchListRow.js @@ -0,0 +1,54 @@ +import React, { useState } from 'react'; + +import SearchIcon from '../SearchIcon'; + +import { + Table, + Icon +} from 'semantic-ui-react'; + +const SearchListRow = ({ search, index, onRemove, onStop }) => { + const [working, setWorking] = useState(false); + + const invoke = async (func) => { + setWorking(true); + await func(); + setWorking(false); + } + + const ActionIcon = () => { + if (working) { + return () + } + + if (search.state.includes('Completed')) { + return ( invoke(() => onRemove(search))} + />) + } + + return ( invoke(() => onStop(search))} + />) + } + + return ( + + {working} + {search.startedAt} + {search.searchText} + {search.responseCount} + {search.fileCount} ({search.lockedFileCount}) + + + ) +} + +export default SearchListRow; \ No newline at end of file diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index 789be02f..6f7efe4e 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -1,4 +1,3 @@ -import { orderBy } from 'lodash'; import React, { useState, useEffect, useRef } from 'react'; import { v4 as uuidv4 } from 'uuid'; @@ -6,6 +5,9 @@ import { v4 as uuidv4 } from 'uuid'; import * as lib from '../../lib/searches'; import { createSearchLogHubConnection } from '../../lib/hubFactory'; +import SearchList from './List/SearchList'; +import SearchListAlt from './List/SearchListAlt'; + import './Search.css'; import { @@ -112,62 +114,8 @@ const Searches = () => { onKeyUp={(e) => e.key === 'Enter' ? create() : ''} /> - - - - - Searches - - cancelAndDeleteAll()} - /> - - - - cancelAndDeleteAll()} - /> - - - - - - - - Started - Search Phrase - Responses - Files (Locked) - - - - - {searches - .sort((a, b) => { - //console.log(new Date(b.startedAt), new Date(a.startedAt)) - return new Date(b.startedAt) - new Date(a.startedAt) - }) - .map((s, index) => - - {s.startedAt} - {s.searchText} - {s.responseCount} - {s.fileCount} ({s.lockedFileCount}) - {s.state.includes('Completed') ? - remove(s)}/> : - stop(s)}/>} - - )} - -
-
-
+ + ) }; -- cgit v1.2.3 From 223543b5889a1e3ee139b597eaa2cdfc5988fe02 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 Apr 2022 22:25:47 -0500 Subject: broadcast creates and deletes --- src/slskd/Search/API/Hubs/SearchHub.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index 86434669..4417f8c9 100644 --- a/src/slskd/Search/API/Hubs/SearchHub.cs +++ b/src/slskd/Search/API/Hubs/SearchHub.cs @@ -26,8 +26,10 @@ namespace slskd.Search.API public static class SearchHubMethods { + public static readonly string Create = "CREATE"; public static readonly string Response = "RESPONSE"; public static readonly string Update = "UPDATE"; + public static readonly string Delete = "DELETE"; } /// @@ -57,6 +59,16 @@ namespace slskd.Search.API { return hub.Clients.All.SendAsync(SearchHubMethods.Response, new { searchId, response }); } + + public static Task BroadcastCreateAsync(this IHubContext hub, Search search) + { + return hub.Clients.All.SendAsync(SearchHubMethods.Create, search); + } + + public static Task BroadcastDeleteAsync(this IHubContext hub, Search search) + { + return hub.Clients.All.SendAsync(SearchHubMethods.Delete, search); + } } /// -- cgit v1.2.3 From 45b1866243e4c9be432393a763565253f0595fba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 Apr 2022 22:26:10 -0500 Subject: don't broadcast results, return after create --- src/slskd/Search/SearchService.cs | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index ef094008..8042388f 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -105,22 +105,18 @@ namespace slskd.Search stateChanged: (args) => UpdateSearchState(search, args.Search), responseReceived: (args) => UpdateSearchResponses(search, args.Search, args.Response)); - try - { - using var context = ContextFactory.CreateDbContext(); + using var context = ContextFactory.CreateDbContext(); - context.Add(search); - await context.SaveChangesAsync(); + context.Add(search); + await context.SaveChangesAsync(); + await SearchHub.BroadcastCreateAsync(search); - CancellationTokens.TryAdd(id, cancellationTokenSource); - var responses = new List(); + CancellationTokens.TryAdd(id, cancellationTokenSource); - var soulseekSearch = await Client.SearchAsync( + _ = Task.Run(async () => + { + var (soulseekSearch, responses) = await Client.SearchAsync( query, - responseReceived: (response) => - { - responses.Add(Response.FromSoulseekSearchResponse(response)); - }, scope, token, options, @@ -133,16 +129,11 @@ namespace slskd.Search search.ResponseCount = soulseekSearch.ResponseCount; search.State = soulseekSearch.State; search.EndedAt = DateTime.UtcNow; - search.Responses = responses; + search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); SaveSearchState(search); + }, cancellationToken: cancellationTokenSource.Token); - return search; - } - finally - { - CancellationTokens.TryRemove(id, out _); - Application.CollectGarbage(); - } + return search; } /// @@ -160,6 +151,7 @@ namespace slskd.Search using var context = ContextFactory.CreateDbContext(); context.Searches.Remove(search); await context.SaveChangesAsync(); + await SearchHub.BroadcastDeleteAsync(search); } /// @@ -227,7 +219,7 @@ namespace slskd.Search { if (CancellationTokens.ContainsKey(search.Id)) { - SearchHub.BroadcastResponseAsync(search.Id, response); + //SearchHub.BroadcastResponseAsync(search.Id, response); UpdateSearchState(search, soulseekSearch); } } @@ -242,7 +234,7 @@ namespace slskd.Search search.State = soulseekSearch.State; SearchHub.BroadcastUpdateAsync(search); - SaveSearchState(search); + //SaveSearchState(search); } } } -- cgit v1.2.3 From 80833506bbfc9f85c6d41a06afe53337b3a6011e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 Apr 2022 22:26:16 -0500 Subject: more wip --- src/web/src/components/App.css | 2 +- src/web/src/components/Search/List/SearchList.js | 44 ++++++++++++---------- .../src/components/Search/List/SearchListRow.js | 16 +++++--- src/web/src/components/Search/Search.css | 28 ++++++++++++++ src/web/src/components/Search/Search.js | 3 +- src/web/src/components/Search/SearchIcon.js | 16 ++++---- src/web/src/components/Search/Searches.js | 2 +- 7 files changed, 75 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index 6244cdf8..b92ba4e2 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -56,7 +56,7 @@ body { margin-top: 20px !important; } -.filelist-selector, .transferlist-selector { +.filelist-selector, .transferlist-selector, .list-selector { width: 40px; } diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js index 9e206e42..6450672a 100644 --- a/src/web/src/components/Search/List/SearchList.js +++ b/src/web/src/components/Search/List/SearchList.js @@ -18,7 +18,7 @@ const SearchList = () => { const [{ loading, loadError }, setLoading] = useState({ loading: true, loadError: false }); const [{ creating, createError }, setCreating] = useState({ creating: false, createError: false }); const [connected, setConnected] = useState(false); - const [searches, setSearches] = useState([]); + const [searches, setSearches] = useState({}); const inputRef = useRef(); useEffect(() => { @@ -27,17 +27,16 @@ const SearchList = () => { const searchHub = createSearchLogHubConnection(); searchHub.on('update', search => { + setConnected(true); + setSearches(old => ({ ...old, [search.id]: search })) + }); + + searchHub.on('delete', search => { setConnected(true); setSearches(old => { - const idx = old.findIndex(s => s.id === search.id); - - if (idx < 0) { - return [search, ...old] - } else { - old[idx] = search - return [...old]; - } - }) + delete old[search.id]; + return { ...old } + }); }); searchHub.on('response', () => { }); @@ -68,7 +67,10 @@ const SearchList = () => { try { const all = await lib.getAll(); - setSearches(all); + setSearches(all.reduce((acc, search) => { + acc[search.id] = search; + return acc; + }, {})); setLoading({ loading: false, error: false }) } catch (error) { setLoading({ loading: false, error: error.message }) @@ -79,7 +81,10 @@ const SearchList = () => { console.log('remove', searches) try { await lib.remove({ id: search.id }) - setSearches(old => old.filter(s => s.id !== search.id)) + setSearches(old => { + delete old[search.id]; + return { ...old } + }); } catch (err) { console.error(err) // noop @@ -123,16 +128,17 @@ const SearchList = () => { - - Started - Search Phrase - Responses - Files (Locked) - + + Search Phrase + Files + Locked + Responses + Started + - {searches + {Object.values(searches) .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) .map((search, index) => { setWorking(false); } - const ActionIcon = () => { + const ActionIcon = ({ ...props }) => { if (working) { - return () + return () } if (search.state.includes('Completed')) { @@ -26,6 +26,7 @@ const SearchListRow = ({ search, index, onRemove, onStop }) => { name="trash alternate" color='red' onClick={() => invoke(() => onRemove(search))} + {...props} />) } @@ -33,20 +34,23 @@ const SearchListRow = ({ search, index, onRemove, onStop }) => { name="stop circle" color="red" onClick={() => invoke(() => onStop(search))} + {...props} />) } + // return ( - {working} - {search.startedAt} + {search.searchText} + {search.fileCount} + {search.lockedFileCount} {search.responseCount} - {search.fileCount} ({search.lockedFileCount}) - + {new Date(search.startedAt).toLocaleTimeString()} + ) } diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css index 3fe76b80..76079ee9 100644 --- a/src/web/src/components/Search/Search.css +++ b/src/web/src/components/Search/Search.css @@ -69,4 +69,32 @@ .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; } \ No newline at end of file diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index 6e90a443..5704c3c0 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -5,6 +5,7 @@ import * as searches from '../../lib/searches'; import './Search.css'; import Response from './Response'; +import SearchList from './List/SearchList'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; import { @@ -268,7 +269,7 @@ class Search extends Component { onChange={this.onResultFilterChange} action={!!resultFilters && { icon: 'x', color: 'red', onClick: this.clearResultFilter }} /> - : + : } {sortedAndFilteredResults.slice(0, displayCount).map((r, i) => { +const getIcon = ({ state, ...props }) => { switch (state) { case 'None': case 'Requested': - return + return case 'InProgress': - return + return case 'Completed, TimedOut': case 'Completed, ResponseLimitReached': case 'Completed, FileLimitReached': - return + return case 'Completed, Cancelled': - return + return case 'Completed, Errored': - return + return default: - return + return } } const SearchIcon = ({ state, ...props }) => - + export default SearchIcon; \ No newline at end of file diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index 6f7efe4e..e4be00b6 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -32,6 +32,7 @@ const Searches = () => { const searchHub = createSearchLogHubConnection(); searchHub.on('update', search => { + console.log(search) setConnected(true); setSearches(old => { const idx = old.findIndex(s => s.id === search.id); @@ -115,7 +116,6 @@ const Searches = () => { /> - ) }; -- cgit v1.2.3 From 463c96b6f22d78543f25376edd2d7716af1b44a4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 Apr 2022 22:33:22 -0500 Subject: load searches from hub --- src/slskd/Search/API/Hubs/SearchHub.cs | 10 ++++++++++ src/web/src/components/Search/List/SearchList.js | 10 ++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index 4417f8c9..881cd7c2 100644 --- a/src/slskd/Search/API/Hubs/SearchHub.cs +++ b/src/slskd/Search/API/Hubs/SearchHub.cs @@ -26,6 +26,7 @@ namespace slskd.Search.API public static class SearchHubMethods { + public static readonly string Load = "LOAD"; public static readonly string Create = "CREATE"; public static readonly string Response = "RESPONSE"; public static readonly string Update = "UPDATE"; @@ -78,14 +79,23 @@ namespace slskd.Search.API public class SearchHub : Hub { public SearchHub( + ISearchService searchService, IStateMonitor stateMonitor, IOptionsMonitor optionsMonitor) { + Searches = searchService; StateMonitor = stateMonitor; OptionsMonitor = optionsMonitor; } + private ISearchService Searches { get; } private IStateMonitor StateMonitor { get; } private IOptionsMonitor OptionsMonitor { get; } + + public override async Task OnConnectedAsync() + { + var searches = await Searches.ListAsync(); + await Clients.Caller.SendAsync(SearchHubMethods.Load, searches); + } } } \ 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 index 6450672a..a774fb05 100644 --- a/src/web/src/components/Search/List/SearchList.js +++ b/src/web/src/components/Search/List/SearchList.js @@ -22,10 +22,16 @@ const SearchList = () => { const inputRef = useRef(); useEffect(() => { - get(); - const searchHub = createSearchLogHubConnection(); + searchHub.on('load', searches => { + setConnected(true); + setSearches(searches.reduce((acc, search) => { + acc[search.id] = search; + return acc; + }, {})); + }) + searchHub.on('update', search => { setConnected(true); setSearches(old => ({ ...old, [search.id]: search })) -- cgit v1.2.3 From 6c711fe518dba77bd7fdc3314cc6a23730db7e88 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 Apr 2022 22:37:46 -0500 Subject: prepare throttle --- src/slskd/Search/API/Hubs/SearchHub.cs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index 881cd7c2..dc27ca9d 100644 --- a/src/slskd/Search/API/Hubs/SearchHub.cs +++ b/src/slskd/Search/API/Hubs/SearchHub.cs @@ -46,6 +46,7 @@ namespace slskd.Search.API /// The operation context. public static Task BroadcastUpdateAsync(this IHubContext hub, Search search) { + // todo: throttle updates to at most 1 per 100ms or so return hub.Clients.All.SendAsync(SearchHubMethods.Update, search); } @@ -79,23 +80,24 @@ namespace slskd.Search.API public class SearchHub : Hub { public SearchHub( - ISearchService searchService, - IStateMonitor stateMonitor, - IOptionsMonitor optionsMonitor) + ISearchService searchService) { Searches = searchService; - StateMonitor = stateMonitor; - OptionsMonitor = optionsMonitor; } private ISearchService Searches { get; } - private IStateMonitor StateMonitor { get; } - private IOptionsMonitor OptionsMonitor { get; } public override async Task OnConnectedAsync() { var searches = await Searches.ListAsync(); await Clients.Caller.SendAsync(SearchHubMethods.Load, searches); + // todo: create buffer specific to this client + } + + public override Task OnDisconnectedAsync(Exception exception) + { + // todo: destroy buffer specific to this client + return Task.CompletedTask; } } } \ No newline at end of file -- cgit v1.2.3 From ddcefd51dcd7674e86fd54b4c0fbdf168c21170a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 Apr 2022 08:58:24 -0500 Subject: rename load to list --- src/slskd/Search/API/Hubs/SearchHub.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index dc27ca9d..5c9fc114 100644 --- a/src/slskd/Search/API/Hubs/SearchHub.cs +++ b/src/slskd/Search/API/Hubs/SearchHub.cs @@ -26,7 +26,7 @@ namespace slskd.Search.API public static class SearchHubMethods { - public static readonly string Load = "LOAD"; + public static readonly string List = "LIST"; public static readonly string Create = "CREATE"; public static readonly string Response = "RESPONSE"; public static readonly string Update = "UPDATE"; @@ -90,7 +90,7 @@ namespace slskd.Search.API public override async Task OnConnectedAsync() { var searches = await Searches.ListAsync(); - await Clients.Caller.SendAsync(SearchHubMethods.Load, searches); + await Clients.Caller.SendAsync(SearchHubMethods.List, searches); // todo: create buffer specific to this client } -- cgit v1.2.3 From 5e7ebf07d1facb3565e24ce40330514e59ccacc7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 Apr 2022 08:58:33 -0500 Subject: more wip --- src/web/src/components/Search/List/SearchList.js | 135 ++++++++++++--------- .../src/components/Search/List/SearchListRow.js | 2 +- src/web/src/components/Search/SearchIcon.js | 2 +- src/web/src/components/Shared/Switch.js | 11 ++ 4 files changed, 94 insertions(+), 56 deletions(-) create mode 100644 src/web/src/components/Shared/Switch.js (limited to 'src') diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js index a774fb05..08490210 100644 --- a/src/web/src/components/Search/List/SearchList.js +++ b/src/web/src/components/Search/List/SearchList.js @@ -6,52 +6,75 @@ import * as lib from '../../../lib/searches'; import { createSearchLogHubConnection } from '../../../lib/hubFactory'; import SearchListRow from './SearchListRow'; +import ErrorSegment from '../../Shared/ErrorSegment'; +import Switch from '../../Shared/Switch'; import { Card, Table, - Icon + Icon, + Loader } from 'semantic-ui-react'; import SearchIcon from '../SearchIcon'; const SearchList = () => { - const [{ loading, loadError }, setLoading] = useState({ loading: true, loadError: false }); + const [{ connected, connecting, connectError} , setConnected] = useState({ connected: false, connecting: true, connectError: false }); const [{ creating, createError }, setCreating] = useState({ creating: false, createError: false }); - const [connected, setConnected] = useState(false); + const [error, setError] = useState(undefined); const [searches, setSearches] = useState({}); const inputRef = useRef(); + const onConnecting = () => setConnected({ connected: false, connecting: true, connectError: false }) + const onConnected = () => setConnected({ connected: true, connecting: false, connectError: false }); + const onConnectionError = (error) => setConnected({ connected: false, connecting: false, connectError: error }) + + const onUpdate = (update) => { + onConnected(); + setSearches(update); + } + useEffect(() => { + onConnecting(); + const searchHub = createSearchLogHubConnection(); - searchHub.on('load', searches => { - setConnected(true); - setSearches(searches.reduce((acc, search) => { + searchHub.on('list', searches => { + onUpdate(searches.reduce((acc, search) => { acc[search.id] = search; return acc; }, {})); + onConnected(); }) searchHub.on('update', search => { - setConnected(true); - setSearches(old => ({ ...old, [search.id]: search })) + onUpdate(old => ({ ...old, [search.id]: search })); }); searchHub.on('delete', search => { - setConnected(true); - setSearches(old => { + onUpdate(old => { delete old[search.id]; return { ...old } }); }); - searchHub.on('response', () => { }); + 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') + } + } - searchHub.onreconnecting(() => setConnected(false)); - searchHub.onclose(() => setConnected(false)); - searchHub.onreconnected(() => setConnected(true)); + connect(); - searchHub.start(); + return () => { + searchHub.stop(); + } }, []); const create = async () => { @@ -69,18 +92,7 @@ const SearchList = () => { } const get = async () => { - setLoading({ loading: true, error: false }); - - try { - const all = await lib.getAll(); - setSearches(all.reduce((acc, search) => { - acc[search.id] = search; - return acc; - }, {})); - setLoading({ loading: false, error: false }) - } catch (error) { - setLoading({ loading: false, error: error.message }) - } + } const remove = async (search) => { @@ -105,6 +117,19 @@ const SearchList = () => { // todo } + const TableContents = () => ( + <> + {Object.values(searches) + .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) + .map((search, index) => )} + + ); + return ( <> @@ -116,44 +141,46 @@ const SearchList = () => { cancelAndDeleteAll()} /> - + cancelAndDeleteAll()} /> - + -
- - - - Search Phrase - Files - Locked - Responses - Started - - - - - {Object.values(searches) - .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) - .map((search, index) => )} - -
+ + } + error={error && } + > + + + + + Search Phrase + Files + Locked + Responses + Started + + + + + + +
+
+
diff --git a/src/web/src/components/Search/List/SearchListRow.js b/src/web/src/components/Search/List/SearchListRow.js index a2941c0a..907569a6 100644 --- a/src/web/src/components/Search/List/SearchListRow.js +++ b/src/web/src/components/Search/List/SearchListRow.js @@ -31,7 +31,7 @@ const SearchListRow = ({ search, index, onRemove, onStop }) => { } return ( invoke(() => onStop(search))} {...props} diff --git a/src/web/src/components/Search/SearchIcon.js b/src/web/src/components/Search/SearchIcon.js index 05704643..d3643ceb 100644 --- a/src/web/src/components/Search/SearchIcon.js +++ b/src/web/src/components/Search/SearchIcon.js @@ -21,7 +21,7 @@ const getIcon = ({ state, ...props }) => { case 'Completed, FileLimitReached': return case 'Completed, Cancelled': - return + return case 'Completed, Errored': return default: 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 -- cgit v1.2.3 From fbbb8b87b25f4add96f10099b91daedfe00c5f28 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 Apr 2022 20:55:34 -0500 Subject: add WithSoulseekSearch --- src/slskd/Search/Extensions.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src') diff --git a/src/slskd/Search/Extensions.cs b/src/slskd/Search/Extensions.cs index 149e0a14..b43c3e68 100644 --- a/src/slskd/Search/Extensions.cs +++ b/src/slskd/Search/Extensions.cs @@ -118,5 +118,21 @@ namespace slskd.Search Token = s.Token, }); } + + public static Search WithSoulseekSearch(this Search search, Soulseek.Search s) + { + return new Search() + { + Id = search.Id, + StartedAt = search.StartedAt, + EndedAt = search.EndedAt, + FileCount = s.FileCount, + LockedFileCount = s.LockedFileCount, + ResponseCount = s.ResponseCount, + SearchText = search.SearchText, + State = s.State, + Token = search.Token, + }; + } } } -- cgit v1.2.3 From afb0af902010c2a5c64a054a7f0be0f6f655695b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 Apr 2022 20:56:32 -0500 Subject: remove disconnect handler --- src/slskd/Search/API/Hubs/SearchHub.cs | 10 ---------- 1 file changed, 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index 5c9fc114..aaf9a287 100644 --- a/src/slskd/Search/API/Hubs/SearchHub.cs +++ b/src/slskd/Search/API/Hubs/SearchHub.cs @@ -15,8 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -using Microsoft.Extensions.Options; - namespace slskd.Search.API { using System; @@ -46,7 +44,6 @@ namespace slskd.Search.API /// The operation context. public static Task BroadcastUpdateAsync(this IHubContext hub, Search search) { - // todo: throttle updates to at most 1 per 100ms or so return hub.Clients.All.SendAsync(SearchHubMethods.Update, search); } @@ -91,13 +88,6 @@ namespace slskd.Search.API { var searches = await Searches.ListAsync(); await Clients.Caller.SendAsync(SearchHubMethods.List, searches); - // todo: create buffer specific to this client - } - - public override Task OnDisconnectedAsync(Exception exception) - { - // todo: destroy buffer specific to this client - return Task.CompletedTask; } } } \ No newline at end of file -- cgit v1.2.3 From d675d04aafabc0ca5b1ac1f762e6296fd19dc7b9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 Apr 2022 20:57:09 -0500 Subject: simplify updates --- src/slskd/Search/SearchService.cs | 55 +++++++-------------------------------- 1 file changed, 10 insertions(+), 45 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 8042388f..afbfe0fb 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -35,7 +35,6 @@ namespace slskd.Search using SearchQuery = Soulseek.SearchQuery; using SearchScope = Soulseek.SearchScope; using SearchStates = Soulseek.SearchStates; - using SoulseekSearch = Soulseek.Search; /// /// Handles the lifecycle and persistence of searches. @@ -48,29 +47,24 @@ namespace slskd.Search /// /// /// - /// /// The database context to use. /// The logger. public SearchService( IHubContext searchHub, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, - IApplication application, IDbContextFactory contextFactory, ILogger log) { SearchHub = searchHub; OptionsMonitor = optionsMonitor; Client = soulseekClient; - Application = application; ContextFactory = contextFactory; Log = log; } - private IApplication Application { get; } - private ConcurrentDictionary CancellationTokens { get; } - = new ConcurrentDictionary(); + = new ConcurrentDictionary(); private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } @@ -102,13 +96,14 @@ namespace slskd.Search options ??= new SearchOptions(); options = options.WithActions( - stateChanged: (args) => UpdateSearchState(search, args.Search), - responseReceived: (args) => UpdateSearchResponses(search, args.Search, args.Response)); + stateChanged: (args) => SearchHub.BroadcastUpdateAsync(search.WithSoulseekSearch(args.Search)), + responseReceived: (args) => SearchHub.BroadcastUpdateAsync(search.WithSoulseekSearch(args.Search))); using var context = ContextFactory.CreateDbContext(); context.Add(search); await context.SaveChangesAsync(); + await SearchHub.BroadcastCreateAsync(search); CancellationTokens.TryAdd(id, cancellationTokenSource); @@ -124,13 +119,12 @@ namespace slskd.Search CancellationTokens.TryRemove(id, out _); - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - search.EndedAt = DateTime.UtcNow; + search = search.WithSoulseekSearch(soulseekSearch); search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); - SaveSearchState(search); + + using var context = ContextFactory.CreateDbContext(); + context.Update(search); + context.SaveChanges(); }, cancellationToken: cancellationTokenSource.Token); return search; @@ -151,6 +145,7 @@ namespace slskd.Search using var context = ContextFactory.CreateDbContext(); context.Searches.Remove(search); await context.SaveChangesAsync(); + await SearchHub.BroadcastDeleteAsync(search); } @@ -207,35 +202,5 @@ namespace slskd.Search return false; } - - private void SaveSearchState(Search search) - { - var context = ContextFactory.CreateDbContext(); - context.Update(search); - context.SaveChanges(); - } - - private void UpdateSearchResponses(Search search, SoulseekSearch soulseekSearch, Soulseek.SearchResponse response) - { - if (CancellationTokens.ContainsKey(search.Id)) - { - //SearchHub.BroadcastResponseAsync(search.Id, response); - UpdateSearchState(search, soulseekSearch); - } - } - - private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) - { - if (CancellationTokens.ContainsKey(search.Id)) - { - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - - SearchHub.BroadcastUpdateAsync(search); - //SaveSearchState(search); - } - } } } \ No newline at end of file -- cgit v1.2.3 From 938b3ad1f34b671fc967849bd668610838e499d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 Apr 2022 22:41:23 -0500 Subject: add RateLimiter --- src/slskd/Common/RateLimiter.cs | 94 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/slskd/Common/RateLimiter.cs (limited to 'src') diff --git a/src/slskd/Common/RateLimiter.cs b/src/slskd/Common/RateLimiter.cs new file mode 100644 index 00000000..af0e9870 --- /dev/null +++ b/src/slskd/Common/RateLimiter.cs @@ -0,0 +1,94 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.ComponentModel; + + /// + /// Ensures a minimum interval between successive invocations of a delegate. + /// + public class RateLimiter : IDisposable + { + /// + /// Initializes a new instance of the class. + /// + /// The minimum interval between invocations. + public RateLimiter(int interval) + { + Timer = new System.Timers.Timer(interval) + { + AutoReset = true, + }; + + Timer.Elapsed += (s, e) => + { + Staged?.Invoke(); + Staged = null; + }; + } + + private bool Disposed { get; set; } + private bool Init { get; set; } + private Action Staged { get; set; } + private System.Timers.Timer Timer { get; set; } + + /// + /// Releases all resources used by the . + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// + /// Invokes the specified , dropping invocations created prior to the elapse of the + /// configured interval. + /// + /// The delegate to invoke. + public void Invoke(Action action) + { + if (!Init) + { + Init = true; + Timer.Start(); + action(); + return; + } + + Staged = action; + } + + /// + /// Releases all resources used by the . + /// + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + Timer.Dispose(); + } + + Disposed = true; + } + } + } +} \ No newline at end of file -- cgit v1.2.3 From 3e5126630c88aae010c0d91f0f2597c1815fb5e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 Apr 2022 22:42:13 -0500 Subject: rate limit updates --- src/slskd/Search/SearchService.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index afbfe0fb..7eda0f0b 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -94,20 +94,21 @@ namespace slskd.Search StartedAt = DateTime.Now, }; + var rateLimiter = new RateLimiter(250); + options ??= new SearchOptions(); options = options.WithActions( stateChanged: (args) => SearchHub.BroadcastUpdateAsync(search.WithSoulseekSearch(args.Search)), - responseReceived: (args) => SearchHub.BroadcastUpdateAsync(search.WithSoulseekSearch(args.Search))); + responseReceived: (args) => rateLimiter.Invoke(() => SearchHub.BroadcastUpdateAsync(search.WithSoulseekSearch(args.Search)))); using var context = ContextFactory.CreateDbContext(); - context.Add(search); await context.SaveChangesAsync(); - await SearchHub.BroadcastCreateAsync(search); - CancellationTokens.TryAdd(id, cancellationTokenSource); + await SearchHub.BroadcastCreateAsync(search); + _ = Task.Run(async () => { var (soulseekSearch, responses) = await Client.SearchAsync( @@ -117,9 +118,11 @@ namespace slskd.Search options, cancellationToken: cancellationTokenSource.Token); + rateLimiter.Dispose(); CancellationTokens.TryRemove(id, out _); search = search.WithSoulseekSearch(soulseekSearch); + await SearchHub.BroadcastUpdateAsync(search); search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); using var context = ContextFactory.CreateDbContext(); -- cgit v1.2.3 From 5545e4730c44a8fc5b1ec25629b962160d05fb34 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 Apr 2022 22:13:58 -0500 Subject: send EndedAt --- src/slskd/Search/SearchService.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 7eda0f0b..e8b78031 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -121,8 +121,11 @@ namespace slskd.Search rateLimiter.Dispose(); CancellationTokens.TryRemove(id, out _); + search.EndedAt = DateTime.Now; search = search.WithSoulseekSearch(soulseekSearch); + await SearchHub.BroadcastUpdateAsync(search); + search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); using var context = ContextFactory.CreateDbContext(); -- cgit v1.2.3 From f2b11298df5f2523168ad65613d5f93206b315f4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 Apr 2022 22:14:12 -0500 Subject: wip --- src/web/src/components/Search/List/SearchList.js | 77 +++++++++------------- .../src/components/Search/List/SearchListRow.js | 47 ++----------- 2 files changed, 38 insertions(+), 86 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js index 08490210..806196f1 100644 --- a/src/web/src/components/Search/List/SearchList.js +++ b/src/web/src/components/Search/List/SearchList.js @@ -1,4 +1,5 @@ -import React, { useState, useEffect, useRef } from 'react'; +import { isEmpty } from 'lodash'; +import React, { useState, useEffect, useRef, useMemo } from 'react'; import { v4 as uuidv4 } from 'uuid'; @@ -13,7 +14,9 @@ import { Card, Table, Icon, - Loader + Loader, + Segment, + Checkbox } from 'semantic-ui-react'; import SearchIcon from '../SearchIcon'; @@ -28,6 +31,10 @@ const SearchList = () => { const onConnected = () => setConnected({ connected: true, connecting: false, connectError: false }); const onConnectionError = (error) => setConnected({ connected: false, connecting: false, connectError: error }) + const searchCount = useMemo(() => { + return Object.values(searches).length + }, [searches]) + const onUpdate = (update) => { onConnected(); setSearches(update); @@ -113,77 +120,55 @@ const SearchList = () => { await lib.stop({ id: search.id }) } - const cancelAndDeleteAll = () => { - // todo - } - - const TableContents = () => ( - <> - {Object.values(searches) - .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) - .map((search, index) => )} - - ); + console.log(searches) return ( - <> Searches - - cancelAndDeleteAll()} - /> - - - - cancelAndDeleteAll()} - /> - - } - error={error && } + error={error && } > - - Search Phrase + + + Search Files Locked Responses - Started - + Ended - + + + No searches to display + + } + > + {Object.values(searches) + .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) + .map((search, index) => )} +
- ) }; diff --git a/src/web/src/components/Search/List/SearchListRow.js b/src/web/src/components/Search/List/SearchListRow.js index 907569a6..6288ef17 100644 --- a/src/web/src/components/Search/List/SearchListRow.js +++ b/src/web/src/components/Search/List/SearchListRow.js @@ -1,56 +1,23 @@ -import React, { useState } from 'react'; +import React from 'react'; import SearchIcon from '../SearchIcon'; import { Table, - Icon + Icon, + Checkbox } from 'semantic-ui-react'; const SearchListRow = ({ search, index, onRemove, onStop }) => { - const [working, setWorking] = useState(false); - - const invoke = async (func) => { - setWorking(true); - await func(); - setWorking(false); - } - - const ActionIcon = ({ ...props }) => { - if (working) { - return () - } - - if (search.state.includes('Completed')) { - return ( invoke(() => onRemove(search))} - {...props} - />) - } - - return ( invoke(() => onStop(search))} - {...props} - />) - } - // - return ( - - + + + {search.searchText} {search.fileCount} {search.lockedFileCount} {search.responseCount} - {new Date(search.startedAt).toLocaleTimeString()} - + {search.endedAt ? new Date(search.endedAt).toLocaleTimeString() : '-'} ) } -- cgit v1.2.3 From 9ab5999103b59976f0ad580b6ec849f961a91f68 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 Apr 2022 22:46:26 -0500 Subject: add button for background search --- src/web/src/components/Search/Search.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index 5704c3c0..887937b3 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -59,6 +59,14 @@ class Search extends Component { }); } + backgroundSearch = async () => { + const searchPhrase = this.inputtext.inputRef.current.value; + const searchId = uuidv4(); + await searches.create({ id: searchId, searchText: searchPhrase }); + this.setSearchText(); + this.inputtext.focus(); + } + clear = () => { this.setState(initialState, () => { this.saveState(); @@ -217,7 +225,11 @@ class Search extends Component { disabled={pending} className='search-input' placeholder="Search phrase" - action={!pending && (searchState === 'idle' ? { icon: 'search', onClick: this.search } : { icon: 'x', color: 'red', onClick: this.clear })} + action={!pending && (searchState === 'idle' ? + <> + + : filteredCount > 0 ? + : ''} + ) } -- cgit v1.2.3 From 3ee2c0b442660f13f36beae095eff2beb059cec9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 16 May 2022 10:54:12 -0500 Subject: wip --- src/web/src/components/App.css | 6 +- src/web/src/components/App.js | 4 +- .../src/components/Search/Detail/SearchDetail.js | 27 +++++++- src/web/src/components/Search/Searches.js | 77 +++++++++------------- src/web/src/components/Shared/LoaderSegment.js | 11 ++++ 5 files changed, 75 insertions(+), 50 deletions(-) create mode 100644 src/web/src/components/Shared/LoaderSegment.js (limited to 'src') diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index 9cad4f33..1f52554c 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -145,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 2a390de4..5e1cda69 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -244,7 +244,7 @@ class App extends Component { - this.withTokenCheck()}/> + this.withTokenCheck(
)}/> this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> @@ -260,4 +260,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 index fd696f8e..31d2616e 100644 --- a/src/web/src/components/Search/Detail/SearchDetail.js +++ b/src/web/src/components/Search/Detail/SearchDetail.js @@ -12,13 +12,14 @@ import { import ErrorSegment from '../../Shared/ErrorSegment'; import Response from '../Response'; import { getResponses, parseFiltersFromString, filterResponse } from '../../../lib/searches'; +import LoaderSegment from '../../Shared/LoaderSegment'; 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 }) => { +const SearchDetail = ({ search, onStop, onBack }) => { const { id, state, isComplete, fileCount, lockedFileCount, responseCount } = search; const [loading, setLoading] = useState(false); @@ -100,11 +101,33 @@ const SearchDetail = ({ search }) => { } if (loading) { - return () + return () } return ( <> + + {/* } + size='big' + ref={searchRef} + disabled={true} + className='search-input' + placeholder="Search phrase" + action={ + ) }; diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css index 10d7c15f..d4010bc0 100644 --- a/src/web/src/components/Search/Search.css +++ b/src/web/src/components/Search/Search.css @@ -97,4 +97,15 @@ .search-list-action { width: 5px !important; +} + +.search-detail-header { + font-weight: normal !important; + margin-top: 13px !important; + margin-left: 16px !important; +} + +.search-detail-action-button { + float: right; + margin-top: -48px !important; } \ No newline at end of file -- cgit v1.2.3 From 1fa2b9911f1b1f80ff246140758fc6a7cd09df60 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 16 May 2022 22:27:07 -0500 Subject: move SearchStatusIcon --- .../src/components/Search/List/SearchStatusIcon.js | 35 ---------------------- src/web/src/components/Search/SearchStatusIcon.js | 35 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 35 deletions(-) delete mode 100644 src/web/src/components/Search/List/SearchStatusIcon.js create mode 100644 src/web/src/components/Search/SearchStatusIcon.js (limited to 'src') diff --git a/src/web/src/components/Search/List/SearchStatusIcon.js b/src/web/src/components/Search/List/SearchStatusIcon.js deleted file mode 100644 index c5de5d72..00000000 --- a/src/web/src/components/Search/List/SearchStatusIcon.js +++ /dev/null @@ -1,35 +0,0 @@ -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 - case 'InProgress': - return - case 'Completed, TimedOut': - case 'Completed, ResponseLimitReached': - case 'Completed, FileLimitReached': - return - case 'Completed, Cancelled': - return - case 'Completed, Errored': - return - default: - return - } -} - -const SearchStatusIcon = ({ state, ...props }) => - - -export default SearchStatusIcon; \ 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 + case 'InProgress': + return + case 'Completed, TimedOut': + case 'Completed, ResponseLimitReached': + case 'Completed, FileLimitReached': + return + case 'Completed, Cancelled': + return + case 'Completed, Errored': + return + default: + return + } +} + +const SearchStatusIcon = ({ state, ...props }) => + + +export default SearchStatusIcon; \ No newline at end of file -- cgit v1.2.3 From 739e6398e237facf2c23eb689d1c051ab5d9d551 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 16 May 2022 22:27:23 -0500 Subject: move SearchStatusIcon --- src/web/src/components/Search/List/SearchListRow.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/List/SearchListRow.js b/src/web/src/components/Search/List/SearchListRow.js index 90648dae..c2552892 100644 --- a/src/web/src/components/Search/List/SearchListRow.js +++ b/src/web/src/components/Search/List/SearchListRow.js @@ -10,7 +10,7 @@ import { Icon, } from 'semantic-ui-react'; -import SearchStatusIcon from './SearchStatusIcon'; +import SearchStatusIcon from '../SearchStatusIcon'; import SearchActionIcon from './SearchActionIcon'; const SearchListRow = ({ search, onRemove, onStop }) => { -- cgit v1.2.3 From 302fa8b8deb8f2d67850c5ec8f46c0b0b31f243e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 16 May 2022 22:41:31 -0500 Subject: clean up loader --- .../src/components/Search/Detail/SearchDetail.js | 36 ++++++++++++---------- src/web/src/components/Search/Searches.js | 4 +-- src/web/src/components/Shared/LoaderSegment.js | 4 +-- 3 files changed, 23 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Detail/SearchDetail.js b/src/web/src/components/Search/Detail/SearchDetail.js index 810ac897..5cadd941 100644 --- a/src/web/src/components/Search/Detail/SearchDetail.js +++ b/src/web/src/components/Search/Detail/SearchDetail.js @@ -1,7 +1,6 @@ import React, { useEffect, useState, useMemo } from 'react'; import { - Loader, Checkbox, Input, Segment, @@ -9,6 +8,7 @@ import { Button, } from 'semantic-ui-react'; +import Switch from '../../Shared/Switch'; import ErrorSegment from '../../Shared/ErrorSegment'; import Response from '../Response'; import { getResponses, parseFiltersFromString, filterResponse } from '../../../lib/searches'; @@ -20,7 +20,7 @@ const sortDropdownOptions = [ { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' } ]; -const SearchDetail = ({ search, onStop, onBack }) => { +const SearchDetail = ({ search, onStop, onRemove }) => { const { id, state, isComplete, fileCount, lockedFileCount, responseCount } = search; const [loading, setLoading] = useState(false); @@ -92,22 +92,23 @@ const SearchDetail = ({ search, onStop, onBack }) => { return () } - if (!isComplete) { - return ( - - {state === 'InProgress' ? Found {fileCount} files {lockedFileCount > 0 ? `(plus ${lockedFileCount} locked) ` : ''}from {responseCount} users - : 'Loading results...'} - - ); - } - - if (loading) { - return () - } - return ( <> - + + + {state === 'InProgress' ? `Found ${fileCount} files ${lockedFileCount > 0 ? `(plus ${lockedFileCount} locked) ` : ''}from ${responseCount} users` + : 'Loading results...'} + + } + loading={loading && } + > {(results && results.length > 0) && { : filteredCount > 0 ? : ''} - +
+ ) } diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index 34b0db88..31e77e08 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -119,7 +119,7 @@ const Searches = () => { return { ...old } }); } catch (err) { - setError(error.message); + setError(error?.message ?? error); } }; @@ -141,7 +141,7 @@ const Searches = () => { history.push('/searches')} + onRemove={remove} /> ); } diff --git a/src/web/src/components/Shared/LoaderSegment.js b/src/web/src/components/Shared/LoaderSegment.js index e63d8029..cc3d598c 100644 --- a/src/web/src/components/Shared/LoaderSegment.js +++ b/src/web/src/components/Shared/LoaderSegment.js @@ -2,9 +2,9 @@ import React from 'react'; import { Segment, Loader } from 'semantic-ui-react'; -const LoaderSegment = ({ caption }) => ( +const LoaderSegment = ({ size = 'big', children, ...props }) => ( - {caption} + {children} ); -- cgit v1.2.3 From ac1ca6e5d11adfd13d0917b3776cb75e9a20574c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 16 May 2022 22:45:53 -0500 Subject: make list font bigger --- src/web/src/components/Search/List/SearchList.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js index 48414772..c65c949d 100644 --- a/src/web/src/components/Search/List/SearchList.js +++ b/src/web/src/components/Search/List/SearchList.js @@ -40,7 +40,7 @@ const SearchList = ({ connecting = false, error = undefined, searches = {}, onRe No searches to display } > - +
-- cgit v1.2.3 From 12ccc35465336ab76cbea4b8e86e637c26d6c04e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 May 2022 08:14:50 -0500 Subject: media queries, ability to re-search --- .../src/components/Search/Detail/SearchDetail.js | 5 +- .../components/Search/Detail/SearchDetailHeader.js | 57 ++++++++++++++++------ src/web/src/components/Search/Searches.js | 15 ++++-- 3 files changed, 55 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Detail/SearchDetail.js b/src/web/src/components/Search/Detail/SearchDetail.js index 5cadd941..19cc1b84 100644 --- a/src/web/src/components/Search/Detail/SearchDetail.js +++ b/src/web/src/components/Search/Detail/SearchDetail.js @@ -20,7 +20,7 @@ const sortDropdownOptions = [ { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' } ]; -const SearchDetail = ({ search, onStop, onRemove }) => { +const SearchDetail = ({ search, onCreate, onStop, onRemove }) => { const { id, state, isComplete, fileCount, lockedFileCount, responseCount } = search; const [loading, setLoading] = useState(false); @@ -96,7 +96,8 @@ const SearchDetail = ({ search, onStop, onRemove }) => { <> diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.js b/src/web/src/components/Search/Detail/SearchDetailHeader.js index 0768d963..7b78d134 100644 --- a/src/web/src/components/Search/Detail/SearchDetailHeader.js +++ b/src/web/src/components/Search/Detail/SearchDetailHeader.js @@ -1,4 +1,5 @@ import React from 'react'; +import { useMediaQuery } from 'react-responsive'; import { Segment, @@ -8,7 +9,10 @@ import { } from 'semantic-ui-react'; import SearchStatusIcon from '../SearchStatusIcon'; -const SearchDetailHeader = ({ search, loading, onStop, onRemove }) => { +const SearchDetailHeader = ({ search, loading, onCreate, onStop, onRemove }) => { + const isSmallScreen = useMediaQuery({ query: '(max-width: 899px)' }); + const isTinyScreen = useMediaQuery({ query: '(max-width: 684px)'}); + const { searchText, isComplete, state } = search; const stopOrRemove = () => { @@ -19,22 +23,43 @@ const SearchDetailHeader = ({ search, loading, onStop, onRemove }) => { } } + const RefreshButton = ({ ...props }) => + + + const StopOrDeleteButton = ({ ...props }) => + + return ( - -
- - {searchText} -
- -
+ <> + +
+ {searchText} +
+ {!isTinyScreen &&
+ + +
} +
+ {isTinyScreen && + + + } + ) }; diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index 31e77e08..32496bf9 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -93,20 +93,26 @@ const Searches = () => { } }, []); - const create = async ({ navigate = false } = {}) => { - const searchText = inputRef.current.inputRef.current.value; + const create = async ({ search, navigate = false } = {}) => { + const searchText = search || inputRef.current.inputRef.current.value; const id = uuidv4(); try { setCreating({ creating: true, createError: false }) await lib.create({ id, searchText }) setCreating({ creating: false, createError: false }) - inputRef.current.inputRef.current.value = ''; + + try { + inputRef.current.inputRef.current.value = ''; + } catch { + // no-op + } if (navigate) { - history.push(`${match.url}/${id}`) + history.push(`/searches/${id}`) } } catch (error) { + console.error(error) setCreating({ creating: false, createError: error.message }) } } @@ -140,6 +146,7 @@ const Searches = () => { return ( -- cgit v1.2.3 From d303e5e03cb09f51ea04cc259667ed502406dc70 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 May 2022 08:15:02 -0500 Subject: fix media breakpoint --- src/web/src/components/Search/Search.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css index d4010bc0..fb90353d 100644 --- a/src/web/src/components/Search/Search.css +++ b/src/web/src/components/Search/Search.css @@ -31,7 +31,7 @@ } } -@media only screen and (max-width: 685px) { +@media only screen and (max-width: 684px) { .search-options-sort { width: 100%; } -- cgit v1.2.3 From 30d5f990c5bd0a5519f3a8242c91a23d663d8b60 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 May 2022 09:59:44 -0500 Subject: add sleep function --- src/web/src/lib/util.js | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') 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 -- cgit v1.2.3 From b8bf146c78e26dd7d8a9fc849b508434b5a2a3e2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 May 2022 10:00:31 -0500 Subject: clean up and document --- .../src/components/Search/Detail/SearchDetail.js | 50 +++++++++++++--- .../components/Search/Detail/SearchDetailHeader.js | 22 ++++--- src/web/src/components/Search/Search.css | 3 +- src/web/src/components/Search/Searches.js | 70 ++++++++++++++-------- 4 files changed, 102 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Detail/SearchDetail.js b/src/web/src/components/Search/Detail/SearchDetail.js index 19cc1b84..880d5cd0 100644 --- a/src/web/src/components/Search/Detail/SearchDetail.js +++ b/src/web/src/components/Search/Detail/SearchDetail.js @@ -8,6 +8,7 @@ import { Button, } from 'semantic-ui-react'; +import { sleep } from '../../../lib/util'; import Switch from '../../Shared/Switch'; import ErrorSegment from '../../Shared/ErrorSegment'; import Response from '../Response'; @@ -20,7 +21,7 @@ const sortDropdownOptions = [ { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' } ]; -const SearchDetail = ({ search, onCreate, onStop, onRemove }) => { +const SearchDetail = ({ search, creating, stopping, removing, onCreate, onStop, onRemove }) => { const { id, state, isComplete, fileCount, lockedFileCount, responseCount } = search; const [loading, setLoading] = useState(false); @@ -28,6 +29,7 @@ const SearchDetail = ({ search, onCreate, onStop, onRemove }) => { const [results, setResults] = useState([]); + // filters and sorting options const [hiddenResults, setHiddenResults] = useState([]); const [resultSort, setResultSort] = useState('uploadSpeed'); const [hideLocked, setHideLocked] = useState(true); @@ -36,10 +38,17 @@ const SearchDetail = ({ search, onCreate, onStop, onRemove }) => { 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); @@ -54,6 +63,8 @@ const SearchDetail = ({ search, onCreate, onStop, onRemove }) => { } }, [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' }, @@ -85,8 +96,29 @@ const SearchDetail = ({ search, onCreate, onStop, onRemove }) => { }, [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 () @@ -96,10 +128,14 @@ const SearchDetail = ({ search, onCreate, onStop, onRemove }) => { <> { } loading={loading && } > - {(results && results.length > 0) && + {loaded && { /> } - {sortedAndFilteredResults.slice(0, displayCount).map((r, i) => + {loaded && sortedAndFilteredResults.slice(0, displayCount).map((r, i) => { isInitiallyFolded={foldResults} /> )} - {remainingCount > 0 ? + {loaded && (remainingCount > 0 ? : filteredCount > 0 ? - : ''} + : '')} ) diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.js b/src/web/src/components/Search/Detail/SearchDetailHeader.js index 7b78d134..d31f8a49 100644 --- a/src/web/src/components/Search/Detail/SearchDetailHeader.js +++ b/src/web/src/components/Search/Detail/SearchDetailHeader.js @@ -9,11 +9,12 @@ import { } from 'semantic-ui-react'; import SearchStatusIcon from '../SearchStatusIcon'; -const SearchDetailHeader = ({ search, loading, onCreate, onStop, onRemove }) => { +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) { @@ -23,27 +24,32 @@ const SearchDetailHeader = ({ search, loading, onCreate, onStop, onRemove }) => } } - const RefreshButton = ({ ...props }) => + const RefreshButton = () => loaded && - const StopOrDeleteButton = ({ ...props }) => + const StopOrDeleteButton = () => + // 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 ( <> @@ -55,7 +61,7 @@ const SearchDetailHeader = ({ search, loading, onCreate, onStop, onRemove }) => } - {isTinyScreen && + {isTinyScreen && } diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css index fb90353d..42912ed5 100644 --- a/src/web/src/components/Search/Search.css +++ b/src/web/src/components/Search/Search.css @@ -101,8 +101,7 @@ .search-detail-header { font-weight: normal !important; - margin-top: 13px !important; - margin-left: 16px !important; + margin-top: 12px !important; } .search-detail-action-button { diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index 32496bf9..33fb4176 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -14,27 +14,29 @@ import { Input, Segment, Button, - Loader, } from 'semantic-ui-react'; import SearchDetail from './Detail/SearchDetail'; import ErrorSegment from '../Shared/ErrorSegment'; const Searches = () => { - const [{ connected, connecting, connectError } , setConnected] = useState({ connected: false, connecting: true, connectError: false }); - const [{ creating, createError }, setCreating] = useState({ creating: false, createError: false }); + 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 searchRef = useRef(); const { id: searchId } = useParams(); const history = useHistory(); const match = useRouteMatch(); - const onConnecting = () => setConnected({ connected: false, connecting: true, connectError: false }) - const onConnected = () => setConnected({ connected: true, connecting: false, connectError: false }); - const onConnectionError = (error) => setConnected({ connected: false, connecting: false, connectError: error }) + const onConnecting = () => { setConnecting(true); } + const onConnected = () => { setConnecting(false); setError(undefined); } + const onConnectionError = (error) => { setConnecting(false); setError(error); } const onUpdate = (update) => { onConnected(); @@ -47,7 +49,6 @@ const Searches = () => { const searchHub = createSearchHubConnection(); searchHub.on('list', searches => { - console.log('list of searches received', searches); onUpdate(searches.reduce((acc, search) => { acc[search.id] = search; return acc; @@ -56,7 +57,6 @@ const Searches = () => { }) searchHub.on('update', search => { - console.log(search.responses) onUpdate(old => ({ ...old, [search.id]: search })); }); @@ -75,10 +75,8 @@ const Searches = () => { const connect = async () => { try { - console.log('connecting to search hub'); onConnecting(); await searchHub.start(); - console.log('search hub connected'); } catch (error) { onConnectionError(error?.message ?? 'Failed to connect') } @@ -87,65 +85,85 @@ const Searches = () => { connect(); return () => { - console.log('stopping search hub'); searchHub.stop(); - console.log('search hub stopped'); } }, []); + // 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({ creating: true, createError: false }) + setCreating(true) await lib.create({ id, searchText }) - setCreating({ creating: false, createError: false }) - + try { inputRef.current.inputRef.current.value = ''; } catch { - // no-op + // we are probably repeating an existing search; the input isn't mounted. no-op. } + + setCreating(false) if (navigate) { - history.push(`/searches/${id}`) + history.push(`${match.url.replace(`/${searchId}`, '')}/${id}`); } } catch (error) { console.error(error) - setCreating({ creating: false, createError: error.message }) + 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) { - setError(error?.message ?? error); + console.error(err); + setRemoving(false); } }; + // stop an in-progress search const stop = async (search) => { - await lib.stop({ id: search.id }) + try { + setStopping(true); + await lib.stop({ id: search.id }) + setStopping(false); + } catch (error) { + console.error(error); + setStopping(false); + } } if (connecting) { return } - if (connectError) { - return ; + if (error) { + return ; } + // 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 ( { ); } - return ( - - ); + // 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 ( -- cgit v1.2.3 From 92f7903db4d98ec28a3827d11b4b9c8f67377369 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 May 2022 10:38:42 -0500 Subject: fix tests --- src/web/src/lib/search.test.js | 277 --------------------------------------- src/web/src/lib/searches.test.js | 277 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 277 insertions(+), 277 deletions(-) delete mode 100644 src/web/src/lib/search.test.js create mode 100644 src/web/src/lib/searches.test.js (limited to 'src') diff --git a/src/web/src/lib/search.test.js b/src/web/src/lib/search.test.js deleted file mode 100644 index 68afe91c..00000000 --- a/src/web/src/lib/search.test.js +++ /dev/null @@ -1,277 +0,0 @@ -import * as search from './search'; - -describe('filterResponse', () => { - it('removes VBR files if "iscbr" is specified', () => { - const response = { - files: [ - { bitRate: 123, isVariableBitRate: true }, - { bitRate: 320, isVariableBitRate: false } - ] - }; - - const filters = { isCBR: true }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { bitRate: 320, isVariableBitRate: false } - ] - }); - }); - - it('removes CBR files if "isvbr" is specified', () => { - const response = { - files: [ - { bitRate: 123, isVariableBitRate: true }, - { bitRate: 320, isVariableBitRate: false } - ] - }; - - const filters = { isVBR: true }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { bitRate: 123, isVariableBitRate: true } - ] - }); - }); - - it('removes all files if "iscbr" and "isvbr" are both specified', () => { - const response = { - files: [ - { isVariableBitrate: true }, - { isVariableBitrate: false } - ] - }; - - const filters = { isCBR: true, isVBR: true }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [] - }); - }); - - it('removes lossy files if "islossless" is specified', () => { - const response = { - files: [ - { sampleRate: 41000, bitDepth: 16 }, - { bitRate: 320, isVariableBitRate: false } - ] - }; - - const filters = { isLossless: true }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { sampleRate: 41000, bitDepth: 16 } - ] - }); - }); - - it('removes lossless files if "islossy" is specified', () => { - const response = { - files: [ - { sampleRate: 41000, bitDepth: 16 }, - { bitRate: 320, isVariableBitRate: false } - ] - }; - - const filters = { isLossy: true }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { bitRate: 320, isVariableBitRate: false } - ] - }); - }); - - it('removes files with bitRate less than minBitRate', () => { - const response = { - files: [ - { bitRate: 100 }, - { bitRate: 99 } - ] - }; - - const filters = { minBitRate: 100 }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { bitRate: 100 } - ] - }); - }); - - it('removes files with size less than minFileSize', () => { - const response = { - files: [ - { size: 100 }, - { size: 99 } - ] - }; - - const filters = { minFileSize: 100 }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { size: 100 } - ] - }); - }); - - it('removes files with length less than minLength', () => { - const response = { - files: [ - { length: 100 }, - { length: 99 } - ] - }; - - const filters = { minLength: 100 }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { length: 100 } - ] - }); - }); - - describe('term filtering', () => { - const response = { - files: [ - { filename: '/path/to/foo.mp3' }, - { filename: '/path/to/bar.mp3' }, - { filename: '/path/to/baz.mp3' }, - { filename: '/path/to/qux.mp3' }, - { filename: '/path/to/info.nfo' }, - { filename: '/path/to/folder.jpg' } - ] - }; - - 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' }, - ] - }); - }); - - it('removes files with filenames containing excluded phrases', () => { - const filters = { exclude: ['bar', 'jpg', 'qux'] }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { filename: '/path/to/foo.mp3' }, - { filename: '/path/to/baz.mp3' }, - { filename: '/path/to/info.nfo' }, - ] - }); - }); - - it('removes a mix of includes and excludes', () => { - const filters = { - include: ['path', '.mp3'], - exclude: ['foo', 'bar'] - }; - - expect(search.filterResponse({ response, filters })).toMatchObject({ - files: [ - { filename: '/path/to/baz.mp3' }, - { filename: '/path/to/qux.mp3' }, - ] - }); - }); - }); -}); - -describe('parseFiltersFromString', () => { - it('returns correct minBitrate', () => { - expect(search.parseFiltersFromString('foo minbr:42 bar')).toMatchObject({ - minBitRate: 42 - }); - - expect(search.parseFiltersFromString('foo minbitrate:123 bar')).toMatchObject({ - minBitRate: 123 - }); - }); - - it('returns correct minFileSize', () => { - expect(search.parseFiltersFromString('foo minfs:42 bar')).toMatchObject({ - minFileSize: 42 - }); - - expect(search.parseFiltersFromString('foo minfilesize:123 bar')).toMatchObject({ - minFileSize: 123 - }); - }); - - it('returns correct minLength', () => { - expect(search.parseFiltersFromString('foo minlen:42 bar')).toMatchObject({ - minLength: 42 - }); - - expect(search.parseFiltersFromString('foo minlength:123 bar')).toMatchObject({ - minLength: 123 - }); - }); - - it('returns correct minFilesInFolder', () => { - expect(search.parseFiltersFromString('foo minfif:42 bar')).toMatchObject({ - minFilesInFolder: 42 - }); - - 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'] - }); - - expect(search.parseFiltersFromString('foo iscbr isvbr bar')).toMatchObject({ - include: [ 'foo', 'bar'] - }); - - expect(search.parseFiltersFromString('foo some:thing bar')).toMatchObject({ - include: [ 'foo', 'bar'] - }); - - expect(search.parseFiltersFromString('foo -bar')).toMatchObject({ - include: [ 'foo' ], - exclude: [ 'bar' ] - }); - - expect(search.parseFiltersFromString('-foo -bar -baz qux')).toMatchObject({ - exclude: [ 'foo', 'bar', 'baz' ], - include: [ 'qux' ] - }); - - expect(search.parseFiltersFromString('foo bar baz -qux')).toMatchObject({ - include: [ 'foo', 'bar', 'baz' ], - exclude: [ 'qux' ] - }); - }); - - it('returns isVBR and isCBR if terms are present', () => { - expect(search.parseFiltersFromString('isvbr')).toMatchObject({ - isVBR: true - }); - - expect(search.parseFiltersFromString('iscbr')).toMatchObject({ - isCBR: true - }); - }); - - 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, - isCBR: true, - minBitRate: 42 - }); - }); -}); \ No newline at end of file diff --git a/src/web/src/lib/searches.test.js b/src/web/src/lib/searches.test.js new file mode 100644 index 00000000..737843ed --- /dev/null +++ b/src/web/src/lib/searches.test.js @@ -0,0 +1,277 @@ +import * as search from './searches'; + +describe('filterResponse', () => { + it('removes VBR files if "iscbr" is specified', () => { + const response = { + files: [ + { bitRate: 123, isVariableBitRate: true }, + { bitRate: 320, isVariableBitRate: false } + ] + }; + + const filters = { isCBR: true }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { bitRate: 320, isVariableBitRate: false } + ] + }); + }); + + it('removes CBR files if "isvbr" is specified', () => { + const response = { + files: [ + { bitRate: 123, isVariableBitRate: true }, + { bitRate: 320, isVariableBitRate: false } + ] + }; + + const filters = { isVBR: true }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { bitRate: 123, isVariableBitRate: true } + ] + }); + }); + + it('removes all files if "iscbr" and "isvbr" are both specified', () => { + const response = { + files: [ + { isVariableBitrate: true }, + { isVariableBitrate: false } + ] + }; + + const filters = { isCBR: true, isVBR: true }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [] + }); + }); + + it('removes lossy files if "islossless" is specified', () => { + const response = { + files: [ + { sampleRate: 41000, bitDepth: 16 }, + { bitRate: 320, isVariableBitRate: false } + ] + }; + + const filters = { isLossless: true }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { sampleRate: 41000, bitDepth: 16 } + ] + }); + }); + + it('removes lossless files if "islossy" is specified', () => { + const response = { + files: [ + { sampleRate: 41000, bitDepth: 16 }, + { bitRate: 320, isVariableBitRate: false } + ] + }; + + const filters = { isLossy: true }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { bitRate: 320, isVariableBitRate: false } + ] + }); + }); + + it('removes files with bitRate less than minBitRate', () => { + const response = { + files: [ + { bitRate: 100 }, + { bitRate: 99 } + ] + }; + + const filters = { minBitRate: 100 }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { bitRate: 100 } + ] + }); + }); + + it('removes files with size less than minFileSize', () => { + const response = { + files: [ + { size: 100 }, + { size: 99 } + ] + }; + + const filters = { minFileSize: 100 }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { size: 100 } + ] + }); + }); + + it('removes files with length less than minLength', () => { + const response = { + files: [ + { length: 100 }, + { length: 99 } + ] + }; + + const filters = { minLength: 100 }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { length: 100 } + ] + }); + }); + + describe('term filtering', () => { + const response = { + files: [ + { filename: '/path/to/foo.mp3' }, + { filename: '/path/to/bar.mp3' }, + { filename: '/path/to/baz.mp3' }, + { filename: '/path/to/qux.mp3' }, + { filename: '/path/to/info.nfo' }, + { filename: '/path/to/folder.jpg' } + ] + }; + + 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' }, + ] + }); + }); + + it('removes files with filenames containing excluded phrases', () => { + const filters = { exclude: ['bar', 'jpg', 'qux'] }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { filename: '/path/to/foo.mp3' }, + { filename: '/path/to/baz.mp3' }, + { filename: '/path/to/info.nfo' }, + ] + }); + }); + + it('removes a mix of includes and excludes', () => { + const filters = { + include: ['path', '.mp3'], + exclude: ['foo', 'bar'] + }; + + expect(search.filterResponse({ response, filters })).toMatchObject({ + files: [ + { filename: '/path/to/baz.mp3' }, + { filename: '/path/to/qux.mp3' }, + ] + }); + }); + }); +}); + +describe('parseFiltersFromString', () => { + it('returns correct minBitrate', () => { + expect(search.parseFiltersFromString('foo minbr:42 bar')).toMatchObject({ + minBitRate: 42 + }); + + expect(search.parseFiltersFromString('foo minbitrate:123 bar')).toMatchObject({ + minBitRate: 123 + }); + }); + + it('returns correct minFileSize', () => { + expect(search.parseFiltersFromString('foo minfs:42 bar')).toMatchObject({ + minFileSize: 42 + }); + + expect(search.parseFiltersFromString('foo minfilesize:123 bar')).toMatchObject({ + minFileSize: 123 + }); + }); + + it('returns correct minLength', () => { + expect(search.parseFiltersFromString('foo minlen:42 bar')).toMatchObject({ + minLength: 42 + }); + + expect(search.parseFiltersFromString('foo minlength:123 bar')).toMatchObject({ + minLength: 123 + }); + }); + + it('returns correct minFilesInFolder', () => { + expect(search.parseFiltersFromString('foo minfif:42 bar')).toMatchObject({ + minFilesInFolder: 42 + }); + + 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'] + }); + + expect(search.parseFiltersFromString('foo iscbr isvbr bar')).toMatchObject({ + include: [ 'foo', 'bar'] + }); + + expect(search.parseFiltersFromString('foo some:thing bar')).toMatchObject({ + include: [ 'foo', 'bar'] + }); + + expect(search.parseFiltersFromString('foo -bar')).toMatchObject({ + include: [ 'foo' ], + exclude: [ 'bar' ] + }); + + expect(search.parseFiltersFromString('-foo -bar -baz qux')).toMatchObject({ + exclude: [ 'foo', 'bar', 'baz' ], + include: [ 'qux' ] + }); + + expect(search.parseFiltersFromString('foo bar baz -qux')).toMatchObject({ + include: [ 'foo', 'bar', 'baz' ], + exclude: [ 'qux' ] + }); + }); + + it('returns isVBR and isCBR if terms are present', () => { + expect(search.parseFiltersFromString('isvbr')).toMatchObject({ + isVBR: true + }); + + expect(search.parseFiltersFromString('iscbr')).toMatchObject({ + isCBR: true + }); + }); + + 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, + isCBR: true, + minBitRate: 42 + }); + }); +}); \ No newline at end of file -- cgit v1.2.3 From c775d1415b393387b99c6e1ba108bb836d92ae2b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 May 2022 10:42:39 -0500 Subject: remove deprecated Search component --- src/web/src/components/App.js | 1 - src/web/src/components/Search/Search.js | 319 ------------------------------ src/web/src/components/Search/Searches.js | 1 + 3 files changed, 1 insertion(+), 320 deletions(-) delete mode 100644 src/web/src/components/Search/Search.js (limited to 'src') diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 5e1cda69..9654c2ff 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -8,7 +8,6 @@ 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'; diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js deleted file mode 100644 index 4f270a5d..00000000 --- a/src/web/src/components/Search/Search.js +++ /dev/null @@ -1,319 +0,0 @@ -import { v4 as uuidv4 } from 'uuid'; -import React, { Component } from 'react'; -import * as searches from '../../lib/searches'; - -import './Search.css'; - -import Response from './Response'; -import SearchList from './List/SearchList'; -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(); - searches.create({ id: searchId, searchText: searchPhrase }); - }); - } - - backgroundSearch = async () => { - const searchPhrase = this.inputtext.inputRef.current.value; - const searchId = uuidv4(); - await searches.create({ id: searchId, searchText: searchPhrase }); - this.setSearchText(); - this.inputtext.focus(); - } - - 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 searches.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 searches.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 = searches.parseFiltersFromString(resultFilters); - - return results - .filter(r => !hiddenResults.includes(r.username)) - .map(r => { - if (hideLocked) { - return { ...r, lockedFileCount: 0, lockedFiles: [] } - } - return r; - }) - .map(response => searches.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 ( -
- - } - size='big' - ref={input => this.inputtext = input} - loading={pending} - disabled={pending} - className='search-input' - placeholder="Search phrase" - action={!pending && (searchState === 'idle' ? - <> - - : ''} -
} - - ) - } -} - -export default Search; \ No newline at end of file diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index 33fb4176..b21f62b6 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -87,6 +87,7 @@ const Searches = () => { return () => { searchHub.stop(); } + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // create a new search, and optionally navigate to it to display the details -- cgit v1.2.3