aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-05-29 21:27:24 -0500
committerGitHub <noreply@github.com>2021-05-29 21:27:24 -0500
commit92a594f9157311089fbe7b436cdb129a4f7f712d (patch)
tree460aa5bbad06a2134ddcd1c4f0a596f106982419 /src
parentc72d7088ce6d39193ae1a80f2808e34d07e6078f (diff)
parent4533681fbfc20e1e608f7ddf8ce4a105e281d481 (diff)
downloadslskd-92a594f9157311089fbe7b436cdb129a4f7f712d.tar.gz
Merge pull request #81 from slskd/persist-search
Persist search results to disk
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Core/Common/Domain/File.cs51
-rw-r--r--src/slskd/Core/Search/Controllers/SearchesController.cs (renamed from src/slskd/API/Controllers/SearchesController.cs)77
-rw-r--r--src/slskd/Core/Search/Domain/Response.cs51
-rw-r--r--src/slskd/Core/Search/Domain/Search.cs60
-rw-r--r--src/slskd/Core/Search/Extensions.cs94
-rw-r--r--src/slskd/Core/Search/ISearchTracker.cs52
-rw-r--r--src/slskd/Core/Search/Persistence/SearchDbContext.cs32
-rw-r--r--src/slskd/Core/Search/SearchResponseCache.cs6
-rw-r--r--src/slskd/Core/Search/SearchTracker.cs62
-rw-r--r--src/slskd/Core/Search/Services/ISearchService.cs66
-rw-r--r--src/slskd/Core/Search/Services/SearchService.cs205
-rw-r--r--src/slskd/Core/Service.cs10
-rw-r--r--src/slskd/Program.cs19
-rw-r--r--src/slskd/Startup.cs17
-rw-r--r--src/slskd/slskd.csproj4
-rw-r--r--src/web/src/components/Search/Search.js77
-rw-r--r--src/web/src/lib/search.js8
17 files changed, 700 insertions, 191 deletions
diff --git a/src/slskd/Core/Common/Domain/File.cs b/src/slskd/Core/Common/Domain/File.cs
new file mode 100644
index 00000000..079ec0f0
--- /dev/null
+++ b/src/slskd/Core/Common/Domain/File.cs
@@ -0,0 +1,51 @@
+// <copyright file="File.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 SoulseekFile = Soulseek.File;
+
+ public class File
+ {
+ public int? BitDepth { get; init; }
+ public int? BitRate { get; init; }
+ public int Code { get; init; }
+ public string Extension { get; init; }
+ public string Filename { get; init; }
+ public bool? IsVariableBitRate { get; init; }
+ public int? Length { get; init; }
+ public int? SampleRate { get; init; }
+ public long Size { get; init; }
+ public bool IsLocked { get; init; }
+
+ public static File FromSoulseekFile(SoulseekFile file)
+ {
+ return new File()
+ {
+ BitDepth = file.BitDepth,
+ BitRate = file.BitRate,
+ Code = file.Code,
+ Extension = file.Extension,
+ Filename = file.Filename,
+ IsVariableBitRate = file.IsVariableBitRate,
+ Length = file.Length,
+ SampleRate = file.SampleRate,
+ Size = file.Size,
+ };
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/API/Controllers/SearchesController.cs b/src/slskd/Core/Search/Controllers/SearchesController.cs
index 4a3dc7ab..18bdba15 100644
--- a/src/slskd/API/Controllers/SearchesController.cs
+++ b/src/slskd/Core/Search/Controllers/SearchesController.cs
@@ -15,18 +15,16 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd.API.Controllers
+namespace slskd.Search
{
using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using slskd.API.DTO;
- using slskd.Search;
- using Soulseek;
+ using SearchQuery = Soulseek.SearchQuery;
+ using SearchScope = Soulseek.SearchScope;
/// <summary>
/// Search.
@@ -41,16 +39,13 @@ namespace slskd.API.Controllers
/// <summary>
/// Initializes a new instance of the <see cref="SearchesController"/> class.
/// </summary>
- /// <param name="client"></param>
- /// <param name="tracker"></param>
- public SearchesController(ISoulseekClient client, ISearchTracker tracker)
+ /// <param name="searchService"></param>
+ public SearchesController(ISearchService searchService)
{
- Client = client;
- Tracker = tracker;
+ Searches = searchService;
}
- private ISoulseekClient Client { get; }
- private ISearchTracker Tracker { get; }
+ private ISearchService Searches { get; }
/// <summary>
/// Performs a search for the specified <paramref name="request"/>.
@@ -62,25 +57,17 @@ namespace slskd.API.Controllers
/// <response code="500">The search terminated abnormally.</response>
[HttpPost("")]
[Authorize]
- [ProducesResponseType(typeof(IEnumerable<SearchResponse>), 200)]
- [ProducesResponseType(400)]
- [ProducesResponseType(typeof(string), 500)]
public async Task<IActionResult> Post([FromBody]SearchRequest request)
{
var id = request.Id ?? Guid.NewGuid();
-
- var options = request.ToSearchOptions(
- responseReceived: (e) => Tracker.AddOrUpdate(id, e),
- stateChanged: (e) => Tracker.AddOrUpdate(id, e));
-
- var results = new ConcurrentBag<SearchResponse>();
-
var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1));
+ Search search = null;
+
try
{
- await Client.SearchAsync(SearchQuery.FromText(searchText), (r) => results.Add(r), SearchScope.Network, request.Token, options);
- return Ok(results);
+ search = await Searches.CreateAsync(id, SearchQuery.FromText(searchText), SearchScope.Network);
+ return Ok(search.Responses);
}
catch (Exception ex)
{
@@ -88,8 +75,7 @@ namespace slskd.API.Controllers
}
finally
{
- results = null;
- Tracker.TryRemove(id);
+ search = null;
}
}
@@ -97,16 +83,15 @@ namespace slskd.API.Controllers
/// Gets the state of the search corresponding to the specified <paramref name="id"/>.
/// </summary>
/// <param name="id">The unique id of the search.</param>
+ /// <param name="includeResponses">A value indicating whether to include search responses in the response.</param>
/// <returns></returns>
/// <response code="200">The request completed successfully.</response>
/// <response code="404">A matching search was not found.</response>
[HttpGet("{id}")]
[Authorize]
- [ProducesResponseType(typeof(Search), 200)]
- [ProducesResponseType(404)]
- public IActionResult GetById([FromRoute]Guid id)
+ public async Task<IActionResult> GetById([FromRoute]Guid id, [FromQuery]bool includeResponses = false)
{
- Tracker.Searches.TryGetValue(id, out var search);
+ var search = await Searches.FindAsync(search => search.Id == id, includeResponses);
if (search == default)
{
@@ -115,5 +100,37 @@ namespace slskd.API.Controllers
return Ok(search);
}
+
+ /// <summary>
+ /// Gets the state of the search corresponding to the specified <paramref name="id"/>.
+ /// </summary>
+ /// <param name="id">The unique id of the search.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">A matching search was not found.</response>
+ [HttpGet("{id}/responses")]
+ [Authorize]
+ public async Task<IActionResult> GetResponsesById([FromRoute] Guid id)
+ {
+ var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true);
+
+ if (search == default)
+ {
+ return NotFound();
+ }
+
+ return Ok(search.Responses);
+ }
+
+ /// <summary>
+ /// Gets the list of active and completed searches.
+ /// </summary>
+ /// <returns></returns>
+ [HttpGet("")]
+ [Authorize]
+ public async Task<IActionResult> GetAll()
+ {
+ return Ok(await Searches.ListAsync());
+ }
}
}
diff --git a/src/slskd/Core/Search/Domain/Response.cs b/src/slskd/Core/Search/Domain/Response.cs
new file mode 100644
index 00000000..ea2e8993
--- /dev/null
+++ b/src/slskd/Core/Search/Domain/Response.cs
@@ -0,0 +1,51 @@
+// <copyright file="Response.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.Search
+{
+ using System.Collections.Generic;
+ using System.Linq;
+
+ public class Response
+ {
+ public int FileCount { get; init; }
+ public ICollection<File> Files { get; init; } = new List<File>();
+ public int FreeUploadSlots { get; init; }
+ public int LockedFileCount { get; init; }
+ public ICollection<File> LockedFiles { get; init; } = new List<File>();
+ public long QueueLength { get; init; }
+ public int Token { get; init; }
+ public int UploadSpeed { get; init; }
+ public string Username { get; init; }
+
+ public static Response FromSoulseekSearchResponse(Soulseek.SearchResponse searchResponse)
+ {
+ return new Response()
+ {
+ FileCount = searchResponse.FileCount,
+ Files = searchResponse.Files.Select(file => File.FromSoulseekFile(file)).ToList(),
+ FreeUploadSlots = searchResponse.FreeUploadSlots,
+ LockedFileCount = searchResponse.LockedFileCount,
+ LockedFiles = searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file)).ToList(),
+ QueueLength = searchResponse.QueueLength,
+ Token = searchResponse.Token,
+ UploadSpeed = searchResponse.UploadSpeed,
+ Username = searchResponse.Username,
+ };
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs
new file mode 100644
index 00000000..b93c62cb
--- /dev/null
+++ b/src/slskd/Core/Search/Domain/Search.cs
@@ -0,0 +1,60 @@
+// <copyright file="Search.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.Search
+{
+ using System;
+ using System.Collections.Generic;
+ using System.ComponentModel.DataAnnotations;
+ using System.ComponentModel.DataAnnotations.Schema;
+ using System.Text.Json;
+ using System.Text.Json.Serialization;
+ using Soulseek;
+
+ public class Search
+ {
+ public DateTime? EndedAt { get; set; }
+ public int FileCount { get; set; }
+
+ [Key]
+ public Guid Id { get; init; }
+
+ [NotMapped]
+ public bool IsComplete => State.HasFlag(SearchStates.Completed);
+
+ public int LockedFileCount { get; set; }
+ public int ResponseCount { get; set; }
+
+ [NotMapped]
+ public IEnumerable<Response> Responses { get; set; } = new List<Response>();
+
+ [JsonIgnore]
+ public string ResponsesJson
+ {
+ get => JsonSerializer.Serialize(Responses);
+ set
+ {
+ Responses = JsonSerializer.Deserialize<IEnumerable<Response>>(value);
+ }
+ }
+
+ public string SearchText { get; init; }
+ public DateTime StartedAt { get; init; } = DateTime.UtcNow;
+ public SearchStates State { get; set; }
+ public int Token { get; init; }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/Search/Extensions.cs b/src/slskd/Core/Search/Extensions.cs
new file mode 100644
index 00000000..d52975d2
--- /dev/null
+++ b/src/slskd/Core/Search/Extensions.cs
@@ -0,0 +1,94 @@
+// <copyright file="Extensions.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.Search
+{
+ using System;
+ using System.Linq;
+ using Soulseek;
+
+ public static class Extensions
+ {
+ /// <summary>
+ /// Returns a copy of the specified <paramref name="options"/> with the specified actions bound, while retaining the existing actions.
+ /// </summary>
+ /// <param name="options"></param>
+ /// <param name="stateChanged"></param>
+ /// <param name="responseReceived"></param>
+ /// <returns></returns>
+ public static SearchOptions WithActions(
+ this SearchOptions options,
+ Action<SearchStateChangedEventArgs> stateChanged = null,
+ Action<SearchResponseReceivedEventArgs> responseReceived = null)
+ {
+ stateChanged ??= (args) => { };
+ responseReceived ??= (args) => { };
+
+ return new SearchOptions(
+ options.SearchTimeout,
+ options.ResponseLimit,
+ options.FilterResponses,
+ options.MinimumResponseFileCount,
+ options.MinimumPeerFreeUploadSlots,
+ options.MaximumPeerQueueLength,
+ options.MinimumPeerUploadSpeed,
+ options.FileLimit,
+ options.RemoveSingleCharacterSearchTerms,
+ options.ResponseFilter,
+ options.FileFilter,
+ stateChanged: (args) =>
+ {
+ if (options.StateChanged != null)
+ {
+ options.StateChanged(args);
+ }
+
+ stateChanged(args);
+ },
+ responseReceived: (args) =>
+ {
+ if (options.ResponseReceived != null)
+ {
+ options.ResponseReceived(args);
+ }
+
+ responseReceived(args);
+ });
+ }
+
+ /// <summary>
+ /// Creates a projection over the specified <paramref name="query"/> which omits responses.
+ /// </summary>
+ /// <param name="query"></param>
+ /// <returns></returns>
+ public static IQueryable<Search> WithoutResponses(this IQueryable<Search> query)
+ {
+ return query.Select(s => new Search()
+ {
+ Id = s.Id,
+ StartedAt = s.StartedAt,
+ EndedAt = s.EndedAt,
+ FileCount = s.FileCount,
+ LockedFileCount = s.LockedFileCount,
+ ResponseCount = s.ResponseCount,
+ SearchText = s.SearchText,
+ State = s.State,
+ Token = s.Token,
+ });
+ }
+ }
+}
diff --git a/src/slskd/Core/Search/ISearchTracker.cs b/src/slskd/Core/Search/ISearchTracker.cs
deleted file mode 100644
index c2bdcbaa..00000000
--- a/src/slskd/Core/Search/ISearchTracker.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// <copyright file="ISearchTracker.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.Search
-{
- using System;
- using System.Collections.Concurrent;
- using Soulseek;
-
- /// <summary>
- /// Tracks active searches.
- /// </summary>
- public interface ISearchTracker
- {
- /// <summary>
- /// Gets active searches.
- /// </summary>
- ConcurrentDictionary<Guid, Search> Searches { get; }
-
- /// <summary>
- /// Adds or updates a tracked search.
- /// </summary>
- /// <param name="id"></param>
- /// <param name="args"></param>
- void AddOrUpdate(Guid id, SearchEventArgs args);
-
- /// <summary>
- /// Removes all tracked searches.
- /// </summary>
- void Clear();
-
- /// <summary>
- /// Removes a tracked search.
- /// </summary>
- /// <param name="id"></param>
- void TryRemove(Guid id);
- }
-} \ No newline at end of file
diff --git a/src/slskd/Core/Search/Persistence/SearchDbContext.cs b/src/slskd/Core/Search/Persistence/SearchDbContext.cs
new file mode 100644
index 00000000..efb2fdd6
--- /dev/null
+++ b/src/slskd/Core/Search/Persistence/SearchDbContext.cs
@@ -0,0 +1,32 @@
+// <copyright file="SearchDbContext.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.Search
+{
+ using Microsoft.EntityFrameworkCore;
+
+ public class SearchDbContext : DbContext
+ {
+ public SearchDbContext(DbContextOptions<SearchDbContext> options)
+ : base(options)
+ {
+ Database.EnsureCreated();
+ }
+
+ public DbSet<Search> Searches { get; set; }
+ }
+}
diff --git a/src/slskd/Core/Search/SearchResponseCache.cs b/src/slskd/Core/Search/SearchResponseCache.cs
index 6b223280..c31a3a9b 100644
--- a/src/slskd/Core/Search/SearchResponseCache.cs
+++ b/src/slskd/Core/Search/SearchResponseCache.cs
@@ -41,7 +41,7 @@ namespace slskd.Search
/// </summary>
/// <param name="responseToken">The token for which the response is to be added or updated.</param>
/// <param name="response">The response and context to cache.</param>
- public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, SearchResponse SearchResponse) response)
+ public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response)
{
Cache.Set(responseToken, response, TimeSpan.FromMinutes(3));
}
@@ -52,7 +52,7 @@ namespace slskd.Search
/// <param name="responseToken">The token for the cached response.</param>
/// <param name="response">The cached response and context, if present.</param>
/// <returns>A value indicating whether a response for the specified responseToken is cached.</returns>
- public bool TryGet(int responseToken, out (string Username, int Token, string Query, SearchResponse SearchResponse) response)
+ public bool TryGet(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response)
{
return Cache.TryGetValue(responseToken, out response);
}
@@ -63,7 +63,7 @@ namespace slskd.Search
/// <param name="responseToken">The token for the cached response.</param>
/// <param name="response">The cached response and context, if present.</param>
/// <returns>A value indicating whether a response for the specified responseToken was removed.</returns>
- public bool TryRemove(int responseToken, out (string Username, int Token, string Query, SearchResponse SearchResponse) response)
+ public bool TryRemove(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response)
{
if (Cache.TryGetValue(responseToken, out response))
{
diff --git a/src/slskd/Core/Search/SearchTracker.cs b/src/slskd/Core/Search/SearchTracker.cs
deleted file mode 100644
index c4f124ca..00000000
--- a/src/slskd/Core/Search/SearchTracker.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-// <copyright file="SearchTracker.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.Search
-{
- using System;
- using System.Collections.Concurrent;
- using Soulseek;
-
- /// <summary>
- /// Tracks active searches.
- /// </summary>
- public class SearchTracker : ISearchTracker
- {
- /// <summary>
- /// Gets active searches.
- /// </summary>
- public ConcurrentDictionary<Guid, Search> Searches { get; private set; } =
- new ConcurrentDictionary<Guid, Search>();
-
- /// <summary>
- /// Adds or updates a tracked search.
- /// </summary>
- /// <param name="id"></param>
- /// <param name="args"></param>
- public void AddOrUpdate(Guid id, SearchEventArgs args)
- {
- Searches.AddOrUpdate(id, args.Search, (token, search) => args.Search);
- }
-
- /// <summary>
- /// Removes all tracked searches.
- /// </summary>
- public void Clear()
- {
- Searches.Clear();
- }
-
- /// <summary>
- /// Removes a tracked search.
- /// </summary>
- /// <param name="id"></param>
- public void TryRemove(Guid id)
- {
- Searches.TryRemove(id, out _);
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/Core/Search/Services/ISearchService.cs b/src/slskd/Core/Search/Services/ISearchService.cs
new file mode 100644
index 00000000..d696617d
--- /dev/null
+++ b/src/slskd/Core/Search/Services/ISearchService.cs
@@ -0,0 +1,66 @@
+// <copyright file="ISearchService.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.Search
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq.Expressions;
+ using System.Threading.Tasks;
+ using SearchOptions = Soulseek.SearchOptions;
+ using SearchQuery = Soulseek.SearchQuery;
+ using SearchScope = Soulseek.SearchScope;
+
+ /// <summary>
+ /// Handles the lifecycle and persistence of searches.
+ /// </summary>
+ public interface ISearchService
+ {
+ /// <summary>
+ /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>.
+ /// </summary>
+ /// <param name="id">A unique identifier for the search.</param>
+ /// <param name="query">The search query.</param>
+ /// <param name="scope">The search scope.</param>
+ /// <param name="options">Search options.</param>
+ /// <returns>The completed search.</returns>
+ Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null);
+
+ /// <summary>
+ /// Finds a single search matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match searches.</param>
+ /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param>
+ /// <returns>The found search, or default if not found.</returns>
+ /// <exception cref="ArgumentException">Thrown an expression is not supplied.</exception>
+ Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false);
+
+ /// <summary>
+ /// Returns a list of all completed and in-progress searches, with responses omitted.
+ /// </summary>
+ /// <param name="expression">An optional expression used to match searches.</param>
+ /// <returns>The list of searches matching the specified expression.</returns>
+ Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null);
+
+ /// <summary>
+ /// Cancels the search matching the specified <paramref name="id"/>, if it is in progress.
+ /// </summary>
+ /// <param name="id">The unique identifier for the search.</param>
+ /// <returns>A value indicating whether the search was sucessfully cancelled.</returns>
+ bool TryCancel(Guid id);
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/Search/Services/SearchService.cs b/src/slskd/Core/Search/Services/SearchService.cs
new file mode 100644
index 00000000..e3c1bbef
--- /dev/null
+++ b/src/slskd/Core/Search/Services/SearchService.cs
@@ -0,0 +1,205 @@
+// <copyright file="SearchService.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.Search
+{
+ using System;
+ using System.Collections.Concurrent;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Linq.Expressions;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using Microsoft.EntityFrameworkCore;
+ using Microsoft.Extensions.Logging;
+ using ISoulseekClient = Soulseek.ISoulseekClient;
+ 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.
+ /// </summary>
+ public class SearchService : ISearchService
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SearchService"/> class.
+ /// </summary>
+ /// <param name="client">The client instance to use.</param>
+ /// <param name="contextFactory">The database context to use.</param>
+ /// <param name="log">The logger.</param>
+ public SearchService(
+ ISoulseekClient client,
+ IDbContextFactory<SearchDbContext> contextFactory,
+ ILogger<SearchService> log)
+ {
+ Client = client;
+ ContextFactory = contextFactory;
+ Log = log;
+ }
+
+ private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; }
+ = new ConcurrentDictionary<Guid, CancellationTokenSource>();
+
+ private ISoulseekClient Client { get; }
+ private IDbContextFactory<SearchDbContext> ContextFactory { get; }
+ private ILogger<SearchService> Log { get; set; }
+
+ /// <summary>
+ /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>.
+ /// </summary>
+ /// <param name="id">A unique identifier for the search.</param>
+ /// <param name="query">The search query.</param>
+ /// <param name="scope">The search scope.</param>
+ /// <param name="options">Search options.</param>
+ /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param>
+ /// <returns>The completed search.</returns>
+ public async Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null)
+ {
+ var token = Client.GetNextToken();
+ var cancellationTokenSource = new CancellationTokenSource();
+
+ var search = new Search()
+ {
+ SearchText = query.SearchText,
+ Token = token,
+ Id = id,
+ State = SearchStates.Requested,
+ StartedAt = DateTime.UtcNow,
+ };
+
+ options ??= new SearchOptions();
+ options = options.WithActions(
+ stateChanged: (args) => UpdateSearchState(search, args.Search),
+ responseReceived: (args) => UpdateSearchState(search, args.Search));
+
+ try
+ {
+ using var context = ContextFactory.CreateDbContext();
+
+ context.Add(search);
+ await context.SaveChangesAsync();
+
+ CancellationTokens.TryAdd(id, cancellationTokenSource);
+ var responses = new List<Response>();
+
+ var soulseekSearch = await Client.SearchAsync(
+ query,
+ responseReceived: (response) =>
+ {
+ 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
+ {
+ CancellationTokens.TryRemove(id, out _);
+ }
+ }
+
+ /// <summary>
+ /// Finds a single search matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match searches.</param>
+ /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param>
+ /// <returns>The found search, or default if not found.</returns>
+ /// <exception cref="ArgumentException">Thrown an expression is not supplied.</exception>
+ public Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false)
+ {
+ if (expression == default)
+ {
+ throw new ArgumentException("An expression must be supplied.", nameof(expression));
+ }
+
+ using var context = ContextFactory.CreateDbContext();
+
+ var selector = context.Searches.Where(expression);
+
+ if (!includeResponses)
+ {
+ selector = selector.WithoutResponses();
+ }
+
+ return selector.FirstOrDefaultAsync();
+ }
+
+ /// <summary>
+ /// Returns a list of all completed and in-progress searches, with responses omitted.
+ /// </summary>
+ /// <param name="expression">An optional expression used to match searches.</param>
+ /// <returns>The list of searches matching the specified expression.</returns>
+ public Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null)
+ {
+ expression ??= s => true;
+ using var context = ContextFactory.CreateDbContext();
+ return context.Searches.Where(expression).WithoutResponses().ToListAsync();
+ }
+
+ /// <summary>
+ /// Cancels the search matching the specified <paramref name="id"/>, if it is in progress.
+ /// </summary>
+ /// <param name="id">The unique identifier for the search.</param>
+ /// <returns>A value indicating whether the search was sucessfully cancelled.</returns>
+ public bool TryCancel(Guid id)
+ {
+ if (CancellationTokens.TryGetValue(id, out var cts))
+ {
+ cts.Cancel();
+ return true;
+ }
+
+ 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;
+
+ SaveSearchState(search);
+ }
+ }
+
+ private void SaveSearchState(Search search)
+ {
+ var context = ContextFactory.CreateDbContext();
+ context.Update(search);
+ context.SaveChanges();
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/Service.cs b/src/slskd/Core/Service.cs
index f46e6739..6df1ddcb 100644
--- a/src/slskd/Core/Service.cs
+++ b/src/slskd/Core/Service.cs
@@ -365,15 +365,15 @@ namespace slskd
}
/// <summary>
- /// Creates and returns a <see cref="SearchResponse"/> in response to the given <paramref name="query"/>.
+ /// Creates and returns a <see cref="Response"/> in response to the given <paramref name="query"/>.
/// </summary>
/// <param name="username">The username of the requesting user.</param>
/// <param name="token">The search token.</param>
/// <param name="query">The search query.</param>
/// <returns>A Task resolving a SearchResponse, or null.</returns>
- private Task<SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query)
+ private Task<Soulseek.SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query)
{
- var defaultResponse = Task.FromResult<SearchResponse>(null);
+ var defaultResponse = Task.FromResult<Soulseek.SearchResponse>(null);
// some bots continually query for very common strings. blacklist known names here.
var blacklist = new[] { "Lola45", "Lolo51", "rajah" };
@@ -394,7 +394,7 @@ namespace slskd
{
Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}");
- return Task.FromResult(new SearchResponse(
+ return Task.FromResult(new Soulseek.SearchResponse(
SoulseekClient.Username,
token,
freeUploadSlots: 1,
@@ -405,7 +405,7 @@ namespace slskd
// if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no
// response will be sent to the requestor.
- return Task.FromResult<SearchResponse>(null);
+ return Task.FromResult<Soulseek.SearchResponse>(null);
}
/// <summary>
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 7a526fb2..42c3c508 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -41,6 +41,7 @@ namespace slskd
using slskd.Validation;
using Utility.CommandLine;
using Utility.EnvironmentVariables;
+ using IOFile = System.IO.File;
/// <summary>
/// Bootstraps configuration and handles primitive command-line instructions.
@@ -63,11 +64,6 @@ namespace slskd
public static readonly string DefaultConfigurationFile = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.yml");
/// <summary>
- /// The default XML documentation filename.
- /// </summary>
- public static readonly string DefaultXmlDocumentationFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml");
-
- /// <summary>
/// The default incomplete download directory.
/// </summary>
public static readonly string DefaultIncompleteDirectory = Path.Combine(DefaultAppDirectory, "incomplete");
@@ -88,6 +84,11 @@ namespace slskd
public static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_";
/// <summary>
+ /// The default XML documentation filename.
+ /// </summary>
+ public static readonly string XmlDocumentationFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml");
+
+ /// <summary>
/// Gets the assembly version of the application.
/// </summary>
/// <remarks>
@@ -253,7 +254,7 @@ namespace slskd
PrintLogo(Version);
}
- if (ConfigurationFile != DefaultConfigurationFile && !File.Exists(ConfigurationFile))
+ if (ConfigurationFile != DefaultConfigurationFile && !IOFile.Exists(ConfigurationFile))
{
logger.Warning($"Specified configuration file '{ConfigurationFile}' could not be found and was not loaded.");
}
@@ -346,7 +347,7 @@ namespace slskd
filename = Path.Combine(AppContext.BaseDirectory, filename);
var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable);
- File.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password));
+ IOFile.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password));
Console.WriteLine($"Password: {password}");
Console.WriteLine($"Certificate exported to {filename}");
@@ -503,8 +504,8 @@ namespace slskd
{
var file = Guid.NewGuid().ToString();
var probe = Path.Combine(directory, file);
- File.WriteAllText(probe, string.Empty);
- File.Delete(probe);
+ IOFile.WriteAllText(probe, string.Empty);
+ IOFile.Delete(probe);
}
catch (Exception ex)
{
diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs
index f073117c..4d11ad1a 100644
--- a/src/slskd/Startup.cs
+++ b/src/slskd/Startup.cs
@@ -24,6 +24,7 @@ namespace slskd
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
+ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
@@ -149,13 +150,13 @@ namespace slskd
Version = "v0",
});
- if (File.Exists(Program.DefaultXmlDocumentationFile))
+ if (System.IO.File.Exists(Program.XmlDocumentationFile))
{
- options.IncludeXmlComments(Program.DefaultXmlDocumentationFile);
+ options.IncludeXmlComments(Program.XmlDocumentationFile);
}
else
{
- logger.Warning($"Unable to find XML documentation in {Program.DefaultXmlDocumentationFile}, Swagger will not include metadata");
+ logger.Warning($"Unable to find XML documentation in {Program.XmlDocumentationFile}, Swagger will not include metadata");
}
});
}
@@ -165,14 +166,22 @@ namespace slskd
services.AddSystemMetrics();
}
+ services.AddDbContextFactory<SearchDbContext>(options =>
+ {
+ options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "search.db")}");
+ });
+
+ services.AddTransient(p => p.GetRequiredService<IDbContextFactory<SearchDbContext>>().CreateDbContext());
+
services.AddSingleton<ITransferTracker, TransferTracker>();
- services.AddSingleton<ISearchTracker, SearchTracker>();
services.AddSingleton<IBrowseTracker, BrowseTracker>();
services.AddSingleton<IConversationTracker, ConversationTracker>();
services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
services.AddSingleton<ISharedFileCache>(_ =>
new SharedFileCache(Options.Directories.Shared, 3600000));
+ services.AddSingleton<ISearchService, SearchService>();
+
services.AddHostedService<Service>();
services.AddSingleton(_ => Service.SoulseekClient);
}
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 5d9e477c..18f94fd6 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -49,6 +49,8 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Data.Sqlite" Version="5.0.6" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.6" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="5.0.6" />
<PackageReference Include="prometheus-net" Version="4.1.1" />
<PackageReference Include="prometheus-net.AspNetCore" Version="4.1.1" />
<PackageReference Include="prometheus-net.AspNetCore.HealthChecks" Version="4.1.1" />
@@ -65,7 +67,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
- <PackageReference Include="Soulseek" Version="2.3.8" />
+ <PackageReference Include="Soulseek" Version="3.0.0-pre-52521953" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.321">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js
index 48e05775..60720c1a 100644
--- a/src/web/src/components/Search/Search.js
+++ b/src/web/src/components/Search/Search.js
@@ -18,7 +18,7 @@ import {
const initialState = {
searchPhrase: '',
- searchId: '',
+ searchId: undefined,
searchState: 'idle',
searchStatus: {
responseCount: 0,
@@ -31,6 +31,7 @@ const initialState = {
hideNoFreeSlots: true,
hiddenResults: [],
hideLocked: true,
+ fetching: false,
};
const sortOptions = {
@@ -50,13 +51,9 @@ class Search extends Component {
const searchPhrase = this.inputtext.inputRef.current.value;
const searchId = uuidv4();
- this.setState({ searchPhrase, searchId, searchState: 'pending' }, () => {
- search.search({ id: searchId, searchText: searchPhrase })
- .then(response => this.setState({ results: response.data }))
- .then(() => this.setState({ searchState: 'complete' }, () => {
- this.saveState();
- this.setSearchText();
- }))
+ this.setState({ searchPhrase, searchId, searchState: 'pending' }, async () => {
+ this.saveState();
+ search.search({ id: searchId, searchText: searchPhrase });
});
}
@@ -76,19 +73,20 @@ class Search extends Component {
saveState = () => {
try {
- localStorage.setItem('soulseek-example-search-state', JSON.stringify(this.state));
+ localStorage.setItem('soulseek-example-search-state', JSON.stringify({ ...this.state, results: [] }));
} catch(error) {
console.log(error);
}
}
loadState = () => {
- this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState);
+ return new Promise((resolve) =>
+ this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState, resolve));
}
- componentDidMount = () => {
- this.fetchStatus();
- this.loadState();
+ componentDidMount = async () => {
+ await this.loadState();
+ this.fetchResults();
this.setState({
interval: window.setInterval(this.fetchStatus, 500)
}, () => this.setSearchText());
@@ -107,12 +105,44 @@ class Search extends Component {
document.removeEventListener("keyup", this.keyUp, false);
}
- fetchStatus = () => {
- if (this.state.searchState === 'pending') {
- search.getStatus({ id: this.state.searchId })
- .then(response => this.setState({
- searchStatus: response
- }));
+ 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);
+ }
+ });
}
}
@@ -121,7 +151,7 @@ class Search extends Component {
}
sortAndFilterResults = () => {
- const { results, hideNoFreeSlots, resultSort, hideLocked, hiddenResults } = this.state;
+ const { results = [], hideNoFreeSlots, resultSort, hideLocked, hiddenResults = [] } = this.state;
const { field, order } = sortOptions[resultSort];
return results
@@ -154,8 +184,8 @@ class Search extends Component {
}
render = () => {
- let { searchState, searchStatus, results, displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults } = this.state;
- let pending = searchState === 'pending';
+ let { searchState, searchStatus, results = [], displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults = [], fetching } = this.state;
+ let pending = fetching || searchState === 'pending';
const sortedAndFilteredResults = this.sortAndFilterResults();
@@ -185,7 +215,8 @@ class Search extends Component {
inline='centered'
size='big'
>
- Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users
+ {searchState === 'pending' ? <span>Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users</span>
+ : 'Loading results...'}
</Loader>
:
<div>
diff --git a/src/web/src/lib/search.js b/src/web/src/lib/search.js
index c71dba96..2179dcd2 100644
--- a/src/web/src/lib/search.js
+++ b/src/web/src/lib/search.js
@@ -4,6 +4,10 @@ export const search = ({ id, searchText }) => {
return api.post(`/searches`, { id, searchText });
};
-export const getStatus = async ({ id }) => {
- return (await api.get(`/searches/${encodeURIComponent(id)}`)).data;
+export const getStatus = async ({ id, includeResponses = false }) => {
+ return (await api.get(`/searches/${encodeURIComponent(id)}?includeResponses=${includeResponses}`)).data;
+};
+
+export const getResponses = async ({ id }) => {
+ return (await api.get(`/searches/${encodeURIComponent(id)}/responses`)).data;
}; \ No newline at end of file