aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Core
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/slskd/Core
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/slskd/Core')
-rw-r--r--src/slskd/Core/Common/Domain/File.cs51
-rw-r--r--src/slskd/Core/Search/Controllers/SearchesController.cs136
-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
12 files changed, 703 insertions, 122 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/Core/Search/Controllers/SearchesController.cs b/src/slskd/Core/Search/Controllers/SearchesController.cs
new file mode 100644
index 00000000..18bdba15
--- /dev/null
+++ b/src/slskd/Core/Search/Controllers/SearchesController.cs
@@ -0,0 +1,136 @@
+// <copyright file="SearchesController.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 System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+ using slskd.API.DTO;
+ using SearchQuery = Soulseek.SearchQuery;
+ using SearchScope = Soulseek.SearchScope;
+
+ /// <summary>
+ /// Search.
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("0")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class SearchesController : ControllerBase
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SearchesController"/> class.
+ /// </summary>
+ /// <param name="searchService"></param>
+ public SearchesController(ISearchService searchService)
+ {
+ Searches = searchService;
+ }
+
+ private ISearchService Searches { get; }
+
+ /// <summary>
+ /// Performs a search for the specified <paramref name="request"/>.
+ /// </summary>
+ /// <param name="request">The search request.</param>
+ /// <returns></returns>
+ /// <response code="200">The search completed successfully.</response>
+ /// <response code="400">The specified <paramref name="request"/> was malformed.</response>
+ /// <response code="500">The search terminated abnormally.</response>
+ [HttpPost("")]
+ [Authorize]
+ public async Task<IActionResult> Post([FromBody]SearchRequest request)
+ {
+ var id = request.Id ?? Guid.NewGuid();
+ var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1));
+
+ Search search = null;
+
+ try
+ {
+ search = await Searches.CreateAsync(id, SearchQuery.FromText(searchText), SearchScope.Network);
+ return Ok(search.Responses);
+ }
+ catch (Exception ex)
+ {
+ return StatusCode(500, $"Search terminated abnormally: {ex.Message}");
+ }
+ finally
+ {
+ search = null;
+ }
+ }
+
+ /// <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>
+ /// <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]
+ public async Task<IActionResult> GetById([FromRoute]Guid id, [FromQuery]bool includeResponses = false)
+ {
+ var search = await Searches.FindAsync(search => search.Id == id, includeResponses);
+
+ if (search == default)
+ {
+ return NotFound();
+ }
+
+ 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>