diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-09-21 08:28:11 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2021-09-21 08:28:11 -0500 |
| commit | 0eb773dbd4aa2fe971bc55e5c5f12413003296bb (patch) | |
| tree | 7e36184eb454ed8b0f5f0cbce07c53c191a0a3c1 /src/slskd/Messaging | |
| parent | 7387d568548af0898d9fd2b716d3bb16b6d9be2b (diff) | |
| download | slskd-0eb773dbd4aa2fe971bc55e5c5f12413003296bb.tar.gz | |
move stuff again
Diffstat (limited to 'src/slskd/Messaging')
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/ConversationsController.cs | 219 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/PublicChatController.cs | 67 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/RoomsController.cs | 309 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs | 74 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/RoomInfoResponse.cs | 60 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/RoomMessageResponse.cs | 62 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/RoomResponse.cs | 75 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/UserDataResponse.cs | 85 | ||||
| -rw-r--r-- | src/slskd/Messaging/ConversationTracker.cs | 62 | ||||
| -rw-r--r-- | src/slskd/Messaging/Domain/PrivateMessage.cs | 71 | ||||
| -rw-r--r-- | src/slskd/Messaging/Domain/Room.cs | 75 | ||||
| -rw-r--r-- | src/slskd/Messaging/Domain/RoomMessage.cs | 59 | ||||
| -rw-r--r-- | src/slskd/Messaging/IConversationTracker.cs | 55 | ||||
| -rw-r--r-- | src/slskd/Messaging/IRoomTracker.cs | 75 | ||||
| -rw-r--r-- | src/slskd/Messaging/RoomService.cs | 218 | ||||
| -rw-r--r-- | src/slskd/Messaging/RoomTracker.cs | 112 |
16 files changed, 1678 insertions, 0 deletions
diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs new file mode 100644 index 00000000..c4341ec1 --- /dev/null +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -0,0 +1,219 @@ +// <copyright file="ConversationsController.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.Messaging.API +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Conversations. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ConversationsController : ControllerBase + { + /// <summary> + /// Initializes a new instance of the <see cref="ConversationsController"/> class. + /// </summary> + /// <param name="soulseekClient"></param> + /// <param name="applicationStateMonotor"></param> + /// <param name="tracker"></param> + public ConversationsController( + ISoulseekClient soulseekClient, + IStateMonitor<State> applicationStateMonotor, + IConversationTracker tracker) + { + Client = soulseekClient; + ApplicationStateMonitor = applicationStateMonotor; + Tracker = tracker; + } + + private ISoulseekClient Client { get; } + private IStateMonitor<State> ApplicationStateMonitor { get; } + private IConversationTracker Tracker { get; } + + /// <summary> + /// Acknowledges the given message id for the given username. + /// </summary> + /// <param name="username"></param> + /// <param name="id"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404"> + /// A conversation with the specified username, or a message matching the specified id could not be found. + /// </response> + [HttpPut("{username}/{id}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task<IActionResult> Acknowledge([FromRoute]string username, [FromRoute]int id) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default || !conversation.Any(p => p.Id == id)) + { + return NotFound(); + } + + await Client.AcknowledgePrivateMessageAsync(id); + return StatusCode(200); + } + + /// <summary> + /// Acknowledges all messages for the given username. + /// </summary> + /// <param name="username"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">A conversation with the specified username could not be found.</response> + [HttpPut("{username}")] + [Authorize] + [ProducesResponseType(200)] + [ProducesResponseType(404)] + public async Task<IActionResult> AcknowledgeAll([FromRoute]string username) + { + Tracker.Conversations.TryGetValue(username, out var conversation); + + if (conversation == default) + { + return NotFound(); + } + + var tasks = new List<Task>(); + + foreach (var message in conversation.Where(p => !p.Acknowledged)) + { + tasks.Add(Task.Run(async () => + { + await Client.AcknowledgePrivateMessageAsync(message.Id); + message.Acknowledged = true; + })); + } + + await Task.WhenAll(tasks); + return StatusCode(200); + } + + /// <summary> + /// Deletes the conversation associated with the given username. + /// </summary> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="404">A conversation with the specified username could not be found.</response> + [HttpDelete("{username}")] + [Authorize] + [ProducesResponseType(404)] + [ProducesResponseType(204)] + public IActionResult Delete([FromRoute]string username) + { + var deleted = Tracker.Conversations.TryRemove(username, out _); + + if (deleted) + { + return StatusCode(204); + } + + return StatusCode(404); + } + + /// <summary> + /// Gets all tracked conversations. + /// </summary> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("")] + [Authorize] + [ProducesResponseType(typeof(Dictionary<string, List<PrivateMessageResponse>>), 200)] + public IActionResult GetAll() + { + var response = Tracker.Conversations.ToDictionary( + entry => entry.Key, + entry => entry.Value + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.Server.Username)) + .OrderBy(m => m.Timestamp)); + + return Ok(response); + } + + /// <summary> + /// Gets the conversation associated with the specified username. + /// </summary> + /// <param name="username">The username associated with the desired conversation.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">A matching search was not found.</response> + [HttpGet("{username}")] + [Authorize] + [ProducesResponseType(typeof(List<PrivateMessageResponse>), 200)] + [ProducesResponseType(404)] + public IActionResult GetByUsername([FromRoute]string username) + { + if (Tracker.TryGet(username, out var conversation)) + { + var response = conversation + .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.Server.Username)) + .OrderBy(m => m.Timestamp); + + return Ok(response); + } + + return NotFound(); + } + + /// <summary> + /// Sends a private message to the specified username. + /// </summary> + /// <param name="username"></param> + /// <param name="message"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="400">The specified message is null or empty.</response> + [HttpPost("{username}")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(400)] + public async Task<IActionResult> Send([FromRoute]string username, [FromBody]string message) + { + if (string.IsNullOrEmpty(message)) + { + return BadRequest(); + } + + await Client.SendPrivateMessageAsync(username, message); + + // append the outgoing message to the tracker + Tracker.AddOrUpdate(username, new PrivateMessage() + { + Username = ApplicationStateMonitor.CurrentValue.Server.Username, + Timestamp = DateTime.UtcNow, + Message = message, + Acknowledged = true, + }); + + return StatusCode(201); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Messaging/API/Controllers/PublicChatController.cs b/src/slskd/Messaging/API/Controllers/PublicChatController.cs new file mode 100644 index 00000000..c30e08a8 --- /dev/null +++ b/src/slskd/Messaging/API/Controllers/PublicChatController.cs @@ -0,0 +1,67 @@ +// <copyright file="PublicChatController.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.Messaging.API +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Server. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class PublicChatController : ControllerBase + { + public PublicChatController(ISoulseekClient soulseekClient) + { + Client = soulseekClient; + } + + private ISoulseekClient Client { get; } + + /// <summary> + /// Starts public chat. + /// </summary> + /// <returns></returns> + [HttpPost] + [Authorize] + public async Task<IActionResult> Start() + { + await Client.StartPublicChatAsync(); + return StatusCode(StatusCodes.Status201Created); + } + + /// <summary> + /// Stops public chat. + /// </summary> + /// <returns></returns> + [HttpDelete] + [Authorize] + public async Task<IActionResult> Stop() + { + await Client.StopPublicChatAsync(); + return StatusCode(StatusCodes.Status204NoContent); + } + } +} diff --git a/src/slskd/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs new file mode 100644 index 00000000..743df527 --- /dev/null +++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs @@ -0,0 +1,309 @@ +// <copyright file="RoomsController.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.Messaging.API +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Rooms. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class RoomsController : ControllerBase + { + public RoomsController( + ISoulseekClient soulseekClient, + IRoomService roomService, + IStateMonitor<State> applicationStateMonitor, + IRoomTracker tracker) + { + 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> + /// Gets all rooms. + /// </summary> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("joined")] + [Authorize] + [ProducesResponseType(typeof(Dictionary<string, Dictionary<string, Room>>), 200)] + public IActionResult GetAll() + { + return Ok(Tracker.Rooms.Keys); + } + + /// <summary> + /// Gets the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpGet("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 200)] + [ProducesResponseType(404)] + public IActionResult GetByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + return Ok(MapRoomToRoomResponse(room)); + } + + return NotFound(); + } + + /// <summary> + /// Sends a message to the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="message"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpPost("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task<IActionResult> SendMessage([FromRoute]string roomName, [FromBody]string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SendRoomMessageAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// <summary> + /// Sets a ticker for the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="message"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpPost("joined/{roomName}/ticker")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task<IActionResult> SetTicker([FromRoute] string roomName, [FromBody] string message) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.SetRoomTickerAsync(roomName, message); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// <summary> + /// Adds a member to a private room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="username"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpPost("joined/{roomName}/members")] + [Authorize] + [ProducesResponseType(201)] + [ProducesResponseType(404)] + public async Task<IActionResult> AddRoomMember([FromRoute]string roomName, [FromBody]string username) + { + if (Tracker.TryGet(roomName, out var _)) + { + await Client.AddPrivateRoomMemberAsync(roomName, username); + return StatusCode(StatusCodes.Status201Created); + } + + return NotFound(); + } + + /// <summary> + /// Gets the current list of users for the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpGet("joined/{roomName}/users")] + [Authorize] + [ProducesResponseType(typeof(IList<UserData>), 200)] + [ProducesResponseType(404)] + public IActionResult GetUsersByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + var response = room.Users + .Select(user => UserDataResponse.FromUserData(user, self: user.Username == ApplicationStateMonitor.CurrentValue.Server.Username)); + + return Ok(response); + } + + return NotFound(); + } + + /// <summary> + /// Gets the current list of messages for the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The specified roomName could not be found.</response> + [HttpGet("joined/{roomName}/messages")] + [Authorize] + [ProducesResponseType(typeof(IList<RoomMessage>), 200)] + [ProducesResponseType(404)] + public IActionResult GetMessagesByRoomName([FromRoute]string roomName) + { + if (Tracker.TryGet(roomName, out var room)) + { + var response = room.Messages + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: message.Username == ApplicationStateMonitor.CurrentValue.Server.Username)); + + return Ok(response); + } + + return NotFound(); + } + + /// <summary> + /// Gets a list of rooms from the server. + /// </summary> + /// <returns></returns> + [HttpGet("available")] + [Authorize] + [ProducesResponseType(typeof(List<RoomInfo>), 200)] + public async Task<IActionResult> GetRooms() + { + var list = await Client.GetRoomListAsync(); + + var response = new List<RoomInfoResponse>(); + + response.AddRange(list.Public.Select(r => RoomInfoResponse.FromRoomInfo(r))); + response.AddRange(list.Private.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true))); + response.AddRange(list.Owned.Select(r => RoomInfoResponse.FromRoomInfo(r, isPrivate: true, isOwned: true))); + + foreach (var room in response) + { + room.IsModerated = list.ModeratedRoomNames.Contains(room.Name); + } + + return Ok(response); + } + + /// <summary> + /// Joins a room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="201">The request completed successfully.</response> + /// <response code="304">The room has already been joined.</response> + [HttpPost("joined/{roomName}")] + [Authorize] + [ProducesResponseType(typeof(Room), 201)] + [ProducesResponseType(304)] + public async Task<IActionResult> JoinRoom([FromRoute]string roomName) + { + if (Tracker.Rooms.ContainsKey(roomName)) + { + return StatusCode(StatusCodes.Status304NotModified); + } + + try + { + var roomData = await RoomService.JoinAsync(roomName); + var room = Room.FromRoomData(roomData); + Tracker.TryAdd(roomName, room); + + return StatusCode(StatusCodes.Status201Created, MapRoomToRoomResponse(room)); + } + catch (Exception ex) + { + if (ex.InnerException is RoomJoinForbiddenException) + { + return StatusCode(StatusCodes.Status403Forbidden, $"The server rejected your request to join {roomName}"); + } + + throw; + } + } + + /// <summary> + /// Leaves a room. + /// </summary> + /// <param name="roomName"></param> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="404">The room has not been joined.</response> + [HttpDelete("joined/{roomName}")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public async Task<IActionResult> LeaveRoom([FromRoute]string roomName) + { + if (!Tracker.Rooms.ContainsKey(roomName)) + { + return StatusCode(StatusCodes.Status404NotFound); + } + + await RoomService.LeaveAsync(roomName); + Tracker.TryRemove(roomName); + + return StatusCode(StatusCodes.Status204NoContent); + } + + private RoomResponse MapRoomToRoomResponse(Room room) + { + bool IsSelf(string username) + { + return username == ApplicationStateMonitor.CurrentValue.Server.Username; + } + + var response = RoomResponse.FromRoom(room); + response.Users = room.Users + .Select(user => UserDataResponse.FromUserData(user, self: IsSelf(user.Username))); + response.Messages = room.Messages + .Select(message => RoomMessageResponse.FromRoomMessage(message, self: IsSelf(message.Username))); + + return response; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs b/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs new file mode 100644 index 00000000..a7e08d50 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs @@ -0,0 +1,74 @@ +// <copyright file="PrivateMessageResponse.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.Messaging.API +{ + using System; + using slskd.Messaging; + + public class PrivateMessageResponse + { + /// <summary> + /// A value indicating whether the message has been acknowledged. + /// </summary> + public bool Acknowledged { get; set; } = false; + + /// <summary> + /// The unique message id, used to acknowledge receipt. + /// </summary> + public int Id { get; set; } + + /// <summary> + /// The message. + /// </summary> + public string Message { get; set; } + + /// <summary> + /// A value indicating whether the message was replayed. + /// </summary> + public bool Replayed { get; set; } + + /// <summary> + /// The UTC timestamp of the message. + /// </summary> + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// <summary> + /// The username of the user who sent the message. + /// </summary> + public string Username { get; set; } + + /// <summary> + /// A value indicating whether this message was sent by the currently logged in user. + /// </summary> + public bool? Self { get; set; } + + public static PrivateMessageResponse FromPrivateMessage(PrivateMessage privateMessage, bool self = false) + { + return new PrivateMessageResponse() + { + Id = privateMessage.Id, + Timestamp = privateMessage.Timestamp, + Username = privateMessage.Username, + Message = privateMessage.Message, + Acknowledged = privateMessage.Acknowledged, + Replayed = privateMessage.Replayed, + Self = self ? self : (bool?)null, + }; + } + } +} diff --git a/src/slskd/Messaging/API/DTO/RoomInfoResponse.cs b/src/slskd/Messaging/API/DTO/RoomInfoResponse.cs new file mode 100644 index 00000000..46edbdc8 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/RoomInfoResponse.cs @@ -0,0 +1,60 @@ +// <copyright file="RoomInfoResponse.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.Messaging.API +{ + using Soulseek; + + public class RoomInfoResponse + { + /// <summary> + /// Gets the room name. + /// </summary> + public string Name { get; init; } + + /// <summary> + /// Gets the number of users in the room. + /// </summary> + public int UserCount { get; init; } + + /// <summary> + /// Gets a value indicating whether the room is private. + /// </summary> + public bool IsPrivate { get; init; } + + /// <summary> + /// Gets a value indicating whether the room is owned by the currently logged in user. + /// </summary> + public bool IsOwned { get; init; } + + /// <summary> + /// Gets a value indicating whether the room is moderated by the currently logged in user. + /// </summary> + public bool IsModerated { get; set; } + + public static RoomInfoResponse FromRoomInfo(RoomInfo info, bool isPrivate = false, bool isOwned = false) + { + return new RoomInfoResponse() + { + Name = info.Name, + UserCount = info.UserCount, + IsPrivate = isPrivate, + IsOwned = isOwned, + }; + } + } +} diff --git a/src/slskd/Messaging/API/DTO/RoomMessageResponse.cs b/src/slskd/Messaging/API/DTO/RoomMessageResponse.cs new file mode 100644 index 00000000..965c63a6 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/RoomMessageResponse.cs @@ -0,0 +1,62 @@ +// <copyright file="RoomMessageResponse.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.Messaging.API +{ + using System; + using slskd.Messaging; + + public class RoomMessageResponse + { + /// <summary> + /// The timestamp of the message. + /// </summary> + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// <summary> + /// The username of the user who sent the message. + /// </summary> + public string Username { get; set; } + + /// <summary> + /// The message. + /// </summary> + public string Message { get; set; } + + /// <summary> + /// The room to which the message pertains. + /// </summary> + public string RoomName { get; set; } + + /// <summary> + /// A value indicating whether this user data belongs to the currently logged in user. + /// </summary> + public bool? Self { get; set; } + + public static RoomMessageResponse FromRoomMessage(RoomMessage roomMessage, bool self = false) + { + return new RoomMessageResponse() + { + Timestamp = roomMessage.Timestamp, + Username = roomMessage.Username, + Message = roomMessage.Message, + RoomName = roomMessage.RoomName, + Self = self ? self : (bool?)null, + }; + } + } +} diff --git a/src/slskd/Messaging/API/DTO/RoomResponse.cs b/src/slskd/Messaging/API/DTO/RoomResponse.cs new file mode 100644 index 00000000..cf7e1478 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/RoomResponse.cs @@ -0,0 +1,75 @@ +// <copyright file="RoomResponse.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.Messaging.API +{ + using System.Collections.Generic; + using System.Linq; + using slskd.Messaging; + + public class RoomResponse + { + /// <summary> + /// The room name. + /// </summary> + public string Name { get; set; } + + /// <summary> + /// A value indicating whether the room is private. + /// </summary> + public bool IsPrivate { get; set; } + + /// <summary> + /// The number of operators in the room, if private. + /// </summary> + public int? OperatorCount { get; set; } + + /// <summary> + /// The operators in the room, if private. + /// </summary> + public IList<string> Operators { get; set; } + + /// <summary> + /// The owner of the room, if private. + /// </summary> + public string Owner { get; set; } + + /// <summary> + /// The list of users in the room. + /// </summary> + public IEnumerable<UserDataResponse> Users { get; set; } = new List<UserDataResponse>(); + + /// <summary> + /// The list of messages. + /// </summary> + public IEnumerable<RoomMessageResponse> Messages { get; set; } = new List<RoomMessageResponse>(); + + public static RoomResponse FromRoom(Room room) + { + return new RoomResponse() + { + Name = room.Name, + IsPrivate = room.IsPrivate, + OperatorCount = room.OperatorCount, + Operators = room.Operators?.ToList(), + Owner = room.Owner, + Users = new List<UserDataResponse>(), + Messages = new List<RoomMessageResponse>(), + }; + } + } +} diff --git a/src/slskd/Messaging/API/DTO/UserDataResponse.cs b/src/slskd/Messaging/API/DTO/UserDataResponse.cs new file mode 100644 index 00000000..8f1e9544 --- /dev/null +++ b/src/slskd/Messaging/API/DTO/UserDataResponse.cs @@ -0,0 +1,85 @@ +// <copyright file="UserDataResponse.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.Messaging.API +{ + using Soulseek; + + public class UserDataResponse + { + /// <summary> + /// The average upload speed of the user. + /// </summary> + public int AverageSpeed { get; set; } + + /// <summary> + /// The user's country code, if provided. + /// </summary> + public string CountryCode { get; set; } + + /// <summary> + /// The number of directories shared by the user. + /// </summary> + public int DirectoryCount { get; set; } + + /// <summary> + /// The number of files shared by the user. + /// </summary> + public int FileCount { get; set; } + + /// <summary> + /// A value indicating whether this user data belongs to the currently logged in user. + /// </summary> + public bool? Self { get; set; } + + /// <summary> + /// The number of the user's free download slots, if provided. + /// </summary> + public int? SlotsFree { get; set; } + + /// <summary> + /// The status of the user (0 = offline, 1 = away, 2 = online). + /// </summary> + public UserPresence Status { get; set; } + + /// <summary> + /// The number of uploads tracked by the server for the user. + /// </summary> + public long UploadCount { get; set; } + + /// <summary> + /// The username of the user. + /// </summary> + public string Username { get; set; } + + public static UserDataResponse FromUserData(UserData userData, bool self = false) + { + return new UserDataResponse() + { + AverageSpeed = userData.AverageSpeed, + CountryCode = userData.CountryCode, + DirectoryCount = userData.DirectoryCount, + UploadCount = userData.UploadCount, + FileCount = userData.FileCount, + SlotsFree = userData.SlotsFree, + Status = userData.Status, + Username = userData.Username, + Self = self ? self : (bool?)null, + }; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Messaging/ConversationTracker.cs b/src/slskd/Messaging/ConversationTracker.cs new file mode 100644 index 00000000..27d678ca --- /dev/null +++ b/src/slskd/Messaging/ConversationTracker.cs @@ -0,0 +1,62 @@ +// <copyright file="ConversationTracker.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.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + + /// <summary> + /// Tracks private message conversations. + /// </summary> + public class ConversationTracker : IConversationTracker + { + /// <summary> + /// Tracked private message conversations. + /// </summary> + public ConcurrentDictionary<string, IList<PrivateMessage>> Conversations { get; } = new ConcurrentDictionary<string, IList<PrivateMessage>>(); + + /// <summary> + /// Adds a private message conversation and appends the specified <paramref name="message"/>, or just appends the + /// message if the conversation exists. + /// </summary> + /// <param name="username"></param> + /// <param name="message"></param> + public void AddOrUpdate(string username, PrivateMessage message) + { + Conversations.AddOrUpdate(username, new List<PrivateMessage>() { message }, (_, messageList) => + { + messageList.Add(message); + return messageList; + }); + } + + /// <summary> + /// Returns the list of private messages for the specified <paramref name="username"/>, if any exist. + /// </summary> + /// <param name="username"></param> + /// <param name="messages"></param> + /// <returns></returns> + public bool TryGet(string username, out IList<PrivateMessage> messages) => Conversations.TryGetValue(username, out messages); + + /// <summary> + /// Removes a tracked private message conversation for the specified user. + /// </summary> + /// <param name="username"></param> + public void TryRemove(string username) => Conversations.TryRemove(username, out _); + } +}
\ No newline at end of file diff --git a/src/slskd/Messaging/Domain/PrivateMessage.cs b/src/slskd/Messaging/Domain/PrivateMessage.cs new file mode 100644 index 00000000..236632aa --- /dev/null +++ b/src/slskd/Messaging/Domain/PrivateMessage.cs @@ -0,0 +1,71 @@ +// <copyright file="PrivateMessage.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.Messaging +{ + using System; + using Soulseek; + + /// <summary> + /// A private message. + /// </summary> + public class PrivateMessage + { + /// <summary> + /// A value indicating whether the message has been acknowledged. + /// </summary> + public bool Acknowledged { get; set; } = false; + + /// <summary> + /// The unique message id, used to acknowledge receipt. + /// </summary> + public int Id { get; set; } + + /// <summary> + /// The message. + /// </summary> + public string Message { get; set; } + + /// <summary> + /// A value indicating whether the message was replayed. + /// </summary> + public bool Replayed { get; set; } + + /// <summary> + /// The UTC timestamp of the message. + /// </summary> + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// <summary> + /// The username of the user who sent the message. + /// </summary> + public string Username { get; set; } + + public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) + { + return new PrivateMessage() + { + Id = eventArgs.Id, + Timestamp = eventArgs.Timestamp, + Username = eventArgs.Username, + Message = eventArgs.Message, + Acknowledged = false, + Replayed = eventArgs.Replayed, + }; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Messaging/Domain/Room.cs b/src/slskd/Messaging/Domain/Room.cs new file mode 100644 index 00000000..459dea2c --- /dev/null +++ b/src/slskd/Messaging/Domain/Room.cs @@ -0,0 +1,75 @@ +// <copyright file="Room.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.Messaging +{ + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + public class Room + { + /// <summary> + /// The room name. + /// </summary> + public string Name { get; set; } + + /// <summary> + /// A value indicating whether the room is private. + /// </summary> + public bool IsPrivate { get; set; } + + /// <summary> + /// The number of operators in the room, if private. + /// </summary> + public int? OperatorCount { get; set; } + + /// <summary> + /// The operators in the room, if private. + /// </summary> + public IList<string> Operators { get; set; } + + /// <summary> + /// The owner of the room, if private. + /// </summary> + public string Owner { get; set; } + + /// <summary> + /// The list of users in the room. + /// </summary> + public IList<UserData> Users { get; set; } = new List<UserData>(); + + /// <summary> + /// The list of messages. + /// </summary> + public IList<RoomMessage> Messages { get; set; } = new List<RoomMessage>(); + + public static Room FromRoomData(RoomData roomData) + { + return new Room() + { + Name = roomData.Name, + IsPrivate = roomData.IsPrivate, + OperatorCount = roomData.OperatorCount, + Operators = roomData.Operators?.ToList(), + Owner = roomData.Owner, + Users = roomData.Users?.ToList(), + Messages = new List<RoomMessage>(), + }; + } + } +} diff --git a/src/slskd/Messaging/Domain/RoomMessage.cs b/src/slskd/Messaging/Domain/RoomMessage.cs new file mode 100644 index 00000000..7a06a192 --- /dev/null +++ b/src/slskd/Messaging/Domain/RoomMessage.cs @@ -0,0 +1,59 @@ +// <copyright file="RoomMessage.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.Messaging +{ + using System; + using Soulseek; + + /// <summary> + /// A message sent to a room. + /// </summary> + public class RoomMessage + { + /// <summary> + /// The timestamp of the message. + /// </summary> + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// <summary> + /// The username of the user who sent the message. + /// </summary> + public string Username { get; set; } + + /// <summary> + /// The message. + /// </summary> + public string Message { get; set; } + + /// <summary> + /// The room to which the message pertains. + /// </summary> + public string RoomName { get; set; } + + public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) + { + return new RoomMessage() + { + Timestamp = timestamp ?? DateTime.UtcNow, + Username = eventArgs.Username, + Message = eventArgs.Message, + RoomName = eventArgs.RoomName, + }; + } + } +} diff --git a/src/slskd/Messaging/IConversationTracker.cs b/src/slskd/Messaging/IConversationTracker.cs new file mode 100644 index 00000000..8e7a90f4 --- /dev/null +++ b/src/slskd/Messaging/IConversationTracker.cs @@ -0,0 +1,55 @@ +// <copyright file="IConversationTracker.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.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + + /// <summary> + /// Tracks private message conversations. + /// </summary> + public interface IConversationTracker + { + /// <summary> + /// Tracked private message conversations. + /// </summary> + ConcurrentDictionary<string, IList<PrivateMessage>> Conversations { get; } + + /// <summary> + /// Adds a private message conversation and appends the specified <paramref name="message"/>, or just appends the + /// message if the conversation exists. + /// </summary> + /// <param name="username"></param> + /// <param name="message"></param> + void AddOrUpdate(string username, PrivateMessage message); + + /// <summary> + /// Returns the list of private messages for the specified <paramref name="username"/>, if any exist. + /// </summary> + /// <param name="username"></param> + /// <param name="messages"></param> + /// <returns></returns> + bool TryGet(string username, out IList<PrivateMessage> messages); + + /// <summary> + /// Removes a tracked private message conversation for the specified user. + /// </summary> + /// <param name="username"></param> + void TryRemove(string username); + } +}
\ No newline at end of file diff --git a/src/slskd/Messaging/IRoomTracker.cs b/src/slskd/Messaging/IRoomTracker.cs new file mode 100644 index 00000000..225e5f69 --- /dev/null +++ b/src/slskd/Messaging/IRoomTracker.cs @@ -0,0 +1,75 @@ +// <copyright file="IRoomTracker.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.Messaging +{ + using System.Collections.Concurrent; + using Soulseek; + + /// <summary> + /// Tracks rooms. + /// </summary> + public interface IRoomTracker + { + /// <summary> + /// Gets tracked rooms. + /// </summary> + ConcurrentDictionary<string, Room> Rooms { get; } + + /// <summary> + /// Adds a room and appends the specified <paramref name="message"/>, or just appends the message if the room exists. + /// </summary> + /// <param name="roomName"></param> + /// <param name="message"></param> + void AddOrUpdateMessage(string roomName, RoomMessage message); + + /// <summary> + /// Adds the specified room to the tracker. + /// </summary> + /// <param name="roomName"></param> + /// <param name="room"></param> + void TryAdd(string roomName, Room room); + + /// <summary> + /// Adds the specified <paramref name="userData"/> to the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="userData"></param> + void TryAddUser(string roomName, UserData userData); + + /// <summary> + /// Returns the list of messages for the specified <paramref name="roomName"/>, if it is tracked. + /// </summary> + /// <param name="roomName"></param> + /// <param name="room"></param> + /// <returns></returns> + bool TryGet(string roomName, out Room room); + + /// <summary> + /// Removes a tracked room. + /// </summary> + /// <param name="roomName"></param> + void TryRemove(string roomName); + + /// <summary> + /// Removes the specified <paramref name="username"/> from the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="username"></param> + void TryRemoveUser(string roomName, string username); + } +}
\ No newline at end of file diff --git a/src/slskd/Messaging/RoomService.cs b/src/slskd/Messaging/RoomService.cs new file mode 100644 index 00000000..2b6d2489 --- /dev/null +++ b/src/slskd/Messaging/RoomService.cs @@ -0,0 +1,218 @@ +// <copyright 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/Messaging/RoomTracker.cs b/src/slskd/Messaging/RoomTracker.cs new file mode 100644 index 00000000..c586f401 --- /dev/null +++ b/src/slskd/Messaging/RoomTracker.cs @@ -0,0 +1,112 @@ +// <copyright file="RoomTracker.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.Messaging +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + /// <summary> + /// Tracks rooms. + /// </summary> + public class RoomTracker : IRoomTracker + { + /// <summary> + /// Initializes a new instance of the <see cref="RoomTracker"/> class. + /// </summary> + /// <param name="messageLimit"></param> + public RoomTracker(int messageLimit = 25) + { + MessageLimit = messageLimit; + } + + /// <summary> + /// Tracked rooms. + /// </summary> + public ConcurrentDictionary<string, Room> Rooms { get; } = new ConcurrentDictionary<string, Room>(); + + private int MessageLimit { get; } + + /// <summary> + /// Adds a room and appends the specified <paramref name="message"/>, or just appends the message if the room exists. + /// </summary> + /// <param name="roomName"></param> + /// <param name="message"></param> + public void AddOrUpdateMessage(string roomName, RoomMessage message) + { + Rooms.AddOrUpdate(roomName, new Room() { Messages = new List<RoomMessage>() { message } }, (_, room) => + { + if (room.Messages.Count >= MessageLimit) + { + room.Messages = room.Messages.TakeLast(MessageLimit - 1).ToList(); + } + + room.Messages.Add(message); + return room; + }); + } + + /// <summary> + /// Adds the specified room to the tracker. + /// </summary> + /// <param name="roomName"></param> + /// <param name="room"></param> + public void TryAdd(string roomName, Room room) => Rooms.TryAdd(roomName, room); + + /// <summary> + /// Adds the specified <paramref name="userData"/> to the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="userData"></param> + public void TryAddUser(string roomName, UserData userData) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users.Add(userData); + } + } + + /// <summary> + /// Removes a tracked room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="room"></param> + /// <returns></returns> + public bool TryGet(string roomName, out Room room) => Rooms.TryGetValue(roomName, out room); + + /// <summary> + /// Returns the list of messages for the specified <paramref name="roomName"/>, if it is tracked. + /// </summary> + /// <param name="roomName"></param> + public void TryRemove(string roomName) => Rooms.TryRemove(roomName, out _); + + /// <summary> + /// Removes the specified <paramref name="username"/> from the specified room. + /// </summary> + /// <param name="roomName"></param> + /// <param name="username"></param> + public void TryRemoveUser(string roomName, string username) + { + if (Rooms.TryGetValue(roomName, out var room)) + { + room.Users = room.Users.Where(u => u.Username != username).ToList(); + } + } + } +}
\ No newline at end of file |
