// // 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.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using slskd.Search.API; 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( IHubContext searchHub, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IApplication application, IDbContextFactory contextFactory, ILogger log) { SearchHub = searchHub; OptionsMonitor = optionsMonitor; Client = soulseekClient; Application = application; ContextFactory = contextFactory; Log = log; } private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); private IOptionsMonitor OptionsMonitor { get; } private IApplication Application { get; } private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } private ILogger Log { get; set; } private IHubContext SearchHub { 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) => UpdateSearchResponses(search, args.Search, args.Response)); 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 _); Application.CollectGarbage(); } } /// /// 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; SearchHub.BroadcastUpdateAsync(search); SaveSearchState(search); } } private void UpdateSearchResponses(Search search, SoulseekSearch soulseekSearch, Soulseek.SearchResponse response) { if (CancellationTokens.ContainsKey(search.Id)) { SearchHub.BroadcastResponseAsync(search.Id, response); UpdateSearchState(search, soulseekSearch); } } private void SaveSearchState(Search search) { var context = ContextFactory.CreateDbContext(); context.Update(search); context.SaveChanges(); } } }