From 2ed141e2f55207cce5ab80acc8477402fd5aae94 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 May 2021 12:26:31 -0500 Subject: add DbContext and domain for search --- src/slskd/Core/DbContext.cs | 32 ++++++++++++++++ src/slskd/Core/Search/Domain/Search.cs | 53 ++++++++++++++++++++++++++ src/slskd/Core/Search/Domain/SearchResponse.cs | 33 ++++++++++++++++ src/slskd/Core/Search/ISearchTracker.cs | 2 +- src/slskd/Core/Search/SearchTracker.cs | 4 +- 5 files changed, 121 insertions(+), 3 deletions(-) create mode 100644 src/slskd/Core/DbContext.cs create mode 100644 src/slskd/Core/Search/Domain/Search.cs create mode 100644 src/slskd/Core/Search/Domain/SearchResponse.cs (limited to 'src') diff --git a/src/slskd/Core/DbContext.cs b/src/slskd/Core/DbContext.cs new file mode 100644 index 00000000..ba4e50a6 --- /dev/null +++ b/src/slskd/Core/DbContext.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 +{ + using Microsoft.EntityFrameworkCore; + using slskd.Search; + + public class AppDbContext : DbContext + { + public AppDbContext(DbContextOptions options) + : base(options) + { + } + + public DbSet Searches { get; set; } + } +} diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs new file mode 100644 index 00000000..10cbdc9d --- /dev/null +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -0,0 +1,53 @@ +// +// 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 Soulseek; + + public class Search + { + public Guid Id { get; init; } + + /// + /// Gets the text for which to search. + /// + public string SearchText { get; set; } + + /// + /// Gets the state of the search. + /// + public SearchStates State { get; set; } + + /// + /// Gets the unique identifier for the search. + /// + public int Token { get; set; } + + public static Search FromSoulseekSearch(Soulseek.Search s) + { + return new Search + { + Id = Guid.NewGuid(), + SearchText = s.SearchText, + State = s.State, + Token = s.Token, + }; + } + } +} diff --git a/src/slskd/Core/Search/Domain/SearchResponse.cs b/src/slskd/Core/Search/Domain/SearchResponse.cs new file mode 100644 index 00000000..b9bafc7b --- /dev/null +++ b/src/slskd/Core/Search/Domain/SearchResponse.cs @@ -0,0 +1,33 @@ +// +// 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.Text.Json; + + /// + /// A response to a file search. + /// + public class SearchResponseRecord + { + public Guid SearchId { get; init; } + + public string ResponseJson { get; set; } + public Soulseek.SearchResponse Response => new Lazy(() => JsonSerializer.Deserialize(ResponseJson)).Value; + } +} \ No newline at end of file diff --git a/src/slskd/Core/Search/ISearchTracker.cs b/src/slskd/Core/Search/ISearchTracker.cs index c2bdcbaa..c962138e 100644 --- a/src/slskd/Core/Search/ISearchTracker.cs +++ b/src/slskd/Core/Search/ISearchTracker.cs @@ -29,7 +29,7 @@ namespace slskd.Search /// /// Gets active searches. /// - ConcurrentDictionary Searches { get; } + ConcurrentDictionary Searches { get; } /// /// Adds or updates a tracked search. diff --git a/src/slskd/Core/Search/SearchTracker.cs b/src/slskd/Core/Search/SearchTracker.cs index c4f124ca..b1ab2b18 100644 --- a/src/slskd/Core/Search/SearchTracker.cs +++ b/src/slskd/Core/Search/SearchTracker.cs @@ -29,8 +29,8 @@ namespace slskd.Search /// /// Gets active searches. /// - public ConcurrentDictionary Searches { get; private set; } = - new ConcurrentDictionary(); + public ConcurrentDictionary Searches { get; private set; } = + new ConcurrentDictionary(); /// /// Adds or updates a tracked search. -- cgit v1.2.3 From 7588c5d8281213de2714d817c7e861cc5fb661e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 May 2021 12:26:58 -0500 Subject: add EF --- src/slskd/slskd.csproj | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 5d9e477c..8bd0e2c3 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -49,6 +49,8 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + + -- cgit v1.2.3 From ea78f7f0c5b0858f15a1af8a700100d7ae101ae1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 May 2021 12:33:27 -0500 Subject: add SearchDbContext --- src/slskd/API/Controllers/SearchesController.cs | 2 +- src/slskd/Core/DbContext.cs | 32 ------------------------- src/slskd/Core/Search/SearchDbContext.cs | 31 ++++++++++++++++++++++++ src/slskd/Program.cs | 10 ++++---- src/slskd/Startup.cs | 14 ++++++++--- 5 files changed, 48 insertions(+), 41 deletions(-) delete mode 100644 src/slskd/Core/DbContext.cs create mode 100644 src/slskd/Core/Search/SearchDbContext.cs (limited to 'src') diff --git a/src/slskd/API/Controllers/SearchesController.cs b/src/slskd/API/Controllers/SearchesController.cs index 4a3dc7ab..6d322bda 100644 --- a/src/slskd/API/Controllers/SearchesController.cs +++ b/src/slskd/API/Controllers/SearchesController.cs @@ -102,7 +102,7 @@ namespace slskd.API.Controllers /// A matching search was not found. [HttpGet("{id}")] [Authorize] - [ProducesResponseType(typeof(Search), 200)] + [ProducesResponseType(typeof(Soulseek.Search), 200)] [ProducesResponseType(404)] public IActionResult GetById([FromRoute]Guid id) { diff --git a/src/slskd/Core/DbContext.cs b/src/slskd/Core/DbContext.cs deleted file mode 100644 index ba4e50a6..00000000 --- a/src/slskd/Core/DbContext.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 -{ - using Microsoft.EntityFrameworkCore; - using slskd.Search; - - public class AppDbContext : DbContext - { - public AppDbContext(DbContextOptions options) - : base(options) - { - } - - 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..4832bc17 --- /dev/null +++ b/src/slskd/Core/Search/SearchDbContext.cs @@ -0,0 +1,31 @@ +// +// 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) + { + } + + public DbSet Searches { get; set; } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 7a526fb2..7ccebe6e 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -62,11 +62,6 @@ namespace slskd /// public static readonly string DefaultConfigurationFile = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.yml"); - /// - /// The default XML documentation filename. - /// - public static readonly string DefaultXmlDocumentationFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml"); - /// /// The default incomplete download directory. /// @@ -87,6 +82,11 @@ namespace slskd /// public static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_"; + /// + /// The default XML documentation filename. + /// + public static readonly string XmlDocumentationFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml"); + /// /// Gets the assembly version of the application. /// diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index f073117c..bd2e8963 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -24,6 +24,7 @@ namespace slskd using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc.ApiExplorer; + using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; @@ -149,13 +150,13 @@ namespace slskd Version = "v0", }); - if (File.Exists(Program.DefaultXmlDocumentationFile)) + if (File.Exists(Program.XmlDocumentationFile)) { - options.IncludeXmlComments(Program.DefaultXmlDocumentationFile); + options.IncludeXmlComments(Program.XmlDocumentationFile); } else { - logger.Warning($"Unable to find XML documentation in {Program.DefaultXmlDocumentationFile}, Swagger will not include metadata"); + logger.Warning($"Unable to find XML documentation in {Program.XmlDocumentationFile}, Swagger will not include metadata"); } }); } @@ -165,6 +166,13 @@ namespace slskd services.AddSystemMetrics(); } + services.AddDbContextFactory(options => + { + options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "search.db")}"); + }); + + services.AddTransient(p => p.GetRequiredService>().CreateDbContext()); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From 752849c5ca06b31b951d4c3de00e5acd52946238 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 May 2021 22:45:06 -0500 Subject: rough in SearchService --- src/slskd/Core/Search/Domain/Search.cs | 16 ++--- src/slskd/Core/Search/ISearchService.cs | 30 +++++++++ src/slskd/Core/Search/SearchService.cs | 110 ++++++++++++++++++++++++++++++++ 3 files changed, 144 insertions(+), 12 deletions(-) create mode 100644 src/slskd/Core/Search/ISearchService.cs create mode 100644 src/slskd/Core/Search/SearchService.cs (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs index 10cbdc9d..9b54d367 100644 --- a/src/slskd/Core/Search/Domain/Search.cs +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -22,7 +22,10 @@ namespace slskd.Search public class Search { - public Guid Id { get; init; } + public Guid Id { get; init; } = Guid.NewGuid(); + + public DateTime StartedAt { get; init; } = DateTime.UtcNow; + public DateTime? EndedAt { get; set; } /// /// Gets the text for which to search. @@ -38,16 +41,5 @@ namespace slskd.Search /// Gets the unique identifier for the search. /// public int Token { get; set; } - - public static Search FromSoulseekSearch(Soulseek.Search s) - { - return new Search - { - Id = Guid.NewGuid(), - 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 new file mode 100644 index 00000000..0182beab --- /dev/null +++ b/src/slskd/Core/Search/ISearchService.cs @@ -0,0 +1,30 @@ +// +// 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.Threading.Tasks; + using Soulseek; + + public interface ISearchService + { + Task BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null); + bool TryCancel(Guid id); + Task FindAsync(Guid id); + } +} diff --git a/src/slskd/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs new file mode 100644 index 00000000..0f69f632 --- /dev/null +++ b/src/slskd/Core/Search/SearchService.cs @@ -0,0 +1,110 @@ +// +// 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.Threading; + using System.Threading.Tasks; + using Soulseek; + + public class SearchService : ISearchService + { + public SearchService(SearchDbContext context, ISoulseekClient client) + { + Context = context; + Client = client; + + Client.SearchStateChanged += Client_SearchStateChanged; + Client.SearchRequestReceived += Client_SearchRequestReceived; + } + + private void Client_SearchRequestReceived(object sender, SearchRequestEventArgs e) + { + throw new NotImplementedException(); + } + + private void Client_SearchStateChanged(object sender, SearchStateChangedEventArgs e) + { + throw new NotImplementedException(); + } + + private SearchDbContext Context { get; } + private ISoulseekClient Client { get; } + private ConcurrentDictionary Lookup { get; } + = new ConcurrentDictionary(); + private ConcurrentDictionary InProgress { get; } + = new ConcurrentDictionary(); + + public async Task BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null) + { + scope = scope ?? SearchScope.Network; + var token = Client.GetNextToken(); + options = options ?? new SearchOptions(); + var cts = new CancellationTokenSource(); + var id = Guid.NewGuid(); + + var record = new Search() + { + SearchText = query.SearchText, + Token = token, + Id = id, + State = SearchStates.Requested, + }; + + Context.Add(record); + await Context.SaveChangesAsync(); + + InProgress.TryAdd(token, cts); + Lookup.TryAdd(id, token); + + _ = Client.SearchAsync(query, scope, token, options, cancellationToken: cts.Token).ContinueWith(async task => + { + try + { + var result = await task; + + // todo: update db with status and end time + } + finally + { + InProgress.TryRemove(token, out _); + Lookup.TryRemove(id, out _); + } + }); + + return id; + } + + public bool TryCancel(Guid id) + { + if (Lookup.TryGetValue(id, out var token) && InProgress.TryGetValue(token, out var cts)) + { + cts.Cancel(); + return true; + } + + return false; + } + + public Task FindAsync(Guid id) + { + return Context.Searches.FindAsync(id).AsTask(); + } + } +} -- cgit v1.2.3 From 611174cf4a2a2eccd2636df5d96bcf1557f29f3c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 May 2021 21:02:00 -0500 Subject: bump to Soulseek.NET 3.0.0-pre --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 8bd0e2c3..18f94fd6 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -67,7 +67,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 5a74a2339b2546e82f5e410571966af2e6459062 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 May 2021 23:45:11 -0500 Subject: flesh out domain --- src/slskd/Core/Search/Domain/File.cs | 63 ++++++++++++++++++++++++++ src/slskd/Core/Search/Domain/Search.cs | 5 ++ src/slskd/Core/Search/Domain/SearchResponse.cs | 49 ++++++++++++++++---- 3 files changed, 109 insertions(+), 8 deletions(-) create mode 100644 src/slskd/Core/Search/Domain/File.cs (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/File.cs b/src/slskd/Core/Search/Domain/File.cs new file mode 100644 index 00000000..9dd7b5a0 --- /dev/null +++ b/src/slskd/Core/Search/Domain/File.cs @@ -0,0 +1,63 @@ +// +// 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.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Text.Json.Serialization; + + public class File + { + [ForeignKey("SearchResponse")] + [JsonIgnore] + public Guid SearchResponseId { get; set; } + + [Key] + public Guid Id { get; set; } + 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(Soulseek.File file, Guid searchResponseId, bool isLocked = false) + { + return new File() + { + SearchResponseId = searchResponseId, + Id = Guid.NewGuid(), + 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, + IsLocked = isLocked, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs index 9b54d367..fcb11a04 100644 --- a/src/slskd/Core/Search/Domain/Search.cs +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -18,10 +18,13 @@ namespace slskd.Search { using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; using Soulseek; public class Search { + [Key] public Guid Id { get; init; } = Guid.NewGuid(); public DateTime StartedAt { get; init; } = DateTime.UtcNow; @@ -41,5 +44,7 @@ namespace slskd.Search /// Gets the unique identifier for the search. /// public int Token { get; set; } + + public ICollection Responses { get; set; } = new List(); } } diff --git a/src/slskd/Core/Search/Domain/SearchResponse.cs b/src/slskd/Core/Search/Domain/SearchResponse.cs index b9bafc7b..cb3196ae 100644 --- a/src/slskd/Core/Search/Domain/SearchResponse.cs +++ b/src/slskd/Core/Search/Domain/SearchResponse.cs @@ -18,16 +18,49 @@ namespace slskd.Search { using System; - using System.Text.Json; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Linq; + using System.Text.Json.Serialization; - /// - /// A response to a file search. - /// - public class SearchResponseRecord + public class SearchResponse { - public Guid SearchId { get; init; } + [ForeignKey("Search")] + [JsonIgnore] + public Guid SearchId { get; set; } - public string ResponseJson { get; set; } - public Soulseek.SearchResponse Response => new Lazy(() => JsonSerializer.Deserialize(ResponseJson)).Value; + [Key] + public Guid Id { get; init; } = Guid.NewGuid(); + public int FileCount { get; init; } + public ICollection Files { get; init; } = new List(); + public int FreeUploadSlots { get; init; } + public int LockedFileCount { get; init; } + public long QueueLength { get; init; } + public int Token { get; init; } + public int UploadSpeed { get; init; } + public string Username { get; init; } + + public static SearchResponse FromSoulseekSearchResponse(Soulseek.SearchResponse searchResponse, Guid searchId) + { + var id = Guid.NewGuid(); + + var files = searchResponse.Files.Select(file => File.FromSoulseekFile(file, id, isLocked: false)).ToList(); + files.AddRange(searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file, id, isLocked: true))); + + return new SearchResponse() + { + SearchId = searchId, + Id = id, + FileCount = searchResponse.FileCount, + Files = files, + FreeUploadSlots = searchResponse.FreeUploadSlots, + LockedFileCount = searchResponse.LockedFileCount, + QueueLength = searchResponse.QueueLength, + Token = searchResponse.Token, + UploadSpeed = searchResponse.UploadSpeed, + Username = searchResponse.Username, + }; + } } } \ No newline at end of file -- cgit v1.2.3 From 0354b842141d354a82072aee78000f87ce8b348f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 May 2021 23:47:54 -0500 Subject: add responses and files to db context --- src/slskd/Core/Search/SearchDbContext.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Search/SearchDbContext.cs b/src/slskd/Core/Search/SearchDbContext.cs index 4832bc17..96d62432 100644 --- a/src/slskd/Core/Search/SearchDbContext.cs +++ b/src/slskd/Core/Search/SearchDbContext.cs @@ -24,8 +24,11 @@ namespace slskd.Search public SearchDbContext(DbContextOptions options) : base(options) { + Database.EnsureCreated(); } public DbSet Searches { get; set; } + public DbSet SearchResponses { get; set; } + public DbSet Files { get; set; } } } -- cgit v1.2.3 From 8feb789ba5dd4729ea0a7fbafdccd86e9e06f74c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 May 2021 23:48:13 -0500 Subject: rough in SearchService --- src/slskd/Core/Search/ISearchService.cs | 5 +- src/slskd/Core/Search/SearchService.cs | 94 ++++++++++++++++++++++----------- 2 files changed, 67 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/ISearchService.cs b/src/slskd/Core/Search/ISearchService.cs index 0182beab..1936b30f 100644 --- a/src/slskd/Core/Search/ISearchService.cs +++ b/src/slskd/Core/Search/ISearchService.cs @@ -18,13 +18,14 @@ namespace slskd.Search { using System; + using System.Linq.Expressions; using System.Threading.Tasks; using Soulseek; public interface ISearchService { - Task BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null); + Task<(Guid Id, Task Completed)> BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null, Guid? id = null); bool TryCancel(Guid id); - Task FindAsync(Guid id); + Task FindAsync(Expression> expression, bool includeResponses = false); } } diff --git a/src/slskd/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs index 0f69f632..f0632211 100644 --- a/src/slskd/Core/Search/SearchService.cs +++ b/src/slskd/Core/Search/SearchService.cs @@ -19,76 +19,86 @@ namespace slskd.Search { using System; using System.Collections.Concurrent; + using System.Linq.Expressions; + using System.Text.Json; using System.Threading; using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; using Soulseek; public class SearchService : ISearchService { - public SearchService(SearchDbContext context, ISoulseekClient client) + public SearchService(IDbContextFactory contextFactory, ISoulseekClient client) { - Context = context; + ContextFactory = contextFactory; Client = client; - - Client.SearchStateChanged += Client_SearchStateChanged; - Client.SearchRequestReceived += Client_SearchRequestReceived; } - private void Client_SearchRequestReceived(object sender, SearchRequestEventArgs e) - { - throw new NotImplementedException(); - } - - private void Client_SearchStateChanged(object sender, SearchStateChangedEventArgs e) - { - throw new NotImplementedException(); - } - - private SearchDbContext Context { get; } + private IDbContextFactory ContextFactory { get; } private ISoulseekClient Client { get; } private ConcurrentDictionary Lookup { get; } = new ConcurrentDictionary(); private ConcurrentDictionary InProgress { get; } = new ConcurrentDictionary(); - public async Task BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null) + public async Task<(Guid Id, Task Completed)> BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null, Guid? id = null) { scope = scope ?? SearchScope.Network; var token = Client.GetNextToken(); - options = options ?? new SearchOptions(); + id = id ?? Guid.NewGuid(); + var cts = new CancellationTokenSource(); - var id = Guid.NewGuid(); var record = new Search() { SearchText = query.SearchText, Token = token, - Id = id, + Id = id.Value, State = SearchStates.Requested, + StartedAt = DateTime.UtcNow, }; - Context.Add(record); - await Context.SaveChangesAsync(); + options = options ?? new SearchOptions(stateChanged: (args) => + { + record.State = args.Search.State; + ContextFactory.CreateDbContext().Update(record); + }); + + using var context = ContextFactory.CreateDbContext(); + context.Add(record); + context.SaveChanges(); InProgress.TryAdd(token, cts); - Lookup.TryAdd(id, token); + Lookup.TryAdd(id.Value, token); + + var task = Client.SearchAsync(query, responseReceived: (response) => AddResponse(id.Value, response), scope, token, options, cancellationToken: cts.Token); - _ = Client.SearchAsync(query, scope, token, options, cancellationToken: cts.Token).ContinueWith(async task => + _ = task.ContinueWith(async task => { + Console.WriteLine($"Continued..."); + try { - var result = await task; + var search = await task; + record.State = search.State; + record.EndedAt = DateTime.UtcNow; + + Console.WriteLine($"Saving with state {record.State}"); - // todo: update db with status and end time + using var context = ContextFactory.CreateDbContext(); + context.Update(record); + context.SaveChanges(); + + Console.WriteLine($"Saved"); } finally { InProgress.TryRemove(token, out _); - Lookup.TryRemove(id, out _); + Lookup.TryRemove(id.Value, out _); } }); - return id; + return (id.Value, task); } public bool TryCancel(Guid id) @@ -102,9 +112,33 @@ namespace slskd.Search return false; } - public Task FindAsync(Guid id) + public async Task FindAsync(Expression> expression, bool includeResponses = true) + { + using var context = ContextFactory.CreateDbContext(); + var search = await context + .Searches + .Include(s => s.Responses) + .ThenInclude(r => r.Files) + .FirstOrDefaultAsync(expression); + + //if (search == default) + //{ + // return default; + //} + + //if (includeResponses) + //{ + // await context.Entry(search).Collection(s => s.Responses).LoadAsync(); + //} + + return search; + } + + private void AddResponse(Guid searchId, Soulseek.SearchResponse soulseekResponse) { - return Context.Searches.FindAsync(id).AsTask(); + using var context = ContextFactory.CreateDbContext(); + context.Add(SearchResponse.FromSoulseekSearchResponse(soulseekResponse, searchId)); + context.SaveChanges(); } } } -- cgit v1.2.3 From a95516adebf98c482f207cac4113e0e1e98eceba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 May 2021 23:48:29 -0500 Subject: disambiguate Search --- src/slskd/Core/Search/SearchResponseCache.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/SearchResponseCache.cs b/src/slskd/Core/Search/SearchResponseCache.cs index 6b223280..c31a3a9b 100644 --- a/src/slskd/Core/Search/SearchResponseCache.cs +++ b/src/slskd/Core/Search/SearchResponseCache.cs @@ -41,7 +41,7 @@ namespace slskd.Search /// /// 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, SearchResponse SearchResponse) response) + public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) { Cache.Set(responseToken, response, TimeSpan.FromMinutes(3)); } @@ -52,7 +52,7 @@ namespace slskd.Search /// 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, SearchResponse SearchResponse) response) + public bool TryGet(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) { return Cache.TryGetValue(responseToken, out response); } @@ -63,7 +63,7 @@ namespace slskd.Search /// 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, SearchResponse SearchResponse) response) + public bool TryRemove(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) { if (Cache.TryGetValue(responseToken, out response)) { -- cgit v1.2.3 From 019a77eaca48afa206381aafdcf97b292f71efd2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 May 2021 23:48:53 -0500 Subject: disambiguate Search --- src/slskd/Core/Service.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Service.cs b/src/slskd/Core/Service.cs index f46e6739..af6376af 100644 --- a/src/slskd/Core/Service.cs +++ b/src/slskd/Core/Service.cs @@ -371,9 +371,9 @@ namespace slskd /// The search token. /// The search query. /// A Task resolving a SearchResponse, or null. - private Task SearchResponseResolver(string username, int token, SearchQuery query) + private Task SearchResponseResolver(string username, int token, SearchQuery query) { - var defaultResponse = Task.FromResult(null); + var defaultResponse = Task.FromResult(null); // some bots continually query for very common strings. blacklist known names here. var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; @@ -394,7 +394,7 @@ namespace slskd { Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); - return Task.FromResult(new SearchResponse( + return Task.FromResult(new Soulseek.SearchResponse( SoulseekClient.Username, token, freeUploadSlots: 1, @@ -405,7 +405,7 @@ namespace slskd // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no // response will be sent to the requestor. - return Task.FromResult(null); + return Task.FromResult(null); } /// -- cgit v1.2.3 From ccc8ad7b0ce16d69161c70ab16d530027c2b78ce Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 26 May 2021 23:48:59 -0500 Subject: rough in controller and DI --- src/slskd/API/Controllers/SearchesController.cs | 20 +++++++++++++------- src/slskd/Startup.cs | 4 +++- 2 files changed, 16 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/API/Controllers/SearchesController.cs b/src/slskd/API/Controllers/SearchesController.cs index 6d322bda..d38d509e 100644 --- a/src/slskd/API/Controllers/SearchesController.cs +++ b/src/slskd/API/Controllers/SearchesController.cs @@ -43,12 +43,14 @@ namespace slskd.API.Controllers /// /// /// - public SearchesController(ISoulseekClient client, ISearchTracker tracker) + public SearchesController(ISoulseekClient client, ISearchTracker tracker, ISearchService searchService) { Client = client; Tracker = tracker; + SearchService = searchService; } + private ISearchService SearchService { get; } private ISoulseekClient Client { get; } private ISearchTracker Tracker { get; } @@ -62,7 +64,7 @@ namespace slskd.API.Controllers /// The search terminated abnormally. [HttpPost("")] [Authorize] - [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(400)] [ProducesResponseType(typeof(string), 500)] public async Task Post([FromBody]SearchRequest request) @@ -73,13 +75,16 @@ namespace slskd.API.Controllers responseReceived: (e) => Tracker.AddOrUpdate(id, e), stateChanged: (e) => Tracker.AddOrUpdate(id, e)); - var results = new ConcurrentBag(); + var results = new ConcurrentBag(); var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1)); try { - await Client.SearchAsync(SearchQuery.FromText(searchText), (r) => results.Add(r), SearchScope.Network, request.Token, options); + //await Client.SearchAsync(SearchQuery.FromText(searchText), (r) => results.Add(r), SearchScope.Network, request.Token, options); + var (guid, completed) = await SearchService.BeginAsync(SearchQuery.FromText(searchText), SearchScope.Network, id: id); + await completed; + return Ok(results); } catch (Exception ex) @@ -102,14 +107,15 @@ namespace slskd.API.Controllers /// A matching search was not found. [HttpGet("{id}")] [Authorize] - [ProducesResponseType(typeof(Soulseek.Search), 200)] + [ProducesResponseType(typeof(slskd.Search.Search), 200)] [ProducesResponseType(404)] - public IActionResult GetById([FromRoute]Guid id) + public async Task GetById([FromRoute]Guid id) { - Tracker.Searches.TryGetValue(id, out var search); + var search = await SearchService.FindAsync(search => search.Id == id); if (search == default) { + Console.WriteLine($"Search: {id} not found"); return NotFound(); } diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index bd2e8963..a4627114 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -150,7 +150,7 @@ namespace slskd Version = "v0", }); - if (File.Exists(Program.XmlDocumentationFile)) + if (System.IO.File.Exists(Program.XmlDocumentationFile)) { options.IncludeXmlComments(Program.XmlDocumentationFile); } @@ -181,6 +181,8 @@ namespace slskd services.AddSingleton(_ => new SharedFileCache(Options.Directories.Shared, 3600000)); + services.AddSingleton(); + services.AddHostedService(); services.AddSingleton(_ => Service.SoulseekClient); } -- cgit v1.2.3 From 3cdd58f0c5d5aaaac4eb4165512eab1b36c1ce3e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 09:12:47 -0500 Subject: init-only more props --- src/slskd/Core/Search/Domain/File.cs | 4 ++-- src/slskd/Core/Search/Domain/SearchResponse.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/File.cs b/src/slskd/Core/Search/Domain/File.cs index 9dd7b5a0..ee14dcff 100644 --- a/src/slskd/Core/Search/Domain/File.cs +++ b/src/slskd/Core/Search/Domain/File.cs @@ -26,10 +26,10 @@ namespace slskd.Search { [ForeignKey("SearchResponse")] [JsonIgnore] - public Guid SearchResponseId { get; set; } + public Guid SearchResponseId { get; init; } [Key] - public Guid Id { get; set; } + public Guid Id { get; init; } public int? BitDepth { get; init; } public int? BitRate { get; init; } public int Code { get; init; } diff --git a/src/slskd/Core/Search/Domain/SearchResponse.cs b/src/slskd/Core/Search/Domain/SearchResponse.cs index cb3196ae..894fe96c 100644 --- a/src/slskd/Core/Search/Domain/SearchResponse.cs +++ b/src/slskd/Core/Search/Domain/SearchResponse.cs @@ -28,7 +28,7 @@ namespace slskd.Search { [ForeignKey("Search")] [JsonIgnore] - public Guid SearchId { get; set; } + public Guid SearchId { get; init; } [Key] public Guid Id { get; init; } = Guid.NewGuid(); -- cgit v1.2.3 From 1738eeba4bf9942270b6c0c7481c2f6705588ed9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 09:13:09 -0500 Subject: add counts and mappers --- src/slskd/Core/Search/Domain/Search.cs | 54 ++++++++++++++++++++++++++++++---- 1 file changed, 49 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs index fcb11a04..b16c7e7c 100644 --- a/src/slskd/Core/Search/Domain/Search.cs +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -28,23 +28,67 @@ namespace slskd.Search public Guid Id { get; init; } = Guid.NewGuid(); public DateTime StartedAt { get; init; } = DateTime.UtcNow; - public DateTime? EndedAt { get; set; } + public DateTime? EndedAt { get; init; } + + /// + /// Gets the total number of files contained within received responses. + /// + public int FileCount { get; init; } + + /// + /// Gets the total number of locked files contained within received responses. + /// + public int LockedFileCount { get; init; } + + /// + /// Gets the current number of responses received. + /// + public int ResponseCount { get; init; } /// /// Gets the text for which to search. /// - public string SearchText { get; set; } + public string SearchText { get; init; } /// /// Gets the state of the search. /// - public SearchStates State { get; set; } + public SearchStates State { get; init; } /// /// Gets the unique identifier for the search. /// - public int Token { get; set; } + public int Token { get; init; } + + public ICollection Responses { get; init; } = new List(); + + public static Search FromSoulseekSearch(Soulseek.Search search) + { + return new Search() + { + FileCount = search.FileCount, + LockedFileCount = search.LockedFileCount, + ResponseCount = search.ResponseCount, + SearchText = search.SearchText, + State = search.State, + Token = search.Token, + }; + } - public ICollection Responses { get; set; } = new List(); + public Search WithSoulseekSearch(Soulseek.Search search) + { + return new Search() + { + Id = Id, + StartedAt = StartedAt, + EndedAt = EndedAt, + FileCount = search.FileCount, + LockedFileCount = search.LockedFileCount, + ResponseCount = search.ResponseCount, + SearchText = SearchText, + State = search.State, + Token = Token, + }; + } } } -- cgit v1.2.3 From dc0ce0fe06c99f4bf473541854081fdf07a8de7f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 09:13:32 -0500 Subject: add WithActions extension for options --- src/slskd/Core/Search/Extensions.cs | 65 +++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/slskd/Core/Search/Extensions.cs (limited to 'src') diff --git a/src/slskd/Core/Search/Extensions.cs b/src/slskd/Core/Search/Extensions.cs new file mode 100644 index 00000000..2ff1139c --- /dev/null +++ b/src/slskd/Core/Search/Extensions.cs @@ -0,0 +1,65 @@ +// +// 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 Soulseek; + + public static class Extensions + { + 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); + }); + } + } +} -- cgit v1.2.3 From 457de100a5a13f5583f47f2258ae07c0518bf3b6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 09:16:56 -0500 Subject: oops --- src/slskd/Core/Search/Domain/Search.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs index b16c7e7c..13f1dd06 100644 --- a/src/slskd/Core/Search/Domain/Search.cs +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -28,7 +28,7 @@ namespace slskd.Search public Guid Id { get; init; } = Guid.NewGuid(); public DateTime StartedAt { get; init; } = DateTime.UtcNow; - public DateTime? EndedAt { get; init; } + public DateTime? EndedAt { get; set; } /// /// Gets the total number of files contained within received responses. @@ -53,7 +53,7 @@ namespace slskd.Search /// /// Gets the state of the search. /// - public SearchStates State { get; init; } + public SearchStates State { get; set; } /// /// Gets the unique identifier for the search. -- cgit v1.2.3 From 5888e345d7392dbd4cb75be96d2134461442cc0c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 10:07:32 -0500 Subject: update search record with counts --- src/slskd/Core/Search/ISearchService.cs | 2 +- src/slskd/Core/Search/SearchService.cs | 96 ++++++++++++++++++++++----------- 2 files changed, 66 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/ISearchService.cs b/src/slskd/Core/Search/ISearchService.cs index 1936b30f..7f44abb7 100644 --- a/src/slskd/Core/Search/ISearchService.cs +++ b/src/slskd/Core/Search/ISearchService.cs @@ -24,7 +24,7 @@ namespace slskd.Search public interface ISearchService { - Task<(Guid Id, Task Completed)> BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null, Guid? id = null); + Task<(Guid Id, Task Completed)> BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null, Guid? id = null); bool TryCancel(Guid id); Task FindAsync(Expression> expression, bool includeResponses = false); } diff --git a/src/slskd/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs index f0632211..2e513b34 100644 --- a/src/slskd/Core/Search/SearchService.cs +++ b/src/slskd/Core/Search/SearchService.cs @@ -20,34 +20,39 @@ namespace slskd.Search using System; using System.Collections.Concurrent; using System.Linq.Expressions; - using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.Logging; using Soulseek; public class SearchService : ISearchService { - public SearchService(IDbContextFactory contextFactory, ISoulseekClient client) + public SearchService( + IDbContextFactory contextFactory, + ILogger log, + ISoulseekClient client) { ContextFactory = contextFactory; + Log = log; Client = client; } private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; set; } private ISoulseekClient Client { get; } - private ConcurrentDictionary Lookup { get; } - = new ConcurrentDictionary(); - private ConcurrentDictionary InProgress { get; } - = new ConcurrentDictionary(); - public async Task<(Guid Id, Task Completed)> BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null, Guid? id = null) + private ConcurrentDictionary InProgress { get; } + = new ConcurrentDictionary(); + + public async Task<(Guid Id, Task Completed)> BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null, Guid? id = null) { - scope = scope ?? SearchScope.Network; - var token = Client.GetNextToken(); - id = id ?? Guid.NewGuid(); + scope ??= SearchScope.Network; + options ??= new SearchOptions(); + id ??= Guid.NewGuid(); - var cts = new CancellationTokenSource(); + var token = Client.GetNextToken(); + var cancellationTokenSource = new CancellationTokenSource(); var record = new Search() { @@ -58,20 +63,33 @@ namespace slskd.Search StartedAt = DateTime.UtcNow, }; - options = options ?? new SearchOptions(stateChanged: (args) => - { - record.State = args.Search.State; - ContextFactory.CreateDbContext().Update(record); - }); + options = options.WithActions(stateChanged: (args) => UpdateState(record, args), (args) => UpdateState(record, args)); - using var context = ContextFactory.CreateDbContext(); - context.Add(record); - context.SaveChanges(); + try + { + using var context = ContextFactory.CreateDbContext(); + context.Add(record); + await context.SaveChangesAsync(); + } + catch (Exception ex) + { + Log.LogError(ex, "Failed to save search: {Message}", ex.Message); + } - InProgress.TryAdd(token, cts); - Lookup.TryAdd(id.Value, token); + InProgress.TryAdd(id.Value, cancellationTokenSource); - var task = Client.SearchAsync(query, responseReceived: (response) => AddResponse(id.Value, response), scope, token, options, cancellationToken: cts.Token); + var task = Task.Run(async () => + { + var completedSearch = await Client.SearchAsync( + query, + responseReceived: (response) => AddResponse(id.Value, response), + scope, + token, + options, + cancellationToken: cancellationTokenSource.Token); + + return Search.FromSoulseekSearch(completedSearch); + }); _ = task.ContinueWith(async task => { @@ -87,14 +105,13 @@ namespace slskd.Search using var context = ContextFactory.CreateDbContext(); context.Update(record); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine($"Saved"); } finally { - InProgress.TryRemove(token, out _); - Lookup.TryRemove(id.Value, out _); + InProgress.TryRemove(id.Value, out _); } }); @@ -103,7 +120,7 @@ namespace slskd.Search public bool TryCancel(Guid id) { - if (Lookup.TryGetValue(id, out var token) && InProgress.TryGetValue(token, out var cts)) + if (InProgress.TryGetValue(id, out var cts)) { cts.Cancel(); return true; @@ -118,7 +135,7 @@ namespace slskd.Search var search = await context .Searches .Include(s => s.Responses) - .ThenInclude(r => r.Files) + .ThenInclude(r => r.Files).AsSplitQuery() .FirstOrDefaultAsync(expression); //if (search == default) @@ -134,11 +151,28 @@ namespace slskd.Search return search; } - private void AddResponse(Guid searchId, Soulseek.SearchResponse soulseekResponse) + private void AddResponse(Guid searchId, Soulseek.SearchResponse response) { - using var context = ContextFactory.CreateDbContext(); - context.Add(SearchResponse.FromSoulseekSearchResponse(soulseekResponse, searchId)); - context.SaveChanges(); + _ = Task.Run(async () => + { + using var context = ContextFactory.CreateDbContext(); + context.Add(SearchResponse.FromSoulseekSearchResponse(response, searchId)); + await context.SaveChangesAsync(); + }).ContinueWith(task => + Log.LogError(task.Exception, "Failed to save search response for {SearchId} from {Username}", searchId, response.Username), + TaskContinuationOptions.OnlyOnFaulted); + } + + private void UpdateState(Search search, SearchEventArgs args) + { + _ = Task.Run(async () => + { + var context = ContextFactory.CreateDbContext(); + context.Update(search.WithSoulseekSearch(args.Search)); + await context.SaveChangesAsync(); + }).ContinueWith(task => + Log.LogError(task.Exception, "Failed to update state of {SearchId}", search.Id), + TaskContinuationOptions.OnlyOnFaulted); } } } -- cgit v1.2.3 From 34aa00ddc772fd02a2930677bbb974014af363bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 22:23:33 -0500 Subject: remove annotations from File and Response --- src/slskd/Core/Search/Domain/File.cs | 16 +------ src/slskd/Core/Search/Domain/Response.cs | 51 ++++++++++++++++++++ src/slskd/Core/Search/Domain/Search.cs | 56 +++++++++++----------- src/slskd/Core/Search/Domain/SearchResponse.cs | 66 -------------------------- 4 files changed, 80 insertions(+), 109 deletions(-) create mode 100644 src/slskd/Core/Search/Domain/Response.cs delete mode 100644 src/slskd/Core/Search/Domain/SearchResponse.cs (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/File.cs b/src/slskd/Core/Search/Domain/File.cs index ee14dcff..5ad99986 100644 --- a/src/slskd/Core/Search/Domain/File.cs +++ b/src/slskd/Core/Search/Domain/File.cs @@ -17,19 +17,8 @@ namespace slskd.Search { - using System; - using System.ComponentModel.DataAnnotations; - using System.ComponentModel.DataAnnotations.Schema; - using System.Text.Json.Serialization; - public class File { - [ForeignKey("SearchResponse")] - [JsonIgnore] - public Guid SearchResponseId { get; init; } - - [Key] - public Guid Id { get; init; } public int? BitDepth { get; init; } public int? BitRate { get; init; } public int Code { get; init; } @@ -41,12 +30,10 @@ namespace slskd.Search public long Size { get; init; } public bool IsLocked { get; init; } - public static File FromSoulseekFile(Soulseek.File file, Guid searchResponseId, bool isLocked = false) + public static File FromSoulseekFile(Soulseek.File file) { return new File() { - SearchResponseId = searchResponseId, - Id = Guid.NewGuid(), BitDepth = file.BitDepth, BitRate = file.BitRate, Code = file.Code, @@ -56,7 +43,6 @@ namespace slskd.Search Length = file.Length, SampleRate = file.SampleRate, Size = file.Size, - IsLocked = isLocked, }; } } diff --git a/src/slskd/Core/Search/Domain/Response.cs b/src/slskd/Core/Search/Domain/Response.cs new file mode 100644 index 00000000..a675d62f --- /dev/null +++ b/src/slskd/Core/Search/Domain/Response.cs @@ -0,0 +1,51 @@ +// +// 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/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs index 13f1dd06..74be902f 100644 --- a/src/slskd/Core/Search/Domain/Search.cs +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -20,12 +20,15 @@ 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 { [Key] - public Guid Id { get; init; } = Guid.NewGuid(); + public Guid Id { get; init; } public DateTime StartedAt { get; init; } = DateTime.UtcNow; public DateTime? EndedAt { get; set; } @@ -33,17 +36,17 @@ namespace slskd.Search /// /// Gets the total number of files contained within received responses. /// - public int FileCount { get; init; } + public int FileCount { get; set; } /// /// Gets the total number of locked files contained within received responses. /// - public int LockedFileCount { get; init; } + public int LockedFileCount { get; set; } /// /// Gets the current number of responses received. /// - public int ResponseCount { get; init; } + public int ResponseCount { get; set; } /// /// Gets the text for which to search. @@ -60,35 +63,32 @@ namespace slskd.Search /// public int Token { get; init; } - public ICollection Responses { get; init; } = new List(); - - public static Search FromSoulseekSearch(Soulseek.Search search) + [JsonIgnore] + public string ResponsesJson { - return new Search() + get => JsonSerializer.Serialize(Responses); + set { - FileCount = search.FileCount, - LockedFileCount = search.LockedFileCount, - ResponseCount = search.ResponseCount, - SearchText = search.SearchText, - State = search.State, - Token = search.Token, - }; + Responses = JsonSerializer.Deserialize>(value); + } } - public Search WithSoulseekSearch(Soulseek.Search search) + [NotMapped] + public IEnumerable Responses { get; set; } = new List(); + + public Search UpdateFromSoulseekSearch(Soulseek.Search search) { - return new Search() - { - Id = Id, - StartedAt = StartedAt, - EndedAt = EndedAt, - FileCount = search.FileCount, - LockedFileCount = search.LockedFileCount, - ResponseCount = search.ResponseCount, - SearchText = SearchText, - State = search.State, - Token = Token, - }; + FileCount = search.FileCount; + LockedFileCount = search.LockedFileCount; + ResponseCount = search.ResponseCount; + State = search.State; + return this; + } + + public Search AddResponses(List responses) + { + Responses = responses; + return this; } } } diff --git a/src/slskd/Core/Search/Domain/SearchResponse.cs b/src/slskd/Core/Search/Domain/SearchResponse.cs deleted file mode 100644 index 894fe96c..00000000 --- a/src/slskd/Core/Search/Domain/SearchResponse.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.ComponentModel.DataAnnotations; - using System.ComponentModel.DataAnnotations.Schema; - using System.Linq; - using System.Text.Json.Serialization; - - public class SearchResponse - { - [ForeignKey("Search")] - [JsonIgnore] - public Guid SearchId { get; init; } - - [Key] - public Guid Id { get; init; } = Guid.NewGuid(); - public int FileCount { get; init; } - public ICollection Files { get; init; } = new List(); - public int FreeUploadSlots { get; init; } - public int LockedFileCount { get; init; } - public long QueueLength { get; init; } - public int Token { get; init; } - public int UploadSpeed { get; init; } - public string Username { get; init; } - - public static SearchResponse FromSoulseekSearchResponse(Soulseek.SearchResponse searchResponse, Guid searchId) - { - var id = Guid.NewGuid(); - - var files = searchResponse.Files.Select(file => File.FromSoulseekFile(file, id, isLocked: false)).ToList(); - files.AddRange(searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file, id, isLocked: true))); - - return new SearchResponse() - { - SearchId = searchId, - Id = id, - FileCount = searchResponse.FileCount, - Files = files, - FreeUploadSlots = searchResponse.FreeUploadSlots, - LockedFileCount = searchResponse.LockedFileCount, - QueueLength = searchResponse.QueueLength, - Token = searchResponse.Token, - UploadSpeed = searchResponse.UploadSpeed, - Username = searchResponse.Username, - }; - } - } -} \ No newline at end of file -- cgit v1.2.3 From 008d9b60d34949099354ee7ebc76beea37581ed0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 22:24:01 -0500 Subject: docs --- src/slskd/Core/Service.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Service.cs b/src/slskd/Core/Service.cs index af6376af..6df1ddcb 100644 --- a/src/slskd/Core/Service.cs +++ b/src/slskd/Core/Service.cs @@ -365,7 +365,7 @@ namespace slskd } /// - /// Creates and returns a in response to the given . + /// Creates and returns a in response to the given . /// /// The username of the requesting user. /// The search token. -- cgit v1.2.3 From 1774865e4027b1233d497d66396677699ee25341 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 22:24:15 -0500 Subject: remove files and responses --- src/slskd/Core/Search/SearchDbContext.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/SearchDbContext.cs b/src/slskd/Core/Search/SearchDbContext.cs index 96d62432..efb2fdd6 100644 --- a/src/slskd/Core/Search/SearchDbContext.cs +++ b/src/slskd/Core/Search/SearchDbContext.cs @@ -28,7 +28,5 @@ namespace slskd.Search } public DbSet Searches { get; set; } - public DbSet SearchResponses { get; set; } - public DbSet Files { get; set; } } } -- cgit v1.2.3 From fdf5a546e1a33ea5efd507bfec0859b7ad56c174 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 22:24:39 -0500 Subject: simplify api, don't persist results until search is complete --- src/slskd/Core/Search/ISearchService.cs | 2 +- src/slskd/Core/Search/SearchService.cs | 120 +++++++++++--------------------- 2 files changed, 41 insertions(+), 81 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/ISearchService.cs b/src/slskd/Core/Search/ISearchService.cs index 7f44abb7..44d3edb9 100644 --- a/src/slskd/Core/Search/ISearchService.cs +++ b/src/slskd/Core/Search/ISearchService.cs @@ -24,7 +24,7 @@ namespace slskd.Search public interface ISearchService { - Task<(Guid Id, Task Completed)> BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null, Guid? id = null); + Task SearchAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); bool TryCancel(Guid id); Task FindAsync(Expression> expression, bool includeResponses = false); } diff --git a/src/slskd/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs index 2e513b34..f1818423 100644 --- a/src/slskd/Core/Search/SearchService.cs +++ b/src/slskd/Core/Search/SearchService.cs @@ -19,6 +19,7 @@ namespace slskd.Search { using System; using System.Collections.Concurrent; + using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; @@ -42,85 +43,57 @@ namespace slskd.Search private ILogger Log { get; set; } private ISoulseekClient Client { get; } - private ConcurrentDictionary InProgress { get; } + private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); - public async Task<(Guid Id, Task Completed)> BeginAsync(SearchQuery query, SearchScope scope = null, SearchOptions options = null, Guid? id = null) + public async Task SearchAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null) { - scope ??= SearchScope.Network; - options ??= new SearchOptions(); - id ??= Guid.NewGuid(); - var token = Client.GetNextToken(); var cancellationTokenSource = new CancellationTokenSource(); - var record = new Search() + var search = new Search() { SearchText = query.SearchText, Token = token, - Id = id.Value, + Id = id, State = SearchStates.Requested, StartedAt = DateTime.UtcNow, }; - options = options.WithActions(stateChanged: (args) => UpdateState(record, args), (args) => UpdateState(record, args)); - - try - { - using var context = ContextFactory.CreateDbContext(); - context.Add(record); - await context.SaveChangesAsync(); - } - catch (Exception ex) - { - Log.LogError(ex, "Failed to save search: {Message}", ex.Message); - } - - InProgress.TryAdd(id.Value, cancellationTokenSource); - - var task = Task.Run(async () => - { - var completedSearch = await Client.SearchAsync( - query, - responseReceived: (response) => AddResponse(id.Value, response), - scope, - token, - options, - cancellationToken: cancellationTokenSource.Token); - - return Search.FromSoulseekSearch(completedSearch); - }); - - _ = task.ContinueWith(async task => - { - Console.WriteLine($"Continued..."); + options ??= new SearchOptions(); + options = options.WithActions(stateChanged: (args) => UpdateState(search, args.Search), (args) => UpdateState(search, args.Search)); - try - { - var search = await task; - record.State = search.State; - record.EndedAt = DateTime.UtcNow; + using var context = ContextFactory.CreateDbContext(); - Console.WriteLine($"Saving with state {record.State}"); + context.Add(search); + await context.SaveChangesAsync(); - using var context = ContextFactory.CreateDbContext(); - context.Update(record); - await context.SaveChangesAsync(); + CancellationTokens.TryAdd(id, cancellationTokenSource); + var responses = new List(); - Console.WriteLine($"Saved"); - } - finally + var soulseekSearch = await Client.SearchAsync( + query, + responseReceived: (response) => { - InProgress.TryRemove(id.Value, out _); - } - }); + 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 (id.Value, task); + return search; } public bool TryCancel(Guid id) { - if (InProgress.TryGetValue(id, out var cts)) + if (CancellationTokens.TryGetValue(id, out var cts)) { cts.Cancel(); return true; @@ -134,41 +107,28 @@ namespace slskd.Search using var context = ContextFactory.CreateDbContext(); var search = await context .Searches - .Include(s => s.Responses) - .ThenInclude(r => r.Files).AsSplitQuery() + .Select(search => search.) .FirstOrDefaultAsync(expression); - //if (search == default) - //{ - // return default; - //} - - //if (includeResponses) - //{ - // await context.Entry(search).Collection(s => s.Responses).LoadAsync(); - //} + if (!includeResponses) + { + } return search; } - private void AddResponse(Guid searchId, Soulseek.SearchResponse response) + private void UpdateState(Search search, Soulseek.Search soulseekSearch) { _ = Task.Run(async () => { - using var context = ContextFactory.CreateDbContext(); - context.Add(SearchResponse.FromSoulseekSearchResponse(response, searchId)); - await context.SaveChangesAsync(); - }).ContinueWith(task => - Log.LogError(task.Exception, "Failed to save search response for {SearchId} from {Username}", searchId, response.Username), - TaskContinuationOptions.OnlyOnFaulted); - } + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; - private void UpdateState(Search search, SearchEventArgs args) - { - _ = Task.Run(async () => - { var context = ContextFactory.CreateDbContext(); - context.Update(search.WithSoulseekSearch(args.Search)); + + context.Update(search); await context.SaveChangesAsync(); }).ContinueWith(task => Log.LogError(task.Exception, "Failed to update state of {SearchId}", search.Id), -- cgit v1.2.3 From c3a3d3c3e21a0bbe04116b5c98f7be1df6ad3c92 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 22:25:02 -0500 Subject: implement the rest of SearchService --- src/slskd/API/Controllers/SearchesController.cs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/API/Controllers/SearchesController.cs b/src/slskd/API/Controllers/SearchesController.cs index d38d509e..05a0e002 100644 --- a/src/slskd/API/Controllers/SearchesController.cs +++ b/src/slskd/API/Controllers/SearchesController.cs @@ -70,22 +70,14 @@ namespace slskd.API.Controllers public async Task Post([FromBody]SearchRequest request) { var id = request.Id ?? Guid.NewGuid(); - - var options = request.ToSearchOptions( - responseReceived: (e) => Tracker.AddOrUpdate(id, e), - stateChanged: (e) => Tracker.AddOrUpdate(id, e)); - - var results = new ConcurrentBag(); - var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1)); + slskd.Search.Search search = null; + try { - //await Client.SearchAsync(SearchQuery.FromText(searchText), (r) => results.Add(r), SearchScope.Network, request.Token, options); - var (guid, completed) = await SearchService.BeginAsync(SearchQuery.FromText(searchText), SearchScope.Network, id: id); - await completed; - - return Ok(results); + search = await SearchService.SearchAsync(id, SearchQuery.FromText(searchText), SearchScope.Network); + return Ok(search.Responses); } catch (Exception ex) { @@ -93,8 +85,7 @@ namespace slskd.API.Controllers } finally { - results = null; - Tracker.TryRemove(id); + search = null; } } -- cgit v1.2.3 From ae31d127746032803de0eabc9a8bfe3846f6fb78 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 May 2021 22:27:27 -0500 Subject: deprecate SearchTracker --- src/slskd/API/Controllers/SearchesController.cs | 4 +- src/slskd/Core/Search/ISearchTracker.cs | 52 --------------------- src/slskd/Core/Search/SearchService.cs | 1 - src/slskd/Core/Search/SearchTracker.cs | 62 ------------------------- src/slskd/Startup.cs | 1 - 5 files changed, 1 insertion(+), 119 deletions(-) delete mode 100644 src/slskd/Core/Search/ISearchTracker.cs delete mode 100644 src/slskd/Core/Search/SearchTracker.cs (limited to 'src') diff --git a/src/slskd/API/Controllers/SearchesController.cs b/src/slskd/API/Controllers/SearchesController.cs index 05a0e002..d652f147 100644 --- a/src/slskd/API/Controllers/SearchesController.cs +++ b/src/slskd/API/Controllers/SearchesController.cs @@ -43,16 +43,14 @@ namespace slskd.API.Controllers /// /// /// - public SearchesController(ISoulseekClient client, ISearchTracker tracker, ISearchService searchService) + public SearchesController(ISoulseekClient client, ISearchService searchService) { Client = client; - Tracker = tracker; SearchService = searchService; } private ISearchService SearchService { get; } private ISoulseekClient Client { get; } - private ISearchTracker Tracker { get; } /// /// Performs a search for the specified . diff --git a/src/slskd/Core/Search/ISearchTracker.cs b/src/slskd/Core/Search/ISearchTracker.cs deleted file mode 100644 index c962138e..00000000 --- a/src/slskd/Core/Search/ISearchTracker.cs +++ /dev/null @@ -1,52 +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 Soulseek; - - /// - /// Tracks active searches. - /// - public interface ISearchTracker - { - /// - /// Gets active searches. - /// - ConcurrentDictionary Searches { get; } - - /// - /// Adds or updates a tracked search. - /// - /// - /// - void AddOrUpdate(Guid id, SearchEventArgs args); - - /// - /// Removes all tracked searches. - /// - void Clear(); - - /// - /// Removes a tracked search. - /// - /// - void TryRemove(Guid id); - } -} \ No newline at end of file diff --git a/src/slskd/Core/Search/SearchService.cs b/src/slskd/Core/Search/SearchService.cs index f1818423..0fd4d6d5 100644 --- a/src/slskd/Core/Search/SearchService.cs +++ b/src/slskd/Core/Search/SearchService.cs @@ -107,7 +107,6 @@ namespace slskd.Search using var context = ContextFactory.CreateDbContext(); var search = await context .Searches - .Select(search => search.) .FirstOrDefaultAsync(expression); if (!includeResponses) diff --git a/src/slskd/Core/Search/SearchTracker.cs b/src/slskd/Core/Search/SearchTracker.cs deleted file mode 100644 index b1ab2b18..00000000 --- a/src/slskd/Core/Search/SearchTracker.cs +++ /dev/null @@ -1,62 +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 Soulseek; - - /// - /// Tracks active searches. - /// - public class SearchTracker : ISearchTracker - { - /// - /// Gets active searches. - /// - public ConcurrentDictionary Searches { get; private set; } = - new ConcurrentDictionary(); - - /// - /// Adds or updates a tracked search. - /// - /// - /// - public void AddOrUpdate(Guid id, SearchEventArgs args) - { - Searches.AddOrUpdate(id, args.Search, (token, search) => args.Search); - } - - /// - /// Removes all tracked searches. - /// - public void Clear() - { - Searches.Clear(); - } - - /// - /// Removes a tracked search. - /// - /// - public void TryRemove(Guid id) - { - Searches.TryRemove(id, out _); - } - } -} \ No newline at end of file diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index a4627114..4d11ad1a 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -174,7 +174,6 @@ namespace slskd services.AddTransient(p => p.GetRequiredService>().CreateDbContext()); services.AddSingleton(); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); -- cgit v1.2.3 From dd95f05ac6c887cfffd92f462229631cb37bf60e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:01:07 -0500 Subject: disambiguate File --- src/slskd/Program.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 7ccebe6e..42c3c508 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -41,6 +41,7 @@ namespace slskd using slskd.Validation; using Utility.CommandLine; using Utility.EnvironmentVariables; + using IOFile = System.IO.File; /// /// Bootstraps configuration and handles primitive command-line instructions. @@ -253,7 +254,7 @@ namespace slskd PrintLogo(Version); } - if (ConfigurationFile != DefaultConfigurationFile && !File.Exists(ConfigurationFile)) + if (ConfigurationFile != DefaultConfigurationFile && !IOFile.Exists(ConfigurationFile)) { logger.Warning($"Specified configuration file '{ConfigurationFile}' could not be found and was not loaded."); } @@ -346,7 +347,7 @@ namespace slskd filename = Path.Combine(AppContext.BaseDirectory, filename); var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable); - File.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password)); + IOFile.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password)); Console.WriteLine($"Password: {password}"); Console.WriteLine($"Certificate exported to {filename}"); @@ -503,8 +504,8 @@ namespace slskd { var file = Guid.NewGuid().ToString(); var probe = Path.Combine(directory, file); - File.WriteAllText(probe, string.Empty); - File.Delete(probe); + IOFile.WriteAllText(probe, string.Empty); + IOFile.Delete(probe); } catch (Exception ex) { -- cgit v1.2.3 From 3a93d826852ca0d489efee6ce12e2f2400530949 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:01:21 -0500 Subject: move SearchesController --- src/slskd/API/Controllers/SearchesController.cs | 114 ----------------- .../Core/Search/Controllers/SearchesController.cs | 135 +++++++++++++++++++++ 2 files changed, 135 insertions(+), 114 deletions(-) delete mode 100644 src/slskd/API/Controllers/SearchesController.cs create mode 100644 src/slskd/Core/Search/Controllers/SearchesController.cs (limited to 'src') diff --git a/src/slskd/API/Controllers/SearchesController.cs b/src/slskd/API/Controllers/SearchesController.cs deleted file mode 100644 index d652f147..00000000 --- a/src/slskd/API/Controllers/SearchesController.cs +++ /dev/null @@ -1,114 +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.API.Controllers -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using slskd.API.DTO; - using slskd.Search; - using Soulseek; - - /// - /// 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(ISoulseekClient client, ISearchService searchService) - { - Client = client; - SearchService = searchService; - } - - private ISearchService SearchService { get; } - private ISoulseekClient Client { get; } - - /// - /// Performs a search for the specified . - /// - /// The search request. - /// - /// The search completed successfully. - /// The specified was malformed. - /// The search terminated abnormally. - [HttpPost("")] - [Authorize] - [ProducesResponseType(typeof(IEnumerable), 200)] - [ProducesResponseType(400)] - [ProducesResponseType(typeof(string), 500)] - 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)); - - slskd.Search.Search search = null; - - try - { - search = await SearchService.SearchAsync(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. - /// - /// The request completed successfully. - /// A matching search was not found. - [HttpGet("{id}")] - [Authorize] - [ProducesResponseType(typeof(slskd.Search.Search), 200)] - [ProducesResponseType(404)] - public async Task GetById([FromRoute]Guid id) - { - var search = await SearchService.FindAsync(search => search.Id == id); - - if (search == default) - { - Console.WriteLine($"Search: {id} not found"); - return NotFound(); - } - - return Ok(search); - } - } -} diff --git a/src/slskd/Core/Search/Controllers/SearchesController.cs b/src/slskd/Core/Search/Controllers/SearchesController.cs new file mode 100644 index 00000000..a027feed --- /dev/null +++ b/src/slskd/Core/Search/Controllers/SearchesController.cs @@ -0,0 +1,135 @@ +// +// 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. + /// + /// The request completed successfully. + /// A matching search was not found. + [HttpGet("{id}")] + [Authorize] + public async Task GetById([FromRoute]Guid id) + { + var search = await Searches.FindAsync(search => search.Id == id); + + 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 GetByIdWithResponses([FromRoute] Guid id) + { + var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); + + if (search == default) + { + return NotFound(); + } + + return Ok(search); + } + + /// + /// Gets the list of active and completed searches. + /// + /// + [HttpGet("")] + [Authorize] + public async Task GetAll() + { + return Ok(await Searches.ListAsync()); + } + } +} -- cgit v1.2.3 From ff1574348a9b106b85d6dbf8131bd5a4ba9958c1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:01:32 -0500 Subject: move File to common --- src/slskd/Core/Common/Domain/File.cs | 51 ++++++++++++++++++++++++++++++++++++ src/slskd/Core/Search/Domain/File.cs | 49 ---------------------------------- 2 files changed, 51 insertions(+), 49 deletions(-) create mode 100644 src/slskd/Core/Common/Domain/File.cs delete mode 100644 src/slskd/Core/Search/Domain/File.cs (limited to 'src') diff --git a/src/slskd/Core/Common/Domain/File.cs b/src/slskd/Core/Common/Domain/File.cs new file mode 100644 index 00000000..079ec0f0 --- /dev/null +++ b/src/slskd/Core/Common/Domain/File.cs @@ -0,0 +1,51 @@ +// +// 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 +{ + 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/Core/Search/Domain/File.cs b/src/slskd/Core/Search/Domain/File.cs deleted file mode 100644 index 5ad99986..00000000 --- a/src/slskd/Core/Search/Domain/File.cs +++ /dev/null @@ -1,49 +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 -{ - 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(Soulseek.File 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 -- cgit v1.2.3 From 117cd518209ad190492bcd483f1ca54f696ceb34 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:01:45 -0500 Subject: tidy up --- src/slskd/Core/Search/Domain/Response.cs | 2 +- src/slskd/Core/Search/Domain/Search.cs | 24 ------------------------ 2 files changed, 1 insertion(+), 25 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/Response.cs b/src/slskd/Core/Search/Domain/Response.cs index a675d62f..ea2e8993 100644 --- a/src/slskd/Core/Search/Domain/Response.cs +++ b/src/slskd/Core/Search/Domain/Response.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs index 74be902f..b5ed8e4a 100644 --- a/src/slskd/Core/Search/Domain/Search.cs +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -32,35 +32,11 @@ namespace slskd.Search public DateTime StartedAt { get; init; } = DateTime.UtcNow; public DateTime? EndedAt { get; set; } - - /// - /// Gets the total number of files contained within received responses. - /// public int FileCount { get; set; } - - /// - /// Gets the total number of locked files contained within received responses. - /// public int LockedFileCount { get; set; } - - /// - /// Gets the current number of responses received. - /// public int ResponseCount { get; set; } - - /// - /// Gets the text for which to search. - /// public string SearchText { get; init; } - - /// - /// Gets the state of the search. - /// public SearchStates State { get; set; } - - /// - /// Gets the unique identifier for the search. - /// public int Token { get; init; } [JsonIgnore] -- cgit v1.2.3 From d3688262afeb01cf5ffd6df0c5ac2cbb1a8a6459 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:02:02 -0500 Subject: move SearchDbContext --- .../Core/Search/Persistence/SearchDbContext.cs | 32 ++++++++++++++++++++++ src/slskd/Core/Search/SearchDbContext.cs | 32 ---------------------- 2 files changed, 32 insertions(+), 32 deletions(-) create mode 100644 src/slskd/Core/Search/Persistence/SearchDbContext.cs delete mode 100644 src/slskd/Core/Search/SearchDbContext.cs (limited to 'src') diff --git a/src/slskd/Core/Search/Persistence/SearchDbContext.cs b/src/slskd/Core/Search/Persistence/SearchDbContext.cs new file mode 100644 index 00000000..efb2fdd6 --- /dev/null +++ b/src/slskd/Core/Search/Persistence/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/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 (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; } - } -} -- cgit v1.2.3 From 770e931191983638dd3c422720af014779ad75ad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:02:09 -0500 Subject: docs --- src/slskd/Core/Search/Extensions.cs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Search/Extensions.cs b/src/slskd/Core/Search/Extensions.cs index 2ff1139c..d52975d2 100644 --- a/src/slskd/Core/Search/Extensions.cs +++ b/src/slskd/Core/Search/Extensions.cs @@ -18,10 +18,18 @@ 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, @@ -61,5 +69,26 @@ namespace slskd.Search responseReceived(args); }); } + + /// + /// 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, + }); + } } } -- cgit v1.2.3 From ef5371276a7293d464fd058dcfa903072fae67e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:02:22 -0500 Subject: polish SearchService --- src/slskd/Core/Search/ISearchService.cs | 31 ---- src/slskd/Core/Search/SearchService.cs | 137 --------------- src/slskd/Core/Search/Services/ISearchService.cs | 67 ++++++++ src/slskd/Core/Search/Services/SearchService.cs | 203 +++++++++++++++++++++++ 4 files changed, 270 insertions(+), 168 deletions(-) delete mode 100644 src/slskd/Core/Search/ISearchService.cs delete mode 100644 src/slskd/Core/Search/SearchService.cs create mode 100644 src/slskd/Core/Search/Services/ISearchService.cs create mode 100644 src/slskd/Core/Search/Services/SearchService.cs (limited to 'src') 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 (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.Expressions; - using System.Threading.Tasks; - using Soulseek; - - public interface ISearchService - { - Task SearchAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); - bool TryCancel(Guid id); - Task FindAsync(Expression> 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 (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.Expressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; - using Soulseek; - - public class SearchService : ISearchService - { - public SearchService( - IDbContextFactory contextFactory, - ILogger log, - ISoulseekClient client) - { - ContextFactory = contextFactory; - Log = log; - Client = client; - } - - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; set; } - private ISoulseekClient Client { get; } - - private ConcurrentDictionary CancellationTokens { get; } - = new ConcurrentDictionary(); - - public async Task 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(); - - 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 FindAsync(Expression> 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 (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. + /// A value indicating whether to include search responses in the result. + /// The completed search. + Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null, bool includeResponses = true); + + /// + /// 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 new file mode 100644 index 00000000..7b6f0f2b --- /dev/null +++ b/src/slskd/Core/Search/Services/SearchService.cs @@ -0,0 +1,203 @@ +// +// 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, 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(); + + 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 _); + } + } + + /// + /// 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) + { + _ = 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 -- cgit v1.2.3 From 6532946913e03086cb7a9f308770b52265b98b98 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 May 2021 15:31:15 -0500 Subject: set EndedAt --- src/slskd/Core/Search/Services/SearchService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Core/Search/Services/SearchService.cs b/src/slskd/Core/Search/Services/SearchService.cs index 7b6f0f2b..48f7e600 100644 --- a/src/slskd/Core/Search/Services/SearchService.cs +++ b/src/slskd/Core/Search/Services/SearchService.cs @@ -114,6 +114,7 @@ namespace slskd.Search search.LockedFileCount = soulseekSearch.LockedFileCount; search.ResponseCount = soulseekSearch.ResponseCount; search.State = soulseekSearch.State; + search.EndedAt = DateTime.UtcNow; if (includeResponses) { -- cgit v1.2.3 From c3108fcdb83d1c4ad032971dcb2be1d9bdc04983 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 10:21:44 -0500 Subject: tidy up --- src/slskd/Core/Search/Domain/Search.cs | 35 +++++++++++----------------------- 1 file changed, 11 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs index b5ed8e4a..e89caf54 100644 --- a/src/slskd/Core/Search/Domain/Search.cs +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -27,17 +27,17 @@ namespace slskd.Search public class Search { + public DateTime? EndedAt { get; set; } + public int FileCount { get; set; } + [Key] public Guid Id { get; init; } - public DateTime StartedAt { get; init; } = DateTime.UtcNow; - public DateTime? EndedAt { get; set; } - public int FileCount { get; set; } public int LockedFileCount { get; set; } public int ResponseCount { get; set; } - public string SearchText { get; init; } - public SearchStates State { get; set; } - public int Token { get; init; } + + [NotMapped] + public IEnumerable Responses { get; set; } = new List(); [JsonIgnore] public string ResponsesJson @@ -49,22 +49,9 @@ namespace slskd.Search } } - [NotMapped] - public IEnumerable Responses { get; set; } = new List(); - - public Search UpdateFromSoulseekSearch(Soulseek.Search search) - { - FileCount = search.FileCount; - LockedFileCount = search.LockedFileCount; - ResponseCount = search.ResponseCount; - State = search.State; - return this; - } - - public Search AddResponses(List responses) - { - Responses = responses; - return this; - } + 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 -- cgit v1.2.3 From 9ba6bedaac35cc31d23fc3ba4808f813b214cb91 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 16:54:14 -0500 Subject: prevent out of band search updates, save final state --- src/slskd/Core/Search/Services/ISearchService.cs | 3 +-- src/slskd/Core/Search/Services/SearchService.cs | 27 ++++++++++++------------ 2 files changed, 15 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/Services/ISearchService.cs b/src/slskd/Core/Search/Services/ISearchService.cs index f56f2ab3..d696617d 100644 --- a/src/slskd/Core/Search/Services/ISearchService.cs +++ b/src/slskd/Core/Search/Services/ISearchService.cs @@ -37,9 +37,8 @@ namespace slskd.Search /// The search query. /// The search scope. /// Search options. - /// A value indicating whether to include search responses in the result. /// The completed search. - Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null, bool includeResponses = true); + Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); /// /// Finds a single search matching the specified . diff --git a/src/slskd/Core/Search/Services/SearchService.cs b/src/slskd/Core/Search/Services/SearchService.cs index 48f7e600..e3c1bbef 100644 --- a/src/slskd/Core/Search/Services/SearchService.cs +++ b/src/slskd/Core/Search/Services/SearchService.cs @@ -70,7 +70,7 @@ namespace slskd.Search /// 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, bool includeResponses = true) + public async Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null) { var token = Client.GetNextToken(); var cancellationTokenSource = new CancellationTokenSource(); @@ -110,16 +110,15 @@ namespace slskd.Search 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; - - if (includeResponses) - { - search.Responses = responses; - } + search.Responses = responses; + SaveSearchState(search); return search; } @@ -185,20 +184,22 @@ namespace slskd.Search private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) { - _ = Task.Run(async () => + if (CancellationTokens.ContainsKey(search.Id)) { search.FileCount = soulseekSearch.FileCount; search.LockedFileCount = soulseekSearch.LockedFileCount; search.ResponseCount = soulseekSearch.ResponseCount; search.State = soulseekSearch.State; - var context = ContextFactory.CreateDbContext(); + SaveSearchState(search); + } + } - context.Update(search); - await context.SaveChangesAsync(); - }).ContinueWith(task => - Log.LogError(task.Exception, "Failed to update state of {SearchId}", search.Id), - TaskContinuationOptions.OnlyOnFaulted); + private void SaveSearchState(Search search) + { + var context = ContextFactory.CreateDbContext(); + context.Update(search); + context.SaveChanges(); } } } \ No newline at end of file -- cgit v1.2.3 From b65ff5de2206daad4aac6ca9b6ac9dbf5bc2fbd9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 16:54:39 -0500 Subject: add IsComplete --- src/slskd/Core/Search/Domain/Search.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Search/Domain/Search.cs b/src/slskd/Core/Search/Domain/Search.cs index e89caf54..b93c62cb 100644 --- a/src/slskd/Core/Search/Domain/Search.cs +++ b/src/slskd/Core/Search/Domain/Search.cs @@ -33,6 +33,9 @@ namespace slskd.Search [Key] public Guid Id { get; init; } + [NotMapped] + public bool IsComplete => State.HasFlag(SearchStates.Completed); + public int LockedFileCount { get; set; } public int ResponseCount { get; set; } -- cgit v1.2.3 From 599ebb1a2b02620d2f97da067ce9eb78ca032f46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 16:55:42 -0500 Subject: add find parameter to omit responses --- src/slskd/Core/Search/Controllers/SearchesController.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Search/Controllers/SearchesController.cs b/src/slskd/Core/Search/Controllers/SearchesController.cs index a027feed..18bdba15 100644 --- a/src/slskd/Core/Search/Controllers/SearchesController.cs +++ b/src/slskd/Core/Search/Controllers/SearchesController.cs @@ -83,14 +83,15 @@ namespace slskd.Search /// 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) + public async Task GetById([FromRoute]Guid id, [FromQuery]bool includeResponses = false) { - var search = await Searches.FindAsync(search => search.Id == id); + var search = await Searches.FindAsync(search => search.Id == id, includeResponses); if (search == default) { @@ -109,7 +110,7 @@ namespace slskd.Search /// A matching search was not found. [HttpGet("{id}/responses")] [Authorize] - public async Task GetByIdWithResponses([FromRoute] Guid id) + public async Task GetResponsesById([FromRoute] Guid id) { var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); @@ -118,7 +119,7 @@ namespace slskd.Search return NotFound(); } - return Ok(search); + return Ok(search.Responses); } /// -- cgit v1.2.3 From fbbaf853dcc135e43a7500bf56287098a84edca6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 16:56:31 -0500 Subject: add getResponses --- src/web/src/lib/search.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/lib/search.js b/src/web/src/lib/search.js index c71dba96..47f431aa 100644 --- a/src/web/src/lib/search.js +++ b/src/web/src/lib/search.js @@ -4,6 +4,10 @@ export const search = ({ id, searchText }) => { return api.post(`/searches`, { id, searchText }); }; -export const getStatus = async ({ id }) => { +export const getStatus = async ({ id, includeResponses = false }) => { + return (await api.get(`/searches/${encodeURIComponent(id)}?includeResponses=${includeResponses}`)).data; +}; + +export const getResponses = async ({ id }) => { return (await api.get(`/searches/${encodeURIComponent(id)}`)).data; }; \ No newline at end of file -- cgit v1.2.3 From c9295fdaa1e0c004a406f1f7b5fbf9e181afbc54 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 17:03:54 -0500 Subject: actually get responses --- src/web/src/lib/search.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/lib/search.js b/src/web/src/lib/search.js index 47f431aa..2179dcd2 100644 --- a/src/web/src/lib/search.js +++ b/src/web/src/lib/search.js @@ -9,5 +9,5 @@ export const getStatus = async ({ id, includeResponses = false }) => { }; export const getResponses = async ({ id }) => { - return (await api.get(`/searches/${encodeURIComponent(id)}`)).data; + return (await api.get(`/searches/${encodeURIComponent(id)}/responses`)).data; }; \ No newline at end of file -- cgit v1.2.3 From a4280e899dd5d7b8b4cef6cb33fe48a375055e98 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 17:04:28 -0500 Subject: dont rely on POST response for search state --- src/web/src/components/Search/Search.js | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index 48e05775..f1caee54 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -50,13 +50,9 @@ class Search extends Component { const searchPhrase = this.inputtext.inputRef.current.value; const searchId = uuidv4(); - this.setState({ searchPhrase, searchId, searchState: 'pending' }, () => { - search.search({ id: searchId, searchText: searchPhrase }) - .then(response => this.setState({ results: response.data })) - .then(() => this.setState({ searchState: 'complete' }, () => { - this.saveState(); - this.setSearchText(); - })) + this.setState({ searchPhrase, searchId, searchState: 'pending' }, async () => { + this.saveState(); + search.search({ id: searchId, searchText: searchPhrase }); }); } -- cgit v1.2.3 From 762833d3fed517fd1acad9aa5ac469a6f894bc13 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 17:05:49 -0500 Subject: dont save results to localstorage --- src/web/src/components/Search/Search.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index f1caee54..94b36051 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -72,7 +72,7 @@ class Search extends Component { saveState = () => { try { - localStorage.setItem('soulseek-example-search-state', JSON.stringify(this.state)); + localStorage.setItem('soulseek-example-search-state', JSON.stringify({ ...this.state, results: [] })); } catch(error) { console.log(error); } -- cgit v1.2.3 From 61375627fb3a82bdf53cc989339d69f39dca0165 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 17:06:03 -0500 Subject: promisify loadstate --- src/web/src/components/Search/Search.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index 94b36051..ab1257e9 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -79,7 +79,8 @@ class Search extends Component { } loadState = () => { - this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState); + return new Promise((resolve) => + this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState, resolve)); } componentDidMount = () => { -- cgit v1.2.3 From 0a4f7c5e6c6dd09ac4457460cbff0e33f0ab934f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 17:06:38 -0500 Subject: fetch results on mount --- src/web/src/components/Search/Search.js | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index ab1257e9..ccb9c874 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -83,9 +83,9 @@ class Search extends Component { this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState, resolve)); } - componentDidMount = () => { - this.fetchStatus(); - this.loadState(); + componentDidMount = async () => { + await this.loadState(); + this.fetchResults(); this.setState({ interval: window.setInterval(this.fetchStatus, 500) }, () => this.setSearchText()); @@ -104,12 +104,25 @@ class Search extends Component { document.removeEventListener("keyup", this.keyUp, false); } - fetchStatus = () => { - if (this.state.searchState === 'pending') { - search.getStatus({ id: this.state.searchId }) - .then(response => this.setState({ - searchStatus: response - })); + fetchResults = async () => { + const { searchId } = this.state; + + if (!!searchId) { + this.setState({ fetching: true }, async () => { + try { + const responses = await search.getResponses({ id: searchId }); + + this.setState({ + results: responses, + fetching: false + }, this.saveState); + } catch (error) { + console.log(error); + this.clear(); + } + }); + } + } } } -- cgit v1.2.3 From 25ddbc2a75cec8cc3a2b5d2b1be7b86b733a2b1e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 17:08:36 -0500 Subject: display loading status --- src/web/src/components/Search/Search.js | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index ccb9c874..639cc5d8 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -18,7 +18,7 @@ import { const initialState = { searchPhrase: '', - searchId: '', + searchId: undefined, searchState: 'idle', searchStatus: { responseCount: 0, @@ -31,6 +31,7 @@ const initialState = { hideNoFreeSlots: true, hiddenResults: [], hideLocked: true, + fetching: false, }; const sortOptions = { @@ -123,6 +124,25 @@ class Search extends Component { }); } } + + fetchStatus = async () => { + const { searchState, searchId } = this.state; + + if (searchState === 'pending') { + this.setState({ fetching: true }, async () => { + const response = await search.getStatus({ id: searchId }); + + if (response.isComplete) { + this.setState({ + searchState: 'complete' + }, this.fetchResults); + } else { + this.setState({ + searchStatus: response, + fetching: false + }, this.saveState); + } + }); } } @@ -131,7 +151,7 @@ class Search extends Component { } sortAndFilterResults = () => { - const { results, hideNoFreeSlots, resultSort, hideLocked, hiddenResults } = this.state; + const { results = [], hideNoFreeSlots, resultSort, hideLocked, hiddenResults = [] } = this.state; const { field, order } = sortOptions[resultSort]; return results @@ -164,8 +184,8 @@ class Search extends Component { } render = () => { - let { searchState, searchStatus, results, displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults } = this.state; - let pending = searchState === 'pending'; + let { searchState, searchStatus, results = [], displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults = [], fetching } = this.state; + let pending = fetching || searchState === 'pending'; const sortedAndFilteredResults = this.sortAndFilterResults(); @@ -195,7 +215,8 @@ class Search extends Component { inline='centered' size='big' > - Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users + {searchState === 'pending' ? Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users + : 'Fetching results'} :
-- cgit v1.2.3 From 4533681fbfc20e1e608f7ddf8ce4a105e281d481 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 May 2021 17:10:04 -0500 Subject: tweak verbiage --- src/web/src/components/Search/Search.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index 639cc5d8..60720c1a 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -216,7 +216,7 @@ class Search extends Component { size='big' > {searchState === 'pending' ? Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users - : 'Fetching results'} + : 'Loading results...'} :
-- cgit v1.2.3