From e6326c6d27c9e6aca60fed2e313d5e62c46ca5d2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 31 May 2021 12:57:36 -0500 Subject: move stuff around again --- .../Core/Search/Controllers/SearchesController.cs | 136 -------------- src/slskd/Core/Search/ISearchService.cs | 66 +++++++ .../Core/Search/Persistence/SearchDbContext.cs | 32 ---- src/slskd/Core/Search/SearchDbContext.cs | 32 ++++ src/slskd/Core/Search/SearchService.cs | 204 ++++++++++++++++++++ src/slskd/Core/Search/Services/ISearchService.cs | 66 ------- src/slskd/Core/Search/Services/SearchService.cs | 205 --------------------- 7 files changed, 302 insertions(+), 439 deletions(-) delete mode 100644 src/slskd/Core/Search/Controllers/SearchesController.cs create mode 100644 src/slskd/Core/Search/ISearchService.cs delete mode 100644 src/slskd/Core/Search/Persistence/SearchDbContext.cs create mode 100644 src/slskd/Core/Search/SearchDbContext.cs create mode 100644 src/slskd/Core/Search/SearchService.cs delete mode 100644 src/slskd/Core/Search/Services/ISearchService.cs delete mode 100644 src/slskd/Core/Search/Services/SearchService.cs (limited to 'src') diff --git a/src/slskd/Core/Search/Controllers/SearchesController.cs b/src/slskd/Core/Search/Controllers/SearchesController.cs deleted file mode 100644 index 18bdba15..00000000 --- a/src/slskd/Core/Search/Controllers/SearchesController.cs +++ /dev/null @@ -1,136 +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 System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using slskd.API.DTO; - 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/Core/Search/ISearchService.cs b/src/slskd/Core/Search/ISearchService.cs new file mode 100644 index 00000000..d696617d --- /dev/null +++ b/src/slskd/Core/Search/ISearchService.cs @@ -0,0 +1,66 @@ +// +// 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/Core/Search/Persistence/SearchDbContext.cs b/src/slskd/Core/Search/Persistence/SearchDbContext.cs deleted file mode 100644 index efb2fdd6..00000000 --- a/src/slskd/Core/Search/Persistence/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/Core/Search/SearchDbContext.cs b/src/slskd/Core/Search/SearchDbContext.cs new file mode 100644 index 00000000..efb2fdd6 --- /dev/null +++ b/src/slskd/Core/Search/SearchDbContext.cs @@ -0,0 +1,32 @@ +// +// 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/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs new file mode 100644 index 00000000..84cfd756 --- /dev/null +++ b/src/slskd/Core/Search/SearchService.cs @@ -0,0 +1,204 @@ +// +// 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.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; + + /// + /// Handles the lifecycle and persistence of searches. + /// + public class SearchService : ISearchService + { + /// + /// Initializes a new instance of the class. + /// + /// The client instance to use. + /// The database context to use. + /// The logger. + public SearchService( + ISoulseekClient client, + IDbContextFactory contextFactory, + ILogger log) + { + Client = client; + ContextFactory = contextFactory; + Log = log; + } + + private ConcurrentDictionary CancellationTokens { get; } + = new ConcurrentDictionary(); + + 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 diff --git a/src/slskd/Core/Search/Services/ISearchService.cs b/src/slskd/Core/Search/Services/ISearchService.cs deleted file mode 100644 index d696617d..00000000 --- a/src/slskd/Core/Search/Services/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/Core/Search/Services/SearchService.cs b/src/slskd/Core/Search/Services/SearchService.cs deleted file mode 100644 index e3c1bbef..00000000 --- a/src/slskd/Core/Search/Services/SearchService.cs +++ /dev/null @@ -1,205 +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.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; - - /// - /// Handles the lifecycle and persistence of searches. - /// - public class SearchService : ISearchService - { - /// - /// Initializes a new instance of the class. - /// - /// The client instance to use. - /// The database context to use. - /// The logger. - public SearchService( - ISoulseekClient client, - IDbContextFactory contextFactory, - ILogger log) - { - Client = client; - ContextFactory = contextFactory; - Log = log; - } - - private ConcurrentDictionary CancellationTokens { get; } - = new ConcurrentDictionary(); - - 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. - /// A value indicating whether to include search responses in the result. - /// 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