From 852fd1322bf5910e1e81a576b91b299415e06f06 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Dec 2022 16:19:25 -0600 Subject: add Conversation type --- src/slskd/Messaging/Types/Conversation.cs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/slskd/Messaging/Types/Conversation.cs (limited to 'src') diff --git a/src/slskd/Messaging/Types/Conversation.cs b/src/slskd/Messaging/Types/Conversation.cs new file mode 100644 index 00000000..5feb7dc8 --- /dev/null +++ b/src/slskd/Messaging/Types/Conversation.cs @@ -0,0 +1,30 @@ +// +// 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/. +// + +namespace slskd.Messaging +{ + using System.Collections.Generic; + using System.Linq; + + public class Conversation + { + public string Username { get; set; } + public bool Active { get; set; } = true; + public bool HasUnacknowledgedMessages => Messages.Any(m => !m.Acknowledged); + public IEnumerable Messages { get; set; } = new List(); + } +} -- cgit v1.2.3 From dfe7b03fcc10bfacd7527af83b6d2891329be18a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Dec 2022 16:19:42 -0600 Subject: add MessageDirection --- src/slskd/Messaging/Types/MessageDirection.cs | 25 +++++++++++++++++++++++++ src/slskd/Messaging/Types/PrivateMessage.cs | 10 ++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 src/slskd/Messaging/Types/MessageDirection.cs (limited to 'src') diff --git a/src/slskd/Messaging/Types/MessageDirection.cs b/src/slskd/Messaging/Types/MessageDirection.cs new file mode 100644 index 00000000..18fedf5d --- /dev/null +++ b/src/slskd/Messaging/Types/MessageDirection.cs @@ -0,0 +1,25 @@ +// +// 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/. +// + +namespace slskd.Messaging +{ + public enum MessageDirection + { + In = 0, + Out = 1, + } +} diff --git a/src/slskd/Messaging/Types/PrivateMessage.cs b/src/slskd/Messaging/Types/PrivateMessage.cs index 236632aa..fbaa43a0 100644 --- a/src/slskd/Messaging/Types/PrivateMessage.cs +++ b/src/slskd/Messaging/Types/PrivateMessage.cs @@ -30,6 +30,11 @@ namespace slskd.Messaging /// public bool Acknowledged { get; set; } = false; + /// + /// Gets or sets the message direction. + /// + public MessageDirection Direction { get; set; } + /// /// The unique message id, used to acknowledge receipt. /// @@ -43,7 +48,7 @@ namespace slskd.Messaging /// /// A value indicating whether the message was replayed. /// - public bool Replayed { get; set; } + public bool Replayed { get; set; } = false; /// /// The UTC timestamp of the message. @@ -51,7 +56,7 @@ namespace slskd.Messaging public DateTime Timestamp { get; set; } = DateTime.UtcNow; /// - /// The username of the user who sent the message. + /// The username of the remote user. /// public string Username { get; set; } @@ -65,6 +70,7 @@ namespace slskd.Messaging Message = eventArgs.Message, Acknowledged = false, Replayed = eventArgs.Replayed, + Direction = MessageDirection.In, }; } } -- cgit v1.2.3 From c8d2458da64b2d060128aca13ad4690f7add8361 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Dec 2022 16:20:48 -0600 Subject: add direction to room --- src/slskd/Messaging/Types/RoomMessage.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') 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 /// public string RoomName { get; set; } + /// + /// Gets or sets the message direction. + /// + public MessageDirection Direction { get; set; } + public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) { return new RoomMessage() -- cgit v1.2.3 From d9a90c231565b520e11eda3380bebac20974e35b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Dec 2022 16:21:03 -0600 Subject: add DbContext for Messaging --- src/slskd/Messaging/MessagingDbContext.cs | 58 +++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/slskd/Messaging/MessagingDbContext.cs (limited to 'src') diff --git a/src/slskd/Messaging/MessagingDbContext.cs b/src/slskd/Messaging/MessagingDbContext.cs new file mode 100644 index 00000000..2b0422ee --- /dev/null +++ b/src/slskd/Messaging/MessagingDbContext.cs @@ -0,0 +1,58 @@ +// +// 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/. +// + +namespace slskd.Messaging +{ + using System; + using Microsoft.EntityFrameworkCore; + + public class MessagingDbContext : DbContext + { + public MessagingDbContext(DbContextOptions options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet Conversations { get; set; } + public DbSet PrivateMessages { get; set; } + public DbSet RoomMessages { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasKey(e => e.Username); + modelBuilder.Entity().Ignore(e => e.Messages); + modelBuilder.Entity().Ignore(e => e.HasUnacknowledgedMessages); + + modelBuilder + .Entity() + .Property(e => e.Timestamp) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + + modelBuilder.Entity().HasNoKey(); + modelBuilder.Entity().HasIndex(e => e.Username); + + modelBuilder + .Entity() + .Property(e => e.Timestamp) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + + modelBuilder.Entity().HasNoKey(); + modelBuilder.Entity().HasIndex(e => e.RoomName); + } + } +} -- cgit v1.2.3 From f5701b6dced92ca43d6dc9dabc1c716a43ead357 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Dec 2022 16:21:16 -0600 Subject: add MessagingService --- src/slskd/Messaging/MessagingService.cs | 50 +++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/slskd/Messaging/MessagingService.cs (limited to 'src') 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 (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/. +// + +namespace slskd.Messaging +{ + /// + /// Manages private and room messages. + /// + public interface IMessagingService + { + /// + /// Gets the . + /// + IConversationService Conversations { get; } + } + + /// + /// Manages private and room messages. + /// + public class MessagingService : IMessagingService + { + /// + /// Initializes a new instance of the class. + /// + /// + public MessagingService(IConversationService conversations) + { + Conversations = conversations; + } + + /// + /// Gets the . + /// + public IConversationService Conversations { get; } + } +} \ No newline at end of file -- cgit v1.2.3 From 7c3315edf44426748506e09eeb9d9ba31459cbcb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Dec 2022 16:21:29 -0600 Subject: add and implement ConversationService --- src/slskd/Messaging/ConversationService.cs | 301 +++++++++++++++++++++++++++++ 1 file changed, 301 insertions(+) create mode 100644 src/slskd/Messaging/ConversationService.cs (limited to 'src') diff --git a/src/slskd/Messaging/ConversationService.cs b/src/slskd/Messaging/ConversationService.cs new file mode 100644 index 00000000..996feb64 --- /dev/null +++ b/src/slskd/Messaging/ConversationService.cs @@ -0,0 +1,301 @@ +// +// 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/. +// + +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; + + /// + /// Manages private messages. + /// + public interface IConversationService + { + /// + /// Acknowledges all unacknowledged records from the specified . + /// + /// The username associated with the conversation. + /// The operation context. + Task AcknowledgeAsync(string username); + + /// + /// Acknowledges the record associated with the specified and . + /// + /// The username associated with the conversation. + /// The ID of the message. + /// The operation context. + Task AcknowledgeMessageAsync(string username, int id); + + /// + /// Creates a new, or activates an existing, conversation with the specified . + /// + /// The username associated with the conversation. + /// The operation context. + Task CreateAsync(string username); + + /// + /// Returns the matching the specified . + /// + /// An expression used to locate the conversation. + /// The operation context, including the located conversation, if one was found. + Task FindAsync(Expression> expression); + + /// + /// Returns the list of all records matching the specified . + /// + /// An optional expression used to locate conversations. + /// The operation context, including the list of found conversations. + Task> ListAsync(Expression> expression = null); + + /// + /// Handles the receipt of an inbound . + /// + /// The username associated with the message. + /// The message. + /// The operation context. + Task HandleMessageAsync(string username, PrivateMessage message); + + /// + /// Removes (marks inactive) the conversation with the specified . + /// + /// The username associated with the conversation. + /// The operation context. + Task RemoveAsync(string username); + + /// + /// Sends the specified to the specified . + /// + /// The username of the recipient. + /// The message. + /// The operation context. + Task SendMessageAsync(string username, string message); + } + + public class ConversationService : IConversationService + { + public ConversationService( + ISoulseekClient soulseekClient, + IDbContextFactory contextFactory) + { + SoulseekClient = soulseekClient; + ContextFactory = contextFactory; + } + + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private ISoulseekClient SoulseekClient { get; } + + /// + /// Acknowledges all unacknowledged records from the specified . + /// + /// The username associated with the conversation. + /// The operation context. + public async Task AcknowledgeAsync(string username) + { + using var context = ContextFactory.CreateDbContext(); + + var unacked = context.PrivateMessages + .Where(m => m.Username == username && !m.Acknowledged) + .Select(m => AcknowledgeMessageAsync(username, m.Id)); + + await Task.WhenAll(unacked); + } + + /// + /// Acknowledges the record associated with the specified and . + /// + /// The username associated with the conversation. + /// The ID of the message. + /// The operation context. + public async Task AcknowledgeMessageAsync(string username, int id) + { + using var context = ContextFactory.CreateDbContext(); + var message = context.PrivateMessages.FirstOrDefault(m => m.Username == username && m.Id == id); + + if (message != default) + { + await SoulseekClient.AcknowledgePrivateMessageAsync(id); + message.Acknowledged = true; + context.SaveChanges(); + } + else + { + Log.Warning("Attempted to acknowledge an unknown private message from {Username} with ID {Id}", username, id); + } + } + + /// + /// Creates a new, or activates an existing, conversation with the specified . + /// + /// The username associated with the conversation. + /// The operation context. + public Task CreateAsync(string username) + { + ActivateConversation(username); + return Task.CompletedTask; + } + + /// + /// Returns the matching the specified . + /// + /// An expression used to locate the conversation. + /// The operation context, including the located conversation, if one was found. + public Task FindAsync(Expression> expression) + { + using var context = ContextFactory.CreateDbContext(); + + var conversation = context.Conversations + .AsNoTracking() + .Where(expression) + .FirstOrDefault(); + + if (conversation != default) + { + // add an option to limit this, or figure out pagination. + conversation.Messages = context.PrivateMessages.Where(m => m.Username == conversation.Username); + } + + return Task.FromResult(conversation); + } + + /// + /// Returns the list of all records matching the specified . + /// + /// An optional expression used to locate conversations. + /// The operation context, including the list of found conversations. + public Task> ListAsync(Expression> expression = null) + { + using var context = ContextFactory.CreateDbContext(); + + return Task.FromResult(context.Conversations.Where(expression).AsEnumerable()); + } + + /// + /// Handles the receipt of an inbound . + /// + /// The username associated with the message. + /// The message. + /// The operation context. + 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. + var existing = context.PrivateMessages.FirstOrDefault(m => + m.Username == message.Username && + m.Message == message.Message && + m.Id == message.Id); + + if (existing != null) + { + // the message was replayed. i'm not sure what is updated, so just update anything that might have updated + existing.Timestamp = message.Timestamp; + existing.Replayed = message.Replayed; + existing.Acknowledged = message.Acknowledged; + } + else + { + // this is a new message, so append it + context.PrivateMessages.Add(message); + } + + context.SaveChanges(); + + return Task.CompletedTask; + } + + /// + /// Removes (marks inactive) the conversation with the specified . + /// + /// The username associated with the conversation. + /// The operation context. + 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.Active = false; + context.SaveChanges(); + } + else + { + Log.Warning("Attempted to remove an unknown conversation with {Username}", username); + } + } + + /// + /// Sends the specified to the specified . + /// + /// The username of the recipient. + /// The message. + /// The operation context. + 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 + { + Acknowledged = true, + Id = 0, + Message = message, + Replayed = false, + Timestamp = DateTime.UtcNow, + Username = username, + Direction = MessageDirection.Out, + }); + + 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.Active = true; + } + else + { + context.Conversations.Add(new Conversation { Username = username, Active = true }); + } + + context.SaveChanges(); + } + } +} -- cgit v1.2.3 From fe6659e9554604c85e9e278ec39bf802a6727196 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Dec 2022 16:21:55 -0600 Subject: create MessagingDbContext --- src/slskd/Program.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 04d3b7e4..24420b7d 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -534,11 +534,13 @@ namespace slskd { services.AddDbContext($"Data Source=file:search?mode=memory;Cache=shared;Pooling=True;"); services.AddDbContext($"Data Source=file:transfers?mode=memory;Cache=shared;Pooling=True;"); + services.AddDbContext($"Data Source=file:messaging?mode=memory;Cache=shared;Pooling=True;"); } else { services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;"); services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;"); + services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "messaging.db")};Cache=shared;Pooling=True;"); } services.AddSingleton(); -- cgit v1.2.3 From 55b1a3b53eedb8f1b0a179c8951c9fee88576bdf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 26 Dec 2022 16:23:06 -0600 Subject: add new services to DI --- src/slskd/Program.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 24420b7d..f961c610 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -547,6 +547,9 @@ namespace slskd services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddTransient(); -- cgit v1.2.3 From 8b133dd5163c30986910064dd269780e07d82ed6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Dec 2022 11:13:00 -0600 Subject: remove PrivateMessageResponse --- .../Messaging/API/DTO/PrivateMessageResponse.cs | 74 ---------------------- 1 file changed, 74 deletions(-) delete mode 100644 src/slskd/Messaging/API/DTO/PrivateMessageResponse.cs (limited to 'src') 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 (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/. -// - -namespace slskd.Messaging.API -{ - using System; - using slskd.Messaging; - - public class PrivateMessageResponse - { - /// - /// A value indicating whether the message has been acknowledged. - /// - public bool Acknowledged { get; set; } = false; - - /// - /// The unique message id, used to acknowledge receipt. - /// - public int Id { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// A value indicating whether the message was replayed. - /// - public bool Replayed { get; set; } - - /// - /// The UTC timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - /// - /// A value indicating whether this message was sent by the currently logged in user. - /// - 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, - }; - } - } -} -- cgit v1.2.3 From 6b044ce2ea2a29d6c67e27afff719cfd0f85ed31 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Dec 2022 11:14:47 -0600 Subject: tweak types --- src/slskd/Messaging/Types/Conversation.cs | 5 ++--- src/slskd/Messaging/Types/PrivateMessage.cs | 28 +++++++++++----------------- 2 files changed, 13 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/Types/Conversation.cs b/src/slskd/Messaging/Types/Conversation.cs index 5feb7dc8..062fbec6 100644 --- a/src/slskd/Messaging/Types/Conversation.cs +++ b/src/slskd/Messaging/Types/Conversation.cs @@ -18,13 +18,12 @@ namespace slskd.Messaging { using System.Collections.Generic; - using System.Linq; public class Conversation { public string Username { get; set; } - public bool Active { get; set; } = true; - public bool HasUnacknowledgedMessages => Messages.Any(m => !m.Acknowledged); + public bool IsActive { get; set; } = true; + public bool? HasUnAcknowledgedMessages { get; set; } public IEnumerable Messages { get; set; } = new List(); } } diff --git a/src/slskd/Messaging/Types/PrivateMessage.cs b/src/slskd/Messaging/Types/PrivateMessage.cs index fbaa43a0..a4b1c325 100644 --- a/src/slskd/Messaging/Types/PrivateMessage.cs +++ b/src/slskd/Messaging/Types/PrivateMessage.cs @@ -26,14 +26,9 @@ namespace slskd.Messaging public class PrivateMessage { /// - /// A value indicating whether the message has been acknowledged. - /// - public bool Acknowledged { get; set; } = false; - - /// - /// Gets or sets the message direction. + /// The UTC timestamp of the message. /// - public MessageDirection Direction { get; set; } + public DateTime Timestamp { get; set; } = DateTime.UtcNow; /// /// The unique message id, used to acknowledge receipt. @@ -41,24 +36,24 @@ namespace slskd.Messaging public int Id { get; set; } /// - /// The message. + /// The username of the remote user. /// - public string Message { get; set; } + public string Username { get; set; } /// - /// A value indicating whether the message was replayed. + /// Gets or sets the message direction. /// - public bool Replayed { get; set; } = false; + public MessageDirection Direction { get; set; } /// - /// The UTC timestamp of the message. + /// The message. /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; + public string Message { get; set; } /// - /// The username of the remote user. + /// A value indicating whether the message has been acknowledged. /// - public string Username { get; set; } + public bool IsAcknowledged { get; set; } = false; public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) { @@ -68,8 +63,7 @@ namespace slskd.Messaging Timestamp = eventArgs.Timestamp, Username = eventArgs.Username, Message = eventArgs.Message, - Acknowledged = false, - Replayed = eventArgs.Replayed, + IsAcknowledged = false, Direction = MessageDirection.In, }; } -- cgit v1.2.3 From 2d2c82e84fa8b2efacd431c42eeb3d106c85bd40 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Dec 2022 11:15:29 -0600 Subject: tweak type back --- src/slskd/Messaging/Types/Conversation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Messaging/Types/Conversation.cs b/src/slskd/Messaging/Types/Conversation.cs index 062fbec6..3b140a61 100644 --- a/src/slskd/Messaging/Types/Conversation.cs +++ b/src/slskd/Messaging/Types/Conversation.cs @@ -23,7 +23,7 @@ namespace slskd.Messaging { public string Username { get; set; } public bool IsActive { get; set; } = true; - public bool? HasUnAcknowledgedMessages { get; set; } + public bool HasUnAcknowledgedMessages { get; set; } public IEnumerable Messages { get; set; } = new List(); } } -- cgit v1.2.3 From 909b6e532721936e82914712d6228b62619d2fc1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Dec 2022 11:16:13 -0600 Subject: remove deprecated ConversationTracker --- src/slskd/Messaging/ConversationTracker.cs | 62 ----------------------------- src/slskd/Messaging/IConversationTracker.cs | 55 ------------------------- src/slskd/Program.cs | 1 - 3 files changed, 118 deletions(-) delete mode 100644 src/slskd/Messaging/ConversationTracker.cs delete mode 100644 src/slskd/Messaging/IConversationTracker.cs (limited to 'src') 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 (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/. -// - -namespace slskd.Messaging -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - - /// - /// Tracks private message conversations. - /// - public class ConversationTracker : IConversationTracker - { - /// - /// Tracked private message conversations. - /// - public ConcurrentDictionary> Conversations { get; } = new ConcurrentDictionary>(); - - /// - /// Adds a private message conversation and appends the specified , or just appends the - /// message if the conversation exists. - /// - /// - /// - public void AddOrUpdate(string username, PrivateMessage message) - { - Conversations.AddOrUpdate(username, new List() { message }, (_, messageList) => - { - messageList.Add(message); - return messageList; - }); - } - - /// - /// Returns the list of private messages for the specified , if any exist. - /// - /// - /// - /// - public bool TryGet(string username, out IList messages) => Conversations.TryGetValue(username, out messages); - - /// - /// Removes a tracked private message conversation for the specified user. - /// - /// - 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 (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/. -// - -namespace slskd.Messaging -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - - /// - /// Tracks private message conversations. - /// - public interface IConversationTracker - { - /// - /// Tracked private message conversations. - /// - ConcurrentDictionary> Conversations { get; } - - /// - /// Adds a private message conversation and appends the specified , or just appends the - /// message if the conversation exists. - /// - /// - /// - void AddOrUpdate(string username, PrivateMessage message); - - /// - /// Returns the list of private messages for the specified , if any exist. - /// - /// - /// - /// - bool TryGet(string username, out IList messages); - - /// - /// Removes a tracked private message conversation for the specified user. - /// - /// - void TryRemove(string username); - } -} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f961c610..c909d7a4 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -544,7 +544,6 @@ namespace slskd } services.AddSingleton(); - services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(); -- cgit v1.2.3 From 583a05087d435e2590cef02aa339af74946325b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Dec 2022 11:16:25 -0600 Subject: swap tracker for service --- src/slskd/Application.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') 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(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); 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) { -- cgit v1.2.3 From 56eaf60295a9c8f7906ac9621a6dca23a8271dae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Dec 2022 11:16:47 -0600 Subject: add a composite key for PMs --- src/slskd/Messaging/MessagingDbContext.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/MessagingDbContext.cs b/src/slskd/Messaging/MessagingDbContext.cs index 2b0422ee..a1f3dd8e 100644 --- a/src/slskd/Messaging/MessagingDbContext.cs +++ b/src/slskd/Messaging/MessagingDbContext.cs @@ -36,14 +36,14 @@ namespace slskd.Messaging { modelBuilder.Entity().HasKey(e => e.Username); modelBuilder.Entity().Ignore(e => e.Messages); - modelBuilder.Entity().Ignore(e => e.HasUnacknowledgedMessages); + modelBuilder.Entity().Ignore(e => e.HasUnAcknowledgedMessages); modelBuilder .Entity() .Property(e => e.Timestamp) .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); - modelBuilder.Entity().HasNoKey(); + modelBuilder.Entity().HasKey(e => new { e.Username, e.Id, e.Timestamp }); modelBuilder.Entity().HasIndex(e => e.Username); modelBuilder -- cgit v1.2.3 From a2c74b250e2a39aa2cbeefd33a1698bf0da7ad87 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Dec 2022 11:17:05 -0600 Subject: refactor a bunch of stuff --- src/slskd/Messaging/ConversationService.cs | 150 +++++++++++++++++++++++------ 1 file changed, 119 insertions(+), 31 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/ConversationService.cs b/src/slskd/Messaging/ConversationService.cs index 996feb64..5f5f703c 100644 --- a/src/slskd/Messaging/ConversationService.cs +++ b/src/slskd/Messaging/ConversationService.cs @@ -54,11 +54,21 @@ namespace slskd.Messaging Task CreateAsync(string username); /// - /// Returns the matching the specified . + /// Returns the record associated with the specified . /// - /// An expression used to locate the conversation. + /// The username associated with the conversation. + /// A value indicating whether to include conversations marked as inactive. + /// A value indicating whether records should be included in the return value. /// The operation context, including the located conversation, if one was found. - Task FindAsync(Expression> expression); + Task FindAsync(string username, bool includeInactive = true, bool includeMessages = false); + + /// + /// Returns the record associated with the specified and . + /// + /// The username associated with the conversation. + /// The ID of the message. + /// The operation context, including the located message, if one was found. + Task FindMessageAsync(string username, int id); /// /// Returns the list of all records matching the specified . @@ -67,6 +77,13 @@ namespace slskd.Messaging /// The operation context, including the list of found conversations. Task> ListAsync(Expression> expression = null); + /// + /// Returns the list of all records matching the specified . + /// + /// An optional expression used to locate private messages. + /// The operation context, including the list of found private messages. + Task> ListMessagesAsync(Expression> expression = null); + /// /// Handles the receipt of an inbound . /// @@ -115,10 +132,15 @@ namespace slskd.Messaging using var context = ContextFactory.CreateDbContext(); var unacked = context.PrivateMessages - .Where(m => m.Username == username && !m.Acknowledged) - .Select(m => AcknowledgeMessageAsync(username, m.Id)); + .Where(m => m.Username == username && !m.IsAcknowledged); + + foreach (var message in unacked) + { + await SoulseekClient.AcknowledgePrivateMessageAsync(message.Id); + message.IsAcknowledged = true; + } - await Task.WhenAll(unacked); + context.SaveChanges(); } /// @@ -130,12 +152,12 @@ namespace slskd.Messaging public async Task AcknowledgeMessageAsync(string username, int id) { using var context = ContextFactory.CreateDbContext(); - var message = context.PrivateMessages.FirstOrDefault(m => m.Username == username && m.Id == id); + var message = context.PrivateMessages.SingleOrDefault(m => m.Username == username && m.Id == id); if (message != default) { - await SoulseekClient.AcknowledgePrivateMessageAsync(id); - message.Acknowledged = true; + await SoulseekClient.AcknowledgePrivateMessageAsync(message.Id); + message.IsAcknowledged = true; context.SaveChanges(); } else @@ -156,26 +178,55 @@ namespace slskd.Messaging } /// - /// Returns the matching the specified . + /// Returns the record associated with the specified . /// - /// An expression used to locate the conversation. + /// The username associated with the conversation. + /// A value indicating whether to include conversations marked as inactive. + /// A value indicating whether records should be included in the return value. /// The operation context, including the located conversation, if one was found. - public Task FindAsync(Expression> expression) + public async Task FindAsync(string username, bool includeInactive = true, bool includeMessages = false) { using var context = ContextFactory.CreateDbContext(); var conversation = context.Conversations .AsNoTracking() - .Where(expression) - .FirstOrDefault(); + .Where(c => c.Username == username && (includeInactive || c.IsActive)) + .SingleOrDefault(); if (conversation != default) { - // add an option to limit this, or figure out pagination. - conversation.Messages = context.PrivateMessages.Where(m => m.Username == conversation.Username); + if (includeMessages) + { + // TODO: add an option to limit this, or figure out pagination. + conversation.Messages = await ListMessagesAsync(m => m.Username == conversation.Username); + conversation.HasUnAcknowledgedMessages = conversation.Messages.Any(m => !m.IsAcknowledged); + } + else + { + var unacked = await ListMessagesAsync(m => m.Username == conversation.Username && !m.IsAcknowledged); + conversation.HasUnAcknowledgedMessages = unacked.Any(); + } } - return Task.FromResult(conversation); + return conversation; + } + + /// + /// Returns the record associated with the specified and . + /// + /// The username associated with the conversation. + /// The ID of the message. + /// The operation context, including the located message, if one was found. + public Task 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); } /// @@ -187,7 +238,46 @@ namespace slskd.Messaging { using var context = ContextFactory.CreateDbContext(); - return Task.FromResult(context.Conversations.Where(expression).AsEnumerable()); + var unAckedConversations = context.PrivateMessages + .AsNoTracking() + .Where(m => !m.IsAcknowledged) + .Select(m => m.Username) + .Distinct() + .ToList(); + + var response = context.Conversations + .AsNoTracking() + .Select(c => new Conversation + { + Username = c.Username, + IsActive = c.IsActive, + HasUnAcknowledgedMessages = unAckedConversations.Contains(c.Username), + }) + .Where(expression) + .OrderBy(c => c.Username) + .ToList() + .AsEnumerable(); + + return Task.FromResult(response); + } + + /// + /// Returns the list of all records matching the specified . + /// + /// An optional expression used to locate private messages. + /// The operation context, including the list of found private messages. + public Task> ListMessagesAsync(Expression> expression = null) + { + using var context = ContextFactory.CreateDbContext(); + + var response = context.PrivateMessages + .AsNoTracking() + .Where(expression) + .OrderBy(m => m.Timestamp) + .ToList() + .AsEnumerable(); + + return Task.FromResult(response); } /// @@ -203,17 +293,16 @@ namespace slskd.Messaging 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.Message == message.Message && - m.Id == message.Id); + m.Id == message.Id && + m.Timestamp == message.Timestamp); if (existing != null) { - // the message was replayed. i'm not sure what is updated, so just update anything that might have updated - existing.Timestamp = message.Timestamp; - existing.Replayed = message.Replayed; - existing.Acknowledged = message.Acknowledged; + // the message was replayed. ensure the local ack bit is in sync with the server + existing.IsAcknowledged = message.IsAcknowledged; } else { @@ -241,7 +330,7 @@ namespace slskd.Messaging if (conversation != default) { - conversation.Active = false; + conversation.IsActive = false; context.SaveChanges(); } else @@ -268,13 +357,12 @@ namespace slskd.Messaging context.PrivateMessages.Add(new PrivateMessage { - Acknowledged = true, - Id = 0, - Message = message, - Replayed = false, 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(); @@ -288,11 +376,11 @@ namespace slskd.Messaging if (conversation != default) { - conversation.Active = true; + conversation.IsActive = true; } else { - context.Conversations.Add(new Conversation { Username = username, Active = true }); + context.Conversations.Add(new Conversation { Username = username, IsActive = true }); } context.SaveChanges(); -- cgit v1.2.3 From 7f7e226813e54b767839bc195017276e3b2ac9fb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Dec 2022 11:17:19 -0600 Subject: swap tracker for service --- .../API/Controllers/ConversationsController.cs | 118 ++++++++++----------- 1 file changed, 56 insertions(+), 62 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index d39c2c10..5b67ca86 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; /// /// Conversations. @@ -41,24 +38,21 @@ namespace slskd.Messaging.API /// /// Initializes a new instance of the class. /// - /// /// - /// + /// + /// public ConversationsController( - ISoulseekClient soulseekClient, IStateMonitor applicationStateMonotor, - IConversationTracker tracker, + IMessagingService messagingService, IOptionsSnapshot optionsSnapshot) { - Client = soulseekClient; ApplicationStateMonitor = applicationStateMonotor; - Tracker = tracker; + Messages = messagingService; OptionsSnapshot = optionsSnapshot; } - private ISoulseekClient Client { get; } private IStateMonitor ApplicationStateMonitor { get; } - private IConversationTracker Tracker { get; } + private IMessagingService Messages { get; } private IOptionsSnapshot OptionsSnapshot { get; } /// @@ -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(); } /// - /// Acknowledges all messages for the given username. + /// Acknowledges all messages from the given username. /// /// /// @@ -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(); - - foreach (var message in conversation.Where(p => !p.Acknowledged)) - { - tasks.Add(Task.Run(async () => - { - await Client.AcknowledgePrivateMessageAsync(message.Id); - message.Acknowledged = true; - })); - } + await Messages.Conversations.AcknowledgeAsync(username); - await Task.WhenAll(tasks); - return StatusCode(200); + return Ok(); } /// - /// Deletes the conversation associated with the given username. + /// Closes the conversation associated with the given username. /// /// /// The request completed successfully. @@ -143,75 +128,93 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(404)] [ProducesResponseType(204)] - public IActionResult Delete([FromRoute]string username) + public async Task 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); } /// - /// Gets all tracked conversations. + /// Gets all active conversations. /// /// /// The request completed successfully. [HttpGet("")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary>), 200)] - public IActionResult GetAll() + [ProducesResponseType(typeof(List), 200)] + public async Task GetAll([FromQuery]bool unAckedOnly = 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 => c.IsActive && (!unAckedOnly || c.HasUnAcknowledgedMessages)); - return Ok(response); + return Ok(conversations); } /// /// Gets the conversation associated with the specified username. /// /// The username associated with the desired conversation. + /// /// /// The request completed successfully. /// A matching search was not found. [HttpGet("{username}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 200)] + [ProducesResponseType(typeof(Conversation), 200)] [ProducesResponseType(404)] - public IActionResult GetByUsername([FromRoute]string username) + public async Task GetByUsername([FromRoute]string username, [FromQuery]bool includeMessages = true) { if (Program.IsRelayAgent) { return Forbid(); } - if (Tracker.TryGet(username, out var conversation)) + var conversation = await Messages.Conversations.FindAsync(username, includeMessages); + + if (conversation == default) + { + return NotFound(); + } + + return Ok(conversation); + } + + [HttpGet("{username}/messages")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 200)] + [ProducesResponseType(404)] + public async Task GetMessagesByUsername([FromRoute]string username) + { + if (Program.IsRelayAgent) { - var response = conversation - .Select(pm => PrivateMessageResponse.FromPrivateMessage(pm, self: pm.Username == ApplicationStateMonitor.CurrentValue.User.Username)) - .OrderBy(m => m.Timestamp); + return Forbid(); + } + + var messages = await Messages.Conversations.ListMessagesAsync(m => m.Username == username); - return Ok(response); + if (!messages.Any()) + { + return NotFound(); } - return NotFound(); + return Ok(messages); } /// @@ -238,16 +241,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); } -- cgit v1.2.3 From 49122da2c8dde09e73032278939fe165bd98acdf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Dec 2022 13:29:27 -0600 Subject: invert MessageDirection --- src/slskd/Messaging/Types/MessageDirection.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/Types/MessageDirection.cs b/src/slskd/Messaging/Types/MessageDirection.cs index 18fedf5d..e0b9a0b5 100644 --- a/src/slskd/Messaging/Types/MessageDirection.cs +++ b/src/slskd/Messaging/Types/MessageDirection.cs @@ -19,7 +19,7 @@ namespace slskd.Messaging { public enum MessageDirection { - In = 0, - Out = 1, + Out = 0, + In = 1, } } -- cgit v1.2.3 From cc09f70335662fc828f61919207885d01f98fbc5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 12:31:50 -0600 Subject: add unacked count --- src/slskd/Messaging/Types/Conversation.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Messaging/Types/Conversation.cs b/src/slskd/Messaging/Types/Conversation.cs index 3b140a61..e482e560 100644 --- a/src/slskd/Messaging/Types/Conversation.cs +++ b/src/slskd/Messaging/Types/Conversation.cs @@ -23,7 +23,8 @@ namespace slskd.Messaging { public string Username { get; set; } public bool IsActive { get; set; } = true; - public bool HasUnAcknowledgedMessages { get; set; } + public int UnAcknowledgedMessageCount { get; set; } + public bool HasUnAcknowledgedMessages => UnAcknowledgedMessageCount > 0; public IEnumerable Messages { get; set; } = new List(); } } -- cgit v1.2.3 From 6281660e13147c2c05e07729266966c7eb64e5a0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 12:54:54 -0600 Subject: compute unacked --- src/slskd/Messaging/ConversationService.cs | 14 ++++++++------ src/slskd/Messaging/MessagingDbContext.cs | 1 + 2 files changed, 9 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/ConversationService.cs b/src/slskd/Messaging/ConversationService.cs index 5f5f703c..dc9fe017 100644 --- a/src/slskd/Messaging/ConversationService.cs +++ b/src/slskd/Messaging/ConversationService.cs @@ -199,12 +199,12 @@ namespace slskd.Messaging { // TODO: add an option to limit this, or figure out pagination. conversation.Messages = await ListMessagesAsync(m => m.Username == conversation.Username); - conversation.HasUnAcknowledgedMessages = conversation.Messages.Any(m => !m.IsAcknowledged); + conversation.UnAcknowledgedMessageCount = conversation.Messages.Count(m => !m.IsAcknowledged); } else { var unacked = await ListMessagesAsync(m => m.Username == conversation.Username && !m.IsAcknowledged); - conversation.HasUnAcknowledgedMessages = unacked.Any(); + conversation.UnAcknowledgedMessageCount = unacked.Count(); } } @@ -238,12 +238,14 @@ namespace slskd.Messaging { using var context = ContextFactory.CreateDbContext(); + // todo: replace this garbage with Dapper and a real SQL query var unAckedConversations = context.PrivateMessages .AsNoTracking() .Where(m => !m.IsAcknowledged) - .Select(m => m.Username) - .Distinct() - .ToList(); + .GroupBy( + keySelector: p => p.Username, + resultSelector: (key, group) => new { Username = key, Count = group.Count() }) + .ToDictionary(k => k.Username, v => v.Count); var response = context.Conversations .AsNoTracking() @@ -251,7 +253,7 @@ namespace slskd.Messaging { Username = c.Username, IsActive = c.IsActive, - HasUnAcknowledgedMessages = unAckedConversations.Contains(c.Username), + UnAcknowledgedMessageCount = unAckedConversations.GetValueOrDefault(c.Username), }) .Where(expression) .OrderBy(c => c.Username) diff --git a/src/slskd/Messaging/MessagingDbContext.cs b/src/slskd/Messaging/MessagingDbContext.cs index a1f3dd8e..5acb94ae 100644 --- a/src/slskd/Messaging/MessagingDbContext.cs +++ b/src/slskd/Messaging/MessagingDbContext.cs @@ -36,6 +36,7 @@ namespace slskd.Messaging { modelBuilder.Entity().HasKey(e => e.Username); modelBuilder.Entity().Ignore(e => e.Messages); + modelBuilder.Entity().Ignore(e => e.UnAcknowledgedMessageCount); modelBuilder.Entity().Ignore(e => e.HasUnAcknowledgedMessages); modelBuilder -- cgit v1.2.3 From dfb87bdbee091f389f8c5606d3b214f19add8491 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 12:55:22 -0600 Subject: rename unacked arg --- src/slskd/Messaging/API/Controllers/ConversationsController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index 5b67ca86..707791af 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -155,14 +155,14 @@ namespace slskd.Messaging.API [HttpGet("")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(List), 200)] - public async Task GetAll([FromQuery]bool unAckedOnly = false) + public async Task GetAll([FromQuery]bool unAcknowledgedOnly = false) { if (Program.IsRelayAgent) { return Forbid(); } - var conversations = await Messages.Conversations.ListAsync(c => c.IsActive && (!unAckedOnly || c.HasUnAcknowledgedMessages)); + var conversations = await Messages.Conversations.ListAsync(c => c.IsActive && (!unAcknowledgedOnly || c.HasUnAcknowledgedMessages)); return Ok(conversations); } -- cgit v1.2.3 From 300d8e182317e44fe83376044e543058ad087c42 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 12:55:36 -0600 Subject: fix menu --- src/web/src/components/Chat/ChatMenu.js | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) (limited to 'src') 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 }) => { > {name} - {(unread[name] || []).length === 0 ? '' : - + {conversations[name].hasUnAcknowledgedMessages && + } )} -- cgit v1.2.3 From a80fdc66cfb70e092e5ef70086eba4b0af09f22c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 15:08:05 -0600 Subject: limit messages to the last 100 --- src/slskd/Messaging/ConversationService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Messaging/ConversationService.cs b/src/slskd/Messaging/ConversationService.cs index dc9fe017..535998c3 100644 --- a/src/slskd/Messaging/ConversationService.cs +++ b/src/slskd/Messaging/ConversationService.cs @@ -197,7 +197,6 @@ namespace slskd.Messaging { if (includeMessages) { - // TODO: add an option to limit this, or figure out pagination. conversation.Messages = await ListMessagesAsync(m => m.Username == conversation.Username); conversation.UnAcknowledgedMessageCount = conversation.Messages.Count(m => !m.IsAcknowledged); } @@ -275,6 +274,8 @@ namespace slskd.Messaging var response = context.PrivateMessages .AsNoTracking() .Where(expression) + .OrderByDescending(m => m.Timestamp) + .Take(100) // stupid. TakeLast doesn't work .OrderBy(m => m.Timestamp) .ToList() .AsEnumerable(); -- cgit v1.2.3 From 53a5418c47f85e330e10ae853b25a1a163553df4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 15:08:24 -0600 Subject: fix positional error --- src/slskd/Messaging/API/Controllers/ConversationsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index 707791af..66ca62ff 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -186,7 +186,7 @@ namespace slskd.Messaging.API return Forbid(); } - var conversation = await Messages.Conversations.FindAsync(username, includeMessages); + var conversation = await Messages.Conversations.FindAsync(username, includeMessages: includeMessages); if (conversation == default) { -- cgit v1.2.3 From 9176bbb14ee35e4bc12c5ff947fcf8bdbf2bb090 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 15:08:36 -0600 Subject: add get() --- src/web/src/lib/chat.js | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') 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)}`); }; -- cgit v1.2.3 From 47edf3ca8bca0ddb0b298091bac856d508ecc25b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 15:08:51 -0600 Subject: pass state to Chat --- src/web/src/components/App.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') 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 { )} /> this.withTokenCheck()}/> - this.withTokenCheck()}/> - this.withTokenCheck()}/> + + this.withTokenCheck()} + /> + + this.withTokenCheck()} + /> this.withTokenCheck()}/> -- cgit v1.2.3 From f8dc73ac2fb26a9f37cfea899e47e2fbc68a7d6c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 15:09:05 -0600 Subject: fix all the broken stuff --- src/web/src/components/Chat/Chat.js | 74 +++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 24 deletions(-) (limited to 'src') 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 (
@@ -183,10 +208,11 @@ class Chat extends Component { {messages.map((message, index) => {this.formatTimestamp(message.timestamp)} - {message.username}: + + {message.direction === 'Out' ? user.username : message.username}: {message.message} )} -- cgit v1.2.3 From 9e57b9fb6e1978cacb4bef3071f0ab6d86bcde5c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 16:27:16 -0600 Subject: allow messages to null --- src/slskd/Messaging/Types/Conversation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Messaging/Types/Conversation.cs b/src/slskd/Messaging/Types/Conversation.cs index e482e560..6fabfcf1 100644 --- a/src/slskd/Messaging/Types/Conversation.cs +++ b/src/slskd/Messaging/Types/Conversation.cs @@ -25,6 +25,6 @@ namespace slskd.Messaging public bool IsActive { get; set; } = true; public int UnAcknowledgedMessageCount { get; set; } public bool HasUnAcknowledgedMessages => UnAcknowledgedMessageCount > 0; - public IEnumerable Messages { get; set; } = new List(); + public IEnumerable Messages { get; set; } } } -- cgit v1.2.3 From c675426488998111e854d62c28106e040298ae52 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 16:27:31 -0600 Subject: tweak list logic again --- src/slskd/Messaging/ConversationService.cs | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/ConversationService.cs b/src/slskd/Messaging/ConversationService.cs index 535998c3..de772ff0 100644 --- a/src/slskd/Messaging/ConversationService.cs +++ b/src/slskd/Messaging/ConversationService.cs @@ -238,26 +238,23 @@ namespace slskd.Messaging using var context = ContextFactory.CreateDbContext(); // todo: replace this garbage with Dapper and a real SQL query - var unAckedConversations = context.PrivateMessages + var unAckedMessages = context.PrivateMessages .AsNoTracking() .Where(m => !m.IsAcknowledged) - .GroupBy( - keySelector: p => p.Username, - resultSelector: (key, group) => new { Username = key, Count = group.Count() }) - .ToDictionary(k => k.Username, v => v.Count); + .ToList(); - var response = context.Conversations + var conversations = context.Conversations .AsNoTracking() - .Select(c => new Conversation - { - Username = c.Username, - IsActive = c.IsActive, - UnAcknowledgedMessageCount = unAckedConversations.GetValueOrDefault(c.Username), - }) .Where(expression) .OrderBy(c => c.Username) - .ToList() - .AsEnumerable(); + .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); } -- cgit v1.2.3 From 8352d28eb6eae848530aa2d6b4a4196d53f4ac88 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Dec 2022 16:34:44 -0600 Subject: finalize API --- .../API/Controllers/ConversationsController.cs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index 66ca62ff..6efb5459 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -155,14 +155,19 @@ namespace slskd.Messaging.API [HttpGet("")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(List), 200)] - public async Task GetAll([FromQuery]bool unAcknowledgedOnly = false) + public async Task GetAll([FromQuery] bool includeInactive = false, [FromQuery]bool unAcknowledgedOnly = false) { if (Program.IsRelayAgent) { return Forbid(); } - var conversations = await Messages.Conversations.ListAsync(c => c.IsActive && (!unAcknowledgedOnly || c.HasUnAcknowledgedMessages)); + var conversations = await Messages.Conversations.ListAsync(c => includeInactive || c.IsActive); + + if (unAcknowledgedOnly) + { + conversations = conversations.Where(c => c.HasUnAcknowledgedMessages); + } return Ok(conversations); } @@ -200,20 +205,27 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(404)] - public async Task GetMessagesByUsername([FromRoute]string username) + public async Task GetMessagesByUsername([FromRoute]string username, [FromQuery]bool unAcknowledgedOnly = false) { if (Program.IsRelayAgent) { return Forbid(); } - var messages = await Messages.Conversations.ListMessagesAsync(m => m.Username == username); + var conversation = await Messages.Conversations.FindAsync(username, includeMessages: true); - if (!messages.Any()) + if (conversation == default) { return NotFound(); } + var messages = conversation.Messages; + + if (unAcknowledgedOnly) + { + messages = messages.Where(m => !m.IsAcknowledged); + } + return Ok(messages); } -- cgit v1.2.3