//
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see https://www.gnu.org/licenses/.
//
using Microsoft.Extensions.Options;
namespace slskd.Messaging
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog;
using Soulseek;
///
/// Chat room management and event handling.
///
public interface IRoomService
{
///
/// Joins the specfied .
///
/// The name of the room to join.
/// The operation context, including information about the room.
Task JoinAsync(string roomName);
///
/// Leaves the specified .
///
/// The name of the room to leave.
/// The operation context.
Task LeaveAsync(string roomName);
///
/// Attempts to join the specified .
///
///
/// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions.
///
/// The list of room names to join.
/// The operation context.
Task TryJoinAsync(params string[] roomNames);
}
///
/// Chat room management and event handling.
///
public class RoomService : IRoomService
{
///
/// Initializes a new instance of the class.
///
///
///
///
///
public RoomService(
ISoulseekClient soulseekClient,
IOptionsMonitor optionsMonitor,
IStateMutator stateMutator,
IRoomTracker roomTracker)
{
Client = soulseekClient;
StateMutator = stateMutator;
OptionsMonitor = optionsMonitor;
RoomTracker = roomTracker;
Client.LoggedIn += Client_LoggedIn;
Client.RoomJoined += Client_RoomJoined;
Client.RoomLeft += Client_RoomLeft;
Client.RoomMessageReceived += Client_RoomMessageReceived;
}
private ISoulseekClient Client { get; }
private ILogger Logger { get; set; } = Log.ForContext();
private IStateMutator StateMutator { get; }
private IOptionsMonitor OptionsMonitor { get; }
private IRoomTracker RoomTracker { get; set; }
///
/// Joins the specfied .
///
/// The name of the room to join.
/// The operation context, including information about the room.
public async Task JoinAsync(string roomName)
{
Logger.Debug("Joining room {Room}", roomName);
try
{
var data = await Client.JoinRoomAsync(roomName);
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;
}
}
///
/// Leaves the specified .
///
/// The name of the room to leave.
/// The operation context.
public async Task LeaveAsync(string roomName)
{
Logger.Debug("Leaving room {Room}", roomName);
try
{
await Client.LeaveRoomAsync(roomName);
}
catch (Exception ex)
{
Logger.Warning("Failed to leave room {Room}: {Message}", roomName, ex.Message);
throw;
}
}
///
/// Attempts to join the specified .
///
///
/// Failures are logged but not thrown. Use JoinAsync() to trap Exceptions.
///
/// The list of room names to join.
/// The operation context.
public async Task TryJoinAsync(params string[] roomNames)
{
var tasks = new List();
foreach (var room in roomNames)
{
tasks.Add(JoinAsync(room));
}
try
{
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
Logger.Debug(ex, "Caught Exception in JoinAsync");
}
}
private async void Client_LoggedIn(object sender, EventArgs e)
{
var autoJoinRooms = OptionsMonitor.CurrentValue.Rooms;
if (autoJoinRooms.Any())
{
Logger.Information("Auto-joining room(s) {Rooms}", string.Join(", ", autoJoinRooms));
await TryJoinAsync(autoJoinRooms);
}
var previouslyJoinedRooms = RoomTracker.Rooms.Keys.Except(autoJoinRooms);
if (previouslyJoinedRooms.Any())
{
Logger.Information("Attempting to rejoin room(s) {Rooms}", string.Join(", ", previouslyJoinedRooms));
await TryJoinAsync(previouslyJoinedRooms.ToArray());
}
}
private void Client_RoomJoined(object sender, RoomJoinedEventArgs args)
{
if (args.Username == Client.Username)
{
Logger.Information("Joined room {Room}", args.RoomName);
StateMutator.SetValue(state => state with { Rooms = state.Rooms.Concat(new[] { args.RoomName }).Distinct().ToArray() });
}
else
{
RoomTracker.TryAddUser(args.RoomName, args.UserData);
}
}
private void Client_RoomLeft(object sender, RoomLeftEventArgs args)
{
if (args.Username == Client.Username)
{
Logger.Information("Left room {Room}", args.RoomName);
StateMutator.SetValue(state => state with { Rooms = state.Rooms.Where(room => room != args.RoomName).ToArray() });
}
else
{
RoomTracker.TryRemoveUser(args.RoomName, args.Username);
}
}
private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args)
{
var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow);
RoomTracker.AddOrUpdateMessage(args.RoomName, message);
}
}
}