diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-05-28 15:02:22 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2021-05-28 15:02:22 -0500 |
| commit | ef5371276a7293d464fd058dcfa903072fae67e8 (patch) | |
| tree | 1ebc5b570e15634fd749b7194c5f463540f0dce2 /src | |
| parent | 770e931191983638dd3c422720af014779ad75ad (diff) | |
| download | slskd-ef5371276a7293d464fd058dcfa903072fae67e8.tar.gz | |
polish SearchService
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Core/Search/ISearchService.cs | 31 | ||||
| -rw-r--r-- | src/slskd/Core/Search/SearchService.cs | 137 | ||||
| -rw-r--r-- | src/slskd/Core/Search/Services/ISearchService.cs | 67 | ||||
| -rw-r--r-- | src/slskd/Core/Search/Services/SearchService.cs | 203 |
4 files changed, 270 insertions, 168 deletions
diff --git a/src/slskd/Core/Search/ISearchService.cs b/src/slskd/Core/Search/ISearchService.cs deleted file mode 100644 index 44d3edb9..00000000 --- a/src/slskd/Core/Search/ISearchService.cs +++ /dev/null @@ -1,31 +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.Linq.Expressions; - using System.Threading.Tasks; - using Soulseek; - - public interface ISearchService - { - Task<Search> SearchAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); - bool TryCancel(Guid id); - Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false); - } -} diff --git a/src/slskd/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs deleted file mode 100644 index 0fd4d6d5..00000000 --- a/src/slskd/Core/Search/SearchService.cs +++ /dev/null @@ -1,137 +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.Expressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; - using Soulseek; - - public class SearchService : ISearchService - { - public SearchService( - IDbContextFactory<SearchDbContext> contextFactory, - ILogger<SearchService> log, - ISoulseekClient client) - { - ContextFactory = contextFactory; - Log = log; - Client = client; - } - - private IDbContextFactory<SearchDbContext> ContextFactory { get; } - private ILogger<SearchService> Log { get; set; } - private ISoulseekClient Client { get; } - - private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } - = new ConcurrentDictionary<Guid, CancellationTokenSource>(); - - public async Task<Search> SearchAsync(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) => UpdateState(search, args.Search), (args) => UpdateState(search, args.Search)); - - 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); - - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - search.Responses = responses; - - return search; - } - - public bool TryCancel(Guid id) - { - if (CancellationTokens.TryGetValue(id, out var cts)) - { - cts.Cancel(); - return true; - } - - return false; - } - - public async Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = true) - { - using var context = ContextFactory.CreateDbContext(); - var search = await context - .Searches - .FirstOrDefaultAsync(expression); - - if (!includeResponses) - { - - } - return search; - } - - private void UpdateState(Search search, Soulseek.Search soulseekSearch) - { - _ = Task.Run(async () => - { - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - - var context = ContextFactory.CreateDbContext(); - - context.Update(search); - await context.SaveChangesAsync(); - }).ContinueWith(task => - Log.LogError(task.Exception, "Failed to update state of {SearchId}", search.Id), - TaskContinuationOptions.OnlyOnFaulted); - } - } -} diff --git a/src/slskd/Core/Search/Services/ISearchService.cs b/src/slskd/Core/Search/Services/ISearchService.cs new file mode 100644 index 00000000..f56f2ab3 --- /dev/null +++ b/src/slskd/Core/Search/Services/ISearchService.cs @@ -0,0 +1,67 @@ +// <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> + /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param> + /// <returns>The completed search.</returns> + Task<Search> CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null, bool includeResponses = true); + + /// <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..7b6f0f2b --- /dev/null +++ b/src/slskd/Core/Search/Services/SearchService.cs @@ -0,0 +1,203 @@ +// <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, bool includeResponses = true) + { + 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); + + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + + if (includeResponses) + { + search.Responses = responses; + } + + 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) + { + _ = Task.Run(async () => + { + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + + var context = ContextFactory.CreateDbContext(); + + context.Update(search); + await context.SaveChangesAsync(); + }).ContinueWith(task => + Log.LogError(task.Exception, "Failed to update state of {SearchId}", search.Id), + TaskContinuationOptions.OnlyOnFaulted); + } + } +}
\ No newline at end of file |
