diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-09-21 08:28:11 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2021-09-21 08:28:11 -0500 |
| commit | 0eb773dbd4aa2fe971bc55e5c5f12413003296bb (patch) | |
| tree | 7e36184eb454ed8b0f5f0cbce07c53c191a0a3c1 /src/slskd/Application/Search | |
| parent | 7387d568548af0898d9fd2b716d3bb16b6d9be2b (diff) | |
| download | slskd-0eb773dbd4aa2fe971bc55e5c5f12413003296bb.tar.gz | |
move stuff again
Diffstat (limited to 'src/slskd/Application/Search')
| -rw-r--r-- | src/slskd/Application/Search/API/Controllers/SearchesController.cs | 135 | ||||
| -rw-r--r-- | src/slskd/Application/Search/API/DTO/SearchRequest.cs | 116 | ||||
| -rw-r--r-- | src/slskd/Application/Search/Domain/File.cs | 51 | ||||
| -rw-r--r-- | src/slskd/Application/Search/Domain/Response.cs | 51 | ||||
| -rw-r--r-- | src/slskd/Application/Search/Domain/Search.cs | 60 | ||||
| -rw-r--r-- | src/slskd/Application/Search/Extensions.cs | 122 | ||||
| -rw-r--r-- | src/slskd/Application/Search/ISearchService.cs | 66 | ||||
| -rw-r--r-- | src/slskd/Application/Search/SearchDbContext.cs | 32 | ||||
| -rw-r--r-- | src/slskd/Application/Search/SearchResponseCache.cs | 77 | ||||
| -rw-r--r-- | src/slskd/Application/Search/SearchService.cs | 210 |
10 files changed, 0 insertions, 920 deletions
diff --git a/src/slskd/Application/Search/API/Controllers/SearchesController.cs b/src/slskd/Application/Search/API/Controllers/SearchesController.cs deleted file mode 100644 index 5f740044..00000000 --- a/src/slskd/Application/Search/API/Controllers/SearchesController.cs +++ /dev/null @@ -1,135 +0,0 @@ -// <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.API -{ - using System; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - 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/Application/Search/API/DTO/SearchRequest.cs b/src/slskd/Application/Search/API/DTO/SearchRequest.cs deleted file mode 100644 index aad5a200..00000000 --- a/src/slskd/Application/Search/API/DTO/SearchRequest.cs +++ /dev/null @@ -1,116 +0,0 @@ -// <copyright file="SearchRequest.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.API -{ - using System; - using Soulseek; - - /// <summary> - /// A search request. - /// </summary> - public class SearchRequest - { - /// <summary> - /// Gets or sets the unique search identifier. - /// </summary> - public Guid? Id { get; set; } - - /// <summary> - /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000). - /// </summary> - public int? FileLimit { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether responses are to be filtered. (Default = true). - /// </summary> - public bool? FilterResponses { get; set; } - - /// <summary> - /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000). - /// </summary> - public int? MaximumPeerQueueLength { get; set; } - - /// <summary> - /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. - /// (Default = 0). - /// </summary> - public int? MinimumPeerFreeUploadSlots { get; set; } - - /// <summary> - /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). - /// </summary> - public int? MinimumPeerUploadSpeed { get; set; } - - /// <summary> - /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1). - /// </summary> - public int? MinimumResponseFileCount { get; set; } - - /// <summary> - /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100). - /// </summary> - public int? ResponseLimit { get; set; } - - /// <summary> - /// Gets or sets the search text. - /// </summary> - public string SearchText { get; set; } - - /// <summary> - /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15). - /// </summary> - /// <remarks>The timeout duration is from the time of the last response.</remarks> - public int? SearchTimeout { get; set; } - - /// <summary> - /// Gets or sets the search token. - /// </summary> - public int? Token { get; set; } - - /// <summary> - /// Maps to a new instance of <see cref="SearchOptions"/>. - /// </summary> - /// <param name="responseFilter"></param> - /// <param name="fileFilter"></param> - /// <param name="stateChanged"></param> - /// <param name="responseReceived"></param> - /// <returns></returns> - public SearchOptions ToSearchOptions( - Func<SearchResponse, bool> responseFilter = null, - Func<File, bool> fileFilter = null, - Action<SearchStateChangedEventArgs> stateChanged = null, - Action<SearchResponseReceivedEventArgs> responseReceived = null) - { - var def = new SearchOptions(); - - return new SearchOptions( - searchTimeout: SearchTimeout ?? def.SearchTimeout, - responseLimit: ResponseLimit ?? def.ResponseLimit, - fileLimit: FileLimit ?? def.FileLimit, - filterResponses: FilterResponses ?? def.FilterResponses, - minimumResponseFileCount: MinimumResponseFileCount ?? def.MinimumResponseFileCount, - minimumPeerFreeUploadSlots: MinimumPeerFreeUploadSlots ?? def.MinimumPeerFreeUploadSlots, - maximumPeerQueueLength: MaximumPeerQueueLength ?? def.MaximumPeerQueueLength, - minimumPeerUploadSpeed: MinimumPeerUploadSpeed ?? def.MinimumPeerUploadSpeed, - responseFilter: responseFilter, - fileFilter: fileFilter, - responseReceived: responseReceived, - stateChanged: stateChanged); - } - } -}
\ No newline at end of file diff --git a/src/slskd/Application/Search/Domain/File.cs b/src/slskd/Application/Search/Domain/File.cs deleted file mode 100644 index 0a86eec3..00000000 --- a/src/slskd/Application/Search/Domain/File.cs +++ /dev/null @@ -1,51 +0,0 @@ -// <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.Search -{ - 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/Application/Search/Domain/Response.cs b/src/slskd/Application/Search/Domain/Response.cs deleted file mode 100644 index ea2e8993..00000000 --- a/src/slskd/Application/Search/Domain/Response.cs +++ /dev/null @@ -1,51 +0,0 @@ -// <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/Application/Search/Domain/Search.cs b/src/slskd/Application/Search/Domain/Search.cs deleted file mode 100644 index b93c62cb..00000000 --- a/src/slskd/Application/Search/Domain/Search.cs +++ /dev/null @@ -1,60 +0,0 @@ -// <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/Application/Search/Extensions.cs b/src/slskd/Application/Search/Extensions.cs deleted file mode 100644 index 149e0a14..00000000 --- a/src/slskd/Application/Search/Extensions.cs +++ /dev/null @@ -1,122 +0,0 @@ -// <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> - /// Returns a copy of the specified <paramref name="options"/> with the specified filter delegates overridden. - /// </summary> - /// <param name="options"></param> - /// <param name="responseFilter"></param> - /// <param name="fileFilter"></param> - /// <returns></returns> - public static SearchOptions WithFilters( - this SearchOptions options, - Func<SearchResponse, bool> responseFilter = null, - Func<Soulseek.File, bool> fileFilter = null) - { - return new SearchOptions( - options.SearchTimeout, - options.ResponseLimit, - filterResponses: options.FilterResponses || responseFilter != null || fileFilter != null, - options.MinimumResponseFileCount, - options.MinimumPeerFreeUploadSlots, - options.MaximumPeerQueueLength, - options.MinimumPeerUploadSpeed, - options.FileLimit, - options.RemoveSingleCharacterSearchTerms, - responseFilter, - fileFilter, - options.StateChanged, - options.ResponseReceived); - } - - /// <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/Application/Search/ISearchService.cs b/src/slskd/Application/Search/ISearchService.cs deleted file mode 100644 index d696617d..00000000 --- a/src/slskd/Application/Search/ISearchService.cs +++ /dev/null @@ -1,66 +0,0 @@ -// <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/Application/Search/SearchDbContext.cs b/src/slskd/Application/Search/SearchDbContext.cs deleted file mode 100644 index efb2fdd6..00000000 --- a/src/slskd/Application/Search/SearchDbContext.cs +++ /dev/null @@ -1,32 +0,0 @@ -// <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/Application/Search/SearchResponseCache.cs b/src/slskd/Application/Search/SearchResponseCache.cs deleted file mode 100644 index c31a3a9b..00000000 --- a/src/slskd/Application/Search/SearchResponseCache.cs +++ /dev/null @@ -1,77 +0,0 @@ -// <copyright file="SearchResponseCache.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 Microsoft.Extensions.Caching.Memory; - using Soulseek; - - /// <summary> - /// Caches undelivered search responses. - /// </summary> - public class SearchResponseCache : ISearchResponseCache - { - /// <summary> - /// Initializes a new instance of the <see cref="SearchResponseCache"/> class. - /// </summary> - public SearchResponseCache() - { - Cache = new MemoryCache(new MemoryCacheOptions()); - } - - private IMemoryCache Cache { get; } - - /// <summary> - /// Caches or updates a response. - /// </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, Soulseek.SearchResponse SearchResponse) response) - { - Cache.Set(responseToken, response, TimeSpan.FromMinutes(3)); - } - - /// <summary> - /// Attempts to fetch a cached response and context for the specified <paramref name="responseToken"/>. - /// </summary> - /// <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, Soulseek.SearchResponse SearchResponse) response) - { - return Cache.TryGetValue(responseToken, out response); - } - - /// <summary> - /// Attempts to remove a cached Soulseek.SearchResponse and context for the specified <paramref name="responseToken"/>. - /// </summary> - /// <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, Soulseek.SearchResponse SearchResponse) response) - { - if (Cache.TryGetValue(responseToken, out response)) - { - Cache.Remove(responseToken); - return true; - } - - return false; - } - } -}
\ No newline at end of file diff --git a/src/slskd/Application/Search/SearchService.cs b/src/slskd/Application/Search/SearchService.cs deleted file mode 100644 index e529f738..00000000 --- a/src/slskd/Application/Search/SearchService.cs +++ /dev/null @@ -1,210 +0,0 @@ -// <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> - -using Microsoft.Extensions.Options; - -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 Soulseek; - using SearchOptions = Soulseek.SearchOptions; - using SearchQuery = Soulseek.SearchQuery; - using SearchScope = Soulseek.SearchScope; - using SearchStates = Soulseek.SearchStates; - using SoulseekSearch = Soulseek.Search; - - /// <summary> - /// Handles the lifecycle and persistence of searches. - /// </summary> - public class SearchService : ISearchService - { - /// <summary> - /// Initializes a new instance of the <see cref="SearchService"/> class. - /// </summary> - /// <param name="optionsMonitor"></param> - /// <param name="soulseekClient"></param> - /// <param name="contextFactory">The database context to use.</param> - /// <param name="log">The logger.</param> - public SearchService( - IOptionsMonitor<Options> optionsMonitor, - ISoulseekClient soulseekClient, - IDbContextFactory<SearchDbContext> contextFactory, - ILogger<SearchService> log) - { - OptionsMonitor = optionsMonitor; - Client = soulseekClient; - ContextFactory = contextFactory; - Log = log; - } - - private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } - = new ConcurrentDictionary<Guid, CancellationTokenSource>(); - - private IOptionsMonitor<Options> OptionsMonitor { get; } - 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> - /// <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 |
