aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-06-02 10:33:35 -0500
committerGitHub <noreply@github.com>2022-06-02 10:33:35 -0500
commite044a75f285b1b1bfb19631ea2eef5509714a703 (patch)
treea9bdec768dbd36d831fb655aeefd5754e96d8e87 /src
parentadf5e7800452e861903b00faa5729c92187ef3ce (diff)
parent908972ae3655973cb2d1536e12b7c2dd42437062 (diff)
downloadslskd-e044a75f285b1b1bfb19631ea2eef5509714a703.tar.gz
Merge branch 'master' into dependabot/npm_and_yarn/src/web/eventsource-1.1.1
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs90
-rw-r--r--src/slskd/Common/Exceptions/NotFoundException.cs (renamed from src/slskd/Common/Exceptions/ShareAliasException.cs)22
-rw-r--r--src/slskd/Core/API/Controllers/ApplicationController.cs15
-rw-r--r--src/slskd/Core/API/Controllers/OptionsController.cs20
-rw-r--r--src/slskd/Program.cs4
-rw-r--r--src/slskd/Search/SearchService.cs15
-rw-r--r--src/slskd/Shares/API/Controllers/SharesController.cs195
-rw-r--r--src/slskd/Shares/API/DTO/SummarizedShare.cs32
-rw-r--r--src/slskd/Shares/Domain/Share.cs26
-rw-r--r--src/slskd/Shares/IShareService.cs82
-rw-r--r--src/slskd/Shares/ShareService.cs183
-rw-r--r--src/slskd/Shares/SharedFileCache.cs53
-rw-r--r--src/slskd/Shares/SoulseekFileFactory.cs2
-rw-r--r--src/slskd/State.cs23
-rw-r--r--src/web/src/components/App.css28
-rw-r--r--src/web/src/components/App.js18
-rw-r--r--src/web/src/components/Browse/Browse.js2
-rw-r--r--src/web/src/components/Search/Detail/SearchDetailHeader.js6
-rw-r--r--src/web/src/components/Search/List/SearchList.js51
-rw-r--r--src/web/src/components/Search/Search.css17
-rw-r--r--src/web/src/components/Search/Searches.js3
-rw-r--r--src/web/src/components/Shared/PlaceholderSegment.js19
-rw-r--r--src/web/src/components/Shared/ShrinkableButton.js6
-rw-r--r--src/web/src/components/System/Info/index.js (renamed from src/web/src/components/System/Info.js)50
-rw-r--r--src/web/src/components/System/Logs/index.js (renamed from src/web/src/components/System/Logs.js)9
-rw-r--r--src/web/src/components/System/Options/DebugModal.js66
-rw-r--r--src/web/src/components/System/Options/Edit.js87
-rw-r--r--src/web/src/components/System/Options/EditModal.js105
-rw-r--r--src/web/src/components/System/Options/View.js30
-rw-r--r--src/web/src/components/System/Options/index.js87
-rw-r--r--src/web/src/components/System/Shares/ContentsModal.js80
-rw-r--r--src/web/src/components/System/Shares/ExclusionTable.js35
-rw-r--r--src/web/src/components/System/Shares/ShareTable.js47
-rw-r--r--src/web/src/components/System/Shares/index.js78
-rw-r--r--src/web/src/components/System/System.css40
-rw-r--r--src/web/src/components/System/System.js49
-rw-r--r--src/web/src/components/Transfers/TransferGroup.js4
-rw-r--r--src/web/src/components/Transfers/Transfers.js6
-rw-r--r--src/web/src/lib/options.js4
-rw-r--r--src/web/src/lib/shares.js23
40 files changed, 1373 insertions, 339 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 1064e56a..0144daa2 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -48,7 +48,6 @@ namespace slskd
public interface IApplication : IHostedService
{
public Task CheckVersionAsync();
- public Task RescanSharesAsync();
public void CollectGarbage();
}
@@ -83,7 +82,7 @@ namespace slskd
IRoomTracker roomTracker,
IRoomService roomService,
IUserService userService,
- ISharedFileCache sharedFileCache,
+ IShareService shareService,
IPushbulletService pushbulletService,
IHubContext<ApplicationHub> applicationHub,
IHubContext<LogsHub> logHub)
@@ -98,8 +97,8 @@ namespace slskd
State = state;
State.OnChange(state => State_OnChange(state));
- SharedFileCache = sharedFileCache;
- SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state));
+ Shares = shareService;
+ Shares.StateMonitor.OnChange(state => ShareState_OnChange(state));
TransferTracker = transferTracker;
Transfers = transferService;
@@ -153,7 +152,6 @@ namespace slskd
private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1);
private Options PreviousOptions { get; set; }
private IPushbulletService Pushbullet { get; }
- private ISharedFileCache SharedFileCache { get; set; }
private DateTime SharesRefreshStarted { get; set; }
private IManagedState<State> State { get; }
private ITransferTracker TransferTracker { get; set; }
@@ -161,6 +159,7 @@ namespace slskd
private IHubContext<ApplicationHub> ApplicationHub { get; set; }
private IHubContext<LogsHub> LogHub { get; set; }
private IUserService Users { get; set; }
+ private IShareService Shares { get; set; }
public void CollectGarbage()
{
@@ -226,12 +225,6 @@ namespace slskd
}
}
- /// <summary>
- /// Re-scans shared directories.
- /// </summary>
- /// <returns>The operation context.</returns>
- public Task RescanSharesAsync() => SharedFileCache.FillAsync();
-
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
{
Log.Information("Configuring client");
@@ -313,7 +306,7 @@ namespace slskd
}
else
{
- _ = SharedFileCache.FillAsync();
+ _ = Shares.StartScanAsync();
}
if (OptionsAtStartup.NoConnect)
@@ -344,12 +337,12 @@ namespace slskd
/// <param name="username">The username of the requesting user.</param>
/// <param name="endpoint">The IP endpoint of the requesting user.</param>
/// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns>
- private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint)
+ private async Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint)
{
- var directories = SharedFileCache.Browse()
+ var directories = (await Shares.BrowseAsync())
.Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes
- return Task.FromResult(new BrowseResponse(directories));
+ return new BrowseResponse(directories);
}
private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args)
@@ -448,7 +441,7 @@ namespace slskd
// send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero
// initially, but we'll update them when the cache is filled.
- _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files);
+ _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files);
}
private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args)
@@ -516,9 +509,7 @@ namespace slskd
private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args)
{
- // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}]
- // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}]
- // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s");
+ // no-op. this is really verbose, use for troubleshooting.
}
private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args)
@@ -560,10 +551,10 @@ namespace slskd
/// <param name="token">The unique token for the request, supplied by the requesting user.</param>
/// <param name="directory">The requested directory.</param>
/// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns>
- private Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory)
+ private async Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory)
{
- var dir = SharedFileCache.List(directory);
- return Task.FromResult(dir);
+ var dir = await Shares.ListDirectoryAsync(directory);
+ return dir;
}
/// <summary>
@@ -581,18 +572,28 @@ namespace slskd
/// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for
/// security reasons.
/// </exception>
- private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker)
+ private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker)
{
_ = endpoint;
- var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath();
-
- var fileInfo = new FileInfo(localFilename);
+ string localFilename;
+ FileInfo fileInfo = default;
Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]");
- if (!fileInfo.Exists)
+ try
{
- Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found.");
+ localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath();
+
+ fileInfo = new FileInfo(localFilename);
+
+ if (!fileInfo.Exists)
+ {
+ throw new NotFoundException();
+ }
+ }
+ catch (NotFoundException)
+ {
+ Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found.");
throw new DownloadEnqueueException($"File not shared.");
}
@@ -600,7 +601,7 @@ namespace slskd
{
// in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse
Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]");
- return Task.CompletedTask;
+ return;
}
// create a new cancellation token source so that we can cancel the upload from the UI.
@@ -623,7 +624,7 @@ namespace slskd
// accept all download requests, and begin the upload immediately. normally there would be an internal queue, and
// uploads would be handled separately.
- Task.Run(async () =>
+ _ = Task.Run(async () =>
{
// users with uploads must be watched so that we can keep informed of their
// online status, privileges, and statistics. this is so that we can accurately
@@ -639,9 +640,6 @@ namespace slskd
{
Console.WriteLine($"[UPLOAD FAILED] {t.Exception}");
}, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget
-
- // return a completed task so that the invoking code can respond to the remote client.
- return Task.CompletedTask;
}
private async Task OptionsMonitor_OnChange(Options newOptions)
@@ -681,14 +679,14 @@ namespace slskd
if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any()
|| newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any())
{
- State.SetValue(state => state with { PendingShareRescan = true });
+ State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } });
Log.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect.");
}
if (PreviousOptions.Filters.Share.Except(newOptions.Filters.Share).Any()
|| newOptions.Filters.Share.Except(PreviousOptions.Filters.Share).Any())
{
- State.SetValue(state => state with { PendingShareRescan = true });
+ State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } });
Log.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect.");
}
@@ -826,7 +824,7 @@ namespace slskd
return null;
}
- var results = await SharedFileCache.SearchAsync(query);
+ var results = await Shares.SearchAsync(query);
if (results.Any())
{
@@ -846,30 +844,30 @@ namespace slskd
return null;
}
- private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state)
+ private void ShareState_OnChange((ShareState Previous, ShareState Current) state)
{
var (previous, current) = state;
- if (!previous.Filling && current.Filling)
+ if (!previous.Scanning && current.Scanning)
{
SharesRefreshStarted = DateTime.UtcNow;
- State.SetValue(s => s with { SharedFileCache = current });
+ State.SetValue(s => s with { Shares = current });
Log.Information("Scanning shares");
}
- var lastProgress = Math.Round(previous.FillProgress * 100);
- var currentProgress = Math.Round(current.FillProgress * 100);
+ var lastProgress = Math.Round(previous.ScanProgress * 100);
+ var currentProgress = Math.Round(current.ScanProgress * 100);
if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0)
{
- State.SetValue(s => s with { SharedFileCache = current });
+ State.SetValue(s => s with { Shares = current });
Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files);
}
- if (previous.Filling && !current.Filling)
+ if (previous.Scanning && !current.Scanning)
{
- State.SetValue(s => s with { SharedFileCache = current });
+ State.SetValue(s => s with { Shares = current });
if (current.Faulted)
{
@@ -877,14 +875,14 @@ namespace slskd
}
else
{
- State.SetValue(s => s with { PendingShareRescan = false });
+ State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } });
Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds);
SharesRefreshStarted = default;
if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn))
{
- _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files);
+ _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files);
}
}
}
diff --git a/src/slskd/Common/Exceptions/ShareAliasException.cs b/src/slskd/Common/Exceptions/NotFoundException.cs
index 3047d0a9..cc0f6969 100644
--- a/src/slskd/Common/Exceptions/ShareAliasException.cs
+++ b/src/slskd/Common/Exceptions/NotFoundException.cs
@@ -1,4 +1,4 @@
-// <copyright file="ShareAliasException.cs" company="slskd Team">
+// <copyright file="NotFoundException.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -22,31 +22,31 @@ namespace slskd
using System.Runtime.Serialization;
/// <summary>
- /// Represents an error that occurs when multiple share scans are attempted concurrently.
+ /// Represents errors that originate when a searched resource can't be located.
/// </summary>
[ExcludeFromCodeCoverage]
[Serializable]
- public class ShareAliasException : SlskdException
+ public class NotFoundException : SlskdException
{
/// <summary>
- /// Initializes a new instance of the <see cref="ShareAliasException"/> class.
+ /// Initializes a new instance of the <see cref="NotFoundException"/> class.
/// </summary>
- public ShareAliasException()
+ public NotFoundException()
: base()
{
}
/// <summary>
- /// Initializes a new instance of the <see cref="ShareAliasException"/> class with a specified error message.
+ /// Initializes a new instance of the <see cref="NotFoundException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
- public ShareAliasException(string message)
+ public NotFoundException(string message)
: base(message)
{
}
/// <summary>
- /// Initializes a new instance of the <see cref="ShareAliasException"/> class with a specified error message and a
+ /// Initializes a new instance of the <see cref="NotFoundException"/> class with a specified error message and a
/// reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
@@ -54,17 +54,17 @@ namespace slskd
/// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
/// inner exception is specified.
/// </param>
- public ShareAliasException(string message, Exception innerException)
+ public NotFoundException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
- /// Initializes a new instance of the <see cref="ShareAliasException"/> class with serialized data.
+ /// Initializes a new instance of the <see cref="NotFoundException"/> class with serialized data.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
- protected ShareAliasException(SerializationInfo info, StreamingContext context)
+ protected NotFoundException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs
index cd03d96f..3cf3c0a3 100644
--- a/src/slskd/Core/API/Controllers/ApplicationController.cs
+++ b/src/slskd/Core/API/Controllers/ApplicationController.cs
@@ -136,20 +136,5 @@ namespace slskd.Core.API
return Ok();
}
-
- [HttpPut]
- [Route("shares")]
- [Authorize]
- public IActionResult RescanSharesAsync()
- {
- if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling)
- {
- return Conflict("A share scan is already in progress.");
- }
-
- _ = Application.RescanSharesAsync();
-
- return Ok();
- }
}
}
diff --git a/src/slskd/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs
index 062de8f7..b0856ed3 100644
--- a/src/slskd/Core/API/Controllers/OptionsController.cs
+++ b/src/slskd/Core/API/Controllers/OptionsController.cs
@@ -21,8 +21,10 @@ namespace slskd.Core.API
{
using System;
using System.IO;
+ using System.Reflection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+ using Microsoft.Extensions.Configuration;
using Serilog;
using slskd.Validation;
using IOFile = System.IO.File;
@@ -74,6 +76,24 @@ namespace slskd.Core.API
return Ok(OptionsAtStartup.Redact());
}
+ /// <summary>
+ /// Gets the debug view of the current application options.
+ /// </summary>
+ /// <returns></returns>
+ [HttpGet]
+ [Route("debug")]
+ [Authorize]
+ [ProducesResponseType(typeof(string), 200)]
+ public IActionResult Debug()
+ {
+ // retrieve the IConfigurationRoot instance with reflection to avoid
+ // exposing it as a public member of Program.
+ var property = typeof(Program).GetProperty("Configuration", BindingFlags.NonPublic | BindingFlags.Static);
+ var configurationRoot = (IConfigurationRoot)property.GetValue(null, null);
+
+ return Ok(configurationRoot.GetDebugView());
+ }
+
[HttpGet]
[Authorize]
[Route("yaml/location")]
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 40e6e72d..df1fb55c 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -453,7 +453,7 @@ namespace slskd
services.AddSingleton<IConversationTracker, ConversationTracker>();
services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
- services.AddSingleton<ISharedFileCache, SharedFileCache>();
+ services.AddSingleton<IShareService, ShareService>();
services.AddSingleton<ISearchService, SearchService>();
services.AddSingleton<IUserService, UserService>();
@@ -682,7 +682,7 @@ namespace slskd
}
// if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused.
- // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next
+ // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next
// middleware
app.Use(async (context, next) =>
{
diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs
index 949a7088..f077e76b 100644
--- a/src/slskd/Search/SearchService.cs
+++ b/src/slskd/Search/SearchService.cs
@@ -162,18 +162,23 @@ namespace slskd.Search
/// </summary>
/// <param name="search">The search to delete.</param>
/// <returns>The operation context.</returns>
- public async Task DeleteAsync(Search search)
+ public Task DeleteAsync(Search search)
{
if (search == default)
{
throw new ArgumentNullException(nameof(search));
}
- using var context = ContextFactory.CreateDbContext();
- context.Searches.Remove(search);
- await context.SaveChangesAsync();
+ return DoDeleteAsync(search);
- await SearchHub.BroadcastDeleteAsync(search);
+ async Task DoDeleteAsync(Search search)
+ {
+ using var context = ContextFactory.CreateDbContext();
+ context.Searches.Remove(search);
+ await context.SaveChangesAsync();
+
+ await SearchHub.BroadcastDeleteAsync(search);
+ }
}
/// <summary>
diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs
new file mode 100644
index 00000000..41178bac
--- /dev/null
+++ b/src/slskd/Shares/API/Controllers/SharesController.cs
@@ -0,0 +1,195 @@
+// <copyright file="SharesController.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Shares.API
+{
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+ using Soulseek;
+
+ /// <summary>
+ /// Shares.
+ /// </summary>
+ [ApiController]
+ [ApiVersion("0")]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [Authorize]
+ public class SharesController : ControllerBase
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SharesController"/> class.
+ /// </summary>
+ /// <param name="shareService"></param>
+ public SharesController(
+ IShareService shareService)
+ {
+ Shares = shareService;
+ }
+
+ private IShareService Shares { get; }
+
+ /// <summary>
+ /// Gets the current list of shares.
+ /// </summary>
+ /// <response code="200">The request completed successfully.</response>
+ /// <returns></returns>
+ [HttpGet("")]
+ [Authorize]
+ [ProducesResponseType(typeof(IEnumerable<SummarizedShare>), 200)]
+ public async Task<IActionResult> List()
+ {
+ var browse = await Shares.BrowseAsync();
+
+ var summary = Shares.CachedShares.Select(share =>
+ {
+ var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath));
+ var fileCount = directories.Aggregate(seed: 0, (sum, directory) =>
+ {
+ sum += directory.FileCount;
+ return sum;
+ });
+
+ return new SummarizedShare()
+ {
+ Id = share.Id,
+ Alias = share.Alias,
+ IsExcluded = share.IsExcluded,
+ LocalPath = share.LocalPath,
+ Mask = share.Mask,
+ Raw = share.Raw,
+ RemotePath = share.RemotePath,
+ Directories = directories.Count(),
+ Files = fileCount,
+ };
+ });
+
+ return Ok(summary);
+ }
+
+ /// <summary>
+ /// Gets the share associated with the specified <see paramref="id"/>.
+ /// </summary>
+ /// <param name="id">The id of the share.</param>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The requested share could not be found.</response>
+ /// <returns></returns>
+ [HttpGet("{id}")]
+ [Authorize]
+ [ProducesResponseType(typeof(SummarizedShare), 200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> Get(string id)
+ {
+ var share = Shares.Shares.FirstOrDefault(share => share.Id == id);
+
+ if (share == default)
+ {
+ return NotFound();
+ }
+
+ var browse = await Shares.BrowseAsync();
+ var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath));
+ var fileCount = directories.Aggregate(seed: 0, (sum, directory) =>
+ {
+ sum += directory.FileCount;
+ return sum;
+ });
+
+ var summary = new SummarizedShare()
+ {
+ Id = share.Id,
+ Alias = share.Alias,
+ IsExcluded = share.IsExcluded,
+ LocalPath = share.LocalPath,
+ Mask = share.Mask,
+ Raw = share.Raw,
+ RemotePath = share.RemotePath,
+ Directories = directories.Count(),
+ Files = fileCount,
+ };
+
+ return Ok(summary);
+ }
+
+ /// <summary>
+ /// Returns a list of all shared directories and files.
+ /// </summary>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ [HttpGet("contents")]
+ [Authorize]
+ [ProducesResponseType(typeof(IEnumerable<Directory>), 200)]
+ public async Task<IActionResult> BrowseAll()
+ {
+ return Ok(await Shares.BrowseAsync());
+ }
+
+ /// <summary>
+ /// Gets the contents of the share associated with the specified <see paramref="id"/>.
+ /// </summary>
+ /// <param name="id">The id of the share.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The requested share could not be found.</response>
+ [HttpGet("{id}/contents")]
+ [ProducesResponseType(typeof(IEnumerable<Directory>), 200)]
+ [ProducesResponseType(404)]
+ public async Task<IActionResult> BrowseShare(string id)
+ {
+ var share = Shares.Shares.FirstOrDefault(share => share.Id == id);
+
+ if (share == default)
+ {
+ return NotFound();
+ }
+
+ var contents = (await Shares.BrowseAsync())
+ .Where(directory => directory.Name.StartsWith(share.RemotePath));
+
+ return Ok(contents);
+ }
+
+ /// <summary>
+ /// Initiates a scan of the configured shares.
+ /// </summary>
+ /// <returns></returns>
+ /// <response code="204">The request completed successfully.</response>
+ /// <response code="409">A share scan is already in progress.</response>
+ [HttpPut]
+ [Route("")]
+ [Authorize]
+ [ProducesResponseType(204)]
+ [ProducesResponseType(409)]
+ public async Task<IActionResult> RescanSharesAsync()
+ {
+ try
+ {
+ await Shares.StartScanAsync();
+ }
+ catch (ShareScanInProgressException)
+ {
+ return Conflict("A share scan is already in progress.");
+ }
+
+ return Ok();
+ }
+ }
+}
diff --git a/src/slskd/Shares/API/DTO/SummarizedShare.cs b/src/slskd/Shares/API/DTO/SummarizedShare.cs
new file mode 100644
index 00000000..a1d6ed7b
--- /dev/null
+++ b/src/slskd/Shares/API/DTO/SummarizedShare.cs
@@ -0,0 +1,32 @@
+// <copyright file="SummarizedShare.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.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 Mask { 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/Domain/Share.cs b/src/slskd/Shares/Domain/Share.cs
index 890c8565..9bdbc002 100644
--- a/src/slskd/Shares/Domain/Share.cs
+++ b/src/slskd/Shares/Domain/Share.cs
@@ -18,6 +18,7 @@
namespace slskd.Shares
{
using System.Linq;
+ using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
/// <summary>
@@ -28,6 +29,28 @@ namespace slskd.Shares
/// <summary>
/// Initializes a new instance of the <see cref="Share"/> class.
/// </summary>
+ /// <param name="id"></param>
+ /// <param name="alias"></param>
+ /// <param name="isExcluded"></param>
+ /// <param name="localPath"></param>
+ /// <param name="mask"></param>
+ /// <param name="raw"></param>
+ /// <param name="remotePath"></param>
+ [JsonConstructor]
+ public Share (string id, string alias, bool isExcluded, string localPath, string mask, string raw, string remotePath)
+ {
+ Id = id;
+ Alias = alias;
+ IsExcluded = isExcluded;
+ LocalPath = localPath;
+ Mask = mask;
+ Raw = raw;
+ RemotePath = remotePath;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Share"/> class.
+ /// </summary>
/// <param name="share"></param>
public Share(string share)
{
@@ -63,8 +86,11 @@ namespace slskd.Shares
var aliasedSegment = LocalPath[(parent.Length + 1)..];
RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias);
+
+ Id = Compute.Sha1Hash(RemotePath);
}
+ public string Id { get; init; }
public string Alias { get; init; }
public bool IsExcluded { get; init; }
public string LocalPath { get; init; }
diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs
new file mode 100644
index 00000000..fd88f2b0
--- /dev/null
+++ b/src/slskd/Shares/IShareService.cs
@@ -0,0 +1,82 @@
+// <copyright file="IShareService.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Shares
+{
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+ using Soulseek;
+
+ /// <summary>
+ /// Provides control and interactions with configured shares and shared files.
+ /// </summary>
+ public interface IShareService
+ {
+ /// <summary>
+ /// Gets the list of shares stored in the cache.
+ /// </summary>
+ IReadOnlyList<Share> CachedShares { get; }
+
+ /// <summary>
+ /// Gets the list of configured shares.
+ /// </summary>
+ IReadOnlyList<Share> Shares { get; }
+
+ /// <summary>
+ /// Gets the state monitor for the service.
+ /// </summary>
+ public IStateMonitor<ShareState> StateMonitor { get; }
+
+ /// <summary>
+ /// Returns the entire contents of the share.
+ /// </summary>
+ /// <returns>The entire contents of the share.</returns>
+ Task<IEnumerable<Directory>> BrowseAsync();
+
+ /// <summary>
+ /// Returns the contents of the specified <paramref name="directory"/>.
+ /// </summary>
+ /// <param name="directory">The directory for which the contents are to be listed.</param>
+ /// <returns>The contents of the directory.</returns>
+ Task<Directory> ListDirectoryAsync(string directory);
+
+ /// <summary>
+ /// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a
+ /// configured share.
+ /// </summary>
+ /// <param name="remoteFilename">The fully qualified filename to resolve.</param>
+ /// <returns>The resolved local filename.</returns>
+ /// <exception cref="NotFoundException">
+ /// Thrown when the specified remote filename can not be associated with a configured share.
+ /// </exception>
+ Task<string> ResolveFilenameAsync(string remoteFilename);
+
+ /// <summary>
+ /// Searches the cache for the specified <paramref name="query"/> and returns the matching files.
+ /// </summary>
+ /// <param name="query">The query for which to search.</param>
+ /// <returns>The matching files.</returns>
+ Task<IEnumerable<File>> SearchAsync(SearchQuery query);
+
+ /// <summary>
+ /// Starts a scan of the configured shares.
+ /// </summary>
+ /// <returns>The operation context.</returns>
+ /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
+ Task StartScanAsync();
+ }
+}
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
new file mode 100644
index 00000000..ead96d10
--- /dev/null
+++ b/src/slskd/Shares/ShareService.cs
@@ -0,0 +1,183 @@
+// <copyright file="ShareService.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+using Microsoft.Extensions.Options;
+
+namespace slskd.Shares
+{
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text.RegularExpressions;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using Soulseek;
+
+ /// <summary>
+ /// Provides control and interactions with configured shares and shared files.
+ /// </summary>
+ public class ShareService : IShareService
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareService"/> class.
+ /// </summary>
+ /// <param name="optionsMonitor"></param>
+ /// <param name="sharedFileCache"></param>
+ public ShareService(
+ IOptionsMonitor<Options> optionsMonitor,
+ ISharedFileCache sharedFileCache = null)
+ {
+ Cache = sharedFileCache ?? new SharedFileCache();
+ Cache.StateMonitor.OnChange(cacheState =>
+ {
+ var (previous, current) = cacheState;
+
+ State.SetValue(state => state with
+ {
+ // scan is pending if faulted, or if state DIDN'T just transition from filling to not filling AND a scan was already pending
+ ScanPending = current.Faulted || (!(previous.Filling && !current.Filling) && state.ScanPending),
+ Scanning = current.Filling,
+ Faulted = current.Faulted,
+ ScanProgress = current.FillProgress,
+ Directories = current.Directories,
+ Files = current.Files,
+ });
+
+ if (previous.Filling && !current.Filling)
+ {
+ CachedShares = current.Shares.ToList().AsReadOnly();
+ }
+ });
+
+ OptionsMonitor = optionsMonitor;
+ OptionsMonitor.OnChange(options => Configure(options));
+
+ Configure(OptionsMonitor.CurrentValue);
+ }
+
+ /// <summary>
+ /// Gets the list of configured shares.
+ /// </summary>
+ public IReadOnlyList<Share> Shares => SharesList.AsReadOnly();
+
+ /// <summary>
+ /// Gets the list of shares stored in the cache.
+ /// </summary>
+ public IReadOnlyList<Share> CachedShares { get; private set; } = new List<Share>().AsReadOnly();
+
+ /// <summary>
+ /// Gets the state monitor for the service.
+ /// </summary>
+ public IStateMonitor<ShareState> StateMonitor => State;
+
+ private ISharedFileCache Cache { get; }
+ private string LastOptionsHash { get; set; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private List<Share> SharesList { get; set; } = new List<Share>();
+ private IManagedState<ShareState> State { get; } = new ManagedState<ShareState>();
+ private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1);
+ private List<Regex> FilterRegexes { get; set; } = new List<Regex>();
+
+ /// <summary>
+ /// Returns the entire contents of the share.
+ /// </summary>
+ /// <returns>The entire contents of the share.</returns>
+ public Task<IEnumerable<Directory>> BrowseAsync()
+ => Task.FromResult(Cache.Browse());
+
+ /// <summary>
+ /// Returns the contents of the specified <paramref name="directory"/>.
+ /// </summary>
+ /// <param name="directory">The directory for which the contents are to be listed.</param>
+ /// <returns>The contents of the directory.</returns>
+ public Task<Directory> ListDirectoryAsync(string directory)
+ => Task.FromResult(Cache.List(directory));
+
+ /// <summary>
+ /// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a
+ /// configured share.
+ /// </summary>
+ /// <param name="remoteFilename">The fully qualified filename to resolve.</param>
+ /// <returns>The resolved local filename.</returns>
+ /// <exception cref="NotFoundException">
+ /// Thrown when the specified remote filename can not be associated with a configured share.
+ /// </exception>
+ public Task<string> ResolveFilenameAsync(string remoteFilename)
+ {
+ var resolvedFilename = Cache.Resolve(remoteFilename);
+
+ if (resolvedFilename == remoteFilename)
+ {
+ throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a configured share.");
+ }
+
+ return Task.FromResult(resolvedFilename);
+ }
+
+ /// <summary>
+ /// Searches the cache for the specified <paramref name="query"/> and returns the matching files.
+ /// </summary>
+ /// <param name="query">The query for which to search.</param>
+ /// <returns>The matching files.</returns>
+ public Task<IEnumerable<File>> SearchAsync(SearchQuery query)
+ => Cache.SearchAsync(query);
+
+ /// <summary>
+ /// Starts a scan of the configured shares.
+ /// </summary>
+ /// <returns>The operation context.</returns>
+ /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
+ public Task StartScanAsync()
+ => Cache.FillAsync(Shares, FilterRegexes);
+
+ private void Configure(Options options)
+ {
+ SyncRoot.Wait();
+
+ try
+ {
+ var optionsHash = Compute.Sha1Hash(string.Join(';', options.Directories.Shared));
+
+ if (optionsHash == LastOptionsHash)
+ {
+ return;
+ }
+
+ var shares = options.Directories.Shared
+ .Select(share => share.TrimEnd('/', '\\'))
+ .ToHashSet() // remove duplicates
+ .Select(share => new Share(share)) // convert to Shares
+ .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent
+ .ToList();
+
+ var regexes = options.Filters.Share
+ .Select(filter => new Regex(filter, RegexOptions.Compiled))
+ .ToList();
+
+ SharesList = shares;
+ FilterRegexes = regexes;
+
+ State.SetValue(state => state with { ScanPending = true });
+
+ LastOptionsHash = optionsHash;
+ }
+ finally
+ {
+ SyncRoot.Release();
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs
index ac996fa6..6b7a3ca3 100644
--- a/src/slskd/Shares/SharedFileCache.cs
+++ b/src/slskd/Shares/SharedFileCache.cs
@@ -16,7 +16,6 @@
// </copyright>
using System.IO;
-using Microsoft.Extensions.Options;
namespace slskd.Shares
{
@@ -51,8 +50,11 @@ namespace slskd.Shares
/// <summary>
/// Scans the configured shares and fills the cache.
/// </summary>
+ /// <remarks>Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete.</remarks>
+ /// <param name="shares">The list of shares from which to fill the cache.</param>
+ /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param>
/// <returns>The operation context.</returns>
- Task FillAsync();
+ Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters);
/// <summary>
/// Returns the contents of the specified <paramref name="directory"/>.
@@ -85,13 +87,9 @@ namespace slskd.Shares
/// <summary>
/// Initializes a new instance of the <see cref="SharedFileCache"/> class.
/// </summary>
- /// <param name="optionsMonitor"></param>
/// <param name="soulseekFileFactory"></param>
- public SharedFileCache(
- IOptionsMonitor<Options> optionsMonitor,
- ISoulseekFileFactory soulseekFileFactory = null)
+ public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null)
{
- OptionsMonitor = optionsMonitor;
SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory();
}
@@ -100,15 +98,14 @@ namespace slskd.Shares
/// </summary>
public IStateMonitor<SharedFileCacheState> StateMonitor => State;
- private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>();
private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>();
private HashSet<string> MaskedDirectories { get; set; }
private Dictionary<string, File> MaskedFiles { get; set; }
- private IOptionsMonitor<Options> OptionsMonitor { get; set; }
private List<Share> Shares { get; set; }
+ private ISoulseekFileFactory SoulseekFileFactory { get; }
private SqliteConnection SQLite { get; set; }
+ private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>();
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1);
- private ISoulseekFileFactory SoulseekFileFactory { get; }
/// <summary>
/// Returns the contents of the cache.
@@ -164,8 +161,10 @@ namespace slskd.Shares
/// <summary>
/// Scans the configured shares and fills the cache.
/// </summary>
+ /// <param name="shares">The list of shares from which to fill the cache.</param>
+ /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param>
/// <returns>The operation context.</returns>
- public async Task FillAsync()
+ public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters)
{
// obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running.
if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0))
@@ -176,7 +175,14 @@ namespace slskd.Shares
try
{
- State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 });
+ State.SetValue(state => state with
+ {
+ Filling = true,
+ Filled = false,
+ FillProgress = 0,
+ Shares = Enumerable.Empty<Share>().ToList().AsReadOnly(),
+ });
+
Log.Debug("Starting shared file scan");
await Task.Yield();
@@ -187,12 +193,7 @@ namespace slskd.Shares
var swSnapshot = 0L;
sw.Start();
- Shares = OptionsMonitor.CurrentValue.Directories.Shared
- .Select(share => share.TrimEnd('/', '\\'))
- .ToHashSet() // remove duplicates
- .Select(share => new Share(share)) // convert to Shares
- .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent
- .ToList();
+ Shares = shares.ToList();
if (!Shares.Any())
{
@@ -236,9 +237,6 @@ namespace slskd.Shares
Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot);
swSnapshot = sw.ElapsedMilliseconds;
- var filters = OptionsMonitor.CurrentValue.Filters.Share
- .Select(filter => new Regex(filter, RegexOptions.Compiled));
-
var files = new Dictionary<string, File>();
var maskedDirectories = new HashSet<string>();
var current = 0;
@@ -300,7 +298,16 @@ namespace slskd.Shares
MaskedDirectories = maskedDirectories;
MaskedFiles = files;
- State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count });
+ State.SetValue(state => state with {
+ Filling = false,
+ Faulted = false,
+ Filled = true,
+ FillProgress = 1,
+ Directories = MaskedDirectories.Count,
+ Files = MaskedFiles.Count,
+ Shares = shares.ToList().AsReadOnly(),
+ });
+
Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}");
}
catch (Exception ex)
@@ -451,7 +458,7 @@ namespace slskd.Shares
SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared");
SQLite.Open();
- using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite);
+ using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite);
cmd.ExecuteNonQuery();
}
diff --git a/src/slskd/Shares/SoulseekFileFactory.cs b/src/slskd/Shares/SoulseekFileFactory.cs
index 5221265b..7cdd6174 100644
--- a/src/slskd/Shares/SoulseekFileFactory.cs
+++ b/src/slskd/Shares/SoulseekFileFactory.cs
@@ -48,7 +48,7 @@ namespace slskd.Shares
private static readonly string[] VideoExtensions = { "mkv", "ogv", "avi", "wmv", "asf", "mp4", "m4p", "m4v", "mpg", "mpe", "mpv", "mpg", "m2v" };
private static readonly HashSet<string> SupportedExtensions = AudioExtensions.Concat(VideoExtensions).ToHashSet();
- private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>();
+ private ILogger Log { get; } = Serilog.Log.ForContext<SoulseekFileFactory>();
/// <summary>
/// Creates an instance of <see cref="Soulseek.File"/> from the given path.
diff --git a/src/slskd/State.cs b/src/slskd/State.cs
index 0daa5d76..10ed80f6 100644
--- a/src/slskd/State.cs
+++ b/src/slskd/State.cs
@@ -21,6 +21,7 @@ namespace slskd
using System.Collections.Generic;
using System.Net;
using System.Text.Json.Serialization;
+ using slskd.Shares;
using slskd.Users;
using Soulseek;
@@ -32,10 +33,9 @@ namespace slskd
public VersionState Version { get; init; } = new VersionState();
public bool PendingReconnect { get; init; }
public bool PendingRestart { get; init; }
- public bool PendingShareRescan { get; init; }
public ServerState Server { get; init; } = new ServerState();
public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState();
- public SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState();
+ public ShareState Shares { get; init; } = new ShareState();
public string[] Rooms { get; init; } = Array.Empty<string>();
public User[] Users { get; init; } = Array.Empty<User>();
}
@@ -69,15 +69,25 @@ namespace slskd
public string BranchRoot { get; init; }
public bool CanAcceptChildren { get; init; }
public int ChildLimit { get; init; }
- public IReadOnlyCollection<string> Children { get; init; }
+ public IReadOnlyCollection<string> Children { get; init; } = new List<string>().AsReadOnly();
public bool HasParent { get; init; }
public bool IsBranchRoot { get; init; }
public string Parent { get; init; }
}
/// <summary>
- /// Share cache state.
+ /// Share state.
/// </summary>
+ public record ShareState
+ {
+ public bool ScanPending { get; init; }
+ public bool Scanning { get; init; }
+ public bool Faulted { get; init; }
+ public double ScanProgress { get; init; }
+ public int Directories { get; init; }
+ public int Files { get; init; }
+ }
+
public record SharedFileCacheState
{
/// <summary>
@@ -114,5 +124,10 @@ namespace slskd
/// Gets the number of directories excluded by filters.
/// </summary>
public int ExcludedDirectories { get; init; }
+
+ /// <summary>
+ /// Gets the list of shares stored in the cache.
+ /// </summary>
+ public IReadOnlyCollection<Share> Shares { get; init; } = new List<Share>().AsReadOnly();
}
} \ No newline at end of file
diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css
index e0935163..78b029b8 100644
--- a/src/web/src/components/App.css
+++ b/src/web/src/components/App.css
@@ -101,10 +101,23 @@ body {
line-height: 1.15 !important;
}
-.placeholder-segment {
+.placeholder-segment, .placeholder-segment-small {
opacity: .25;
}
+.placeholder-segment-small {
+ min-height: 6rem !important;
+}
+
+.placeholder-segment-small > .ui.icon.header {
+ font-size: 1em !important;
+}
+
+.placeholder-segment-small > .ui.icon.header > i {
+ font-size: 2em !important;
+}
+
+
.menu-icon-group {
font-size: 1.71428571em !important;
margin: 0 auto .5rem !important;
@@ -120,7 +133,7 @@ body {
background-color: transparent !important;
}
-.page {
+.view {
padding-left: 15px;
padding-right: 15px;
max-width: 1200px !important;
@@ -128,6 +141,15 @@ body {
margin-right: auto !important;
}
-.page:last-child {
+.view:last-child {
margin-bottom: 17px;
+}
+
+/* https://github.com/Semantic-Org/Semantic-UI-React/issues/3133#issuecomment-418766748 */
+.ui.dimmer .ui.modal-loader.loader:before {
+ border-color: rgba(0,0,0,.1);
+}
+
+.ui.dimmer .ui.modal-loader.loader:after {
+ border-color: #767676 transparent transparent;
} \ No newline at end of file
diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js
index 09039442..206cea34 100644
--- a/src/web/src/components/App.js
+++ b/src/web/src/components/App.js
@@ -116,8 +116,9 @@ class App extends Component {
render = () => {
const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted } = this.state;
- const { version = {}, server } = applicationState;
+ const { version = {}, server, pendingReconnect, pendingRestart, shares = {} } = applicationState;
const { isUpdateAvailable, current, latest } = version;
+ const { scanPending: pendingShareRescan } = shares;
if (!initialized) {
return <Loader active size='big'/>;
@@ -202,7 +203,7 @@ class App extends Component {
{server?.isConnected && <Menu.Item
onClick={() => disconnect()}
>
- <Icon name='plug' color='green'/>Connected
+ <Icon name='plug' color={pendingReconnect ? 'yellow' : 'green'}/>Connected
</Menu.Item>}
{(!server?.isConnected) && <Menu.Item
onClick={() => connect()}
@@ -212,6 +213,13 @@ class App extends Component {
<Icon name='close' color='red' corner='bottom right' className='menu-icon-no-shadow'/>
</Icon.Group>Disconnected
</Menu.Item>}
+ {(pendingReconnect || pendingRestart || pendingShareRescan) && <Menu.Item position='right'>
+ <Icon.Group className='menu-icon-group'>
+ <Link to={`${urlBase}/system/info`}>
+ <Icon name='exclamation circle' color='yellow'/>
+ </Link>
+ </Icon.Group>Pending Action
+ </Menu.Item>}
{isUpdateAvailable && <Modal
trigger={<Menu.Item position='right'>
<Icon.Group className='menu-icon-group'>
@@ -260,7 +268,7 @@ class App extends Component {
<AppContext.Provider value={{ state: applicationState, options: applicationOptions }}>
<Switch>
<Route path={`${urlBase}/searches/:id?`} render={(props) =>
- this.withTokenCheck(<div className='page'>
+ this.withTokenCheck(<div className='view'>
<Searches
server={applicationState.server}
{...props}
@@ -273,11 +281,11 @@ class App extends Component {
<Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/>
<Route path={`${urlBase}/uploads`} render={
(props) =>
- this.withTokenCheck(<div className='page'><Transfers {...props} direction='upload'/></div>)
+ this.withTokenCheck(<div className='view'><Transfers {...props} direction='upload'/></div>)
}/>
<Route path={`${urlBase}/downloads`} render={
(props) =>
- this.withTokenCheck(<div className='page'>
+ this.withTokenCheck(<div className='view'>
<Transfers {...props} direction='download' server={applicationState.server}/>
</div>)
}/>
diff --git a/src/web/src/components/Browse/Browse.js b/src/web/src/components/Browse/Browse.js
index e1a3c7f0..93cf31f0 100644
--- a/src/web/src/components/Browse/Browse.js
+++ b/src/web/src/components/Browse/Browse.js
@@ -90,7 +90,7 @@ class Browse extends Component {
try {
localStorage.setItem('soulseek-example-browse-state', lzString.compress(JSON.stringify(this.state)));
} catch (error) {
- console.log(error);
+ console.error(error);
}
};
diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.js b/src/web/src/components/Search/Detail/SearchDetailHeader.js
index ac613249..2071540f 100644
--- a/src/web/src/components/Search/Detail/SearchDetailHeader.js
+++ b/src/web/src/components/Search/Detail/SearchDetailHeader.js
@@ -63,11 +63,11 @@ const SearchDetailHeader = ({
// if the screen is less than 684 pixels, display the action buttons in a new segment, with full text.
return (
<>
- <Segment className='search-segment' raised>
- <Header className='search-detail-header'>
+ <Segment className='search-detail-header-segment' raised>
+ <Header>
<SearchStatusIcon state={state}/>{searchText}
</Header>
- {!isTinyScreen && <div className='search-detail-action-button'>
+ {!isTinyScreen && <div className='search-detail-header-buttons'>
<RefreshButton/>
<StopOrDeleteButton/>
</div>}
diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js
index db16fa71..11cfcb22 100644
--- a/src/web/src/components/Search/List/SearchList.js
+++ b/src/web/src/components/Search/List/SearchList.js
@@ -9,7 +9,6 @@ import {
Table,
Icon,
Loader,
- List,
} from 'semantic-ui-react';
const SearchList = ({
@@ -27,33 +26,29 @@ const SearchList = ({
connecting={connecting && <Loader active inline='centered' size='small'/>}
error={error && <ErrorSegment caption={error} />}
>
- <List>
- <List.Item>
- <Table size='large'>
- <Table.Header>
- <Table.Row>
- <Table.HeaderCell className="search-list-action"><Icon name="info circle"/></Table.HeaderCell>
- <Table.HeaderCell className="search-list-phrase">Search</Table.HeaderCell>
- <Table.HeaderCell className="search-list-files">Files</Table.HeaderCell>
- <Table.HeaderCell className="search-list-locked">Locked</Table.HeaderCell>
- <Table.HeaderCell className="search-list-responses">Responses</Table.HeaderCell>
- <Table.HeaderCell className="search-list-started">Ended</Table.HeaderCell>
- <Table.HeaderCell className="search-list-action"></Table.HeaderCell>
- </Table.Row>
- </Table.Header>
- <Table.Body>
- {Object.values(searches)
- .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt)))
- .map((search, index) => <SearchListRow
- search={search}
- key={index}
- onRemove={onRemove}
- onStop={onStop}
- />)}
- </Table.Body>
- </Table>
- </List.Item>
- </List>
+ <Table size='large'>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell className="search-list-action"><Icon name="info circle"/></Table.HeaderCell>
+ <Table.HeaderCell className="search-list-phrase">Search</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-files">Files</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-locked">Locked</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-responses">Responses</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-started">Ended</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-action"></Table.HeaderCell>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {Object.values(searches)
+ .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt)))
+ .map((search, index) => <SearchListRow
+ search={search}
+ key={index}
+ onRemove={onRemove}
+ onStop={onStop}
+ />)}
+ </Table.Body>
+ </Table>
</Switch>
</div>
</Card.Content>
diff --git a/src/web/src/components/Search/Search.css b/src/web/src/components/Search/Search.css
index f66a3bc7..ca31d308 100644
--- a/src/web/src/components/Search/Search.css
+++ b/src/web/src/components/Search/Search.css
@@ -105,12 +105,19 @@
width: 5px !important;
}
-.search-detail-header {
+.search-detail-header-segment {
+ margin-top: 15px !important;
+ height: 78px !important;
+ padding-top: 20px !important;
+ display: flex;
+}
+
+.search-detail-header-segment > .header {
font-weight: normal !important;
- margin-top: 12px !important;
+ margin-top: 8px !important;
}
-.search-detail-action-button {
- float: right;
- margin-top: -48px !important;
+.search-detail-header-buttons {
+ display: inline;
+ margin-left: auto;
} \ No newline at end of file
diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js
index fdcda3ac..fb0ce027 100644
--- a/src/web/src/components/Search/Searches.js
+++ b/src/web/src/components/Search/Searches.js
@@ -91,8 +91,7 @@ const Searches = ({ server }) => {
return () => {
searchHub.stop();
};
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
// create a new search, and optionally navigate to it to display the details
// we do this if the user clicks the search icon, or repeats an existing search
diff --git a/src/web/src/components/Shared/PlaceholderSegment.js b/src/web/src/components/Shared/PlaceholderSegment.js
index 0307b9e0..31ac8e9e 100644
--- a/src/web/src/components/Shared/PlaceholderSegment.js
+++ b/src/web/src/components/Shared/PlaceholderSegment.js
@@ -2,13 +2,16 @@ import React from 'react';
import { Segment, Header, Icon } from 'semantic-ui-react';
-const PlaceholderSegment = ({ icon, caption, ...rest }) => (
- <Segment className='placeholder-segment' placeholder basic {...rest}>
- <Header icon>
- <Icon name={icon}/>
- {caption}
- </Header>
- </Segment>
-);
+const PlaceholderSegment = ({ icon, caption, size, ...rest }) => {
+ const className = size === 'small' ? 'placeholder-segment-small' : 'placeholder-segment';
+
+ return (
+ <Segment className={className} placeholder basic {...rest}>
+ <Header icon>
+ <Icon name={icon}/>
+ {caption}
+ </Header>
+ </Segment>);
+};
export default PlaceholderSegment; \ No newline at end of file
diff --git a/src/web/src/components/Shared/ShrinkableButton.js b/src/web/src/components/Shared/ShrinkableButton.js
index 2f736ade..67c9f660 100644
--- a/src/web/src/components/Shared/ShrinkableButton.js
+++ b/src/web/src/components/Shared/ShrinkableButton.js
@@ -3,13 +3,13 @@ import React from 'react';
import { useMediaQuery } from 'react-responsive';
import { Button, Icon, Popup } from 'semantic-ui-react';
-const ShrinkableButton = ({ icon, mediaQuery, children, ...rest }) => {
+const ShrinkableButton = ({ icon, loading, mediaQuery, children, ...rest }) => {
const shouldShrink = useMediaQuery({ query: mediaQuery });
if (!shouldShrink) {
return (
<Button {...rest}>
- <Icon name={icon}/>
+ <Icon name={icon} loading={loading}/>
{children}
</Button>
);
@@ -20,7 +20,7 @@ const ShrinkableButton = ({ icon, mediaQuery, children, ...rest }) => {
content={children}
trigger={
<Button icon {...rest}>
- <Icon name={icon}/>
+ <Icon name={icon} loading={loading}/>
</Button>
}
/>
diff --git a/src/web/src/components/System/Info.js b/src/web/src/components/System/Info/index.js
index d9ce8813..7068e047 100644
--- a/src/web/src/components/System/Info.js
+++ b/src/web/src/components/System/Info/index.js
@@ -1,30 +1,37 @@
-import React from 'react';
+import React, { useState, useEffect } from 'react';
import YAML from 'yaml';
-import { restart, shutdown, getVersion } from '../../lib/application';
+import { restart, shutdown, getVersion } from '../../../lib/application';
-import { Modal, Header } from 'semantic-ui-react';
-import CodeEditor from '../Shared/CodeEditor';
-import ShrinkableButton from '../Shared/ShrinkableButton';
+import { Modal, Header, Divider } from 'semantic-ui-react';
+
+import {
+ CodeEditor,
+ LoaderSegment,
+ ShrinkableButton,
+ Switch,
+} from '../../Shared';
const Info = ({ state }) => {
- const stateAsYaml = YAML.stringify(state, { simpleKeys: true, sortMapEntries: true });
+ const [contents, setContents] = useState();
+
+ useEffect(() => {
+ setTimeout(() => {
+ setContents(YAML.stringify(state, { simpleKeys: true, sortMapEntries: true }));
+ }, 250);
+ }, [state]);
+
+ const { pendingRestart } = state;
return (
<>
- <div className='view-code-container'>
- <CodeEditor
- value={stateAsYaml}
- basicSetup={false}
- editable={false}
- />
- </div>
- <div className='footer-buttons'>
+ <div className='header-buttons'>
<div style={{float: 'left'}}>
<ShrinkableButton
icon='refresh'
mediaQuery='(max-width: 516px)'
primary
+ disabled={!contents}
onClick={() => getVersion({ forceCheck: true })}
>
Check for Updates
@@ -36,6 +43,7 @@ const Info = ({ state }) => {
icon='shutdown'
mediaQuery='(max-width: 516px)'
negative
+ disabled={!contents}
>
Shut Down
</ShrinkableButton>
@@ -51,7 +59,9 @@ const Info = ({ state }) => {
<ShrinkableButton
icon='redo'
mediaQuery='(max-width: 516px)'
- negative
+ negative={!pendingRestart}
+ color={pendingRestart ? 'yellow' : undefined}
+ disabled={!contents}
>
Restart
</ShrinkableButton>
@@ -63,6 +73,16 @@ const Info = ({ state }) => {
actions={['Cancel', { key: 'done', content: 'Restart', negative: true, onClick: restart }]}
/>
</div>
+ <Divider/>
+ <Switch
+ loading={!contents && <LoaderSegment/>}
+ >
+ <CodeEditor
+ value={contents}
+ basicSetup={false}
+ editable={false}
+ />
+ </Switch>
</>
);
};
diff --git a/src/web/src/components/System/Logs.js b/src/web/src/components/System/Logs/index.js
index 4a118414..b30b0a43 100644
--- a/src/web/src/components/System/Logs.js
+++ b/src/web/src/components/System/Logs/index.js
@@ -1,9 +1,10 @@
import React, { Component } from 'react';
-import { Table, Loader, Dimmer } from 'semantic-ui-react';
+import { Table } from 'semantic-ui-react';
-import { createLogsHubConnection } from '../../lib/hubFactory';
+import { createLogsHubConnection } from '../../../lib/hubFactory';
+import { LoaderSegment } from '../../Shared';
-import './System.css';
+import '../System.css';
const initialState = {
logs: [],
@@ -50,7 +51,7 @@ class Logs extends Component {
return (
<div className='logs'>
- {!connected && <Dimmer active inverted><Loader inverted/></Dimmer>}
+ {!connected && <LoaderSegment/>}
{connected &&
<Table compact='very' className='logs-table'>
<Table.Header>
diff --git a/src/web/src/components/System/Options/DebugModal.js b/src/web/src/components/System/Options/DebugModal.js
new file mode 100644
index 00000000..21514c57
--- /dev/null
+++ b/src/web/src/components/System/Options/DebugModal.js
@@ -0,0 +1,66 @@
+import React, { useState, useEffect } from 'react';
+import { toast } from 'react-toastify';
+
+import {
+ Modal,
+ Button,
+ Icon,
+} from 'semantic-ui-react';
+
+import { getCurrentDebugView } from '../../../lib/options';
+import { CodeEditor, PlaceholderSegment, Switch } from '../../Shared';
+
+const DebugModal = ({ open, onClose }) => {
+ const [loading, setLoading] = useState(true);
+ const [debugView, setDebugView] = useState();
+
+ useEffect(() => {
+ if (open) {
+ get();
+ }
+ }, [open]);
+
+ const get = async () => {
+ setLoading(true);
+
+ try {
+ setDebugView(await getCurrentDebugView());
+ } catch (error) {
+ console.error(error);
+ toast.error(error?.response?.data ?? error?.message ?? error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Modal
+ size='large'
+ open={open}
+ onClose={onClose}
+ >
+ <Modal.Header>
+ <Icon name='bug'/>
+ Options (Debug View)
+ </Modal.Header>
+ <Modal.Content className='debug-view-content' scrolling>
+ <Switch
+ loading={loading && <PlaceholderSegment loading={true} />}
+ >
+ <CodeEditor
+ style={{minHeight: 500}}
+ value={debugView}
+ basicSetup={false}
+ editable={false}
+ />
+ </Switch>
+ </Modal.Content>
+ <Modal.Actions>
+ <Button onClick={onClose}>
+ Close
+ </Button>
+ </Modal.Actions>
+ </Modal>);
+};
+
+export default DebugModal; \ No newline at end of file
diff --git a/src/web/src/components/System/Options/Edit.js b/src/web/src/components/System/Options/Edit.js
deleted file mode 100644
index f9657022..00000000
--- a/src/web/src/components/System/Options/Edit.js
+++ /dev/null
@@ -1,87 +0,0 @@
-import React, { useState, useEffect } from 'react';
-
-import { Button, Icon, Message } from 'semantic-ui-react';
-import CodeEditor from '../../Shared/CodeEditor';
-
-import { getYamlLocation, getYaml, validateYaml, updateYaml } from '../../../lib/options';
-import PlaceholderSegment from '../../Shared/PlaceholderSegment';
-
-const Edit = ({ cancelAction }) => {
- const [{ loading, error }, setLoading] = useState({ loading: true, error: false });
- const [{ location, yaml, isDirty }, setYaml] = useState({ location: undefined, yaml: undefined, isDirty: false });
- const [yamlError, setYamlError] = useState();
- const [updateError, setUpdateError] = useState();
-
- useEffect(() => {
- get();
- }, []);
-
- const get = async () => {
- setLoading({ loading: true, error: false });
-
- try {
- const [location, yaml] = await Promise.all([getYamlLocation(), getYaml()]);
-
- setYaml({ location, yaml, isDirty: false });
- setLoading({ loading: false, error: false });
- } catch (error) {
- setLoading({ loading: false, error: error.message });
- }
- };
-
- const update = async (yaml) => {
- setYaml({ location, yaml, isDirty: true });
- validate(yaml);
- };
-
- const validate = async (yaml) => {
- const response = await validateYaml({ yaml });
- setYamlError(response);
- };
-
- const save = async (yaml) => {
- await validate(yaml);
-
- if (!yamlError) {
- try {
- await updateYaml({ yaml });
- cancelAction();
- }
- catch (error) {
- setUpdateError(error.response.data);
- }
- }
- };
-
- if (loading) {
- return <PlaceholderSegment loading={true}/>;
- }
-
- if (error) {
- return <PlaceholderSegment icon='close'/>;
- }
-
- return (
- <>
- <Message className='no-grow' warning>
- <Icon name='warning sign'/>Editing {location}
- </Message>
- <div
- {...{ className: (yamlError || updateError) ? 'edit-code-container-error' : 'edit-code-container' }}
- >
- <CodeEditor
- value={yaml}
- onChange={(value) => update(value)}
- />
- </div>
- {(yamlError || updateError) &&
- <Message className='no-grow' negative><Icon name='x' />{(yamlError ?? '') + (updateError ?? '')}</Message>}
- <div className='footer-buttons'>
- <Button primary disabled={!isDirty} onClick={() => save(yaml)}><Icon name='save'/>Save</Button>
- <Button negative onClick={() => cancelAction()}><Icon name='close'/>Cancel</Button>
- </div>
- </>
- );
-};
-
-export default Edit; \ No newline at end of file
diff --git a/src/web/src/components/System/Options/EditModal.js b/src/web/src/components/System/Options/EditModal.js
new file mode 100644
index 00000000..d435bfd8
--- /dev/null
+++ b/src/web/src/components/System/Options/EditModal.js
@@ -0,0 +1,105 @@
+import React, { useState, useEffect } from 'react';
+
+import { Button, Icon, Message, Modal } from 'semantic-ui-react';
+import CodeEditor from '../../Shared/CodeEditor';
+
+import { getYamlLocation, getYaml, validateYaml, updateYaml } from '../../../lib/options';
+import {
+ PlaceholderSegment,
+ Switch,
+ Div,
+} from '../../Shared';
+
+const EditModal = ({ open, onClose }) => {
+ const [{ loading, error }, setLoading] = useState({ loading: true, error: false });
+ const [{ location, yaml, isDirty }, setYaml] = useState({ location: undefined, yaml: undefined, isDirty: false });
+ const [yamlError, setYamlError] = useState();
+ const [updateError, setUpdateError] = useState();
+
+ useEffect(() => {
+ if (open) {
+ get();
+ }
+ }, [open]);
+
+ const get = async () => {
+ setLoading({ loading: true, error: false });
+
+ try {
+ const [location, yaml] = await Promise.all([getYamlLocation(), getYaml()]);
+
+ setYaml({ location, yaml, isDirty: false });
+ setLoading({ loading: false, error: false });
+ } catch (error) {
+ setLoading({ loading: false, error: error.message });
+ }
+ };
+
+ const update = async (yaml) => {
+ setYaml({ location, yaml, isDirty: true });
+ validate(yaml);
+ };
+
+ const validate = async (yaml) => {
+ const response = await validateYaml({ yaml });
+ setYamlError(response);
+ };
+
+ const save = async (yaml) => {
+ await validate(yaml);
+
+ if (!yamlError) {
+ try {
+ await updateYaml({ yaml });
+ onClose();
+ }
+ catch (error) {
+ setUpdateError(error.response.data);
+ }
+ }
+ };
+
+ return (
+ <Modal
+ size='large'
+ open={open}
+ onClose={onClose}
+ >
+ <Modal.Header>
+ <Icon name='edit'/>
+ Edit Options
+ <Div hidden={loading}>
+ <Message className='no-grow edit-code-header' warning>
+ <Icon name='warning sign'/>Editing {location}
+ </Message>
+ </Div>
+ </Modal.Header>
+ <Modal.Content className='edit-code-content' scrolling>
+ <Switch
+ loading={loading && <PlaceholderSegment loading={true}/>}
+ error={error && <PlaceholderSegment icon='close'/>}
+ >
+ <div
+ {...{ className: (yamlError || updateError) ? 'edit-code-container-error' : 'edit-code-container' }}
+ >
+ <CodeEditor
+ style={{minHeight: 500}}
+ value={yaml}
+ onChange={(value) => update(value)}
+ />
+ </div>
+ </Switch>
+ </Modal.Content>
+ <Modal.Actions>
+ {(yamlError || updateError) &&
+ <Message className='no-grow left-align' negative>
+ <Icon name='x' />{(yamlError ?? '') + (updateError ?? '')}
+ </Message>}
+ <Button primary disabled={!isDirty} onClick={() => save(yaml)}><Icon name='save'/>Save</Button>
+ <Button negative onClick={onClose}><Icon name='close'/>Cancel</Button>
+ </Modal.Actions>
+ </Modal>
+ );
+};
+
+export default EditModal; \ No newline at end of file
diff --git a/src/web/src/components/System/Options/View.js b/src/web/src/components/System/Options/View.js
deleted file mode 100644
index 9d4d7635..00000000
--- a/src/web/src/components/System/Options/View.js
+++ /dev/null
@@ -1,30 +0,0 @@
-import React from 'react';
-import YAML from 'yaml';
-
-import { Icon, Button } from 'semantic-ui-react';
-import CodeEditor from '../../Shared/CodeEditor';
-
-const View = ({ options, editAction }) => {
- const { remoteConfiguration } = options;
-
- const optionsAsYaml = YAML.stringify(options, { simpleKeys: true, sortMapEntries: true });
-
- return (
- <>
- <div className='view-code-container'>
- <CodeEditor
- value={optionsAsYaml}
- basicSetup={false}
- editable={false}
- />
- </div>
- <div className='footer-buttons'>
- {remoteConfiguration ?
- <Button primary onClick={() => editAction()}><Icon name='edit'/>Edit</Button> :
- <Button disabled icon='x'><Icon name='lock'/>Remote Configuration Disabled</Button>}
- </div>
- </>
- );
-};
-
-export default View; \ No newline at end of file
diff --git a/src/web/src/components/System/Options/index.js b/src/web/src/components/System/Options/index.js
index 92535b95..16928a29 100644
--- a/src/web/src/components/System/Options/index.js
+++ b/src/web/src/components/System/Options/index.js
@@ -1,16 +1,87 @@
-import React, { useState } from 'react';
+import React, { useState, useEffect } from 'react';
+import YAML from 'yaml';
-import Edit from './Edit';
-import View from './View';
+import DebugModal from './DebugModal';
+import EditModal from './EditModal';
+
+import { Divider } from 'semantic-ui-react';
+import {
+ CodeEditor,
+ LoaderSegment,
+ ShrinkableButton,
+ Switch,
+} from '../../Shared';
const Index = ({ options }) => {
- const [mode, setMode] = useState('view');
+ const [debugModal, setDebugModal] = useState(false);
+ const [editModal, setEditModal] = useState(false);
+ const [contents, setContents] = useState();
+
+ useEffect(() => {
+ setTimeout(() => {
+ setContents(YAML.stringify(options, { simpleKeys: true, sortMapEntries: true }));
+ }, 250);
+ }, [options]);
+
+ const { remoteConfiguration, debug } = options;
+
+ const DebugButton = ({ ...props }) => {
+ if (!debug) return <></>;
+
+ return <ShrinkableButton
+ icon='bug'
+ mediaQuery='(max-width: 516px)'
+ onClick={() => setDebugModal(true)}
+ {...props}
+ >
+ Debug View
+ </ShrinkableButton>;
+ };
+
+ const EditButton = ({ ...props }) => {
+ if (!remoteConfiguration) {
+ return <ShrinkableButton
+ disabled
+ icon='lock'
+ mediaQuery='(max-width: 516px)'
+ >Remote Configuration Disabled</ShrinkableButton>;
+ }
- if (mode === 'edit') {
- return <Edit cancelAction={() => setMode('view')}/>;
- }
+ return <ShrinkableButton
+ primary
+ icon='edit'
+ mediaQuery='(max-width: 516px)'
+ onClick={() => setEditModal(true)}
+ {...props}
+ >Edit</ShrinkableButton>;
+ };
- return <View options={options} editAction={() => setMode('edit')}/>;
+ return (
+ <>
+ <div className='header-buttons'>
+ <DebugButton disabled={!contents}/>
+ <EditButton disabled={!contents}/>
+ </div>
+ <Divider/>
+ <Switch
+ loading={!contents && <LoaderSegment/>}
+ >
+ <CodeEditor
+ value={contents}
+ basicSetup={false}
+ editable={false}
+ />
+ </Switch>
+ <DebugModal
+ open={debugModal}
+ onClose={() => setDebugModal(false)}
+ />
+ <EditModal
+ open={editModal}
+ onClose={() => setEditModal(false)}
+ />
+ </>
+ );
};
export default Index; \ No newline at end of file
diff --git a/src/web/src/components/System/Shares/ContentsModal.js b/src/web/src/components/System/Shares/ContentsModal.js
new file mode 100644
index 00000000..b9f0d86d
--- /dev/null
+++ b/src/web/src/components/System/Shares/ContentsModal.js
@@ -0,0 +1,80 @@
+import React, { useEffect, useState } from 'react';
+import { orderBy } from 'lodash';
+
+import { browse } from '../../../lib/shares';
+
+import {
+ Modal,
+ Button,
+ Icon,
+} from 'semantic-ui-react';
+
+import {
+ CodeEditor, LoaderSegment, Switch,
+} from '../../Shared';
+
+const ContentsModal = ({ share, onClose }) => {
+ const [loading, setLoading] = useState(true);
+ const [contents, setContents] = useState();
+
+ const { id, localPath, remotePath } = share || {};
+
+ useEffect(() => {
+ const fetch = async () => {
+ setLoading(true);
+
+ const contents = await browse({ id });
+
+ var directories = contents.map(directory => {
+ const lines = [directory.name.replace(remotePath, localPath)];
+
+ orderBy(directory.files, 'filename').forEach(file => {
+ lines.push('\t' + file.filename.replace(remotePath, ''));
+ });
+
+ lines.push('');
+
+ return lines.join('\n');
+ });
+
+ setContents(directories.join('\n'));
+ setLoading(false);
+ };
+
+ if (id) {
+ fetch();
+ } else {
+ setLoading(true);
+ setContents();
+ }
+ }, [id]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ return (
+ <Modal
+ size='large'
+ open={share}
+ onClose={onClose}
+ >
+ <Modal.Header><Icon name='folder'/>{localPath}</Modal.Header>
+ <Modal.Content scrolling className='share-ls-content'>
+ <Switch
+ loading={loading && <LoaderSegment className="modal-loader"/>}
+ >
+ <CodeEditor
+ style={{minHeight: 500}}
+ value={contents || ''}
+ basicSetup={false}
+ editable={false}
+ />
+ </Switch>
+ </Modal.Content>
+ <Modal.Actions>
+ <Button onClick={onClose}>
+ Close
+ </Button>
+ </Modal.Actions>
+ </Modal>
+ );
+};
+
+export default ContentsModal; \ No newline at end of file
diff --git a/src/web/src/components/System/Shares/ExclusionTable.js b/src/web/src/components/System/Shares/ExclusionTable.js
new file mode 100644
index 00000000..5e010e30
--- /dev/null
+++ b/src/web/src/components/System/Shares/ExclusionTable.js
@@ -0,0 +1,35 @@
+import React from 'react';
+
+import {
+ Table,
+ Icon,
+} from 'semantic-ui-react';
+
+import { Switch } from '../../Shared';
+
+const ExclusionTable = ({ exclusions = [] } = {}) => {
+ return (
+ <Table>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell>Excluded Paths</Table.HeaderCell>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ <Switch
+ empty={exclusions.length === 0 && <Table.Row>
+ <Table.Cell style={{ opacity: .5, padding: '10px !important', textAlign: 'center' }}>
+ No exclusions configured
+ </Table.Cell>
+ </Table.Row>}
+ >
+ {exclusions.map((share, index) => (<Table.Row key={index}>
+ <Table.Cell><Icon name='x' color='red'/>{share.localPath}</Table.Cell>
+ </Table.Row>))}
+ </Switch>
+ </Table.Body>
+ </Table>
+ );
+};
+
+export default ExclusionTable; \ No newline at end of file
diff --git a/src/web/src/components/System/Shares/ShareTable.js b/src/web/src/components/System/Shares/ShareTable.js
new file mode 100644
index 00000000..d264fc8f
--- /dev/null
+++ b/src/web/src/components/System/Shares/ShareTable.js
@@ -0,0 +1,47 @@
+import React from 'react';
+
+import {
+ Table,
+ Icon,
+} from 'semantic-ui-react';
+
+import { Link } from 'react-router-dom';
+import { Switch } from '../../Shared';
+
+const ShareTable = ({ shares, onClick }) => {
+ return (
+ <Table>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell>Local Path</Table.HeaderCell>
+ <Table.HeaderCell className='share-count-column'>Directories</Table.HeaderCell>
+ <Table.HeaderCell className='share-count-column'>Files</Table.HeaderCell>
+ <Table.HeaderCell>Alias</Table.HeaderCell>
+ <Table.HeaderCell>Remote Path</Table.HeaderCell>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ <Switch
+ empty={shares.length === 0 && <Table.Row>
+ <Table.Cell colSpan={5} style={{ opacity: .5, padding: '10px !important', textAlign: 'center' }}>
+ No shares configured
+ </Table.Cell>
+ </Table.Row>}
+ >
+ {shares.map((share, index) => (<Table.Row key={index}>
+ <Table.Cell onClick={() => onClick(share)}>
+ <Icon name='folder'/>
+ <Link to='#'>{share.localPath}</Link>
+ </Table.Cell>
+ <Table.Cell>{share.directories}</Table.Cell>
+ <Table.Cell>{share.files}</Table.Cell>
+ <Table.Cell>{share.alias}</Table.Cell>
+ <Table.Cell>{share.remotePath}</Table.Cell>
+ </Table.Row>))}
+ </Switch>
+ </Table.Body>
+ </Table>
+ );
+};
+
+export default ShareTable; \ No newline at end of file
diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js
new file mode 100644
index 00000000..ceb5746c
--- /dev/null
+++ b/src/web/src/components/System/Shares/index.js
@@ -0,0 +1,78 @@
+import React, { useState, useEffect } from 'react';
+import { toast } from 'react-toastify';
+
+import * as sharesLib from '../../../lib/shares';
+import {
+ LoaderSegment,
+ ShrinkableButton,
+ Switch,
+} from '../../Shared';
+
+import ContentsModal from './ContentsModal';
+
+import {
+ Divider,
+} from 'semantic-ui-react';
+
+import ExclusionTable from './ExclusionTable';
+import ShareTable from './ShareTable';
+
+const Index = ({ state = {} } = {}) => {
+ const [loading, setLoading] = useState(true);
+ const [shares, setShares] = useState([]);
+ const [modal, setModal] = useState(false);
+
+ const { scanning, scanProgress, scanPending } = state;
+ const scanned = !scanning;
+
+ useEffect(() => {
+ getAll();
+ }, []);
+
+ useEffect(() => {
+ if (scanned) {
+ getAll();
+ }
+ }, [scanned]);
+
+ const getAll = async () => {
+ try {
+ setLoading(true);
+ setShares(await sharesLib.getAll());
+ } catch (error) {
+ console.error(error);
+ toast.error(error?.response?.data ?? error?.message ?? error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const shared = shares.filter(share => !share.isExcluded);
+ const excluded = shares.filter(share => share.isExcluded);
+
+ return (
+ <>
+ <div className="header-buttons">
+ <ShrinkableButton
+ primary={!scanPending}
+ color={scanPending ? 'yellow' : undefined}
+ icon='refresh'
+ loading={scanning}
+ disabled={scanning || loading}
+ mediaQuery={'(max-width: 516px)'}
+ onClick={() => sharesLib.rescan()}
+ >{scanning ? 'Scanning shares' : 'Rescan Shares'}</ShrinkableButton>
+ </div>
+ <Divider/>
+ <Switch
+ filling={(loading || scanning) && <LoaderSegment>{Math.round(scanProgress * 100)}%</LoaderSegment>}
+ >
+ <ShareTable shares={shared} onClick={setModal}/>
+ <ExclusionTable exclusions={excluded}/>
+ </Switch>
+ <ContentsModal share={modal} onClose={() => setModal(false)}/>
+ </>
+ );
+};
+
+export default Index; \ No newline at end of file
diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css
index 560cc21a..a8e9cb8e 100644
--- a/src/web/src/components/System/System.css
+++ b/src/web/src/components/System/System.css
@@ -24,15 +24,28 @@
min-height: 100px;
}
-.full-height {
- height: calc(100vh - 175px);
-}
-
.no-grow {
white-space: nowrap;
overflow: overlay;
}
+.edit-code-header {
+ margin-top: 1em !important;
+ font-size: initial !important;
+}
+
+.edit-code-content {
+ padding: 0px !important;
+}
+
+.debug-view-content, .share-ls-content {
+ padding: 5px !important;
+}
+
+.left-align {
+ text-align: left;
+}
+
.footer-buttons {
margin-top: 14px;
text-align: right;
@@ -43,23 +56,10 @@
text-align: right;
}
-.state-code-editor, .view-code-container, .edit-code-container, .edit-code-container-error {
- border: 1px solid #d4d4d5;
+.edit-code-container, .edit-code-container-error {
overflow: auto;
}
-.state-code-container {
- height: calc(100vh - 204px);
-}
-
-.view-code-container {
- height: calc(100vh - 254px);
-}
-
-.edit-code-container {
- height: calc(100vh - 316px);
-}
-
-.edit-code-container-error {
- height: calc(100vh - 378px);
+.share-count-column {
+ width: 110px;
} \ No newline at end of file
diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js
index 9310777f..2be10f81 100644
--- a/src/web/src/components/System/System.js
+++ b/src/web/src/components/System/System.js
@@ -1,25 +1,64 @@
import React from 'react';
import { useRouteMatch, useHistory, Redirect } from 'react-router-dom';
-import { Segment, Tab } from 'semantic-ui-react';
+import { Segment, Tab, Menu, Icon } from 'semantic-ui-react';
import './System.css';
import Info from './Info';
import Logs from './Logs';
import Options from './Options';
+import Shares from './Shares';
+import { Switch } from '../Shared';
const System = ({ state = {}, options = {} }) => {
const { params: { tab }, ...route } = useRouteMatch();
const history = useHistory();
const panes = [
- { route: 'info', menuItem: 'Info', render: () => <Tab.Pane><Info state={state}/></Tab.Pane> },
+ {
+ route: 'info',
+ menuItem: (<Menu.Item key='info'>
+ <Switch
+ pending={((state?.pendingRestart ?? false) || (state?.pendingReconnect ?? false))
+ && <Icon name='exclamation circle' color='yellow'/>}
+ >
+ <Icon name='info circle'/>
+ </Switch>
+ Info
+ </Menu.Item>),
+ render: () => <Tab.Pane><Info state={state}/></Tab.Pane>,
+ },
+ {
+ route: 'options',
+ menuItem: {
+ key: 'options',
+ icon: 'options',
+ content: 'Options',
+ },
+ render: () => <Tab.Pane className='full-height'><Options options={options} /></Tab.Pane>,
+ },
{
- route: 'options', menuItem: 'Options', render: () =>
- <Tab.Pane className='full-height'><Options options={options} /></Tab.Pane>,
+ route: 'shares',
+ menuItem: (<Menu.Item key='shares'>
+ <Switch
+ scanPending={(state?.shares?.scanPending ?? false) && <Icon name='exclamation circle' color='yellow'/>}
+ >
+ <Icon name='share external'/>
+ </Switch>
+ Shares
+ </Menu.Item>),
+ render: () => <Tab.Pane><Shares state={state.shares}/></Tab.Pane>,
+ },
+ {
+ route: 'logs',
+ menuItem: {
+ key: 'logs',
+ icon: 'file outline',
+ content: 'Logs',
+ },
+ render: () => <Tab.Pane><Logs/></Tab.Pane>,
},
- { route: 'logs', menuItem: 'Logs', render: () => <Tab.Pane><Logs/></Tab.Pane> },
];
const activeIndex = panes.findIndex(pane => pane.route === tab);
diff --git a/src/web/src/components/Transfers/TransferGroup.js b/src/web/src/components/Transfers/TransferGroup.js
index 023c18a0..ad4ab969 100644
--- a/src/web/src/components/Transfers/TransferGroup.js
+++ b/src/web/src/components/Transfers/TransferGroup.js
@@ -70,7 +70,7 @@ class TransferGroup extends Component {
try {
await transfers.download({username, files: [{filename, size }] });
} catch (error) {
- console.log(error);
+ console.error(error);
}
};
@@ -80,7 +80,7 @@ class TransferGroup extends Component {
try {
await transfers.getPlaceInQueue({ username, id });
} catch (error) {
- console.log(error);
+ console.error(error);
}
};
diff --git a/src/web/src/components/Transfers/Transfers.js b/src/web/src/components/Transfers/Transfers.js
index 638c0d67..7820400e 100644
--- a/src/web/src/components/Transfers/Transfers.js
+++ b/src/web/src/components/Transfers/Transfers.js
@@ -64,7 +64,7 @@ const Transfers = ({ direction, server }) => {
await transfersLib.download({username, files: [{filename, size }] });
if (!suppressStateChange) setRetrying(false);
} catch (error) {
- console.log(error);
+ console.error(error);
toast.error(error?.response?.data ?? error?.message ?? error);
if (!suppressStateChange) setRetrying(false);
}
@@ -84,7 +84,7 @@ const Transfers = ({ direction, server }) => {
await transfersLib.cancel({ direction, username, id });
if (!suppressStateChange) setCancelling(false);
} catch (error) {
- console.log(error);
+ console.error(error);
toast.error(error?.response?.data ?? error?.message ?? error);
if (!suppressStateChange) setCancelling(false);
}
@@ -104,7 +104,7 @@ const Transfers = ({ direction, server }) => {
await transfersLib.cancel({ direction, username, id, remove: true });
if (!suppressStateChange) setRemoving(false);
} catch (error) {
- console.log(error);
+ console.error(error);
toast.error(error?.response?.data ?? error?.message ?? error);
if (!suppressStateChange) setRemoving(false);
}
diff --git a/src/web/src/lib/options.js b/src/web/src/lib/options.js
index 20f8dd0a..32e48534 100644
--- a/src/web/src/lib/options.js
+++ b/src/web/src/lib/options.js
@@ -4,6 +4,10 @@ export const getCurrent = async () => {
return (await api.get('/options')).data;
};
+export const getCurrentDebugView = async () => {
+ return (await api.get('/options/debug')).data;
+};
+
export const getYaml = async () => {
return (await api.get('/options/yaml')).data;
};
diff --git a/src/web/src/lib/shares.js b/src/web/src/lib/shares.js
new file mode 100644
index 00000000..f1d0373c
--- /dev/null
+++ b/src/web/src/lib/shares.js
@@ -0,0 +1,23 @@
+import api from './api';
+
+export const getAll = async () => {
+ return (await api.get('/shares')).data;
+};
+
+export const get = async ({ id } = {}) => {
+ if (!id) throw new Error('unable to get share: id is missing');
+ return (await api.get(`/shares/${id}`)).data;
+};
+
+export const browseAll = async () => {
+ return (await api.get('/shares/contents')).data;
+};
+
+export const browse = async ({ id } = {}) => {
+ if (!id) throw new Error('unable to get share contents: id is missing');
+ return (await api.get(`/shares/${id}/contents`)).data;
+};
+
+export const rescan = async () => {
+ return (await api.put('/shares')).data;
+}; \ No newline at end of file