diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-05-17 10:55:31 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-05-17 10:55:31 -0500 |
| commit | 8ea2d8a4d88180a103081cce7a425c2bb6172b03 (patch) | |
| tree | 7292443fa34f2cca21c432ed338d9013aa240d84 /src | |
| parent | 978d0d08ab34a9e5dd0211de1d242a264b17577e (diff) | |
| parent | daf5e72ad63109978eeef2d0c4377b942f6209cb (diff) | |
| download | slskd-8ea2d8a4d88180a103081cce7a425c2bb6172b03.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/ejs-3.1.8
Diffstat (limited to 'src')
27 files changed, 1082 insertions, 407 deletions
diff --git a/src/slskd/Common/RateLimiter.cs b/src/slskd/Common/RateLimiter.cs new file mode 100644 index 00000000..a5d1ba45 --- /dev/null +++ b/src/slskd/Common/RateLimiter.cs @@ -0,0 +1,97 @@ +// <copyright file="RateLimiter.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.ComponentModel; + + /// <summary> + /// Ensures a minimum interval between successive invocations of a delegate. + /// </summary> + public class RateLimiter : IDisposable + { + /// <summary> + /// Initializes a new instance of the <see cref="RateLimiter"/> class. + /// </summary> + /// <param name="interval">The minimum interval between invocations.</param> + 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; } + + /// <summary> + /// Releases all resources used by the <see cref="Component"/>. + /// </summary> + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// <summary> + /// Invokes the specified <paramref name="action"/>, dropping invocations created prior to the elapse of the + /// configured interval. + /// </summary> + /// <param name="action">The delegate to invoke.</param> + public void Invoke(Action action) + { + if (!Init) + { + Init = true; + Timer.Start(); + action(); + return; + } + + Staged = action; + } + + /// <summary> + /// Releases all resources used by the <see cref="Component"/>. + /// </summary> + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + // if an action is staged, invoke it to 'flush' + Staged?.Invoke(); + + Timer.Dispose(); + } + + Disposed = true; + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 66fe9762..40e6e72d 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -471,10 +471,11 @@ namespace slskd private static IServiceCollection ConfigureAspDotNetServices(this IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", builder => builder + .SetIsOriginAllowed((host) => true) .AllowAnyHeader() .AllowAnyMethod() - .SetIsOriginAllowed((host) => true) - .AllowCredentials())); + .AllowCredentials() + .WithExposedHeaders("X-URL-Base"))); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppDirectory, "data", ".DataProtection-Keys"))); 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<IActionResult> GetAll() { - return Ok(await Searches.ListAsync()); + var searches = await Searches.ListAsync(); + return Ok(searches); + } + + /// <summary> + /// Stops the search corresponding to the specified <paramref name="id"/>. + /// </summary> + /// <param name="id">The unique id of the search.</param> + /// <response code="200">The search was stopped.</response> + /// <response code="304">The search was not in progress.</response> + /// <returns></returns> + [HttpPut("{id}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(304)] + public async Task<IActionResult> 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); + } + + /// <summary> + /// Deletes the search corresponding to the specified <paramref name="id"/>. + /// </summary> + /// <param name="id">The unique id of the search.</param> + /// <response code="204">The search was deleted.</response> + /// <response code="404">A search with the specified id could not be found.</response> + /// <returns></returns> + [HttpDelete("{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public async Task<IActionResult> 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(); } } } diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index 86434669..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/. // </copyright> -using Microsoft.Extensions.Options; - namespace slskd.Search.API { using System; @@ -26,8 +24,11 @@ namespace slskd.Search.API public static class SearchHubMethods { + public static readonly string List = "LIST"; + public static readonly string Create = "CREATE"; public static readonly string Response = "RESPONSE"; public static readonly string Update = "UPDATE"; + public static readonly string Delete = "DELETE"; } /// <summary> @@ -57,6 +58,16 @@ namespace slskd.Search.API { return hub.Clients.All.SendAsync(SearchHubMethods.Response, new { searchId, response }); } + + public static Task BroadcastCreateAsync(this IHubContext<SearchHub> hub, Search search) + { + return hub.Clients.All.SendAsync(SearchHubMethods.Create, search); + } + + public static Task BroadcastDeleteAsync(this IHubContext<SearchHub> hub, Search search) + { + return hub.Clients.All.SendAsync(SearchHubMethods.Delete, search); + } } /// <summary> @@ -66,14 +77,17 @@ namespace slskd.Search.API public class SearchHub : Hub { public SearchHub( - IStateMonitor<State> stateMonitor, - IOptionsMonitor<Options> optionsMonitor) + ISearchService searchService) { - StateMonitor = stateMonitor; - OptionsMonitor = optionsMonitor; + Searches = searchService; } - private IStateMonitor<State> StateMonitor { get; } - private IOptionsMonitor<Options> OptionsMonitor { get; } + private ISearchService Searches { get; } + + public override async Task OnConnectedAsync() + { + var searches = await Searches.ListAsync(); + await Clients.Caller.SendAsync(SearchHubMethods.List, searches); + } } }
\ No newline at end of file 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/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, + }; + } } } 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 @@ -41,6 +41,13 @@ namespace slskd.Search Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); /// <summary> + /// Deletes the specified ssearch. + /// </summary> + /// <param name="search">The search to delete.</param> + /// <returns>The operation context.</returns> + Task DeleteAsync(Search search); + + /// <summary> /// Finds a single search matching the specified <paramref name="expression"/>. /// </summary> /// <param name="expression">The expression to use to match searches.</param> diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 1eb92bc2..57d5e321 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -28,14 +28,13 @@ namespace slskd.Search using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; + using Serilog; using slskd.Search.API; using Soulseek; using SearchOptions = Soulseek.SearchOptions; using SearchQuery = Soulseek.SearchQuery; using SearchScope = Soulseek.SearchScope; using SearchStates = Soulseek.SearchStates; - using SoulseekSearch = Soulseek.Search; /// <summary> /// Handles the lifecycle and persistence of searches. @@ -48,33 +47,27 @@ namespace slskd.Search /// <param name="searchHub"></param> /// <param name="optionsMonitor"></param> /// <param name="soulseekClient"></param> - /// <param name="application"></param> /// <param name="contextFactory">The database context to use.</param> /// <param name="log">The logger.</param> public SearchService( IHubContext<SearchHub> searchHub, IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient, - IApplication application, - IDbContextFactory<SearchDbContext> contextFactory, - ILogger<SearchService> log) + IDbContextFactory<SearchDbContext> contextFactory) { SearchHub = searchHub; OptionsMonitor = optionsMonitor; Client = soulseekClient; - Application = application; ContextFactory = contextFactory; - Log = log; } private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>(); - private IOptionsMonitor<Options> OptionsMonitor { get; } - private IApplication Application { get; } private ISoulseekClient Client { get; } private IDbContextFactory<SearchDbContext> ContextFactory { get; } - private ILogger<SearchService> Log { get; set; } + private ILogger Log { get; set; } = Serilog.Log.ForContext<Application>(); + private IOptionsMonitor<Options> OptionsMonitor { get; } private IHubContext<SearchHub> SearchHub { get; set; } /// <summary> @@ -88,7 +81,11 @@ namespace slskd.Search public async Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null) { var token = Client.GetNextToken(); + var cancellationTokenSource = new CancellationTokenSource(); + CancellationTokens.TryAdd(id, cancellationTokenSource); + + var rateLimiter = new RateLimiter(250); var search = new Search() { @@ -96,52 +93,86 @@ namespace slskd.Search Token = token, Id = id, State = SearchStates.Requested, - StartedAt = DateTime.UtcNow, + StartedAt = DateTime.Now, }; - options ??= new SearchOptions(); - options = options.WithActions( - stateChanged: (args) => UpdateSearchState(search, args.Search), - responseReceived: (args) => UpdateSearchResponses(search, args.Search, args.Response)); + using var context = ContextFactory.CreateDbContext(); + context.Add(search); + await context.SaveChangesAsync(); + await SearchHub.BroadcastCreateAsync(search); + + List<SearchResponse> responses = new(); - try + _ = Task.Run(async () => { - using var context = ContextFactory.CreateDbContext(); + try + { + options ??= new SearchOptions(); + options = options.WithActions( + stateChanged: (args) => + { + search = search.WithSoulseekSearch(args.Search); + SearchHub.BroadcastUpdateAsync(search); + }, + responseReceived: (args) => + rateLimiter.Invoke(() => SearchHub.BroadcastUpdateAsync(search.WithSoulseekSearch(args.Search)))); + + var soulseekSearch = await Client.SearchAsync( + query, + responseReceived: (response) => responses.Add(response), + scope, + token, + options, + cancellationToken: cancellationTokenSource.Token); + + search = search.WithSoulseekSearch(soulseekSearch); + } + finally + { + rateLimiter.Dispose(); + CancellationTokens.TryRemove(id, out _); + + try + { + using var context = ContextFactory.CreateDbContext(); - context.Add(search); - await context.SaveChangesAsync(); + search.EndedAt = DateTime.Now; + search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); - CancellationTokens.TryAdd(id, cancellationTokenSource); - var responses = new List<Response>(); + context.Update(search); + await context.SaveChangesAsync(); - var soulseekSearch = await Client.SearchAsync( - query, - responseReceived: (response) => + // zero responses before broadcasting + search.Responses = Enumerable.Empty<Response>(); + await SearchHub.BroadcastUpdateAsync(search); + } + catch (Exception ex) { - responses.Add(Response.FromSoulseekSearchResponse(response)); - }, - scope, - token, - options, - cancellationToken: cancellationTokenSource.Token); - - 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.Responses = responses; - SaveSearchState(search); - - return search; - } - finally + Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); + } + } + }); + + return search; + } + + /// <summary> + /// Deletes the specified ssearch. + /// </summary> + /// <param name="search">The search to delete.</param> + /// <returns>The operation context.</returns> + public async Task DeleteAsync(Search search) + { + if (search == default) { - CancellationTokens.TryRemove(id, out _); - Application.CollectGarbage(); + throw new ArgumentNullException(nameof(search)); } + + using var context = ContextFactory.CreateDbContext(); + context.Searches.Remove(search); + await context.SaveChangesAsync(); + + await SearchHub.BroadcastDeleteAsync(search); } /// <summary> @@ -197,35 +228,5 @@ namespace slskd.Search return false; } - - 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); - } - } - - 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 SaveSearchState(Search search) - { - var context = ContextFactory.CreateDbContext(); - context.Update(search); - context.SaveChanges(); - } } }
\ No newline at end of file diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index 6244cdf8..1f52554c 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -31,7 +31,11 @@ body { width: 100% !important; } -.result-card:last-child, .transfer-card:last-child { +.search-list-card { + width: 100% !important; +} + +.result-card:last-child, .transfer-card:last-child, .search-list-card:last-child { margin-bottom: 17px !important; } @@ -56,7 +60,7 @@ body { margin-top: 20px !important; } -.filelist-selector, .transferlist-selector { +.filelist-selector, .transferlist-selector, .list-selector { width: 40px; } @@ -141,4 +145,8 @@ body { .menu-icon-no-shadow { font-size: 1rem !important; text-shadow: unset !important; -}
\ No newline at end of file +} + +.loader-segment.ui.placeholder > :before { + background-color: transparent !important; +} diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 09f3f742..9654c2ff 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -8,7 +8,7 @@ import { urlBase } from '../config'; import { createApplicationHubConnection } from '../lib/hubFactory'; import './App.css'; -import Search from './Search/Search'; +import Searches from './Search/Searches'; import Browse from './Browse/Browse'; import Users from './Users/Users'; import Transfers from './Transfers/Transfers'; @@ -243,7 +243,7 @@ class App extends Component { </Sidebar> <Sidebar.Pusher className='app-content'> <Switch> - <Route path={`${urlBase}/searches`} render={(props) => this.withTokenCheck(<Search {...props}/>)}/> + <Route path={`${urlBase}/searches/:id?`} render={(props) => this.withTokenCheck(<div className='search-container'><Searches {...props}/></div>)}/> <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/> <Route path={`${urlBase}/users`} render={(props) => this.withTokenCheck(<Users {...props}/>)}/> <Route path={`${urlBase}/chat`} render={(props) => this.withTokenCheck(<Chat {...props}/>)}/> @@ -259,4 +259,4 @@ class App extends Component { }; }; -export default App; +export default App;
\ No newline at end of file diff --git a/src/web/src/components/Search/Detail/SearchDetail.js b/src/web/src/components/Search/Detail/SearchDetail.js new file mode 100644 index 00000000..880d5cd0 --- /dev/null +++ b/src/web/src/components/Search/Detail/SearchDetail.js @@ -0,0 +1,214 @@ +import React, { useEffect, useState, useMemo } from 'react'; + +import { + Checkbox, + Input, + Segment, + Dropdown, + Button, +} from 'semantic-ui-react'; + +import { sleep } from '../../../lib/util'; +import Switch from '../../Shared/Switch'; +import ErrorSegment from '../../Shared/ErrorSegment'; +import Response from '../Response'; +import { getResponses, parseFiltersFromString, filterResponse } from '../../../lib/searches'; +import LoaderSegment from '../../Shared/LoaderSegment'; +import SearchDetailHeader from './SearchDetailHeader'; + +const sortDropdownOptions = [ + { key: 'uploadSpeed', text: 'Upload Speed (Fastest to Slowest)', value: 'uploadSpeed' }, + { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' } +]; + +const SearchDetail = ({ search, creating, stopping, removing, onCreate, onStop, onRemove }) => { + const { id, state, isComplete, fileCount, lockedFileCount, responseCount } = search; + + const [loading, setLoading] = useState(false); + const [error, setError] = useState(undefined); + + const [results, setResults] = useState([]); + + // filters and sorting options + const [hiddenResults, setHiddenResults] = useState([]); + const [resultSort, setResultSort] = useState('uploadSpeed'); + const [hideLocked, setHideLocked] = useState(true); + const [hideNoFreeSlots, setHideNoFreeSlots] = useState(false); + const [foldResults, setFoldResults] = useState(false); + const [resultFilters, setResultFilters] = useState(''); + const [displayCount, setDisplayCount] = useState(5); + + // when the search transitions from !isComplete -> isComplete, + // fetch the results from the server + useEffect(() => { + const get = async () => { + try { + setLoading(true); + + // the results may not be ready yet. this is very rare, but + // if it happens the search will complete with no results. + await sleep(500); + + const responses = await getResponses({ id }); + setResults(responses); + setLoading(false); + } catch (error) { + setError(error); + setLoading(false); + } + } + + if (isComplete) { + get(); + } + }, [id, isComplete]) + + // apply sorting and filters. this can take a while for larger result + // sets, so memoize it. + const sortedAndFilteredResults = useMemo(() => { + const sortOptions = { + uploadSpeed: { field: 'uploadSpeed', order: 'desc' }, + queueLength: { field: 'queueLength', order: 'asc' } + } + + const { field, order } = sortOptions[resultSort]; + + const filters = parseFiltersFromString(resultFilters); + + return results + .filter(r => !hiddenResults.includes(r.username)) + .map(r => { + if (hideLocked) { + return { ...r, lockedFileCount: 0, lockedFiles: [] } + } + return r; + }) + .map(response => filterResponse({ response, filters })) + .filter(r => r.fileCount + r.lockedFileCount > 0) + .filter(r => !(hideNoFreeSlots && r.freeUploadSlots === 0)) + .sort((a, b) => { + if (order === 'asc') { + return a[field] - b[field]; + } + + return b[field] - a[field]; + }); + + }, [results, hideLocked, hideNoFreeSlots, resultFilters, resultSort, hiddenResults]) + + // when a user uses the action buttons, we will *probably* re-use this component, + // but with a new search ID. clear everything to prepare for the transition + const reset = () => { + setLoading(false); + setError(undefined); + setResults([]); + setHiddenResults([]); + setDisplayCount(5); + } + + const create = async ({ search, navigate }) => { + reset(); + onCreate({ search, navigate }) + } + + const remove = async () => { + reset(); + onRemove(search); + } + + const filteredCount = results?.length - sortedAndFilteredResults.length; + const remainingCount = sortedAndFilteredResults.length - displayCount; + const loaded = (!removing && !creating && !loading && results && results.length > 0) + + if (error) { + return (<ErrorSegment caption={error?.message ?? error}/>) + } + + return ( + <> + <SearchDetailHeader + loading={loading} + loaded={loaded} + removing={removing} + stopping={stopping} + creating={creating} + search={search} + onCreate={create} + onStop={onStop} + onRemove={remove} + /> + <Switch + searching={!isComplete && + <LoaderSegment> + {state === 'InProgress' ? `Found ${fileCount} files ${lockedFileCount > 0 ? `(plus ${lockedFileCount} locked) ` : ''}from ${responseCount} users` + : 'Loading results...'} + </LoaderSegment> + } + loading={loading && <LoaderSegment/>} + > + {loaded && + <Segment className='search-options' raised> + <Dropdown + button + className='search-options-sort icon' + floating + labeled + icon='sort' + options={sortDropdownOptions} + onChange={(e, { value }) => setResultSort(value)} + text={sortDropdownOptions.find(o => o.value === resultSort).text} + /> + <div className='search-option-toggles'> + <Checkbox + className='search-options-hide-locked' + toggle + onChange={() => setHideLocked(!hideLocked)} + checked={hideLocked} + label='Hide Locked Results' + /> + <Checkbox + className='search-options-hide-no-slots' + toggle + onChange={() => setHideNoFreeSlots(!hideNoFreeSlots)} + checked={hideNoFreeSlots} + label='Hide Results with No Free Slots' + /> + <Checkbox + className='search-options-fold-results' + toggle + onChange={() => setFoldResults(!foldResults)} + checked={foldResults} + label='Fold Results' + /> + </div> + <Input + className='search-filter' + placeholder='lackluster container -bothersome iscbr|isvbr islossless|islossy minbitrate:320 minfilesize:10 minfilesinfolder:8 minlength:5000' + label={{ icon: 'filter', content: 'Filter' }} + value={resultFilters} + onChange={(e, data) => setResultFilters(data.value)} + action={!!resultFilters && { icon: 'x', color: 'red', onClick: () => setResultFilters('')}} + /> + </Segment> + } + {loaded && sortedAndFilteredResults.slice(0, displayCount).map((r, i) => + <Response + key={i} + response={r} + onHide={() => setHiddenResults([...hiddenResults, r.username])} + isInitiallyFolded={foldResults} + /> + )} + {loaded && (remainingCount > 0 ? + <Button className='showmore-button' size='large' fluid primary + onClick={() => setDisplayCount(displayCount + 5)}> + Show {remainingCount > 5 ? 5 : remainingCount} More Results {`(${remainingCount} remaining, ${filteredCount} hidden by filter(s))`} + </Button> + : filteredCount > 0 ? + <Button className='showmore-button' size='large' fluid disabled>{`All results shown. ${filteredCount} results hidden by filter(s)`}</Button> : '')} + </Switch> + </> + ) +} + +export default SearchDetail;
\ No newline at end of file diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.js b/src/web/src/components/Search/Detail/SearchDetailHeader.js new file mode 100644 index 00000000..d31f8a49 --- /dev/null +++ b/src/web/src/components/Search/Detail/SearchDetailHeader.js @@ -0,0 +1,72 @@ +import React from 'react'; +import { useMediaQuery } from 'react-responsive'; + +import { + Segment, + Button, + Header, + Icon, +} from 'semantic-ui-react'; +import SearchStatusIcon from '../SearchStatusIcon'; + +const SearchDetailHeader = ({ search, loading, loaded, creating, removing, stopping, onCreate, onStop, onRemove }) => { + const isSmallScreen = useMediaQuery({ query: '(max-width: 899px)' }); + const isTinyScreen = useMediaQuery({ query: '(max-width: 684px)'}); + + const { searchText, isComplete, state } = search; + const working = loading || creating || removing || stopping; + + const stopOrRemove = () => { + if (isComplete) { + onRemove(search); + } else { + onStop(search); + } + } + + const RefreshButton = () => loaded && + <Button + disabled={working} + icon={isSmallScreen && !isTinyScreen} + onClick={() => onCreate({ search: searchText, navigate: true })} + loading={creating} + > + <Icon name='refresh'/>{(!isSmallScreen || isTinyScreen) && 'Search Again'} + </Button> + + const StopOrDeleteButton = () => + <Button + negative + disabled={working} + onClick={stopOrRemove} + loading={removing || stopping} + floated={isTinyScreen ? 'right' : undefined} + icon={isSmallScreen && !isTinyScreen} + > + <Icon name={isComplete ? 'trash alternate' : 'stop circle'}/> + {(!isSmallScreen || isTinyScreen) && ((loaded && isComplete) ? 'Delete' : 'Stop')} + </Button> + + // if the screen is full width, display the header and action buttons in the same segment, with full + // button text. if the screen is between 684 and 899 pixels, display the buttons with no text. + // if the screen is less than 684 pixels, display the action buttons in a new segment, with full text. + return ( + <> + <Segment className='search-segment' raised> + <Header className='search-detail-header'> + <SearchStatusIcon state={state}/>{searchText} + </Header> + {!isTinyScreen && <div className='search-detail-action-button'> + <RefreshButton/> + <StopOrDeleteButton/> + </div>} + </Segment> + {isTinyScreen && <Segment> + <RefreshButton/> + <StopOrDeleteButton/> + </Segment>} + </> + ) +}; + +export default SearchDetailHeader;
\ No newline at end of file diff --git a/src/web/src/components/Search/List/SearchActionIcon.js b/src/web/src/components/Search/List/SearchActionIcon.js new file mode 100644 index 00000000..98455241 --- /dev/null +++ b/src/web/src/components/Search/List/SearchActionIcon.js @@ -0,0 +1,27 @@ +import React from 'react'; + +import { Icon } from 'semantic-ui-react'; + +const SearchActionIcon = ({ search, loading, onRemove, onStop,...props }) => { + if (loading) { + return (<Icon name='spinner' loading {...props}/>) + } + + if (search.state.includes('Completed')) { + return (<Icon + name="trash alternate" + color='red' + onClick={() => onRemove()} + style={{ cursor: 'pointer' }} + />) + } + + return (<Icon + name="stop circle" + color="red" + onClick={() => onStop()} + style={{ cursor: 'pointer' }} + />) +}; + +export default SearchActionIcon;
\ No newline at end of file diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js new file mode 100644 index 00000000..c65c949d --- /dev/null +++ b/src/web/src/components/Search/List/SearchList.js @@ -0,0 +1,76 @@ +import React, { useMemo } from 'react'; + +import SearchListRow from './SearchListRow'; +import ErrorSegment from '../../Shared/ErrorSegment'; +import Switch from '../../Shared/Switch'; + +import { + Card, + Table, + Icon, + Loader, + Segment, + Header, + List +} from 'semantic-ui-react'; + +const SearchList = ({ connecting = false, error = undefined, searches = {}, onRemove = () => {}, onStop = () => {} }) => { + const searchCount = useMemo(() => { + return Object.values(searches).length + }, [searches]) + + return ( + <Card className='search-list-card' raised> + <Card.Content> + <div style={{marginTop: -20 }}> + <Switch + connecting={connecting && <Loader active inline='centered' size='small'/>} + error={error && <ErrorSegment caption={error} />} + > + <Header size='small' className='filelist-header'> + <div> + <Icon size='large' name='search'/> + Searches + </div> + </Header> + <List> + <List.Item> + <Switch + noSearches={!searchCount && + <Segment basic style={{opacity: .5}} textAlign='center'>No searches to display</Segment> + } + > + <Table size='large'> + <Table.Header> + <Table.Row> + <Table.HeaderCell className="search-list-action"><Icon name="info circle"/></Table.HeaderCell> + <Table.HeaderCell className="search-list-phrase">Search</Table.HeaderCell> + <Table.HeaderCell className="search-list-files">Files</Table.HeaderCell> + <Table.HeaderCell className="search-list-locked">Locked</Table.HeaderCell> + <Table.HeaderCell className="search-list-responses">Responses</Table.HeaderCell> + <Table.HeaderCell className="search-list-started">Ended</Table.HeaderCell> + <Table.HeaderCell className="search-list-action"></Table.HeaderCell> + </Table.Row> + </Table.Header> + <Table.Body> + {Object.values(searches) + .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) + .map((search, index) => <SearchListRow + search={search} + key={index} + onRemove={onRemove} + onStop={onStop} + />)} + </Table.Body> + </Table> + </Switch> + </List.Item> + </List> + </Switch> + </div> + </Card.Content> + </Card> + ) +}; + +export default SearchList;
\ No newline at end of file diff --git a/src/web/src/components/Search/List/SearchListRow.js b/src/web/src/components/Search/List/SearchListRow.js new file mode 100644 index 00000000..c2552892 --- /dev/null +++ b/src/web/src/components/Search/List/SearchListRow.js @@ -0,0 +1,60 @@ +import React, { useState } from 'react'; + +import { + Link, + useRouteMatch, +} from "react-router-dom"; + +import { + Table, + Icon, +} from 'semantic-ui-react'; + +import SearchStatusIcon from '../SearchStatusIcon'; +import SearchActionIcon from './SearchActionIcon'; + +const SearchListRow = ({ search, onRemove, onStop }) => { + const [working, setWorking] = useState(false); + const match = useRouteMatch(); + + const invoke = async (func) => { + setWorking(true); + + try { + await func(); + } catch (error) { + console.error(error); + } finally { + setWorking(false); + } + } + + return ( + <Table.Row + disabled={working} + style={{ cursor: working ? 'wait' : undefined }} + > + <Table.Cell> + <SearchStatusIcon + state={search.state} + /> + </Table.Cell> + <Table.Cell><Link to={`${match.url}/${search.id}`}>{search.searchText}</Link></Table.Cell> + <Table.Cell>{search.fileCount}</Table.Cell> + <Table.Cell><Icon name="lock" color="yellow" size="small"/>{search.lockedFileCount}</Table.Cell> + <Table.Cell>{search.responseCount}</Table.Cell> + <Table.Cell>{search.endedAt ? new Date(search.endedAt).toLocaleTimeString() : '-'}</Table.Cell> + <Table.Cell> + <SearchActionIcon + search={search} + loading={working} + onRemove={() => invoke(() => onRemove(search))} + onStop={() => invoke(() => onStop(search))} + style={{ cursor: 'pointer' }} + /> + </Table.Cell> + </Table.Row> + ) +} + +export default SearchListRow;
\ No newline at end of file diff --git a/src/web/src/components/Search/Response.js b/src/web/src/components/Search/Response.js index 8d134047..7ffb70d4 100644 --- a/src/web/src/components/Search/Response.js +++ b/src/web/src/components/Search/Response.js @@ -86,6 +86,13 @@ class Response extends Component { /> <Icon name='circle' color={free ? 'green' : 'yellow'}/> {response.username} + <Icon + className='close-button' + name='close' + color='red' + link + onClick={() => this.props.onHide()} + /> </Card.Header> <Card.Meta className='result-meta'> <span>Upload Speed: {formatBytes(response.uploadSpeed)}/s, Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength}</span> diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css index 750c5c2d..42912ed5 100644 --- a/src/web/src/components/Search/Search.css +++ b/src/web/src/components/Search/Search.css @@ -15,6 +15,12 @@ height: 78px !important; } +.search-card { + width: 1200px !important; + margin-left: auto !important; + margin-right: auto !important; +} + @media only screen and (min-width: 991px) { .search-options-hide-no-slots, .search-options-hide-locked, .search-options-fold-results { margin-left: 1rem; @@ -25,7 +31,7 @@ } } -@media only screen and (max-width: 685px) { +@media only screen and (max-width: 684px) { .search-options-sort { width: 100%; } @@ -63,4 +69,42 @@ .search-filter { width: 100%; margin-top: 1rem; +} + +.search-list-icon { + width: 40px !important; +} + +.search-list-phrase { + word-wrap: break-word !important; +} + +.search-list-responses { + width: 30px !important; +} + +.search-list-files { + width: 80px !important; +} + +.search-list-locked { + width: 100px !important; +} + +.search-list-started { + width: 120px !important; +} + +.search-list-action { + width: 5px !important; +} + +.search-detail-header { + font-weight: normal !important; + margin-top: 12px !important; +} + +.search-detail-action-button { + float: right; + margin-top: -48px !important; }
\ No newline at end of file diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js deleted file mode 100644 index 3dbcc939..00000000 --- a/src/web/src/components/Search/Search.js +++ /dev/null @@ -1,306 +0,0 @@ -import { v4 as uuidv4 } from 'uuid'; -import React, { Component } from 'react'; -import * as search from '../../lib/search'; - -import './Search.css'; - -import Response from './Response'; -import PlaceholderSegment from '../Shared/PlaceholderSegment'; - -import { - Segment, - Input, - Loader, - Button, - Dropdown, - Checkbox -} from 'semantic-ui-react'; - -const initialState = { - searchPhrase: '', - searchId: undefined, - searchState: 'idle', - searchStatus: { - responseCount: 0, - fileCount: 0 - }, - results: [], - interval: undefined, - displayCount: 5, - resultSort: 'uploadSpeed', - hideNoFreeSlots: true, - hiddenResults: [], - hideLocked: true, - fetching: false, - resultFilters: '', - foldResults: false, -}; - -const sortOptions = { - uploadSpeed: { field: 'uploadSpeed', order: 'desc' }, - queueLength: { field: 'queueLength', order: 'asc' } -} - -const sortDropdownOptions = [ - { key: 'uploadSpeed', text: 'Upload Speed (Fastest to Slowest)', value: 'uploadSpeed' }, - { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' } -]; - -class Search extends Component { - state = initialState; - - search = () => { - const searchPhrase = this.inputtext.inputRef.current.value; - const searchId = uuidv4(); - - this.setState({ searchPhrase, searchId, searchState: 'pending' }, async () => { - this.saveState(); - search.search({ id: searchId, searchText: searchPhrase }); - }); - } - - clear = () => { - this.setState(initialState, () => { - this.saveState(); - this.setSearchText(); - this.inputtext.focus(); - }); - } - - keyUp = (event) => event.key === 'Escape' ? this.clear() : ''; - - onSearchPhraseChange = (event, data) => { - this.setState({ searchPhrase: data.value }); - } - - onResultFilterChange = (event, data) => { - this.setState({ resultFilters: data.value }, () => this.saveState()); - } - - clearResultFilter = () => { - this.setState({ resultFilters: '' }, () => this.saveState()); - } - - saveState = () => { - try { - localStorage.setItem('soulseek-example-search-state', JSON.stringify({ ...this.state, results: [] })); - } catch(error) { - console.log(error); - } - } - - loadState = () => { - return new Promise((resolve) => - this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState, resolve)); - } - - componentDidMount = async () => { - await this.loadState(); - this.fetchResults(); - this.setState({ - interval: window.setInterval(this.fetchStatus, 500) - }, () => this.setSearchText()); - - document.addEventListener("keyup", this.keyUp, false); - } - - setSearchText = () => { - this.inputtext.inputRef.current.value = this.state.searchPhrase; - this.inputtext.inputRef.current.disabled = this.state.searchState !== 'idle'; - } - - componentWillUnmount = () => { - clearInterval(this.state.interval); - this.setState({ interval: undefined }); - document.removeEventListener("keyup", this.keyUp, false); - } - - fetchResults = async () => { - const { searchId } = this.state; - - if (!!searchId) { - this.setState({ fetching: true }, async () => { - try { - const responses = await search.getResponses({ id: searchId }); - - this.setState({ - results: responses, - fetching: false - }, this.saveState); - } catch (error) { - console.log(error); - this.clear(); - } - }); - } - } - - fetchStatus = async () => { - const { searchState, searchId } = this.state; - - if (searchState === 'pending') { - this.setState({ fetching: true }, async () => { - const response = await search.getStatus({ id: searchId }); - - if (response.isComplete) { - this.setState({ - searchState: 'complete' - }, this.fetchResults); - } else { - this.setState({ - searchStatus: response, - fetching: false - }, this.saveState); - } - }); - } - } - - showMore = () => { - this.setState({ displayCount: this.state.displayCount + 5 }, () => this.saveState()); - } - - sortAndFilterResults = () => { - const { results = [], hideNoFreeSlots, resultSort, resultFilters = '', hideLocked, hiddenResults = [] } = this.state; - const { field, order } = sortOptions[resultSort]; - - const filters = search.parseFiltersFromString(resultFilters); - - return results - .filter(r => !hiddenResults.includes(r.username)) - .map(r => { - if (hideLocked) { - return { ...r, lockedFileCount: 0, lockedFiles: [] } - } - return r; - }) - .map(response => search.filterResponse({ response, filters })) - .filter(r => r.fileCount + r.lockedFileCount > 0) - .filter(r => !(hideNoFreeSlots && r.freeUploadSlots === 0)) - .sort((a, b) => { - if (order === 'asc') { - return a[field] - b[field]; - } - - return b[field] - a[field]; - }); - } - - hideResult = (result) => { - this.setState({ hiddenResults: [...this.state.hiddenResults, result.username]}, () => { - if (this.state.hiddenResults.length === this.state.results.length) { - this.clear(); - } else { - this.saveState(); - } - }); - } - - render = () => { - let { searchState, searchStatus, results = [], displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults = [], fetching, resultFilters, foldResults } = this.state; - let pending = fetching || searchState === 'pending'; - - const sortedAndFilteredResults = this.sortAndFilterResults(); - - const remainingCount = sortedAndFilteredResults.length - displayCount; - const showMoreCount = remainingCount >= 5 ? 5 : remainingCount; - const hiddenCount = results.length - hiddenResults.length - sortedAndFilteredResults.length; - - return ( - <div className='search-container'> - <Segment className='search-segment' raised> - <Input - input={<input placeholder="Search phrase" type="search" data-lpignore="true"></input>} - size='big' - ref={input => this.inputtext = input} - loading={pending} - disabled={pending} - className='search-input' - placeholder="Search phrase" - action={!pending && (searchState === 'idle' ? { icon: 'search', onClick: this.search } : { icon: 'x', color: 'red', onClick: this.clear })} - onKeyUp={(e) => e.key === 'Enter' ? this.search() : ''} - /> - </Segment> - {pending ? - <Loader - className='search-loader' - active - inline='centered' - size='big' - > - {searchState === 'pending' ? <span>Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users</span> - : 'Loading results...'} - </Loader> - : - <div> - {(results && results.length > 0) ? - <Segment className='search-options' raised> - <Dropdown - button - className='search-options-sort icon' - floating - labeled - icon='sort' - options={sortDropdownOptions} - onChange={(e, { value }) => this.setState({ resultSort: value }, () => this.saveState())} - text={sortDropdownOptions.find(o => o.value === resultSort).text} - /> - <div className='search-option-toggles'> - <Checkbox - className='search-options-hide-locked' - toggle - onChange={() => this.setState({ hideLocked: !hideLocked }, () => this.saveState())} - checked={hideLocked} - label='Hide Locked Results' - /> - <Checkbox - className='search-options-hide-no-slots' - toggle - onChange={() => this.setState({ hideNoFreeSlots: !hideNoFreeSlots }, () => this.saveState())} - checked={hideNoFreeSlots} - label='Hide Results with No Free Slots' - /> - <Checkbox - className='search-options-fold-results' - toggle - onChange={() => this.setState({ foldResults: !foldResults }, () => this.saveState())} - checked={foldResults} - label='Fold Results' - /> - </div> - <Input - className='search-filter' - placeholder='lackluster container -bothersome iscbr|isvbr islossless|islossy minbitrate:320 minfilesize:10 minfilesinfolder:8 minlength:5000' - label={{ icon: 'filter', content: 'Filter' }} - value={resultFilters} - onChange={this.onResultFilterChange} - action={!!resultFilters && { icon: 'x', color: 'red', onClick: this.clearResultFilter }} - /> - </Segment> : <PlaceholderSegment icon='search'/> - } - {sortedAndFilteredResults.slice(0, displayCount).map((r, i) => - <Response - key={i} - response={r} - onDownload={this.props.onDownload} - onHide={() => this.hideResult(r)} - isInitiallyFolded={foldResults} - /> - )} - {remainingCount > 0 ? - <Button - className='showmore-button' - size='large' - fluid - primary - onClick={() => this.showMore()}> - Show {showMoreCount} More Results {remainingCount > 5 ? `(${remainingCount} remaining, ${hiddenCount} hidden by filter(s))` : ''} - </Button> - : ''} - </div>} - </div> - ) - } -} - -export default Search;
\ No newline at end of file diff --git a/src/web/src/components/Search/SearchStatusIcon.js b/src/web/src/components/Search/SearchStatusIcon.js new file mode 100644 index 00000000..9ade1daf --- /dev/null +++ b/src/web/src/components/Search/SearchStatusIcon.js @@ -0,0 +1,35 @@ +import React from 'react'; + +import { Icon, Popup } from 'semantic-ui-react'; + +// as of 4.5.2, states are: +// transient: +// None, Requested, InProgress +// terminal: +// good: Completed, [TimedOut | ResponseLimitReached | FileLimitReached] +// bad: Completed, [Errored | Cancelled] + +const getIcon = ({ state, ...props }) => { + switch (state) { + case 'None': + case 'Requested': + return <Icon name='time' {...props}/> + case 'InProgress': + return <Icon name='circle notch' loading color='green' {...props}/> + case 'Completed, TimedOut': + case 'Completed, ResponseLimitReached': + case 'Completed, FileLimitReached': + return <Icon name='check' color='green' {...props}/> + case 'Completed, Cancelled': + return <Icon name='stop circle' color='green' {...props}/> + case 'Completed, Errored': + return <Icon name='x' color='red' {...props}/> + default: + return <Icon name='question circle' color='yellow' {...props}/> + } +} + +const SearchStatusIcon = ({ state, ...props }) => + <Popup content={state} trigger={getIcon({ state, ...props })}/> + +export default SearchStatusIcon;
\ No newline at end of file diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js new file mode 100644 index 00000000..b21f62b6 --- /dev/null +++ b/src/web/src/components/Search/Searches.js @@ -0,0 +1,209 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { v4 as uuidv4 } from 'uuid'; +import { useParams, useHistory, useRouteMatch } from 'react-router-dom'; + +import * as lib from '../../lib/searches'; +import { createSearchHubConnection } from '../../lib/hubFactory'; + +import LoaderSegment from '../Shared/LoaderSegment'; +import SearchList from './List/SearchList'; + +import './Search.css'; + +import { + Input, + Segment, + Button, +} from 'semantic-ui-react'; + +import SearchDetail from './Detail/SearchDetail'; +import ErrorSegment from '../Shared/ErrorSegment'; + +const Searches = () => { + const [connecting, setConnecting] = useState(true); + const [error, setError] = useState(undefined); + const [searches, setSearches] = useState({}); + + const [removing, setRemoving] = useState(false); + const [stopping, setStopping] = useState(false); + const [creating, setCreating] = useState(false); + + const inputRef = useRef(); + + const { id: searchId } = useParams(); + const history = useHistory(); + const match = useRouteMatch(); + + const onConnecting = () => { setConnecting(true); } + const onConnected = () => { setConnecting(false); setError(undefined); } + const onConnectionError = (error) => { setConnecting(false); setError(error); } + + const onUpdate = (update) => { + onConnected(); + setSearches(update); + } + + useEffect(() => { + onConnecting(); + + const searchHub = createSearchHubConnection(); + + searchHub.on('list', searches => { + onUpdate(searches.reduce((acc, search) => { + acc[search.id] = search; + return acc; + }, {})); + onConnected(); + }) + + searchHub.on('update', search => { + onUpdate(old => ({ ...old, [search.id]: search })); + }); + + searchHub.on('delete', search => { + onUpdate(old => { + delete old[search.id]; + return { ...old } + }); + }); + + searchHub.on('create', () => {}); + + searchHub.onreconnecting((error) => onConnectionError(error?.message ?? 'Disconnected')); + searchHub.onreconnected(() => onConnected()); + searchHub.onclose((error) => onConnectionError(error?.message ?? 'Disconnected')); + + const connect = async () => { + try { + onConnecting(); + await searchHub.start(); + } catch (error) { + onConnectionError(error?.message ?? 'Failed to connect') + } + } + + connect(); + + return () => { + searchHub.stop(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // create a new search, and optionally navigate to it to display the details + // we do this if the user clicks the search icon, or repeats an existing search + const create = async ({ search, navigate = false } = {}) => { + const searchText = search || inputRef.current.inputRef.current.value; + const id = uuidv4(); + + try { + setCreating(true) + await lib.create({ id, searchText }) + + try { + inputRef.current.inputRef.current.value = ''; + } catch { + // we are probably repeating an existing search; the input isn't mounted. no-op. + } + + setCreating(false) + + if (navigate) { + history.push(`${match.url.replace(`/${searchId}`, '')}/${id}`); + } + } catch (error) { + console.error(error) + setCreating(false) + } + } + + // delete a search + const remove = async (search) => { + try { + setRemoving(true); + + await lib.remove({ id: search.id }) + setSearches(old => { + delete old[search.id]; + return { ...old } + }); + + setRemoving(false); + } catch (err) { + console.error(err); + setRemoving(false); + } + }; + + // stop an in-progress search + const stop = async (search) => { + try { + setStopping(true); + await lib.stop({ id: search.id }) + setStopping(false); + } catch (error) { + console.error(error); + setStopping(false); + } + } + + if (connecting) { + return <LoaderSegment/> + } + + if (error) { + return <ErrorSegment caption={error?.message ?? error}/>; + } + + // if searchId is not null, there's an id in the route. + // display the details for the search, if there is one + if (searchId) { + if (searches[searchId]) { + return ( + <SearchDetail + search={searches[searchId]} + creating={creating} + stopping={stopping} + removing={removing} + onCreate={create} + onStop={stop} + onRemove={remove} + /> + ); + } + + // if the searchId doesn't match a search we know about, chop + // the id off of the url and force navigation back to the list + history.replace(match.url.replace(`/${searchId}`, '')); + } + + return ( + <> + <Segment className='search-segment' raised> + <Input + input={<input placeholder="Search phrase" type="search" data-lpignore="true"></input>} + size='big' + ref={inputRef} + loading={creating} + disabled={creating} + className='search-input' + placeholder="Search phrase" + action={<> + <Button icon='plus' onClick={create}/> + <Button icon='search' onClick={() => create({ navigate: true })}/> + </>} + onKeyUp={(e) => e.key === 'Enter' ? create() : ''} + /> + </Segment> + <SearchList + connecting={connecting} + error={error} + searches={searches} + onRemove={remove} + onStop={stop} + /> + </> + ) +}; + +export default Searches;
\ No newline at end of file diff --git a/src/web/src/components/Shared/LoaderSegment.js b/src/web/src/components/Shared/LoaderSegment.js new file mode 100644 index 00000000..cc3d598c --- /dev/null +++ b/src/web/src/components/Shared/LoaderSegment.js @@ -0,0 +1,11 @@ +import React from 'react'; + +import { Segment, Loader } from 'semantic-ui-react'; + +const LoaderSegment = ({ size = 'big', children, ...props }) => ( + <Segment className='loader-segment' placeholder basic> + <Loader active size={size} {...props}>{children}</Loader> + </Segment> +); + +export default LoaderSegment;
\ No newline at end of file diff --git a/src/web/src/components/Shared/Switch.js b/src/web/src/components/Shared/Switch.js new file mode 100644 index 00000000..9b8e4beb --- /dev/null +++ b/src/web/src/components/Shared/Switch.js @@ -0,0 +1,11 @@ +const Switch = ({ children, ...rest }) => { + const values = Object.values(rest); + + for (let i = 0; i < values.length; i++) { + if (values[i]) return values[i]; + } + + return children; +} + +export default Switch;
\ No newline at end of file diff --git a/src/web/src/config.js b/src/web/src/config.js index 8f0ac901..b9dedf38 100644 --- a/src/web/src/config.js +++ b/src/web/src/config.js @@ -17,5 +17,5 @@ export { tokenPassthroughValue, activeChatKey, activeRoomKey, - activeUserInfoKey + activeUserInfoKey, }; diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js index 246e9d03..8b41226e 100644 --- a/src/web/src/lib/hubFactory.js +++ b/src/web/src/lib/hubFactory.js @@ -13,11 +13,13 @@ export const createHubConnection = ({ url }) => withCredentials: true, accessTokenFactory: session.isPassthroughEnabled() ? undefined : session.getToken }) - .withAutomaticReconnect([0, 500, 1000, 3000, 5000, 5000, 5000, 5000, 5000]) + .withAutomaticReconnect([0, 100, 250, 500, 1000, 2000, 3000, 5000, 5000, 5000, 5000, 5000]) .withHubProtocol(new JsonHubProtocol()) .configureLogging(LogLevel.Warning) .build(); export const createApplicationHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/application` }); -export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` });
\ No newline at end of file +export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` }); + +export const createSearchHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/search`}) diff --git a/src/web/src/lib/search.js b/src/web/src/lib/searches.js index 306c7041..9561ab40 100644 --- a/src/web/src/lib/search.js +++ b/src/web/src/lib/searches.js @@ -1,6 +1,18 @@ import api from './api'; -export const search = ({ id, searchText }) => { +export const getAll = async () => { + return (await api.get('/searches')).data; +} + +export const stop = ({ id }) => { + return api.put(`/searches/${encodeURIComponent(id)}`) +} + +export const remove = ({ id }) => { + return api.delete(`/searches/${encodeURIComponent(id)}`) +} + +export const create = ({ id, searchText }) => { return api.post(`/searches`, { id, searchText }); }; diff --git a/src/web/src/lib/search.test.js b/src/web/src/lib/searches.test.js index 68afe91c..737843ed 100644 --- a/src/web/src/lib/search.test.js +++ b/src/web/src/lib/searches.test.js @@ -1,4 +1,4 @@ -import * as search from './search'; +import * as search from './searches'; describe('filterResponse', () => { it('removes VBR files if "iscbr" is specified', () => { diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js index 9721fbeb..1704a990 100644 --- a/src/web/src/lib/util.js +++ b/src/web/src/lib/util.js @@ -48,6 +48,10 @@ export const formatAttributes = ({ bitRate, isVariableBitRate, bitDepth, sampleR return bitRate ? `${bitRate} Kbps` : '' } +export const sleep = (milliseconds) => { + return new Promise(resolve => setTimeout(resolve, milliseconds)) +} + /* https://www.npmjs.com/package/js-file-download * * Copyright 2017 Kenneth Jiang |
