diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-04-05 16:49:23 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-04-05 16:49:23 -0500 |
| commit | 1a3e8c9d8a1857e1ac0c3fe92d5ab1408aa3d0df (patch) | |
| tree | 29726be4a5ecdb1aae6e4f296ad5af7152ea9ce2 | |
| parent | cacd8538fb46283c74a399e53ac2cb48ede3734b (diff) | |
| parent | eec6e0f098effcb9bfda297a441ca7ffd8d33934 (diff) | |
| download | slskd-1a3e8c9d8a1857e1ac0c3fe92d5ab1408aa3d0df.tar.gz | |
Merge branch 'master' into feature/add-profile-picture-support
| -rw-r--r-- | Dockerfile | 1 | ||||
| -rw-r--r-- | config/slskd.example.yml | 2 | ||||
| -rw-r--r-- | src/slskd/Application.cs | 6 | ||||
| -rw-r--r-- | src/slskd/Search/API/Controllers/SearchesController.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Search/SearchService.cs | 145 | ||||
| -rw-r--r-- | src/slskd/slskd.csproj | 2 | ||||
| -rw-r--r-- | src/web/package-lock.json | 7 | ||||
| -rw-r--r-- | src/web/src/components/Browse/Browse.jsx | 18 | ||||
| -rw-r--r-- | src/web/src/components/Rooms/Rooms.css | 6 | ||||
| -rw-r--r-- | src/web/src/components/Rooms/Rooms.jsx | 118 | ||||
| -rw-r--r-- | src/web/src/components/Search/SearchStatusIcon.jsx | 5 | ||||
| -rw-r--r-- | src/web/src/components/Users/Users.jsx | 5 |
12 files changed, 228 insertions, 90 deletions
@@ -40,6 +40,7 @@ ARG REVISION=0 ARG BUILD_DATE RUN apt-get update && apt-get install --no-install-recommends -y \ + jq \ wget \ tini \ && \ diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 26d54afd..69725415 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -158,7 +158,7 @@ # role: readonly # readonly, readwrite, administrator # cidr: 0.0.0.0/0,::/0 # retention: -# searches: 10080 # 7 days, in minutes +# search: 10080 # 7 days, in minutes # transfers: # upload: # succeeded: 1440 # 1 day, in minutes diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 6a539fa9..acfecdbf 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1258,18 +1258,18 @@ namespace slskd /// <param name="token">The unique token for the request, supplied by the requesting user.</param> /// <param name="directory">The requested directory.</param> /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> - private async Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + private async Task<IEnumerable<Soulseek.Directory>> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); - return new Soulseek.Directory(directory); + return [new Soulseek.Directory(directory)]; } try { var dir = await Shares.ListDirectoryAsync(directory); - return dir; + return [dir]; } catch (Exception ex) { diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 58e1fe37..1d00b482 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -82,6 +82,7 @@ namespace slskd.Search.API try { search = await Searches.StartAsync(id, SearchQuery.FromText(request.SearchText), SearchScope.Network, request.ToSearchOptions()); + return Ok(search); } catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException) { @@ -98,8 +99,6 @@ namespace slskd.Search.API Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); return StatusCode(500, ex.Message); } - - return Ok(search); } /// <summary> diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index b4864918..ac99ee2e 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -239,41 +239,54 @@ namespace slskd.Search StartedAt = DateTime.UtcNow, }; - using var context = ContextFactory.CreateDbContext(); - context.Add(search); - context.SaveChanges(); + bool searchCreated = false; + bool searchBroadcasted = false; - await SearchHub.BroadcastCreateAsync(search); + try + { + using var context = ContextFactory.CreateDbContext(); + context.Add(search); + context.SaveChanges(); - // initialize the list of responses that we'll use to accumulate them - // populated by the responseHandler we pass to SearchAsync - List<SearchResponse> responses = new(); + searchCreated = true; - options ??= new SearchOptions(); - options = options.WithActions( - stateChanged: (args) => - { - search = search.WithSoulseekSearch(args.Search); - SearchHub.BroadcastUpdateAsync(search); - Update(search); - }, - responseReceived: (args) => rateLimiter.Invoke(() => - { - // note: this is rate limited, but has the potential to update the database every 250ms (or whatever the - // interval is set to) for the duration of the search. any issues with disk i/o or performance while searches - // are running should investigate this as a cause - search.ResponseCount = args.Search.ResponseCount; - search.FileCount = args.Search.FileCount; - search.LockedFileCount = args.Search.LockedFileCount; - - // note that we're not actually doing anything with the response here, that's happening in the - // response handler. we're only updating counts here. - SearchHub.BroadcastUpdateAsync(search); - Update(search); - })); + await SearchHub.BroadcastCreateAsync(search); + + searchBroadcasted = true; + + // initialize the list of responses that we'll use to accumulate them + // populated by the responseHandler we pass to SearchAsync + List<SearchResponse> responses = new(); + + options ??= new SearchOptions(); + options = options.WithActions( + stateChanged: (args) => + { + // this logic is executed by Soulseek.NET upon each transition of the searcn, including the final + // transition to Completed. if for some reason something goes wrong, we won't see the final Completed + // transition, we should instead see the task below throw, in which case it will become + // faulted and we'll set the Completed flag manually in the ContinueWith() block + search = search.WithSoulseekSearch(args.Search); + SearchHub.BroadcastUpdateAsync(search); + Update(search); + + Log.Debug("Search for '{Query}' state changed: {State} (id: {Id})", query, search.State, id); + }, + responseReceived: (args) => rateLimiter.Invoke(() => + { + // note: this is rate limited, but has the potential to update the database every 250ms (or whatever the + // interval is set to) for the duration of the search. any issues with disk i/o or performance while searches + // are running should investigate this as a cause + search.ResponseCount = args.Search.ResponseCount; + search.FileCount = args.Search.FileCount; + search.LockedFileCount = args.Search.LockedFileCount; + + // note that we're not actually doing anything with the response here, that's happening in the + // response handler. we're only updating counts here. + SearchHub.BroadcastUpdateAsync(search); + Update(search); + })); - try - { // initiate the search. this can throw at invocation if there's a problem with // the client state (e.g. disconnected) or a problem with the search (e.g. no terms) var soulseekSearchTask = Client.SearchAsync( @@ -284,47 +297,56 @@ namespace slskd.Search options, cancellationToken: cancellationTokenSource.Token); - // seach looks ok so far; let the rest of the logic run asynchronously + // search looks ok so far; let the rest of the logic run asynchronously // on a background thread. this logic needs to clean up after itself and // update the search record to accurately reflect the final state _ = Task.Run(async () => { + var soulseekSearch = await soulseekSearchTask; + search = search.WithSoulseekSearch(soulseekSearch); + + Log.Debug("Search for '{Query}' ended normally (id: {Id})", query, id); + }, cancellationToken: cancellationTokenSource.Token) + .ContinueWith(async task => + { try { - var soulseekSearch = await soulseekSearchTask; - search = search.WithSoulseekSearch(soulseekSearch); + // the only way we should ever get to this point is if we encounter an error sending the search + // request to the server (timeout, cancelled) or hit some highly improbable error within Soulseek.NET, + // potentially OOM or something. in these cases the task will throw and we need to force the + // search record into Errored state. + if (task.IsFaulted) + { + Log.Error(task.Exception, "Failed to execute search for '{Query}' (id: {Id}): {Message}", query, id, task.Exception?.Message ?? "Task completed in Faulted state, but there is no Exception"); + search.State = SearchStates.Completed | SearchStates.Errored; + } + + search.EndedAt = DateTime.UtcNow; + search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); + + Update(search); + + // zero responses before broadcasting, as we don't want to blast this + // data out over the SignalR socket + await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); + + Log.Debug("Search for '{Query}' finalized (id: {Id}): {Search}", query, id, search with { Responses = [] }); } catch (Exception ex) { - Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message); - search.State = SearchStates.Completed | SearchStates.Errored; + // record may be left 'hanging' and will need to be cleaned up at the next boot; we tried to update but failed + Log.Error(ex, "Failed to finalize search for '{Query}' (id: {Id}): {Message}", query, id, ex.Message); + throw; } finally { rateLimiter.Dispose(); CancellationTokens.TryRemove(id, out _); - - try - { - search.EndedAt = DateTime.UtcNow; - search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r)); - - Update(search); - - // zero responses before broadcasting, as we don't want to blast this - // data out over the SignalR socket - await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); - } - catch (Exception ex) - { - // record may be left 'hanging' and will need to be cleaned up at the next boot - Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id); - } } }); + // broadcast and return the _newly created_ search; it will continue to be updated in the background await SearchHub.BroadcastUpdateAsync(search); - return search; } catch (Exception ex) @@ -333,11 +355,18 @@ namespace slskd.Search // the app isn't connected, and a few other straightforward issues that arise before even requesting the search Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message); - search.State = SearchStates.Completed | SearchStates.Errored; - search.EndedAt = search.StartedAt; - Update(search); + // selectively 'undo' whatever actions we were able to take successfully + if (searchCreated) + { + search.State = SearchStates.Completed | SearchStates.Errored; + search.EndedAt = search.StartedAt; + Update(search); - await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); + if (searchBroadcasted) + { + await SearchHub.BroadcastUpdateAsync(search with { Responses = [] }); + } + } throw; } diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 0a282645..0a5d0683 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -67,7 +67,7 @@ <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" /> <PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" /> - <PackageReference Include="Soulseek" Version="6.5.0" /> + <PackageReference Include="Soulseek" Version="7.0.1" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 912ea6e9..a61bca8f 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -18432,10 +18432,11 @@ "dev": true }, "node_modules/serialize-javascript": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.1.tgz", - "integrity": "sha512-owoXEFjWRllis8/M1Q+Cw5k8ZH40e3zhp/ovX+Xr/vi1qj6QesbyXXViFbpNvWvPNAD62SutwEXavefrLJWj7w==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { "randombytes": "^2.1.0" } diff --git a/src/web/src/components/Browse/Browse.jsx b/src/web/src/components/Browse/Browse.jsx index 75c8fb53..d5e16cb3 100644 --- a/src/web/src/components/Browse/Browse.jsx +++ b/src/web/src/components/Browse/Browse.jsx @@ -6,6 +6,7 @@ import Directory from './Directory'; import DirectoryTree from './DirectoryTree'; import * as lzString from 'lz-string'; import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; import { Card, Icon, Input, Loader, Segment } from 'semantic-ui-react'; const initialState = { @@ -42,6 +43,9 @@ class Browse extends Component { }, () => this.saveState(), ); + if (this.props.location.state?.user) { + this.setState({ username: this.props.location.state.user }, this.browse); + } document.addEventListener('keyup', this.keyUp, false); } @@ -150,11 +154,13 @@ class Browse extends Component { loadState = () => { this.setState( - JSON.parse( - lzString.decompress( - localStorage.getItem('soulseek-example-browse-state') || '', - ), - ) || initialState, + (!this.props.location.state?.user && + JSON.parse( + lzString.decompress( + localStorage.getItem('soulseek-example-browse-state') || '', + ), + )) || + initialState, ); }; @@ -351,4 +357,4 @@ class Browse extends Component { } } -export default Browse; +export default withRouter(Browse); diff --git a/src/web/src/components/Rooms/Rooms.css b/src/web/src/components/Rooms/Rooms.css index e001d6ea..62bd45e6 100644 --- a/src/web/src/components/Rooms/Rooms.css +++ b/src/web/src/components/Rooms/Rooms.css @@ -1,3 +1,9 @@ +.popup-menu { + overflow-y: auto; + position: fixed; + z-index: 1000; +} + .rooms { padding-left: 15px; padding-right: 15px; diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index 54e67d3c..0f2e4382 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -4,19 +4,28 @@ import PlaceholderSegment from '../Shared/PlaceholderSegment'; import RoomMenu from './RoomMenu'; import RoomUserList from './RoomUserList'; import React, { Component, createRef } from 'react'; +import { withRouter } from 'react-router-dom'; import { + Button, Card, Dimmer, Icon, Input, List, Loader, + Portal, Ref, Segment, } from 'semantic-ui-react'; const initialState = { active: '', + contextMenu: { + message: null, + open: false, + x: 0, + y: 0, + }, intervals: { messages: undefined, rooms: undefined, @@ -48,6 +57,7 @@ class Rooms extends Component { async () => { await this.fetchJoinedRooms(); this.selectRoom(this.state.active || this.getFirstRoom()); + document.addEventListener('click', this.handleCloseContextMenu); }, ); } @@ -59,6 +69,8 @@ class Rooms extends Component { clearInterval(roomsInterval); clearInterval(messagesInterval); + document.removeEventListener('click', this.handleCloseContextMenu); + this.setState({ intervals: initialState.intervals }); } @@ -173,6 +185,79 @@ class Rooms extends Component { this.messageRef.current.value = ''; }; + handleContextMenu = (clickEvent, message) => { + clickEvent.preventDefault(); + this.setState({ + contextMenu: { + message, + open: true, + x: clickEvent.pageX, + y: clickEvent.pageY, + }, + }); + }; + + handleCloseContextMenu = () => { + this.setState((previousState) => ({ + contextMenu: { + ...previousState.contextMenu, + open: false, + }, + })); + }; + + handleReply = () => { + this.messageRef.current.value = `[${this.state.contextMenu.message.username}] ${this.state.contextMenu.message.message} --> `; + this.focusInput(); + }; + + handleUserProfile = () => { + this.props.history.push('/users', { + user: this.state.contextMenu.message.username, + }); + }; + + handleBrowseShares = () => { + this.props.history.push('/browse', { + user: this.state.contextMenu.message.username, + }); + }; + + renderContextMenu() { + const { contextMenu } = this.state; + return ( + <Portal open={contextMenu.open}> + <div + className="ui vertical buttons popup-menu" + style={{ + left: contextMenu.x, + maxHeight: `calc(100vh - ${contextMenu.y}px)`, + top: contextMenu.y, + }} + > + <Button + className="ui compact button popup-option" + onClick={this.handleReply} + > + Reply + </Button> + <Button + className="ui compact button popup-option" + onClick={this.handleUserProfile} + > + User Profile + </Button> + <Button + className="ui compact button popup-option" + onClick={this.handleBrowseShares} + > + Browse Shares + </Button> + </div> + </Portal> + ); + } + render() { const { active = [], joined = [], loading, room } = this.state; @@ -235,20 +320,26 @@ class Rooms extends Component { <Ref innerRef={this.listRef}> <List> {room.messages.map((message) => ( - <List.Content - className={`room-message ${message.self ? 'room-message-self' : ''}`} + <div key={`${message.timestamp}+${message.message}`} + onContextMenu={(clickEvent) => + this.handleContextMenu(clickEvent, message) + } > - <span className="room-message-time"> - {this.formatTimestamp(message.timestamp)} - </span> - <span className="room-message-name"> - {message.username}:{' '} - </span> - <span className="room-message-message"> - {message.message} - </span> - </List.Content> + <List.Content + className={`room-message ${message.self ? 'room-message-self' : ''}`} + > + <span className="room-message-time"> + {this.formatTimestamp(message.timestamp)} + </span> + <span className="room-message-name"> + {message.username}:{' '} + </span> + <span className="room-message-message"> + {message.message} + </span> + </List.Content> + </div> ))} <List.Content id="room-history-scroll-anchor" /> </List> @@ -295,9 +386,10 @@ class Rooms extends Component { </Card.Content> </Card> )} + {this.renderContextMenu()} </div> ); } } -export default Rooms; +export default withRouter(Rooms); diff --git a/src/web/src/components/Search/SearchStatusIcon.jsx b/src/web/src/components/Search/SearchStatusIcon.jsx index 9658b626..0a3d4a5d 100644 --- a/src/web/src/components/Search/SearchStatusIcon.jsx +++ b/src/web/src/components/Search/SearchStatusIcon.jsx @@ -1,9 +1,9 @@ import React from 'react'; import { Icon, Popup } from 'semantic-ui-react'; -// as of 4.5.2, states are: +// as of 3/26/25 states are: // transient: -// None, Requested, InProgress +// None, Queued, Requested, InProgress // terminal: // good: Completed, [TimedOut | ResponseLimitReached | FileLimitReached] // bad: Completed, [Errored | Cancelled] @@ -11,6 +11,7 @@ import { Icon, Popup } from 'semantic-ui-react'; const getIcon = ({ state, ...props }) => { switch (state) { case 'None': + case 'Queued': case 'Requested': return ( <Icon diff --git a/src/web/src/components/Users/Users.jsx b/src/web/src/components/Users/Users.jsx index e7f279ea..55dc1047 100644 --- a/src/web/src/components/Users/Users.jsx +++ b/src/web/src/components/Users/Users.jsx @@ -4,9 +4,11 @@ import * as users from '../../lib/users'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; import User from './User'; import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; +import { useLocation } from 'react-router-dom'; import { Icon, Input, Item, Loader, Segment } from 'semantic-ui-react'; const Users = () => { + const location = useLocation(); const inputRef = useRef(); const [user, setUser] = useState(); const [usernameInput, setUsernameInput] = useState(); @@ -42,7 +44,8 @@ const Users = () => { useEffect(() => { document.addEventListener('keyup', keyUp, false); - const storedUsername = localStorage.getItem(activeUserInfoKey); + const storedUsername = + location.state?.user || localStorage.getItem(activeUserInfoKey); if (storedUsername !== undefined) { setSelectedUsername(storedUsername); |
