From ca80897a3c56eec9ea367bd6c2b7262e306d3685 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 17 Sep 2021 09:50:37 -0500 Subject: move auto join and room tracking to RoomService --- src/slskd/Application/Application.cs | 55 +-------- src/slskd/Application/Messaging/RoomService.cs | 165 +++++++++++++++++++++---- 2 files changed, 144 insertions(+), 76 deletions(-) diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs index 98a1ecc2..b2f29fd2 100644 --- a/src/slskd/Application/Application.cs +++ b/src/slskd/Application/Application.cs @@ -19,7 +19,6 @@ namespace slskd { using System; using System.Collections.Concurrent; - using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; @@ -72,7 +71,6 @@ namespace slskd TransferTracker = transferTracker; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; - RoomTracker = roomTracker; Pushbullet = pushbulletService; RoomService = roomService; @@ -95,8 +93,6 @@ 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; @@ -115,7 +111,6 @@ namespace slskd private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } - private IRoomTracker RoomTracker { get; set; } private ISharedFileCache SharedFileCache { get; set; } private DateTime SharesRefreshStarted { get; set; } private IManagedState State { get; } @@ -253,14 +248,6 @@ namespace slskd return Task.CompletedTask; } - 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); - } - /// /// Creates and returns an instances of in response to a remote request. /// @@ -372,12 +359,6 @@ namespace slskd // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero // initially, but we'll update them when the cache is filled. _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files); - - // 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 void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -401,24 +382,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)) { @@ -530,25 +496,6 @@ namespace slskd return Task.CompletedTask; } - private async Task JoinRoomsAsync(IEnumerable roomNames) - { - var tasks = new List(); - - foreach (var room in roomNames) - { - tasks.Add(RoomService.JoinAsync(room)); - } - - try - { - await Task.WhenAll(tasks); - } - catch (Exception ex) - { - Logger.Debug(ex, "Caught Exception in JoinRoomsAsync"); - } - } - 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. @@ -601,7 +548,7 @@ namespace slskd || newOptions.Rooms.Except(PreviousOptions.Rooms).Any()) { Logger.Information("Room configuration changed. Joining any newly added rooms."); - _ = AutoJoinRoomsAsync(newOptions.Rooms); + _ = RoomService.TryJoinAsync(newOptions.Rooms); } // determine whether any Soulseek options changed. if so, we need to construct a patch and invoke ReconfigureOptionsAsync(). diff --git a/src/slskd/Application/Messaging/RoomService.cs b/src/slskd/Application/Messaging/RoomService.cs index 89fa4446..fde62c83 100644 --- a/src/slskd/Application/Messaging/RoomService.cs +++ b/src/slskd/Application/Messaging/RoomService.cs @@ -1,81 +1,202 @@ -namespace slskd.Messaging +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Messaging { using System; + using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Serilog; using Soulseek; + /// + /// Chat room management and event handling. + /// public interface IRoomService { - Task JoinAsync(string name); - Task LeaveAsync(string name); + /// + /// Joins the specfied . + /// + /// The name of the room to join. + /// The operation context, including information about the room. + Task JoinAsync(string roomName); + + /// + /// Leaves the specified . + /// + /// The name of the room to leave. + /// The operation context. + Task LeaveAsync(string roomName); + + /// + /// Attempts to join the specified . + /// + /// + /// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions. + /// + /// The list of room names to join. + /// The operation context. + Task TryJoinAsync(params string[] roomNames); } + /// + /// Chat room management and event handling. + /// public class RoomService : IRoomService { public RoomService( ISoulseekClient soulseekClient, - IStateMonitor stateMonitor, - IStateMutator stateMutator) + IOptionsMonitor optionsMonitor, + IStateMutator stateMutator, + IRoomTracker roomTracker) { Client = soulseekClient; - Monitor = stateMonitor; - Mutator = stateMutator; + StateMutator = stateMutator; + OptionsMonitor = optionsMonitor; + + RoomTracker = roomTracker; Client.RoomJoined += Client_RoomJoined; Client.RoomLeft += Client_RoomLeft; + Client.RoomMessageReceived += Client_RoomMessageReceived; + Client.LoggedIn += Client_LoggedIn; } private ISoulseekClient Client { get; } - private IStateMonitor Monitor { get; } - private IStateMutator Mutator { get; } private ILogger Logger { get; set; } = Log.ForContext(); + private IStateMutator StateMutator { get; } + private IOptionsMonitor OptionsMonitor { get; } + private IRoomTracker RoomTracker { get; set; } - public async Task JoinAsync(string name) + /// + /// Joins the specfied . + /// + /// The name of the room to join. + /// The operation context, including information about the room. + public async Task JoinAsync(string roomName) { - Logger.Debug("Joining room {Room}", name); + Logger.Debug("Joining room {Room}", roomName); try { - var data = await Client.JoinRoomAsync(name); + var data = await Client.JoinRoomAsync(roomName); - Mutator.SetValue(state => state with { Rooms = state.Rooms.Concat(new[] { name }).ToArray() }); + StateMutator.SetValue(state => state with { Rooms = state.Rooms.Concat(new[] { roomName }).Distinct().ToArray() }); - Logger.Information("Joined room {Room}", name); - Logger.Debug("Room data for {Room}: {Info}", name, data.ToJson()); + Logger.Information("Joined room {Room}", roomName); + Logger.Debug("Room data for {Room}: {Info}", roomName, data.ToJson()); return data; } catch (Exception ex) { - Logger.Warning("Failed to join room {Room}: {Message}", name, ex.Message); + Logger.Warning("Failed to join room {Room}: {Message}", roomName, ex.Message); throw; } } - public async Task LeaveAsync(string name) + /// + /// Leaves the specified . + /// + /// The name of the room to leave. + /// The operation context. + public async Task LeaveAsync(string roomName) { - Logger.Debug("Leaving room {Room}", name); + Logger.Debug("Leaving room {Room}", roomName); + try { - await Client.LeaveRoomAsync(name); + await Client.LeaveRoomAsync(roomName); - Mutator.SetValue(state => state with { Rooms = state.Rooms.Where(room => room != name).ToArray() }); + StateMutator.SetValue(state => state with { Rooms = state.Rooms.Where(room => room != roomName).ToArray() }); } catch (Exception ex) { - Logger.Warning("Failed to leave room {Room}: {Message}", name, ex.Message); + Logger.Warning("Failed to leave room {Room}: {Message}", roomName, ex.Message); throw; } } + /// + /// Attempts to join the specified . + /// + /// + /// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions. + /// + /// The list of room names to join. + /// The operation context. + public async Task TryJoinAsync(params string[] roomNames) + { + var tasks = new List(); + + foreach (var room in roomNames) + { + tasks.Add(JoinAsync(room)); + } + + try + { + await Task.WhenAll(tasks); + } + catch (Exception ex) + { + Logger.Debug(ex, "Caught Exception in JoinAsync"); + } + } + + private async void Client_LoggedIn(object sender, EventArgs e) + { + var autoJoinRooms = OptionsMonitor.CurrentValue.Rooms; + + if (autoJoinRooms.Any()) + { + Logger.Information("Auto-joining room(s) {Rooms}", string.Join(", ", autoJoinRooms)); + await TryJoinAsync(autoJoinRooms); + } + + var previouslyJoinedRooms = RoomTracker.Rooms.Keys.Except(autoJoinRooms); + + if (previouslyJoinedRooms.Any()) + { + Logger.Information("Attempting to rejoin room(s) {Rooms}", string.Join(", ", previouslyJoinedRooms)); + await TryJoinAsync(previouslyJoinedRooms.ToArray()); + } + } + private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) { + if (args.Username != Client.Username) + { + 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); } } -} +} \ No newline at end of file -- cgit v1.2.3