diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-12-29 16:47:43 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-12-29 16:47:43 -0600 |
| commit | 49bc255026aa5ef2c4df0727134b7627808270fc (patch) | |
| tree | 89349c7aeb4beac343e0e70388dce7063e243388 /src | |
| parent | 5276699801f25eec692e48a39c73f45424a22d27 (diff) | |
| parent | 8352d28eb6eae848530aa2d6b4a4196d53f4ac88 (diff) | |
| download | slskd-49bc255026aa5ef2c4df0727134b7627808270fc.tar.gz | |
Merge pull request #809 from slskd/chat-logs
Save chat logs in a database (prevent message loss when restarting)
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/ConversationsController.cs | 130 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs | 74 | ||||
| -rw-r--r-- | src/slskd/Messaging/ConversationService.cs | 389 | ||||
| -rw-r--r-- | src/slskd/Messaging/ConversationTracker.cs | 62 | ||||
| -rw-r--r-- | src/slskd/Messaging/IConversationTracker.cs | 55 | ||||
| -rw-r--r-- | src/slskd/Messaging/MessagingDbContext.cs | 59 | ||||
| -rw-r--r-- | src/slskd/Messaging/MessagingService.cs | 50 | ||||
| -rw-r--r-- | src/slskd/Messaging/Types/Conversation.cs | 30 | ||||
| -rw-r--r-- | src/slskd/Messaging/Types/MessageDirection.cs | 25 | ||||
| -rw-r--r-- | src/slskd/Messaging/Types/PrivateMessage.cs | 24 | ||||
| -rw-r--r-- | src/slskd/Messaging/Types/RoomMessage.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 6 | ||||
| -rw-r--r-- | src/web/src/components/App.js | 8 | ||||
| -rw-r--r-- | src/web/src/components/Chat/Chat.js | 74 | ||||
| -rw-r--r-- | src/web/src/components/Chat/ChatMenu.js | 10 | ||||
| -rw-r--r-- | src/web/src/lib/chat.js | 4 |
17 files changed, 709 insertions, 304 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 44b7c627..30fee1be 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -83,10 +83,10 @@ namespace slskd IConnectionWatchdog connectionWatchdog, ITransferService transferService, IBrowseTracker browseTracker, - IConversationTracker conversationTracker, IRoomTracker roomTracker, IRoomService roomService, IUserService userService, + IMessagingService messagingService, IShareService shareService, IPushbulletService pushbulletService, IRelayService relayService, @@ -137,11 +137,11 @@ namespace slskd Transfers = transferService; BrowseTracker = browseTracker; - ConversationTracker = conversationTracker; Pushbullet = pushbulletService; RoomService = roomService; Users = userService; + Messaging = messagingService; ApplicationHub = applicationHub; Relay = relayService; @@ -192,7 +192,7 @@ namespace slskd private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } private IConnectionWatchdog ConnectionWatchdog { get; } - private IConversationTracker ConversationTracker { get; set; } + private IMessagingService Messaging { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext<Application>(); private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); private Options Options => OptionsMonitor.CurrentValue; @@ -642,7 +642,7 @@ namespace slskd private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) { - ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); + Messaging.Conversations.HandleMessageAsync(args.Username, PrivateMessage.FromEventArgs(args)); if (Options.Integration.Pushbullet.Enabled && !args.Replayed) { diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index d39c2c10..6efb5459 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -19,14 +19,11 @@ using Microsoft.Extensions.Options; 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 slskd.Relay; - using Soulseek; /// <summary> /// Conversations. @@ -41,24 +38,21 @@ namespace slskd.Messaging.API /// <summary> /// Initializes a new instance of the <see cref="ConversationsController"/> class. /// </summary> - /// <param name="soulseekClient"></param> /// <param name="applicationStateMonotor"></param> - /// <param name="tracker"></param> + /// <param name="messagingService"></param> + /// <param name="optionsSnapshot"></param> public ConversationsController( - ISoulseekClient soulseekClient, IStateMonitor<State> applicationStateMonotor, - IConversationTracker tracker, + IMessagingService messagingService, IOptionsSnapshot<Options> optionsSnapshot) { - Client = soulseekClient; ApplicationStateMonitor = applicationStateMonotor; - Tracker = tracker; + Messages = messagingService; OptionsSnapshot = optionsSnapshot; } - private ISoulseekClient Client { get; } private IStateMonitor<State> ApplicationStateMonitor { get; } - private IConversationTracker Tracker { get; } + private IMessagingService Messages { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } /// <summary> @@ -82,19 +76,20 @@ namespace slskd.Messaging.API return Forbid(); } - Tracker.Conversations.TryGetValue(username, out var conversation); + var message = Messages.Conversations.FindMessageAsync(username, id); - if (conversation == default || !conversation.Any(p => p.Id == id)) + if (message == default) { return NotFound(); } - await Client.AcknowledgePrivateMessageAsync(id); - return StatusCode(200); + await Messages.Conversations.AcknowledgeMessageAsync(username, id); + + return Ok(); } /// <summary> - /// Acknowledges all messages for the given username. + /// Acknowledges all messages from the given username. /// </summary> /// <param name="username"></param> /// <returns></returns> @@ -111,30 +106,20 @@ namespace slskd.Messaging.API return Forbid(); } - Tracker.Conversations.TryGetValue(username, out var conversation); + var conversation = Messages.Conversations.FindAsync(username); if (conversation == default) { return NotFound(); } - var tasks = new List<Task>(); + await Messages.Conversations.AcknowledgeAsync(username); - 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); + return Ok(); } /// <summary> - /// Deletes the conversation associated with the given username. + /// Closes the conversation associated with the given username. /// </summary> /// <returns></returns> /// <response code="204">The request completed successfully.</response> @@ -143,75 +128,105 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(404)] [ProducesResponseType(204)] - public IActionResult Delete([FromRoute]string username) + public async Task<IActionResult> Close([FromRoute]string username) { if (Program.IsRelayAgent) { return Forbid(); } - var deleted = Tracker.Conversations.TryRemove(username, out _); + var conversation = Messages.Conversations.FindAsync(username, includeInactive: false); - if (deleted) + if (conversation == default) { - return StatusCode(204); + return NotFound(); } - return StatusCode(404); + await Messages.Conversations.RemoveAsync(username); + + return StatusCode(204); } /// <summary> - /// Gets all tracked conversations. + /// Gets all active conversations. /// </summary> /// <returns></returns> /// <response code="200">The request completed successfully.</response> [HttpGet("")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary<string, List<PrivateMessageResponse>>), 200)] - public IActionResult GetAll() + [ProducesResponseType(typeof(List<Conversation>), 200)] + public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false, [FromQuery]bool unAcknowledgedOnly = false) { if (Program.IsRelayAgent) { return Forbid(); } - var response = Tracker.Conversations.ToDictionary( - entry => entry.Key, - entry => entry.Value - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.User.Username)) - .OrderBy(m => m.Timestamp)); + var conversations = await Messages.Conversations.ListAsync(c => includeInactive || c.IsActive); - return Ok(response); + if (unAcknowledgedOnly) + { + conversations = conversations.Where(c => c.HasUnAcknowledgedMessages); + } + + return Ok(conversations); } /// <summary> /// Gets the conversation associated with the specified username. /// </summary> /// <param name="username">The username associated with the desired conversation.</param> + /// <param name="includeMessages"></param> /// <returns></returns> /// <response code="200">The request completed successfully.</response> /// <response code="404">A matching search was not found.</response> [HttpGet("{username}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List<PrivateMessageResponse>), 200)] + [ProducesResponseType(typeof(Conversation), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> GetByUsername([FromRoute]string username, [FromQuery]bool includeMessages = true) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + var conversation = await Messages.Conversations.FindAsync(username, includeMessages: includeMessages); + + if (conversation == default) + { + return NotFound(); + } + + return Ok(conversation); + } + + [HttpGet("{username}/messages")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List<PrivateMessage>), 200)] [ProducesResponseType(404)] - public IActionResult GetByUsername([FromRoute]string username) + public async Task<IActionResult> GetMessagesByUsername([FromRoute]string username, [FromQuery]bool unAcknowledgedOnly = false) { if (Program.IsRelayAgent) { return Forbid(); } - if (Tracker.TryGet(username, out var conversation)) + var conversation = await Messages.Conversations.FindAsync(username, includeMessages: true); + + if (conversation == default) { - var response = conversation - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.User.Username)) - .OrderBy(m => m.Timestamp); + return NotFound(); + } - return Ok(response); + var messages = conversation.Messages; + + if (unAcknowledgedOnly) + { + messages = messages.Where(m => !m.IsAcknowledged); } - return NotFound(); + return Ok(messages); } /// <summary> @@ -238,16 +253,7 @@ namespace slskd.Messaging.API return BadRequest(); } - await Client.SendPrivateMessageAsync(username, message); - - // append the outgoing message to the tracker - Tracker.AddOrUpdate(username, new PrivateMessage() - { - Username = ApplicationStateMonitor.CurrentValue.User.Username, - Timestamp = DateTime.UtcNow, - Message = message, - Acknowledged = true, - }); + await Messages.Conversations.SendMessageAsync(username, message); return StatusCode(201); } diff --git a/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs b/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs deleted file mode 100644 index a7e08d50..00000000 --- a/src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs +++ /dev/null @@ -1,74 +0,0 @@ -// <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/ConversationService.cs b/src/slskd/Messaging/ConversationService.cs new file mode 100644 index 00000000..de772ff0 --- /dev/null +++ b/src/slskd/Messaging/ConversationService.cs @@ -0,0 +1,389 @@ +// <copyright file="ConversationService.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 System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Serilog; + using Soulseek; + + /// <summary> + /// Manages private messages. + /// </summary> + public interface IConversationService + { + /// <summary> + /// Acknowledges all unacknowledged <see cref="PrivateMessage"/> records from the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <returns>The operation context.</returns> + Task AcknowledgeAsync(string username); + + /// <summary> + /// Acknowledges the <see cref="PrivateMessage"/> record associated with the specified <paramref name="username"/> and <paramref name="id"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <param name="id">The ID of the message.</param> + /// <returns>The operation context.</returns> + Task AcknowledgeMessageAsync(string username, int id); + + /// <summary> + /// Creates a new, or activates an existing, conversation with the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <returns>The operation context.</returns> + Task CreateAsync(string username); + + /// <summary> + /// Returns the <see cref="Conversation"/> record associated with the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <param name="includeInactive">A value indicating whether to include conversations marked as inactive.</param> + /// <param name="includeMessages">A value indicating whether <see cref="PrivateMessage"/> records should be included in the return value.</param> + /// <returns>The operation context, including the located conversation, if one was found.</returns> + Task<Conversation> FindAsync(string username, bool includeInactive = true, bool includeMessages = false); + + /// <summary> + /// Returns the <see cref="PrivateMessage"/> record associated with the specified <paramref name="username"/> and <paramref name="id"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <param name="id">The ID of the message.</param> + /// <returns>The operation context, including the located message, if one was found.</returns> + Task<PrivateMessage> FindMessageAsync(string username, int id); + + /// <summary> + /// Returns the list of all <see cref="Conversation"/> records matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">An optional expression used to locate conversations.</param> + /// <returns>The operation context, including the list of found conversations.</returns> + Task<IEnumerable<Conversation>> ListAsync(Expression<Func<Conversation, bool>> expression = null); + + /// <summary> + /// Returns the list of all <see cref="PrivateMessage"/> records matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">An optional expression used to locate private messages.</param> + /// <returns>The operation context, including the list of found private messages.</returns> + Task<IEnumerable<PrivateMessage>> ListMessagesAsync(Expression<Func<PrivateMessage, bool>> expression = null); + + /// <summary> + /// Handles the receipt of an inbound <see cref="PrivateMessage"/>. + /// </summary> + /// <param name="username">The username associated with the message.</param> + /// <param name="message">The message.</param> + /// <returns>The operation context.</returns> + Task HandleMessageAsync(string username, PrivateMessage message); + + /// <summary> + /// Removes (marks inactive) the conversation with the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <returns>The operation context.</returns> + Task RemoveAsync(string username); + + /// <summary> + /// Sends the specified <paramref name="message"/> to the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the recipient.</param> + /// <param name="message">The message.</param> + /// <returns>The operation context.</returns> + Task SendMessageAsync(string username, string message); + } + + public class ConversationService : IConversationService + { + public ConversationService( + ISoulseekClient soulseekClient, + IDbContextFactory<MessagingDbContext> contextFactory) + { + SoulseekClient = soulseekClient; + ContextFactory = contextFactory; + } + + private IDbContextFactory<MessagingDbContext> ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<ConversationService>(); + private ISoulseekClient SoulseekClient { get; } + + /// <summary> + /// Acknowledges all unacknowledged <see cref="PrivateMessage"/> records from the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <returns>The operation context.</returns> + public async Task AcknowledgeAsync(string username) + { + using var context = ContextFactory.CreateDbContext(); + + var unacked = context.PrivateMessages + .Where(m => m.Username == username && !m.IsAcknowledged); + + foreach (var message in unacked) + { + await SoulseekClient.AcknowledgePrivateMessageAsync(message.Id); + message.IsAcknowledged = true; + } + + context.SaveChanges(); + } + + /// <summary> + /// Acknowledges the <see cref="PrivateMessage"/> record associated with the specified <paramref name="username"/> and <paramref name="id"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <param name="id">The ID of the message.</param> + /// <returns>The operation context.</returns> + public async Task AcknowledgeMessageAsync(string username, int id) + { + using var context = ContextFactory.CreateDbContext(); + var message = context.PrivateMessages.SingleOrDefault(m => m.Username == username && m.Id == id); + + if (message != default) + { + await SoulseekClient.AcknowledgePrivateMessageAsync(message.Id); + message.IsAcknowledged = true; + context.SaveChanges(); + } + else + { + Log.Warning("Attempted to acknowledge an unknown private message from {Username} with ID {Id}", username, id); + } + } + + /// <summary> + /// Creates a new, or activates an existing, conversation with the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <returns>The operation context.</returns> + public Task CreateAsync(string username) + { + ActivateConversation(username); + return Task.CompletedTask; + } + + /// <summary> + /// Returns the <see cref="Conversation"/> record associated with the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <param name="includeInactive">A value indicating whether to include conversations marked as inactive.</param> + /// <param name="includeMessages">A value indicating whether <see cref="PrivateMessage"/> records should be included in the return value.</param> + /// <returns>The operation context, including the located conversation, if one was found.</returns> + public async Task<Conversation> FindAsync(string username, bool includeInactive = true, bool includeMessages = false) + { + using var context = ContextFactory.CreateDbContext(); + + var conversation = context.Conversations + .AsNoTracking() + .Where(c => c.Username == username && (includeInactive || c.IsActive)) + .SingleOrDefault(); + + if (conversation != default) + { + if (includeMessages) + { + conversation.Messages = await ListMessagesAsync(m => m.Username == conversation.Username); + conversation.UnAcknowledgedMessageCount = conversation.Messages.Count(m => !m.IsAcknowledged); + } + else + { + var unacked = await ListMessagesAsync(m => m.Username == conversation.Username && !m.IsAcknowledged); + conversation.UnAcknowledgedMessageCount = unacked.Count(); + } + } + + return conversation; + } + + /// <summary> + /// Returns the <see cref="PrivateMessage"/> record associated with the specified <paramref name="username"/> and <paramref name="id"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <param name="id">The ID of the message.</param> + /// <returns>The operation context, including the located message, if one was found.</returns> + public Task<PrivateMessage> FindMessageAsync(string username, int id) + { + using var context = ContextFactory.CreateDbContext(); + + var message = context.PrivateMessages + .AsNoTracking() + .Where(m => m.Username == username && m.Id == id) + .SingleOrDefault(); + + return Task.FromResult(message); + } + + /// <summary> + /// Returns the list of all <see cref="Conversation"/> records matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">An optional expression used to locate conversations.</param> + /// <returns>The operation context, including the list of found conversations.</returns> + public Task<IEnumerable<Conversation>> ListAsync(Expression<Func<Conversation, bool>> expression = null) + { + using var context = ContextFactory.CreateDbContext(); + + // todo: replace this garbage with Dapper and a real SQL query + var unAckedMessages = context.PrivateMessages + .AsNoTracking() + .Where(m => !m.IsAcknowledged) + .ToList(); + + var conversations = context.Conversations + .AsNoTracking() + .Where(expression) + .OrderBy(c => c.Username) + .ToList(); + + var response = conversations.Select(c => new Conversation + { + Username = c.Username, + IsActive = c.IsActive, + UnAcknowledgedMessageCount = unAckedMessages.Count(m => m.Username == c.Username), + }); + + return Task.FromResult(response); + } + + /// <summary> + /// Returns the list of all <see cref="PrivateMessage"/> records matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">An optional expression used to locate private messages.</param> + /// <returns>The operation context, including the list of found private messages.</returns> + public Task<IEnumerable<PrivateMessage>> ListMessagesAsync(Expression<Func<PrivateMessage, bool>> expression = null) + { + using var context = ContextFactory.CreateDbContext(); + + var response = context.PrivateMessages + .AsNoTracking() + .Where(expression) + .OrderByDescending(m => m.Timestamp) + .Take(100) // stupid. TakeLast doesn't work + .OrderBy(m => m.Timestamp) + .ToList() + .AsEnumerable(); + + return Task.FromResult(response); + } + + /// <summary> + /// Handles the receipt of an inbound <see cref="PrivateMessage"/>. + /// </summary> + /// <param name="username">The username associated with the message.</param> + /// <param name="message">The message.</param> + /// <returns>The operation context.</returns> + public Task HandleMessageAsync(string username, PrivateMessage message) + { + ActivateConversation(username); + + using var context = ContextFactory.CreateDbContext(); + + // the server replays unacked messages when we log in. figure out if we've seen this message before, and if so sync it. + // note that the table for PMs uses a composite key; this expression should match whatever is in the DbContext. + var existing = context.PrivateMessages.FirstOrDefault(m => + m.Username == message.Username && + m.Id == message.Id && + m.Timestamp == message.Timestamp); + + if (existing != null) + { + // the message was replayed. ensure the local ack bit is in sync with the server + existing.IsAcknowledged = message.IsAcknowledged; + } + else + { + // this is a new message, so append it + context.PrivateMessages.Add(message); + } + + context.SaveChanges(); + + return Task.CompletedTask; + } + + /// <summary> + /// Removes (marks inactive) the conversation with the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username associated with the conversation.</param> + /// <returns>The operation context.</returns> + public async Task RemoveAsync(string username) + { + await AcknowledgeAsync(username); + + using var context = ContextFactory.CreateDbContext(); + + var conversation = context.Conversations.FirstOrDefault(c => c.Username == username); + + if (conversation != default) + { + conversation.IsActive = false; + context.SaveChanges(); + } + else + { + Log.Warning("Attempted to remove an unknown conversation with {Username}", username); + } + } + + /// <summary> + /// Sends the specified <paramref name="message"/> to the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the recipient.</param> + /// <param name="message">The message.</param> + /// <returns>The operation context.</returns> + public async Task SendMessageAsync(string username, string message) + { + ActivateConversation(username); + + // send the message over the network, then persist this should *probably* use a transaction but i'm scared of locking + // with SQLite so i won't + await SoulseekClient.SendPrivateMessageAsync(username, message); + + using var context = ContextFactory.CreateDbContext(); + + context.PrivateMessages.Add(new PrivateMessage + { + Timestamp = DateTime.UtcNow, + Id = 0, // the server assigns IDs. this message will get one but it'll only be known to the recipient + Username = username, + Direction = MessageDirection.Out, + Message = message, + IsAcknowledged = true, + }); + + context.SaveChanges(); + } + + private void ActivateConversation(string username) + { + using var context = ContextFactory.CreateDbContext(); + + var conversation = context.Conversations.FirstOrDefault(c => c.Username == username); + + if (conversation != default) + { + conversation.IsActive = true; + } + else + { + context.Conversations.Add(new Conversation { Username = username, IsActive = true }); + } + + context.SaveChanges(); + } + } +} diff --git a/src/slskd/Messaging/ConversationTracker.cs b/src/slskd/Messaging/ConversationTracker.cs deleted file mode 100644 index 27d678ca..00000000 --- a/src/slskd/Messaging/ConversationTracker.cs +++ /dev/null @@ -1,62 +0,0 @@ -// <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/IConversationTracker.cs b/src/slskd/Messaging/IConversationTracker.cs deleted file mode 100644 index 8e7a90f4..00000000 --- a/src/slskd/Messaging/IConversationTracker.cs +++ /dev/null @@ -1,55 +0,0 @@ -// <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/MessagingDbContext.cs b/src/slskd/Messaging/MessagingDbContext.cs new file mode 100644 index 00000000..5acb94ae --- /dev/null +++ b/src/slskd/Messaging/MessagingDbContext.cs @@ -0,0 +1,59 @@ +// <copyright file="MessagingDbContext.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 Microsoft.EntityFrameworkCore; + + public class MessagingDbContext : DbContext + { + public MessagingDbContext(DbContextOptions<MessagingDbContext> options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet<Conversation> Conversations { get; set; } + public DbSet<PrivateMessage> PrivateMessages { get; set; } + public DbSet<RoomMessage> RoomMessages { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity<Conversation>().HasKey(e => e.Username); + modelBuilder.Entity<Conversation>().Ignore(e => e.Messages); + modelBuilder.Entity<Conversation>().Ignore(e => e.UnAcknowledgedMessageCount); + modelBuilder.Entity<Conversation>().Ignore(e => e.HasUnAcknowledgedMessages); + + modelBuilder + .Entity<PrivateMessage>() + .Property(e => e.Timestamp) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + + modelBuilder.Entity<PrivateMessage>().HasKey(e => new { e.Username, e.Id, e.Timestamp }); + modelBuilder.Entity<PrivateMessage>().HasIndex(e => e.Username); + + modelBuilder + .Entity<RoomMessage>() + .Property(e => e.Timestamp) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + + modelBuilder.Entity<RoomMessage>().HasNoKey(); + modelBuilder.Entity<RoomMessage>().HasIndex(e => e.RoomName); + } + } +} diff --git a/src/slskd/Messaging/MessagingService.cs b/src/slskd/Messaging/MessagingService.cs new file mode 100644 index 00000000..d8ec40b6 --- /dev/null +++ b/src/slskd/Messaging/MessagingService.cs @@ -0,0 +1,50 @@ +// <copyright file="MessagingService.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 +{ + /// <summary> + /// Manages private and room messages. + /// </summary> + public interface IMessagingService + { + /// <summary> + /// Gets the <see cref="ConversationService"/>. + /// </summary> + IConversationService Conversations { get; } + } + + /// <summary> + /// Manages private and room messages. + /// </summary> + public class MessagingService : IMessagingService + { + /// <summary> + /// Initializes a new instance of the <see cref="MessagingService"/> class. + /// </summary> + /// <param name="conversations"></param> + public MessagingService(IConversationService conversations) + { + Conversations = conversations; + } + + /// <summary> + /// Gets the <see cref="ConversationService"/>. + /// </summary> + public IConversationService Conversations { get; } + } +}
\ No newline at end of file diff --git a/src/slskd/Messaging/Types/Conversation.cs b/src/slskd/Messaging/Types/Conversation.cs new file mode 100644 index 00000000..6fabfcf1 --- /dev/null +++ b/src/slskd/Messaging/Types/Conversation.cs @@ -0,0 +1,30 @@ +// <copyright file="Conversation.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; + + public class Conversation + { + public string Username { get; set; } + public bool IsActive { get; set; } = true; + public int UnAcknowledgedMessageCount { get; set; } + public bool HasUnAcknowledgedMessages => UnAcknowledgedMessageCount > 0; + public IEnumerable<PrivateMessage> Messages { get; set; } + } +} diff --git a/src/slskd/Messaging/Types/MessageDirection.cs b/src/slskd/Messaging/Types/MessageDirection.cs new file mode 100644 index 00000000..e0b9a0b5 --- /dev/null +++ b/src/slskd/Messaging/Types/MessageDirection.cs @@ -0,0 +1,25 @@ +// <copyright file="MessageDirection.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 +{ + public enum MessageDirection + { + Out = 0, + In = 1, + } +} diff --git a/src/slskd/Messaging/Types/PrivateMessage.cs b/src/slskd/Messaging/Types/PrivateMessage.cs index 236632aa..a4b1c325 100644 --- a/src/slskd/Messaging/Types/PrivateMessage.cs +++ b/src/slskd/Messaging/Types/PrivateMessage.cs @@ -26,9 +26,9 @@ namespace slskd.Messaging public class PrivateMessage { /// <summary> - /// A value indicating whether the message has been acknowledged. + /// The UTC timestamp of the message. /// </summary> - public bool Acknowledged { get; set; } = false; + public DateTime Timestamp { get; set; } = DateTime.UtcNow; /// <summary> /// The unique message id, used to acknowledge receipt. @@ -36,24 +36,24 @@ namespace slskd.Messaging public int Id { get; set; } /// <summary> - /// The message. + /// The username of the remote user. /// </summary> - public string Message { get; set; } + public string Username { get; set; } /// <summary> - /// A value indicating whether the message was replayed. + /// Gets or sets the message direction. /// </summary> - public bool Replayed { get; set; } + public MessageDirection Direction { get; set; } /// <summary> - /// The UTC timestamp of the message. + /// The message. /// </summary> - public DateTime Timestamp { get; set; } = DateTime.UtcNow; + public string Message { get; set; } /// <summary> - /// The username of the user who sent the message. + /// A value indicating whether the message has been acknowledged. /// </summary> - public string Username { get; set; } + public bool IsAcknowledged { get; set; } = false; public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) { @@ -63,8 +63,8 @@ namespace slskd.Messaging Timestamp = eventArgs.Timestamp, Username = eventArgs.Username, Message = eventArgs.Message, - Acknowledged = false, - Replayed = eventArgs.Replayed, + IsAcknowledged = false, + Direction = MessageDirection.In, }; } } diff --git a/src/slskd/Messaging/Types/RoomMessage.cs b/src/slskd/Messaging/Types/RoomMessage.cs index 7a06a192..6d109464 100644 --- a/src/slskd/Messaging/Types/RoomMessage.cs +++ b/src/slskd/Messaging/Types/RoomMessage.cs @@ -45,6 +45,11 @@ namespace slskd.Messaging /// </summary> public string RoomName { get; set; } + /// <summary> + /// Gets or sets the message direction. + /// </summary> + public MessageDirection Direction { get; set; } + public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) { return new RoomMessage() diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 04d3b7e4..c909d7a4 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -534,17 +534,21 @@ namespace slskd { services.AddDbContext<SearchDbContext>($"Data Source=file:search?mode=memory;Cache=shared;Pooling=True;"); services.AddDbContext<TransfersDbContext>($"Data Source=file:transfers?mode=memory;Cache=shared;Pooling=True;"); + services.AddDbContext<MessagingDbContext>($"Data Source=file:messaging?mode=memory;Cache=shared;Pooling=True;"); } else { services.AddDbContext<SearchDbContext>($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;"); services.AddDbContext<TransfersDbContext>($"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;"); + services.AddDbContext<MessagingDbContext>($"Data Source={Path.Combine(DataDirectory, "messaging.db")};Cache=shared;Pooling=True;"); } services.AddSingleton<IBrowseTracker, BrowseTracker>(); - services.AddSingleton<IConversationTracker, ConversationTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); + services.AddSingleton<IMessagingService, MessagingService>(); + services.AddSingleton<IConversationService, ConversationService>(); + services.AddSingleton<IShareService, ShareService>(); services.AddTransient<IShareRepositoryFactory, SqliteShareRepositoryFactory>(); diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index df65bc20..70d154af 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -334,8 +334,12 @@ class App extends Component { </div>)} /> <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/> - <Route path={`${urlBase}/users`} render={(props) => this.withTokenCheck(<Users {...props}/>)}/> - <Route path={`${urlBase}/chat`} render={(props) => this.withTokenCheck(<Chat {...props}/>)}/> + <Route path={`${urlBase}/users`} render={(props) => + this.withTokenCheck(<Users {...props}/>)} + /> + <Route path={`${urlBase}/chat`} render={(props) => + this.withTokenCheck(<Chat {...props} state={applicationState}/>)} + /> <Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/> <Route path={`${urlBase}/uploads`} render={ (props) => diff --git a/src/web/src/components/Chat/Chat.js b/src/web/src/components/Chat/Chat.js index 12840e4a..e9ff0be9 100644 --- a/src/web/src/components/Chat/Chat.js +++ b/src/web/src/components/Chat/Chat.js @@ -43,41 +43,55 @@ class Chat extends Component { }; fetchConversations = async () => { - const { active } = this.state; + // fetch all of the active conversations (but no messages) let conversations = await chat.getAll(); - - const unAckedActiveMessages = (conversations[active] || []) - .filter(message => !message.acknowledged); - - if (unAckedActiveMessages.length > 0) { - await this.acknowledgeMessages(active, { force: true }); + + // turn into a map, keyed by username + // if there are no active conversations, set to an empty map + if (conversations.length === 0) { + conversations = {}; + } else { + conversations = conversations.reduce((map, current) => { + map[current.username] = current; + return map; + }, {}); + } + + const { active } = this.state; + const activeConversation = conversations[active]; + + // check to see if the active chat is still active + // this will happen whenever a chat is closed/removed + if (activeConversation) { + console.log('active?', activeConversation); + // *before* fetching messages, ack any unacked messages + // for the active chat + if (activeConversation.hasUnAcknowledgedMessages === true) { + await this.acknowledgeMessages(active); + } + conversations = { - ...conversations, - [active]: conversations[active].map(message => ({...message, acknowledged: true })), + ...conversations, + [active]: await chat.get({ username: active }), }; } this.setState({ conversations }, () => { + // if a chat isn't active or the active chat is closed, + // select the first conversation, if there is one if (!this.state.conversations[this.state.active]) { this.selectConversation(this.getFirstConversation()); - } else { - this.acknowledgeMessages(this.state.active); } }); }; - acknowledgeMessages = async (username, { force = false } = {}) => { - if (!username) return; - - const unAckedMessages = (this.state.conversations[username] || []) - .filter(message => !message.acknowledged); - - if (!force && unAckedMessages.length === 0) return; - + acknowledgeMessages = async (username) => { + if (!username || username === '') return; await chat.acknowledge({ username }); }; sendMessage = async (username, message) => { + if (!username || !message || username === '') return; await chat.send({ username, message }); }; @@ -91,6 +105,10 @@ class Chat extends Component { await this.sendMessage(active, message); this.messageRef.current.value = ''; + + // force a refresh to append the message + // we could probably do this in the browser but we can be lazy + this.fetchConversations(); }; validInput = () => @@ -118,11 +136,17 @@ class Chat extends Component { active: username, loading: true, }, async () => { - const { active } = this.state; + const { active, conversations } = this.state; sessionStorage.setItem(activeChatKey, active); - this.setState({ loading: false }, () => { + this.setState({ + loading: false, + conversations: active === '' ? conversations : { + ...conversations, + [active]: await chat.get({ username: active }), + }, + }, () => { try { this.listRef.current.lastChild.scrollIntoView(); } catch { @@ -146,7 +170,8 @@ class Chat extends Component { render = () => { const { conversations = [], active, loading } = this.state; - const messages = conversations[active] || []; + const messages = conversations[active]?.messages || []; + const { user } = this.props.state; return ( <div className='chats'> @@ -183,10 +208,11 @@ class Chat extends Component { {messages.map((message, index) => <List.Content key={index} - className={`chat-message ${message.username !== active ? 'chat-message-self' : ''}`} + className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`} > <span className='chat-message-time'>{this.formatTimestamp(message.timestamp)}</span> - <span className='chat-message-name'>{message.username}: </span> + <span className='chat-message-name'> + {message.direction === 'Out' ? user.username : message.username}: </span> <span className='chat-message-message'>{message.message}</span> </List.Content> )} diff --git a/src/web/src/components/Chat/ChatMenu.js b/src/web/src/components/Chat/ChatMenu.js index 971646f4..3dd91763 100644 --- a/src/web/src/components/Chat/ChatMenu.js +++ b/src/web/src/components/Chat/ChatMenu.js @@ -8,12 +8,6 @@ import SendMessageModal from './SendMessageModal'; const ChatMenu = ({ conversations, active, onConversationChange, ...rest }) => { const names = Object.keys(conversations); - - const unread = Object.entries(conversations).reduce((acc, [name, messages]) => { - acc[name] = messages.filter(message => !message.acknowledged); - return acc; - }, {}); - const isActive = (name) => active === name; return ( @@ -28,8 +22,8 @@ const ChatMenu = ({ conversations, active, onConversationChange, ...rest }) => { > <Icon name='circle' size='tiny' color='green'/> {name} - {(unread[name] || []).length === 0 ? '' : - <Label size='tiny' color='red'>{(unread[name] || []).length}</Label> + {conversations[name].hasUnAcknowledgedMessages && + <Label size='tiny' color='red'>{conversations[name].unAcknowledgedMessageCount}</Label> } </Menu.Item> )} diff --git a/src/web/src/lib/chat.js b/src/web/src/lib/chat.js index 2b31bcd8..31edcc8b 100644 --- a/src/web/src/lib/chat.js +++ b/src/web/src/lib/chat.js @@ -4,6 +4,10 @@ export const getAll = async () => { return (await api.get('/conversations')).data; }; +export const get = async ({ username }) => { + return (await api.get(`/conversations/${encodeURIComponent(username)}`)).data; +}; + export const acknowledge = ({ username }) => { return api.put(`/conversations/${encodeURIComponent(username)}`); }; |
