From 0eb773dbd4aa2fe971bc55e5c5f12413003296bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Sep 2021 08:28:11 -0500 Subject: move stuff again --- src/slskd/Application.cs | 759 +++++++++++++++++++++ src/slskd/Application/Application.cs | 759 --------------------- .../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 -- .../API/Controllers/ConversationsController.cs | 219 ------ .../API/Controllers/PublicChatController.cs | 67 -- .../Messaging/API/Controllers/RoomsController.cs | 309 --------- .../Messaging/API/DTO/PrivateMessageResponse.cs | 74 -- .../Messaging/API/DTO/RoomInfoResponse.cs | 60 -- .../Messaging/API/DTO/RoomMessageResponse.cs | 62 -- .../Application/Messaging/API/DTO/RoomResponse.cs | 75 -- .../Messaging/API/DTO/UserDataResponse.cs | 85 --- .../Application/Messaging/ConversationTracker.cs | 62 -- .../Application/Messaging/Domain/PrivateMessage.cs | 71 -- src/slskd/Application/Messaging/Domain/Room.cs | 75 -- .../Application/Messaging/Domain/RoomMessage.cs | 59 -- .../Application/Messaging/IConversationTracker.cs | 55 -- src/slskd/Application/Messaging/IRoomTracker.cs | 75 -- src/slskd/Application/Messaging/RoomService.cs | 218 ------ src/slskd/Application/Messaging/RoomTracker.cs | 112 --- .../Search/API/Controllers/SearchesController.cs | 135 ---- .../Application/Search/API/DTO/SearchRequest.cs | 116 ---- src/slskd/Application/Search/Domain/File.cs | 51 -- src/slskd/Application/Search/Domain/Response.cs | 51 -- src/slskd/Application/Search/Domain/Search.cs | 60 -- src/slskd/Application/Search/Extensions.cs | 122 ---- src/slskd/Application/Search/ISearchService.cs | 66 -- src/slskd/Application/Search/SearchDbContext.cs | 32 - .../Application/Search/SearchResponseCache.cs | 77 --- src/slskd/Application/Search/SearchService.cs | 210 ------ src/slskd/Application/Shares/SharedFileCache.cs | 473 ------------- .../API/Controllers/TransfersController.cs | 331 --------- .../Transfers/API/DTO/QueueDownloadRequest.cs | 37 - .../Application/Transfers/API/DTO/Transfer.cs | 148 ---- .../Application/Transfers/ITransferTracker.cs | 57 -- src/slskd/Application/Transfers/TransferTracker.cs | 192 ------ .../Users/API/Controllers/UsersController.cs | 171 ----- .../Application/Users/API/DTO/UserDataResponse.cs | 85 --- src/slskd/Application/Users/BrowseTracker.cs | 57 -- src/slskd/Application/Users/Domain/Info.cs | 51 -- src/slskd/Application/Users/Domain/Status.cs | 36 - src/slskd/Application/Users/IBrowseTracker.cs | 54 -- src/slskd/Application/Users/IUserService.cs | 72 -- src/slskd/Application/Users/UserDbContext.cs | 32 - src/slskd/Application/Users/UserService.cs | 138 ---- .../Core/API/Controllers/ApplicationController.cs | 115 ++++ .../API/Controllers/ConfigurationController.cs | 73 ++ .../Core/API/Controllers/OptionsController.cs | 71 ++ src/slskd/Core/API/Controllers/ServerController.cs | 105 +++ .../Core/API/Controllers/SessionController.cs | 148 ++++ src/slskd/Core/API/DTO/LoginRequest.cs | 25 + src/slskd/Core/API/DTO/ServerState.cs | 33 + src/slskd/Core/API/DTO/TokenResponse.cs | 67 ++ src/slskd/Core/API/Hubs/ApplicationHub.cs | 51 ++ .../API/Controllers/ConversationsController.cs | 219 ++++++ .../API/Controllers/PublicChatController.cs | 67 ++ .../Messaging/API/Controllers/RoomsController.cs | 309 +++++++++ .../Messaging/API/DTO/PrivateMessageResponse.cs | 74 ++ src/slskd/Messaging/API/DTO/RoomInfoResponse.cs | 60 ++ src/slskd/Messaging/API/DTO/RoomMessageResponse.cs | 62 ++ src/slskd/Messaging/API/DTO/RoomResponse.cs | 75 ++ src/slskd/Messaging/API/DTO/UserDataResponse.cs | 85 +++ src/slskd/Messaging/ConversationTracker.cs | 62 ++ src/slskd/Messaging/Domain/PrivateMessage.cs | 71 ++ src/slskd/Messaging/Domain/Room.cs | 75 ++ src/slskd/Messaging/Domain/RoomMessage.cs | 59 ++ src/slskd/Messaging/IConversationTracker.cs | 55 ++ src/slskd/Messaging/IRoomTracker.cs | 75 ++ src/slskd/Messaging/RoomService.cs | 218 ++++++ src/slskd/Messaging/RoomTracker.cs | 112 +++ .../Search/API/Controllers/SearchesController.cs | 135 ++++ src/slskd/Search/API/DTO/SearchRequest.cs | 116 ++++ src/slskd/Search/Domain/File.cs | 51 ++ src/slskd/Search/Domain/Response.cs | 51 ++ src/slskd/Search/Domain/Search.cs | 60 ++ src/slskd/Search/Extensions.cs | 122 ++++ src/slskd/Search/ISearchService.cs | 66 ++ src/slskd/Search/SearchDbContext.cs | 32 + src/slskd/Search/SearchResponseCache.cs | 77 +++ src/slskd/Search/SearchService.cs | 210 ++++++ src/slskd/Shares/SharedFileCache.cs | 473 +++++++++++++ .../API/Controllers/TransfersController.cs | 331 +++++++++ .../Transfers/API/DTO/QueueDownloadRequest.cs | 37 + src/slskd/Transfers/API/DTO/Transfer.cs | 148 ++++ src/slskd/Transfers/ITransferTracker.cs | 57 ++ src/slskd/Transfers/TransferTracker.cs | 192 ++++++ src/slskd/Users/API/Controllers/UsersController.cs | 171 +++++ src/slskd/Users/API/DTO/UserDataResponse.cs | 85 +++ src/slskd/Users/BrowseTracker.cs | 57 ++ src/slskd/Users/Domain/Info.cs | 51 ++ src/slskd/Users/Domain/Status.cs | 36 + src/slskd/Users/IBrowseTracker.cs | 54 ++ src/slskd/Users/IUserService.cs | 72 ++ src/slskd/Users/UserDbContext.cs | 32 + src/slskd/Users/UserService.cs | 138 ++++ 102 files changed, 5979 insertions(+), 5979 deletions(-) create mode 100644 src/slskd/Application.cs delete mode 100644 src/slskd/Application/Application.cs delete mode 100644 src/slskd/Application/Core/API/Controllers/ApplicationController.cs delete mode 100644 src/slskd/Application/Core/API/Controllers/ConfigurationController.cs delete mode 100644 src/slskd/Application/Core/API/Controllers/OptionsController.cs delete mode 100644 src/slskd/Application/Core/API/Controllers/ServerController.cs delete mode 100644 src/slskd/Application/Core/API/Controllers/SessionController.cs delete mode 100644 src/slskd/Application/Core/API/DTO/LoginRequest.cs delete mode 100644 src/slskd/Application/Core/API/DTO/ServerState.cs delete mode 100644 src/slskd/Application/Core/API/DTO/TokenResponse.cs delete mode 100644 src/slskd/Application/Core/API/Hubs/ApplicationHub.cs delete mode 100644 src/slskd/Application/Messaging/API/Controllers/ConversationsController.cs delete mode 100644 src/slskd/Application/Messaging/API/Controllers/PublicChatController.cs delete mode 100644 src/slskd/Application/Messaging/API/Controllers/RoomsController.cs delete mode 100644 src/slskd/Application/Messaging/API/DTO/PrivateMessageResponse.cs delete mode 100644 src/slskd/Application/Messaging/API/DTO/RoomInfoResponse.cs delete mode 100644 src/slskd/Application/Messaging/API/DTO/RoomMessageResponse.cs delete mode 100644 src/slskd/Application/Messaging/API/DTO/RoomResponse.cs delete mode 100644 src/slskd/Application/Messaging/API/DTO/UserDataResponse.cs delete mode 100644 src/slskd/Application/Messaging/ConversationTracker.cs delete mode 100644 src/slskd/Application/Messaging/Domain/PrivateMessage.cs delete mode 100644 src/slskd/Application/Messaging/Domain/Room.cs delete mode 100644 src/slskd/Application/Messaging/Domain/RoomMessage.cs delete mode 100644 src/slskd/Application/Messaging/IConversationTracker.cs delete mode 100644 src/slskd/Application/Messaging/IRoomTracker.cs delete mode 100644 src/slskd/Application/Messaging/RoomService.cs delete mode 100644 src/slskd/Application/Messaging/RoomTracker.cs delete mode 100644 src/slskd/Application/Search/API/Controllers/SearchesController.cs delete mode 100644 src/slskd/Application/Search/API/DTO/SearchRequest.cs delete mode 100644 src/slskd/Application/Search/Domain/File.cs delete mode 100644 src/slskd/Application/Search/Domain/Response.cs delete mode 100644 src/slskd/Application/Search/Domain/Search.cs delete mode 100644 src/slskd/Application/Search/Extensions.cs delete mode 100644 src/slskd/Application/Search/ISearchService.cs delete mode 100644 src/slskd/Application/Search/SearchDbContext.cs delete mode 100644 src/slskd/Application/Search/SearchResponseCache.cs delete mode 100644 src/slskd/Application/Search/SearchService.cs delete mode 100644 src/slskd/Application/Shares/SharedFileCache.cs delete mode 100644 src/slskd/Application/Transfers/API/Controllers/TransfersController.cs delete mode 100644 src/slskd/Application/Transfers/API/DTO/QueueDownloadRequest.cs delete mode 100644 src/slskd/Application/Transfers/API/DTO/Transfer.cs delete mode 100644 src/slskd/Application/Transfers/ITransferTracker.cs delete mode 100644 src/slskd/Application/Transfers/TransferTracker.cs delete mode 100644 src/slskd/Application/Users/API/Controllers/UsersController.cs delete mode 100644 src/slskd/Application/Users/API/DTO/UserDataResponse.cs delete mode 100644 src/slskd/Application/Users/BrowseTracker.cs delete mode 100644 src/slskd/Application/Users/Domain/Info.cs delete mode 100644 src/slskd/Application/Users/Domain/Status.cs delete mode 100644 src/slskd/Application/Users/IBrowseTracker.cs delete mode 100644 src/slskd/Application/Users/IUserService.cs delete mode 100644 src/slskd/Application/Users/UserDbContext.cs delete mode 100644 src/slskd/Application/Users/UserService.cs create mode 100644 src/slskd/Core/API/Controllers/ApplicationController.cs create mode 100644 src/slskd/Core/API/Controllers/ConfigurationController.cs create mode 100644 src/slskd/Core/API/Controllers/OptionsController.cs create mode 100644 src/slskd/Core/API/Controllers/ServerController.cs create mode 100644 src/slskd/Core/API/Controllers/SessionController.cs create mode 100644 src/slskd/Core/API/DTO/LoginRequest.cs create mode 100644 src/slskd/Core/API/DTO/ServerState.cs create mode 100644 src/slskd/Core/API/DTO/TokenResponse.cs create mode 100644 src/slskd/Core/API/Hubs/ApplicationHub.cs create mode 100644 src/slskd/Messaging/API/Controllers/ConversationsController.cs create mode 100644 src/slskd/Messaging/API/Controllers/PublicChatController.cs create mode 100644 src/slskd/Messaging/API/Controllers/RoomsController.cs create mode 100644 src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs create mode 100644 src/slskd/Messaging/API/DTO/RoomInfoResponse.cs create mode 100644 src/slskd/Messaging/API/DTO/RoomMessageResponse.cs create mode 100644 src/slskd/Messaging/API/DTO/RoomResponse.cs create mode 100644 src/slskd/Messaging/API/DTO/UserDataResponse.cs create mode 100644 src/slskd/Messaging/ConversationTracker.cs create mode 100644 src/slskd/Messaging/Domain/PrivateMessage.cs create mode 100644 src/slskd/Messaging/Domain/Room.cs create mode 100644 src/slskd/Messaging/Domain/RoomMessage.cs create mode 100644 src/slskd/Messaging/IConversationTracker.cs create mode 100644 src/slskd/Messaging/IRoomTracker.cs create mode 100644 src/slskd/Messaging/RoomService.cs create mode 100644 src/slskd/Messaging/RoomTracker.cs create mode 100644 src/slskd/Search/API/Controllers/SearchesController.cs create mode 100644 src/slskd/Search/API/DTO/SearchRequest.cs create mode 100644 src/slskd/Search/Domain/File.cs create mode 100644 src/slskd/Search/Domain/Response.cs create mode 100644 src/slskd/Search/Domain/Search.cs create mode 100644 src/slskd/Search/Extensions.cs create mode 100644 src/slskd/Search/ISearchService.cs create mode 100644 src/slskd/Search/SearchDbContext.cs create mode 100644 src/slskd/Search/SearchResponseCache.cs create mode 100644 src/slskd/Search/SearchService.cs create mode 100644 src/slskd/Shares/SharedFileCache.cs create mode 100644 src/slskd/Transfers/API/Controllers/TransfersController.cs create mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs create mode 100644 src/slskd/Transfers/API/DTO/Transfer.cs create mode 100644 src/slskd/Transfers/ITransferTracker.cs create mode 100644 src/slskd/Transfers/TransferTracker.cs create mode 100644 src/slskd/Users/API/Controllers/UsersController.cs create mode 100644 src/slskd/Users/API/DTO/UserDataResponse.cs create mode 100644 src/slskd/Users/BrowseTracker.cs create mode 100644 src/slskd/Users/Domain/Info.cs create mode 100644 src/slskd/Users/Domain/Status.cs create mode 100644 src/slskd/Users/IBrowseTracker.cs create mode 100644 src/slskd/Users/IUserService.cs create mode 100644 src/slskd/Users/UserDbContext.cs create mode 100644 src/slskd/Users/UserService.cs (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs new file mode 100644 index 00000000..0c95edeb --- /dev/null +++ b/src/slskd/Application.cs @@ -0,0 +1,759 @@ +// +// 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 +{ + 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.Core; + 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/Application.cs b/src/slskd/Application/Application.cs deleted file mode 100644 index 0c95edeb..00000000 --- a/src/slskd/Application/Application.cs +++ /dev/null @@ -1,759 +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 -{ - 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.Core; - 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/Core/API/Controllers/ApplicationController.cs b/src/slskd/Application/Core/API/Controllers/ApplicationController.cs deleted file mode 100644 index 16cd68b9..00000000 --- a/src/slskd/Application/Core/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.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 deleted file mode 100644 index 01c8bbc1..00000000 --- a/src/slskd/Application/Core/API/Controllers/ConfigurationController.cs +++ /dev/null @@ -1,73 +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.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 deleted file mode 100644 index fb2057b9..00000000 --- a/src/slskd/Application/Core/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.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 deleted file mode 100644 index 172333ec..00000000 --- a/src/slskd/Application/Core/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.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 deleted file mode 100644 index 5f20aa9f..00000000 --- a/src/slskd/Application/Core/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.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 deleted file mode 100644 index 0653847d..00000000 --- a/src/slskd/Application/Core/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.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 deleted file mode 100644 index 5dd16365..00000000 --- a/src/slskd/Application/Core/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.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 deleted file mode 100644 index 85992917..00000000 --- a/src/slskd/Application/Core/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.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 deleted file mode 100644 index be6c2fe7..00000000 --- a/src/slskd/Application/Core/API/Hubs/ApplicationHub.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.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/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Application/Messaging/API/Controllers/ConversationsController.cs deleted file mode 100644 index c4341ec1..00000000 --- a/src/slskd/Application/Messaging/API/Controllers/ConversationsController.cs +++ /dev/null @@ -1,219 +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.Messaging.API -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - - /// - /// Conversations. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class ConversationsController : ControllerBase - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// - public ConversationsController( - ISoulseekClient soulseekClient, - IStateMonitor applicationStateMonotor, - IConversationTracker tracker) - { - Client = soulseekClient; - ApplicationStateMonitor = applicationStateMonotor; - Tracker = tracker; - } - - private ISoulseekClient Client { get; } - private IStateMonitor ApplicationStateMonitor { get; } - private IConversationTracker Tracker { get; } - - /// - /// Acknowledges the given message id for the given username. - /// - /// - /// - /// - /// The request completed successfully. - /// - /// A conversation with the specified username, or a message matching the specified id could not be found. - /// - [HttpPut("{username}/{id}")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(404)] - public async Task Acknowledge([FromRoute]string username, [FromRoute]int id) - { - Tracker.Conversations.TryGetValue(username, out var conversation); - - if (conversation == default || !conversation.Any(p => p.Id == id)) - { - return NotFound(); - } - - await Client.AcknowledgePrivateMessageAsync(id); - return StatusCode(200); - } - - /// - /// Acknowledges all messages for the given username. - /// - /// - /// - /// The request completed successfully. - /// A conversation with the specified username could not be found. - [HttpPut("{username}")] - [Authorize] - [ProducesResponseType(200)] - [ProducesResponseType(404)] - public async Task AcknowledgeAll([FromRoute]string username) - { - Tracker.Conversations.TryGetValue(username, out var conversation); - - if (conversation == default) - { - return NotFound(); - } - - var tasks = new List(); - - foreach (var message in conversation.Where(p => !p.Acknowledged)) - { - tasks.Add(Task.Run(async () => - { - await Client.AcknowledgePrivateMessageAsync(message.Id); - message.Acknowledged = true; - })); - } - - await Task.WhenAll(tasks); - return StatusCode(200); - } - - /// - /// Deletes the conversation associated with the given username. - /// - /// - /// The request completed successfully. - /// A conversation with the specified username could not be found. - [HttpDelete("{username}")] - [Authorize] - [ProducesResponseType(404)] - [ProducesResponseType(204)] - public IActionResult Delete([FromRoute]string username) - { - var deleted = Tracker.Conversations.TryRemove(username, out _); - - if (deleted) - { - return StatusCode(204); - } - - return StatusCode(404); - } - - /// - /// Gets all tracked conversations. - /// - /// - /// The request completed successfully. - [HttpGet("")] - [Authorize] - [ProducesResponseType(typeof(Dictionary>), 200)] - public IActionResult GetAll() - { - var response = Tracker.Conversations.ToDictionary( - entry => entry.Key, - entry => entry.Value - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.Server.Username)) - .OrderBy(m => m.Timestamp)); - - return Ok(response); - } - - /// - /// Gets the conversation associated with the specified username. - /// - /// The username associated with the desired conversation. - /// - /// The request completed successfully. - /// A matching search was not found. - [HttpGet("{username}")] - [Authorize] - [ProducesResponseType(typeof(List), 200)] - [ProducesResponseType(404)] - public IActionResult GetByUsername([FromRoute]string username) - { - if (Tracker.TryGet(username, out var conversation)) - { - var response = conversation - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.Server.Username)) - .OrderBy(m => m.Timestamp); - - return Ok(response); - } - - return NotFound(); - } - - /// - /// Sends a private message to the specified username. - /// - /// - /// - /// - /// The request completed successfully. - /// The specified message is null or empty. - [HttpPost("{username}")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(400)] - public async Task Send([FromRoute]string username, [FromBody]string message) - { - if (string.IsNullOrEmpty(message)) - { - return BadRequest(); - } - - await Client.SendPrivateMessageAsync(username, message); - - // append the outgoing message to the tracker - Tracker.AddOrUpdate(username, new PrivateMessage() - { - Username = ApplicationStateMonitor.CurrentValue.Server.Username, - Timestamp = DateTime.UtcNow, - Message = message, - Acknowledged = true, - }); - - return StatusCode(201); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Messaging/API/Controllers/PublicChatController.cs b/src/slskd/Application/Messaging/API/Controllers/PublicChatController.cs deleted file mode 100644 index c30e08a8..00000000 --- a/src/slskd/Application/Messaging/API/Controllers/PublicChatController.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.Messaging.API -{ - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - - /// - /// Server. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class PublicChatController : ControllerBase - { - public PublicChatController(ISoulseekClient soulseekClient) - { - Client = soulseekClient; - } - - private ISoulseekClient Client { get; } - - /// - /// Starts public chat. - /// - /// - [HttpPost] - [Authorize] - public async Task Start() - { - await Client.StartPublicChatAsync(); - return StatusCode(StatusCodes.Status201Created); - } - - /// - /// Stops public chat. - /// - /// - [HttpDelete] - [Authorize] - public async Task Stop() - { - await Client.StopPublicChatAsync(); - return StatusCode(StatusCodes.Status204NoContent); - } - } -} diff --git a/src/slskd/Application/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Application/Messaging/API/Controllers/RoomsController.cs deleted file mode 100644 index 743df527..00000000 --- a/src/slskd/Application/Messaging/API/Controllers/RoomsController.cs +++ /dev/null @@ -1,309 +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.Messaging.API -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - - /// - /// Rooms. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class RoomsController : ControllerBase - { - public RoomsController( - ISoulseekClient soulseekClient, - IRoomService roomService, - IStateMonitor applicationStateMonitor, - IRoomTracker tracker) - { - Client = soulseekClient; - ApplicationStateMonitor = applicationStateMonitor; - Tracker = tracker; - RoomService = roomService; - } - - private IRoomService RoomService { get; } - private ISoulseekClient Client { get; } - private IStateMonitor ApplicationStateMonitor { get; } - private IRoomTracker Tracker { get; } - - /// - /// Gets all rooms. - /// - /// - /// The request completed successfully. - [HttpGet("joined")] - [Authorize] - [ProducesResponseType(typeof(Dictionary>), 200)] - public IActionResult GetAll() - { - return Ok(Tracker.Rooms.Keys); - } - - /// - /// Gets the specified room. - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpGet("joined/{roomName}")] - [Authorize] - [ProducesResponseType(typeof(Room), 200)] - [ProducesResponseType(404)] - public IActionResult GetByRoomName([FromRoute]string roomName) - { - if (Tracker.TryGet(roomName, out var room)) - { - return Ok(MapRoomToRoomResponse(room)); - } - - return NotFound(); - } - - /// - /// Sends a message to the specified room. - /// - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpPost("joined/{roomName}/messages")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task SendMessage([FromRoute]string roomName, [FromBody]string message) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.SendRoomMessageAsync(roomName, message); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// - /// Sets a ticker for the specified room. - /// - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpPost("joined/{roomName}/ticker")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task SetTicker([FromRoute] string roomName, [FromBody] string message) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.SetRoomTickerAsync(roomName, message); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// - /// Adds a member to a private room. - /// - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpPost("joined/{roomName}/members")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(404)] - public async Task AddRoomMember([FromRoute]string roomName, [FromBody]string username) - { - if (Tracker.TryGet(roomName, out var _)) - { - await Client.AddPrivateRoomMemberAsync(roomName, username); - return StatusCode(StatusCodes.Status201Created); - } - - return NotFound(); - } - - /// - /// Gets the current list of users for the specified room. - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpGet("joined/{roomName}/users")] - [Authorize] - [ProducesResponseType(typeof(IList), 200)] - [ProducesResponseType(404)] - public IActionResult GetUsersByRoomName([FromRoute]string roomName) - { - if (Tracker.TryGet(roomName, out var room)) - { - var response = room.Users - .Select(user => UserDataResponse.FromUserData(user, self: user.Username == ApplicationStateMonitor.CurrentValue.Server.Username)); - - return Ok(response); - } - - return NotFound(); - } - - /// - /// Gets the current list of messages for the specified room. - /// - /// - /// - /// The request completed successfully. - /// The specified roomName could not be found. - [HttpGet("joined/{roomName}/messages")] - [Authorize] - [ProducesResponseType(typeof(IList), 200)] - [ProducesResponseType(404)] - public IActionResult GetMessagesByRoomName([FromRoute]string roomName) - { - if (Tracker.TryGet(roomName, out var room)) - { - var response = room.Messages - .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == ApplicationStateMonitor.CurrentValue.Server.Username)); - - return Ok(response); - } - - return NotFound(); - } - - /// - /// Gets a list of rooms from the server. - /// - /// - [HttpGet("available")] - [Authorize] - [ProducesResponseType(typeof(List), 200)] - public async Task GetRooms() - { - var list = await Client.GetRoomListAsync(); - - var response = new List(); - - response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r))); - response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true))); - response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true))); - - foreach (var room in response) - { - room.IsModerated = list.ModeratedRoomNames.Contains(room.Name); - } - - return Ok(response); - } - - /// - /// Joins a room. - /// - /// - /// - /// The request completed successfully. - /// The room has already been joined. - [HttpPost("joined/{roomName}")] - [Authorize] - [ProducesResponseType(typeof(Room), 201)] - [ProducesResponseType(304)] - public async Task JoinRoom([FromRoute]string roomName) - { - if (Tracker.Rooms.ContainsKey(roomName)) - { - return StatusCode(StatusCodes.Status304NotModified); - } - - try - { - var roomData = await RoomService.JoinAsync(roomName); - var room = Room.FromRoomData(roomData); - Tracker.TryAdd(roomName, room); - - return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room)); - } - catch (Exception ex) - { - if (ex.InnerException is RoomJoinForbiddenException) - { - return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}"); - } - - throw; - } - } - - /// - /// Leaves a room. - /// - /// - /// - /// The request completed successfully. - /// The room has not been joined. - [HttpDelete("joined/{roomName}")] - [Authorize] - [ProducesResponseType(204)] - [ProducesResponseType(404)] - public async Task LeaveRoom([FromRoute]string roomName) - { - if (!Tracker.Rooms.ContainsKey(roomName)) - { - return StatusCode(StatusCodes.Status404NotFound); - } - - await RoomService.LeaveAsync(roomName); - Tracker.TryRemove(roomName); - - return StatusCode(StatusCodes.Status204NoContent); - } - - private RoomResponse MapRoomToRoomResponse(Room room) - { - bool IsSelf(string username) - { - return username == ApplicationStateMonitor.CurrentValue.Server.Username; - } - - var response = RoomResponse.FromRoom(room); - response.Users = room.Users - .Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username))); - response.Messages = room.Messages - .Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username))); - - return response; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Messaging/API/DTO/PrivateMessageResponse.cs b/src/slskd/Application/Messaging/API/DTO/PrivateMessageResponse.cs deleted file mode 100644 index a7e08d50..00000000 --- a/src/slskd/Application/Messaging/API/DTO/PrivateMessageResponse.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/. -// - -namespace slskd.Messaging.API -{ - using System; - using slskd.Messaging; - - public class PrivateMessageResponse - { - /// - /// A value indicating whether the message has been acknowledged. - /// - public bool Acknowledged { get; set; } = false; - - /// - /// The unique message id, used to acknowledge receipt. - /// - public int Id { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// A value indicating whether the message was replayed. - /// - public bool Replayed { get; set; } - - /// - /// The UTC timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - /// - /// A value indicating whether this message was sent by the currently logged in user. - /// - public bool? Self { get; set; } - - public static PrivateMessageResponse FromPrivateMessage(PrivateMessage privateMessage, bool self = false) - { - return new PrivateMessageResponse() - { - Id = privateMessage.Id, - Timestamp = privateMessage.Timestamp, - Username = privateMessage.Username, - Message = privateMessage.Message, - Acknowledged = privateMessage.Acknowledged, - Replayed = privateMessage.Replayed, - Self = self ? self : (bool?)null, - }; - } - } -} diff --git a/src/slskd/Application/Messaging/API/DTO/RoomInfoResponse.cs b/src/slskd/Application/Messaging/API/DTO/RoomInfoResponse.cs deleted file mode 100644 index 46edbdc8..00000000 --- a/src/slskd/Application/Messaging/API/DTO/RoomInfoResponse.cs +++ /dev/null @@ -1,60 +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.Messaging.API -{ - using Soulseek; - - public class RoomInfoResponse - { - /// - /// Gets the room name. - /// - public string Name { get; init; } - - /// - /// Gets the number of users in the room. - /// - public int UserCount { get; init; } - - /// - /// Gets a value indicating whether the room is private. - /// - public bool IsPrivate { get; init; } - - /// - /// Gets a value indicating whether the room is owned by the currently logged in user. - /// - public bool IsOwned { get; init; } - - /// - /// Gets a value indicating whether the room is moderated by the currently logged in user. - /// - public bool IsModerated { get; set; } - - public static RoomInfoResponse FromRoomInfo(RoomInfo info, bool isPrivate = false, bool isOwned = false) - { - return new RoomInfoResponse() - { - Name = info.Name, - UserCount = info.UserCount, - IsPrivate = isPrivate, - IsOwned = isOwned, - }; - } - } -} diff --git a/src/slskd/Application/Messaging/API/DTO/RoomMessageResponse.cs b/src/slskd/Application/Messaging/API/DTO/RoomMessageResponse.cs deleted file mode 100644 index 965c63a6..00000000 --- a/src/slskd/Application/Messaging/API/DTO/RoomMessageResponse.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Messaging.API -{ - using System; - using slskd.Messaging; - - public class RoomMessageResponse - { - /// - /// The timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// The room to which the message pertains. - /// - public string RoomName { get; set; } - - /// - /// A value indicating whether this user data belongs to the currently logged in user. - /// - public bool? Self { get; set; } - - public static RoomMessageResponse FromRoomMessage(RoomMessage roomMessage, bool self = false) - { - return new RoomMessageResponse() - { - Timestamp = roomMessage.Timestamp, - Username = roomMessage.Username, - Message = roomMessage.Message, - RoomName = roomMessage.RoomName, - Self = self ? self : (bool?)null, - }; - } - } -} diff --git a/src/slskd/Application/Messaging/API/DTO/RoomResponse.cs b/src/slskd/Application/Messaging/API/DTO/RoomResponse.cs deleted file mode 100644 index cf7e1478..00000000 --- a/src/slskd/Application/Messaging/API/DTO/RoomResponse.cs +++ /dev/null @@ -1,75 +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.Messaging.API -{ - using System.Collections.Generic; - using System.Linq; - using slskd.Messaging; - - public class RoomResponse - { - /// - /// The room name. - /// - public string Name { get; set; } - - /// - /// A value indicating whether the room is private. - /// - public bool IsPrivate { get; set; } - - /// - /// The number of operators in the room, if private. - /// - public int? OperatorCount { get; set; } - - /// - /// The operators in the room, if private. - /// - public IList Operators { get; set; } - - /// - /// The owner of the room, if private. - /// - public string Owner { get; set; } - - /// - /// The list of users in the room. - /// - public IEnumerable Users { get; set; } = new List(); - - /// - /// The list of messages. - /// - public IEnumerable Messages { get; set; } = new List(); - - public static RoomResponse FromRoom(Room room) - { - return new RoomResponse() - { - Name = room.Name, - IsPrivate = room.IsPrivate, - OperatorCount = room.OperatorCount, - Operators = room.Operators?.ToList(), - Owner = room.Owner, - Users = new List(), - Messages = new List(), - }; - } - } -} diff --git a/src/slskd/Application/Messaging/API/DTO/UserDataResponse.cs b/src/slskd/Application/Messaging/API/DTO/UserDataResponse.cs deleted file mode 100644 index 8f1e9544..00000000 --- a/src/slskd/Application/Messaging/API/DTO/UserDataResponse.cs +++ /dev/null @@ -1,85 +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.Messaging.API -{ - using Soulseek; - - public class UserDataResponse - { - /// - /// The average upload speed of the user. - /// - public int AverageSpeed { get; set; } - - /// - /// The user's country code, if provided. - /// - public string CountryCode { get; set; } - - /// - /// The number of directories shared by the user. - /// - public int DirectoryCount { get; set; } - - /// - /// The number of files shared by the user. - /// - public int FileCount { get; set; } - - /// - /// A value indicating whether this user data belongs to the currently logged in user. - /// - public bool? Self { get; set; } - - /// - /// The number of the user's free download slots, if provided. - /// - public int? SlotsFree { get; set; } - - /// - /// The status of the user (0 = offline, 1 = away, 2 = online). - /// - public UserPresence Status { get; set; } - - /// - /// The number of uploads tracked by the server for the user. - /// - public long UploadCount { get; set; } - - /// - /// The username of the user. - /// - public string Username { get; set; } - - public static UserDataResponse FromUserData(UserData userData, bool self = false) - { - return new UserDataResponse() - { - AverageSpeed = userData.AverageSpeed, - CountryCode = userData.CountryCode, - DirectoryCount = userData.DirectoryCount, - UploadCount = userData.UploadCount, - FileCount = userData.FileCount, - SlotsFree = userData.SlotsFree, - Status = userData.Status, - Username = userData.Username, - Self = self ? self : (bool?)null, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Messaging/ConversationTracker.cs b/src/slskd/Application/Messaging/ConversationTracker.cs deleted file mode 100644 index 27d678ca..00000000 --- a/src/slskd/Application/Messaging/ConversationTracker.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Messaging -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - - /// - /// Tracks private message conversations. - /// - public class ConversationTracker : IConversationTracker - { - /// - /// Tracked private message conversations. - /// - public ConcurrentDictionary> Conversations { get; } = new ConcurrentDictionary>(); - - /// - /// Adds a private message conversation and appends the specified , or just appends the - /// message if the conversation exists. - /// - /// - /// - public void AddOrUpdate(string username, PrivateMessage message) - { - Conversations.AddOrUpdate(username, new List() { message }, (_, messageList) => - { - messageList.Add(message); - return messageList; - }); - } - - /// - /// Returns the list of private messages for the specified , if any exist. - /// - /// - /// - /// - public bool TryGet(string username, out IList messages) => Conversations.TryGetValue(username, out messages); - - /// - /// Removes a tracked private message conversation for the specified user. - /// - /// - public void TryRemove(string username) => Conversations.TryRemove(username, out _); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Messaging/Domain/PrivateMessage.cs b/src/slskd/Application/Messaging/Domain/PrivateMessage.cs deleted file mode 100644 index 236632aa..00000000 --- a/src/slskd/Application/Messaging/Domain/PrivateMessage.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/. -// - -namespace slskd.Messaging -{ - using System; - using Soulseek; - - /// - /// A private message. - /// - public class PrivateMessage - { - /// - /// A value indicating whether the message has been acknowledged. - /// - public bool Acknowledged { get; set; } = false; - - /// - /// The unique message id, used to acknowledge receipt. - /// - public int Id { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// A value indicating whether the message was replayed. - /// - public bool Replayed { get; set; } - - /// - /// The UTC timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) - { - return new PrivateMessage() - { - Id = eventArgs.Id, - Timestamp = eventArgs.Timestamp, - Username = eventArgs.Username, - Message = eventArgs.Message, - Acknowledged = false, - Replayed = eventArgs.Replayed, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Messaging/Domain/Room.cs b/src/slskd/Application/Messaging/Domain/Room.cs deleted file mode 100644 index 459dea2c..00000000 --- a/src/slskd/Application/Messaging/Domain/Room.cs +++ /dev/null @@ -1,75 +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.Messaging -{ - using System.Collections.Generic; - using System.Linq; - using Soulseek; - - public class Room - { - /// - /// The room name. - /// - public string Name { get; set; } - - /// - /// A value indicating whether the room is private. - /// - public bool IsPrivate { get; set; } - - /// - /// The number of operators in the room, if private. - /// - public int? OperatorCount { get; set; } - - /// - /// The operators in the room, if private. - /// - public IList Operators { get; set; } - - /// - /// The owner of the room, if private. - /// - public string Owner { get; set; } - - /// - /// The list of users in the room. - /// - public IList Users { get; set; } = new List(); - - /// - /// The list of messages. - /// - public IList Messages { get; set; } = new List(); - - public static Room FromRoomData(RoomData roomData) - { - return new Room() - { - Name = roomData.Name, - IsPrivate = roomData.IsPrivate, - OperatorCount = roomData.OperatorCount, - Operators = roomData.Operators?.ToList(), - Owner = roomData.Owner, - Users = roomData.Users?.ToList(), - Messages = new List(), - }; - } - } -} diff --git a/src/slskd/Application/Messaging/Domain/RoomMessage.cs b/src/slskd/Application/Messaging/Domain/RoomMessage.cs deleted file mode 100644 index 7a06a192..00000000 --- a/src/slskd/Application/Messaging/Domain/RoomMessage.cs +++ /dev/null @@ -1,59 +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.Messaging -{ - using System; - using Soulseek; - - /// - /// A message sent to a room. - /// - public class RoomMessage - { - /// - /// The timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// The room to which the message pertains. - /// - public string RoomName { get; set; } - - public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) - { - return new RoomMessage() - { - Timestamp = timestamp ?? DateTime.UtcNow, - Username = eventArgs.Username, - Message = eventArgs.Message, - RoomName = eventArgs.RoomName, - }; - } - } -} diff --git a/src/slskd/Application/Messaging/IConversationTracker.cs b/src/slskd/Application/Messaging/IConversationTracker.cs deleted file mode 100644 index 8e7a90f4..00000000 --- a/src/slskd/Application/Messaging/IConversationTracker.cs +++ /dev/null @@ -1,55 +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.Messaging -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - - /// - /// Tracks private message conversations. - /// - public interface IConversationTracker - { - /// - /// Tracked private message conversations. - /// - ConcurrentDictionary> Conversations { get; } - - /// - /// Adds a private message conversation and appends the specified , or just appends the - /// message if the conversation exists. - /// - /// - /// - void AddOrUpdate(string username, PrivateMessage message); - - /// - /// Returns the list of private messages for the specified , if any exist. - /// - /// - /// - /// - bool TryGet(string username, out IList messages); - - /// - /// Removes a tracked private message conversation for the specified user. - /// - /// - void TryRemove(string username); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Messaging/IRoomTracker.cs b/src/slskd/Application/Messaging/IRoomTracker.cs deleted file mode 100644 index 225e5f69..00000000 --- a/src/slskd/Application/Messaging/IRoomTracker.cs +++ /dev/null @@ -1,75 +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.Messaging -{ - using System.Collections.Concurrent; - using Soulseek; - - /// - /// Tracks rooms. - /// - public interface IRoomTracker - { - /// - /// Gets tracked rooms. - /// - ConcurrentDictionary Rooms { get; } - - /// - /// Adds a room and appends the specified , or just appends the message if the room exists. - /// - /// - /// - void AddOrUpdateMessage(string roomName, RoomMessage message); - - /// - /// Adds the specified room to the tracker. - /// - /// - /// - void TryAdd(string roomName, Room room); - - /// - /// Adds the specified to the specified room. - /// - /// - /// - void TryAddUser(string roomName, UserData userData); - - /// - /// Returns the list of messages for the specified , if it is tracked. - /// - /// - /// - /// - bool TryGet(string roomName, out Room room); - - /// - /// Removes a tracked room. - /// - /// - void TryRemove(string roomName); - - /// - /// Removes the specified from the specified room. - /// - /// - /// - void TryRemoveUser(string roomName, string username); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Messaging/RoomService.cs b/src/slskd/Application/Messaging/RoomService.cs deleted file mode 100644 index 2b6d2489..00000000 --- a/src/slskd/Application/Messaging/RoomService.cs +++ /dev/null @@ -1,218 +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.Messaging -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Serilog; - using Soulseek; - - /// - /// Chat room management and event handling. - /// - public interface IRoomService - { - /// - /// Joins the specfied . - /// - /// The name of the room to join. - /// The operation context, including information about the room. - Task JoinAsync(string roomName); - - /// - /// Leaves the specified . - /// - /// The name of the room to leave. - /// The operation context. - Task LeaveAsync(string roomName); - - /// - /// Attempts to join the specified . - /// - /// - /// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions. - /// - /// The list of room names to join. - /// The operation context. - Task TryJoinAsync(params string[] roomNames); - } - - /// - /// Chat room management and event handling. - /// - public class RoomService : IRoomService - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// - /// - public RoomService( - ISoulseekClient soulseekClient, - IOptionsMonitor optionsMonitor, - IStateMutator stateMutator, - IRoomTracker roomTracker) - { - Client = soulseekClient; - - StateMutator = stateMutator; - OptionsMonitor = optionsMonitor; - - RoomTracker = roomTracker; - - Client.LoggedIn += Client_LoggedIn; - - Client.RoomJoined += Client_RoomJoined; - Client.RoomLeft += Client_RoomLeft; - Client.RoomMessageReceived += Client_RoomMessageReceived; - } - - private ISoulseekClient Client { get; } - private ILogger Logger { get; set; } = Log.ForContext(); - private IStateMutator StateMutator { get; } - private IOptionsMonitor OptionsMonitor { get; } - private IRoomTracker RoomTracker { get; set; } - - /// - /// Joins the specfied . - /// - /// The name of the room to join. - /// The operation context, including information about the room. - public async Task JoinAsync(string roomName) - { - Logger.Debug("Joining room {Room}", roomName); - - try - { - var data = await Client.JoinRoomAsync(roomName); - - Logger.Debug("Room data for {Room}: {Info}", roomName, data.ToJson()); - return data; - } - catch (Exception ex) - { - Logger.Warning("Failed to join room {Room}: {Message}", roomName, ex.Message); - throw; - } - } - - /// - /// Leaves the specified . - /// - /// The name of the room to leave. - /// The operation context. - public async Task LeaveAsync(string roomName) - { - Logger.Debug("Leaving room {Room}", roomName); - - try - { - await Client.LeaveRoomAsync(roomName); - } - catch (Exception ex) - { - Logger.Warning("Failed to leave room {Room}: {Message}", roomName, ex.Message); - throw; - } - } - - /// - /// Attempts to join the specified . - /// - /// - /// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions. - /// - /// The list of room names to join. - /// The operation context. - public async Task TryJoinAsync(params string[] roomNames) - { - var tasks = new List(); - - foreach (var room in roomNames) - { - tasks.Add(JoinAsync(room)); - } - - try - { - await Task.WhenAll(tasks); - } - catch (Exception ex) - { - Logger.Debug(ex, "Caught Exception in JoinAsync"); - } - } - - private async void Client_LoggedIn(object sender, EventArgs e) - { - var autoJoinRooms = OptionsMonitor.CurrentValue.Rooms; - - if (autoJoinRooms.Any()) - { - Logger.Information("Auto-joining room(s) {Rooms}", string.Join(", ", autoJoinRooms)); - await TryJoinAsync(autoJoinRooms); - } - - var previouslyJoinedRooms = RoomTracker.Rooms.Keys.Except(autoJoinRooms); - - if (previouslyJoinedRooms.Any()) - { - Logger.Information("Attempting to rejoin room(s) {Rooms}", string.Join(", ", previouslyJoinedRooms)); - await TryJoinAsync(previouslyJoinedRooms.ToArray()); - } - } - - private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) - { - if (args.Username == Client.Username) - { - Logger.Information("Joined room {Room}", args.RoomName); - StateMutator.SetValue(state => state with { Rooms = state.Rooms.Concat(new[] { args.RoomName }).Distinct().ToArray() }); - } - else - { - RoomTracker.TryAddUser(args.RoomName, args.UserData); - } - } - - private void Client_RoomLeft(object sender, RoomLeftEventArgs args) - { - if (args.Username == Client.Username) - { - Logger.Information("Left room {Room}", args.RoomName); - StateMutator.SetValue(state => state with { Rooms = state.Rooms.Where(room => room != args.RoomName).ToArray() }); - } - else - { - RoomTracker.TryRemoveUser(args.RoomName, args.Username); - } - } - - private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) - { - var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); - RoomTracker.AddOrUpdateMessage(args.RoomName, message); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Messaging/RoomTracker.cs b/src/slskd/Application/Messaging/RoomTracker.cs deleted file mode 100644 index c586f401..00000000 --- a/src/slskd/Application/Messaging/RoomTracker.cs +++ /dev/null @@ -1,112 +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.Messaging -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using Soulseek; - - /// - /// Tracks rooms. - /// - public class RoomTracker : IRoomTracker - { - /// - /// Initializes a new instance of the class. - /// - /// - public RoomTracker(int messageLimit = 25) - { - MessageLimit = messageLimit; - } - - /// - /// Tracked rooms. - /// - public ConcurrentDictionary Rooms { get; } = new ConcurrentDictionary(); - - private int MessageLimit { get; } - - /// - /// Adds a room and appends the specified , or just appends the message if the room exists. - /// - /// - /// - public void AddOrUpdateMessage(string roomName, RoomMessage message) - { - Rooms.AddOrUpdate(roomName, new Room() { Messages = new List() { message } }, (_, room) => - { - if (room.Messages.Count >= MessageLimit) - { - room.Messages = room.Messages.TakeLast(MessageLimit - 1).ToList(); - } - - room.Messages.Add(message); - return room; - }); - } - - /// - /// Adds the specified room to the tracker. - /// - /// - /// - public void TryAdd(string roomName, Room room) => Rooms.TryAdd(roomName, room); - - /// - /// Adds the specified to the specified room. - /// - /// - /// - public void TryAddUser(string roomName, UserData userData) - { - if (Rooms.TryGetValue(roomName, out var room)) - { - room.Users.Add(userData); - } - } - - /// - /// Removes a tracked room. - /// - /// - /// - /// - public bool TryGet(string roomName, out Room room) => Rooms.TryGetValue(roomName, out room); - - /// - /// Returns the list of messages for the specified , if it is tracked. - /// - /// - public void TryRemove(string roomName) => Rooms.TryRemove(roomName, out _); - - /// - /// Removes the specified from the specified room. - /// - /// - /// - public void TryRemoveUser(string roomName, string username) - { - if (Rooms.TryGetValue(roomName, out var room)) - { - room.Users = room.Users.Where(u => u.Username != username).ToList(); - } - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Search/API/Controllers/SearchesController.cs b/src/slskd/Application/Search/API/Controllers/SearchesController.cs deleted file mode 100644 index 5f740044..00000000 --- a/src/slskd/Application/Search/API/Controllers/SearchesController.cs +++ /dev/null @@ -1,135 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Search.API -{ - using System; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using SearchQuery = Soulseek.SearchQuery; - using SearchScope = Soulseek.SearchScope; - - /// - /// Search. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class SearchesController : ControllerBase - { - /// - /// Initializes a new instance of the class. - /// - /// - public SearchesController(ISearchService searchService) - { - Searches = searchService; - } - - private ISearchService Searches { get; } - - /// - /// Performs a search for the specified . - /// - /// The search request. - /// - /// The search completed successfully. - /// The specified was malformed. - /// The search terminated abnormally. - [HttpPost("")] - [Authorize] - public async Task Post([FromBody]SearchRequest request) - { - var id = request.Id ?? Guid.NewGuid(); - var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1)); - - Search search = null; - - try - { - search = await Searches.CreateAsync(id, SearchQuery.FromText(searchText), SearchScope.Network); - return Ok(search.Responses); - } - catch (Exception ex) - { - return StatusCode(500, $"Search terminated abnormally: {ex.Message}"); - } - finally - { - search = null; - } - } - - /// - /// Gets the state of the search corresponding to the specified . - /// - /// The unique id of the search. - /// A value indicating whether to include search responses in the response. - /// - /// The request completed successfully. - /// A matching search was not found. - [HttpGet("{id}")] - [Authorize] - public async Task GetById([FromRoute]Guid id, [FromQuery]bool includeResponses = false) - { - var search = await Searches.FindAsync(search => search.Id == id, includeResponses); - - if (search == default) - { - return NotFound(); - } - - return Ok(search); - } - - /// - /// Gets the state of the search corresponding to the specified . - /// - /// The unique id of the search. - /// - /// The request completed successfully. - /// A matching search was not found. - [HttpGet("{id}/responses")] - [Authorize] - public async Task GetResponsesById([FromRoute] Guid id) - { - var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); - - if (search == default) - { - return NotFound(); - } - - return Ok(search.Responses); - } - - /// - /// Gets the list of active and completed searches. - /// - /// - [HttpGet("")] - [Authorize] - public async Task GetAll() - { - return Ok(await Searches.ListAsync()); - } - } -} diff --git a/src/slskd/Application/Search/API/DTO/SearchRequest.cs b/src/slskd/Application/Search/API/DTO/SearchRequest.cs deleted file mode 100644 index aad5a200..00000000 --- a/src/slskd/Application/Search/API/DTO/SearchRequest.cs +++ /dev/null @@ -1,116 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Search.API -{ - using System; - using Soulseek; - - /// - /// A search request. - /// - public class SearchRequest - { - /// - /// Gets or sets the unique search identifier. - /// - public Guid? Id { get; set; } - - /// - /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000). - /// - public int? FileLimit { get; set; } - - /// - /// Gets or sets a value indicating whether responses are to be filtered. (Default = true). - /// - public bool? FilterResponses { get; set; } - - /// - /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000). - /// - public int? MaximumPeerQueueLength { get; set; } - - /// - /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. - /// (Default = 0). - /// - public int? MinimumPeerFreeUploadSlots { get; set; } - - /// - /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). - /// - public int? MinimumPeerUploadSpeed { get; set; } - - /// - /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1). - /// - public int? MinimumResponseFileCount { get; set; } - - /// - /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100). - /// - public int? ResponseLimit { get; set; } - - /// - /// Gets or sets the search text. - /// - public string SearchText { get; set; } - - /// - /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15). - /// - /// The timeout duration is from the time of the last response. - public int? SearchTimeout { get; set; } - - /// - /// Gets or sets the search token. - /// - public int? Token { get; set; } - - /// - /// Maps to a new instance of . - /// - /// - /// - /// - /// - /// - public SearchOptions ToSearchOptions( - Func responseFilter = null, - Func fileFilter = null, - Action stateChanged = null, - Action responseReceived = null) - { - var def = new SearchOptions(); - - return new SearchOptions( - searchTimeout: SearchTimeout ?? def.SearchTimeout, - responseLimit: ResponseLimit ?? def.ResponseLimit, - fileLimit: FileLimit ?? def.FileLimit, - filterResponses: FilterResponses ?? def.FilterResponses, - minimumResponseFileCount: MinimumResponseFileCount ?? def.MinimumResponseFileCount, - minimumPeerFreeUploadSlots: MinimumPeerFreeUploadSlots ?? def.MinimumPeerFreeUploadSlots, - maximumPeerQueueLength: MaximumPeerQueueLength ?? def.MaximumPeerQueueLength, - minimumPeerUploadSpeed: MinimumPeerUploadSpeed ?? def.MinimumPeerUploadSpeed, - responseFilter: responseFilter, - fileFilter: fileFilter, - responseReceived: responseReceived, - stateChanged: stateChanged); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Search/Domain/File.cs b/src/slskd/Application/Search/Domain/File.cs deleted file mode 100644 index 0a86eec3..00000000 --- a/src/slskd/Application/Search/Domain/File.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.Search -{ - using SoulseekFile = Soulseek.File; - - public class File - { - public int? BitDepth { get; init; } - public int? BitRate { get; init; } - public int Code { get; init; } - public string Extension { get; init; } - public string Filename { get; init; } - public bool? IsVariableBitRate { get; init; } - public int? Length { get; init; } - public int? SampleRate { get; init; } - public long Size { get; init; } - public bool IsLocked { get; init; } - - public static File FromSoulseekFile(SoulseekFile file) - { - return new File() - { - BitDepth = file.BitDepth, - BitRate = file.BitRate, - Code = file.Code, - Extension = file.Extension, - Filename = file.Filename, - IsVariableBitRate = file.IsVariableBitRate, - Length = file.Length, - SampleRate = file.SampleRate, - Size = file.Size, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Search/Domain/Response.cs b/src/slskd/Application/Search/Domain/Response.cs deleted file mode 100644 index ea2e8993..00000000 --- a/src/slskd/Application/Search/Domain/Response.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.Search -{ - using System.Collections.Generic; - using System.Linq; - - public class Response - { - public int FileCount { get; init; } - public ICollection Files { get; init; } = new List(); - public int FreeUploadSlots { get; init; } - public int LockedFileCount { get; init; } - public ICollection LockedFiles { get; init; } = new List(); - public long QueueLength { get; init; } - public int Token { get; init; } - public int UploadSpeed { get; init; } - public string Username { get; init; } - - public static Response FromSoulseekSearchResponse(Soulseek.SearchResponse searchResponse) - { - return new Response() - { - FileCount = searchResponse.FileCount, - Files = searchResponse.Files.Select(file => File.FromSoulseekFile(file)).ToList(), - FreeUploadSlots = searchResponse.FreeUploadSlots, - LockedFileCount = searchResponse.LockedFileCount, - LockedFiles = searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file)).ToList(), - QueueLength = searchResponse.QueueLength, - Token = searchResponse.Token, - UploadSpeed = searchResponse.UploadSpeed, - Username = searchResponse.Username, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Search/Domain/Search.cs b/src/slskd/Application/Search/Domain/Search.cs deleted file mode 100644 index b93c62cb..00000000 --- a/src/slskd/Application/Search/Domain/Search.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Search -{ - using System; - using System.Collections.Generic; - using System.ComponentModel.DataAnnotations; - using System.ComponentModel.DataAnnotations.Schema; - using System.Text.Json; - using System.Text.Json.Serialization; - using Soulseek; - - public class Search - { - public DateTime? EndedAt { get; set; } - public int FileCount { get; set; } - - [Key] - public Guid Id { get; init; } - - [NotMapped] - public bool IsComplete => State.HasFlag(SearchStates.Completed); - - public int LockedFileCount { get; set; } - public int ResponseCount { get; set; } - - [NotMapped] - public IEnumerable Responses { get; set; } = new List(); - - [JsonIgnore] - public string ResponsesJson - { - get => JsonSerializer.Serialize(Responses); - set - { - Responses = JsonSerializer.Deserialize>(value); - } - } - - public string SearchText { get; init; } - public DateTime StartedAt { get; init; } = DateTime.UtcNow; - public SearchStates State { get; set; } - public int Token { get; init; } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Search/Extensions.cs b/src/slskd/Application/Search/Extensions.cs deleted file mode 100644 index 149e0a14..00000000 --- a/src/slskd/Application/Search/Extensions.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Search -{ - using System; - using System.Linq; - using Soulseek; - - public static class Extensions - { - /// - /// Returns a copy of the specified with the specified actions bound, while retaining the existing actions. - /// - /// - /// - /// - /// - public static SearchOptions WithActions( - this SearchOptions options, - Action stateChanged = null, - Action responseReceived = null) - { - stateChanged ??= (args) => { }; - responseReceived ??= (args) => { }; - - return new SearchOptions( - options.SearchTimeout, - options.ResponseLimit, - options.FilterResponses, - options.MinimumResponseFileCount, - options.MinimumPeerFreeUploadSlots, - options.MaximumPeerQueueLength, - options.MinimumPeerUploadSpeed, - options.FileLimit, - options.RemoveSingleCharacterSearchTerms, - options.ResponseFilter, - options.FileFilter, - stateChanged: (args) => - { - if (options.StateChanged != null) - { - options.StateChanged(args); - } - - stateChanged(args); - }, - responseReceived: (args) => - { - if (options.ResponseReceived != null) - { - options.ResponseReceived(args); - } - - responseReceived(args); - }); - } - - /// - /// Returns a copy of the specified with the specified filter delegates overridden. - /// - /// - /// - /// - /// - public static SearchOptions WithFilters( - this SearchOptions options, - Func responseFilter = null, - Func fileFilter = null) - { - return new SearchOptions( - options.SearchTimeout, - options.ResponseLimit, - filterResponses: options.FilterResponses || responseFilter != null || fileFilter != null, - options.MinimumResponseFileCount, - options.MinimumPeerFreeUploadSlots, - options.MaximumPeerQueueLength, - options.MinimumPeerUploadSpeed, - options.FileLimit, - options.RemoveSingleCharacterSearchTerms, - responseFilter, - fileFilter, - options.StateChanged, - options.ResponseReceived); - } - - /// - /// Creates a projection over the specified which omits responses. - /// - /// - /// - public static IQueryable WithoutResponses(this IQueryable query) - { - return query.Select(s => new Search() - { - Id = s.Id, - StartedAt = s.StartedAt, - EndedAt = s.EndedAt, - FileCount = s.FileCount, - LockedFileCount = s.LockedFileCount, - ResponseCount = s.ResponseCount, - SearchText = s.SearchText, - State = s.State, - Token = s.Token, - }); - } - } -} diff --git a/src/slskd/Application/Search/ISearchService.cs b/src/slskd/Application/Search/ISearchService.cs deleted file mode 100644 index d696617d..00000000 --- a/src/slskd/Application/Search/ISearchService.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Search -{ - using System; - using System.Collections.Generic; - using System.Linq.Expressions; - using System.Threading.Tasks; - using SearchOptions = Soulseek.SearchOptions; - using SearchQuery = Soulseek.SearchQuery; - using SearchScope = Soulseek.SearchScope; - - /// - /// Handles the lifecycle and persistence of searches. - /// - public interface ISearchService - { - /// - /// Performs a search for the specified and . - /// - /// A unique identifier for the search. - /// The search query. - /// The search scope. - /// Search options. - /// The completed search. - Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); - - /// - /// Finds a single search matching the specified . - /// - /// The expression to use to match searches. - /// A value indicating whether to include search responses in the result. - /// The found search, or default if not found. - /// Thrown an expression is not supplied. - Task FindAsync(Expression> expression, bool includeResponses = false); - - /// - /// Returns a list of all completed and in-progress searches, with responses omitted. - /// - /// An optional expression used to match searches. - /// The list of searches matching the specified expression. - Task> ListAsync(Expression> expression = null); - - /// - /// Cancels the search matching the specified , if it is in progress. - /// - /// The unique identifier for the search. - /// A value indicating whether the search was sucessfully cancelled. - bool TryCancel(Guid id); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Search/SearchDbContext.cs b/src/slskd/Application/Search/SearchDbContext.cs deleted file mode 100644 index efb2fdd6..00000000 --- a/src/slskd/Application/Search/SearchDbContext.cs +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Search -{ - using Microsoft.EntityFrameworkCore; - - public class SearchDbContext : DbContext - { - public SearchDbContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } - - public DbSet Searches { get; set; } - } -} diff --git a/src/slskd/Application/Search/SearchResponseCache.cs b/src/slskd/Application/Search/SearchResponseCache.cs deleted file mode 100644 index c31a3a9b..00000000 --- a/src/slskd/Application/Search/SearchResponseCache.cs +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Search -{ - using System; - using Microsoft.Extensions.Caching.Memory; - using Soulseek; - - /// - /// Caches undelivered search responses. - /// - public class SearchResponseCache : ISearchResponseCache - { - /// - /// Initializes a new instance of the class. - /// - public SearchResponseCache() - { - Cache = new MemoryCache(new MemoryCacheOptions()); - } - - private IMemoryCache Cache { get; } - - /// - /// Caches or updates a response. - /// - /// The token for which the response is to be added or updated. - /// The response and context to cache. - public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) - { - Cache.Set(responseToken, response, TimeSpan.FromMinutes(3)); - } - - /// - /// Attempts to fetch a cached response and context for the specified . - /// - /// The token for the cached response. - /// The cached response and context, if present. - /// A value indicating whether a response for the specified responseToken is cached. - public bool TryGet(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) - { - return Cache.TryGetValue(responseToken, out response); - } - - /// - /// Attempts to remove a cached Soulseek.SearchResponse and context for the specified . - /// - /// The token for the cached response. - /// The cached response and context, if present. - /// A value indicating whether a response for the specified responseToken was removed. - public bool TryRemove(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) - { - if (Cache.TryGetValue(responseToken, out response)) - { - Cache.Remove(responseToken); - return true; - } - - return false; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Search/SearchService.cs b/src/slskd/Application/Search/SearchService.cs deleted file mode 100644 index e529f738..00000000 --- a/src/slskd/Application/Search/SearchService.cs +++ /dev/null @@ -1,210 +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.Search -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Linq.Expressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; - using Soulseek; - using SearchOptions = Soulseek.SearchOptions; - using SearchQuery = Soulseek.SearchQuery; - using SearchScope = Soulseek.SearchScope; - using SearchStates = Soulseek.SearchStates; - using SoulseekSearch = Soulseek.Search; - - /// - /// Handles the lifecycle and persistence of searches. - /// - public class SearchService : ISearchService - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// The database context to use. - /// The logger. - public SearchService( - IOptionsMonitor optionsMonitor, - ISoulseekClient soulseekClient, - IDbContextFactory contextFactory, - ILogger log) - { - OptionsMonitor = optionsMonitor; - Client = soulseekClient; - ContextFactory = contextFactory; - Log = log; - } - - private ConcurrentDictionary CancellationTokens { get; } - = new ConcurrentDictionary(); - - private IOptionsMonitor OptionsMonitor { get; } - private ISoulseekClient Client { get; } - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; set; } - - /// - /// Performs a search for the specified and . - /// - /// A unique identifier for the search. - /// The search query. - /// The search scope. - /// Search options. - /// The completed search. - public async Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null) - { - var token = Client.GetNextToken(); - var cancellationTokenSource = new CancellationTokenSource(); - - var search = new Search() - { - SearchText = query.SearchText, - Token = token, - Id = id, - State = SearchStates.Requested, - StartedAt = DateTime.UtcNow, - }; - - options ??= new SearchOptions(); - options = options.WithActions( - stateChanged: (args) => UpdateSearchState(search, args.Search), - responseReceived: (args) => UpdateSearchState(search, args.Search)); - - try - { - using var context = ContextFactory.CreateDbContext(); - - context.Add(search); - await context.SaveChangesAsync(); - - CancellationTokens.TryAdd(id, cancellationTokenSource); - var responses = new List(); - - var soulseekSearch = await Client.SearchAsync( - query, - responseReceived: (response) => - { - responses.Add(Response.FromSoulseekSearchResponse(response)); - }, - scope, - token, - options, - cancellationToken: cancellationTokenSource.Token); - - CancellationTokens.TryRemove(id, out _); - - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - search.EndedAt = DateTime.UtcNow; - search.Responses = responses; - SaveSearchState(search); - - return search; - } - finally - { - CancellationTokens.TryRemove(id, out _); - } - } - - /// - /// Finds a single search matching the specified . - /// - /// The expression to use to match searches. - /// A value indicating whether to include search responses in the result. - /// The found search, or default if not found. - /// Thrown an expression is not supplied. - public Task FindAsync(Expression> expression, bool includeResponses = false) - { - if (expression == default) - { - throw new ArgumentException("An expression must be supplied.", nameof(expression)); - } - - using var context = ContextFactory.CreateDbContext(); - - var selector = context.Searches.Where(expression); - - if (!includeResponses) - { - selector = selector.WithoutResponses(); - } - - return selector.FirstOrDefaultAsync(); - } - - /// - /// Returns a list of all completed and in-progress searches, with responses omitted. - /// - /// An optional expression used to match searches. - /// The list of searches matching the specified expression. - public Task> ListAsync(Expression> expression = null) - { - expression ??= s => true; - using var context = ContextFactory.CreateDbContext(); - return context.Searches.Where(expression).WithoutResponses().ToListAsync(); - } - - /// - /// Cancels the search matching the specified , if it is in progress. - /// - /// The unique identifier for the search. - /// A value indicating whether the search was sucessfully cancelled. - public bool TryCancel(Guid id) - { - if (CancellationTokens.TryGetValue(id, out var cts)) - { - cts.Cancel(); - return true; - } - - return false; - } - - private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) - { - if (CancellationTokens.ContainsKey(search.Id)) - { - search.FileCount = soulseekSearch.FileCount; - search.LockedFileCount = soulseekSearch.LockedFileCount; - search.ResponseCount = soulseekSearch.ResponseCount; - search.State = soulseekSearch.State; - - SaveSearchState(search); - } - } - - private void SaveSearchState(Search search) - { - var context = ContextFactory.CreateDbContext(); - context.Update(search); - context.SaveChanges(); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharedFileCache.cs b/src/slskd/Application/Shares/SharedFileCache.cs deleted file mode 100644 index 79e9d5a5..00000000 --- a/src/slskd/Application/Shares/SharedFileCache.cs +++ /dev/null @@ -1,473 +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.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; - } - - var parent = System.IO.Directory.GetParent(LocalPath).FullName.TrimEnd('/', '\\'); - - Mask = Compute.MaskHash(parent); - - var maskedPath = LocalPath.ReplaceFirst(parent, Mask); - - var aliasedSegment = LocalPath[(parent.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/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfers/API/Controllers/TransfersController.cs deleted file mode 100644 index b912bbda..00000000 --- a/src/slskd/Application/Transfers/API/Controllers/TransfersController.cs +++ /dev/null @@ -1,331 +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.Transfers.API -{ - using System; - using System.ComponentModel.DataAnnotations; - using System.IO; - using System.Linq; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using slskd.Integrations.FTP; - using Soulseek; - - /// - /// Transfers. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class TransfersController : ControllerBase - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// - /// - public TransfersController( - IOptionsSnapshot options, - ISoulseekClient soulseekClient, - ITransferTracker tracker, - IFTPService ftpClient) - { - Client = soulseekClient; - Tracker = tracker; - Options = options.Value; - FTP = ftpClient; - } - - private Options Options { get; } - private ISoulseekClient Client { get; } - private ITransferTracker Tracker { get; } - private IFTPService FTP { get; } - - /// - /// Cancels the specified download. - /// - /// The username of the download source. - /// The id of the download. - /// A value indicating whether the tracked download should be removed after cancellation. - /// - /// The download was cancelled successfully. - /// The specified download was not found. - [HttpDelete("downloads/{username}/{id}")] - [Authorize] - [ProducesResponseType(204)] - [ProducesResponseType(404)] - public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) - { - return CancelTransfer(TransferDirection.Download, username, id, remove); - } - - /// - /// Cancels the specified upload. - /// - /// The username of the upload destination. - /// The id of the upload. - /// A value indicating whether the tracked upload should be removed after cancellation. - /// - /// The upload was cancelled successfully. - /// The specified upload was not found. - [HttpDelete("uploads/{username}/{id}")] - [Authorize] - [ProducesResponseType(204)] - [ProducesResponseType(404)] - public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) - { - return CancelTransfer(TransferDirection.Upload, username, id, remove); - } - - /// - /// Enqueues the specified download. - /// - /// The username of the download source. - /// The download request. - /// - /// The download was successfully enqueued. - /// The download was rejected. - /// An unexpected error was encountered. - [HttpPost("downloads/{username}")] - [Authorize] - [ProducesResponseType(201)] - [ProducesResponseType(typeof(string), 403)] - [ProducesResponseType(typeof(string), 500)] - public async Task Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request) - { - try - { - var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var stream = GetLocalFileStream(request.Filename, Options.Directories.Incomplete); - - var cts = new CancellationTokenSource(); - - var downloadTask = Task.Run(async () => - { - await Client.DownloadAsync(username, request.Filename, stream, request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => - { - Tracker.AddOrUpdate(e, cts); - - if (e.Transfer.State == TransferStates.Queued || e.Transfer.State == TransferStates.Initializing) - { - waitUntilEnqueue.TrySetResult(true); - } - }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token); - - MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); - - if (Options.Integration.FTP.Enabled) - { - _ = FTP.UploadAsync(request.Filename.ToLocalFilename(Options.Directories.Downloads)); - } - }); - - // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the - // downloadTask throws due to an error prior to successfully queueing. - var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); - - if (task == downloadTask) - { - if (downloadTask.Exception is AggregateException) - { - var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); - if (rejected.Any()) - { - return StatusCode(403, rejected.First().Message); - } - } - - return StatusCode(500, downloadTask.Exception.Message); - } - - // if it didn't throw, just return ok. the download will continue waiting in the background. - return StatusCode(201); - } - catch (Exception ex) - { - return StatusCode(500, ex.Message); - } - } - - /// - /// Gets all downloads. - /// - /// - /// The request completed successfully. - [HttpGet("downloads")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetDownloads() - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .ToMap()); - } - - /// - /// Gets all downloads for the specified username. - /// - /// - /// - /// The request completed successfully. - [HttpGet("downloads/{username}")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetDownloads([FromRoute, Required]string username) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .FromUser(username) - .ToMap()); - } - - /// - /// Gets the downlaod for the specified username matching the specified filename, and requests - /// the current place in the remote queue of the specified download. - /// - /// The username of the download source. - /// The id of the download. - /// - /// The request completed successfully. - /// The specified download was not found. - [HttpGet("downloads/{username}/{id}")] - [Authorize] - [ProducesResponseType(typeof(API.Transfer), 200)] - [ProducesResponseType(404)] - public async Task GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) - { - var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id); - - if (record == default) - { - return NotFound(); - } - - record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename); - return Ok(record.Transfer); - } - - /// - /// Gets all uploads. - /// - /// - /// The request completed successfully. - [HttpGet("uploads")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetUploads() - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .ToMap()); - } - - /// - /// Gets all uploads for the specified username. - /// - /// - /// - /// The request completed successfully. - [HttpGet("uploads/{username}")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .ToMap()); - } - - /// - /// Gets the upload for the specified username matching the specified filename. - /// - /// The username of the upload destination. - /// The id of the upload. - /// - /// The request completed successfully. - [HttpGet("uploads/{username}/{id}")] - [Authorize] - [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .WithId(id).Transfer); - } - - private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) - { - var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); - var path = Path.GetDirectoryName(localFilename); - - if (!System.IO.Directory.Exists(path)) - { - System.IO.Directory.CreateDirectory(path); - } - - return new FileStream(localFilename, FileMode.Create); - } - - private static void MoveFile(string filename, string sourceDirectory, string destinationDirectory) - { - var sourceFilename = filename.ToLocalFilename(sourceDirectory); - var destinationFilename = filename.ToLocalFilename(destinationDirectory); - - var destinationPath = Path.GetDirectoryName(destinationFilename); - - if (!System.IO.Directory.Exists(destinationPath)) - { - System.IO.Directory.CreateDirectory(destinationPath); - } - - System.IO.File.Move(sourceFilename, destinationFilename, overwrite: true); - - if (!System.IO.Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) - { - System.IO.Directory.Delete(Path.GetDirectoryName(sourceFilename)); - } - } - - private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false) - { - if (Tracker.TryGet(direction, username, id, out var transfer)) - { - transfer.CancellationTokenSource.Cancel(); - - if (remove) - { - Tracker.TryRemove(direction, username, id); - } - - return NoContent(); - } - - return NotFound(); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Transfers/API/DTO/QueueDownloadRequest.cs b/src/slskd/Application/Transfers/API/DTO/QueueDownloadRequest.cs deleted file mode 100644 index 5e8807c2..00000000 --- a/src/slskd/Application/Transfers/API/DTO/QueueDownloadRequest.cs +++ /dev/null @@ -1,37 +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.Transfers.API -{ - public class QueueDownloadRequest - { - /// - /// Gets or sets the filename to download. - /// - public string Filename { get; set; } - - /// - /// Gets or sets the size of the file. - /// - public long? Size { get; set; } - - /// - /// Gets or sets the optional transfer token. - /// - public int? Token { get; set; } - } -} diff --git a/src/slskd/Application/Transfers/API/DTO/Transfer.cs b/src/slskd/Application/Transfers/API/DTO/Transfer.cs deleted file mode 100644 index 8465fd1d..00000000 --- a/src/slskd/Application/Transfers/API/DTO/Transfer.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/. -// - -namespace slskd.Transfers.API -{ - using System; - using System.Net; - using Soulseek; - - /// - /// A single file transfer. - /// - public class Transfer - { - /// - /// Gets the current average transfer speed. - /// - public double AverageSpeed { get; set; } - - /// - /// Gets the number of remaining bytes to be transferred. - /// - public long BytesRemaining { get; set; } - - /// - /// Gets the total number of bytes transferred. - /// - public long BytesTransferred { get; set; } - - /// - /// Gets the transfer direction. - /// - public TransferDirection Direction { get; set; } - - /// - /// Gets the current duration of the transfer, if it has been started. - /// - public double? ElapsedTime { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? EndTime { get; set; } - - /// - /// Gets the filename of the file to be transferred. - /// - public string Filename { get; set; } - - /// - /// Gets the transfer id. - /// - public string Id => Compute.Sha1Hash(Filename); - - /// - /// Gets the ip endpoint of the remote transfer connection, if one has been established. - /// - public IPEndPoint IPEndPoint { get; set; } - - /// - /// Gets the current progress in percent. - /// - public double PercentComplete { get; set; } - - /// - /// Gets the current place in queue, if it has been fetched. - /// - public int? PlaceInQueue { get; set; } - - /// - /// Gets the projected remaining duration of the transfer. - /// - public double? RemainingTime { get; set; } - - /// - /// Gets the remote unique token for the transfer. - /// - public int? RemoteToken { get; set; } - - /// - /// Gets the size of the file to be transferred, in bytes. - /// - public long Size { get; set; } - - /// - /// Gets the starting offset of the transfer, in bytes. - /// - public long StartOffset { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? StartTime { get; set; } - - /// - /// Gets the state of the transfer. - /// - public TransferStates State { get; set; } - - /// - /// Gets the unique token for the transfer. - /// - public int Token { get; set; } - - /// - /// Gets the username of the peer to or from which the file is to be transferred. - /// - public string Username { get; set; } - - public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) - { - return new Transfer() - { - AverageSpeed = transfer.AverageSpeed, - BytesRemaining = transfer.BytesRemaining, - BytesTransferred = transfer.BytesTransferred, - Direction = transfer.Direction, - ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, - EndTime = transfer.EndTime, - Filename = transfer.Filename, - IPEndPoint = transfer.IPEndPoint, - PercentComplete = transfer.PercentComplete, - RemainingTime = transfer.RemainingTime?.TotalMilliseconds, - RemoteToken = transfer.RemoteToken, - Size = transfer.Size, - StartOffset = transfer.StartOffset, - StartTime = transfer.StartTime, - State = transfer.State, - Token = transfer.Token, - Username = transfer.Username, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Transfers/ITransferTracker.cs b/src/slskd/Application/Transfers/ITransferTracker.cs deleted file mode 100644 index 4edbdd63..00000000 --- a/src/slskd/Application/Transfers/ITransferTracker.cs +++ /dev/null @@ -1,57 +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.Transfers -{ - using System.Collections.Concurrent; - using System.Threading; - using Soulseek; - - /// - /// Tracks transfers. - /// - public interface ITransferTracker - { - /// - /// Tracked transfers. - /// - ConcurrentDictionary>> Transfers { get; } - - /// - /// Adds or updates a tracked transfer. - /// - /// - /// - void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource); - - /// - /// Removes a tracked transfer. - /// - /// Omitting an id will remove ALL transfers associated with the specified username. - void TryRemove(TransferDirection direction, string username, string id = null); - - /// - /// Gets the specified transfer. - /// - /// - /// - /// - /// - /// - bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Transfers/TransferTracker.cs b/src/slskd/Application/Transfers/TransferTracker.cs deleted file mode 100644 index d70717dd..00000000 --- a/src/slskd/Application/Transfers/TransferTracker.cs +++ /dev/null @@ -1,192 +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.Transfers -{ - using System.Collections.Concurrent; - using System.Linq; - using System.Threading; - using Soulseek; - - /// - /// Transfer extensions. - /// - public static class TransferTrackerExtensions - { - /// - /// Filters a Transfer collection by user. - /// - /// - /// - /// - public static ConcurrentDictionary FromUser( - this ConcurrentDictionary> directedTransfers, - string username) - { - directedTransfers.TryGetValue(username, out var transfers); - return transfers ?? new ConcurrentDictionary(); - } - - /// - /// Maps a Transfer collection to a serializable object. - /// - /// - /// - public static object ToMap( - this ConcurrentDictionary> directedTransfers) - { - return directedTransfers.Select(u => new - { - Username = u.Key, - Directories = u.Value.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }), - }); - } - - /// - /// Maps a Transfer collection to a serializable object. - /// - /// - /// - public static object ToMap( - this ConcurrentDictionary userTransfers) - { - return userTransfers.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }); - } - - /// - /// Filters a Transfer collection by direction. - /// - /// - /// - /// - public static ConcurrentDictionary> WithDirection( - this ConcurrentDictionary>> allTransfers, - TransferDirection direction) - { - allTransfers.TryGetValue(direction, out var transfers); - return transfers ?? new ConcurrentDictionary>(); - } - - /// - /// Retrieves a Transfer from a Transfer collection by id. - /// - /// - /// - /// - public static (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( - this ConcurrentDictionary userTransfers, - string id) - { - userTransfers.TryGetValue(id, out var transfer); - return transfer; - } - } - - /// - /// Tracks transfers. - /// - public class TransferTracker : ITransferTracker - { - /// - /// Initializes a new instance of the class. - /// - public TransferTracker() - { - Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary>()); - Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary>()); - } - - /// - /// Gets tracked transfers. - /// - public ConcurrentDictionary>> Transfers { get; private set; } = - new ConcurrentDictionary>>(); - - /// - /// Adds or updates a tracked transfer. - /// - /// - /// - public void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) - { - Transfers.TryGetValue(args.Transfer.Direction, out var direction); - - direction.AddOrUpdate(args.Transfer.Username, GetNewDictionaryForUser(args, cancellationTokenSource), (user, dict) => - { - var transfer = API.Transfer.FromSoulseekTransfer(args.Transfer); - dict.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, cancellationTokenSource)); - return dict; - }); - } - - /// - /// Gets the specified transfer. - /// - /// - /// - /// - /// - /// - public bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer) - { - transfer = default; - - if (Transfers.TryGetValue(direction, out var transfers) && transfers.TryGetValue(username, out var user) && user.TryGetValue(id, out transfer)) - { - return true; - } - - return false; - } - - /// - /// Removes a tracked transfer. - /// - /// Omitting an id will remove ALL transfers associated with the specified username. - public void TryRemove(TransferDirection direction, string username, string id = null) - { - Transfers.TryGetValue(direction, out var directionDict); - - if (string.IsNullOrEmpty(id)) - { - directionDict.TryRemove(username, out _); - } - else - { - directionDict.TryGetValue(username, out var userDict); - userDict.TryRemove(id, out _); - - if (userDict.IsEmpty) - { - directionDict.TryRemove(username, out _); - } - } - } - - private ConcurrentDictionary GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) - { - var r = new ConcurrentDictionary(); - var transfer = API.Transfer.FromSoulseekTransfer(args.Transfer); - r.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, record.CancellationTokenSource)); - return r; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Users/API/Controllers/UsersController.cs b/src/slskd/Application/Users/API/Controllers/UsersController.cs deleted file mode 100644 index e7eb5256..00000000 --- a/src/slskd/Application/Users/API/Controllers/UsersController.cs +++ /dev/null @@ -1,171 +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.Users.API -{ - using System.Collections.Generic; - using System.ComponentModel.DataAnnotations; - using System.Net; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - - /// - /// Users. - /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class UsersController : ControllerBase - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// - public UsersController(ISoulseekClient soulseekClient, IBrowseTracker browseTracker, IUserService peerService) - { - Client = soulseekClient; - BrowseTracker = browseTracker; - Peers = peerService; - } - - private IBrowseTracker BrowseTracker { get; } - private ISoulseekClient Client { get; } - private IUserService Peers { get; } - - /// - /// Retrieves the address of the specified . - /// - /// The username of the user. - /// - /// The request completed successfully. - [HttpGet("{username}/endpoint")] - [Authorize] - [ProducesResponseType(typeof(IPEndPoint), 200)] - [ProducesResponseType(404)] - public async Task Endpoint([FromRoute, Required] string username) - { - try - { - var endpoint = await Peers.GetIPEndPointAsync(username); - return Ok(endpoint); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - - /// - /// Retrieves the files shared by the specified . - /// - /// The username of the user. - /// - [HttpGet("{username}/browse")] - [Authorize] - [ProducesResponseType(typeof(IEnumerable), 200)] - [ProducesResponseType(404)] - public async Task Browse([FromRoute, Required] string username) - { - try - { - var result = await Client.BrowseAsync(username); - - _ = Task.Run(async () => - { - await Task.Delay(5000); - BrowseTracker.TryRemove(username); - }); - - return Ok(result); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - - /// - /// Retrieves the status of the current browse operation for the specified , if any. - /// - /// The username of the user. - /// - [HttpGet("{username}/browse/status")] - [Authorize] - [ProducesResponseType(typeof(decimal), 200)] - [ProducesResponseType(404)] - public IActionResult BrowseStatus([FromRoute, Required] string username) - { - if (BrowseTracker.TryGet(username, out var progress)) - { - return Ok(progress); - } - - return NotFound(); - } - - /// - /// Retrieves information about the specified . - /// - /// The username of the user. - /// Bypasses the internal cache and requests the latest information from the peer. - /// - [HttpGet("{username}/info")] - [Authorize] - [ProducesResponseType(typeof(Info), 200)] - [ProducesResponseType(404)] - public async Task Info([FromRoute, Required] string username, [FromQuery]bool bypassCache = false) - { - try - { - var response = await Peers.GetInfoAsync(username, bypassCache); - return Ok(response); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - - /// - /// Retrieves status for the specified . - /// - /// The username of the user. - /// - [HttpGet("{username}/status")] - [Authorize] - [ProducesResponseType(typeof(Status), 200)] - [ProducesResponseType(404)] - public async Task Status([FromRoute, Required] string username) - { - try - { - var response = await Peers.GetStatusAsync(username); - return Ok(response); - } - catch (UserOfflineException ex) - { - return NotFound(ex.Message); - } - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Users/API/DTO/UserDataResponse.cs b/src/slskd/Application/Users/API/DTO/UserDataResponse.cs deleted file mode 100644 index 664b1276..00000000 --- a/src/slskd/Application/Users/API/DTO/UserDataResponse.cs +++ /dev/null @@ -1,85 +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.Users.API -{ - using Soulseek; - - public class UserDataResponse - { - /// - /// The average upload speed of the user. - /// - public int AverageSpeed { get; set; } - - /// - /// The user's country code, if provided. - /// - public string CountryCode { get; set; } - - /// - /// The number of directories shared by the user. - /// - public int DirectoryCount { get; set; } - - /// - /// The number of files shared by the user. - /// - public int FileCount { get; set; } - - /// - /// A value indicating whether this user data belongs to the currently logged in user. - /// - public bool? Self { get; set; } - - /// - /// The number of the user's free download slots, if provided. - /// - public int? SlotsFree { get; set; } - - /// - /// The status of the user (0 = offline, 1 = away, 2 = online). - /// - public UserPresence Status { get; set; } - - /// - /// The number of uploads tracked by the server for the user. - /// - public long UploadCount { get; set; } - - /// - /// The username of the user. - /// - public string Username { get; set; } - - public static UserDataResponse FromUserData(UserData userData, bool self = false) - { - return new UserDataResponse() - { - AverageSpeed = userData.AverageSpeed, - CountryCode = userData.CountryCode, - DirectoryCount = userData.DirectoryCount, - UploadCount = userData.UploadCount, - FileCount = userData.FileCount, - SlotsFree = userData.SlotsFree, - Status = userData.Status, - Username = userData.Username, - Self = self ? self : (bool?)null, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Users/BrowseTracker.cs b/src/slskd/Application/Users/BrowseTracker.cs deleted file mode 100644 index 57c7c1d8..00000000 --- a/src/slskd/Application/Users/BrowseTracker.cs +++ /dev/null @@ -1,57 +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.Users -{ - using System.Collections.Concurrent; - using Soulseek; - - /// - /// Tracks browse operations. - /// - public class BrowseTracker : IBrowseTracker - { - /// - /// Tracked browse operations. - /// - public ConcurrentDictionary Browses { get; } = new ConcurrentDictionary(); - - /// - /// Adds or updates a tracked browse operation. - /// - /// - /// - public void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress) - => Browses.AddOrUpdate(username, progress, (user, oldprogress) => progress); - - /// - /// Removes a tracked browse operation for the specified user. - /// - /// - public void TryRemove(string username) - => Browses.TryRemove(username, out _); - - /// - /// Gets the browse progress for the specified user. - /// - /// - /// - /// - public bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress) - => Browses.TryGetValue(username, out progress); - } -} diff --git a/src/slskd/Application/Users/Domain/Info.cs b/src/slskd/Application/Users/Domain/Info.cs deleted file mode 100644 index aaf19942..00000000 --- a/src/slskd/Application/Users/Domain/Info.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.Users -{ - using System; - using System.ComponentModel.DataAnnotations; - using Soulseek; - - public class Info - { - [Key] - public string Username { get; init; } - public string Description { get; init; } - public bool HasFreeUploadSlot { get; init; } - public bool HasPicture { get; init; } - public byte[] Picture { get; init; } - public int QueueLength { get; init; } - public int UploadSlots { get; init; } - public DateTime UpdatedAt { get; init; } - - public static Info FromSoulseekUserInfo(string username, UserInfo info) - { - return new Info() - { - Username = username, - Description = info.Description, - HasFreeUploadSlot = info.HasFreeUploadSlot, - HasPicture = info.HasPicture, - Picture = info.Picture, - QueueLength = info.QueueLength, - UploadSlots = info.UploadSlots, - UpdatedAt = DateTime.UtcNow, - }; - } - } -} diff --git a/src/slskd/Application/Users/Domain/Status.cs b/src/slskd/Application/Users/Domain/Status.cs deleted file mode 100644 index 41452e66..00000000 --- a/src/slskd/Application/Users/Domain/Status.cs +++ /dev/null @@ -1,36 +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.Users -{ - using Soulseek; - - public class Status - { - public bool IsPrivileged { get; init; } - public UserPresence Presence { get; init; } - - public static Status FromSoulseekUserStatus(UserStatus status) - { - return new Status() - { - IsPrivileged = status.IsPrivileged, - Presence = status.Presence, - }; - } - } -} diff --git a/src/slskd/Application/Users/IBrowseTracker.cs b/src/slskd/Application/Users/IBrowseTracker.cs deleted file mode 100644 index 29ed06b3..00000000 --- a/src/slskd/Application/Users/IBrowseTracker.cs +++ /dev/null @@ -1,54 +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.Users -{ - using System.Collections.Concurrent; - using Soulseek; - - /// - /// Tracks browse operations. - /// - public interface IBrowseTracker - { - /// - /// Tracked browse operations. - /// - ConcurrentDictionary Browses { get; } - - /// - /// Adds or updates a tracked browse operation. - /// - /// - /// - void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress); - - /// - /// Gets the browse progress for the specified user. - /// - /// - /// - /// - bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress); - - /// - /// Removes a tracked browse operation for the specified user. - /// - /// - void TryRemove(string username); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Users/IUserService.cs b/src/slskd/Application/Users/IUserService.cs deleted file mode 100644 index 469acef6..00000000 --- a/src/slskd/Application/Users/IUserService.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.Users -{ - using System.Net; - using System.Threading.Tasks; - - /// - /// Provides information and operations for network peers. - /// - public interface IUserService - { - /// - /// Retrieves peer . - /// - /// The username of the peer. - /// A value indicating whether the local cache should be bypassed. - /// The cached or retrieved info. - Task GetInfoAsync(string username, bool bypassCache = false); - - /// - /// Retrieves a peer's IP endpoint, including their IP address and listen port. - /// - /// The username of the peer. - /// The retrieved endpoint. - Task GetIPEndPointAsync(string username); - - /// - /// Retrieves the current of a peer. - /// - /// The username of the peer. - /// The retrieved status. - Task GetStatusAsync(string username); - - /// - /// Grants the specified peer the specified number of privilege days. - /// - /// The username of the peer. - /// The number of days to grant. - /// The operation context. - Task GrantPrivilegesAsync(string username, int days); - - /// - /// Retrieves a value indicating whether the specified peer is privileged. - /// - /// The username of the peer. - /// A value indicating whether the specified peer is privileged. - Task IsPrivilegedAsync(string username); - - /// - /// Adds the specified username to the server-side user list. - /// - /// The username of the peer. - /// The operation context. - Task WatchAsync(string username); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Users/UserDbContext.cs b/src/slskd/Application/Users/UserDbContext.cs deleted file mode 100644 index 4d0fd08c..00000000 --- a/src/slskd/Application/Users/UserDbContext.cs +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Users -{ - using Microsoft.EntityFrameworkCore; - - public class UserDbContext : DbContext - { - public UserDbContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } - - public DbSet Info { get; set; } - } -} diff --git a/src/slskd/Application/Users/UserService.cs b/src/slskd/Application/Users/UserService.cs deleted file mode 100644 index f52f19f1..00000000 --- a/src/slskd/Application/Users/UserService.cs +++ /dev/null @@ -1,138 +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.Users -{ - using System; - using System.Net; - using System.Threading.Tasks; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; - using Soulseek; - - /// - /// Provides information and operations for network peers. - /// - public class UserService : IUserService - { - private const int CacheTTLSeconds = 300; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The database context to use. - /// The logger. - public UserService( - ISoulseekClient soulseekClient, - IDbContextFactory contextFactory, - ILogger log) - { - Client = soulseekClient; - ContextFactory = contextFactory; - Log = log; - } - - private ISoulseekClient Client { get; } - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; set; } - - /// - /// Retrieves peer . - /// - /// The username of the peer. - /// A value indicating whether the local cache should be bypassed. - /// The cached or retrieved info. - public async Task GetInfoAsync(string username, bool bypassCache = false) - { - using var context = ContextFactory.CreateDbContext(); - - var info = await context.Info.AsNoTracking().FirstOrDefaultAsync(peer => peer.Username == username); - var peerExists = info != default; - - if (!bypassCache && peerExists && info.UpdatedAt < DateTime.UtcNow.AddSeconds(CacheTTLSeconds)) - { - return info; - } - - var soulseekUserInfo = await Client.GetUserInfoAsync(username); - info = Info.FromSoulseekUserInfo(username, soulseekUserInfo); - - if (peerExists) - { - context.Update(info); - } - else - { - context.Add(info); - } - - await context.SaveChangesAsync(); - - return info; - } - - /// - /// Retrieves a peer's IP endpoint, including their IP address and listen port. - /// - /// The username of the peer. - /// The retrieved endpoint. - public Task GetIPEndPointAsync(string username) - { - return Client.GetUserEndPointAsync(username); - } - - /// - /// Retrieves the current of a peer. - /// - /// The username of the peer. - /// The retrieved status. - public async Task GetStatusAsync(string username) - { - var soulseekStatus = await Client.GetUserStatusAsync(username); - - return Status.FromSoulseekUserStatus(soulseekStatus); - } - - /// - /// Grants the specified peer the specified number of privilege days. - /// - /// The username of the peer. - /// The number of days to grant. - /// The operation context. - public Task GrantPrivilegesAsync(string username, int days) - => Client.GrantUserPrivilegesAsync(username, days); - - /// - /// Retrieves a value indicating whether the specified peer is privileged. - /// - /// The username of the peer. - /// A value indicating whether the specified peer is privileged. - public Task IsPrivilegedAsync(string username) - => Client.GetUserPrivilegedAsync(username); - - /// - /// Adds the specified username to the server-side user list. - /// - /// The username of the peer. - /// The operation context. - public async Task WatchAsync(string username) - { - await Client.AddUserAsync(username); - } - } -} \ No newline at end of file diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs new file mode 100644 index 00000000..16cd68b9 --- /dev/null +++ b/src/slskd/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/Core/API/Controllers/ConfigurationController.cs b/src/slskd/Core/API/Controllers/ConfigurationController.cs new file mode 100644 index 00000000..01c8bbc1 --- /dev/null +++ b/src/slskd/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/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs new file mode 100644 index 00000000..fb2057b9 --- /dev/null +++ b/src/slskd/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/Core/API/Controllers/ServerController.cs b/src/slskd/Core/API/Controllers/ServerController.cs new file mode 100644 index 00000000..172333ec --- /dev/null +++ b/src/slskd/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/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs new file mode 100644 index 00000000..5f20aa9f --- /dev/null +++ b/src/slskd/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/Core/API/DTO/LoginRequest.cs b/src/slskd/Core/API/DTO/LoginRequest.cs new file mode 100644 index 00000000..0653847d --- /dev/null +++ b/src/slskd/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/Core/API/DTO/ServerState.cs b/src/slskd/Core/API/DTO/ServerState.cs new file mode 100644 index 00000000..5dd16365 --- /dev/null +++ b/src/slskd/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/Core/API/DTO/TokenResponse.cs b/src/slskd/Core/API/DTO/TokenResponse.cs new file mode 100644 index 00000000..85992917 --- /dev/null +++ b/src/slskd/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/Core/API/Hubs/ApplicationHub.cs b/src/slskd/Core/API/Hubs/ApplicationHub.cs new file mode 100644 index 00000000..be6c2fe7 --- /dev/null +++ b/src/slskd/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/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs new file mode 100644 index 00000000..c4341ec1 --- /dev/null +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -0,0 +1,219 @@ +// +// 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.Messaging.API +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// + /// Conversations. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ConversationsController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public ConversationsController( + ISoulseekClient soulseekClient, + IStateMonitor applicationStateMonotor, + IConversationTracker tracker) + { + Client = soulseekClient; + ApplicationStateMonitor = applicationStateMonotor; + Tracker = tracker; + } + + private ISoulseekClient Client { get; } + private IStateMonitor ApplicationStateMonitor { get; } + private IConversationTracker Tracker { get; } + + /// + /// Acknowledges the given message id for the given username. + /// + /// + /// + /// + /// The request completed successfully. + /// + /// A conversation with the specified username, or a message matching the specified id could not be found. + /// + [HttpPut("{username}/{id}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task Acknowledge([FromRoute]string username, [FromRoute]int id) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default || !conversation.Any(p => p.Id == id)) + { + return NotFound(); + } + + await Client.AcknowledgePrivateMessageAsync(id); + return StatusCode(200); + } + + /// + /// Acknowledges all messages for the given username. + /// + /// + /// + /// The request completed successfully. + /// A conversation with the specified username could not be found. + [HttpPut("{username}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task AcknowledgeAll([FromRoute]string username) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default) + { + return NotFound(); + } + + var tasks = new List(); + + foreach (var message in conversation.Where(p => !p.Acknowledged)) + { + tasks.Add(Task.Run(async () => + { + await Client.AcknowledgePrivateMessageAsync(message.Id); + message.Acknowledged = true; + })); + } + + await Task.WhenAll(tasks); + return StatusCode(200); + } + + /// + /// Deletes the conversation associated with the given username. + /// + /// + /// The request completed successfully. + /// A conversation with the specified username could not be found. + [HttpDelete("{username}")] + [Authorize] + [ProducesResponseType(404)] + [ProducesResponseType(204)] + public IActionResult Delete([FromRoute]string username) + { + var deleted = Tracker.Conversations.TryRemove(username, out _); + + if (deleted) + { + return StatusCode(204); + } + + return StatusCode(404); + } + + /// + /// Gets all tracked conversations. + /// + /// + /// The request completed successfully. + [HttpGet("")] + [Authorize] + [ProducesResponseType(typeof(Dictionary>), 200)] + public IActionResult GetAll() + { + var response = Tracker.Conversations.ToDictionary( + entry => entry.Key, + entry => entry.Value + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.Server.Username)) + .OrderBy(m => m.Timestamp)); + + return Ok(response); + } + + /// + /// Gets the conversation associated with the specified username. + /// + /// The username associated with the desired conversation. + /// + /// The request completed successfully. + /// A matching search was not found. + [HttpGet("{username}")] + [Authorize] + [ProducesResponseType(typeof(List), 200)] + [ProducesResponseType(404)] + public IActionResult GetByUsername([FromRoute]string username) + { + if (Tracker.TryGet(username, out var conversation)) + { + var response = conversation + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.Server.Username)) + .OrderBy(m => m.Timestamp); + + return Ok(response); + } + + return NotFound(); + } + + /// + /// Sends a private message to the specified username. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified message is null or empty. + [HttpPost("{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(400)] + public async Task Send([FromRoute]string username, [FromBody]string message) + { + if (string.IsNullOrEmpty(message)) + { + return BadRequest(); + } + + await Client.SendPrivateMessageAsync(username, message); + + // append the outgoing message to the tracker + Tracker.AddOrUpdate(username, new PrivateMessage() + { + Username = ApplicationStateMonitor.CurrentValue.Server.Username, + Timestamp = DateTime.UtcNow, + Message = message, + Acknowledged = true, + }); + + return StatusCode(201); + } + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/API/Controllers/PublicChatController.cs b/src/slskd/Messaging/API/Controllers/PublicChatController.cs new file mode 100644 index 00000000..c30e08a8 --- /dev/null +++ b/src/slskd/Messaging/API/Controllers/PublicChatController.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.Messaging.API +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// + /// Server. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class PublicChatController : ControllerBase + { + public PublicChatController(ISoulseekClient soulseekClient) + { + Client = soulseekClient; + } + + private ISoulseekClient Client { get; } + + /// + /// Starts public chat. + /// + /// + [HttpPost] + [Authorize] + public async Task Start() + { + await Client.StartPublicChatAsync(); + return StatusCode(StatusCodes.Status201Created); + } + + /// + /// Stops public chat. + /// + /// + [HttpDelete] + [Authorize] + public async Task Stop() + { + await Client.StopPublicChatAsync(); + return StatusCode(StatusCodes.Status204NoContent); + } + } +} diff --git a/src/slskd/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs new file mode 100644 index 00000000..743df527 --- /dev/null +++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs @@ -0,0 +1,309 @@ +// +// 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.Messaging.API +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// + /// Rooms. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class RoomsController : ControllerBase + { + public RoomsController( + ISoulseekClient soulseekClient, + IRoomService roomService, + IStateMonitor applicationStateMonitor, + IRoomTracker tracker) + { + Client = soulseekClient; + ApplicationStateMonitor = applicationStateMonitor; + Tracker = tracker; + RoomService = roomService; + } + + private IRoomService RoomService { get; } + private ISoulseekClient Client { get; } + private IStateMonitor ApplicationStateMonitor { get; } + private IRoomTracker Tracker { get; } + + /// + /// Gets all rooms. + /// + /// + /// The request completed successfully. + [HttpGet("joined")] + [Authorize] + [ProducesResponseType(typeof(Dictionary>), 200)] + public IActionResult GetAll() + { + return Ok(Tracker.Rooms.Keys); + } + + /// + /// Gets the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpGet("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 200)] + [ProducesResponseType(404)] + public IActionResult GetByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + return Ok(MapRoomToRoomResponse(room)); + } + + return NotFound(); + } + + /// + /// Sends a message to the specified room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task SendMessage([FromRoute]string roomName, [FromBody]string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SendRoomMessageAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Sets a ticker for the specified room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/ticker")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task SetTicker([FromRoute] string roomName, [FromBody] string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SetRoomTickerAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Adds a member to a private room. + /// + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpPost("joined/{roomName}/members")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task AddRoomMember([FromRoute]string roomName, [FromBody]string username) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.AddPrivateRoomMemberAsync(roomName, username); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// + /// Gets the current list of users for the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpGet("joined/{roomName}/users")] + [Authorize] + [ProducesResponseType(typeof(IList), 200)] + [ProducesResponseType(404)] + public IActionResult GetUsersByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + var response = room.Users + .Select(user => UserDataResponse.FromUserData(user, self: user.Username == ApplicationStateMonitor.CurrentValue.Server.Username)); + + return Ok(response); + } + + return NotFound(); + } + + /// + /// Gets the current list of messages for the specified room. + /// + /// + /// + /// The request completed successfully. + /// The specified roomName could not be found. + [HttpGet("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(typeof(IList), 200)] + [ProducesResponseType(404)] + public IActionResult GetMessagesByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + var response = room.Messages + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == ApplicationStateMonitor.CurrentValue.Server.Username)); + + return Ok(response); + } + + return NotFound(); + } + + /// + /// Gets a list of rooms from the server. + /// + /// + [HttpGet("available")] + [Authorize] + [ProducesResponseType(typeof(List), 200)] + public async Task GetRooms() + { + var list = await Client.GetRoomListAsync(); + + var response = new List(); + + response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r))); + response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true))); + response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true))); + + foreach (var room in response) + { + room.IsModerated = list.ModeratedRoomNames.Contains(room.Name); + } + + return Ok(response); + } + + /// + /// Joins a room. + /// + /// + /// + /// The request completed successfully. + /// The room has already been joined. + [HttpPost("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 201)] + [ProducesResponseType(304)] + public async Task JoinRoom([FromRoute]string roomName) + { + if (Tracker.Rooms.ContainsKey(roomName)) + { + return StatusCode(StatusCodes.Status304NotModified); + } + + try + { + var roomData = await RoomService.JoinAsync(roomName); + var room = Room.FromRoomData(roomData); + Tracker.TryAdd(roomName, room); + + return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room)); + } + catch (Exception ex) + { + if (ex.InnerException is RoomJoinForbiddenException) + { + return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}"); + } + + throw; + } + } + + /// + /// Leaves a room. + /// + /// + /// + /// The request completed successfully. + /// The room has not been joined. + [HttpDelete("joined/{roomName}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public async Task LeaveRoom([FromRoute]string roomName) + { + if (!Tracker.Rooms.ContainsKey(roomName)) + { + return StatusCode(StatusCodes.Status404NotFound); + } + + await RoomService.LeaveAsync(roomName); + Tracker.TryRemove(roomName); + + return StatusCode(StatusCodes.Status204NoContent); + } + + private RoomResponse MapRoomToRoomResponse(Room room) + { + bool IsSelf(string username) + { + return username == ApplicationStateMonitor.CurrentValue.Server.Username; + } + + var response = RoomResponse.FromRoom(room); + response.Users = room.Users + .Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username))); + response.Messages = room.Messages + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username))); + + return response; + } + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs b/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs new file mode 100644 index 00000000..a7e08d50 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs @@ -0,0 +1,74 @@ +// +// 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.Messaging.API +{ + using System; + using slskd.Messaging; + + public class PrivateMessageResponse + { + /// + /// A value indicating whether the message has been acknowledged. + /// + public bool Acknowledged { get; set; } = false; + + /// + /// The unique message id, used to acknowledge receipt. + /// + public int Id { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// A value indicating whether the message was replayed. + /// + public bool Replayed { get; set; } + + /// + /// The UTC timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// A value indicating whether this message was sent by the currently logged in user. + /// + public bool? Self { get; set; } + + public static PrivateMessageResponse FromPrivateMessage(PrivateMessage privateMessage, bool self = false) + { + return new PrivateMessageResponse() + { + Id = privateMessage.Id, + Timestamp = privateMessage.Timestamp, + Username = privateMessage.Username, + Message = privateMessage.Message, + Acknowledged = privateMessage.Acknowledged, + Replayed = privateMessage.Replayed, + Self = self ? self : (bool?)null, + }; + } + } +} diff --git a/src/slskd/Messaging/API/DTO/RoomInfoResponse.cs b/src/slskd/Messaging/API/DTO/RoomInfoResponse.cs new file mode 100644 index 00000000..46edbdc8 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/RoomInfoResponse.cs @@ -0,0 +1,60 @@ +// +// 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.Messaging.API +{ + using Soulseek; + + public class RoomInfoResponse + { + /// + /// Gets the room name. + /// + public string Name { get; init; } + + /// + /// Gets the number of users in the room. + /// + public int UserCount { get; init; } + + /// + /// Gets a value indicating whether the room is private. + /// + public bool IsPrivate { get; init; } + + /// + /// Gets a value indicating whether the room is owned by the currently logged in user. + /// + public bool IsOwned { get; init; } + + /// + /// Gets a value indicating whether the room is moderated by the currently logged in user. + /// + public bool IsModerated { get; set; } + + public static RoomInfoResponse FromRoomInfo(RoomInfo info, bool isPrivate = false, bool isOwned = false) + { + return new RoomInfoResponse() + { + Name = info.Name, + UserCount = info.UserCount, + IsPrivate = isPrivate, + IsOwned = isOwned, + }; + } + } +} diff --git a/src/slskd/Messaging/API/DTO/RoomMessageResponse.cs b/src/slskd/Messaging/API/DTO/RoomMessageResponse.cs new file mode 100644 index 00000000..965c63a6 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/RoomMessageResponse.cs @@ -0,0 +1,62 @@ +// +// 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.Messaging.API +{ + using System; + using slskd.Messaging; + + public class RoomMessageResponse + { + /// + /// The timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// The room to which the message pertains. + /// + public string RoomName { get; set; } + + /// + /// A value indicating whether this user data belongs to the currently logged in user. + /// + public bool? Self { get; set; } + + public static RoomMessageResponse FromRoomMessage(RoomMessage roomMessage, bool self = false) + { + return new RoomMessageResponse() + { + Timestamp = roomMessage.Timestamp, + Username = roomMessage.Username, + Message = roomMessage.Message, + RoomName = roomMessage.RoomName, + Self = self ? self : (bool?)null, + }; + } + } +} diff --git a/src/slskd/Messaging/API/DTO/RoomResponse.cs b/src/slskd/Messaging/API/DTO/RoomResponse.cs new file mode 100644 index 00000000..cf7e1478 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/RoomResponse.cs @@ -0,0 +1,75 @@ +// +// 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.Messaging.API +{ + using System.Collections.Generic; + using System.Linq; + using slskd.Messaging; + + public class RoomResponse + { + /// + /// The room name. + /// + public string Name { get; set; } + + /// + /// A value indicating whether the room is private. + /// + public bool IsPrivate { get; set; } + + /// + /// The number of operators in the room, if private. + /// + public int? OperatorCount { get; set; } + + /// + /// The operators in the room, if private. + /// + public IList Operators { get; set; } + + /// + /// The owner of the room, if private. + /// + public string Owner { get; set; } + + /// + /// The list of users in the room. + /// + public IEnumerable Users { get; set; } = new List(); + + /// + /// The list of messages. + /// + public IEnumerable Messages { get; set; } = new List(); + + public static RoomResponse FromRoom(Room room) + { + return new RoomResponse() + { + Name = room.Name, + IsPrivate = room.IsPrivate, + OperatorCount = room.OperatorCount, + Operators = room.Operators?.ToList(), + Owner = room.Owner, + Users = new List(), + Messages = new List(), + }; + } + } +} diff --git a/src/slskd/Messaging/API/DTO/UserDataResponse.cs b/src/slskd/Messaging/API/DTO/UserDataResponse.cs new file mode 100644 index 00000000..8f1e9544 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/UserDataResponse.cs @@ -0,0 +1,85 @@ +// +// 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.Messaging.API +{ + using Soulseek; + + public class UserDataResponse + { + /// + /// The average upload speed of the user. + /// + public int AverageSpeed { get; set; } + + /// + /// The user's country code, if provided. + /// + public string CountryCode { get; set; } + + /// + /// The number of directories shared by the user. + /// + public int DirectoryCount { get; set; } + + /// + /// The number of files shared by the user. + /// + public int FileCount { get; set; } + + /// + /// A value indicating whether this user data belongs to the currently logged in user. + /// + public bool? Self { get; set; } + + /// + /// The number of the user's free download slots, if provided. + /// + public int? SlotsFree { get; set; } + + /// + /// The status of the user (0 = offline, 1 = away, 2 = online). + /// + public UserPresence Status { get; set; } + + /// + /// The number of uploads tracked by the server for the user. + /// + public long UploadCount { get; set; } + + /// + /// The username of the user. + /// + public string Username { get; set; } + + public static UserDataResponse FromUserData(UserData userData, bool self = false) + { + return new UserDataResponse() + { + AverageSpeed = userData.AverageSpeed, + CountryCode = userData.CountryCode, + DirectoryCount = userData.DirectoryCount, + UploadCount = userData.UploadCount, + FileCount = userData.FileCount, + SlotsFree = userData.SlotsFree, + Status = userData.Status, + Username = userData.Username, + Self = self ? self : (bool?)null, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/ConversationTracker.cs b/src/slskd/Messaging/ConversationTracker.cs new file mode 100644 index 00000000..27d678ca --- /dev/null +++ b/src/slskd/Messaging/ConversationTracker.cs @@ -0,0 +1,62 @@ +// +// 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.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + + /// + /// Tracks private message conversations. + /// + public class ConversationTracker : IConversationTracker + { + /// + /// Tracked private message conversations. + /// + public ConcurrentDictionary> Conversations { get; } = new ConcurrentDictionary>(); + + /// + /// Adds a private message conversation and appends the specified , or just appends the + /// message if the conversation exists. + /// + /// + /// + public void AddOrUpdate(string username, PrivateMessage message) + { + Conversations.AddOrUpdate(username, new List() { message }, (_, messageList) => + { + messageList.Add(message); + return messageList; + }); + } + + /// + /// Returns the list of private messages for the specified , if any exist. + /// + /// + /// + /// + public bool TryGet(string username, out IList messages) => Conversations.TryGetValue(username, out messages); + + /// + /// Removes a tracked private message conversation for the specified user. + /// + /// + public void TryRemove(string username) => Conversations.TryRemove(username, out _); + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/Domain/PrivateMessage.cs b/src/slskd/Messaging/Domain/PrivateMessage.cs new file mode 100644 index 00000000..236632aa --- /dev/null +++ b/src/slskd/Messaging/Domain/PrivateMessage.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/. +// + +namespace slskd.Messaging +{ + using System; + using Soulseek; + + /// + /// A private message. + /// + public class PrivateMessage + { + /// + /// A value indicating whether the message has been acknowledged. + /// + public bool Acknowledged { get; set; } = false; + + /// + /// The unique message id, used to acknowledge receipt. + /// + public int Id { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// A value indicating whether the message was replayed. + /// + public bool Replayed { get; set; } + + /// + /// The UTC timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) + { + return new PrivateMessage() + { + Id = eventArgs.Id, + Timestamp = eventArgs.Timestamp, + Username = eventArgs.Username, + Message = eventArgs.Message, + Acknowledged = false, + Replayed = eventArgs.Replayed, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/Domain/Room.cs b/src/slskd/Messaging/Domain/Room.cs new file mode 100644 index 00000000..459dea2c --- /dev/null +++ b/src/slskd/Messaging/Domain/Room.cs @@ -0,0 +1,75 @@ +// +// 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.Messaging +{ + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + public class Room + { + /// + /// The room name. + /// + public string Name { get; set; } + + /// + /// A value indicating whether the room is private. + /// + public bool IsPrivate { get; set; } + + /// + /// The number of operators in the room, if private. + /// + public int? OperatorCount { get; set; } + + /// + /// The operators in the room, if private. + /// + public IList Operators { get; set; } + + /// + /// The owner of the room, if private. + /// + public string Owner { get; set; } + + /// + /// The list of users in the room. + /// + public IList Users { get; set; } = new List(); + + /// + /// The list of messages. + /// + public IList Messages { get; set; } = new List(); + + public static Room FromRoomData(RoomData roomData) + { + return new Room() + { + Name = roomData.Name, + IsPrivate = roomData.IsPrivate, + OperatorCount = roomData.OperatorCount, + Operators = roomData.Operators?.ToList(), + Owner = roomData.Owner, + Users = roomData.Users?.ToList(), + Messages = new List(), + }; + } + } +} diff --git a/src/slskd/Messaging/Domain/RoomMessage.cs b/src/slskd/Messaging/Domain/RoomMessage.cs new file mode 100644 index 00000000..7a06a192 --- /dev/null +++ b/src/slskd/Messaging/Domain/RoomMessage.cs @@ -0,0 +1,59 @@ +// +// 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.Messaging +{ + using System; + using Soulseek; + + /// + /// A message sent to a room. + /// + public class RoomMessage + { + /// + /// The timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// The room to which the message pertains. + /// + public string RoomName { get; set; } + + public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) + { + return new RoomMessage() + { + Timestamp = timestamp ?? DateTime.UtcNow, + Username = eventArgs.Username, + Message = eventArgs.Message, + RoomName = eventArgs.RoomName, + }; + } + } +} diff --git a/src/slskd/Messaging/IConversationTracker.cs b/src/slskd/Messaging/IConversationTracker.cs new file mode 100644 index 00000000..8e7a90f4 --- /dev/null +++ b/src/slskd/Messaging/IConversationTracker.cs @@ -0,0 +1,55 @@ +// +// 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.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + + /// + /// Tracks private message conversations. + /// + public interface IConversationTracker + { + /// + /// Tracked private message conversations. + /// + ConcurrentDictionary> Conversations { get; } + + /// + /// Adds a private message conversation and appends the specified , or just appends the + /// message if the conversation exists. + /// + /// + /// + void AddOrUpdate(string username, PrivateMessage message); + + /// + /// Returns the list of private messages for the specified , if any exist. + /// + /// + /// + /// + bool TryGet(string username, out IList messages); + + /// + /// Removes a tracked private message conversation for the specified user. + /// + /// + void TryRemove(string username); + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/IRoomTracker.cs b/src/slskd/Messaging/IRoomTracker.cs new file mode 100644 index 00000000..225e5f69 --- /dev/null +++ b/src/slskd/Messaging/IRoomTracker.cs @@ -0,0 +1,75 @@ +// +// 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.Messaging +{ + using System.Collections.Concurrent; + using Soulseek; + + /// + /// Tracks rooms. + /// + public interface IRoomTracker + { + /// + /// Gets tracked rooms. + /// + ConcurrentDictionary Rooms { get; } + + /// + /// Adds a room and appends the specified , or just appends the message if the room exists. + /// + /// + /// + void AddOrUpdateMessage(string roomName, RoomMessage message); + + /// + /// Adds the specified room to the tracker. + /// + /// + /// + void TryAdd(string roomName, Room room); + + /// + /// Adds the specified to the specified room. + /// + /// + /// + void TryAddUser(string roomName, UserData userData); + + /// + /// Returns the list of messages for the specified , if it is tracked. + /// + /// + /// + /// + bool TryGet(string roomName, out Room room); + + /// + /// Removes a tracked room. + /// + /// + void TryRemove(string roomName); + + /// + /// Removes the specified from the specified room. + /// + /// + /// + void TryRemoveUser(string roomName, string username); + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/RoomService.cs b/src/slskd/Messaging/RoomService.cs new file mode 100644 index 00000000..2b6d2489 --- /dev/null +++ b/src/slskd/Messaging/RoomService.cs @@ -0,0 +1,218 @@ +// +// 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.Messaging +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Serilog; + using Soulseek; + + /// + /// Chat room management and event handling. + /// + public interface IRoomService + { + /// + /// Joins the specfied . + /// + /// The name of the room to join. + /// The operation context, including information about the room. + Task JoinAsync(string roomName); + + /// + /// Leaves the specified . + /// + /// The name of the room to leave. + /// The operation context. + Task LeaveAsync(string roomName); + + /// + /// Attempts to join the specified . + /// + /// + /// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions. + /// + /// The list of room names to join. + /// The operation context. + Task TryJoinAsync(params string[] roomNames); + } + + /// + /// Chat room management and event handling. + /// + public class RoomService : IRoomService + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + public RoomService( + ISoulseekClient soulseekClient, + IOptionsMonitor optionsMonitor, + IStateMutator stateMutator, + IRoomTracker roomTracker) + { + Client = soulseekClient; + + StateMutator = stateMutator; + OptionsMonitor = optionsMonitor; + + RoomTracker = roomTracker; + + Client.LoggedIn += Client_LoggedIn; + + Client.RoomJoined += Client_RoomJoined; + Client.RoomLeft += Client_RoomLeft; + Client.RoomMessageReceived += Client_RoomMessageReceived; + } + + private ISoulseekClient Client { get; } + private ILogger Logger { get; set; } = Log.ForContext(); + private IStateMutator StateMutator { get; } + private IOptionsMonitor OptionsMonitor { get; } + private IRoomTracker RoomTracker { get; set; } + + /// + /// Joins the specfied . + /// + /// The name of the room to join. + /// The operation context, including information about the room. + public async Task JoinAsync(string roomName) + { + Logger.Debug("Joining room {Room}", roomName); + + try + { + var data = await Client.JoinRoomAsync(roomName); + + Logger.Debug("Room data for {Room}: {Info}", roomName, data.ToJson()); + return data; + } + catch (Exception ex) + { + Logger.Warning("Failed to join room {Room}: {Message}", roomName, ex.Message); + throw; + } + } + + /// + /// Leaves the specified . + /// + /// The name of the room to leave. + /// The operation context. + public async Task LeaveAsync(string roomName) + { + Logger.Debug("Leaving room {Room}", roomName); + + try + { + await Client.LeaveRoomAsync(roomName); + } + catch (Exception ex) + { + Logger.Warning("Failed to leave room {Room}: {Message}", roomName, ex.Message); + throw; + } + } + + /// + /// Attempts to join the specified . + /// + /// + /// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions. + /// + /// The list of room names to join. + /// The operation context. + public async Task TryJoinAsync(params string[] roomNames) + { + var tasks = new List(); + + foreach (var room in roomNames) + { + tasks.Add(JoinAsync(room)); + } + + try + { + await Task.WhenAll(tasks); + } + catch (Exception ex) + { + Logger.Debug(ex, "Caught Exception in JoinAsync"); + } + } + + private async void Client_LoggedIn(object sender, EventArgs e) + { + var autoJoinRooms = OptionsMonitor.CurrentValue.Rooms; + + if (autoJoinRooms.Any()) + { + Logger.Information("Auto-joining room(s) {Rooms}", string.Join(", ", autoJoinRooms)); + await TryJoinAsync(autoJoinRooms); + } + + var previouslyJoinedRooms = RoomTracker.Rooms.Keys.Except(autoJoinRooms); + + if (previouslyJoinedRooms.Any()) + { + Logger.Information("Attempting to rejoin room(s) {Rooms}", string.Join(", ", previouslyJoinedRooms)); + await TryJoinAsync(previouslyJoinedRooms.ToArray()); + } + } + + private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) + { + if (args.Username == Client.Username) + { + Logger.Information("Joined room {Room}", args.RoomName); + StateMutator.SetValue(state => state with { Rooms = state.Rooms.Concat(new[] { args.RoomName }).Distinct().ToArray() }); + } + else + { + RoomTracker.TryAddUser(args.RoomName, args.UserData); + } + } + + private void Client_RoomLeft(object sender, RoomLeftEventArgs args) + { + if (args.Username == Client.Username) + { + Logger.Information("Left room {Room}", args.RoomName); + StateMutator.SetValue(state => state with { Rooms = state.Rooms.Where(room => room != args.RoomName).ToArray() }); + } + else + { + RoomTracker.TryRemoveUser(args.RoomName, args.Username); + } + } + + private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) + { + var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); + RoomTracker.AddOrUpdateMessage(args.RoomName, message); + } + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/RoomTracker.cs b/src/slskd/Messaging/RoomTracker.cs new file mode 100644 index 00000000..c586f401 --- /dev/null +++ b/src/slskd/Messaging/RoomTracker.cs @@ -0,0 +1,112 @@ +// +// 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.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + /// + /// Tracks rooms. + /// + public class RoomTracker : IRoomTracker + { + /// + /// Initializes a new instance of the class. + /// + /// + public RoomTracker(int messageLimit = 25) + { + MessageLimit = messageLimit; + } + + /// + /// Tracked rooms. + /// + public ConcurrentDictionary Rooms { get; } = new ConcurrentDictionary(); + + private int MessageLimit { get; } + + /// + /// Adds a room and appends the specified , or just appends the message if the room exists. + /// + /// + /// + public void AddOrUpdateMessage(string roomName, RoomMessage message) + { + Rooms.AddOrUpdate(roomName, new Room() { Messages = new List() { message } }, (_, room) => + { + if (room.Messages.Count >= MessageLimit) + { + room.Messages = room.Messages.TakeLast(MessageLimit - 1).ToList(); + } + + room.Messages.Add(message); + return room; + }); + } + + /// + /// Adds the specified room to the tracker. + /// + /// + /// + public void TryAdd(string roomName, Room room) => Rooms.TryAdd(roomName, room); + + /// + /// Adds the specified to the specified room. + /// + /// + /// + public void TryAddUser(string roomName, UserData userData) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users.Add(userData); + } + } + + /// + /// Removes a tracked room. + /// + /// + /// + /// + public bool TryGet(string roomName, out Room room) => Rooms.TryGetValue(roomName, out room); + + /// + /// Returns the list of messages for the specified , if it is tracked. + /// + /// + public void TryRemove(string roomName) => Rooms.TryRemove(roomName, out _); + + /// + /// Removes the specified from the specified room. + /// + /// + /// + public void TryRemoveUser(string roomName, string username) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users = room.Users.Where(u => u.Username != username).ToList(); + } + } + } +} \ No newline at end of file diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs new file mode 100644 index 00000000..5f740044 --- /dev/null +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -0,0 +1,135 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search.API +{ + using System; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using SearchQuery = Soulseek.SearchQuery; + using SearchScope = Soulseek.SearchScope; + + /// + /// Search. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SearchesController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + public SearchesController(ISearchService searchService) + { + Searches = searchService; + } + + private ISearchService Searches { get; } + + /// + /// Performs a search for the specified . + /// + /// The search request. + /// + /// The search completed successfully. + /// The specified was malformed. + /// The search terminated abnormally. + [HttpPost("")] + [Authorize] + public async Task Post([FromBody]SearchRequest request) + { + var id = request.Id ?? Guid.NewGuid(); + var searchText = string.Join(' ', request.SearchText.Split(' ').Where(term => term.Length > 1)); + + Search search = null; + + try + { + search = await Searches.CreateAsync(id, SearchQuery.FromText(searchText), SearchScope.Network); + return Ok(search.Responses); + } + catch (Exception ex) + { + return StatusCode(500, $"Search terminated abnormally: {ex.Message}"); + } + finally + { + search = null; + } + } + + /// + /// Gets the state of the search corresponding to the specified . + /// + /// The unique id of the search. + /// A value indicating whether to include search responses in the response. + /// + /// The request completed successfully. + /// A matching search was not found. + [HttpGet("{id}")] + [Authorize] + public async Task GetById([FromRoute]Guid id, [FromQuery]bool includeResponses = false) + { + var search = await Searches.FindAsync(search => search.Id == id, includeResponses); + + if (search == default) + { + return NotFound(); + } + + return Ok(search); + } + + /// + /// Gets the state of the search corresponding to the specified . + /// + /// The unique id of the search. + /// + /// The request completed successfully. + /// A matching search was not found. + [HttpGet("{id}/responses")] + [Authorize] + public async Task GetResponsesById([FromRoute] Guid id) + { + var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); + + if (search == default) + { + return NotFound(); + } + + return Ok(search.Responses); + } + + /// + /// Gets the list of active and completed searches. + /// + /// + [HttpGet("")] + [Authorize] + public async Task GetAll() + { + return Ok(await Searches.ListAsync()); + } + } +} diff --git a/src/slskd/Search/API/DTO/SearchRequest.cs b/src/slskd/Search/API/DTO/SearchRequest.cs new file mode 100644 index 00000000..aad5a200 --- /dev/null +++ b/src/slskd/Search/API/DTO/SearchRequest.cs @@ -0,0 +1,116 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search.API +{ + using System; + using Soulseek; + + /// + /// A search request. + /// + public class SearchRequest + { + /// + /// Gets or sets the unique search identifier. + /// + public Guid? Id { get; set; } + + /// + /// Gets or sets the maximum number of file results to accept before the search is considered complete. (Default = 10,000). + /// + public int? FileLimit { get; set; } + + /// + /// Gets or sets a value indicating whether responses are to be filtered. (Default = true). + /// + public bool? FilterResponses { get; set; } + + /// + /// Gets or sets the maximum queue depth a peer may have in order for a response to be processed. (Default = 1000000). + /// + public int? MaximumPeerQueueLength { get; set; } + + /// + /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. + /// (Default = 0). + /// + public int? MinimumPeerFreeUploadSlots { get; set; } + + /// + /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). + /// + public int? MinimumPeerUploadSpeed { get; set; } + + /// + /// Gets or sets the minimum number of files a response must contain in order to be processed. (Default = 1). + /// + public int? MinimumResponseFileCount { get; set; } + + /// + /// Gets or sets the maximum number of search results to accept before the search is considered complete. (Default = 100). + /// + public int? ResponseLimit { get; set; } + + /// + /// Gets or sets the search text. + /// + public string SearchText { get; set; } + + /// + /// Gets or sets the search timeout value, in seconds, used to determine when the search is complete. (Default = 15). + /// + /// The timeout duration is from the time of the last response. + public int? SearchTimeout { get; set; } + + /// + /// Gets or sets the search token. + /// + public int? Token { get; set; } + + /// + /// Maps to a new instance of . + /// + /// + /// + /// + /// + /// + public SearchOptions ToSearchOptions( + Func responseFilter = null, + Func fileFilter = null, + Action stateChanged = null, + Action responseReceived = null) + { + var def = new SearchOptions(); + + return new SearchOptions( + searchTimeout: SearchTimeout ?? def.SearchTimeout, + responseLimit: ResponseLimit ?? def.ResponseLimit, + fileLimit: FileLimit ?? def.FileLimit, + filterResponses: FilterResponses ?? def.FilterResponses, + minimumResponseFileCount: MinimumResponseFileCount ?? def.MinimumResponseFileCount, + minimumPeerFreeUploadSlots: MinimumPeerFreeUploadSlots ?? def.MinimumPeerFreeUploadSlots, + maximumPeerQueueLength: MaximumPeerQueueLength ?? def.MaximumPeerQueueLength, + minimumPeerUploadSpeed: MinimumPeerUploadSpeed ?? def.MinimumPeerUploadSpeed, + responseFilter: responseFilter, + fileFilter: fileFilter, + responseReceived: responseReceived, + stateChanged: stateChanged); + } + } +} \ No newline at end of file diff --git a/src/slskd/Search/Domain/File.cs b/src/slskd/Search/Domain/File.cs new file mode 100644 index 00000000..0a86eec3 --- /dev/null +++ b/src/slskd/Search/Domain/File.cs @@ -0,0 +1,51 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using SoulseekFile = Soulseek.File; + + public class File + { + public int? BitDepth { get; init; } + public int? BitRate { get; init; } + public int Code { get; init; } + public string Extension { get; init; } + public string Filename { get; init; } + public bool? IsVariableBitRate { get; init; } + public int? Length { get; init; } + public int? SampleRate { get; init; } + public long Size { get; init; } + public bool IsLocked { get; init; } + + public static File FromSoulseekFile(SoulseekFile file) + { + return new File() + { + BitDepth = file.BitDepth, + BitRate = file.BitRate, + Code = file.Code, + Extension = file.Extension, + Filename = file.Filename, + IsVariableBitRate = file.IsVariableBitRate, + Length = file.Length, + SampleRate = file.SampleRate, + Size = file.Size, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Search/Domain/Response.cs b/src/slskd/Search/Domain/Response.cs new file mode 100644 index 00000000..ea2e8993 --- /dev/null +++ b/src/slskd/Search/Domain/Response.cs @@ -0,0 +1,51 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using System.Collections.Generic; + using System.Linq; + + public class Response + { + public int FileCount { get; init; } + public ICollection Files { get; init; } = new List(); + public int FreeUploadSlots { get; init; } + public int LockedFileCount { get; init; } + public ICollection LockedFiles { get; init; } = new List(); + public long QueueLength { get; init; } + public int Token { get; init; } + public int UploadSpeed { get; init; } + public string Username { get; init; } + + public static Response FromSoulseekSearchResponse(Soulseek.SearchResponse searchResponse) + { + return new Response() + { + FileCount = searchResponse.FileCount, + Files = searchResponse.Files.Select(file => File.FromSoulseekFile(file)).ToList(), + FreeUploadSlots = searchResponse.FreeUploadSlots, + LockedFileCount = searchResponse.LockedFileCount, + LockedFiles = searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file)).ToList(), + QueueLength = searchResponse.QueueLength, + Token = searchResponse.Token, + UploadSpeed = searchResponse.UploadSpeed, + Username = searchResponse.Username, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Search/Domain/Search.cs b/src/slskd/Search/Domain/Search.cs new file mode 100644 index 00000000..b93c62cb --- /dev/null +++ b/src/slskd/Search/Domain/Search.cs @@ -0,0 +1,60 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Text.Json; + using System.Text.Json.Serialization; + using Soulseek; + + public class Search + { + public DateTime? EndedAt { get; set; } + public int FileCount { get; set; } + + [Key] + public Guid Id { get; init; } + + [NotMapped] + public bool IsComplete => State.HasFlag(SearchStates.Completed); + + public int LockedFileCount { get; set; } + public int ResponseCount { get; set; } + + [NotMapped] + public IEnumerable Responses { get; set; } = new List(); + + [JsonIgnore] + public string ResponsesJson + { + get => JsonSerializer.Serialize(Responses); + set + { + Responses = JsonSerializer.Deserialize>(value); + } + } + + public string SearchText { get; init; } + public DateTime StartedAt { get; init; } = DateTime.UtcNow; + public SearchStates State { get; set; } + public int Token { get; init; } + } +} \ No newline at end of file diff --git a/src/slskd/Search/Extensions.cs b/src/slskd/Search/Extensions.cs new file mode 100644 index 00000000..149e0a14 --- /dev/null +++ b/src/slskd/Search/Extensions.cs @@ -0,0 +1,122 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using System; + using System.Linq; + using Soulseek; + + public static class Extensions + { + /// + /// Returns a copy of the specified with the specified actions bound, while retaining the existing actions. + /// + /// + /// + /// + /// + public static SearchOptions WithActions( + this SearchOptions options, + Action stateChanged = null, + Action responseReceived = null) + { + stateChanged ??= (args) => { }; + responseReceived ??= (args) => { }; + + return new SearchOptions( + options.SearchTimeout, + options.ResponseLimit, + options.FilterResponses, + options.MinimumResponseFileCount, + options.MinimumPeerFreeUploadSlots, + options.MaximumPeerQueueLength, + options.MinimumPeerUploadSpeed, + options.FileLimit, + options.RemoveSingleCharacterSearchTerms, + options.ResponseFilter, + options.FileFilter, + stateChanged: (args) => + { + if (options.StateChanged != null) + { + options.StateChanged(args); + } + + stateChanged(args); + }, + responseReceived: (args) => + { + if (options.ResponseReceived != null) + { + options.ResponseReceived(args); + } + + responseReceived(args); + }); + } + + /// + /// Returns a copy of the specified with the specified filter delegates overridden. + /// + /// + /// + /// + /// + public static SearchOptions WithFilters( + this SearchOptions options, + Func responseFilter = null, + Func fileFilter = null) + { + return new SearchOptions( + options.SearchTimeout, + options.ResponseLimit, + filterResponses: options.FilterResponses || responseFilter != null || fileFilter != null, + options.MinimumResponseFileCount, + options.MinimumPeerFreeUploadSlots, + options.MaximumPeerQueueLength, + options.MinimumPeerUploadSpeed, + options.FileLimit, + options.RemoveSingleCharacterSearchTerms, + responseFilter, + fileFilter, + options.StateChanged, + options.ResponseReceived); + } + + /// + /// Creates a projection over the specified which omits responses. + /// + /// + /// + public static IQueryable WithoutResponses(this IQueryable query) + { + return query.Select(s => new Search() + { + Id = s.Id, + StartedAt = s.StartedAt, + EndedAt = s.EndedAt, + FileCount = s.FileCount, + LockedFileCount = s.LockedFileCount, + ResponseCount = s.ResponseCount, + SearchText = s.SearchText, + State = s.State, + Token = s.Token, + }); + } + } +} diff --git a/src/slskd/Search/ISearchService.cs b/src/slskd/Search/ISearchService.cs new file mode 100644 index 00000000..d696617d --- /dev/null +++ b/src/slskd/Search/ISearchService.cs @@ -0,0 +1,66 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Threading.Tasks; + using SearchOptions = Soulseek.SearchOptions; + using SearchQuery = Soulseek.SearchQuery; + using SearchScope = Soulseek.SearchScope; + + /// + /// Handles the lifecycle and persistence of searches. + /// + public interface ISearchService + { + /// + /// Performs a search for the specified and . + /// + /// A unique identifier for the search. + /// The search query. + /// The search scope. + /// Search options. + /// The completed search. + Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); + + /// + /// Finds a single search matching the specified . + /// + /// The expression to use to match searches. + /// A value indicating whether to include search responses in the result. + /// The found search, or default if not found. + /// Thrown an expression is not supplied. + Task FindAsync(Expression> expression, bool includeResponses = false); + + /// + /// Returns a list of all completed and in-progress searches, with responses omitted. + /// + /// An optional expression used to match searches. + /// The list of searches matching the specified expression. + Task> ListAsync(Expression> expression = null); + + /// + /// Cancels the search matching the specified , if it is in progress. + /// + /// The unique identifier for the search. + /// A value indicating whether the search was sucessfully cancelled. + bool TryCancel(Guid id); + } +} \ No newline at end of file diff --git a/src/slskd/Search/SearchDbContext.cs b/src/slskd/Search/SearchDbContext.cs new file mode 100644 index 00000000..efb2fdd6 --- /dev/null +++ b/src/slskd/Search/SearchDbContext.cs @@ -0,0 +1,32 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using Microsoft.EntityFrameworkCore; + + public class SearchDbContext : DbContext + { + public SearchDbContext(DbContextOptions options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet Searches { get; set; } + } +} diff --git a/src/slskd/Search/SearchResponseCache.cs b/src/slskd/Search/SearchResponseCache.cs new file mode 100644 index 00000000..c31a3a9b --- /dev/null +++ b/src/slskd/Search/SearchResponseCache.cs @@ -0,0 +1,77 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Search +{ + using System; + using Microsoft.Extensions.Caching.Memory; + using Soulseek; + + /// + /// Caches undelivered search responses. + /// + public class SearchResponseCache : ISearchResponseCache + { + /// + /// Initializes a new instance of the class. + /// + public SearchResponseCache() + { + Cache = new MemoryCache(new MemoryCacheOptions()); + } + + private IMemoryCache Cache { get; } + + /// + /// Caches or updates a response. + /// + /// The token for which the response is to be added or updated. + /// The response and context to cache. + public void AddOrUpdate(int responseToken, (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) + { + Cache.Set(responseToken, response, TimeSpan.FromMinutes(3)); + } + + /// + /// Attempts to fetch a cached response and context for the specified . + /// + /// The token for the cached response. + /// The cached response and context, if present. + /// A value indicating whether a response for the specified responseToken is cached. + public bool TryGet(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) + { + return Cache.TryGetValue(responseToken, out response); + } + + /// + /// Attempts to remove a cached Soulseek.SearchResponse and context for the specified . + /// + /// The token for the cached response. + /// The cached response and context, if present. + /// A value indicating whether a response for the specified responseToken was removed. + public bool TryRemove(int responseToken, out (string Username, int Token, string Query, Soulseek.SearchResponse SearchResponse) response) + { + if (Cache.TryGetValue(responseToken, out response)) + { + Cache.Remove(responseToken); + return true; + } + + return false; + } + } +} \ No newline at end of file diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs new file mode 100644 index 00000000..e529f738 --- /dev/null +++ b/src/slskd/Search/SearchService.cs @@ -0,0 +1,210 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Search +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.Logging; + using Soulseek; + using SearchOptions = Soulseek.SearchOptions; + using SearchQuery = Soulseek.SearchQuery; + using SearchScope = Soulseek.SearchScope; + using SearchStates = Soulseek.SearchStates; + using SoulseekSearch = Soulseek.Search; + + /// + /// Handles the lifecycle and persistence of searches. + /// + public class SearchService : ISearchService + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// The database context to use. + /// The logger. + public SearchService( + IOptionsMonitor optionsMonitor, + ISoulseekClient soulseekClient, + IDbContextFactory contextFactory, + ILogger log) + { + OptionsMonitor = optionsMonitor; + Client = soulseekClient; + ContextFactory = contextFactory; + Log = log; + } + + private ConcurrentDictionary CancellationTokens { get; } + = new ConcurrentDictionary(); + + private IOptionsMonitor OptionsMonitor { get; } + private ISoulseekClient Client { get; } + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; set; } + + /// + /// Performs a search for the specified and . + /// + /// A unique identifier for the search. + /// The search query. + /// The search scope. + /// Search options. + /// The completed search. + public async Task CreateAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null) + { + var token = Client.GetNextToken(); + var cancellationTokenSource = new CancellationTokenSource(); + + var search = new Search() + { + SearchText = query.SearchText, + Token = token, + Id = id, + State = SearchStates.Requested, + StartedAt = DateTime.UtcNow, + }; + + options ??= new SearchOptions(); + options = options.WithActions( + stateChanged: (args) => UpdateSearchState(search, args.Search), + responseReceived: (args) => UpdateSearchState(search, args.Search)); + + try + { + using var context = ContextFactory.CreateDbContext(); + + context.Add(search); + await context.SaveChangesAsync(); + + CancellationTokens.TryAdd(id, cancellationTokenSource); + var responses = new List(); + + var soulseekSearch = await Client.SearchAsync( + query, + responseReceived: (response) => + { + responses.Add(Response.FromSoulseekSearchResponse(response)); + }, + scope, + token, + options, + cancellationToken: cancellationTokenSource.Token); + + CancellationTokens.TryRemove(id, out _); + + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + search.EndedAt = DateTime.UtcNow; + search.Responses = responses; + SaveSearchState(search); + + return search; + } + finally + { + CancellationTokens.TryRemove(id, out _); + } + } + + /// + /// Finds a single search matching the specified . + /// + /// The expression to use to match searches. + /// A value indicating whether to include search responses in the result. + /// The found search, or default if not found. + /// Thrown an expression is not supplied. + public Task FindAsync(Expression> expression, bool includeResponses = false) + { + if (expression == default) + { + throw new ArgumentException("An expression must be supplied.", nameof(expression)); + } + + using var context = ContextFactory.CreateDbContext(); + + var selector = context.Searches.Where(expression); + + if (!includeResponses) + { + selector = selector.WithoutResponses(); + } + + return selector.FirstOrDefaultAsync(); + } + + /// + /// Returns a list of all completed and in-progress searches, with responses omitted. + /// + /// An optional expression used to match searches. + /// The list of searches matching the specified expression. + public Task> ListAsync(Expression> expression = null) + { + expression ??= s => true; + using var context = ContextFactory.CreateDbContext(); + return context.Searches.Where(expression).WithoutResponses().ToListAsync(); + } + + /// + /// Cancels the search matching the specified , if it is in progress. + /// + /// The unique identifier for the search. + /// A value indicating whether the search was sucessfully cancelled. + public bool TryCancel(Guid id) + { + if (CancellationTokens.TryGetValue(id, out var cts)) + { + cts.Cancel(); + return true; + } + + return false; + } + + private void UpdateSearchState(Search search, SoulseekSearch soulseekSearch) + { + if (CancellationTokens.ContainsKey(search.Id)) + { + search.FileCount = soulseekSearch.FileCount; + search.LockedFileCount = soulseekSearch.LockedFileCount; + search.ResponseCount = soulseekSearch.ResponseCount; + search.State = soulseekSearch.State; + + SaveSearchState(search); + } + } + + private void SaveSearchState(Search search) + { + var context = ContextFactory.CreateDbContext(); + context.Update(search); + context.SaveChanges(); + } + } +} \ No newline at end of file diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs new file mode 100644 index 00000000..79e9d5a5 --- /dev/null +++ b/src/slskd/Shares/SharedFileCache.cs @@ -0,0 +1,473 @@ +// +// 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; + } + + var parent = System.IO.Directory.GetParent(LocalPath).FullName.TrimEnd('/', '\\'); + + Mask = Compute.MaskHash(parent); + + var maskedPath = LocalPath.ReplaceFirst(parent, Mask); + + var aliasedSegment = LocalPath[(parent.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/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs new file mode 100644 index 00000000..b912bbda --- /dev/null +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -0,0 +1,331 @@ +// +// 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.Transfers.API +{ + using System; + using System.ComponentModel.DataAnnotations; + using System.IO; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using slskd.Integrations.FTP; + using Soulseek; + + /// + /// Transfers. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class TransfersController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + public TransfersController( + IOptionsSnapshot options, + ISoulseekClient soulseekClient, + ITransferTracker tracker, + IFTPService ftpClient) + { + Client = soulseekClient; + Tracker = tracker; + Options = options.Value; + FTP = ftpClient; + } + + private Options Options { get; } + private ISoulseekClient Client { get; } + private ITransferTracker Tracker { get; } + private IFTPService FTP { get; } + + /// + /// Cancels the specified download. + /// + /// The username of the download source. + /// The id of the download. + /// A value indicating whether the tracked download should be removed after cancellation. + /// + /// The download was cancelled successfully. + /// The specified download was not found. + [HttpDelete("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + { + return CancelTransfer(TransferDirection.Download, username, id, remove); + } + + /// + /// Cancels the specified upload. + /// + /// The username of the upload destination. + /// The id of the upload. + /// A value indicating whether the tracked upload should be removed after cancellation. + /// + /// The upload was cancelled successfully. + /// The specified upload was not found. + [HttpDelete("uploads/{username}/{id}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + { + return CancelTransfer(TransferDirection.Upload, username, id, remove); + } + + /// + /// Enqueues the specified download. + /// + /// The username of the download source. + /// The download request. + /// + /// The download was successfully enqueued. + /// The download was rejected. + /// An unexpected error was encountered. + [HttpPost("downloads/{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 500)] + public async Task Enqueue([FromRoute, Required]string username, [FromBody]QueueDownloadRequest request) + { + try + { + var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var stream = GetLocalFileStream(request.Filename, Options.Directories.Incomplete); + + var cts = new CancellationTokenSource(); + + var downloadTask = Task.Run(async () => + { + await Client.DownloadAsync(username, request.Filename, stream, request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => + { + Tracker.AddOrUpdate(e, cts); + + if (e.Transfer.State == TransferStates.Queued || e.Transfer.State == TransferStates.Initializing) + { + waitUntilEnqueue.TrySetResult(true); + } + }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token); + + MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); + + if (Options.Integration.FTP.Enabled) + { + _ = FTP.UploadAsync(request.Filename.ToLocalFilename(Options.Directories.Downloads)); + } + }); + + // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the + // downloadTask throws due to an error prior to successfully queueing. + var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); + + if (task == downloadTask) + { + if (downloadTask.Exception is AggregateException) + { + var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); + if (rejected.Any()) + { + return StatusCode(403, rejected.First().Message); + } + } + + return StatusCode(500, downloadTask.Exception.Message); + } + + // if it didn't throw, just return ok. the download will continue waiting in the background. + return StatusCode(201); + } + catch (Exception ex) + { + return StatusCode(500, ex.Message); + } + } + + /// + /// Gets all downloads. + /// + /// + /// The request completed successfully. + [HttpGet("downloads")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetDownloads() + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Download) + .ToMap()); + } + + /// + /// Gets all downloads for the specified username. + /// + /// + /// + /// The request completed successfully. + [HttpGet("downloads/{username}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetDownloads([FromRoute, Required]string username) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Download) + .FromUser(username) + .ToMap()); + } + + /// + /// Gets the downlaod for the specified username matching the specified filename, and requests + /// the current place in the remote queue of the specified download. + /// + /// The username of the download source. + /// The id of the download. + /// + /// The request completed successfully. + /// The specified download was not found. + [HttpGet("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(404)] + public async Task GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) + { + var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id); + + if (record == default) + { + return NotFound(); + } + + record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename); + return Ok(record.Transfer); + } + + /// + /// Gets all uploads. + /// + /// + /// The request completed successfully. + [HttpGet("uploads")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads() + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .ToMap()); + } + + /// + /// Gets all uploads for the specified username. + /// + /// + /// + /// The request completed successfully. + [HttpGet("uploads/{username}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads([FromRoute, Required]string username) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .FromUser(username) + .ToMap()); + } + + /// + /// Gets the upload for the specified username matching the specified filename. + /// + /// The username of the upload destination. + /// The id of the upload. + /// + /// The request completed successfully. + [HttpGet("uploads/{username}/{id}")] + [Authorize] + [ProducesResponseType(200)] + public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id) + { + return Ok(Tracker.Transfers + .WithDirection(TransferDirection.Upload) + .FromUser(username) + .WithId(id).Transfer); + } + + private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) + { + var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); + var path = Path.GetDirectoryName(localFilename); + + if (!System.IO.Directory.Exists(path)) + { + System.IO.Directory.CreateDirectory(path); + } + + return new FileStream(localFilename, FileMode.Create); + } + + private static void MoveFile(string filename, string sourceDirectory, string destinationDirectory) + { + var sourceFilename = filename.ToLocalFilename(sourceDirectory); + var destinationFilename = filename.ToLocalFilename(destinationDirectory); + + var destinationPath = Path.GetDirectoryName(destinationFilename); + + if (!System.IO.Directory.Exists(destinationPath)) + { + System.IO.Directory.CreateDirectory(destinationPath); + } + + System.IO.File.Move(sourceFilename, destinationFilename, overwrite: true); + + if (!System.IO.Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + { + System.IO.Directory.Delete(Path.GetDirectoryName(sourceFilename)); + } + } + + private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false) + { + if (Tracker.TryGet(direction, username, id, out var transfer)) + { + transfer.CancellationTokenSource.Cancel(); + + if (remove) + { + Tracker.TryRemove(direction, username, id); + } + + return NoContent(); + } + + return NotFound(); + } + } +} \ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs new file mode 100644 index 00000000..5e8807c2 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs @@ -0,0 +1,37 @@ +// +// 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.Transfers.API +{ + public class QueueDownloadRequest + { + /// + /// Gets or sets the filename to download. + /// + public string Filename { get; set; } + + /// + /// Gets or sets the size of the file. + /// + public long? Size { get; set; } + + /// + /// Gets or sets the optional transfer token. + /// + public int? Token { get; set; } + } +} diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs new file mode 100644 index 00000000..8465fd1d --- /dev/null +++ b/src/slskd/Transfers/API/DTO/Transfer.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/. +// + +namespace slskd.Transfers.API +{ + using System; + using System.Net; + using Soulseek; + + /// + /// A single file transfer. + /// + public class Transfer + { + /// + /// Gets the current average transfer speed. + /// + public double AverageSpeed { get; set; } + + /// + /// Gets the number of remaining bytes to be transferred. + /// + public long BytesRemaining { get; set; } + + /// + /// Gets the total number of bytes transferred. + /// + public long BytesTransferred { get; set; } + + /// + /// Gets the transfer direction. + /// + public TransferDirection Direction { get; set; } + + /// + /// Gets the current duration of the transfer, if it has been started. + /// + public double? ElapsedTime { get; set; } + + /// + /// Gets the UTC time at which the transfer transitioned into the state. + /// + public DateTime? EndTime { get; set; } + + /// + /// Gets the filename of the file to be transferred. + /// + public string Filename { get; set; } + + /// + /// Gets the transfer id. + /// + public string Id => Compute.Sha1Hash(Filename); + + /// + /// Gets the ip endpoint of the remote transfer connection, if one has been established. + /// + public IPEndPoint IPEndPoint { get; set; } + + /// + /// Gets the current progress in percent. + /// + public double PercentComplete { get; set; } + + /// + /// Gets the current place in queue, if it has been fetched. + /// + public int? PlaceInQueue { get; set; } + + /// + /// Gets the projected remaining duration of the transfer. + /// + public double? RemainingTime { get; set; } + + /// + /// Gets the remote unique token for the transfer. + /// + public int? RemoteToken { get; set; } + + /// + /// Gets the size of the file to be transferred, in bytes. + /// + public long Size { get; set; } + + /// + /// Gets the starting offset of the transfer, in bytes. + /// + public long StartOffset { get; set; } + + /// + /// Gets the UTC time at which the transfer transitioned into the state. + /// + public DateTime? StartTime { get; set; } + + /// + /// Gets the state of the transfer. + /// + public TransferStates State { get; set; } + + /// + /// Gets the unique token for the transfer. + /// + public int Token { get; set; } + + /// + /// Gets the username of the peer to or from which the file is to be transferred. + /// + public string Username { get; set; } + + public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) + { + return new Transfer() + { + AverageSpeed = transfer.AverageSpeed, + BytesRemaining = transfer.BytesRemaining, + BytesTransferred = transfer.BytesTransferred, + Direction = transfer.Direction, + ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, + EndTime = transfer.EndTime, + Filename = transfer.Filename, + IPEndPoint = transfer.IPEndPoint, + PercentComplete = transfer.PercentComplete, + RemainingTime = transfer.RemainingTime?.TotalMilliseconds, + RemoteToken = transfer.RemoteToken, + Size = transfer.Size, + StartOffset = transfer.StartOffset, + StartTime = transfer.StartTime, + State = transfer.State, + Token = transfer.Token, + Username = transfer.Username, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Transfers/ITransferTracker.cs b/src/slskd/Transfers/ITransferTracker.cs new file mode 100644 index 00000000..4edbdd63 --- /dev/null +++ b/src/slskd/Transfers/ITransferTracker.cs @@ -0,0 +1,57 @@ +// +// 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.Transfers +{ + using System.Collections.Concurrent; + using System.Threading; + using Soulseek; + + /// + /// Tracks transfers. + /// + public interface ITransferTracker + { + /// + /// Tracked transfers. + /// + ConcurrentDictionary>> Transfers { get; } + + /// + /// Adds or updates a tracked transfer. + /// + /// + /// + void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource); + + /// + /// Removes a tracked transfer. + /// + /// Omitting an id will remove ALL transfers associated with the specified username. + void TryRemove(TransferDirection direction, string username, string id = null); + + /// + /// Gets the specified transfer. + /// + /// + /// + /// + /// + /// + bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); + } +} \ No newline at end of file diff --git a/src/slskd/Transfers/TransferTracker.cs b/src/slskd/Transfers/TransferTracker.cs new file mode 100644 index 00000000..d70717dd --- /dev/null +++ b/src/slskd/Transfers/TransferTracker.cs @@ -0,0 +1,192 @@ +// +// 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.Transfers +{ + using System.Collections.Concurrent; + using System.Linq; + using System.Threading; + using Soulseek; + + /// + /// Transfer extensions. + /// + public static class TransferTrackerExtensions + { + /// + /// Filters a Transfer collection by user. + /// + /// + /// + /// + public static ConcurrentDictionary FromUser( + this ConcurrentDictionary> directedTransfers, + string username) + { + directedTransfers.TryGetValue(username, out var transfers); + return transfers ?? new ConcurrentDictionary(); + } + + /// + /// Maps a Transfer collection to a serializable object. + /// + /// + /// + public static object ToMap( + this ConcurrentDictionary> directedTransfers) + { + return directedTransfers.Select(u => new + { + Username = u.Key, + Directories = u.Value.Values + .GroupBy(f => f.Transfer.Filename.DirectoryName()) + .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }), + }); + } + + /// + /// Maps a Transfer collection to a serializable object. + /// + /// + /// + public static object ToMap( + this ConcurrentDictionary userTransfers) + { + return userTransfers.Values + .GroupBy(f => f.Transfer.Filename.DirectoryName()) + .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }); + } + + /// + /// Filters a Transfer collection by direction. + /// + /// + /// + /// + public static ConcurrentDictionary> WithDirection( + this ConcurrentDictionary>> allTransfers, + TransferDirection direction) + { + allTransfers.TryGetValue(direction, out var transfers); + return transfers ?? new ConcurrentDictionary>(); + } + + /// + /// Retrieves a Transfer from a Transfer collection by id. + /// + /// + /// + /// + public static (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( + this ConcurrentDictionary userTransfers, + string id) + { + userTransfers.TryGetValue(id, out var transfer); + return transfer; + } + } + + /// + /// Tracks transfers. + /// + public class TransferTracker : ITransferTracker + { + /// + /// Initializes a new instance of the class. + /// + public TransferTracker() + { + Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary>()); + Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary>()); + } + + /// + /// Gets tracked transfers. + /// + public ConcurrentDictionary>> Transfers { get; private set; } = + new ConcurrentDictionary>>(); + + /// + /// Adds or updates a tracked transfer. + /// + /// + /// + public void AddOrUpdate(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) + { + Transfers.TryGetValue(args.Transfer.Direction, out var direction); + + direction.AddOrUpdate(args.Transfer.Username, GetNewDictionaryForUser(args, cancellationTokenSource), (user, dict) => + { + var transfer = API.Transfer.FromSoulseekTransfer(args.Transfer); + dict.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, cancellationTokenSource)); + return dict; + }); + } + + /// + /// Gets the specified transfer. + /// + /// + /// + /// + /// + /// + public bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer) + { + transfer = default; + + if (Transfers.TryGetValue(direction, out var transfers) && transfers.TryGetValue(username, out var user) && user.TryGetValue(id, out transfer)) + { + return true; + } + + return false; + } + + /// + /// Removes a tracked transfer. + /// + /// Omitting an id will remove ALL transfers associated with the specified username. + public void TryRemove(TransferDirection direction, string username, string id = null) + { + Transfers.TryGetValue(direction, out var directionDict); + + if (string.IsNullOrEmpty(id)) + { + directionDict.TryRemove(username, out _); + } + else + { + directionDict.TryGetValue(username, out var userDict); + userDict.TryRemove(id, out _); + + if (userDict.IsEmpty) + { + directionDict.TryRemove(username, out _); + } + } + } + + private ConcurrentDictionary GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) + { + var r = new ConcurrentDictionary(); + var transfer = API.Transfer.FromSoulseekTransfer(args.Transfer); + r.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, record.CancellationTokenSource)); + return r; + } + } +} \ No newline at end of file diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs new file mode 100644 index 00000000..e7eb5256 --- /dev/null +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -0,0 +1,171 @@ +// +// 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.Users.API +{ + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.Net; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// + /// Users. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class UsersController : ControllerBase + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public UsersController(ISoulseekClient soulseekClient, IBrowseTracker browseTracker, IUserService peerService) + { + Client = soulseekClient; + BrowseTracker = browseTracker; + Peers = peerService; + } + + private IBrowseTracker BrowseTracker { get; } + private ISoulseekClient Client { get; } + private IUserService Peers { get; } + + /// + /// Retrieves the address of the specified . + /// + /// The username of the user. + /// + /// The request completed successfully. + [HttpGet("{username}/endpoint")] + [Authorize] + [ProducesResponseType(typeof(IPEndPoint), 200)] + [ProducesResponseType(404)] + public async Task Endpoint([FromRoute, Required] string username) + { + try + { + var endpoint = await Peers.GetIPEndPointAsync(username); + return Ok(endpoint); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// + /// Retrieves the files shared by the specified . + /// + /// The username of the user. + /// + [HttpGet("{username}/browse")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(404)] + public async Task Browse([FromRoute, Required] string username) + { + try + { + var result = await Client.BrowseAsync(username); + + _ = Task.Run(async () => + { + await Task.Delay(5000); + BrowseTracker.TryRemove(username); + }); + + return Ok(result); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// + /// Retrieves the status of the current browse operation for the specified , if any. + /// + /// The username of the user. + /// + [HttpGet("{username}/browse/status")] + [Authorize] + [ProducesResponseType(typeof(decimal), 200)] + [ProducesResponseType(404)] + public IActionResult BrowseStatus([FromRoute, Required] string username) + { + if (BrowseTracker.TryGet(username, out var progress)) + { + return Ok(progress); + } + + return NotFound(); + } + + /// + /// Retrieves information about the specified . + /// + /// The username of the user. + /// Bypasses the internal cache and requests the latest information from the peer. + /// + [HttpGet("{username}/info")] + [Authorize] + [ProducesResponseType(typeof(Info), 200)] + [ProducesResponseType(404)] + public async Task Info([FromRoute, Required] string username, [FromQuery]bool bypassCache = false) + { + try + { + var response = await Peers.GetInfoAsync(username, bypassCache); + return Ok(response); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// + /// Retrieves status for the specified . + /// + /// The username of the user. + /// + [HttpGet("{username}/status")] + [Authorize] + [ProducesResponseType(typeof(Status), 200)] + [ProducesResponseType(404)] + public async Task Status([FromRoute, Required] string username) + { + try + { + var response = await Peers.GetStatusAsync(username); + return Ok(response); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + } +} \ No newline at end of file diff --git a/src/slskd/Users/API/DTO/UserDataResponse.cs b/src/slskd/Users/API/DTO/UserDataResponse.cs new file mode 100644 index 00000000..664b1276 --- /dev/null +++ b/src/slskd/Users/API/DTO/UserDataResponse.cs @@ -0,0 +1,85 @@ +// +// 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.Users.API +{ + using Soulseek; + + public class UserDataResponse + { + /// + /// The average upload speed of the user. + /// + public int AverageSpeed { get; set; } + + /// + /// The user's country code, if provided. + /// + public string CountryCode { get; set; } + + /// + /// The number of directories shared by the user. + /// + public int DirectoryCount { get; set; } + + /// + /// The number of files shared by the user. + /// + public int FileCount { get; set; } + + /// + /// A value indicating whether this user data belongs to the currently logged in user. + /// + public bool? Self { get; set; } + + /// + /// The number of the user's free download slots, if provided. + /// + public int? SlotsFree { get; set; } + + /// + /// The status of the user (0 = offline, 1 = away, 2 = online). + /// + public UserPresence Status { get; set; } + + /// + /// The number of uploads tracked by the server for the user. + /// + public long UploadCount { get; set; } + + /// + /// The username of the user. + /// + public string Username { get; set; } + + public static UserDataResponse FromUserData(UserData userData, bool self = false) + { + return new UserDataResponse() + { + AverageSpeed = userData.AverageSpeed, + CountryCode = userData.CountryCode, + DirectoryCount = userData.DirectoryCount, + UploadCount = userData.UploadCount, + FileCount = userData.FileCount, + SlotsFree = userData.SlotsFree, + Status = userData.Status, + Username = userData.Username, + Self = self ? self : (bool?)null, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Users/BrowseTracker.cs b/src/slskd/Users/BrowseTracker.cs new file mode 100644 index 00000000..57c7c1d8 --- /dev/null +++ b/src/slskd/Users/BrowseTracker.cs @@ -0,0 +1,57 @@ +// +// 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.Users +{ + using System.Collections.Concurrent; + using Soulseek; + + /// + /// Tracks browse operations. + /// + public class BrowseTracker : IBrowseTracker + { + /// + /// Tracked browse operations. + /// + public ConcurrentDictionary Browses { get; } = new ConcurrentDictionary(); + + /// + /// Adds or updates a tracked browse operation. + /// + /// + /// + public void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress) + => Browses.AddOrUpdate(username, progress, (user, oldprogress) => progress); + + /// + /// Removes a tracked browse operation for the specified user. + /// + /// + public void TryRemove(string username) + => Browses.TryRemove(username, out _); + + /// + /// Gets the browse progress for the specified user. + /// + /// + /// + /// + public bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress) + => Browses.TryGetValue(username, out progress); + } +} diff --git a/src/slskd/Users/Domain/Info.cs b/src/slskd/Users/Domain/Info.cs new file mode 100644 index 00000000..aaf19942 --- /dev/null +++ b/src/slskd/Users/Domain/Info.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.Users +{ + using System; + using System.ComponentModel.DataAnnotations; + using Soulseek; + + public class Info + { + [Key] + public string Username { get; init; } + public string Description { get; init; } + public bool HasFreeUploadSlot { get; init; } + public bool HasPicture { get; init; } + public byte[] Picture { get; init; } + public int QueueLength { get; init; } + public int UploadSlots { get; init; } + public DateTime UpdatedAt { get; init; } + + public static Info FromSoulseekUserInfo(string username, UserInfo info) + { + return new Info() + { + Username = username, + Description = info.Description, + HasFreeUploadSlot = info.HasFreeUploadSlot, + HasPicture = info.HasPicture, + Picture = info.Picture, + QueueLength = info.QueueLength, + UploadSlots = info.UploadSlots, + UpdatedAt = DateTime.UtcNow, + }; + } + } +} diff --git a/src/slskd/Users/Domain/Status.cs b/src/slskd/Users/Domain/Status.cs new file mode 100644 index 00000000..41452e66 --- /dev/null +++ b/src/slskd/Users/Domain/Status.cs @@ -0,0 +1,36 @@ +// +// 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.Users +{ + using Soulseek; + + public class Status + { + public bool IsPrivileged { get; init; } + public UserPresence Presence { get; init; } + + public static Status FromSoulseekUserStatus(UserStatus status) + { + return new Status() + { + IsPrivileged = status.IsPrivileged, + Presence = status.Presence, + }; + } + } +} diff --git a/src/slskd/Users/IBrowseTracker.cs b/src/slskd/Users/IBrowseTracker.cs new file mode 100644 index 00000000..29ed06b3 --- /dev/null +++ b/src/slskd/Users/IBrowseTracker.cs @@ -0,0 +1,54 @@ +// +// 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.Users +{ + using System.Collections.Concurrent; + using Soulseek; + + /// + /// Tracks browse operations. + /// + public interface IBrowseTracker + { + /// + /// Tracked browse operations. + /// + ConcurrentDictionary Browses { get; } + + /// + /// Adds or updates a tracked browse operation. + /// + /// + /// + void AddOrUpdate(string username, BrowseProgressUpdatedEventArgs progress); + + /// + /// Gets the browse progress for the specified user. + /// + /// + /// + /// + bool TryGet(string username, out BrowseProgressUpdatedEventArgs progress); + + /// + /// Removes a tracked browse operation for the specified user. + /// + /// + void TryRemove(string username); + } +} \ No newline at end of file diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs new file mode 100644 index 00000000..469acef6 --- /dev/null +++ b/src/slskd/Users/IUserService.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.Users +{ + using System.Net; + using System.Threading.Tasks; + + /// + /// Provides information and operations for network peers. + /// + public interface IUserService + { + /// + /// Retrieves peer . + /// + /// The username of the peer. + /// A value indicating whether the local cache should be bypassed. + /// The cached or retrieved info. + Task GetInfoAsync(string username, bool bypassCache = false); + + /// + /// Retrieves a peer's IP endpoint, including their IP address and listen port. + /// + /// The username of the peer. + /// The retrieved endpoint. + Task GetIPEndPointAsync(string username); + + /// + /// Retrieves the current of a peer. + /// + /// The username of the peer. + /// The retrieved status. + Task GetStatusAsync(string username); + + /// + /// Grants the specified peer the specified number of privilege days. + /// + /// The username of the peer. + /// The number of days to grant. + /// The operation context. + Task GrantPrivilegesAsync(string username, int days); + + /// + /// Retrieves a value indicating whether the specified peer is privileged. + /// + /// The username of the peer. + /// A value indicating whether the specified peer is privileged. + Task IsPrivilegedAsync(string username); + + /// + /// Adds the specified username to the server-side user list. + /// + /// The username of the peer. + /// The operation context. + Task WatchAsync(string username); + } +} \ No newline at end of file diff --git a/src/slskd/Users/UserDbContext.cs b/src/slskd/Users/UserDbContext.cs new file mode 100644 index 00000000..4d0fd08c --- /dev/null +++ b/src/slskd/Users/UserDbContext.cs @@ -0,0 +1,32 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Users +{ + using Microsoft.EntityFrameworkCore; + + public class UserDbContext : DbContext + { + public UserDbContext(DbContextOptions options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet Info { get; set; } + } +} diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs new file mode 100644 index 00000000..f52f19f1 --- /dev/null +++ b/src/slskd/Users/UserService.cs @@ -0,0 +1,138 @@ +// +// 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.Users +{ + using System; + using System.Net; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.Logging; + using Soulseek; + + /// + /// Provides information and operations for network peers. + /// + public class UserService : IUserService + { + private const int CacheTTLSeconds = 300; + + /// + /// Initializes a new instance of the class. + /// + /// + /// The database context to use. + /// The logger. + public UserService( + ISoulseekClient soulseekClient, + IDbContextFactory contextFactory, + ILogger log) + { + Client = soulseekClient; + ContextFactory = contextFactory; + Log = log; + } + + private ISoulseekClient Client { get; } + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; set; } + + /// + /// Retrieves peer . + /// + /// The username of the peer. + /// A value indicating whether the local cache should be bypassed. + /// The cached or retrieved info. + public async Task GetInfoAsync(string username, bool bypassCache = false) + { + using var context = ContextFactory.CreateDbContext(); + + var info = await context.Info.AsNoTracking().FirstOrDefaultAsync(peer => peer.Username == username); + var peerExists = info != default; + + if (!bypassCache && peerExists && info.UpdatedAt < DateTime.UtcNow.AddSeconds(CacheTTLSeconds)) + { + return info; + } + + var soulseekUserInfo = await Client.GetUserInfoAsync(username); + info = Info.FromSoulseekUserInfo(username, soulseekUserInfo); + + if (peerExists) + { + context.Update(info); + } + else + { + context.Add(info); + } + + await context.SaveChangesAsync(); + + return info; + } + + /// + /// Retrieves a peer's IP endpoint, including their IP address and listen port. + /// + /// The username of the peer. + /// The retrieved endpoint. + public Task GetIPEndPointAsync(string username) + { + return Client.GetUserEndPointAsync(username); + } + + /// + /// Retrieves the current of a peer. + /// + /// The username of the peer. + /// The retrieved status. + public async Task GetStatusAsync(string username) + { + var soulseekStatus = await Client.GetUserStatusAsync(username); + + return Status.FromSoulseekUserStatus(soulseekStatus); + } + + /// + /// Grants the specified peer the specified number of privilege days. + /// + /// The username of the peer. + /// The number of days to grant. + /// The operation context. + public Task GrantPrivilegesAsync(string username, int days) + => Client.GrantUserPrivilegesAsync(username, days); + + /// + /// Retrieves a value indicating whether the specified peer is privileged. + /// + /// The username of the peer. + /// A value indicating whether the specified peer is privileged. + public Task IsPrivilegedAsync(string username) + => Client.GetUserPrivilegedAsync(username); + + /// + /// Adds the specified username to the server-side user list. + /// + /// The username of the peer. + /// The operation context. + public async Task WatchAsync(string username) + { + await Client.AddUserAsync(username); + } + } +} \ No newline at end of file -- cgit v1.2.3