diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-07-30 20:44:58 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-07-30 20:44:58 -0500 |
| commit | da71a74850b837ce6e831b9212714e510e72ca5e (patch) | |
| tree | 523dc96ed715cf8098758365c6c9277c79b89fa1 /src | |
| parent | 1fade356f1b8b38e269408aeec89e96e5fae5cb6 (diff) | |
| parent | 5beeea03a1bc4f0c05467a7668c7f8a104f69206 (diff) | |
| download | slskd-da71a74850b837ce6e831b9212714e510e72ca5e.tar.gz | |
Merge pull request #1399 from slskd/msg-events
Add chat events for webhooks and scripts
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 28 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs | 81 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrator.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Events/API/EventsController.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Events/Types/Events.cs | 22 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/PublicChatController.cs | 82 | ||||
| -rw-r--r-- | src/slskd/Messaging/ConversationService.cs | 17 | ||||
| -rw-r--r-- | src/slskd/Messaging/RoomService.cs | 13 | ||||
| -rw-r--r-- | src/slskd/Messaging/Types/PrivateMessage.cs | 6 |
10 files changed, 150 insertions, 110 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index ab666c85..1532e33e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -91,7 +91,6 @@ namespace slskd ConnectionWatchdog connectionWatchdog, ITransferService transferService, IBrowseTracker browseTracker, - IRoomTracker roomTracker, IRoomService roomService, IUserService userService, IMessagingService messagingService, @@ -99,7 +98,6 @@ namespace slskd ISearchService searchService, IPushbulletService pushbulletService, IRelayService relayService, - EventService eventService, IHubContext<ApplicationHub> applicationHub, IHubContext<LogsHub> logHub) { @@ -149,8 +147,6 @@ namespace slskd Search = searchService; - Events = eventService; - Transfers = transferService; BrowseTracker = browseTracker; Pushbullet = pushbulletService; @@ -182,7 +178,6 @@ namespace slskd Client.PrivateRoomModerationAdded += (e, room) => Log.Information("Promoted to moderator in private room {Room}", room); Client.PrivateRoomModerationRemoved += (e, room) => Log.Information("Demoted from moderator in private room {Room}", room); - Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; Client.RoomMessageReceived += Client_RoomMessageReceived; Client.Disconnected += Client_Disconnected; Client.Connected += Client_Connected; @@ -231,7 +226,6 @@ namespace slskd private IUserService Users { get; set; } private IShareService Shares { get; set; } private ISearchService Search { get; set; } - private EventService Events { get; } private IRelayService Relay { get; set; } private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions()); private IEnumerable<Regex> CompiledSearchResponseFilters { get; set; } @@ -945,6 +939,10 @@ namespace slskd Log.Debug("Ignored private message from blacklisted user {Username}: {Message}", args.Username, args.Message); return; } + else + { + // todo: raise blacklisted message event? + } Messaging.Conversations.HandleMessageAsync(args.Username, PrivateMessage.FromEventArgs(args)); @@ -954,25 +952,11 @@ namespace slskd } } - private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) - { - if (Users.IsBlacklisted(args.Username)) - { - Log.Debug("Ignored public chat message from blacklisted user {Username}: {Message}", args.Username, args.Message); - return; - } - - Log.Information("[Public Chat/{Room}] [{Username}]: {Message}", args.RoomName, args.Username, args.Message); - - if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) - { - _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); - } - } - private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) { // note: this event is also subscribed in the RoomService class + // this handler is only used for pushbullet. + // todo: refactor pushbullet so that it uses events if (Users.IsBlacklisted(args.Username)) { return; diff --git a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs index f7af80f5..0d540565 100644 --- a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs @@ -24,6 +24,7 @@ using System.IO; using System.Linq; using Microsoft.Data.Sqlite; using Serilog; +using slskd.Transfers; /// <summary> /// Updates the Transfers table to: @@ -50,7 +51,7 @@ public class Z04012025_TransferStateMigration : IMigration var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; - return !txfers.Any(c => c.Name == "StateDescription"); + return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription)); } public void Apply() diff --git a/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs b/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs new file mode 100644 index 00000000..2f587f9e --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs @@ -0,0 +1,81 @@ +// <copyright file="Z07262025_PrivateMessageWasReplayedMigration.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.Migrations; + +using System; +using System.IO; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using slskd.Messaging; + +/// <summary> +/// Updates the Transfers table to add indexes on the Direction and State columns. +/// </summary> +public class Z07262025_PrivateMessageWasReplayedMigration : IMigration +{ + private ILogger Log { get; } = Serilog.Log.ForContext<Z07262025_PrivateMessageWasReplayedMigration>(); + private string DatabaseName { get; } = "messaging"; + private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; + + public bool NeedsToBeApplied() + { + // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var pms = schema["PrivateMessages"]; + + if (pms.Any(r => r.Name == nameof(PrivateMessage.WasReplayed))) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z07262025_PrivateMessageWasReplayedMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + Log.Information("> Adding missing column WasReplayed to PrivateMessages table..."); + + var addColumnCommand = new SqliteCommand(@" + ALTER TABLE PrivateMessages ADD COLUMN WasReplayed INTEGER NOT NULL DEFAULT 0 + ", connection, transaction); + addColumnCommand.ExecuteNonQuery(); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 645f4575..9fe54024 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -45,10 +45,15 @@ public class Migrator /// <summary> /// A map of all migrations, to be applied in the order they are specified (descending). /// </summary> + /// <remarks> + /// This could be done with reflection (e.g. find all instances of IMigration) but it's useful during development + /// to selectively add/comment out lines. Slight risk that something is missed, so this should be append only. + /// </remarks> private Dictionary<string, IMigration> Migrations { get; } = new() { { nameof(Z04012025_TransferStateMigration), new Z04012025_TransferStateMigration() }, { nameof(Z07062025_TransferIndexesMigration), new Z07062025_TransferIndexesMigration() }, + { nameof(Z07262025_PrivateMessageWasReplayedMigration), new Z07262025_PrivateMessageWasReplayedMigration() }, }; /// <summary> diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs index 391b6db5..cd6400ca 100644 --- a/src/slskd/Events/API/EventsController.cs +++ b/src/slskd/Events/API/EventsController.cs @@ -25,6 +25,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; +using slskd.Messaging; using slskd.Transfers; /// <summary> @@ -137,6 +138,8 @@ public class EventsController : ControllerBase EventType.DownloadFileComplete => new DownloadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }, EventType.DownloadDirectoryComplete => new DownloadDirectoryCompleteEvent { LocalDirectoryName = $"{d}local.directory", RemoteDirectoryName = $"{d}remote.directory", Username = $"{d}username" }, EventType.UploadFileComplete => new UploadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }, + EventType.PrivateMessageReceived => new PrivateMessageReceivedEvent { Message = new PrivateMessage { Id = 42, Timestamp = DateTime.UtcNow, Username = $"{d}username", Message = $"{d}message" } }, + EventType.RoomMessageReceived => new RoomMessageReceivedEvent { Message = new RoomMessage { RoomName = $"{d}room", Username = $"{d}username", Message = $"{d}message" } }, EventType.Noop => new NoopEvent(), _ => throw new SlskdException($"Event type {eventType} is an enum member but is not handled. Please submit an issue on GitHub."), }; diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index eec9b292..6e99b800 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -18,6 +18,7 @@ namespace slskd.Events; using System; +using slskd.Messaging; using slskd.Transfers; public enum EventType @@ -27,6 +28,9 @@ public enum EventType DownloadFileComplete = 2, DownloadDirectoryComplete = 3, UploadFileComplete = 4, + // UploadDirectoryComplete = 5, + PrivateMessageReceived = 6, + RoomMessageReceived = 7, Noop = int.MaxValue, } @@ -40,7 +44,7 @@ public abstract record Event public sealed record DownloadFileCompleteEvent : Event { - public override EventType Type { get; } = EventType.DownloadFileComplete; + public override EventType Type => EventType.DownloadFileComplete; public override int Version { get; } = 0; public required string LocalFilename { get; init; } public required string RemoteFilename { get; init; } @@ -58,13 +62,27 @@ public sealed record DownloadDirectoryCompleteEvent : Event public sealed record UploadFileCompleteEvent : Event { - public override EventType Type { get; } = EventType.UploadFileComplete; + public override EventType Type => EventType.UploadFileComplete; public override int Version { get; } = 0; public required string LocalFilename { get; init; } public required string RemoteFilename { get; init; } public required Transfer Transfer { get; init; } } +public sealed record PrivateMessageReceivedEvent : Event +{ + public override EventType Type => EventType.PrivateMessageReceived; + public override int Version => 0; + public required PrivateMessage Message { get; init; } +} + +public sealed record RoomMessageReceivedEvent : Event +{ + public override EventType Type => EventType.RoomMessageReceived; + public override int Version => 0; + public required RoomMessage Message { get; init; } +} + public sealed record NoopEvent : Event { public override EventType Type => EventType.Noop; diff --git a/src/slskd/Messaging/API/Controllers/PublicChatController.cs b/src/slskd/Messaging/API/Controllers/PublicChatController.cs deleted file mode 100644 index d44a5b5a..00000000 --- a/src/slskd/Messaging/API/Controllers/PublicChatController.cs +++ /dev/null @@ -1,82 +0,0 @@ -// <copyright file="PublicChatController.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -using Microsoft.Extensions.Options; - -namespace slskd.Messaging.API -{ - using System.Threading.Tasks; - using Asp.Versioning; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc; - using Soulseek; - - /// <summary> - /// Server. - /// </summary> - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class PublicChatController : ControllerBase - { - public PublicChatController(ISoulseekClient soulseekClient, IOptionsSnapshot<Options> optionsSnapshot) - { - Client = soulseekClient; - OptionsSnapshot = optionsSnapshot; - } - - private ISoulseekClient Client { get; } - private IOptionsSnapshot<Options> OptionsSnapshot { get; } - - /// <summary> - /// Starts public chat. - /// </summary> - /// <returns></returns> - [HttpPost] - [Authorize(Policy = AuthPolicy.Any)] - public async Task<IActionResult> Start() - { - if (Program.IsRelayAgent) - { - return Forbid(); - } - - await Client.StartPublicChatAsync(); - return StatusCode(StatusCodes.Status201Created); - } - - /// <summary> - /// Stops public chat. - /// </summary> - /// <returns></returns> - [HttpDelete] - [Authorize(Policy = AuthPolicy.Any)] - public async Task<IActionResult> Stop() - { - if (Program.IsRelayAgent) - { - return Forbid(); - } - - await Client.StopPublicChatAsync(); - return StatusCode(StatusCodes.Status204NoContent); - } - } -} diff --git a/src/slskd/Messaging/ConversationService.cs b/src/slskd/Messaging/ConversationService.cs index de772ff0..b39162d6 100644 --- a/src/slskd/Messaging/ConversationService.cs +++ b/src/slskd/Messaging/ConversationService.cs @@ -24,6 +24,7 @@ namespace slskd.Messaging using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using slskd.Events; using Soulseek; /// <summary> @@ -112,12 +113,15 @@ namespace slskd.Messaging { public ConversationService( ISoulseekClient soulseekClient, + EventBus eventBus, IDbContextFactory<MessagingDbContext> contextFactory) { SoulseekClient = soulseekClient; + EventBus = eventBus; ContextFactory = contextFactory; } + private EventBus EventBus { get; } private IDbContextFactory<MessagingDbContext> ContextFactory { get; } private ILogger Log { get; } = Serilog.Log.ForContext<ConversationService>(); private ISoulseekClient SoulseekClient { get; } @@ -301,8 +305,12 @@ namespace slskd.Messaging if (existing != null) { - // the message was replayed. ensure the local ack bit is in sync with the server - existing.IsAcknowledged = message.IsAcknowledged; + // the message was replayed. either we haven't ACKed it, or we did and the ACK didn't make it to the + // server. either way we need to ensure that the local db understands the message needs to be ACKed, so + // force the bit false. we shouldn't need to update any other part of the message because IDs are unique + // on the soulseek server + existing.IsAcknowledged = false; + existing.WasReplayed = message.WasReplayed; } else { @@ -312,6 +320,11 @@ namespace slskd.Messaging context.SaveChanges(); + EventBus.Raise(new PrivateMessageReceivedEvent + { + Message = message, + }); + return Task.CompletedTask; } diff --git a/src/slskd/Messaging/RoomService.cs b/src/slskd/Messaging/RoomService.cs index 8dd25431..e85de4a4 100644 --- a/src/slskd/Messaging/RoomService.cs +++ b/src/slskd/Messaging/RoomService.cs @@ -24,6 +24,7 @@ namespace slskd.Messaging using System.Linq; using System.Threading.Tasks; using Serilog; + using slskd.Events; using slskd.Users; using Soulseek; @@ -71,12 +72,14 @@ namespace slskd.Messaging /// <param name="stateMutator"></param> /// <param name="roomTracker"></param> /// <param name="userService"></param> + /// <param name="eventBus"></param> public RoomService( ISoulseekClient soulseekClient, IOptionsMonitor<Options> optionsMonitor, IStateMutator<State> stateMutator, IRoomTracker roomTracker, - IUserService userService) + IUserService userService, + EventBus eventBus) { Client = soulseekClient; @@ -86,6 +89,7 @@ namespace slskd.Messaging RoomTracker = roomTracker; Users = userService; + EventBus = eventBus; Client.LoggedIn += Client_LoggedIn; @@ -100,6 +104,7 @@ namespace slskd.Messaging private IOptionsMonitor<Options> OptionsMonitor { get; } private IRoomTracker RoomTracker { get; set; } private IUserService Users { get; set; } + private EventBus EventBus { get; } /// <summary> /// Joins the specified <paramref name="roomName"/>. @@ -228,6 +233,12 @@ namespace slskd.Messaging var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); RoomTracker.AddOrUpdateMessage(args.RoomName, message); + + // todo: persist these in the database before raising (why are we not??) + EventBus.Raise<RoomMessageReceivedEvent>(new RoomMessageReceivedEvent + { + Message = message, + }); } } }
\ No newline at end of file diff --git a/src/slskd/Messaging/Types/PrivateMessage.cs b/src/slskd/Messaging/Types/PrivateMessage.cs index a4b1c325..a036520d 100644 --- a/src/slskd/Messaging/Types/PrivateMessage.cs +++ b/src/slskd/Messaging/Types/PrivateMessage.cs @@ -55,6 +55,11 @@ namespace slskd.Messaging /// </summary> public bool IsAcknowledged { get; set; } = false; + /// <summary> + /// A value indicating whether the message has was replayed by the server. + /// </summary> + public bool WasReplayed { get; set; } = false; + public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) { return new PrivateMessage() @@ -64,6 +69,7 @@ namespace slskd.Messaging Username = eventArgs.Username, Message = eventArgs.Message, IsAcknowledged = false, + WasReplayed = eventArgs.Replayed, Direction = MessageDirection.In, }; } |
