1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
|
// <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);
var room = Room.FromRoomData(data);
RoomTracker.TryAdd(roomName, room);
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);
}
}
}
|