From 0eb773dbd4aa2fe971bc55e5c5f12413003296bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Sep 2021 08:28:11 -0500 Subject: move stuff again --- .../Search/API/Controllers/SearchesController.cs | 135 ------------- .../Application/Search/API/DTO/SearchRequest.cs | 116 ------------ src/slskd/Application/Search/Domain/File.cs | 51 ----- src/slskd/Application/Search/Domain/Response.cs | 51 ----- src/slskd/Application/Search/Domain/Search.cs | 60 ------ src/slskd/Application/Search/Extensions.cs | 122 ------------ src/slskd/Application/Search/ISearchService.cs | 66 ------- src/slskd/Application/Search/SearchDbContext.cs | 32 ---- .../Application/Search/SearchResponseCache.cs | 77 -------- src/slskd/Application/Search/SearchService.cs | 210 --------------------- 10 files changed, 920 deletions(-) delete mode 100644 src/slskd/Application/Search/API/Controllers/SearchesController.cs delete mode 100644 src/slskd/Application/Search/API/DTO/SearchRequest.cs delete mode 100644 src/slskd/Application/Search/Domain/File.cs delete mode 100644 src/slskd/Application/Search/Domain/Response.cs delete mode 100644 src/slskd/Application/Search/Domain/Search.cs delete mode 100644 src/slskd/Application/Search/Extensions.cs delete mode 100644 src/slskd/Application/Search/ISearchService.cs delete mode 100644 src/slskd/Application/Search/SearchDbContext.cs delete mode 100644 src/slskd/Application/Search/SearchResponseCache.cs delete mode 100644 src/slskd/Application/Search/SearchService.cs (limited to 'src/slskd/Application/Search') 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 (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/. -// - -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; - - /// - /// Search. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class SearchesController : ControllerBase - { - /// - /// Initializes a new instance of the class. - /// - /// - public SearchesController(ISearchService searchService) - { - Searches = searchService; - } - - private ISearchService Searches { get; } - - /// - /// Performs a search for the specified . - /// - /// The search request. - /// - /// The search completed successfully. - /// The specified was malformed. - /// The search terminated abnormally. - [HttpPost("")] - [Authorize] - public async Task 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; - } - } - - /// - /// Gets the state of the search corresponding to the specified . - /// - /// The unique id of the search. - /// A value indicating whether to include search responses in the response. - /// - /// The request completed successfully. - /// A matching search was not found. - [HttpGet("{id}")] - [Authorize] - public async Task 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); - } - - /// - /// Gets the state of the search corresponding to the specified . - /// - /// The unique id of the search. - /// - /// The request completed successfully. - /// A matching search was not found. - [HttpGet("{id}/responses")] - [Authorize] - public async Task GetResponsesById([FromRoute] Guid id) - { - var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); - - if (search == default) - { - return NotFound(); - } - - return Ok(search.Responses); - } - - /// - /// Gets the list of active and completed searches. - /// - /// - [HttpGet("")] - [Authorize] - public async Task 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 (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/. -// - -namespace slskd.Search.API -{ - using System; - using Soulseek; - - /// - /// A search request. - /// - public class SearchRequest - { - /// - /// Gets or sets the unique search identifier. - /// - public Guid? Id { get; set; } - - /// - /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000). - /// - public int? FileLimit { get; set; } - - /// - /// Gets or sets a value indicating whether responses are to be filtered. (Default = true). - /// - public bool? FilterResponses { get; set; } - - /// - /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000). - /// - public int? MaximumPeerQueueLength { get; set; } - - /// - /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. - /// (Default = 0). - /// - public int? MinimumPeerFreeUploadSlots { get; set; } - - /// - /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). - /// - public int? MinimumPeerUploadSpeed { get; set; } - - /// - /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1). - /// - public int? MinimumResponseFileCount { get; set; } - - /// - /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100). - /// - public int? ResponseLimit { get; set; } - - /// - /// Gets or sets the search text. - /// - public string SearchText { get; set; } - - /// - /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15). - /// - /// The timeout duration is from the time of the last response. - public int? SearchTimeout { get; set; } - - /// - /// Gets or sets the search token. - /// - public int? Token { get; set; } - - /// - /// Maps to a new instance of . - /// - /// - /// - /// - /// - /// - public SearchOptions ToSearchOptions( - Func responseFilter = null, - Func fileFilter = null, - Action stateChanged = null, - Action 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 (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/. -// - -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 (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/. -// - -namespace slskd.Search -{ - using System.Collections.Generic; - using System.Linq; - - public class Response - { - public int FileCount { get; init; } - public ICollection Files { get; init; } = new List(); - public int FreeUploadSlots { get; init; } - public int LockedFileCount { get; init; } - public ICollection LockedFiles { get; init; } = new List(); - 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 (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/. -// - -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 Responses { get; set; } = new List(); - - [JsonIgnore] - public string ResponsesJson - { - get => JsonSerializer.Serialize(Responses); - set - { - Responses = JsonSerializer.Deserialize>(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 (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/. -// - -namespace slskd.Search -{ - using System; - using System.Linq; - using Soulseek; - - public static class Extensions - { - /// - /// Returns a copy of the specified with the specified actions bound, while retaining the existing actions. - /// - /// - /// - /// - /// - public static SearchOptions WithActions( - this SearchOptions options, - Action stateChanged = null, - Action 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); - }); - } - - /// - /// Returns a copy of the specified with the specified filter delegates overridden. - /// - /// - /// - /// - /// - public static SearchOptions WithFilters( - this SearchOptions options, - Func responseFilter = null, - Func 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); - } - - /// - /// Creates a projection over the specified which omits responses. - /// - /// - /// - public static IQueryable WithoutResponses(this IQueryable 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 (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/. -// - -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; - - /// - /// Handles the lifecycle and persistence of searches. - /// - public interface ISearchService - { - /// - /// Performs a search for the specified and . - /// - /// A unique identifier for the search. - /// The search query. - /// The search scope. - /// Search options. - /// The completed search. - Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); - - /// - /// Finds a single search matching the specified . - /// - /// The expression to use to match searches. - /// A value indicating whether to include search responses in the result. - /// The found search, or default if not found. - /// Thrown an expression is not supplied. - Task FindAsync(Expression> expression, bool includeResponses = false); - - /// - /// Returns a list of all completed and in-progress searches, with responses omitted. - /// - /// An optional expression used to match searches. - /// The list of searches matching the specified expression. - Task> ListAsync(Expression> expression = null); - - /// - /// Cancels the search matching the specified , if it is in progress. - /// - /// The unique identifier for the search. - /// A value indicating whether the search was sucessfully cancelled. - 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 (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/. -// - -namespace slskd.Search -{ - using Microsoft.EntityFrameworkCore; - - public class SearchDbContext : DbContext - { - public SearchDbContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } - - public DbSet 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 (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/. -// - -namespace slskd.Search -{ - using System; - using Microsoft.Extensions.Caching.Memory; - using Soulseek; - - /// - /// Caches undelivered search responses. - /// - public class SearchResponseCache : ISearchResponseCache - { - /// - /// Initializes a new instance of the class. - /// - public SearchResponseCache() - { - Cache = new MemoryCache(new MemoryCacheOptions()); - } - - private IMemoryCache Cache { get; } - - /// - /// Caches or updates a response. - /// - /// The token for which the response is to be added or updated. - /// The response and context to cache. - public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) - { - Cache.Set(responseToken, response, TimeSpan.FromMinutes(3)); - } - - /// - /// Attempts to fetch a cached response and context for the specified . - /// - /// The token for the cached response. - /// The cached response and context, if present. - /// A value indicating whether a response for the specified responseToken is cached. - public bool TryGet(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) - { - return Cache.TryGetValue(responseToken, out response); - } - - /// - /// Attempts to remove a cached Soulseek.SearchResponse and context for the specified . - /// - /// The token for the cached response. - /// The cached response and context, if present. - /// A value indicating whether a response for the specified responseToken was removed. - 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 (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/. -// - -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; - - /// - /// Handles the lifecycle and persistence of searches. - /// - public class SearchService : ISearchService - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// The database context to use. - /// The logger. - public SearchService( - IOptionsMonitor optionsMonitor, - ISoulseekClient soulseekClient, - IDbContextFactory contextFactory, - ILogger log) - { - OptionsMonitor = optionsMonitor; - Client = soulseekClient; - ContextFactory = contextFactory; - Log = log; - } - - private ConcurrentDictionary CancellationTokens { get; } - = new ConcurrentDictionary(); - - private IOptionsMonitor OptionsMonitor { get; } - private ISoulseekClient Client { get; } - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; set; } - - /// - /// Performs a search for the specified and . - /// - /// A unique identifier for the search. - /// The search query. - /// The search scope. - /// Search options. - /// The completed search. - public async Task 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(); - - 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 _); - } - } - - /// - /// Finds a single search matching the specified . - /// - /// The expression to use to match searches. - /// A value indicating whether to include search responses in the result. - /// The found search, or default if not found. - /// Thrown an expression is not supplied. - public Task FindAsync(Expression> 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(); - } - - /// - /// Returns a list of all completed and in-progress searches, with responses omitted. - /// - /// An optional expression used to match searches. - /// The list of searches matching the specified expression. - public Task> ListAsync(Expression> expression = null) - { - expression ??= s => true; - using var context = ContextFactory.CreateDbContext(); - return context.Searches.Where(expression).WithoutResponses().ToListAsync(); - } - - /// - /// Cancels the search matching the specified , if it is in progress. - /// - /// The unique identifier for the search. - /// A value indicating whether the search was sucessfully cancelled. - 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 -- cgit v1.2.3