From 3c53e43bc9b91aafe93853417436bf761b2a076f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Nov 2022 09:24:23 -0500 Subject: add statistics to Share --- .../Shares/API/Controllers/SharesController.cs | 45 ++++------------------ src/slskd/Shares/API/DTO/SummarizedShare.cs | 31 --------------- src/slskd/Shares/Types/Share.cs | 14 ++++++- 3 files changed, 21 insertions(+), 69 deletions(-) delete mode 100644 src/slskd/Shares/API/DTO/SummarizedShare.cs (limited to 'src') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 671e8992..e4f82848 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -53,29 +53,14 @@ namespace slskd.Shares.API /// [HttpGet("")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable), 200)] - public async Task List() + [ProducesResponseType(typeof(Dictionary>), 200)] + public IActionResult List() { - var shares = new List(); + var response = Shares.Hosts.ToDictionary( + keySelector: host => host.Name, + elementSelector: host => host.Shares); - foreach (var share in Shares.Hosts.SelectMany(host => host.Shares)) - { - var (directories, files) = await Shares.SummarizeShareAsync(share); - - shares.Add(new SummarizedShare() - { - Id = share.Id, - Alias = share.Alias, - IsExcluded = share.IsExcluded, - LocalPath = share.LocalPath, - Raw = share.Raw, - RemotePath = share.RemotePath, - Directories = directories, - Files = files, - }); - } - - return Ok(shares); + return Ok(response); } /// @@ -87,7 +72,7 @@ namespace slskd.Shares.API /// [HttpGet("{id}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(SummarizedShare), 200)] + [ProducesResponseType(typeof(Share), 200)] [ProducesResponseType(404)] public async Task Get(string id) { @@ -98,21 +83,7 @@ namespace slskd.Shares.API return NotFound(); } - var (directories, files) = await Shares.SummarizeShareAsync(share); - - var summary = new SummarizedShare() - { - Id = share.Id, - Alias = share.Alias, - IsExcluded = share.IsExcluded, - LocalPath = share.LocalPath, - Raw = share.Raw, - RemotePath = share.RemotePath, - Directories = directories, - Files = files, - }; - - return Ok(summary); + return Ok(share); } /// diff --git a/src/slskd/Shares/API/DTO/SummarizedShare.cs b/src/slskd/Shares/API/DTO/SummarizedShare.cs deleted file mode 100644 index 4e296d1c..00000000 --- a/src/slskd/Shares/API/DTO/SummarizedShare.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.Shares -{ - public record SummarizedShare - { - public string Id { get; init; } - public string Alias { get; init; } - public bool IsExcluded { get; init; } - public string LocalPath { get; init; } - public string Raw { get; init; } - public string RemotePath { get; init; } - public int Directories { get; init; } - public int Files { get; init; } - } -} \ No newline at end of file diff --git a/src/slskd/Shares/Types/Share.cs b/src/slskd/Shares/Types/Share.cs index 6a6d1f66..42a2e9e2 100644 --- a/src/slskd/Shares/Types/Share.cs +++ b/src/slskd/Shares/Types/Share.cs @@ -35,8 +35,10 @@ namespace slskd.Shares /// /// /// + /// + /// [JsonConstructor] - public Share (string id, string alias, bool isExcluded, string localPath, string raw, string remotePath) + public Share (string id, string alias, bool isExcluded, string localPath, string raw, string remotePath, int directories, int files) { Id = id; Alias = alias; @@ -44,6 +46,8 @@ namespace slskd.Shares LocalPath = localPath; Raw = raw; RemotePath = remotePath; + Directories = directories; + Files = files; } /// @@ -87,5 +91,13 @@ namespace slskd.Shares public string LocalPath { get; init; } public string Raw { get; init; } public string RemotePath { get; init; } + public int Directories { get; private set; } + public int Files { get; private set; } + + public void UpdateStatistics(int directories, int files) + { + Directories = directories; + Files = files; + } } } -- cgit v1.2.3 From 2bd1c00406c177140ce3903299f72ab92fe4b8e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Nov 2022 09:25:17 -0500 Subject: recompute statistics and update state when hosts change --- src/slskd/Shares/IShareService.cs | 14 ++++---- src/slskd/Shares/ShareService.cs | 68 +++++++++++++++++++++++++++------------ 2 files changed, 55 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 34f1bde8..dff6a8ce 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -53,6 +53,13 @@ namespace slskd.Shares /// The entire contents of the share. Task> BrowseAsync(Share share = null); + /// + /// Gets statistical information for the specified . + /// + /// The share to summarize. + /// The summary information. + Task<(int Directories, int Files)> ComputeShareStatisticsAsync(Share share); + /// /// Dumps the local share cache to a file. /// @@ -112,13 +119,6 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. Task ScanAsync(); - /// - /// Gets summary information for the specified . - /// - /// The share to summarize. - /// The summary information. - Task<(int Directories, int Files)> SummarizeShareAsync(Share share); - /// /// Cancels the currently running scan on the local host, if one is running. /// diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index d6c6b977..a497012f 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -57,9 +57,7 @@ namespace slskd.Shares AllRepositories = new List(new[] { repository }); - Scanner = scanner ?? new ShareScanner( - shareRepository: repository, - workerCount: options.Shares.Cache.Workers); + Scanner = scanner ?? new ShareScanner(workerCount: options.Shares.Cache.Workers); Scanner.StateMonitor.OnChange(cacheState => { @@ -130,6 +128,12 @@ namespace slskd.Shares AllRepositories = HostDictionary.Values .Select(value => value.Repository) .Prepend(Local.Repository); + + State.SetValue(state => state with + { + Directories = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)), + Files = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)), + }); } /// @@ -183,6 +187,23 @@ namespace slskd.Shares return Task.FromResult(results); } + /// + /// Gets summary information for the specified . + /// + /// The share to summarize. + /// The summary information. + public Task<(int Directories, int Files)> ComputeShareStatisticsAsync(Share share) + { + var prefix = share.RemotePath + (share.RemotePath.EndsWith('\\') ? string.Empty : '\\'); + + var dirs = AllRepositories.Select(r => r.CountDirectories(prefix)).Sum(); + var files = AllRepositories.Select(r => r.CountFiles(prefix)).Sum(); + + share.UpdateStatistics(dirs, files); + + return Task.FromResult((dirs, files)); + } + /// /// Dumps the local share cache to a file. /// @@ -218,7 +239,20 @@ namespace slskd.Shares /// The name of the host. /// A value indicating whether the host was removed. public bool TryRemoveHost(string name) - => HostDictionary.TryRemove(name, out _); + { + if (HostDictionary.TryRemove(name, out _)) + { + State.SetValue(state => state with + { + Directories = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)), + Files = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)), + }); + + return true; + } + + return false; + } /// /// Returns the contents of the specified . @@ -293,25 +327,15 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. public async Task ScanAsync() { - await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares); + await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares, Local.Repository); Log.Debug("Backing up shared file cache database..."); Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name)); Log.Debug("Shared file cache database backup complete"); - } - /// - /// Gets summary information for the specified . - /// - /// The share to summarize. - /// The summary information. - public Task<(int Directories, int Files)> SummarizeShareAsync(Share share) - { - var prefix = share.RemotePath + (share.RemotePath.EndsWith('\\') ? string.Empty : '\\'); - - var dirs = AllRepositories.Select(r => r.CountDirectories(prefix)).Sum(); - var files = AllRepositories.Select(r => r.CountFiles(prefix)).Sum(); - return Task.FromResult((dirs, files)); + Log.Debug("Recomputing share statistics..."); + await Task.WhenAll(Local.Host.Shares.Select(share => ComputeShareStatisticsAsync(share))); + Log.Debug("Share statistics updated"); } /// @@ -391,6 +415,10 @@ namespace slskd.Shares Local.Repository.EnableKeepalive(true); + Log.Debug("Recomputing share statistics..."); + await Task.WhenAll(Local.Host.Shares.Select(share => ComputeShareStatisticsAsync(share))); + Log.Debug("Share statistics updated"); + // one of several thigns happened above before we got here: // this method was called with forceRescan = true // the storage mode is memory, and we loaded the in-memory db from a valid backup @@ -404,8 +432,8 @@ namespace slskd.Shares Faulted = false, Ready = true, ScanProgress = 1, - Directories = Local.Repository.CountDirectories(), - Files = Local.Repository.CountFiles(), + Directories = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)), + Files = Hosts.Sum(host => host.Shares.Sum(share => share.Directories)), }); } catch (Exception ex) -- cgit v1.2.3 From 8fa74223069adf4b760dd945fec08a0a81a5c6f6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Nov 2022 09:27:05 -0500 Subject: pass repository into ShareScanner --- src/slskd/Shares/ShareScanner.cs | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index d2002e19..1648c850 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -45,8 +45,9 @@ namespace slskd.Shares /// /// The list of shares from which to fill the cache. /// The current options snapshot. + /// The repository to update. /// The operation context. - Task ScanAsync(IEnumerable shares, Options.SharesOptions options); + Task ScanAsync(IEnumerable shares, Options.SharesOptions options, IShareRepository repository); /// /// Cancels the currently running fill operation, if one is running. @@ -64,16 +65,13 @@ namespace slskd.Shares /// Initializes a new instance of the class. /// /// - /// /// public ShareScanner( int workerCount, - IShareRepository shareRepository, ISoulseekFileFactory soulseekFileFactory = null) { WorkerCount = workerCount; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); - Repository = shareRepository; } /// @@ -88,15 +86,15 @@ namespace slskd.Shares private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private CancellationTokenSource CancellationTokenSource { get; set; } - private IShareRepository Repository { get; } /// /// Scans the configured shares and fills the cache. /// /// The list of shares from which to fill the cache. /// The current options snapshot. + /// The repository to update. /// The operation context. - public async Task ScanAsync(IEnumerable shares, Options.SharesOptions options) + public async Task ScanAsync(IEnumerable shares, Options.SharesOptions options, IShareRepository repository) { // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) @@ -127,10 +125,10 @@ namespace slskd.Shares // it's possible that the database was tampered with between the time it was checked at startup and now // validate the tables, and if there's an issue, drop and recreate everything. - if (!Repository.TryValidate()) + if (!repository.TryValidate()) { Log.Warning("Shared file cache missing or invalid. Re-creating prior to scan."); - Repository.Create(discardExisting: true); + repository.Create(discardExisting: true); Log.Information("Shared file cache re-created and ready for scan."); } @@ -142,7 +140,7 @@ namespace slskd.Shares var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - Repository.InsertScan(timestamp, options); + repository.InsertScan(timestamp, options); var sw = new Stopwatch(); var swSnapshot = 0L; @@ -166,7 +164,7 @@ namespace slskd.Shares Log.Information("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; - // derive a list of all directories from all shares skip hidden and system directories, as well as anything that + // derive a list of all directories from all shares. skip hidden and system directories, as well as anything that // can't be accessed due to security restrictions. it's necessary to enumerate these directories up front so we // can deduplicate directories and apply exclusions var unmaskedDirectories = Shares @@ -232,7 +230,7 @@ namespace slskd.Shares var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - Repository.InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek(), timestamp); + repository.InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek(), timestamp); // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized // filename and with a value of a Soulseek.File object @@ -262,7 +260,7 @@ namespace slskd.Shares continue; } - Repository.InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file, timestamp); + repository.InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file, timestamp); } } catch (Exception ex) @@ -313,13 +311,13 @@ namespace slskd.Shares Log.Information("Scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; - var deletedFiles = Repository.PruneFiles(olderThanTimestamp: timestamp); - var deletedDirectories = Repository.PruneDirectories(olderThanTimestamp: timestamp); + var deletedFiles = repository.PruneFiles(olderThanTimestamp: timestamp); + var deletedDirectories = repository.PruneDirectories(olderThanTimestamp: timestamp); Log.Information("Removed or renamed {Files} files and {Directories} directories in {Elapsed}ms", deletedFiles, deletedDirectories, sw.ElapsedMilliseconds - swSnapshot); Log.Information("Rebuilding filename index..."); - Repository.RebuildFilenameIndex(); + repository.RebuildFilenameIndex(); Log.Information("Filename index rebuild complete"); } catch (OperationCanceledException) @@ -330,10 +328,10 @@ namespace slskd.Shares State.SetValue(state => state with { Cancelled = true }); } - Repository.UpdateScan(timestamp, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + repository.UpdateScan(timestamp, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); - var directoryCount = Repository.CountDirectories(); - var fileCount = Repository.CountFiles(); + var directoryCount = repository.CountDirectories(); + var fileCount = repository.CountFiles(); State.SetValue(state => state with { -- cgit v1.2.3 From 573391fa9603d8cb79da71c2d3c005d4bb199729 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Nov 2022 19:20:20 -0500 Subject: display share host --- src/web/src/components/System/Shares/ShareTable.js | 2 ++ src/web/src/components/System/Shares/index.js | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/System/Shares/ShareTable.js b/src/web/src/components/System/Shares/ShareTable.js index d264fc8f..095a8380 100644 --- a/src/web/src/components/System/Shares/ShareTable.js +++ b/src/web/src/components/System/Shares/ShareTable.js @@ -13,6 +13,7 @@ const ShareTable = ({ shares, onClick }) => { + Host Local Path Directories Files @@ -29,6 +30,7 @@ const ShareTable = ({ shares, onClick }) => { } > {shares.map((share, index) => ( + {share.host} onClick(share)}> {share.localPath} diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 6759ad6f..0d93a6a3 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -1,5 +1,6 @@ import React, { useState, useEffect } from 'react'; import { toast } from 'react-toastify'; +import { flatten } from 'lodash'; import * as sharesLib from '../../../lib/shares'; import { @@ -39,7 +40,13 @@ const Index = ({ state = {} } = {}) => { const getAll = async () => { try { setLoading(true); - setShares(await sharesLib.getAll()); + + const sharesByHost = await sharesLib.getAll(); + const flattened = Object.entries(sharesByHost).reduce((acc, [host, shares]) => { + return acc.concat(shares.map(share => ({ host, ...share }))); + }, []); + + setShares(flattened); } catch (error) { console.error(error); toast.error(error?.response?.data ?? error?.message ?? error); -- cgit v1.2.3 From 964d50bc5156069b4404f29f823a4a21bd15ffe5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Nov 2022 09:13:26 -0500 Subject: remove unused import --- src/web/src/components/System/Shares/index.js | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 0d93a6a3..f4f9ac94 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -1,6 +1,5 @@ import React, { useState, useEffect } from 'react'; import { toast } from 'react-toastify'; -import { flatten } from 'lodash'; import * as sharesLib from '../../../lib/shares'; import { -- cgit v1.2.3