From b6463178e3f4679386b57614806d148bbc9b883f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 20 Sep 2021 09:28:34 -0500 Subject: move stuff around --- src/slskd/Application/Application.cs | 756 -------------------- .../Core/API/Controllers/ApplicationController.cs | 115 ++++ .../API/Controllers/ConfigurationController.cs | 73 ++ .../Core/API/Controllers/OptionsController.cs | 71 ++ .../Core/API/Controllers/ServerController.cs | 105 +++ .../Core/API/Controllers/SessionController.cs | 148 ++++ src/slskd/Application/Core/API/DTO/LoginRequest.cs | 25 + src/slskd/Application/Core/API/DTO/ServerState.cs | 33 + .../Application/Core/API/DTO/TokenResponse.cs | 67 ++ .../Application/Core/API/Hubs/ApplicationHub.cs | 51 ++ src/slskd/Application/Core/Application.cs | 758 +++++++++++++++++++++ .../Exceptions/ApplicationShutdownException.cs | 72 -- .../Exceptions/IntentionalDisconnectException.cs | 72 -- src/slskd/Application/Exceptions/RetryException.cs | 72 -- .../Application/Exceptions/ShareAliasException.cs | 72 -- .../Exceptions/ShareScanInProgressException.cs | 72 -- src/slskd/Application/Exceptions/SlskdException.cs | 72 -- src/slskd/Application/Hub.cs | 51 -- .../API/Controllers/ApplicationController.cs | 115 ---- .../API/Controllers/ConfigurationController.cs | 74 -- .../API/Controllers/OptionsController.cs | 71 -- .../Management/API/Controllers/ServerController.cs | 105 --- .../API/Controllers/SessionController.cs | 148 ---- .../Application/Management/API/DTO/LoginRequest.cs | 25 - .../Application/Management/API/DTO/ServerState.cs | 33 - .../Management/API/DTO/TokenResponse.cs | 67 -- src/slskd/Application/SharedFileCache.cs | 471 ------------- src/slskd/Application/Shares/SharedFileCache.cs | 471 +++++++++++++ src/slskd/Application/UserEndPointCache.cs | 61 -- src/slskd/Common/UserEndPointCache.cs | 61 ++ .../Exceptions/ApplicationShutdownException.cs | 72 ++ .../Exceptions/IntentionalDisconnectException.cs | 72 ++ src/slskd/Exceptions/RetryException.cs | 72 ++ src/slskd/Exceptions/ShareAliasException.cs | 72 ++ .../Exceptions/ShareScanInProgressException.cs | 72 ++ src/slskd/Exceptions/SlskdException.cs | 72 ++ src/slskd/Startup.cs | 5 +- 37 files changed, 2414 insertions(+), 2410 deletions(-) delete mode 100644 src/slskd/Application/Application.cs create mode 100644 src/slskd/Application/Core/API/Controllers/ApplicationController.cs create mode 100644 src/slskd/Application/Core/API/Controllers/ConfigurationController.cs create mode 100644 src/slskd/Application/Core/API/Controllers/OptionsController.cs create mode 100644 src/slskd/Application/Core/API/Controllers/ServerController.cs create mode 100644 src/slskd/Application/Core/API/Controllers/SessionController.cs create mode 100644 src/slskd/Application/Core/API/DTO/LoginRequest.cs create mode 100644 src/slskd/Application/Core/API/DTO/ServerState.cs create mode 100644 src/slskd/Application/Core/API/DTO/TokenResponse.cs create mode 100644 src/slskd/Application/Core/API/Hubs/ApplicationHub.cs create mode 100644 src/slskd/Application/Core/Application.cs delete mode 100644 src/slskd/Application/Exceptions/ApplicationShutdownException.cs delete mode 100644 src/slskd/Application/Exceptions/IntentionalDisconnectException.cs delete mode 100644 src/slskd/Application/Exceptions/RetryException.cs delete mode 100644 src/slskd/Application/Exceptions/ShareAliasException.cs delete mode 100644 src/slskd/Application/Exceptions/ShareScanInProgressException.cs delete mode 100644 src/slskd/Application/Exceptions/SlskdException.cs delete mode 100644 src/slskd/Application/Hub.cs delete mode 100644 src/slskd/Application/Management/API/Controllers/ApplicationController.cs delete mode 100644 src/slskd/Application/Management/API/Controllers/ConfigurationController.cs delete mode 100644 src/slskd/Application/Management/API/Controllers/OptionsController.cs delete mode 100644 src/slskd/Application/Management/API/Controllers/ServerController.cs delete mode 100644 src/slskd/Application/Management/API/Controllers/SessionController.cs delete mode 100644 src/slskd/Application/Management/API/DTO/LoginRequest.cs delete mode 100644 src/slskd/Application/Management/API/DTO/ServerState.cs delete mode 100644 src/slskd/Application/Management/API/DTO/TokenResponse.cs delete mode 100644 src/slskd/Application/SharedFileCache.cs create mode 100644 src/slskd/Application/Shares/SharedFileCache.cs delete mode 100644 src/slskd/Application/UserEndPointCache.cs create mode 100644 src/slskd/Common/UserEndPointCache.cs create mode 100644 src/slskd/Exceptions/ApplicationShutdownException.cs create mode 100644 src/slskd/Exceptions/IntentionalDisconnectException.cs create mode 100644 src/slskd/Exceptions/RetryException.cs create mode 100644 src/slskd/Exceptions/ShareAliasException.cs create mode 100644 src/slskd/Exceptions/ShareScanInProgressException.cs create mode 100644 src/slskd/Exceptions/SlskdException.cs (limited to 'src') diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs deleted file mode 100644 index 97294164..00000000 --- a/src/slskd/Application/Application.cs +++ /dev/null @@ -1,756 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Concurrent; - using System.IO; - using System.Linq; - using System.Net; - using System.Reflection; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.AspNetCore.SignalR; - using Microsoft.Extensions.Hosting; - using Microsoft.Extensions.Options; - using Serilog; - using Serilog.Events; - using slskd.Configuration; - using slskd.Integrations.Pushbullet; - using slskd.Messaging; - using slskd.Search; - using slskd.Transfers; - using slskd.Users; - using Soulseek; - using Soulseek.Diagnostics; - - public interface IApplication : IHostedService - { - public Task CheckVersionAsync(); - public Task RescanSharesAsync(); - } - - public sealed class Application : IApplication - { - private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes - - public Application( - OptionsAtStartup optionsAtStartup, - IOptionsMonitor optionsMonitor, - IManagedState state, - ISoulseekClient soulseekClient, - ITransferTracker transferTracker, - IBrowseTracker browseTracker, - IConversationTracker conversationTracker, - IRoomTracker roomTracker, - IRoomService roomService, - ISharedFileCache sharedFileCache, - IPushbulletService pushbulletService, - IHubContext hubContext) - { - OptionsAtStartup = optionsAtStartup; - - OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); - - PreviousOptions = OptionsMonitor.CurrentValue; - - State = state; - State.OnChange(state => State_OnChange(state)); - - SharedFileCache = sharedFileCache; - SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state)); - - TransferTracker = transferTracker; - BrowseTracker = browseTracker; - ConversationTracker = conversationTracker; - Pushbullet = pushbulletService; - - RoomService = roomService; - HubContext = hubContext; - - Client = soulseekClient; - - Client.DiagnosticGenerated += Client_DiagnosticGenerated; - - Client.TransferStateChanged += Client_TransferStateChanged; - Client.TransferProgressUpdated += Client_TransferProgressUpdated; - - Client.BrowseProgressUpdated += Client_BrowseProgressUpdated; - Client.UserStatusChanged += Client_UserStatusChanged; - Client.PrivateMessageReceived += Client_PrivateMessageRecieved; - - Client.PrivateRoomMembershipAdded += (e, room) => Console.WriteLine($"Added to private room {room}"); - Client.PrivateRoomMembershipRemoved += (e, room) => Console.WriteLine($"Removed from private room {room}"); - Client.PrivateRoomModerationAdded += (e, room) => Console.WriteLine($"Promoted to moderator in private room {room}"); - Client.PrivateRoomModerationRemoved += (e, room) => Console.WriteLine($"Demoted from moderator in private room {room}"); - - Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; - Client.RoomMessageReceived += Client_RoomMessageReceived; - Client.Disconnected += Client_Disconnected; - Client.Connected += Client_Connected; - Client.LoggedIn += Client_LoggedIn; - Client.StateChanged += Client_StateChanged; - } - - private ISoulseekClient Client { get; set; } - private IRoomService RoomService { get; set; } - private IBrowseTracker BrowseTracker { get; set; } - private IConversationTracker ConversationTracker { get; set; } - private ILogger Logger { get; set; } = Log.ForContext(); - private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); - private Options Options => OptionsMonitor.CurrentValue; - private OptionsAtStartup OptionsAtStartup { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } - private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); - private Options PreviousOptions { get; set; } - private IPushbulletService Pushbullet { get; } - private ISharedFileCache SharedFileCache { get; set; } - private DateTime SharesRefreshStarted { get; set; } - private IManagedState State { get; } - private ITransferTracker TransferTracker { get; set; } - private IHubContext HubContext { get; set; } - - /// - /// Gets the version of the latest application release. - /// - /// The operation context. - public async Task CheckVersionAsync() - { - if (Program.InformationalVersion.EndsWith("65534")) - { - // todo: use the docker hub API to find the latest canary tag - Logger.Information("Skipping version check for Canary build; check for updates manually."); - } - - Logger.Information("Checking GitHub Releases for latest version"); - - try - { - var latestVersion = await GitHub.GetLatestReleaseVersion( - organization: Program.AppName, - repository: Program.AppName, - userAgent: $"{Program.AppName} v{Program.InformationalVersion}"); - - if (latestVersion > Version.Parse(Program.InformationalVersion)) - { - State.SetValue(state => state with { Version = state.Version with { Latest = latestVersion.ToString(), IsUpdateAvailable = true } }); - Logger.Information("A new version is available! {CurrentVersion} -> {LatestVersion}", Program.InformationalVersion, latestVersion); - } - else - { - State.SetValue(state => state with { Version = state.Version with { Latest = Program.InformationalVersion, IsUpdateAvailable = false } }); - Logger.Information("Version {CurrentVersion} is up to date.", Program.InformationalVersion); - } - } - catch (Exception ex) - { - Logger.Warning("Failed to check version: {Message}", ex.Message); - throw; - } - } - - /// - /// Re-scans shared directories. - /// - /// The operation context. - public Task RescanSharesAsync() => SharedFileCache.FillAsync(); - - async Task IHostedService.StartAsync(CancellationToken cancellationToken) - { - Logger.Information("Configuring client"); - - ProxyOptions proxyOptions = default; - - if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) - { - proxyOptions = new ProxyOptions( - address: OptionsAtStartup.Soulseek.Connection.Proxy.Address, - port: OptionsAtStartup.Soulseek.Connection.Proxy.Port.Value, - username: OptionsAtStartup.Soulseek.Connection.Proxy.Username, - password: OptionsAtStartup.Soulseek.Connection.Proxy.Password); - } - - var connectionOptions = new ConnectionOptions( - readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read, - writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write, - connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect, - inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity, - proxyOptions: proxyOptions); - - var patch = new SoulseekClientOptionsPatch( - listenPort: OptionsAtStartup.Soulseek.ListenPort, - enableListener: true, - userEndPointCache: new UserEndPointCache(), - distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit, - enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled, - autoAcknowledgePrivateMessages: false, - acceptPrivateRoomInvitations: true, - serverConnectionOptions: connectionOptions, - peerConnectionOptions: connectionOptions, - transferConnectionOptions: connectionOptions, - distributedConnectionOptions: connectionOptions, - userInfoResponseResolver: UserInfoResponseResolver, - browseResponseResolver: BrowseResponseResolver, - directoryContentsResponseResolver: DirectoryContentsResponseResolver, - enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), - searchResponseCache: new SearchResponseCache(), - searchResponseResolver: SearchResponseResolver); - - await Client.ReconfigureOptionsAsync(patch); - - Logger.Information("Client configured"); - Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); - - if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) - { - Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}"); - } - - if (!OptionsAtStartup.NoVersionCheck) - { - _ = CheckVersionAsync(); - } - - if (OptionsAtStartup.NoShareScan) - { - Logger.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); - } - else - { - _ = SharedFileCache.FillAsync(); - } - - if (OptionsAtStartup.NoConnect) - { - Logger.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled"); - } - else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) - { - Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); - } - else - { - await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); - } - } - - Task IHostedService.StopAsync(CancellationToken cancellationToken) - { - Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down")); - Client.Dispose(); - Logger.Information("Client stopped"); - return Task.CompletedTask; - } - - /// - /// Creates and returns an instances of in response to a remote request. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// A Task resolving an IEnumerable of Soulseek.Directory. - private Task BrowseResponseResolver(string username, IPEndPoint endpoint) - { - var directories = SharedFileCache.Browse() - .Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes - - return Task.FromResult(new BrowseResponse(directories)); - } - - private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) - { - BrowseTracker.AddOrUpdate(args.Username, args); - } - - private void Client_Connected(object sender, EventArgs e) - { - Logger.Information("Connected to the Soulseek server"); - } - - private void Client_DiagnosticGenerated(object sender, DiagnosticEventArgs args) - { - static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch - { - DiagnosticLevel.Debug => LogEventLevel.Debug, - DiagnosticLevel.Info => LogEventLevel.Information, - DiagnosticLevel.Warning => LogEventLevel.Warning, - DiagnosticLevel.None => default, - _ => default, - }; - - var logger = Loggers.GetOrAdd(sender.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", sender.GetType().FullName)); - - logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); - } - - private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) - { - if (State.CurrentValue.PendingReconnect) - { - State.SetValue(state => state with { PendingReconnect = false }); - } - - if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) - { - Logger.Information("Disconnected from the Soulseek server: the client is shutting down"); - } - else if (args.Exception is IntentionalDisconnectException) - { - Logger.Information("Disconnected from the Soulseek server: disconnected by the user"); - } - else if (args.Exception is LoginRejectedException) - { - Logger.Error("Disconnected from the Soulseek server: invalid username or password"); - } - else if (args.Exception is KickedFromServerException) - { - Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Client.Username); - } - else - { - Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) - { - Logger.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); - return; - } - - var attempts = 1; - - while (true) - { - var (delay, jitter) = Compute.ExponentialBackoffDelay( - iteration: attempts, - maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); - - var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); - Logger.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); - await Task.Delay(delay + jitter); - - Logger.Information($"Attempting to reconnect (#{attempts})...", attempts); - - try - { - // reconnect with the latest configuration values we have for username and password, instead of the - // options that were captured at startup. if a user has updated these values prior to the disconnect, the - // changes will take effect now. - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); - break; - } - catch (Exception ex) - { - attempts++; - Logger.Error("Failed to reconnect: {Message}", ex.Message); - } - } - } - } - - private void Client_LoggedIn(object sender, EventArgs e) - { - Logger.Information("Logged in to the Soulseek server as {Username}", Client.Username); - - // 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); - } - - private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) - { - ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - - if (Options.Integration.Pushbullet.Enabled && !args.Replayed) - { - Console.WriteLine("Pushing..."); - _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); - } - } - - private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) - { - Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - - if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) - { - _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); - } - } - - private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) - { - var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); - - if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) - { - _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); - } - } - - private void Client_StateChanged(object sender, SoulseekClientStateChangedEventArgs e) - { - State.SetValue(state => state with { Server = state.Server with { Address = Client.Address, IPEndPoint = Client.IPEndPoint, State = Client.State, Username = Client.Username } }); - } - - 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"); - } - - private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) - { - var xfer = args.Transfer; - var direction = xfer.Direction.ToString().ToUpper(); - var user = xfer.Username; - var file = Path.GetFileName(xfer.Filename); - var oldState = args.PreviousState; - var state = xfer.State; - - var completed = xfer.State.HasFlag(TransferStates.Completed); - - Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({xfer.BytesTransferred}/{xfer.Size} = {xfer.PercentComplete}%) @ {xfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); - - if (xfer.Direction == TransferDirection.Upload && xfer.State.HasFlag(TransferStates.Completed | TransferStates.Succeeded)) - { - _ = Client.SendUploadSpeedAsync((int)args.Transfer.AverageSpeed); - } - } - - private void Client_UserStatusChanged(object sender, UserStatusChangedEventArgs args) - { - Console.WriteLine($"[USER] {args.Username}: {args.Status}"); - } - - /// - /// Creates and returns a in response to a remote request. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// The unique token for the request, supplied by the requesting user. - /// The requested directory. - /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. - private Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) - { - var dir = SharedFileCache.List(directory); - return Task.FromResult(dir); - } - - /// - /// Invoked upon a remote request to download a file. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// The filename of the requested file. - /// (for example purposes) the ITransferTracker used to track progress. - /// A Task representing the asynchronous operation. - /// - /// Thrown when the download is rejected. The Exception message will be passed to the remote user. - /// - /// - /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for - /// security reasons. - /// - private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) - { - _ = endpoint; - var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath(); - - var fileInfo = new FileInfo(localFilename); - - if (!fileInfo.Exists) - { - Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); - throw new DownloadEnqueueException($"File not shared."); - } - - if (tracker.TryGet(TransferDirection.Upload, username, filename, out _)) - { - // 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; - } - - // create a new cancellation token source so that we can cancel the upload from the UI. - var cts = new CancellationTokenSource(); - var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (t, c) => Task.Delay(1, c)); - - // 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 () => - { - using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - await Client.UploadAsync(username, filename, fileInfo.Length, stream, options: topts, cancellationToken: cts.Token); - }).ContinueWith(t => - { - 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) - { - // this code is known to fire more than once per update. i'm not sure whether these might be executed concurrently. - // lock to be safe, because we need to accurately track the last value of Options for diffing purposes. threading - // shenanigans here could lead to missed updates. - OptionsSyncRoot.EnterWriteLock(); - - try - { - var pendingRestart = false; - var pendingReconnect = false; - var soulseekRequiresReconnect = false; - - var diff = PreviousOptions.DiffWith(newOptions); - - // don't react to duplicate/no-change events https://github.com/slskd/slskd/issues/126 - if (!diff.Any()) - { - return; - } - - foreach (var (property, fqn, left, right) in diff) - { - static bool HasAttribute(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); - - var requiresRestart = HasAttribute(property); - var requiresReconnect = HasAttribute(property); - - Logger.Debug($"{fqn} changed from '{left.ToJson() ?? ""}' to '{right.ToJson() ?? ""}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}"); - - pendingRestart |= requiresRestart; - pendingReconnect |= requiresReconnect; - } - - if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() - || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) - { - State.SetValue(state => state with { PendingShareRescan = true }); - Logger.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 }); - Logger.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect."); - } - - if (PreviousOptions.Rooms.Except(newOptions.Rooms).Any() - || newOptions.Rooms.Except(PreviousOptions.Rooms).Any()) - { - Logger.Information("Room configuration changed. Joining any newly added rooms."); - _ = RoomService.TryJoinAsync(newOptions.Rooms); - } - - // determine whether any Soulseek options changed. if so, we need to construct a patch and invoke ReconfigureOptionsAsync(). - var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek); - - if (slskDiff.Any()) - { - var old = PreviousOptions.Soulseek; - var update = newOptions.Soulseek; - - Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson()); - - // determine whether any Connection options changed. if so, replace the whole object. Soulseek.NET doesn't - // offer a way to patch parts of connection options. the updates only affect new connections, so a partial - // patch doesn't make a lot of sense anyway. - var connectionDiff = old.Connection.DiffWith(update.Connection); - - ConnectionOptions connectionPatch = null; - - if (connectionDiff.Any()) - { - var connection = update.Connection; - - ProxyOptions proxyPatch = null; - - if (connection.Proxy.Enabled) - { - proxyPatch = new ProxyOptions( - connection.Proxy.Address, - connection.Proxy.Port.Value, - connection.Proxy.Username, - connection.Proxy.Password); - } - - connectionPatch = new ConnectionOptions( - connection.Buffer.Read, - connection.Buffer.Write, - connection.Timeout.Connect, - connection.Timeout.Inactivity, - proxyOptions: proxyPatch); - } - - var patch = new SoulseekClientOptionsPatch( - listenPort: old.ListenPort == update.ListenPort ? null : update.ListenPort, - enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled, - distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit, - serverConnectionOptions: connectionPatch, - peerConnectionOptions: connectionPatch, - transferConnectionOptions: connectionPatch, - incomingConnectionOptions: connectionPatch, - distributedConnectionOptions: connectionPatch); - - Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson()); - - soulseekRequiresReconnect = await Client.ReconfigureOptionsAsync(patch); - } - - // require a reconnect if the client is connected and any options marked [RequiresReconnect] changed, OR if the - // call to reconfigure the client requires a reconnect - if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) || soulseekRequiresReconnect) - { - State.SetValue(state => state with { PendingReconnect = true }); - Logger.Information("One or more updated Soulseek options requires the client to be disconnected, then reconnected to the network to take effect."); - } - - if (pendingRestart) - { - State.SetValue(state => state with { PendingRestart = true }); - Logger.Information("One or more updated options requires an application restart to take effect."); - } - - Logger.Information("Options updated successfully."); - } - catch (Exception ex) - { - Logger.Error(ex, "Failed to apply option update: {Message}", ex.Message); - } - finally - { - PreviousOptions = OptionsMonitor.CurrentValue; - OptionsSyncRoot.ExitWriteLock(); - } - } - - /// - /// Creates and returns a in response to the given . - /// - /// The username of the requesting user. - /// The search token. - /// The search query. - /// A Task resolving a SearchResponse, or null. - private async Task SearchResponseResolver(string username, int token, SearchQuery query) - { - // some bots continually query for very common strings. blacklist known names here. - var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; - if (blacklist.Contains(username)) - { - return null; - } - - // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. - if (query.Query.Length < 3) - { - return null; - } - - var results = await SharedFileCache.SearchAsync(query); - - if (results.Any()) - { - Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); - - return new SearchResponse( - Client.Username, - token, - freeUploadSlots: 1, - uploadSpeed: 0, - queueLength: 0, - fileList: results); - } - - // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no - // response will be sent to the requestor. - return null; - } - - private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) - { - var (previous, current) = state; - - if (!previous.Filling && current.Filling) - { - SharesRefreshStarted = DateTime.UtcNow; - - State.SetValue(s => s with { SharedFileCache = current }); - Logger.Information("Scanning shares"); - } - - var lastProgress = Math.Round(previous.FillProgress * 100); - var currentProgress = Math.Round(current.FillProgress * 100); - - if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) - { - State.SetValue(s => s with { SharedFileCache = current }); - Logger.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); - } - - if (previous.Filling && !current.Filling) - { - State.SetValue(s => s with { SharedFileCache = current }); - - if (current.Faulted) - { - Logger.Error("Failed to scan shares."); - } - else - { - State.SetValue(s => s with { PendingShareRescan = false }); - Logger.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); - } - } - } - } - - private void State_OnChange((State Previous, State Current) state) - { - Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); - HubContext.BroadcastStateAsync(state.Current); - } - - /// - /// Creates and returns a object in response to a remote request. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// A Task resolving the UserInfo instance. - private Task UserInfoResponseResolver(string username, IPEndPoint endpoint) - { - var info = new UserInfo( - description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}", - picture: Array.Empty(), - uploadSlots: 1, - queueLength: 0, - hasFreeUploadSlot: false); - - return Task.FromResult(info); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Core/API/Controllers/ApplicationController.cs b/src/slskd/Application/Core/API/Controllers/ApplicationController.cs new file mode 100644 index 00000000..16cd68b9 --- /dev/null +++ b/src/slskd/Application/Core/API/Controllers/ApplicationController.cs @@ -0,0 +1,115 @@ +// +// 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.Core.API +{ + using System; + using System.Diagnostics; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Microsoft.Extensions.Hosting; + + /// + /// Application. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ApplicationController : ControllerBase + { + public ApplicationController( + IHostApplicationLifetime lifetime, + IApplication application, + IStateMonitor applicationStateMonitor) + { + Lifetime = lifetime; + Application = application; + ApplicationStateMonitor = applicationStateMonitor; + } + + private IApplication Application { get; } + private IStateMonitor ApplicationStateMonitor { get; } + private IHostApplicationLifetime Lifetime { get; } + + /// + /// Gets the current state of the application. + /// + /// + [HttpGet] + [Authorize] + public IActionResult State() + { + return Ok(ApplicationStateMonitor.CurrentValue); + } + + /// + /// Stops the application. + /// + /// + [HttpDelete] + [Authorize] + public IActionResult Shutdown() + { + Lifetime.StopApplication(); + return NoContent(); + } + + /// + /// Restarts the application. + /// + /// + [HttpPut] + [Authorize] + public IActionResult Restart() + { + Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); + Lifetime.StopApplication(); + + return NoContent(); + } + + /// + /// Gets the current application version. + /// + /// + [HttpGet("version")] + [Authorize] + public IActionResult GetVersion() + { + return Ok(Program.InformationalVersion); + } + + /// + /// Checks for updates. + /// + /// + [HttpGet("version/latest")] + [Authorize] + public async Task CheckVersion([FromQuery]bool forceCheck = false) + { + if (forceCheck) + { + await Application.CheckVersionAsync(); + } + + return Ok(ApplicationStateMonitor.CurrentValue.Version); + } + } +} diff --git a/src/slskd/Application/Core/API/Controllers/ConfigurationController.cs b/src/slskd/Application/Core/API/Controllers/ConfigurationController.cs new file mode 100644 index 00000000..01c8bbc1 --- /dev/null +++ b/src/slskd/Application/Core/API/Controllers/ConfigurationController.cs @@ -0,0 +1,73 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Core.API +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + + /// + /// Configuration. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ConfigurationController : ControllerBase + { + public ConfigurationController( + IApplication application, + IOptionsSnapshot optionsShapshot, + IStateMonitor applicationStateMonitor) + { + Application = application; + OptionsShapshot = optionsShapshot; + ApplicationStateMonitor = applicationStateMonitor; + } + + private IApplication Application { get; } + private IOptionsSnapshot OptionsShapshot { get; } + private IStateMonitor ApplicationStateMonitor { get; } + + [HttpGet] + [Route("")] + [Authorize] + public IActionResult GetOptions() + { + // todo: sanitize this to remove passwords + return Ok(OptionsShapshot.Value); + } + + [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/Application/Core/API/Controllers/OptionsController.cs b/src/slskd/Application/Core/API/Controllers/OptionsController.cs new file mode 100644 index 00000000..fb2057b9 --- /dev/null +++ b/src/slskd/Application/Core/API/Controllers/OptionsController.cs @@ -0,0 +1,71 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Core.API +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + + /// + /// Options. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class OptionsController : ControllerBase + { + public OptionsController( + OptionsAtStartup optionsAtStartup, + IOptionsSnapshot optionsSnapshot) + { + OptionsAtStartup = optionsAtStartup; + OptionsSnapshot = optionsSnapshot; + } + + private IOptionsSnapshot OptionsSnapshot { get; } + private OptionsAtStartup OptionsAtStartup { get; } + + /// + /// Gets the current application options. + /// + /// + [HttpGet] + [Authorize] + [ProducesResponseType(typeof(Options), 200)] + public IActionResult Current() + { + return Ok(OptionsSnapshot.Value); + } + + /// + /// Gets the application options provided at startup. + /// + /// + [HttpGet] + [Route("startup")] + [Authorize] + [ProducesResponseType(typeof(Options), 200)] + public IActionResult Startup() + { + return Ok(OptionsAtStartup); + } + } +} diff --git a/src/slskd/Application/Core/API/Controllers/ServerController.cs b/src/slskd/Application/Core/API/Controllers/ServerController.cs new file mode 100644 index 00000000..172333ec --- /dev/null +++ b/src/slskd/Application/Core/API/Controllers/ServerController.cs @@ -0,0 +1,105 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Core.API +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// + /// Server. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ServerController : ControllerBase + { + public ServerController( + ISoulseekClient soulseekClient, + IOptionsSnapshot optionsSnapshot, + IStateSnapshot stateSnapshot) + { + Client = soulseekClient; + OptionsSnapshot = optionsSnapshot; + StateSnapshot = stateSnapshot; + } + + private ISoulseekClient Client { get; } + private IOptionsSnapshot OptionsSnapshot { get; } + private IStateSnapshot StateSnapshot { get; } + + /// + /// Connects the client. + /// + /// + [HttpPut] + [Route("")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(403)] + public async Task Connect() + { + if (!Client.State.HasFlag(SoulseekClientStates.Connected)) + { + await Client.ConnectAsync(OptionsSnapshot.Value.Soulseek.Username, OptionsSnapshot.Value.Soulseek.Password); + } + + return Ok(); + } + + /// + /// Disconnects the client. + /// + /// + /// + [HttpDelete] + [Route("")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(403)] + public IActionResult Disconnect([FromBody] string message) + { + if (Client.State.HasFlag(SoulseekClientStates.Connected)) + { + Client.Disconnect(message, new IntentionalDisconnectException(message)); + } + + return NoContent(); + } + + /// + /// Retrieves the current state of the server. + /// + /// + /// + [HttpGet] + [Route("")] + [Authorize] + [ProducesResponseType(typeof(ServerState), 200)] + [ProducesResponseType(403)] + public IActionResult Get() + { + return Ok(StateSnapshot.Value.Server); + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Core/API/Controllers/SessionController.cs b/src/slskd/Application/Core/API/Controllers/SessionController.cs new file mode 100644 index 00000000..5f20aa9f --- /dev/null +++ b/src/slskd/Application/Core/API/Controllers/SessionController.cs @@ -0,0 +1,148 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Core.API +{ + using System; + using System.Collections.Generic; + using System.IdentityModel.Tokens.Jwt; + using System.Security.Claims; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Microsoft.IdentityModel.Tokens; + using slskd.Authentication; + + /// + /// Session. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SessionController : ControllerBase + { + public SessionController( + IOptionsSnapshot optionsSnapshot, + OptionsAtStartup optionsAtStartup, + SymmetricSecurityKey jwtSigningKey) + { + OptionsSnapshot = optionsSnapshot; + OptionsAtStartup = optionsAtStartup; + JwtSigningKey = jwtSigningKey; + } + + private SymmetricSecurityKey JwtSigningKey { get; set; } + private IOptionsSnapshot OptionsSnapshot { get; set; } + private OptionsAtStartup OptionsAtStartup { get; set; } + + /// + /// Checks whether the provided authentication is valid. + /// + /// This is a no-op provided so that the application can test for an expired token on load. + /// + /// The authentication is valid. + /// The authentication is is invalid. + [HttpGet] + [Route("")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(401)] + public IActionResult Check() + { + return Ok(); + } + + /// + /// Checks whether security is enabled. + /// + /// + /// True if security is enabled, false otherwise. + [HttpGet] + [Route("enabled")] + [AllowAnonymous] + [ProducesResponseType(typeof(bool), 200)] + public IActionResult Enabled() + { + return Ok(!OptionsAtStartup.Web.Authentication.Disabled); + } + + /// + /// Logs in. + /// + /// + /// + /// Login was successful. + /// Bad request. + /// Login failed. + [HttpPost] + [Route("")] + [AllowAnonymous] + [ProducesResponseType(typeof(TokenResponse), 200)] + [ProducesResponseType(400)] + [ProducesResponseType(401)] + [ProducesResponseType(typeof(string), 500)] + public IActionResult Login([FromBody] LoginRequest login) + { + if (login == default) + { + return BadRequest(); + } + + if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password)) + { + return BadRequest("Username and/or Password missing or invalid"); + } + + // only admin login for now + if (OptionsSnapshot.Value.Web.Authentication.Username == login.Username && OptionsSnapshot.Value.Web.Authentication.Password == login.Password) + { + return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); + } + + return Unauthorized(); + } + + private JwtSecurityToken GetJwtSecurityToken(string username, Role role) + { + var issuedUtc = DateTime.UtcNow; + var expiresUtc = DateTime.UtcNow.AddMilliseconds(OptionsAtStartup.Web.Authentication.Jwt.Ttl); + + var claims = new List() + { + new Claim(ClaimTypes.Name, username), + new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), + new Claim(ClaimTypes.Role, role.ToString()), + new Claim("name", username), + new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), + }; + + var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); + + var token = new JwtSecurityToken( + issuer: Program.AppName, + claims: claims, + notBefore: issuedUtc, + expires: expiresUtc, + signingCredentials: credentials); + + return token; + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Core/API/DTO/LoginRequest.cs b/src/slskd/Application/Core/API/DTO/LoginRequest.cs new file mode 100644 index 00000000..0653847d --- /dev/null +++ b/src/slskd/Application/Core/API/DTO/LoginRequest.cs @@ -0,0 +1,25 @@ +// +// 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.Core.API +{ + public class LoginRequest + { + public string Username { get; set; } + public string Password { get; set; } + } +} diff --git a/src/slskd/Application/Core/API/DTO/ServerState.cs b/src/slskd/Application/Core/API/DTO/ServerState.cs new file mode 100644 index 00000000..5dd16365 --- /dev/null +++ b/src/slskd/Application/Core/API/DTO/ServerState.cs @@ -0,0 +1,33 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Core +{ + using System.Net; + using Soulseek; + + public class ServerState + { + public string Address { get; set; } + public IPEndPoint IPEndPoint { get; set; } + public SoulseekClientStates State { get; set; } + public string Username { get; set; } + public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); + public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); + public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); + } +} diff --git a/src/slskd/Application/Core/API/DTO/TokenResponse.cs b/src/slskd/Application/Core/API/DTO/TokenResponse.cs new file mode 100644 index 00000000..85992917 --- /dev/null +++ b/src/slskd/Application/Core/API/DTO/TokenResponse.cs @@ -0,0 +1,67 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Core.API +{ + using System; + using System.IdentityModel.Tokens.Jwt; + using System.Linq; + using System.Security.Claims; + using System.Text.Json.Serialization; + using Microsoft.AspNetCore.Authentication.JwtBearer; + + public class TokenResponse + { + public TokenResponse(JwtSecurityToken jwtSecurityToken) + { + JwtSecurityToken = jwtSecurityToken; + } + + /// + /// Gets the time at which the Access Token expires. + /// + public long Expires => ((DateTimeOffset)JwtSecurityToken.ValidTo).ToUnixTimeSeconds(); + + /// + /// Gets the time at which the Access Token was issued. + /// + public long Issued => ((DateTimeOffset)JwtSecurityToken.ValidFrom).ToUnixTimeSeconds(); + + /// + /// Gets the value of the Name claim from the Access Token. + /// + public string Name => JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name)?.Value; + + /// + /// Gets the value of the Not Before claim from the Access Token. + /// + public long NotBefore => long.Parse(JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == "nbf").Value); + + /// + /// Gets the Access Token string. + /// + public string Token => new JwtSecurityTokenHandler().WriteToken(JwtSecurityToken); + + /// + /// Gets the Token type. + /// + public string TokenType => JwtBearerDefaults.AuthenticationScheme; + + [JsonIgnore] + private JwtSecurityToken JwtSecurityToken { get; } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Core/API/Hubs/ApplicationHub.cs b/src/slskd/Application/Core/API/Hubs/ApplicationHub.cs new file mode 100644 index 00000000..be6c2fe7 --- /dev/null +++ b/src/slskd/Application/Core/API/Hubs/ApplicationHub.cs @@ -0,0 +1,51 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Core +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; + + /// + /// Extension methods for the application SignalR hub. + /// + public static class ApplicationHubExtensions + { + /// + /// Broadcast the present application state. + /// + /// The hub. + /// The state to broadcast. + /// The operation context. + public static Task BroadcastStateAsync(this IHubContext hub, State state) + { + return hub.Clients.All.SendAsync(Methods.State, state); + } + + private static class Methods + { + public static readonly string State = "STATE"; + } + } + + /// + /// The application SignalR hub. + /// + public class ApplicationHub : Hub + { + } +} \ No newline at end of file diff --git a/src/slskd/Application/Core/Application.cs b/src/slskd/Application/Core/Application.cs new file mode 100644 index 00000000..56eac586 --- /dev/null +++ b/src/slskd/Application/Core/Application.cs @@ -0,0 +1,758 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Core +{ + using System; + using System.Collections.Concurrent; + using System.IO; + using System.Linq; + using System.Net; + using System.Reflection; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; + using Microsoft.Extensions.Hosting; + using Serilog; + using Serilog.Events; + using slskd.Configuration; + using slskd.Integrations.Pushbullet; + using slskd.Messaging; + using slskd.Search; + using slskd.Shares; + using slskd.Transfers; + using slskd.Users; + using Soulseek; + using Soulseek.Diagnostics; + + public interface IApplication : IHostedService + { + public Task CheckVersionAsync(); + public Task RescanSharesAsync(); + } + + public sealed class Application : IApplication + { + private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + + public Application( + OptionsAtStartup optionsAtStartup, + IOptionsMonitor optionsMonitor, + IManagedState state, + ISoulseekClient soulseekClient, + ITransferTracker transferTracker, + IBrowseTracker browseTracker, + IConversationTracker conversationTracker, + IRoomTracker roomTracker, + IRoomService roomService, + ISharedFileCache sharedFileCache, + IPushbulletService pushbulletService, + IHubContext applicationHub) + { + OptionsAtStartup = optionsAtStartup; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); + + PreviousOptions = OptionsMonitor.CurrentValue; + + State = state; + State.OnChange(state => State_OnChange(state)); + + SharedFileCache = sharedFileCache; + SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state)); + + TransferTracker = transferTracker; + BrowseTracker = browseTracker; + ConversationTracker = conversationTracker; + Pushbullet = pushbulletService; + + RoomService = roomService; + ApplicationHub = applicationHub; + + Client = soulseekClient; + + Client.DiagnosticGenerated += Client_DiagnosticGenerated; + + Client.TransferStateChanged += Client_TransferStateChanged; + Client.TransferProgressUpdated += Client_TransferProgressUpdated; + + Client.BrowseProgressUpdated += Client_BrowseProgressUpdated; + Client.UserStatusChanged += Client_UserStatusChanged; + Client.PrivateMessageReceived += Client_PrivateMessageRecieved; + + Client.PrivateRoomMembershipAdded += (e, room) => Console.WriteLine($"Added to private room {room}"); + Client.PrivateRoomMembershipRemoved += (e, room) => Console.WriteLine($"Removed from private room {room}"); + Client.PrivateRoomModerationAdded += (e, room) => Console.WriteLine($"Promoted to moderator in private room {room}"); + Client.PrivateRoomModerationRemoved += (e, room) => Console.WriteLine($"Demoted from moderator in private room {room}"); + + Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; + Client.RoomMessageReceived += Client_RoomMessageReceived; + Client.Disconnected += Client_Disconnected; + Client.Connected += Client_Connected; + Client.LoggedIn += Client_LoggedIn; + Client.StateChanged += Client_StateChanged; + } + + private ISoulseekClient Client { get; set; } + private IRoomService RoomService { get; set; } + private IBrowseTracker BrowseTracker { get; set; } + private IConversationTracker ConversationTracker { get; set; } + private ILogger Logger { get; set; } = Log.ForContext(); + private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); + private Options Options => OptionsMonitor.CurrentValue; + private OptionsAtStartup OptionsAtStartup { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); + private Options PreviousOptions { get; set; } + private IPushbulletService Pushbullet { get; } + private ISharedFileCache SharedFileCache { get; set; } + private DateTime SharesRefreshStarted { get; set; } + private IManagedState State { get; } + private ITransferTracker TransferTracker { get; set; } + private IHubContext ApplicationHub { get; set; } + + /// + /// Gets the version of the latest application release. + /// + /// The operation context. + public async Task CheckVersionAsync() + { + if (Program.InformationalVersion.EndsWith("65534")) + { + // todo: use the docker hub API to find the latest canary tag + Logger.Information("Skipping version check for Canary build; check for updates manually."); + } + + Logger.Information("Checking GitHub Releases for latest version"); + + try + { + var latestVersion = await GitHub.GetLatestReleaseVersion( + organization: Program.AppName, + repository: Program.AppName, + userAgent: $"{Program.AppName} v{Program.InformationalVersion}"); + + if (latestVersion > Version.Parse(Program.InformationalVersion)) + { + State.SetValue(state => state with { Version = state.Version with { Latest = latestVersion.ToString(), IsUpdateAvailable = true } }); + Logger.Information("A new version is available! {CurrentVersion} -> {LatestVersion}", Program.InformationalVersion, latestVersion); + } + else + { + State.SetValue(state => state with { Version = state.Version with { Latest = Program.InformationalVersion, IsUpdateAvailable = false } }); + Logger.Information("Version {CurrentVersion} is up to date.", Program.InformationalVersion); + } + } + catch (Exception ex) + { + Logger.Warning("Failed to check version: {Message}", ex.Message); + throw; + } + } + + /// + /// Re-scans shared directories. + /// + /// The operation context. + public Task RescanSharesAsync() => SharedFileCache.FillAsync(); + + async Task IHostedService.StartAsync(CancellationToken cancellationToken) + { + Logger.Information("Configuring client"); + + ProxyOptions proxyOptions = default; + + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) + { + proxyOptions = new ProxyOptions( + address: OptionsAtStartup.Soulseek.Connection.Proxy.Address, + port: OptionsAtStartup.Soulseek.Connection.Proxy.Port.Value, + username: OptionsAtStartup.Soulseek.Connection.Proxy.Username, + password: OptionsAtStartup.Soulseek.Connection.Proxy.Password); + } + + var connectionOptions = new ConnectionOptions( + readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read, + writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write, + connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity, + proxyOptions: proxyOptions); + + var patch = new SoulseekClientOptionsPatch( + listenPort: OptionsAtStartup.Soulseek.ListenPort, + enableListener: true, + userEndPointCache: new UserEndPointCache(), + distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled, + autoAcknowledgePrivateMessages: false, + acceptPrivateRoomInvitations: true, + serverConnectionOptions: connectionOptions, + peerConnectionOptions: connectionOptions, + transferConnectionOptions: connectionOptions, + distributedConnectionOptions: connectionOptions, + userInfoResponseResolver: UserInfoResponseResolver, + browseResponseResolver: BrowseResponseResolver, + directoryContentsResponseResolver: DirectoryContentsResponseResolver, + enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), + searchResponseCache: new SearchResponseCache(), + searchResponseResolver: SearchResponseResolver); + + await Client.ReconfigureOptionsAsync(patch); + + Logger.Information("Client configured"); + Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); + + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) + { + Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}"); + } + + if (!OptionsAtStartup.NoVersionCheck) + { + _ = CheckVersionAsync(); + } + + if (OptionsAtStartup.NoShareScan) + { + Logger.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); + } + else + { + _ = SharedFileCache.FillAsync(); + } + + if (OptionsAtStartup.NoConnect) + { + Logger.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled"); + } + else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) + { + Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); + } + else + { + await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); + } + } + + Task IHostedService.StopAsync(CancellationToken cancellationToken) + { + Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down")); + Client.Dispose(); + Logger.Information("Client stopped"); + return Task.CompletedTask; + } + + /// + /// Creates and returns an instances of in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving an IEnumerable of Soulseek.Directory. + private Task BrowseResponseResolver(string username, IPEndPoint endpoint) + { + var directories = SharedFileCache.Browse() + .Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes + + return Task.FromResult(new BrowseResponse(directories)); + } + + private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) + { + BrowseTracker.AddOrUpdate(args.Username, args); + } + + private void Client_Connected(object sender, EventArgs e) + { + Logger.Information("Connected to the Soulseek server"); + } + + private void Client_DiagnosticGenerated(object sender, DiagnosticEventArgs args) + { + static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch + { + DiagnosticLevel.Debug => LogEventLevel.Debug, + DiagnosticLevel.Info => LogEventLevel.Information, + DiagnosticLevel.Warning => LogEventLevel.Warning, + DiagnosticLevel.None => default, + _ => default, + }; + + var logger = Loggers.GetOrAdd(sender.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", sender.GetType().FullName)); + + logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); + } + + private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) + { + if (State.CurrentValue.PendingReconnect) + { + State.SetValue(state => state with { PendingReconnect = false }); + } + + if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) + { + Logger.Information("Disconnected from the Soulseek server: the client is shutting down"); + } + else if (args.Exception is IntentionalDisconnectException) + { + Logger.Information("Disconnected from the Soulseek server: disconnected by the user"); + } + else if (args.Exception is LoginRejectedException) + { + Logger.Error("Disconnected from the Soulseek server: invalid username or password"); + } + else if (args.Exception is KickedFromServerException) + { + Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Client.Username); + } + else + { + Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); + + if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + { + Logger.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); + return; + } + + var attempts = 1; + + while (true) + { + var (delay, jitter) = Compute.ExponentialBackoffDelay( + iteration: attempts, + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); + + var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); + Logger.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); + await Task.Delay(delay + jitter); + + Logger.Information($"Attempting to reconnect (#{attempts})...", attempts); + + try + { + // reconnect with the latest configuration values we have for username and password, instead of the + // options that were captured at startup. if a user has updated these values prior to the disconnect, the + // changes will take effect now. + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + break; + } + catch (Exception ex) + { + attempts++; + Logger.Error("Failed to reconnect: {Message}", ex.Message); + } + } + } + } + + private void Client_LoggedIn(object sender, EventArgs e) + { + Logger.Information("Logged in to the Soulseek server as {Username}", Client.Username); + + // 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); + } + + private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) + { + ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); + + if (Options.Integration.Pushbullet.Enabled && !args.Replayed) + { + Console.WriteLine("Pushing..."); + _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); + } + } + + private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) + { + Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); + + if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) + { + _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); + } + } + + private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) + { + var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); + + if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) + { + _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); + } + } + + private void Client_StateChanged(object sender, SoulseekClientStateChangedEventArgs e) + { + State.SetValue(state => state with { Server = state.Server with { Address = Client.Address, IPEndPoint = Client.IPEndPoint, State = Client.State, Username = Client.Username } }); + } + + 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"); + } + + private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) + { + var xfer = args.Transfer; + var direction = xfer.Direction.ToString().ToUpper(); + var user = xfer.Username; + var file = Path.GetFileName(xfer.Filename); + var oldState = args.PreviousState; + var state = xfer.State; + + var completed = xfer.State.HasFlag(TransferStates.Completed); + + Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({xfer.BytesTransferred}/{xfer.Size} = {xfer.PercentComplete}%) @ {xfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); + + if (xfer.Direction == TransferDirection.Upload && xfer.State.HasFlag(TransferStates.Completed | TransferStates.Succeeded)) + { + _ = Client.SendUploadSpeedAsync((int)args.Transfer.AverageSpeed); + } + } + + private void Client_UserStatusChanged(object sender, UserStatusChangedEventArgs args) + { + Console.WriteLine($"[USER] {args.Username}: {args.Status}"); + } + + /// + /// Creates and returns a in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// The unique token for the request, supplied by the requesting user. + /// The requested directory. + /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. + private Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + { + var dir = SharedFileCache.List(directory); + return Task.FromResult(dir); + } + + /// + /// Invoked upon a remote request to download a file. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// The filename of the requested file. + /// (for example purposes) the ITransferTracker used to track progress. + /// A Task representing the asynchronous operation. + /// + /// Thrown when the download is rejected. The Exception message will be passed to the remote user. + /// + /// + /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for + /// security reasons. + /// + private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) + { + _ = endpoint; + var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath(); + + var fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); + throw new DownloadEnqueueException($"File not shared."); + } + + if (tracker.TryGet(TransferDirection.Upload, username, filename, out _)) + { + // 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; + } + + // create a new cancellation token source so that we can cancel the upload from the UI. + var cts = new CancellationTokenSource(); + var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (t, c) => Task.Delay(1, c)); + + // 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 () => + { + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + await Client.UploadAsync(username, filename, fileInfo.Length, stream, options: topts, cancellationToken: cts.Token); + }).ContinueWith(t => + { + 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) + { + // this code is known to fire more than once per update. i'm not sure whether these might be executed concurrently. + // lock to be safe, because we need to accurately track the last value of Options for diffing purposes. threading + // shenanigans here could lead to missed updates. + OptionsSyncRoot.EnterWriteLock(); + + try + { + var pendingRestart = false; + var pendingReconnect = false; + var soulseekRequiresReconnect = false; + + var diff = PreviousOptions.DiffWith(newOptions); + + // don't react to duplicate/no-change events https://github.com/slskd/slskd/issues/126 + if (!diff.Any()) + { + return; + } + + foreach (var (property, fqn, left, right) in diff) + { + static bool HasAttribute(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); + + var requiresRestart = HasAttribute(property); + var requiresReconnect = HasAttribute(property); + + Logger.Debug($"{fqn} changed from '{left.ToJson() ?? ""}' to '{right.ToJson() ?? ""}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}"); + + pendingRestart |= requiresRestart; + pendingReconnect |= requiresReconnect; + } + + if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() + || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) + { + State.SetValue(state => state with { PendingShareRescan = true }); + Logger.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 }); + Logger.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect."); + } + + if (PreviousOptions.Rooms.Except(newOptions.Rooms).Any() + || newOptions.Rooms.Except(PreviousOptions.Rooms).Any()) + { + Logger.Information("Room configuration changed. Joining any newly added rooms."); + _ = RoomService.TryJoinAsync(newOptions.Rooms); + } + + // determine whether any Soulseek options changed. if so, we need to construct a patch and invoke ReconfigureOptionsAsync(). + var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek); + + if (slskDiff.Any()) + { + var old = PreviousOptions.Soulseek; + var update = newOptions.Soulseek; + + Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson()); + + // determine whether any Connection options changed. if so, replace the whole object. Soulseek.NET doesn't + // offer a way to patch parts of connection options. the updates only affect new connections, so a partial + // patch doesn't make a lot of sense anyway. + var connectionDiff = old.Connection.DiffWith(update.Connection); + + ConnectionOptions connectionPatch = null; + + if (connectionDiff.Any()) + { + var connection = update.Connection; + + ProxyOptions proxyPatch = null; + + if (connection.Proxy.Enabled) + { + proxyPatch = new ProxyOptions( + connection.Proxy.Address, + connection.Proxy.Port.Value, + connection.Proxy.Username, + connection.Proxy.Password); + } + + connectionPatch = new ConnectionOptions( + connection.Buffer.Read, + connection.Buffer.Write, + connection.Timeout.Connect, + connection.Timeout.Inactivity, + proxyOptions: proxyPatch); + } + + var patch = new SoulseekClientOptionsPatch( + listenPort: old.ListenPort == update.ListenPort ? null : update.ListenPort, + enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled, + distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit, + serverConnectionOptions: connectionPatch, + peerConnectionOptions: connectionPatch, + transferConnectionOptions: connectionPatch, + incomingConnectionOptions: connectionPatch, + distributedConnectionOptions: connectionPatch); + + Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson()); + + soulseekRequiresReconnect = await Client.ReconfigureOptionsAsync(patch); + } + + // require a reconnect if the client is connected and any options marked [RequiresReconnect] changed, OR if the + // call to reconfigure the client requires a reconnect + if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) || soulseekRequiresReconnect) + { + State.SetValue(state => state with { PendingReconnect = true }); + Logger.Information("One or more updated Soulseek options requires the client to be disconnected, then reconnected to the network to take effect."); + } + + if (pendingRestart) + { + State.SetValue(state => state with { PendingRestart = true }); + Logger.Information("One or more updated options requires an application restart to take effect."); + } + + Logger.Information("Options updated successfully."); + } + catch (Exception ex) + { + Logger.Error(ex, "Failed to apply option update: {Message}", ex.Message); + } + finally + { + PreviousOptions = OptionsMonitor.CurrentValue; + OptionsSyncRoot.ExitWriteLock(); + } + } + + /// + /// Creates and returns a in response to the given . + /// + /// The username of the requesting user. + /// The search token. + /// The search query. + /// A Task resolving a SearchResponse, or null. + private async Task SearchResponseResolver(string username, int token, SearchQuery query) + { + // some bots continually query for very common strings. blacklist known names here. + var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; + if (blacklist.Contains(username)) + { + return null; + } + + // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. + if (query.Query.Length < 3) + { + return null; + } + + var results = await SharedFileCache.SearchAsync(query); + + if (results.Any()) + { + Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); + + return new SearchResponse( + Client.Username, + token, + freeUploadSlots: 1, + uploadSpeed: 0, + queueLength: 0, + fileList: results); + } + + // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no + // response will be sent to the requestor. + return null; + } + + private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) + { + var (previous, current) = state; + + if (!previous.Filling && current.Filling) + { + SharesRefreshStarted = DateTime.UtcNow; + + State.SetValue(s => s with { SharedFileCache = current }); + Logger.Information("Scanning shares"); + } + + var lastProgress = Math.Round(previous.FillProgress * 100); + var currentProgress = Math.Round(current.FillProgress * 100); + + if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) + { + State.SetValue(s => s with { SharedFileCache = current }); + Logger.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); + } + + if (previous.Filling && !current.Filling) + { + State.SetValue(s => s with { SharedFileCache = current }); + + if (current.Faulted) + { + Logger.Error("Failed to scan shares."); + } + else + { + State.SetValue(s => s with { PendingShareRescan = false }); + Logger.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); + } + } + } + } + + private void State_OnChange((State Previous, State Current) state) + { + Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); + ApplicationHub.BroadcastStateAsync(state.Current); + } + + /// + /// Creates and returns a object in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving the UserInfo instance. + private Task UserInfoResponseResolver(string username, IPEndPoint endpoint) + { + var info = new UserInfo( + description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}", + picture: Array.Empty(), + uploadSlots: 1, + queueLength: 0, + hasFreeUploadSlot: false); + + return Task.FromResult(info); + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Exceptions/ApplicationShutdownException.cs b/src/slskd/Application/Exceptions/ApplicationShutdownException.cs deleted file mode 100644 index e30b5c79..00000000 --- a/src/slskd/Application/Exceptions/ApplicationShutdownException.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.Serialization; - - /// - /// Represents a normal application shutdown. - /// - [ExcludeFromCodeCoverage] - [Serializable] - public class ApplicationShutdownException : SlskdException - { - /// - /// Initializes a new instance of the class. - /// - public ApplicationShutdownException() - : base() - { - } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// The message that describes the error. - public ApplicationShutdownException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class with a specified error message and a - /// reference to the inner exception that is the cause of this exception. - /// - /// The message that describes the error. - /// - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no - /// inner exception is specified. - /// - public ApplicationShutdownException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The SerializationInfo that holds the serialized object data about the exception being thrown. - /// The StreamingContext that contains contextual information about the source or destination. - protected ApplicationShutdownException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Exceptions/IntentionalDisconnectException.cs b/src/slskd/Application/Exceptions/IntentionalDisconnectException.cs deleted file mode 100644 index d5293e63..00000000 --- a/src/slskd/Application/Exceptions/IntentionalDisconnectException.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.Serialization; - - /// - /// Represents an intentional client disconnect. - /// - [ExcludeFromCodeCoverage] - [Serializable] - public class IntentionalDisconnectException : SlskdException - { - /// - /// Initializes a new instance of the class. - /// - public IntentionalDisconnectException() - : base() - { - } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// The message that describes the error. - public IntentionalDisconnectException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class with a specified error message and a - /// reference to the inner exception that is the cause of this exception. - /// - /// The message that describes the error. - /// - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no - /// inner exception is specified. - /// - public IntentionalDisconnectException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The SerializationInfo that holds the serialized object data about the exception being thrown. - /// The StreamingContext that contains contextual information about the source or destination. - protected IntentionalDisconnectException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Exceptions/RetryException.cs b/src/slskd/Application/Exceptions/RetryException.cs deleted file mode 100644 index c688f377..00000000 --- a/src/slskd/Application/Exceptions/RetryException.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.Serialization; - - /// - /// Represents erorrs that originate while attempting to execute retry logic. - /// - [ExcludeFromCodeCoverage] - [Serializable] - public class RetryException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public RetryException() - : base() - { - } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// The message that describes the error. - public RetryException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class with a specified error message and a - /// reference to the inner exception that is the cause of this exception. - /// - /// The message that describes the error. - /// - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no - /// inner exception is specified. - /// - public RetryException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The SerializationInfo that holds the serialized object data about the exception being thrown. - /// The StreamingContext that contains contextual information about the source or destination. - protected RetryException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Exceptions/ShareAliasException.cs b/src/slskd/Application/Exceptions/ShareAliasException.cs deleted file mode 100644 index 3047d0a9..00000000 --- a/src/slskd/Application/Exceptions/ShareAliasException.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.Serialization; - - /// - /// Represents an error that occurs when multiple share scans are attempted concurrently. - /// - [ExcludeFromCodeCoverage] - [Serializable] - public class ShareAliasException : SlskdException - { - /// - /// Initializes a new instance of the class. - /// - public ShareAliasException() - : base() - { - } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// The message that describes the error. - public ShareAliasException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class with a specified error message and a - /// reference to the inner exception that is the cause of this exception. - /// - /// The message that describes the error. - /// - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no - /// inner exception is specified. - /// - public ShareAliasException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The SerializationInfo that holds the serialized object data about the exception being thrown. - /// The StreamingContext that contains contextual information about the source or destination. - protected ShareAliasException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Exceptions/ShareScanInProgressException.cs b/src/slskd/Application/Exceptions/ShareScanInProgressException.cs deleted file mode 100644 index 2e548930..00000000 --- a/src/slskd/Application/Exceptions/ShareScanInProgressException.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.Serialization; - - /// - /// Represents an error that occurs when multiple share scans are attempted concurrently. - /// - [ExcludeFromCodeCoverage] - [Serializable] - public class ShareScanInProgressException : SlskdException - { - /// - /// Initializes a new instance of the class. - /// - public ShareScanInProgressException() - : base() - { - } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// The message that describes the error. - public ShareScanInProgressException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class with a specified error message and a - /// reference to the inner exception that is the cause of this exception. - /// - /// The message that describes the error. - /// - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no - /// inner exception is specified. - /// - public ShareScanInProgressException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The SerializationInfo that holds the serialized object data about the exception being thrown. - /// The StreamingContext that contains contextual information about the source or destination. - protected ShareScanInProgressException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Exceptions/SlskdException.cs b/src/slskd/Application/Exceptions/SlskdException.cs deleted file mode 100644 index 6b4cfc2a..00000000 --- a/src/slskd/Application/Exceptions/SlskdException.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.Serialization; - - /// - /// Represents erorrs that originate from slskd logic. - /// - [ExcludeFromCodeCoverage] - [Serializable] - public class SlskdException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public SlskdException() - : base() - { - } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// The message that describes the error. - public SlskdException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class with a specified error message and a - /// reference to the inner exception that is the cause of this exception. - /// - /// The message that describes the error. - /// - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no - /// inner exception is specified. - /// - public SlskdException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The SerializationInfo that holds the serialized object data about the exception being thrown. - /// The StreamingContext that contains contextual information about the source or destination. - protected SlskdException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Hub.cs b/src/slskd/Application/Hub.cs deleted file mode 100644 index 0112bcb2..00000000 --- a/src/slskd/Application/Hub.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System.Threading.Tasks; - using Microsoft.AspNetCore.SignalR; - - /// - /// Extension methods for the application SignalR hub. - /// - public static class HubExtensions - { - /// - /// Broadcast the present application state. - /// - /// The hub. - /// The state to broadcast. - /// The operation context. - public static Task BroadcastStateAsync(this IHubContext hub, State state) - { - return hub.Clients.All.SendAsync(Methods.State, state); - } - - private static class Methods - { - public static readonly string State = "STATE"; - } - } - - /// - /// The application SignalR hub. - /// - public class Hub : Microsoft.AspNetCore.SignalR.Hub - { - } -} \ No newline at end of file diff --git a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs deleted file mode 100644 index 470e5a30..00000000 --- a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs +++ /dev/null @@ -1,115 +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.Management.API -{ - using System; - using System.Diagnostics; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Microsoft.Extensions.Hosting; - - /// - /// Application. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class ApplicationController : ControllerBase - { - public ApplicationController( - IHostApplicationLifetime lifetime, - IApplication application, - IStateMonitor applicationStateMonitor) - { - Lifetime = lifetime; - Application = application; - ApplicationStateMonitor = applicationStateMonitor; - } - - private IApplication Application { get; } - private IStateMonitor ApplicationStateMonitor { get; } - private IHostApplicationLifetime Lifetime { get; } - - /// - /// Gets the current state of the application. - /// - /// - [HttpGet] - [Authorize] - public IActionResult State() - { - return Ok(ApplicationStateMonitor.CurrentValue); - } - - /// - /// Stops the application. - /// - /// - [HttpDelete] - [Authorize] - public IActionResult Shutdown() - { - Lifetime.StopApplication(); - return NoContent(); - } - - /// - /// Restarts the application. - /// - /// - [HttpPut] - [Authorize] - public IActionResult Restart() - { - Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); - Lifetime.StopApplication(); - - return NoContent(); - } - - /// - /// Gets the current application version. - /// - /// - [HttpGet("version")] - [Authorize] - public IActionResult GetVersion() - { - return Ok(Program.InformationalVersion); - } - - /// - /// Checks for updates. - /// - /// - [HttpGet("version/latest")] - [Authorize] - public async Task CheckVersion([FromQuery]bool forceCheck = false) - { - if (forceCheck) - { - await Application.CheckVersionAsync(); - } - - return Ok(ApplicationStateMonitor.CurrentValue.Version); - } - } -} diff --git a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs deleted file mode 100644 index c28c5c7e..00000000 --- a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs +++ /dev/null @@ -1,74 +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/. -// - -using Microsoft.Extensions.Options; - -namespace slskd.Management.API -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using slskd.Management; - - /// - /// Configuration. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class ConfigurationController : ControllerBase - { - public ConfigurationController( - IApplication application, - IOptionsSnapshot optionsShapshot, - IStateMonitor applicationStateMonitor) - { - Application = application; - OptionsShapshot = optionsShapshot; - ApplicationStateMonitor = applicationStateMonitor; - } - - private IApplication Application { get; } - private IOptionsSnapshot OptionsShapshot { get; } - private IStateMonitor ApplicationStateMonitor { get; } - - [HttpGet] - [Route("")] - [Authorize] - public IActionResult GetOptions() - { - // todo: sanitize this to remove passwords - return Ok(OptionsShapshot.Value); - } - - [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/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs deleted file mode 100644 index 6f6275d1..00000000 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ /dev/null @@ -1,71 +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/. -// - -using Microsoft.Extensions.Options; - -namespace slskd.Management.API -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - - /// - /// Options. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class OptionsController : ControllerBase - { - public OptionsController( - OptionsAtStartup optionsAtStartup, - IOptionsSnapshot optionsSnapshot) - { - OptionsAtStartup = optionsAtStartup; - OptionsSnapshot = optionsSnapshot; - } - - private IOptionsSnapshot OptionsSnapshot { get; } - private OptionsAtStartup OptionsAtStartup { get; } - - /// - /// Gets the current application options. - /// - /// - [HttpGet] - [Authorize] - [ProducesResponseType(typeof(Options), 200)] - public IActionResult Current() - { - return Ok(OptionsSnapshot.Value); - } - - /// - /// Gets the application options provided at startup. - /// - /// - [HttpGet] - [Route("startup")] - [Authorize] - [ProducesResponseType(typeof(Options), 200)] - public IActionResult Startup() - { - return Ok(OptionsAtStartup); - } - } -} diff --git a/src/slskd/Application/Management/API/Controllers/ServerController.cs b/src/slskd/Application/Management/API/Controllers/ServerController.cs deleted file mode 100644 index e3199d78..00000000 --- a/src/slskd/Application/Management/API/Controllers/ServerController.cs +++ /dev/null @@ -1,105 +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/. -// - -using Microsoft.Extensions.Options; - -namespace slskd.Management.API -{ - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - - /// - /// Server. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class ServerController : ControllerBase - { - public ServerController( - ISoulseekClient soulseekClient, - IOptionsSnapshot optionsSnapshot, - IStateSnapshot stateSnapshot) - { - Client = soulseekClient; - OptionsSnapshot = optionsSnapshot; - StateSnapshot = stateSnapshot; - } - - private ISoulseekClient Client { get; } - private IOptionsSnapshot OptionsSnapshot { get; } - private IStateSnapshot StateSnapshot { get; } - - /// - /// Connects the client. - /// - /// - [HttpPut] - [Route("")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(403)] - public async Task Connect() - { - if (!Client.State.HasFlag(SoulseekClientStates.Connected)) - { - await Client.ConnectAsync(OptionsSnapshot.Value.Soulseek.Username, OptionsSnapshot.Value.Soulseek.Password); - } - - return Ok(); - } - - /// - /// Disconnects the client. - /// - /// - /// - [HttpDelete] - [Route("")] - [Authorize] - [ProducesResponseType(204)] - [ProducesResponseType(403)] - public IActionResult Disconnect([FromBody] string message) - { - if (Client.State.HasFlag(SoulseekClientStates.Connected)) - { - Client.Disconnect(message, new IntentionalDisconnectException(message)); - } - - return NoContent(); - } - - /// - /// Retrieves the current state of the server. - /// - /// - /// - [HttpGet] - [Route("")] - [Authorize] - [ProducesResponseType(typeof(ServerState), 200)] - [ProducesResponseType(403)] - public IActionResult Get() - { - return Ok(StateSnapshot.Value.Server); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs deleted file mode 100644 index a9ae0188..00000000 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ /dev/null @@ -1,148 +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/. -// - -using Microsoft.Extensions.Options; - -namespace slskd.Management.API -{ - using System; - using System.Collections.Generic; - using System.IdentityModel.Tokens.Jwt; - using System.Security.Claims; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Microsoft.IdentityModel.Tokens; - using slskd.Authentication; - - /// - /// Session. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class SessionController : ControllerBase - { - public SessionController( - IOptionsSnapshot optionsSnapshot, - OptionsAtStartup optionsAtStartup, - SymmetricSecurityKey jwtSigningKey) - { - OptionsSnapshot = optionsSnapshot; - OptionsAtStartup = optionsAtStartup; - JwtSigningKey = jwtSigningKey; - } - - private SymmetricSecurityKey JwtSigningKey { get; set; } - private IOptionsSnapshot OptionsSnapshot { get; set; } - private OptionsAtStartup OptionsAtStartup { get; set; } - - /// - /// Checks whether the provided authentication is valid. - /// - /// This is a no-op provided so that the application can test for an expired token on load. - /// - /// The authentication is valid. - /// The authentication is is invalid. - [HttpGet] - [Route("")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(401)] - public IActionResult Check() - { - return Ok(); - } - - /// - /// Checks whether security is enabled. - /// - /// - /// True if security is enabled, false otherwise. - [HttpGet] - [Route("enabled")] - [AllowAnonymous] - [ProducesResponseType(typeof(bool), 200)] - public IActionResult Enabled() - { - return Ok(!OptionsAtStartup.Web.Authentication.Disabled); - } - - /// - /// Logs in. - /// - /// - /// - /// Login was successful. - /// Bad request. - /// Login failed. - [HttpPost] - [Route("")] - [AllowAnonymous] - [ProducesResponseType(typeof(TokenResponse), 200)] - [ProducesResponseType(400)] - [ProducesResponseType(401)] - [ProducesResponseType(typeof(string), 500)] - public IActionResult Login([FromBody] LoginRequest login) - { - if (login == default) - { - return BadRequest(); - } - - if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password)) - { - return BadRequest("Username and/or Password missing or invalid"); - } - - // only admin login for now - if (OptionsSnapshot.Value.Web.Authentication.Username == login.Username && OptionsSnapshot.Value.Web.Authentication.Password == login.Password) - { - return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); - } - - return Unauthorized(); - } - - private JwtSecurityToken GetJwtSecurityToken(string username, Role role) - { - var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(OptionsAtStartup.Web.Authentication.Jwt.Ttl); - - var claims = new List() - { - new Claim(ClaimTypes.Name, username), - new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.Role, role.ToString()), - new Claim("name", username), - new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), - }; - - var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); - - var token = new JwtSecurityToken( - issuer: Program.AppName, - claims: claims, - notBefore: issuedUtc, - expires: expiresUtc, - signingCredentials: credentials); - - return token; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Management/API/DTO/LoginRequest.cs b/src/slskd/Application/Management/API/DTO/LoginRequest.cs deleted file mode 100644 index d4b8dd75..00000000 --- a/src/slskd/Application/Management/API/DTO/LoginRequest.cs +++ /dev/null @@ -1,25 +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.Management.API -{ - public class LoginRequest - { - public string Username { get; set; } - public string Password { get; set; } - } -} diff --git a/src/slskd/Application/Management/API/DTO/ServerState.cs b/src/slskd/Application/Management/API/DTO/ServerState.cs deleted file mode 100644 index 80c1e856..00000000 --- a/src/slskd/Application/Management/API/DTO/ServerState.cs +++ /dev/null @@ -1,33 +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.Management -{ - using System.Net; - using Soulseek; - - public class ServerState - { - public string Address { get; set; } - public IPEndPoint IPEndPoint { get; set; } - public SoulseekClientStates State { get; set; } - public string Username { get; set; } - public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); - public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); - public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); - } -} diff --git a/src/slskd/Application/Management/API/DTO/TokenResponse.cs b/src/slskd/Application/Management/API/DTO/TokenResponse.cs deleted file mode 100644 index 21508b81..00000000 --- a/src/slskd/Application/Management/API/DTO/TokenResponse.cs +++ /dev/null @@ -1,67 +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.Management.API -{ - using System; - using System.IdentityModel.Tokens.Jwt; - using System.Linq; - using System.Security.Claims; - using System.Text.Json.Serialization; - using Microsoft.AspNetCore.Authentication.JwtBearer; - - public class TokenResponse - { - public TokenResponse(JwtSecurityToken jwtSecurityToken) - { - JwtSecurityToken = jwtSecurityToken; - } - - /// - /// Gets the time at which the Access Token expires. - /// - public long Expires => ((DateTimeOffset)JwtSecurityToken.ValidTo).ToUnixTimeSeconds(); - - /// - /// Gets the time at which the Access Token was issued. - /// - public long Issued => ((DateTimeOffset)JwtSecurityToken.ValidFrom).ToUnixTimeSeconds(); - - /// - /// Gets the value of the Name claim from the Access Token. - /// - public string Name => JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name)?.Value; - - /// - /// Gets the value of the Not Before claim from the Access Token. - /// - public long NotBefore => long.Parse(JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == "nbf").Value); - - /// - /// Gets the Access Token string. - /// - public string Token => new JwtSecurityTokenHandler().WriteToken(JwtSecurityToken); - - /// - /// Gets the Token type. - /// - public string TokenType => JwtBearerDefaults.AuthenticationScheme; - - [JsonIgnore] - private JwtSecurityToken JwtSecurityToken { get; } - } -} \ No newline at end of file diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs deleted file mode 100644 index 71d1bae1..00000000 --- a/src/slskd/Application/SharedFileCache.cs +++ /dev/null @@ -1,471 +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/. -// - -using System.IO; -using Microsoft.Extensions.Options; - -namespace slskd -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Text.RegularExpressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Data.Sqlite; - using Serilog; - using Soulseek; - - /// - /// Shared file cache. - /// - public interface ISharedFileCache - { - /// - /// Gets the cache state monitor. - /// - IStateMonitor StateMonitor { get; } - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - IEnumerable Browse(); - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - Task FillAsync(); - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - Directory List(string directory); - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename); - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - Task> SearchAsync(SearchQuery query); - } - - /// - /// Shared file cache. - /// - public class SharedFileCache : ISharedFileCache - { - /// - /// Initializes a new instance of the class. - /// - /// - public SharedFileCache( - IOptionsMonitor optionsMonitor) - { - OptionsMonitor = optionsMonitor; - } - - /// - /// Gets the cache state monitor. - /// - public IStateMonitor StateMonitor => State; - - private IManagedState State { get; } = new ManagedState(); - private ILogger Log { get; } = Serilog.Log.ForContext(); - private HashSet MaskedDirectories { get; set; } - private Dictionary MaskedFiles { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } - private List Shares { get; set; } - private SqliteConnection SQLite { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - public IEnumerable Browse() - { - // ignore requests while the cache is building - if (SyncRoot.CurrentCount == 0) - { - return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; - } - - var directories = new ConcurrentDictionary(); - - // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if - // missing, files that are nested within directories which contain only directories (no files) are displayed as being - // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if - // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the - // files. if not they'll be left as is. - foreach (var directory in MaskedDirectories) - { - directories.TryAdd(directory, new Directory(directory)); - } - - var groups = MaskedFiles - .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Directory(g.Key, g.Select(g => - { - var f = g.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. - f.Size, - f.Extension, - f.Attributes); - }))); - - // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. - // entries with no files will remain untouched. - foreach (var group in groups) - { - directories.AddOrUpdate(group.Name, group, (_, _) => group); - } - - return directories.Values.OrderBy(f => f.Name); - } - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - public async Task FillAsync() - { - // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. - if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) - { - Log.Warning("Shared file scan rejected; scan is already in progress."); - throw new ShareScanInProgressException("Shared files are already being scanned."); - } - - try - { - await Task.Yield(); - - ResetCache(); - - State.SetValue(state => state with { Filling = true, FillProgress = 0 }); - Log.Debug("Starting shared file scan"); - - var sw = new Stopwatch(); - var swSnapshot = 0L; - sw.Start(); - - Shares = OptionsMonitor.CurrentValue.Directories.Shared - .Select(share => Path.TrimEndingDirectorySeparator(share)) - .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(); - - if (!Shares.Any()) - { - Log.Warning("Aborting shared file scan; no shares configured."); - } - - Log.Debug("Enumerating shared directories"); - swSnapshot = sw.ElapsedMilliseconds; - - var unmaskedDirectories = Shares - .SelectMany(share => - { - try - { - return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); - } - catch (Exception ex) - { - Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); - return Array.Empty(); - } - }) - .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) - .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. - .ToHashSet(); // remove duplicates (in case shares overlap) - - var excludedDirectories = unmaskedDirectories - .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); - - unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); - - State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); - 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(); - var maskedDirectories = new HashSet(); - var current = 0; - var filtered = 0; - - foreach (var directory in unmaskedDirectories) - { - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); - - // 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 - try - { - var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) - .Select(f => new File(1, f.ReplaceFirst(share.LocalPath, share.RemotePath), new FileInfo(f).Length, Path.GetExtension(f))) - .ToDictionary(f => f.Filename, f => f); - - // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully - // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var file in newFiles) - { - if (filters.Any(filter => filter.IsMatch(file.Key))) - { - filtered++; - continue; - } - - if (files.ContainsKey(file.Key)) - { - Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); - } - - files[file.Key] = file.Value; - } - } - catch (Exception ex) - { - Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); - } - - current++; - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); - } - - Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } - - Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); - - MaskedDirectories = maskedDirectories; - MaskedFiles = files; - - State.SetValue(state => state with { Filling = false, Faulted = false, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); - Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); - } - catch (Exception ex) - { - State.SetValue(state => state with { Filling = false, Faulted = true, FillProgress = 0 }); - Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); - throw; - } - finally - { - SyncRoot.Release(); - } - } - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - public Directory List(string directory) - { - var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => - { - var f = kvp.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), - f.Size, - f.Extension, - f.Attributes); - }); - - return new Directory(directory, files); - } - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename) - { - var resolved = filename; - - // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a - // file. split the requested filename so we can examine the first two segments - var parts = filename.Split(new[] { '/', '\\' }); - - if (parts.Length < 2) - { - return resolved; - } - - // find the share with a matching mask and alias/local directory - var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); - - if (share == default) - { - return resolved; - } - - return resolved.ReplaceFirst(share.RemotePath, share.LocalPath); - } - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - public async Task> SearchAsync(SearchQuery query) - { - // ignore requests while the cache is building - if (SyncRoot.CurrentCount == 0) - { - return Enumerable.Empty(); - } - - string Clean(string str) => str.Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " ") - .Replace("'", "''"); - - var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); - var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); - - var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; - var results = new List(); - - try - { - using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - using var cmd = new SqliteCommand(sql, conn); - await conn.OpenAsync(); - - var reader = await cmd.ExecuteReaderAsync(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - - return results.Select(r => MaskedFiles[r.Replace("''", "'")]); - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); - return Enumerable.Empty(); - } - } - - private void CreateTable() - { - if (SQLite != null) - { - SQLite.Dispose(); - } - - 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); - cmd.ExecuteNonQuery(); - } - - private void InsertFilename(string filename) - { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); - cmd.ExecuteNonQuery(); - } - - private void ResetCache() - { - CreateTable(); - MaskedDirectories = new HashSet(); - MaskedFiles = new Dictionary(); - State.SetValue(state => state with { Directories = 0, Files = 0 }); - } - - private class Share - { - public Share(string share) - { - Raw = share; - IsExcluded = share.StartsWith('-') || share.StartsWith('!'); - - if (IsExcluded) - { - share = share[1..]; - } - - // test to see whether an alias has been specified - var matches = Regex.Matches(share, @"^\[(.*)\](.*)$"); - - if (matches.Any()) - { - // split the alias from the path, and validate the alias - var groups = matches[0].Groups; - Alias = groups[1].Value; - LocalPath = groups[2].Value; - } - else - { - Alias = share.Split(new[] { '/', '\\' }).Last(); - LocalPath = share; - } - - Mask = Compute.MaskHash(System.IO.Directory.GetParent(LocalPath).FullName); - - var maskedPath = LocalPath.ReplaceFirst(System.IO.Directory.GetParent(LocalPath).FullName, Mask); - - var aliasedSegment = LocalPath[(System.IO.Directory.GetParent(LocalPath).FullName.Length + 1)..]; - RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias); - } - - 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; } - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharedFileCache.cs b/src/slskd/Application/Shares/SharedFileCache.cs new file mode 100644 index 00000000..062a059c --- /dev/null +++ b/src/slskd/Application/Shares/SharedFileCache.cs @@ -0,0 +1,471 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System.IO; +using Microsoft.Extensions.Options; + +namespace slskd.Shares +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Serilog; + using Soulseek; + + /// + /// Shared file cache. + /// + public interface ISharedFileCache + { + /// + /// Gets the cache state monitor. + /// + IStateMonitor StateMonitor { get; } + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + IEnumerable Browse(); + + /// + /// Scans the configured shares and fills the cache. + /// + /// The operation context. + Task FillAsync(); + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + Directory List(string directory); + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + Task> SearchAsync(SearchQuery query); + } + + /// + /// Shared file cache. + /// + public class SharedFileCache : ISharedFileCache + { + /// + /// Initializes a new instance of the class. + /// + /// + public SharedFileCache( + IOptionsMonitor optionsMonitor) + { + OptionsMonitor = optionsMonitor; + } + + /// + /// Gets the cache state monitor. + /// + public IStateMonitor StateMonitor => State; + + private IManagedState State { get; } = new ManagedState(); + private ILogger Log { get; } = Serilog.Log.ForContext(); + private HashSet MaskedDirectories { get; set; } + private Dictionary MaskedFiles { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private List Shares { get; set; } + private SqliteConnection SQLite { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + public IEnumerable Browse() + { + // ignore requests while the cache is building + if (SyncRoot.CurrentCount == 0) + { + return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; + } + + var directories = new ConcurrentDictionary(); + + // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if + // missing, files that are nested within directories which contain only directories (no files) are displayed as being + // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if + // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the + // files. if not they'll be left as is. + foreach (var directory in MaskedDirectories) + { + directories.TryAdd(directory, new Directory(directory)); + } + + var groups = MaskedFiles + .GroupBy(f => Path.GetDirectoryName(f.Key)) + .Select(g => new Directory(g.Key, g.Select(g => + { + var f = g.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. + f.Size, + f.Extension, + f.Attributes); + }))); + + // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. + // entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values.OrderBy(f => f.Name); + } + + /// + /// Scans the configured shares and fills the cache. + /// + /// The operation context. + public async Task FillAsync() + { + // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. + if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) + { + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); + } + + try + { + await Task.Yield(); + + ResetCache(); + + State.SetValue(state => state with { Filling = true, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + + var sw = new Stopwatch(); + var swSnapshot = 0L; + sw.Start(); + + Shares = OptionsMonitor.CurrentValue.Directories.Shared + .Select(share => Path.TrimEndingDirectorySeparator(share)) + .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(); + + if (!Shares.Any()) + { + Log.Warning("Aborting shared file scan; no shares configured."); + } + + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; + + var unmaskedDirectories = Shares + .SelectMany(share => + { + try + { + return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); + } + catch (Exception ex) + { + Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); + return Array.Empty(); + } + }) + .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) + .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. + .ToHashSet(); // remove duplicates (in case shares overlap) + + var excludedDirectories = unmaskedDirectories + .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); + + unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); + + State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); + 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(); + var maskedDirectories = new HashSet(); + var current = 0; + var filtered = 0; + + foreach (var directory in unmaskedDirectories) + { + var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + + maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + + // 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 + try + { + var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) + .Select(f => new File(1, f.ReplaceFirst(share.LocalPath, share.RemotePath), new FileInfo(f).Length, Path.GetExtension(f))) + .ToDictionary(f => f.Filename, f => f); + + // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully + // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. + foreach (var file in newFiles) + { + if (filters.Any(filter => filter.IsMatch(file.Key))) + { + filtered++; + continue; + } + + if (files.ContainsKey(file.Key)) + { + Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); + } + + files[file.Key] = file.Value; + } + } + catch (Exception ex) + { + Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); + } + + current++; + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); + } + + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in files) + { + InsertFilename(file.Key); + } + + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + + MaskedDirectories = maskedDirectories; + MaskedFiles = files; + + State.SetValue(state => state with { Filling = false, Faulted = false, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + State.SetValue(state => state with { Filling = false, Faulted = true, FillProgress = 0 }); + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; + } + finally + { + SyncRoot.Release(); + } + } + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + public Directory List(string directory) + { + var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => + { + var f = kvp.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), + f.Size, + f.Extension, + f.Attributes); + }); + + return new Directory(directory, files); + } + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename) + { + var resolved = filename; + + // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a + // file. split the requested filename so we can examine the first two segments + var parts = filename.Split(new[] { '/', '\\' }); + + if (parts.Length < 2) + { + return resolved; + } + + // find the share with a matching mask and alias/local directory + var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); + + if (share == default) + { + return resolved; + } + + return resolved.ReplaceFirst(share.RemotePath, share.LocalPath); + } + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + public async Task> SearchAsync(SearchQuery query) + { + // ignore requests while the cache is building + if (SyncRoot.CurrentCount == 0) + { + return Enumerable.Empty(); + } + + string Clean(string str) => str.Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " ") + .Replace("'", "''"); + + var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); + var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); + + var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; + var results = new List(); + + try + { + using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + using var cmd = new SqliteCommand(sql, conn); + await conn.OpenAsync(); + + var reader = await cmd.ExecuteReaderAsync(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results.Select(r => MaskedFiles[r.Replace("''", "'")]); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); + return Enumerable.Empty(); + } + } + + private void CreateTable() + { + if (SQLite != null) + { + SQLite.Dispose(); + } + + 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); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); + cmd.ExecuteNonQuery(); + } + + private void ResetCache() + { + CreateTable(); + MaskedDirectories = new HashSet(); + MaskedFiles = new Dictionary(); + State.SetValue(state => state with { Directories = 0, Files = 0 }); + } + + private class Share + { + public Share(string share) + { + Raw = share; + IsExcluded = share.StartsWith('-') || share.StartsWith('!'); + + if (IsExcluded) + { + share = share[1..]; + } + + // test to see whether an alias has been specified + var matches = Regex.Matches(share, @"^\[(.*)\](.*)$"); + + if (matches.Any()) + { + // split the alias from the path, and validate the alias + var groups = matches[0].Groups; + Alias = groups[1].Value; + LocalPath = groups[2].Value; + } + else + { + Alias = share.Split(new[] { '/', '\\' }).Last(); + LocalPath = share; + } + + Mask = Compute.MaskHash(System.IO.Directory.GetParent(LocalPath).FullName); + + var maskedPath = LocalPath.ReplaceFirst(System.IO.Directory.GetParent(LocalPath).FullName, Mask); + + var aliasedSegment = LocalPath[(System.IO.Directory.GetParent(LocalPath).FullName.Length + 1)..]; + RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias); + } + + 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; } + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/UserEndPointCache.cs b/src/slskd/Application/UserEndPointCache.cs deleted file mode 100644 index 29164cc4..00000000 --- a/src/slskd/Application/UserEndPointCache.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Net; - using Microsoft.Extensions.Caching.Memory; - using Soulseek; - - /// - /// Caches user EndPoints. - /// - public class UserEndPointCache : IUserEndPointCache - { - /// - /// Initializes a new instance of the class. - /// - public UserEndPointCache() - { - Cache = new MemoryCache(new MemoryCacheOptions()); - } - - private IMemoryCache Cache { get; } - - /// - /// Caches or updates an entry. - /// - /// The username for which to cache the endpoint. - /// The endpoint to cache. - public void AddOrUpdate(string username, IPEndPoint endPoint) - { - Cache.Set(username, endPoint, TimeSpan.FromSeconds(60)); - } - - /// - /// Gets the cached endpoint for the specified , if it exists. - /// - /// The username for which to retrieve the endpoint. - /// The cached endpoint, if it exists. - /// A value indicating whether the endpoint was found in the cache. - public bool TryGet(string username, out IPEndPoint endPoint) - { - return Cache.TryGetValue(username, out endPoint); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/UserEndPointCache.cs b/src/slskd/Common/UserEndPointCache.cs new file mode 100644 index 00000000..29164cc4 --- /dev/null +++ b/src/slskd/Common/UserEndPointCache.cs @@ -0,0 +1,61 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Net; + using Microsoft.Extensions.Caching.Memory; + using Soulseek; + + /// + /// Caches user EndPoints. + /// + public class UserEndPointCache : IUserEndPointCache + { + /// + /// Initializes a new instance of the class. + /// + public UserEndPointCache() + { + Cache = new MemoryCache(new MemoryCacheOptions()); + } + + private IMemoryCache Cache { get; } + + /// + /// Caches or updates an entry. + /// + /// The username for which to cache the endpoint. + /// The endpoint to cache. + public void AddOrUpdate(string username, IPEndPoint endPoint) + { + Cache.Set(username, endPoint, TimeSpan.FromSeconds(60)); + } + + /// + /// Gets the cached endpoint for the specified , if it exists. + /// + /// The username for which to retrieve the endpoint. + /// The cached endpoint, if it exists. + /// A value indicating whether the endpoint was found in the cache. + public bool TryGet(string username, out IPEndPoint endPoint) + { + return Cache.TryGetValue(username, out endPoint); + } + } +} \ No newline at end of file diff --git a/src/slskd/Exceptions/ApplicationShutdownException.cs b/src/slskd/Exceptions/ApplicationShutdownException.cs new file mode 100644 index 00000000..e30b5c79 --- /dev/null +++ b/src/slskd/Exceptions/ApplicationShutdownException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents a normal application shutdown. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class ApplicationShutdownException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public ApplicationShutdownException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ApplicationShutdownException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public ApplicationShutdownException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected ApplicationShutdownException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Exceptions/IntentionalDisconnectException.cs b/src/slskd/Exceptions/IntentionalDisconnectException.cs new file mode 100644 index 00000000..d5293e63 --- /dev/null +++ b/src/slskd/Exceptions/IntentionalDisconnectException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents an intentional client disconnect. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class IntentionalDisconnectException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public IntentionalDisconnectException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public IntentionalDisconnectException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public IntentionalDisconnectException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected IntentionalDisconnectException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Exceptions/RetryException.cs b/src/slskd/Exceptions/RetryException.cs new file mode 100644 index 00000000..c688f377 --- /dev/null +++ b/src/slskd/Exceptions/RetryException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents erorrs that originate while attempting to execute retry logic. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class RetryException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public RetryException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public RetryException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public RetryException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected RetryException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Exceptions/ShareAliasException.cs b/src/slskd/Exceptions/ShareAliasException.cs new file mode 100644 index 00000000..3047d0a9 --- /dev/null +++ b/src/slskd/Exceptions/ShareAliasException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class ShareAliasException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public ShareAliasException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ShareAliasException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public ShareAliasException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected ShareAliasException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Exceptions/ShareScanInProgressException.cs b/src/slskd/Exceptions/ShareScanInProgressException.cs new file mode 100644 index 00000000..2e548930 --- /dev/null +++ b/src/slskd/Exceptions/ShareScanInProgressException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class ShareScanInProgressException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public ShareScanInProgressException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ShareScanInProgressException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public ShareScanInProgressException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected ShareScanInProgressException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Exceptions/SlskdException.cs b/src/slskd/Exceptions/SlskdException.cs new file mode 100644 index 00000000..6b4cfc2a --- /dev/null +++ b/src/slskd/Exceptions/SlskdException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents erorrs that originate from slskd logic. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class SlskdException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public SlskdException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public SlskdException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public SlskdException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected SlskdException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index b47faf2e..2f50cf59 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -34,11 +34,13 @@ namespace slskd using Prometheus.SystemMetrics; using Serilog; using slskd.Authentication; + using slskd.Core; using slskd.Cryptography; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; using slskd.Messaging; using slskd.Search; + using slskd.Shares; using slskd.Transfers; using slskd.Users; using slskd.Validation; @@ -313,7 +315,8 @@ namespace slskd app.UseAuthorization(); app.UseEndpoints(endpoints => { - endpoints.MapHub("/hub"); + endpoints.MapHub("/hub/application"); + endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); -- cgit v1.2.3