diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-09-22 08:33:20 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-09-22 08:33:20 -0500 |
| commit | bc17beab782c8c9b9c04035a31c435d4d9c42596 (patch) | |
| tree | e20377685a358a977639531fc037405a74cb87d9 /src | |
| parent | 597b44ff36d68a7263b7df60bc9a666994e5f82b (diff) | |
| parent | 1d50171490d6d4dbc025ef25bfbb373bc8a5331b (diff) | |
| download | slskd-bc17beab782c8c9b9c04035a31c435d4d9c42596.tar.gz | |
Merge pull request #202 from slskd/cleanup
General refactoring and removal of technical debt
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs (renamed from src/slskd/Application/Application.cs) | 680 | ||||
| -rw-r--r-- | src/slskd/Application/IApplication.cs | 27 | ||||
| -rw-r--r-- | src/slskd/Application/ISharedFileCache.cs | 68 | ||||
| -rw-r--r-- | src/slskd/Application/Management/IManagementService.cs | 62 | ||||
| -rw-r--r-- | src/slskd/Application/Management/ManagementService.cs | 102 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/ApplicationShutdownException.cs (renamed from src/slskd/Application/Exceptions/ApplicationShutdownException.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/IntentionalDisconnectException.cs (renamed from src/slskd/Application/Exceptions/IntentionalDisconnectException.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/RetryException.cs (renamed from src/slskd/Application/Exceptions/RetryException.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/ShareAliasException.cs (renamed from src/slskd/Application/Exceptions/ShareAliasException.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/ShareScanInProgressException.cs (renamed from src/slskd/Application/Exceptions/ShareScanInProgressException.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/SlskdException.cs (renamed from src/slskd/Application/Exceptions/SlskdException.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Common/Extensions.cs | 30 | ||||
| -rw-r--r-- | src/slskd/Common/IStateMonitor.cs | 47 | ||||
| -rw-r--r-- | src/slskd/Common/ManagedState.cs | 231 | ||||
| -rw-r--r-- | src/slskd/Common/StateMonitor.cs | 102 | ||||
| -rw-r--r-- | src/slskd/Common/UserEndPointCache.cs (renamed from src/slskd/Application/UserEndPointCache.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ApplicationController.cs (renamed from src/slskd/Application/Management/API/Controllers/ApplicationController.cs) | 16 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ConfigurationController.cs (renamed from src/slskd/Application/Management/API/Controllers/ConfigurationController.cs) | 16 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/OptionsController.cs (renamed from src/slskd/Application/Management/API/Controllers/OptionsController.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ServerController.cs (renamed from src/slskd/Application/Management/API/Controllers/ServerController.cs) | 27 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/SessionController.cs (renamed from src/slskd/Application/Management/API/Controllers/SessionController.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Core/API/DTO/LoginRequest.cs (renamed from src/slskd/Application/Management/API/DTO/LoginRequest.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Core/API/DTO/ServerState.cs (renamed from src/slskd/Application/Management/API/DTO/ServerState.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Core/API/DTO/TokenResponse.cs (renamed from src/slskd/Application/Management/API/DTO/TokenResponse.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Core/API/Hubs/ApplicationHub.cs | 51 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/ConversationsController.cs (renamed from src/slskd/Application/Messaging/API/Controllers/ConversationsController.cs) | 19 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/PublicChatController.cs (renamed from src/slskd/Application/Messaging/API/Controllers/PublicChatController.cs) | 4 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/RoomsController.cs (renamed from src/slskd/Application/Messaging/API/Controllers/RoomsController.cs) | 22 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs (renamed from src/slskd/Application/Messaging/API/DTO/PrivateMessageResponse.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/RoomInfoResponse.cs (renamed from src/slskd/Application/Messaging/API/DTO/RoomInfoResponse.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/RoomMessageResponse.cs (renamed from src/slskd/Application/Messaging/API/DTO/RoomMessageResponse.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/RoomResponse.cs (renamed from src/slskd/Application/Messaging/API/DTO/RoomResponse.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/UserDataResponse.cs (renamed from src/slskd/Application/Messaging/API/DTO/UserDataResponse.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/ConversationTracker.cs (renamed from src/slskd/Application/Messaging/ConversationTracker.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/Domain/PrivateMessage.cs (renamed from src/slskd/Application/Messaging/Domain/PrivateMessage.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/Domain/Room.cs (renamed from src/slskd/Application/Messaging/Domain/Room.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/Domain/RoomMessage.cs (renamed from src/slskd/Application/Messaging/Domain/RoomMessage.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/IConversationTracker.cs (renamed from src/slskd/Application/Messaging/IConversationTracker.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/IRoomTracker.cs (renamed from src/slskd/Application/Messaging/IRoomTracker.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Messaging/RoomService.cs | 218 | ||||
| -rw-r--r-- | src/slskd/Messaging/RoomTracker.cs (renamed from src/slskd/Application/Messaging/RoomTracker.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Options.cs | 6 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Properties/slskd.yml | 1 | ||||
| -rw-r--r-- | src/slskd/Search/API/Controllers/SearchesController.cs (renamed from src/slskd/Application/Search/API/Controllers/SearchesController.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/API/DTO/SearchRequest.cs (renamed from src/slskd/Application/Search/API/DTO/SearchRequest.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/Domain/File.cs (renamed from src/slskd/Application/Search/Domain/File.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/Domain/Response.cs (renamed from src/slskd/Application/Search/Domain/Response.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/Domain/Search.cs (renamed from src/slskd/Application/Search/Domain/Search.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/Extensions.cs (renamed from src/slskd/Application/Search/Extensions.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/ISearchService.cs (renamed from src/slskd/Application/Search/ISearchService.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/SearchDbContext.cs (renamed from src/slskd/Application/Search/SearchDbContext.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/SearchResponseCache.cs (renamed from src/slskd/Application/Search/SearchResponseCache.cs) | 0 | ||||
| -rw-r--r-- | src/slskd/Search/SearchService.cs (renamed from src/slskd/Application/Search/SearchService.cs) | 8 | ||||
| -rw-r--r-- | src/slskd/Shares/SharedFileCache.cs (renamed from src/slskd/Application/SharedFileCache.cs) | 52 | ||||
| -rw-r--r-- | src/slskd/Startup.cs | 60 | ||||
| -rw-r--r-- | src/slskd/State.cs (renamed from src/slskd/Application/ApplicationState.cs) | 6 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/Controllers/TransfersController.cs (renamed from src/slskd/Application/Transfer/API/Controllers/TransfersController.cs) | 8 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs (renamed from src/slskd/Application/Transfer/API/DTO/QueueDownloadRequest.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/DTO/Transfer.cs (renamed from src/slskd/Application/Transfer/API/DTO/Transfer.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/ITransferTracker.cs (renamed from src/slskd/Application/Transfer/ITransferTracker.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/TransferTracker.cs (renamed from src/slskd/Application/Transfer/TransferTracker.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Users/API/Controllers/UsersController.cs (renamed from src/slskd/Application/Peer/API/Controllers/PeersController.cs) | 16 | ||||
| -rw-r--r-- | src/slskd/Users/API/DTO/UserDataResponse.cs (renamed from src/slskd/Application/Peer/API/DTO/UserDataResponse.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Users/BrowseTracker.cs (renamed from src/slskd/Application/Peer/BrowseTracker.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Users/Domain/Info.cs (renamed from src/slskd/Application/Peer/Domain/Info.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Users/Domain/Status.cs (renamed from src/slskd/Application/Peer/Domain/Status.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Users/IBrowseTracker.cs (renamed from src/slskd/Application/Peer/IBrowseTracker.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Users/IUserService.cs (renamed from src/slskd/Application/Peer/IPeerService.cs) | 6 | ||||
| -rw-r--r-- | src/slskd/Users/UserDbContext.cs (renamed from src/slskd/Application/Peer/PeerDbContext.cs) | 8 | ||||
| -rw-r--r-- | src/slskd/Users/UserService.cs (renamed from src/slskd/Application/Peer/PeerService.cs) | 26 | ||||
| -rw-r--r-- | src/slskd/slskd.csproj | 2 | ||||
| -rw-r--r-- | src/web/src/components/Browse/Browse.js | 6 | ||||
| -rw-r--r-- | src/web/src/components/Users/Users.js | 8 | ||||
| -rw-r--r-- | src/web/src/lib/users.js (renamed from src/web/src/lib/peers.js) | 10 |
75 files changed, 1045 insertions, 930 deletions
diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application.cs index 6b95c779..dfdd2d78 100644 --- a/src/slskd/Application/Application.cs +++ b/src/slskd/Application.cs @@ -15,44 +15,56 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Options; + namespace slskd { using System; using System.Collections.Concurrent; - using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Threading; using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Hosting; - using Microsoft.Extensions.Options; using Serilog; using Serilog.Events; using slskd.Configuration; + using slskd.Core.API; using slskd.Integrations.Pushbullet; using slskd.Messaging; - using slskd.Peer; using slskd.Search; - using slskd.Transfer; + using slskd.Shares; + using slskd.Transfers; + using slskd.Users; using Soulseek; using Soulseek.Diagnostics; - public class Application : IApplication + 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<Options> optionsMonitor, - IStateMonitor<ApplicationState> stateMonitor, + IManagedState<State> state, + ISoulseekClient soulseekClient, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker, + IRoomService roomService, ISharedFileCache sharedFileCache, - IPushbulletService pushbulletService) + IPushbulletService pushbulletService, + IHubContext<ApplicationHub> applicationHub) { OptionsAtStartup = optionsAtStartup; @@ -61,57 +73,21 @@ namespace slskd PreviousOptions = OptionsMonitor.CurrentValue; - StateMonitor = stateMonitor; - StateMonitor.OnChange(state => StateMonitor_OnChange(state)); + State = state; + State.OnChange(state => State_OnChange(state)); SharedFileCache = sharedFileCache; - SharedFileCache.State.OnChange(state => SharedFileCacheState_OnChange(state)); + SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state)); TransferTracker = transferTracker; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; - RoomTracker = roomTracker; Pushbullet = pushbulletService; - 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 clientOptions = new SoulseekClientOptions( - listenPort: OptionsAtStartup.Soulseek.ListenPort, - enableListener: true, - userEndPointCache: new UserEndPointCache(), - distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit, - enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled, - minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel, - 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); + RoomService = roomService; + ApplicationHub = applicationHub; - Client = new SoulseekClient(options: clientOptions); + Client = soulseekClient; Client.DiagnosticGenerated += Client_DiagnosticGenerated; @@ -129,81 +105,29 @@ namespace slskd Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; Client.RoomMessageReceived += Client_RoomMessageReceived; - Client.RoomJoined += Client_RoomJoined; - Client.RoomLeft += Client_RoomLeft; Client.Disconnected += Client_Disconnected; Client.Connected += Client_Connected; Client.LoggedIn += Client_LoggedIn; Client.StateChanged += Client_StateChanged; - - SoulseekClient = Client; } - public static ISoulseekClient SoulseekClient { get; private set; } - - private IBrowseTracker BrowseTracker { get; set; } 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<Application>(); private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); - private IOptionsMonitor<Options> OptionsMonitor { get; set; } private Options Options => OptionsMonitor.CurrentValue; private OptionsAtStartup OptionsAtStartup { get; set; } + private IOptionsMonitor<Options> OptionsMonitor { get; set; } + private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); private Options PreviousOptions { get; set; } - private IRoomTracker RoomTracker { get; set; } - private IStateMonitor<ApplicationState> StateMonitor { get; set; } - private ApplicationState State => StateMonitor.CurrentValue; - private ISharedFileCache SharedFileCache { get; set; } - private ITransferTracker TransferTracker { get; set; } private IPushbulletService Pushbullet { get; } - private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); + private ISharedFileCache SharedFileCache { get; set; } private DateTime SharesRefreshStarted { get; set; } - - public async Task StartAsync(CancellationToken cancellationToken) - { - Logger.Information("Client started"); - 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); - } - } - - public Task StopAsync(CancellationToken cancellationToken) - { - Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down")); - Client.Dispose(); - Logger.Information("Client stopped"); - return Task.CompletedTask; - } + private IManagedState<State> State { get; } + private ITransferTracker TransferTracker { get; set; } + private IHubContext<ApplicationHub> ApplicationHub { get; set; } /// <summary> /// Gets the version of the latest application release. @@ -228,12 +152,12 @@ namespace slskd if (latestVersion > Version.Parse(Program.InformationalVersion)) { - StateMonitor.SetValue(state => state with { Version = state.Version with { Latest = latestVersion.ToString(), IsUpdateAvailable = true } }); + 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 { - StateMonitor.SetValue(state => state with { Version = state.Version with { Latest = Program.InformationalVersion, IsUpdateAvailable = false } }); + State.SetValue(state => state with { Version = state.Version with { Latest = Program.InformationalVersion, IsUpdateAvailable = false } }); Logger.Information("Version {CurrentVersion} is up to date.", Program.InformationalVersion); } } @@ -244,193 +168,99 @@ namespace slskd } } - 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<T>(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); - - var requiresRestart = HasAttribute<RequiresRestartAttribute>(property); - var requiresReconnect = HasAttribute<RequiresReconnectAttribute>(property); - - Logger.Debug($"{fqn} changed from '{left.ToJson() ?? "<null>"}' to '{right.ToJson() ?? "<null>"}'{(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()) - { - StateMonitor.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()) - { - StateMonitor.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."); - _ = AutoJoinRoomsAsync(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; + /// <summary> + /// Re-scans shared directories. + /// </summary> + /// <returns>The operation context.</returns> + public Task RescanSharesAsync() => SharedFileCache.FillAsync(); - ProxyOptions proxyPatch = null; + async Task IHostedService.StartAsync(CancellationToken cancellationToken) + { + Logger.Information("Configuring client"); - if (connection.Proxy.Enabled) - { - proxyPatch = new ProxyOptions( - connection.Proxy.Address, - connection.Proxy.Port.Value, - connection.Proxy.Username, - connection.Proxy.Password); - } + ProxyOptions proxyOptions = default; - connectionPatch = new ConnectionOptions( - connection.Buffer.Read, - connection.Buffer.Write, - connection.Timeout.Connect, - connection.Timeout.Inactivity, - proxyOptions: proxyPatch); - } + 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 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); + 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); - Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson()); + 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); - soulseekRequiresReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); - } + 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) - { - StateMonitor.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."); - } + Logger.Information("Client configured"); + Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); - if (pendingRestart) - { - StateMonitor.SetValue(state => state with { PendingRestart = true }); - Logger.Information("One or more updated options requires an application restart to take effect."); - } + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) + { + Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}"); + } - Logger.Information("Options updated successfully."); + if (!OptionsAtStartup.NoVersionCheck) + { + _ = CheckVersionAsync(); } - catch (Exception ex) + + if (OptionsAtStartup.NoShareScan) { - Logger.Error(ex, "Failed to apply option update: {Message}", ex.Message); + Logger.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); } - finally + else { - PreviousOptions = OptionsMonitor.CurrentValue; - OptionsSyncRoot.ExitWriteLock(); + _ = SharedFileCache.FillAsync(); } - } - private void StateMonitor_OnChange((ApplicationState Previous, ApplicationState Current) state) - { - Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); - } - - private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) - { - if (!state.Previous.Filling && state.Current.Filling) + if (OptionsAtStartup.NoConnect) { - SharesRefreshStarted = DateTime.UtcNow; - - StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); - Logger.Information("Scanning shares"); + Logger.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled"); } - - var lastProgress = Math.Round(state.Previous.FillProgress * 100); - var currentProgress = Math.Round(state.Current.FillProgress * 100); - - if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) + else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) { - StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); - Logger.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, state.Current.Files); + Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); } - - if (state.Previous.Filling && !state.Current.Filling) + else { - StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); - - if (state.Current.Faulted) - { - Logger.Error("Failed to scan shares."); - } - else - { - StateMonitor.SetValue(s => s with { PendingShareRescan = false }); - Logger.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", state.Current.Directories, state.Current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); - - SharesRefreshStarted = default; - - if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) - { - _ = SoulseekClient.SetSharedCountsAsync(State.SharedFileCache.Directories, State.SharedFileCache.Files); - } - } + 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; + } + /// <summary> /// Creates and returns an instances of <see cref="BrowseResponse"/> in response to a remote request. /// </summary> @@ -450,6 +280,11 @@ namespace slskd 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 @@ -466,79 +301,11 @@ namespace slskd logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); } - private void Client_StateChanged(object sender, SoulseekClientStateChangedEventArgs e) - { - StateMonitor.SetValue(state => state with { Server = new ServerState() { Address = Client.Address, IPEndPoint = Client.IPEndPoint, State = Client.State, Username = Client.Username } }); - } - - private void Client_Connected(object sender, EventArgs e) - { - Logger.Information("Connected to the Soulseek server"); - } - - private async 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. - _ = SoulseekClient.SetSharedCountsAsync(State.SharedFileCache.Directories, State.SharedFileCache.Files); - - // rejoin any rooms that we might have been in during the previous session - await JoinRoomsAsync(RoomTracker.Rooms.Keys); - - // join the rooms configured for autojoin. always do this after rejoining has completed. - await AutoJoinRoomsAsync(OptionsMonitor.CurrentValue.Rooms); - } - - private Task AutoJoinRoomsAsync(string[] rooms) - { - // don't try to join rooms that we've already joined. the server returns no response in this case - // and the client believes the request has timed out. - var unjoined = rooms.Where(room => !RoomTracker.Rooms.ContainsKey(room)); - return JoinRoomsAsync(unjoined); - } - - private async Task JoinRoomsAsync(IEnumerable<string> roomNames) - { - var tasks = new List<Task>(); - - foreach (var room in roomNames) - { - tasks.Add(JoinRoomAsync(room)); - } - - try - { - await Task.WhenAll(tasks); - } - catch (Exception ex) - { - Logger.Debug(ex, "Caught Exception in JoinRoomsAsync"); - } - } - - private async Task JoinRoomAsync(string roomName) - { - Logger.Debug("Joining room {Room}", roomName); - - try - { - var data = await SoulseekClient.JoinRoomAsync(roomName); - Logger.Information("Joined room {Room}", roomName); - Logger.Debug("Room data for {Room}: {Info}", roomName, data.ToJson()); - } - catch (Exception ex) - { - Logger.Warning("Failed to join room {Room}: {Message}", roomName, ex.Message); - } - } - private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) { - if (State.PendingReconnect) + if (State.CurrentValue.PendingReconnect) { - StateMonitor.SetValue(state => state with { PendingReconnect = false }); + State.SetValue(state => state with { PendingReconnect = false }); } if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) @@ -583,8 +350,9 @@ namespace slskd 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. + // 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; } @@ -597,6 +365,15 @@ namespace slskd } } + 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)); @@ -618,24 +395,9 @@ namespace slskd } } - private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) - { - // this will fire when we join a room; track that through the join operation. - if (args.Username != Client.Username) - { - RoomTracker.TryAddUser(args.RoomName, args.UserData); - } - } - - private void Client_RoomLeft(object sender, RoomLeftEventArgs args) - { - 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); if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) { @@ -643,6 +405,11 @@ namespace slskd } } + 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()}] @@ -742,6 +509,143 @@ namespace slskd 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<T>(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); + + var requiresRestart = HasAttribute<RequiresRestartAttribute>(property); + var requiresReconnect = HasAttribute<RequiresReconnectAttribute>(property); + + Logger.Debug($"{fqn} changed from '{left.ToJson() ?? "<null>"}' to '{right.ToJson() ?? "<null>"}'{(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(); + } + } + /// <summary> /// Creates and returns a <see cref="Response"/> in response to the given <paramref name="query"/>. /// </summary> @@ -771,7 +675,7 @@ namespace slskd Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); return new SearchResponse( - SoulseekClient.Username, + Client.Username, token, freeUploadSlots: 1, uploadSpeed: 0, @@ -784,6 +688,56 @@ namespace slskd 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); + } + /// <summary> /// Creates and returns a <see cref="UserInfo"/> object in response to a remote request. /// </summary> diff --git a/src/slskd/Application/IApplication.cs b/src/slskd/Application/IApplication.cs deleted file mode 100644 index 45cf0a10..00000000 --- a/src/slskd/Application/IApplication.cs +++ /dev/null @@ -1,27 +0,0 @@ -// <copyright file="IApplication.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -namespace slskd -{ - using System.Threading.Tasks; - using Microsoft.Extensions.Hosting; - - public interface IApplication : IHostedService - { - public Task CheckVersionAsync(); - } -} diff --git a/src/slskd/Application/ISharedFileCache.cs b/src/slskd/Application/ISharedFileCache.cs deleted file mode 100644 index 93b836f3..00000000 --- a/src/slskd/Application/ISharedFileCache.cs +++ /dev/null @@ -1,68 +0,0 @@ -// <copyright file="ISharedFileCache.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -namespace slskd -{ - using System.Collections.Generic; - using System.Threading.Tasks; - using Soulseek; - - /// <summary> - /// Shared file cache. - /// </summary> - public interface ISharedFileCache - { - /// <summary> - /// Gets the cache state. - /// </summary> - IStateMonitor<SharedFileCacheState> State { get; } - - /// <summary> - /// Returns the contents of the cache. - /// </summary> - /// <returns>The contents of the cache.</returns> - IEnumerable<Directory> Browse(); - - /// <summary> - /// Scans the configured shares and fills the cache. - /// </summary> - /// <returns>The operation context.</returns> - Task FillAsync(); - - /// <summary> - /// Returns the contents of the specified <paramref name="directory"/>. - /// </summary> - /// <param name="directory">The directory for which the contents are to be listed.</param> - /// <returns>The contents of the directory.</returns> - Directory List(string directory); - - /// <summary> - /// Substitutes the mask in the specified <paramref name="filename"/> with the original path, if the mask is tracked - /// by the cache. - /// </summary> - /// <param name="filename">The fully qualified filename to unmask.</param> - /// <returns>The unmasked filename.</returns> - public string Resolve(string filename); - - /// <summary> - /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. - /// </summary> - /// <param name="query">The query for which to search.</param> - /// <returns>The matching files.</returns> - Task<IEnumerable<File>> SearchAsync(SearchQuery query); - } -}
\ No newline at end of file diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs deleted file mode 100644 index 9a06d961..00000000 --- a/src/slskd/Application/Management/IManagementService.cs +++ /dev/null @@ -1,62 +0,0 @@ -// <copyright file="IManagementService.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -namespace slskd.Management -{ - using System; - using System.Threading.Tasks; - - /// <summary> - /// Application and Soulseek client management. - /// </summary> - public interface IManagementService - { - /// <summary> - /// Gets the current state of the slskd service. - /// </summary> - ApplicationState ApplicationState { get; } - - /// <summary> - /// Gets the current state of the connection to the Soulseek server. - /// </summary> - ServerState ServerState { get; } - - /// <summary> - /// Gets the current state of the shared file cache. - /// </summary> - SharedFileCacheState SharedFileCacheState { get; } - - /// <summary> - /// Connects the Soulseek client to the server using the configured username and password. - /// </summary> - /// <returns>The operation context.</returns> - Task ConnectServerAsync(); - - /// <summary> - /// Disconnects the Soulseek client from the server. - /// </summary> - /// <param name="message">An optional message containing the reason for the disconnect.</param> - /// <param name="exception">An optional Exception to associate with the disconnect.</param> - void DisconnectServer(string message = null, Exception exception = null); - - /// <summary> - /// Re-scans shared directories. - /// </summary> - /// <returns>The operation context.</returns> - Task RescanSharesAsync(); - } -}
\ No newline at end of file diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs deleted file mode 100644 index 4319c9e3..00000000 --- a/src/slskd/Application/Management/ManagementService.cs +++ /dev/null @@ -1,102 +0,0 @@ -// <copyright file="ManagementService.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -using Microsoft.Extensions.Options; - -namespace slskd.Management -{ - using System; - using System.Threading.Tasks; - using Serilog; - using Soulseek; - - /// <summary> - /// Application and Soulseek client management. - /// </summary> - public class ManagementService : IManagementService - { - /// <summary> - /// Initializes a new instance of the <see cref="ManagementService"/> class. - /// </summary> - /// <param name="optionsMonitor">The options monitor used to derive application options.</param> - /// <param name="applicationStateMonitor">The state monitor for application service state.</param> - /// <param name="soulseekClient">The Soulseek client.</param> - /// <param name="sharedFileCache">The shared file cache.</param> - public ManagementService( - IOptionsMonitor<Options> optionsMonitor, - IStateMonitor<ApplicationState> applicationStateMonitor, - ISoulseekClient soulseekClient, - ISharedFileCache sharedFileCache) - { - OptionsMonitor = optionsMonitor; - ApplicationStateMonitor = applicationStateMonitor; - Client = soulseekClient; - SharedFileCache = sharedFileCache; - } - - private ILogger Log { get; } = Serilog.Log.ForContext<ManagementService>(); - - /// <summary> - /// Gets the current state of the slskd service. - /// </summary> - public ApplicationState ApplicationState => ApplicationStateMonitor.CurrentValue; - - /// <summary> - /// Gets the current state of the connection to the Soulseek server. - /// </summary> - public ServerState ServerState => - new ServerState() - { - Address = Client.Address, - IPEndPoint = Client.IPEndPoint, - State = Client.State, - Username = Client.Username, - }; - - /// <summary> - /// Gets the current state of the connection to the Soulseek server. - /// </summary> - public SharedFileCacheState SharedFileCacheState => SharedFileCache.State.CurrentValue; - - private ISoulseekClient Client { get; } - private Options Options => OptionsMonitor.CurrentValue; - private IOptionsMonitor<Options> OptionsMonitor { get; } - private IStateMonitor<ApplicationState> ApplicationStateMonitor { get; } - private ISharedFileCache SharedFileCache { get; } - - /// <summary> - /// Connects the Soulseek client to the server using the configured username and password. - /// </summary> - /// <returns>The operation context.</returns> - public Task ConnectServerAsync() - => Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); - - /// <summary> - /// Disconnects the Soulseek client from the server. - /// </summary> - /// <param name="message">An optional message containing the reason for the disconnect.</param> - /// <param name="exception">An optional Exception to associate with the disconnect.</param> - public void DisconnectServer(string message = null, Exception exception = null) - => Client.Disconnect(message, exception ?? new IntentionalDisconnectException(message)); - - /// <summary> - /// Re-scans shared directories. - /// </summary> - /// <returns>The operation context.</returns> - public Task RescanSharesAsync() => SharedFileCache.FillAsync(); - } -}
\ No newline at end of file diff --git a/src/slskd/Application/Exceptions/ApplicationShutdownException.cs b/src/slskd/Common/Exceptions/ApplicationShutdownException.cs index e30b5c79..e30b5c79 100644 --- a/src/slskd/Application/Exceptions/ApplicationShutdownException.cs +++ b/src/slskd/Common/Exceptions/ApplicationShutdownException.cs diff --git a/src/slskd/Application/Exceptions/IntentionalDisconnectException.cs b/src/slskd/Common/Exceptions/IntentionalDisconnectException.cs index d5293e63..d5293e63 100644 --- a/src/slskd/Application/Exceptions/IntentionalDisconnectException.cs +++ b/src/slskd/Common/Exceptions/IntentionalDisconnectException.cs diff --git a/src/slskd/Application/Exceptions/RetryException.cs b/src/slskd/Common/Exceptions/RetryException.cs index c688f377..c688f377 100644 --- a/src/slskd/Application/Exceptions/RetryException.cs +++ b/src/slskd/Common/Exceptions/RetryException.cs diff --git a/src/slskd/Application/Exceptions/ShareAliasException.cs b/src/slskd/Common/Exceptions/ShareAliasException.cs index 3047d0a9..3047d0a9 100644 --- a/src/slskd/Application/Exceptions/ShareAliasException.cs +++ b/src/slskd/Common/Exceptions/ShareAliasException.cs diff --git a/src/slskd/Application/Exceptions/ShareScanInProgressException.cs b/src/slskd/Common/Exceptions/ShareScanInProgressException.cs index 2e548930..2e548930 100644 --- a/src/slskd/Application/Exceptions/ShareScanInProgressException.cs +++ b/src/slskd/Common/Exceptions/ShareScanInProgressException.cs diff --git a/src/slskd/Application/Exceptions/SlskdException.cs b/src/slskd/Common/Exceptions/SlskdException.cs index 6b4cfc2a..6b4cfc2a 100644 --- a/src/slskd/Application/Exceptions/SlskdException.cs +++ b/src/slskd/Common/Exceptions/SlskdException.cs diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 077f5b17..4f2cf29f 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -89,36 +89,6 @@ namespace slskd } /// <summary> - /// Computes a stable/consistent hash code for strings. - /// </summary> - /// <remarks> - /// https://stackoverflow.com/questions/5154970/how-do-i-create-a-hashcode-in-net-c-for-a-string-that-is-safe-to-store-in-a - /// </remarks> - /// <param name="str">The string for which the hash code is to be computed.</param> - /// <returns>The hash code.</returns> - public static int GetStableHashCode(this string str) - { - unchecked - { - int hash1 = 5381; - int hash2 = hash1; - - for (int i = 0; i < str.Length && str[i] != '\0'; i += 2) - { - hash1 = ((hash1 << 5) + hash1) ^ str[i]; - if (i == str.Length - 1 || str[i + 1] == '\0') - { - break; - } - - hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; - } - - return hash1 + (hash2 * 1566083941); - } - } - - /// <summary> /// Determines whether the string is a valid regular expression. /// </summary> /// <param name="pattern">The string to validate.</param> diff --git a/src/slskd/Common/IStateMonitor.cs b/src/slskd/Common/IStateMonitor.cs deleted file mode 100644 index 813dbfd5..00000000 --- a/src/slskd/Common/IStateMonitor.cs +++ /dev/null @@ -1,47 +0,0 @@ -// <copyright file="IStateMonitor.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -namespace slskd -{ - using System; - - /// <summary> - /// Provideds observable management of state objects. - /// </summary> - /// <typeparam name="T">The type of the tracked state object.</typeparam> - public interface IStateMonitor<T> - { - /// <summary> - /// Gets the current application state. - /// </summary> - T CurrentValue { get; } - - /// <summary> - /// Registers a listener to be called whenever the tracked state changes. - /// </summary> - /// <param name="listener">Registers a listener to be called whenver state changes.</param> - /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> - IDisposable OnChange(Action<(T Previous, T Current)> listener); - - /// <summary> - /// Replaces the current state with the value resolved by the <paramref name="setter"/>. - /// </summary> - /// <param name="setter">Given the current state, resolves a new state value.</param> - /// <returns>The updated state.</returns> - T SetValue(Func<T, T> setter); - } -} diff --git a/src/slskd/Common/ManagedState.cs b/src/slskd/Common/ManagedState.cs new file mode 100644 index 00000000..bfde3c80 --- /dev/null +++ b/src/slskd/Common/ManagedState.cs @@ -0,0 +1,231 @@ +// <copyright file="ManagedState.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.Text.Json; + using Microsoft.Extensions.DependencyInjection; + + /// <summary> + /// Provides observable read access for state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IStateMonitor<T> + { + /// <summary> + /// Gets the current state. + /// </summary> + T CurrentValue { get; } + + /// <summary> + /// Registers a listener to be called whenever the tracked state changes. + /// </summary> + /// <param name="listener">Registers a listener to be called whenver state changes.</param> + /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> + IDisposable OnChange(Action<(T Previous, T Current)> listener); + } + + /// <summary> + /// Provides write access for state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IStateMutator<T> + { + /// <summary> + /// Replaces the current state with the value resolved by the <paramref name="setter"/>. + /// </summary> + /// <param name="setter">Given the current state, resolves a new state value.</param> + /// <returns>The updated state.</returns> + T SetValue(Func<T, T> setter); + } + + /// <summary> + /// Provides point-in-time read access for state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IStateSnapshot<out T> + { + /// <summary> + /// Gets the snapshotted state. + /// </summary> + T Value { get; } + } + + /// <summary> + /// Provides observable management of state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IManagedState<T> : IStateMonitor<T>, IStateMutator<T> + { + /// <summary> + /// Gets a point-in-time snapshot of the current state. + /// </summary> + IStateSnapshot<T> Snapshot { get; } + } + + /// <summary> + /// ManagedState extension methods. + /// </summary> + public static class ManagedStateExtensions + { + /// <summary> + /// <para> + /// Adds managed state of an object of the specified <typeparamref name="T"/> to the specified <see cref="IServiceCollection"/>. + /// </para> + /// <para> + /// <list type="bullet"> + /// <item>A singleton instance of <see cref="IManagedState{T}"/> to be used by instances requiring full control over the state</item> + /// <item>A singleton instance of <see cref="IStateMutator{T}"/> to be used by instances requiring the ability to mutate the state</item> + /// <item>A singleton instance of <see cref="IStateMonitor{T}"/> to be used by instances requiring observable read access to the state</item> + /// <item>A transient instance of <see cref="IStateSnapshot{T}"/> to be used by scoped or transient instances requiring the current state</item> + /// </list> + /// </para> + /// </summary> + /// <typeparam name="T">The type of the managed state object.</typeparam> + /// <param name="services">The IServiceCollection to which the managed state is to be added.</param> + /// <param name="setter">An optional anonymous function used to apply an initial state mutation.</param> + /// <returns>The IServiceCollection with managed state added.</returns> + public static IServiceCollection AddManagedState<T>(this IServiceCollection services, Func<T, T> setter = null) + where T : class + { + services.AddSingleton<IManagedState<T>, ManagedState<T>>(); + services.AddSingleton(services => + { + var monitor = (IStateMutator<T>)services.GetRequiredService<IManagedState<T>>(); + + if (setter != null) + { + monitor.SetValue(setter); + } + + return monitor; + }); + services.AddSingleton(services => (IStateMonitor<T>)services.GetRequiredService<IManagedState<T>>()); + services.AddTransient(services => services.GetRequiredService<IManagedState<T>>().Snapshot); + + return services; + } + } + + /// <summary> + /// Provides a point-in-time snapshot of state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public class StateSnapshot<T> : IStateSnapshot<T> + { + /// <summary> + /// Initializes a new instance of the <see cref="StateSnapshot{T}"/> class. + /// </summary> + /// <param name="value">The current value of the state.</param> + public StateSnapshot(T value) + { + Value = JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(value)); + } + + /// <summary> + /// Gets a snapshot of the current application state. + /// </summary> + public T Value { get; } + } + + /// <summary> + /// Provides observable management of state objects. + /// </summary> + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public class ManagedState<T> : IManagedState<T> + { + private event Action<(T, T)> Changed; + + /// <summary> + /// Gets the current application state. + /// </summary> + public T CurrentValue { get; private set; } = (T)Activator.CreateInstance(typeof(T)); + + /// <summary> + /// Gets a point-in-time snapshot of the current state. + /// </summary> + public IStateSnapshot<T> Snapshot => new StateSnapshot<T>(CurrentValue); + + private object Lock { get; } = new object(); + + /// <summary> + /// Registers a listener to be called whenever the stracked state changes. + /// </summary> + /// <param name="listener">Registers a listener to be called whenver state changes.</param> + /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> + public IDisposable OnChange(Action<(T Previous, T Current)> listener) + { + var disposable = new ManagedStateDisposable<T>(this, listener); + Changed += disposable.OnChange; + return disposable; + } + + /// <summary> + /// Replaces the current state with the value resolved by the <paramref name="setter"/>. + /// </summary> + /// <param name="setter">Given the current state, resolves a new state value.</param> + /// <returns>The updated state.</returns> + public T SetValue(Func<T, T> setter) + { + lock (Lock) + { + var previous = CurrentValue.ToJson().ToObject<T>(); + CurrentValue = setter(CurrentValue); + + Changed?.Invoke((previous, CurrentValue)); + return CurrentValue; + } + } + +#pragma warning disable CS0693 // Type parameter has the same name as the type parameter from outer type + private class ManagedStateDisposable<T> : IDisposable +#pragma warning restore CS0693 // Type parameter has the same name as the type parameter from outer type + { + public ManagedStateDisposable(ManagedState<T> stateMonitor, Action<(T Previous, T Current)> listener) + { + StateMonitor = stateMonitor; + Listener = listener; + } + + private bool Disposed { get; set; } + private Action<(T Previous, T Current)> Listener { get; } + private ManagedState<T> StateMonitor { get; } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + StateMonitor.Changed -= OnChange; + } + + Disposed = true; + } + } + } + } +} diff --git a/src/slskd/Common/StateMonitor.cs b/src/slskd/Common/StateMonitor.cs deleted file mode 100644 index 9397d9b2..00000000 --- a/src/slskd/Common/StateMonitor.cs +++ /dev/null @@ -1,102 +0,0 @@ -// <copyright file="StateMonitor.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -namespace slskd -{ - using System; - - /// <summary> - /// Provideds observable management of state objects. - /// </summary> - /// <typeparam name="T">The type of the tracked state object.</typeparam> - public class StateMonitor<T> : IStateMonitor<T> - { - private event Action<(T, T)> Changed; - - /// <summary> - /// Gets the current application state. - /// </summary> - public T CurrentValue { get; private set; } = (T)Activator.CreateInstance(typeof(T)); - - private object Lock { get; } = new object(); - - /// <summary> - /// Registers a listener to be called whenever the stracked state changes. - /// </summary> - /// <param name="listener">Registers a listener to be called whenver state changes.</param> - /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> - public IDisposable OnChange(Action<(T Previous, T Current)> listener) - { - var disposable = new StateTrackerDisposable<T>(this, listener); - Changed += disposable.OnChange; - return disposable; - } - - /// <summary> - /// Replaces the current state with the value resolved by the <paramref name="setter"/>. - /// </summary> - /// <param name="setter">Given the current state, resolves a new state value.</param> - /// <returns>The updated state.</returns> - public T SetValue(Func<T, T> setter) - { - lock (Lock) - { - var previous = CurrentValue.ToJson().ToObject<T>(); - CurrentValue = setter(CurrentValue); - - Changed?.Invoke((previous, CurrentValue)); - return CurrentValue; - } - } - -#pragma warning disable CS0693 // Type parameter has the same name as the type parameter from outer type - private class StateTrackerDisposable<T> : IDisposable -#pragma warning restore CS0693 // Type parameter has the same name as the type parameter from outer type - { - public StateTrackerDisposable(StateMonitor<T> stateMonitor, Action<(T Previous, T Current)> listener) - { - StateMonitor = stateMonitor; - Listener = listener; - } - - private bool Disposed { get; set; } - private Action<(T Previous, T Current)> Listener { get; } - private StateMonitor<T> StateMonitor { get; } - - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); - - protected virtual void Dispose(bool disposing) - { - if (!Disposed) - { - if (disposing) - { - StateMonitor.Changed -= OnChange; - } - - Disposed = true; - } - } - } - } -} diff --git a/src/slskd/Application/UserEndPointCache.cs b/src/slskd/Common/UserEndPointCache.cs index 29164cc4..29164cc4 100644 --- a/src/slskd/Application/UserEndPointCache.cs +++ b/src/slskd/Common/UserEndPointCache.cs diff --git a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index b3d43300..16cd68b9 100644 --- a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Management.API +namespace slskd.Core.API { using System; using System.Diagnostics; @@ -34,15 +34,18 @@ namespace slskd.Management.API [Consumes("application/json")] public class ApplicationController : ControllerBase { - public ApplicationController(IManagementService managementService, IHostApplicationLifetime lifetime, IApplication application) + public ApplicationController( + IHostApplicationLifetime lifetime, + IApplication application, + IStateMonitor<State> applicationStateMonitor) { - Management = managementService; Lifetime = lifetime; Application = application; + ApplicationStateMonitor = applicationStateMonitor; } private IApplication Application { get; } - private IManagementService Management { get; } + private IStateMonitor<State> ApplicationStateMonitor { get; } private IHostApplicationLifetime Lifetime { get; } /// <summary> @@ -53,7 +56,7 @@ namespace slskd.Management.API [Authorize] public IActionResult State() { - return Ok(Management.ApplicationState); + return Ok(ApplicationStateMonitor.CurrentValue); } /// <summary> @@ -106,8 +109,7 @@ namespace slskd.Management.API await Application.CheckVersionAsync(); } - var state = Management.ApplicationState; - return Ok(state.Version); + return Ok(ApplicationStateMonitor.CurrentValue.Version); } } } diff --git a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs b/src/slskd/Core/API/Controllers/ConfigurationController.cs index f2b90718..01c8bbc1 100644 --- a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs +++ b/src/slskd/Core/API/Controllers/ConfigurationController.cs @@ -17,11 +17,10 @@ using Microsoft.Extensions.Options; -namespace slskd.Management.API +namespace slskd.Core.API { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; - using slskd.Management; /// <summary> /// Configuration. @@ -34,15 +33,18 @@ namespace slskd.Management.API public class ConfigurationController : ControllerBase { public ConfigurationController( + IApplication application, IOptionsSnapshot<Options> optionsShapshot, - IManagementService managementService) + IStateMonitor<State> applicationStateMonitor) { + Application = application; OptionsShapshot = optionsShapshot; - ManagementService = managementService; + ApplicationStateMonitor = applicationStateMonitor; } - private IManagementService ManagementService { get; } + private IApplication Application { get; } private IOptionsSnapshot<Options> OptionsShapshot { get; } + private IStateMonitor<State> ApplicationStateMonitor { get; } [HttpGet] [Route("")] @@ -58,12 +60,12 @@ namespace slskd.Management.API [Authorize] public IActionResult RescanSharesAsync() { - if (ManagementService.SharedFileCacheState.Filling) + if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) { return Conflict("A share scan is already in progress."); } - _ = ManagementService.RescanSharesAsync(); + _ = Application.RescanSharesAsync(); return Ok(); } diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs index 6f6275d1..fb2057b9 100644 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ b/src/slskd/Core/API/Controllers/OptionsController.cs @@ -17,7 +17,7 @@ using Microsoft.Extensions.Options; -namespace slskd.Management.API +namespace slskd.Core.API { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; diff --git a/src/slskd/Application/Management/API/Controllers/ServerController.cs b/src/slskd/Core/API/Controllers/ServerController.cs index fc47f475..172333ec 100644 --- a/src/slskd/Application/Management/API/Controllers/ServerController.cs +++ b/src/slskd/Core/API/Controllers/ServerController.cs @@ -15,11 +15,14 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Management.API +using Microsoft.Extensions.Options; + +namespace slskd.Core.API { using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Soulseek; /// <summary> /// Server. @@ -32,12 +35,18 @@ namespace slskd.Management.API public class ServerController : ControllerBase { public ServerController( - IManagementService managementService) + ISoulseekClient soulseekClient, + IOptionsSnapshot<Options> optionsSnapshot, + IStateSnapshot<State> stateSnapshot) { - Management = managementService; + Client = soulseekClient; + OptionsSnapshot = optionsSnapshot; + StateSnapshot = stateSnapshot; } - private IManagementService Management { get; } + private ISoulseekClient Client { get; } + private IOptionsSnapshot<Options> OptionsSnapshot { get; } + private IStateSnapshot<State> StateSnapshot { get; } /// <summary> /// Connects the client. @@ -50,9 +59,9 @@ namespace slskd.Management.API [ProducesResponseType(403)] public async Task<IActionResult> Connect() { - if (!Management.ServerState.IsConnected) + if (!Client.State.HasFlag(SoulseekClientStates.Connected)) { - await Management.ConnectServerAsync(); + await Client.ConnectAsync(OptionsSnapshot.Value.Soulseek.Username, OptionsSnapshot.Value.Soulseek.Password); } return Ok(); @@ -70,9 +79,9 @@ namespace slskd.Management.API [ProducesResponseType(403)] public IActionResult Disconnect([FromBody] string message) { - if (Management.ServerState.IsConnected) + if (Client.State.HasFlag(SoulseekClientStates.Connected)) { - Management.DisconnectServer(message); + Client.Disconnect(message, new IntentionalDisconnectException(message)); } return NoContent(); @@ -90,7 +99,7 @@ namespace slskd.Management.API [ProducesResponseType(403)] public IActionResult Get() { - return Ok(Management.ServerState); + return Ok(StateSnapshot.Value.Server); } } }
\ No newline at end of file diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs index a9ae0188..5f20aa9f 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Core/API/Controllers/SessionController.cs @@ -17,7 +17,7 @@ using Microsoft.Extensions.Options; -namespace slskd.Management.API +namespace slskd.Core.API { using System; using System.Collections.Generic; diff --git a/src/slskd/Application/Management/API/DTO/LoginRequest.cs b/src/slskd/Core/API/DTO/LoginRequest.cs index d4b8dd75..0653847d 100644 --- a/src/slskd/Application/Management/API/DTO/LoginRequest.cs +++ b/src/slskd/Core/API/DTO/LoginRequest.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Management.API +namespace slskd.Core.API { public class LoginRequest { diff --git a/src/slskd/Application/Management/API/DTO/ServerState.cs b/src/slskd/Core/API/DTO/ServerState.cs index 80c1e856..ec0aa937 100644 --- a/src/slskd/Application/Management/API/DTO/ServerState.cs +++ b/src/slskd/Core/API/DTO/ServerState.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Management +namespace slskd.Core.API { using System.Net; using Soulseek; diff --git a/src/slskd/Application/Management/API/DTO/TokenResponse.cs b/src/slskd/Core/API/DTO/TokenResponse.cs index 21508b81..85992917 100644 --- a/src/slskd/Application/Management/API/DTO/TokenResponse.cs +++ b/src/slskd/Core/API/DTO/TokenResponse.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Management.API +namespace slskd.Core.API { using System; using System.IdentityModel.Tokens.Jwt; diff --git a/src/slskd/Core/API/Hubs/ApplicationHub.cs b/src/slskd/Core/API/Hubs/ApplicationHub.cs new file mode 100644 index 00000000..90dc469f --- /dev/null +++ b/src/slskd/Core/API/Hubs/ApplicationHub.cs @@ -0,0 +1,51 @@ +// <copyright file="ApplicationHub.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Core.API +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; + + /// <summary> + /// Extension methods for the application SignalR hub. + /// </summary> + public static class ApplicationHubExtensions + { + /// <summary> + /// Broadcast the present application state. + /// </summary> + /// <param name="hub">The hub.</param> + /// <param name="state">The state to broadcast.</param> + /// <returns>The operation context.</returns> + public static Task BroadcastStateAsync(this IHubContext<ApplicationHub> hub, State state) + { + return hub.Clients.All.SendAsync(Methods.State, state); + } + + private static class Methods + { + public static readonly string State = "STATE"; + } + } + + /// <summary> + /// The application SignalR hub. + /// </summary> + public class ApplicationHub : Hub + { + } +}
\ No newline at end of file diff --git a/src/slskd/Application/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index 2107ceb1..c4341ec1 100644 --- a/src/slskd/Application/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -38,15 +38,21 @@ namespace slskd.Messaging.API /// <summary> /// Initializes a new instance of the <see cref="ConversationsController"/> class. /// </summary> - /// <param name="client"></param> + /// <param name="soulseekClient"></param> + /// <param name="applicationStateMonotor"></param> /// <param name="tracker"></param> - public ConversationsController(ISoulseekClient client, IConversationTracker tracker) + public ConversationsController( + ISoulseekClient soulseekClient, + IStateMonitor<State> applicationStateMonotor, + IConversationTracker tracker) { - Client = client; + Client = soulseekClient; + ApplicationStateMonitor = applicationStateMonotor; Tracker = tracker; } private ISoulseekClient Client { get; } + private IStateMonitor<State> ApplicationStateMonitor { get; } private IConversationTracker Tracker { get; } /// <summary> @@ -146,7 +152,7 @@ namespace slskd.Messaging.API var response = Tracker.Conversations.ToDictionary( entry => entry.Key, entry => entry.Value - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username)) + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.Server.Username)) .OrderBy(m => m.Timestamp)); return Ok(response); @@ -168,7 +174,7 @@ namespace slskd.Messaging.API if (Tracker.TryGet(username, out var conversation)) { var response = conversation - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == Client.Username)) + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.Server.Username)) .OrderBy(m => m.Timestamp); return Ok(response); @@ -198,9 +204,10 @@ namespace slskd.Messaging.API await Client.SendPrivateMessageAsync(username, message); + // append the outgoing message to the tracker Tracker.AddOrUpdate(username, new PrivateMessage() { - Username = Client.Username, + Username = ApplicationStateMonitor.CurrentValue.Server.Username, Timestamp = DateTime.UtcNow, Message = message, Acknowledged = true, diff --git a/src/slskd/Application/Messaging/API/Controllers/PublicChatController.cs b/src/slskd/Messaging/API/Controllers/PublicChatController.cs index 6868d3fb..c30e08a8 100644 --- a/src/slskd/Application/Messaging/API/Controllers/PublicChatController.cs +++ b/src/slskd/Messaging/API/Controllers/PublicChatController.cs @@ -33,9 +33,9 @@ namespace slskd.Messaging.API [Consumes("application/json")] public class PublicChatController : ControllerBase { - public PublicChatController(ISoulseekClient client) + public PublicChatController(ISoulseekClient soulseekClient) { - Client = client; + Client = soulseekClient; } private ISoulseekClient Client { get; } diff --git a/src/slskd/Application/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs index 12789ef5..743df527 100644 --- a/src/slskd/Application/Messaging/API/Controllers/RoomsController.cs +++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs @@ -36,13 +36,21 @@ namespace slskd.Messaging.API [Consumes("application/json")] public class RoomsController : ControllerBase { - public RoomsController(ISoulseekClient client, IRoomTracker tracker) + public RoomsController( + ISoulseekClient soulseekClient, + IRoomService roomService, + IStateMonitor<State> applicationStateMonitor, + IRoomTracker tracker) { - Client = client; + Client = soulseekClient; + ApplicationStateMonitor = applicationStateMonitor; Tracker = tracker; + RoomService = roomService; } + private IRoomService RoomService { get; } private ISoulseekClient Client { get; } + private IStateMonitor<State> ApplicationStateMonitor { get; } private IRoomTracker Tracker { get; } /// <summary> @@ -164,7 +172,7 @@ namespace slskd.Messaging.API if (Tracker.TryGet(roomName, out var room)) { var response = room.Users - .Select(user => UserDataResponse.FromUserData(user, self: user.Username == Client.Username)); + .Select(user => UserDataResponse.FromUserData(user, self: user.Username == ApplicationStateMonitor.CurrentValue.Server.Username)); return Ok(response); } @@ -188,7 +196,7 @@ namespace slskd.Messaging.API if (Tracker.TryGet(roomName, out var room)) { var response = room.Messages - .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == Client.Username)); + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == ApplicationStateMonitor.CurrentValue.Server.Username)); return Ok(response); } @@ -241,7 +249,7 @@ namespace slskd.Messaging.API try { - var roomData = await Client.JoinRoomAsync(roomName); + var roomData = await RoomService.JoinAsync(roomName); var room = Room.FromRoomData(roomData); Tracker.TryAdd(roomName, room); @@ -276,7 +284,7 @@ namespace slskd.Messaging.API return StatusCode(StatusCodes.Status404NotFound); } - await Client.LeaveRoomAsync(roomName); + await RoomService.LeaveAsync(roomName); Tracker.TryRemove(roomName); return StatusCode(StatusCodes.Status204NoContent); @@ -286,7 +294,7 @@ namespace slskd.Messaging.API { bool IsSelf(string username) { - return username == Client.Username; + return username == ApplicationStateMonitor.CurrentValue.Server.Username; } var response = RoomResponse.FromRoom(room); diff --git a/src/slskd/Application/Messaging/API/DTO/PrivateMessageResponse.cs b/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs index a7e08d50..a7e08d50 100644 --- a/src/slskd/Application/Messaging/API/DTO/PrivateMessageResponse.cs +++ b/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs diff --git a/src/slskd/Application/Messaging/API/DTO/RoomInfoResponse.cs b/src/slskd/Messaging/API/DTO/RoomInfoResponse.cs index 46edbdc8..46edbdc8 100644 --- a/src/slskd/Application/Messaging/API/DTO/RoomInfoResponse.cs +++ b/src/slskd/Messaging/API/DTO/RoomInfoResponse.cs diff --git a/src/slskd/Application/Messaging/API/DTO/RoomMessageResponse.cs b/src/slskd/Messaging/API/DTO/RoomMessageResponse.cs index 965c63a6..965c63a6 100644 --- a/src/slskd/Application/Messaging/API/DTO/RoomMessageResponse.cs +++ b/src/slskd/Messaging/API/DTO/RoomMessageResponse.cs diff --git a/src/slskd/Application/Messaging/API/DTO/RoomResponse.cs b/src/slskd/Messaging/API/DTO/RoomResponse.cs index cf7e1478..cf7e1478 100644 --- a/src/slskd/Application/Messaging/API/DTO/RoomResponse.cs +++ b/src/slskd/Messaging/API/DTO/RoomResponse.cs diff --git a/src/slskd/Application/Messaging/API/DTO/UserDataResponse.cs b/src/slskd/Messaging/API/DTO/UserDataResponse.cs index 8f1e9544..8f1e9544 100644 --- a/src/slskd/Application/Messaging/API/DTO/UserDataResponse.cs +++ b/src/slskd/Messaging/API/DTO/UserDataResponse.cs diff --git a/src/slskd/Application/Messaging/ConversationTracker.cs b/src/slskd/Messaging/ConversationTracker.cs index 27d678ca..27d678ca 100644 --- a/src/slskd/Application/Messaging/ConversationTracker.cs +++ b/src/slskd/Messaging/ConversationTracker.cs diff --git a/src/slskd/Application/Messaging/Domain/PrivateMessage.cs b/src/slskd/Messaging/Domain/PrivateMessage.cs index 236632aa..236632aa 100644 --- a/src/slskd/Application/Messaging/Domain/PrivateMessage.cs +++ b/src/slskd/Messaging/Domain/PrivateMessage.cs diff --git a/src/slskd/Application/Messaging/Domain/Room.cs b/src/slskd/Messaging/Domain/Room.cs index 459dea2c..459dea2c 100644 --- a/src/slskd/Application/Messaging/Domain/Room.cs +++ b/src/slskd/Messaging/Domain/Room.cs diff --git a/src/slskd/Application/Messaging/Domain/RoomMessage.cs b/src/slskd/Messaging/Domain/RoomMessage.cs index 7a06a192..7a06a192 100644 --- a/src/slskd/Application/Messaging/Domain/RoomMessage.cs +++ b/src/slskd/Messaging/Domain/RoomMessage.cs diff --git a/src/slskd/Application/Messaging/IConversationTracker.cs b/src/slskd/Messaging/IConversationTracker.cs index 8e7a90f4..8e7a90f4 100644 --- a/src/slskd/Application/Messaging/IConversationTracker.cs +++ b/src/slskd/Messaging/IConversationTracker.cs diff --git a/src/slskd/Application/Messaging/IRoomTracker.cs b/src/slskd/Messaging/IRoomTracker.cs index 225e5f69..225e5f69 100644 --- a/src/slskd/Application/Messaging/IRoomTracker.cs +++ b/src/slskd/Messaging/IRoomTracker.cs 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 file="RoomService.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Messaging +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Serilog; + using Soulseek; + + /// <summary> + /// Chat room management and event handling. + /// </summary> + public interface IRoomService + { + /// <summary> + /// Joins the specfied <paramref name="roomName"/>. + /// </summary> + /// <param name="roomName">The name of the room to join.</param> + /// <returns>The operation context, including information about the room.</returns> + Task<RoomData> JoinAsync(string roomName); + + /// <summary> + /// Leaves the specified <paramref name="roomName"/>. + /// </summary> + /// <param name="roomName">The name of the room to leave.</param> + /// <returns>The operation context.</returns> + Task LeaveAsync(string roomName); + + /// <summary> + /// Attempts to join the specified <paramref name="roomNames"/>. + /// </summary> + /// <remarks> + /// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions. + /// </remarks> + /// <param name="roomNames">The list of room names to join.</param> + /// <returns>The operation context.</returns> + Task TryJoinAsync(params string[] roomNames); + } + + /// <summary> + /// Chat room management and event handling. + /// </summary> + public class RoomService : IRoomService + { + /// <summary> + /// Initializes a new instance of the <see cref="RoomService"/> class. + /// </summary> + /// <param name="soulseekClient"></param> + /// <param name="optionsMonitor"></param> + /// <param name="stateMutator"></param> + /// <param name="roomTracker"></param> + public RoomService( + ISoulseekClient soulseekClient, + IOptionsMonitor<Options> optionsMonitor, + IStateMutator<State> 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<RoomService>(); + private IStateMutator<State> StateMutator { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } + private IRoomTracker RoomTracker { get; set; } + + /// <summary> + /// Joins the specfied <paramref name="roomName"/>. + /// </summary> + /// <param name="roomName">The name of the room to join.</param> + /// <returns>The operation context, including information about the room.</returns> + public async Task<RoomData> 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; + } + } + + /// <summary> + /// Leaves the specified <paramref name="roomName"/>. + /// </summary> + /// <param name="roomName">The name of the room to leave.</param> + /// <returns>The operation context.</returns> + 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; + } + } + + /// <summary> + /// Attempts to join the specified <paramref name="roomNames"/>. + /// </summary> + /// <remarks> + /// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions. + /// </remarks> + /// <param name="roomNames">The list of room names to join.</param> + /// <returns>The operation context.</returns> + public async Task TryJoinAsync(params string[] roomNames) + { + var tasks = new List<Task>(); + + 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/Messaging/RoomTracker.cs index c586f401..c586f401 100644 --- a/src/slskd/Application/Messaging/RoomTracker.cs +++ b/src/slskd/Messaging/RoomTracker.cs diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 01eeacd7..b1e1a9a9 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -26,6 +26,7 @@ namespace slskd using System.Diagnostics; using System.IO; using System.Linq; + using System.Text.Json.Serialization; using System.Text.RegularExpressions; using FluentFTP; using slskd.Configuration; @@ -442,6 +443,7 @@ namespace slskd [EnvironmentVariable("SLSK_PASSWORD")] [Description("password for the Soulseek network")] [RequiresReconnect] + [JsonIgnore] public string Password { get; private set; } = null; /// <summary> @@ -592,6 +594,7 @@ namespace slskd [EnvironmentVariable("SLSK_PROXY_PASSWORD")] [Description("connection proxy password")] [StringLength(255, MinimumLength = 1)] + [JsonIgnore] public string Password { get; private set; } /// <summary> @@ -719,6 +722,7 @@ namespace slskd [EnvironmentVariable("PASSWORD")] [Description("password for web UI")] [StringLength(255, MinimumLength = 1)] + [JsonIgnore] public string Password { get; private set; } = Program.AppName; /// <summary> @@ -809,6 +813,7 @@ namespace slskd [EnvironmentVariable("HTTPS_CERT_PASSWORD")] [Description("X509 certificate password")] [RequiresRestart] + [JsonIgnore] public string Password { get; private set; } } } @@ -892,6 +897,7 @@ namespace slskd [Argument(default, "ftp-password")] [EnvironmentVariable("FTP_PASSWORD")] [Description("FTP password")] + [JsonIgnore] public string Password { get; private set; } /// <summary> diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index ec672f23..9590ed48 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -89,7 +89,7 @@ namespace slskd /// <remarks> /// Inaccurate when running locally. /// </remarks> - public static Version AssemblyVersion { get; } = Assembly.GetExecutingAssembly().GetName().Version.Equals(new Version(1,0,0,0)) ? new Version(0, 0, 0, 0) : Assembly.GetExecutingAssembly().GetName().Version; + public static Version AssemblyVersion { get; } = Assembly.GetExecutingAssembly().GetName().Version.Equals(new Version(1, 0, 0, 0)) ? new Version(0, 0, 0, 0) : Assembly.GetExecutingAssembly().GetName().Version; /// <summary> /// Gets the informational version of the application, including the git sha at the latest commit. diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index c1f1462e..b8450d35 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -54,6 +54,7 @@ # read: 16384 # write: 16384 # proxy: +# enabled: false # address: ~ # port: ~ # username: ~ diff --git a/src/slskd/Application/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 5f740044..5f740044 100644 --- a/src/slskd/Application/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs diff --git a/src/slskd/Application/Search/API/DTO/SearchRequest.cs b/src/slskd/Search/API/DTO/SearchRequest.cs index aad5a200..aad5a200 100644 --- a/src/slskd/Application/Search/API/DTO/SearchRequest.cs +++ b/src/slskd/Search/API/DTO/SearchRequest.cs diff --git a/src/slskd/Application/Search/Domain/File.cs b/src/slskd/Search/Domain/File.cs index 0a86eec3..0a86eec3 100644 --- a/src/slskd/Application/Search/Domain/File.cs +++ b/src/slskd/Search/Domain/File.cs diff --git a/src/slskd/Application/Search/Domain/Response.cs b/src/slskd/Search/Domain/Response.cs index ea2e8993..ea2e8993 100644 --- a/src/slskd/Application/Search/Domain/Response.cs +++ b/src/slskd/Search/Domain/Response.cs diff --git a/src/slskd/Application/Search/Domain/Search.cs b/src/slskd/Search/Domain/Search.cs index b93c62cb..b93c62cb 100644 --- a/src/slskd/Application/Search/Domain/Search.cs +++ b/src/slskd/Search/Domain/Search.cs diff --git a/src/slskd/Application/Search/Extensions.cs b/src/slskd/Search/Extensions.cs index 149e0a14..149e0a14 100644 --- a/src/slskd/Application/Search/Extensions.cs +++ b/src/slskd/Search/Extensions.cs diff --git a/src/slskd/Application/Search/ISearchService.cs b/src/slskd/Search/ISearchService.cs index d696617d..d696617d 100644 --- a/src/slskd/Application/Search/ISearchService.cs +++ b/src/slskd/Search/ISearchService.cs diff --git a/src/slskd/Application/Search/SearchDbContext.cs b/src/slskd/Search/SearchDbContext.cs index efb2fdd6..efb2fdd6 100644 --- a/src/slskd/Application/Search/SearchDbContext.cs +++ b/src/slskd/Search/SearchDbContext.cs diff --git a/src/slskd/Application/Search/SearchResponseCache.cs b/src/slskd/Search/SearchResponseCache.cs index c31a3a9b..c31a3a9b 100644 --- a/src/slskd/Application/Search/SearchResponseCache.cs +++ b/src/slskd/Search/SearchResponseCache.cs diff --git a/src/slskd/Application/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 8de18977..e529f738 100644 --- a/src/slskd/Application/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -28,7 +28,7 @@ namespace slskd.Search using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; - using ISoulseekClient = Soulseek.ISoulseekClient; + using Soulseek; using SearchOptions = Soulseek.SearchOptions; using SearchQuery = Soulseek.SearchQuery; using SearchScope = Soulseek.SearchScope; @@ -44,17 +44,17 @@ namespace slskd.Search /// Initializes a new instance of the <see cref="SearchService"/> class. /// </summary> /// <param name="optionsMonitor"></param> - /// <param name="client">The client instance to use.</param> + /// <param name="soulseekClient"></param> /// <param name="contextFactory">The database context to use.</param> /// <param name="log">The logger.</param> public SearchService( IOptionsMonitor<Options> optionsMonitor, - ISoulseekClient client, + ISoulseekClient soulseekClient, IDbContextFactory<SearchDbContext> contextFactory, ILogger<SearchService> log) { OptionsMonitor = optionsMonitor; - Client = client; + Client = soulseekClient; ContextFactory = contextFactory; Log = log; } diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 52c75ed1..79e9d5a5 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -18,7 +18,7 @@ using System.IO; using Microsoft.Extensions.Options; -namespace slskd +namespace slskd.Shares { using System; using System.Collections.Concurrent; @@ -35,6 +35,51 @@ namespace slskd /// <summary> /// Shared file cache. /// </summary> + public interface ISharedFileCache + { + /// <summary> + /// Gets the cache state monitor. + /// </summary> + IStateMonitor<SharedFileCacheState> StateMonitor { get; } + + /// <summary> + /// Returns the contents of the cache. + /// </summary> + /// <returns>The contents of the cache.</returns> + IEnumerable<Directory> Browse(); + + /// <summary> + /// Scans the configured shares and fills the cache. + /// </summary> + /// <returns>The operation context.</returns> + Task FillAsync(); + + /// <summary> + /// Returns the contents of the specified <paramref name="directory"/>. + /// </summary> + /// <param name="directory">The directory for which the contents are to be listed.</param> + /// <returns>The contents of the directory.</returns> + Directory List(string directory); + + /// <summary> + /// Substitutes the mask in the specified <paramref name="filename"/> with the original path, if the mask is tracked + /// by the cache. + /// </summary> + /// <param name="filename">The fully qualified filename to unmask.</param> + /// <returns>The unmasked filename.</returns> + public string Resolve(string filename); + + /// <summary> + /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. + /// </summary> + /// <param name="query">The query for which to search.</param> + /// <returns>The matching files.</returns> + Task<IEnumerable<File>> SearchAsync(SearchQuery query); + } + + /// <summary> + /// Shared file cache. + /// </summary> public class SharedFileCache : ISharedFileCache { /// <summary> @@ -48,10 +93,11 @@ namespace slskd } /// <summary> - /// Gets the cache state. + /// Gets the cache state monitor. /// </summary> - public IStateMonitor<SharedFileCacheState> State { get; } = new StateMonitor<SharedFileCacheState>(); + public IStateMonitor<SharedFileCacheState> StateMonitor => State; + private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>(); private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>(); private HashSet<string> MaskedDirectories { get; set; } private Dictionary<string, File> MaskedFiles { get; set; } diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 5c83fed3..47bbae68 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -34,15 +34,18 @@ namespace slskd using Prometheus.SystemMetrics; using Serilog; using slskd.Authentication; + using slskd.Core; + using slskd.Core.API; using slskd.Cryptography; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; - using slskd.Management; using slskd.Messaging; - using slskd.Peer; using slskd.Search; - using slskd.Transfer; + using slskd.Shares; + using slskd.Transfers; + using slskd.Users; using slskd.Validation; + using Soulseek; /// <summary> /// ASP.NET Startup. @@ -104,12 +107,13 @@ namespace slskd return true; }); - // add IStateMonitor instance to DI, to track application state in an observable way. - // similar to IOptionsMonitor, but state is managed by the application itself. - // Usage is roughly the same. - services.AddSingleton<IStateMonitor<ApplicationState>, StateMonitor<ApplicationState>>(); + services.AddManagedState<State>(); - services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); + services.AddCors(options => options.AddPolicy("AllowAll", builder => builder + .AllowAnyHeader() + .AllowAnyMethod() + .SetIsOriginAllowed((host) => true) + .AllowCredentials())); services.AddSingleton(JwtSigningKey); @@ -152,6 +156,12 @@ namespace slskd options.JsonSerializerOptions.IgnoreNullValues = true; }); + services.AddSignalR().AddJsonProtocol(options => + { + options.PayloadSerializerOptions.Converters.Add(new IPAddressConverter()); + options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); + services.AddHealthChecks(); services.AddApiVersioning(options => options.ReportApiVersions = true); @@ -195,13 +205,23 @@ namespace slskd options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "search.db")}"); }); - services.AddDbContextFactory<PeerDbContext>(options => + services.AddDbContextFactory<UserDbContext>(options => { - options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "peer.db")}"); + options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "users.db")}"); }); services.AddHttpClient(); + // add a partially configured instance of SoulseekClient. the Application instance will + // complete configuration at startup. + services.AddSingleton<ISoulseekClient, SoulseekClient>(_ => + new SoulseekClient(options: new SoulseekClientOptions(minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel))); + + // add the core application service to DI as well as a hosted service so that other services can + // access instance methods + services.AddSingleton<IApplication, Application>(); + services.AddHostedService(p => p.GetRequiredService<IApplication>()); + services.AddSingleton<ITransferTracker, TransferTracker>(); services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IConversationTracker, ConversationTracker>(); @@ -210,19 +230,13 @@ namespace slskd services.AddSingleton<ISharedFileCache, SharedFileCache>(); services.AddSingleton<ISearchService, SearchService>(); - services.AddSingleton<IPeerService, PeerService>(); - services.AddSingleton<IManagementService, ManagementService>(); + services.AddSingleton<IUserService, UserService>(); + services.AddSingleton<IRoomService, RoomService>(); services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); services.AddSingleton<IFTPService, FTPService>(); services.AddSingleton<IPushbulletService, PushbulletService>(); - - services.AddSingleton<IApplication, Application>(); - services.AddHostedService(p => p.GetRequiredService<IApplication>()); - - // todo: add public methods to Application until this is no longer necessary - services.AddSingleton(_ => Application.SoulseekClient); } /// <summary> @@ -270,7 +284,7 @@ namespace slskd FileServerOptions fileServerOptions = default; - if (!Directory.Exists(ContentPath)) + if (!System.IO.Directory.Exists(ContentPath)) { logger.Warning($"Static content disabled; cannot find content path '{ContentPath}'"); } @@ -302,12 +316,14 @@ namespace slskd app.UseAuthorization(); app.UseEndpoints(endpoints => { + endpoints.MapHub<ApplicationHub>("/hub/application"); + endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); if (OptionsAtStartup.Feature.Prometheus) { - endpoints.MapMetrics(); + endpoints.MapMetrics("/metrics"); } }); @@ -335,7 +351,7 @@ namespace slskd // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be // returned. otherwise it will throw a final 404 back to the client. - if (Directory.Exists(ContentPath)) + if (System.IO.Directory.Exists(ContentPath)) { app.UseFileServer(fileServerOptions); } @@ -354,7 +370,7 @@ namespace slskd try { using var search = GetFactory<SearchDbContext>().CreateDbContext(); - using var peer = GetFactory<PeerDbContext>().CreateDbContext(); + using var peer = GetFactory<UserDbContext>().CreateDbContext(); } catch (Exception ex) { diff --git a/src/slskd/Application/ApplicationState.cs b/src/slskd/State.cs index c9322eb3..bff2dc5b 100644 --- a/src/slskd/Application/ApplicationState.cs +++ b/src/slskd/State.cs @@ -1,4 +1,4 @@ -// <copyright file="ApplicationState.cs" company="slskd Team"> +// <copyright file="State.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -17,6 +17,7 @@ namespace slskd { + using System; using System.Net; using System.Text.Json.Serialization; using Soulseek; @@ -24,7 +25,7 @@ namespace slskd /// <summary> /// Application service state. /// </summary> - public record ApplicationState + public record State { public VersionState Version { get; init; } = new VersionState(); public bool PendingReconnect { get; init; } @@ -32,6 +33,7 @@ namespace slskd public bool PendingShareRescan { get; init; } public ServerState Server { get; init; } = new ServerState(); public SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState(); + public string[] Rooms { get; init; } = Array.Empty<string>(); } public record VersionState diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 9ed36d1b..b912bbda 100644 --- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -17,7 +17,7 @@ using Microsoft.Extensions.Options; -namespace slskd.Transfer.API +namespace slskd.Transfers.API { using System; using System.ComponentModel.DataAnnotations; @@ -44,16 +44,16 @@ namespace slskd.Transfer.API /// Initializes a new instance of the <see cref="TransfersController"/> class. /// </summary> /// <param name="options"></param> - /// <param name="client"></param> + /// <param name="soulseekClient"></param> /// <param name="tracker"></param> /// <param name="ftpClient"></param> public TransfersController( IOptionsSnapshot<Options> options, - ISoulseekClient client, + ISoulseekClient soulseekClient, ITransferTracker tracker, IFTPService ftpClient) { - Client = client; + Client = soulseekClient; Tracker = tracker; Options = options.Value; FTP = ftpClient; diff --git a/src/slskd/Application/Transfer/API/DTO/QueueDownloadRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs index 2ec88007..5e8807c2 100644 --- a/src/slskd/Application/Transfer/API/DTO/QueueDownloadRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Transfer.API +namespace slskd.Transfers.API { public class QueueDownloadRequest { diff --git a/src/slskd/Application/Transfer/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs index e182db1b..8465fd1d 100644 --- a/src/slskd/Application/Transfer/API/DTO/Transfer.cs +++ b/src/slskd/Transfers/API/DTO/Transfer.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Transfer.API +namespace slskd.Transfers.API { using System; using System.Net; diff --git a/src/slskd/Application/Transfer/ITransferTracker.cs b/src/slskd/Transfers/ITransferTracker.cs index 0dd41129..4edbdd63 100644 --- a/src/slskd/Application/Transfer/ITransferTracker.cs +++ b/src/slskd/Transfers/ITransferTracker.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Transfer +namespace slskd.Transfers { using System.Collections.Concurrent; using System.Threading; diff --git a/src/slskd/Application/Transfer/TransferTracker.cs b/src/slskd/Transfers/TransferTracker.cs index bf0a0bdb..d70717dd 100644 --- a/src/slskd/Application/Transfer/TransferTracker.cs +++ b/src/slskd/Transfers/TransferTracker.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Transfer +namespace slskd.Transfers { using System.Collections.Concurrent; using System.Linq; diff --git a/src/slskd/Application/Peer/API/Controllers/PeersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs index 94ce96dd..e7eb5256 100644 --- a/src/slskd/Application/Peer/API/Controllers/PeersController.cs +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -1,4 +1,4 @@ -// <copyright file="PeersController.cs" company="slskd Team"> +// <copyright file="UsersController.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer.API +namespace slskd.Users.API { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -33,24 +33,24 @@ namespace slskd.Peer.API [ApiController] [Produces("application/json")] [Consumes("application/json")] - public class PeersController : ControllerBase + public class UsersController : ControllerBase { /// <summary> - /// Initializes a new instance of the <see cref="PeersController"/> class. + /// Initializes a new instance of the <see cref="UsersController"/> class. /// </summary> - /// <param name="client"></param> + /// <param name="soulseekClient"></param> /// <param name="browseTracker"></param> /// <param name="peerService"></param> - public PeersController(ISoulseekClient client, IBrowseTracker browseTracker, IPeerService peerService) + public UsersController(ISoulseekClient soulseekClient, IBrowseTracker browseTracker, IUserService peerService) { - Client = client; + Client = soulseekClient; BrowseTracker = browseTracker; Peers = peerService; } private IBrowseTracker BrowseTracker { get; } private ISoulseekClient Client { get; } - private IPeerService Peers { get; } + private IUserService Peers { get; } /// <summary> /// Retrieves the address of the specified <paramref name="username"/>. diff --git a/src/slskd/Application/Peer/API/DTO/UserDataResponse.cs b/src/slskd/Users/API/DTO/UserDataResponse.cs index 5a8554df..664b1276 100644 --- a/src/slskd/Application/Peer/API/DTO/UserDataResponse.cs +++ b/src/slskd/Users/API/DTO/UserDataResponse.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer.API +namespace slskd.Users.API { using Soulseek; diff --git a/src/slskd/Application/Peer/BrowseTracker.cs b/src/slskd/Users/BrowseTracker.cs index 5fa6b14a..57c7c1d8 100644 --- a/src/slskd/Application/Peer/BrowseTracker.cs +++ b/src/slskd/Users/BrowseTracker.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer +namespace slskd.Users { using System.Collections.Concurrent; using Soulseek; diff --git a/src/slskd/Application/Peer/Domain/Info.cs b/src/slskd/Users/Domain/Info.cs index b2d17c8a..aaf19942 100644 --- a/src/slskd/Application/Peer/Domain/Info.cs +++ b/src/slskd/Users/Domain/Info.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer +namespace slskd.Users { using System; using System.ComponentModel.DataAnnotations; diff --git a/src/slskd/Application/Peer/Domain/Status.cs b/src/slskd/Users/Domain/Status.cs index 4db4e859..41452e66 100644 --- a/src/slskd/Application/Peer/Domain/Status.cs +++ b/src/slskd/Users/Domain/Status.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer +namespace slskd.Users { using Soulseek; diff --git a/src/slskd/Application/Peer/IBrowseTracker.cs b/src/slskd/Users/IBrowseTracker.cs index 606b8a45..29ed06b3 100644 --- a/src/slskd/Application/Peer/IBrowseTracker.cs +++ b/src/slskd/Users/IBrowseTracker.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer +namespace slskd.Users { using System.Collections.Concurrent; using Soulseek; diff --git a/src/slskd/Application/Peer/IPeerService.cs b/src/slskd/Users/IUserService.cs index f49cf27b..469acef6 100644 --- a/src/slskd/Application/Peer/IPeerService.cs +++ b/src/slskd/Users/IUserService.cs @@ -1,4 +1,4 @@ -// <copyright file="IPeerService.cs" company="slskd Team"> +// <copyright file="IUserService.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer +namespace slskd.Users { using System.Net; using System.Threading.Tasks; @@ -23,7 +23,7 @@ namespace slskd.Peer /// <summary> /// Provides information and operations for network peers. /// </summary> - public interface IPeerService + public interface IUserService { /// <summary> /// Retrieves peer <see cref="Info"/>. diff --git a/src/slskd/Application/Peer/PeerDbContext.cs b/src/slskd/Users/UserDbContext.cs index ee5dfd04..4d0fd08c 100644 --- a/src/slskd/Application/Peer/PeerDbContext.cs +++ b/src/slskd/Users/UserDbContext.cs @@ -1,4 +1,4 @@ -// <copyright file="PeerDbContext.cs" company="slskd Team"> +// <copyright file="UserDbContext.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,13 +15,13 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer +namespace slskd.Users { using Microsoft.EntityFrameworkCore; - public class PeerDbContext : DbContext + public class UserDbContext : DbContext { - public PeerDbContext(DbContextOptions<PeerDbContext> options) + public UserDbContext(DbContextOptions<UserDbContext> options) : base(options) { Database.EnsureCreated(); diff --git a/src/slskd/Application/Peer/PeerService.cs b/src/slskd/Users/UserService.cs index e0e03fa6..f52f19f1 100644 --- a/src/slskd/Application/Peer/PeerService.cs +++ b/src/slskd/Users/UserService.cs @@ -1,4 +1,4 @@ -// <copyright file="PeerService.cs" company="slskd Team"> +// <copyright file="UserService.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,41 +15,41 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Peer +namespace slskd.Users { using System; using System.Net; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; - using ISoulseekClient = Soulseek.ISoulseekClient; + using Soulseek; /// <summary> /// Provides information and operations for network peers. /// </summary> - public class PeerService : IPeerService + public class UserService : IUserService { private const int CacheTTLSeconds = 300; /// <summary> - /// Initializes a new instance of the <see cref="PeerService"/> class. + /// Initializes a new instance of the <see cref="UserService"/> class. /// </summary> - /// <param name="client">The client instance to use.</param> + /// <param name="soulseekClient"></param> /// <param name="contextFactory">The database context to use.</param> /// <param name="log">The logger.</param> - public PeerService( - ISoulseekClient client, - IDbContextFactory<PeerDbContext> contextFactory, - ILogger<PeerService> log) + public UserService( + ISoulseekClient soulseekClient, + IDbContextFactory<UserDbContext> contextFactory, + ILogger<UserService> log) { - Client = client; + Client = soulseekClient; ContextFactory = contextFactory; Log = log; } private ISoulseekClient Client { get; } - private IDbContextFactory<PeerDbContext> ContextFactory { get; } - private ILogger<PeerService> Log { get; set; } + private IDbContextFactory<UserDbContext> ContextFactory { get; } + private ILogger<UserService> Log { get; set; } /// <summary> /// Retrieves peer <see cref="Info"/>. diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index f2cde33f..3faf445a 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,7 @@ <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Soulseek" Version="3.0.0-pre-905211220" /> + <PackageReference Include="Soulseek" Version="3.0.0-pre-918211156" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> diff --git a/src/web/src/components/Browse/Browse.js b/src/web/src/components/Browse/Browse.js index 295b234e..30e4f556 100644 --- a/src/web/src/components/Browse/Browse.js +++ b/src/web/src/components/Browse/Browse.js @@ -1,5 +1,5 @@ import React, { Component } from 'react'; -import * as peers from '../../lib/peers'; +import * as users from '../../lib/users'; import './Browse.css'; @@ -40,7 +40,7 @@ class Browse extends Component { let username = this.inputtext.inputRef.current.value; this.setState({ username , browseState: 'pending', browseError: undefined }, () => { - peers.browse({ username }) + users.browse({ username }) .then(response => { let { directories, lockedDirectories } = response; @@ -116,7 +116,7 @@ class Browse extends Component { fetchStatus = () => { const { browseState, username } = this.state; if (browseState === 'pending') { - peers.getBrowseStatus({ username }) + users.getBrowseStatus({ username }) .then(response => this.setState({ browseStatus: response.data })); diff --git a/src/web/src/components/Users/Users.js b/src/web/src/components/Users/Users.js index ef92d0d5..d07772e7 100644 --- a/src/web/src/components/Users/Users.js +++ b/src/web/src/components/Users/Users.js @@ -8,7 +8,7 @@ import { import User from './User'; import { activeUserInfoKey } from '../../config'; -import * as peers from '../../lib/peers'; +import * as users from '../../lib/users'; import './Users.css'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; @@ -45,9 +45,9 @@ const Users = (props) => { try { const [info, status, endpoint] = await Promise.all([ - peers.getInfo({ username: selectedUsername, bypassCache: true }), - peers.getStatus({ username: selectedUsername }), - peers.getEndpoint({ username: selectedUsername }) + users.getInfo({ username: selectedUsername, bypassCache: true }), + users.getStatus({ username: selectedUsername }), + users.getEndpoint({ username: selectedUsername }) ]); localStorage.setItem(activeUserInfoKey, selectedUsername); diff --git a/src/web/src/lib/peers.js b/src/web/src/lib/users.js index 8cbc1c1b..a8cd4f88 100644 --- a/src/web/src/lib/peers.js +++ b/src/web/src/lib/users.js @@ -1,21 +1,21 @@ import api from './api'; export const getInfo = ({ username, bypassCache = false }) => { - return api.get(`/peers/${username}/info?bypassCache=${bypassCache}`); + return api.get(`/users/${username}/info?bypassCache=${bypassCache}`); }; export const getStatus = ({ username }) => { - return api.get(`/peers/${username}/status`); + return api.get(`/users/${username}/status`); }; export const getEndpoint = ({ username }) => { - return api.get(`/peers/${username}/endpoint`); + return api.get(`/users/${username}/endpoint`); }; export const browse = async ({ username }) => { - return (await api.get(`/peers/${username}/browse`)).data; + return (await api.get(`/users/${username}/browse`)).data; }; export const getBrowseStatus = ({ username }) => { - return api.get(`/peers/${username}/browse/status`); + return api.get(`/users/${username}/browse/status`); };
\ No newline at end of file |
