diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-06-14 20:03:36 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2021-06-14 20:03:36 -0500 |
| commit | 050be311e68bb316cfc40fbd23bfd5a812e1a060 (patch) | |
| tree | 1476cba9e90845f224bbc0a380e4633697e1306e /src/slskd/Core/Search | |
| parent | 4cf8f8fa862b08131e9cc51c4bad3d6c9838342b (diff) | |
| download | slskd-050be311e68bb316cfc40fbd23bfd5a812e1a060.tar.gz | |
move stuff around
Diffstat (limited to 'src/slskd/Core/Search')
| -rw-r--r-- | src/slskd/Core/Search/Domain/Response.cs | 51 | ||||
| -rw-r--r-- | src/slskd/Core/Search/Domain/Search.cs | 60 | ||||
| -rw-r--r-- | src/slskd/Core/Search/Extensions.cs | 94 | ||||
| -rw-r--r-- | src/slskd/Core/Search/ISearchService.cs | 66 | ||||
| -rw-r--r-- | src/slskd/Core/Search/SearchDbContext.cs | 32 | ||||
| -rw-r--r-- | src/slskd/Core/Search/SearchResponseCache.cs | 77 | ||||
| -rw-r--r-- | src/slskd/Core/Search/SearchService.cs | 204 |
7 files changed, 0 insertions, 584 deletions
diff --git a/src/slskd/Core/Search/Domain/Response.cs b/src/slskd/Core/Search/Domain/Response.cs deleted file mode 100644 index ea2e8993..00000000 --- a/src/slskd/Core/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/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs deleted file mode 100644 index b93c62cb..00000000 --- a/src/slskd/Core/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/Core/Search/Extensions.cs b/src/slskd/Core/Search/Extensions.cs deleted file mode 100644 index d52975d2..00000000 --- a/src/slskd/Core/Search/Extensions.cs +++ /dev/null @@ -1,94 +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> - /// 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/ISearchService.cs b/src/slskd/Core/Search/ISearchService.cs deleted file mode 100644 index d696617d..00000000 --- a/src/slskd/Core/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/Core/Search/SearchDbContext.cs b/src/slskd/Core/Search/SearchDbContext.cs deleted file mode 100644 index efb2fdd6..00000000 --- a/src/slskd/Core/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/Core/Search/SearchResponseCache.cs b/src/slskd/Core/Search/SearchResponseCache.cs deleted file mode 100644 index c31a3a9b..00000000 --- a/src/slskd/Core/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/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs deleted file mode 100644 index 84cfd756..00000000 --- a/src/slskd/Core/Search/SearchService.cs +++ /dev/null @@ -1,204 +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> - -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> - /// <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 |
