From ff13e64dca922550eb6a955de0690d841590a9b0 Mon Sep 17 00:00:00 2001 From: Rory& Date: Wed, 26 Mar 2025 11:13:59 +0100 Subject: Split out invite context, add empty filter constants --- .../LibMatrix.Utilities.Bot/BotCommandInstaller.cs | 6 +- .../Interfaces/IRoomInviteHandler.cs | 5 ++ .../Interfaces/RoomInviteContext.cs | 71 ++++++++++++++++++++++ .../Services/InviteListenerHostedService.cs | 33 ++++------ 4 files changed, 92 insertions(+), 23 deletions(-) create mode 100644 Utilities/LibMatrix.Utilities.Bot/Interfaces/IRoomInviteHandler.cs create mode 100644 Utilities/LibMatrix.Utilities.Bot/Interfaces/RoomInviteContext.cs (limited to 'Utilities') diff --git a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs index f7ef317..4947394 100644 --- a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs +++ b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs @@ -69,16 +69,16 @@ public class BotInstaller(IServiceCollection services) { return this; } - public BotInstaller WithInviteHandler(Func inviteHandler) { + public BotInstaller WithInviteHandler(Func inviteHandler) { services.AddSingleton(inviteHandler); services.AddHostedService(); services.AddSingleton(); return this; } - public BotInstaller WithInviteHandler() where T : class, InviteHandlerHostedService.IInviteHandler { + public BotInstaller WithInviteHandler() where T : class, IRoomInviteHandler { services.AddSingleton(); - services.AddSingleton>(sp => sp.GetRequiredService().HandleInviteAsync); + services.AddSingleton>(sp => sp.GetRequiredService().HandleInviteAsync); services.AddHostedService(); services.AddSingleton(); return this; diff --git a/Utilities/LibMatrix.Utilities.Bot/Interfaces/IRoomInviteHandler.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/IRoomInviteHandler.cs new file mode 100644 index 0000000..a25ca4a --- /dev/null +++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/IRoomInviteHandler.cs @@ -0,0 +1,5 @@ +namespace LibMatrix.Utilities.Bot.Interfaces; + +public interface IRoomInviteHandler { + public Task HandleInviteAsync(RoomInviteContext invite); +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/Interfaces/RoomInviteContext.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/RoomInviteContext.cs new file mode 100644 index 0000000..380c1c7 --- /dev/null +++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/RoomInviteContext.cs @@ -0,0 +1,71 @@ +using LibMatrix.EventTypes.Spec.State.RoomInfo; +using LibMatrix.Homeservers; +using LibMatrix.Responses; + +namespace LibMatrix.Utilities.Bot.Interfaces; + +public class RoomInviteContext { + public required string RoomId { get; init; } + public required AuthenticatedHomeserverGeneric Homeserver { get; init; } + public required StateEventResponse MemberEvent { get; init; } + public required SyncResponse.RoomsDataStructure.InvitedRoomDataStructure InviteData { get; init; } + + public async Task TryGetInviterNameAsync() { + var name = InviteData.InviteState?.Events? + .FirstOrDefault(evt => evt is { Type: RoomMemberEventContent.EventId } && evt.StateKey == MemberEvent.Sender)? + .ContentAs()?.DisplayName; + + if (!string.IsNullOrWhiteSpace(name)) + return name; + + try { + await Homeserver.GetProfileAsync(MemberEvent.Sender!); + } + catch { + //ignored + } + + return MemberEvent.Sender!; + } + + public async Task TryGetRoomNameAsync() { + // try to get room name from invite state + var name = InviteData.InviteState?.Events? + .FirstOrDefault(evt => evt is { Type: RoomNameEventContent.EventId, StateKey: "" })? + .ContentAs()?.Name; + + if (!string.IsNullOrWhiteSpace(name)) + return name; + + // try to get room alias + var alias = InviteData.InviteState?.Events? + .FirstOrDefault(evt => evt is { Type: RoomCanonicalAliasEventContent.EventId, StateKey: "" })? + .ContentAs()?.Alias; + + if (!string.IsNullOrWhiteSpace(alias)) + return alias; + + // try to get room name via public previews + try { + name = await Homeserver.GetRoom(RoomId).GetNameOrFallbackAsync(); + if (name != RoomId && !string.IsNullOrWhiteSpace(name)) + return name; + } + catch { + //ignored + } + + // fallback to room alias via public previews + try { + alias = (await Homeserver.GetRoom(RoomId).GetCanonicalAliasAsync())?.Alias; + if (!string.IsNullOrWhiteSpace(alias)) + return alias; + } + catch { + //ignored + } + + // fall back to room ID + return RoomId; + } +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/Services/InviteListenerHostedService.cs b/Utilities/LibMatrix.Utilities.Bot/Services/InviteListenerHostedService.cs index 9a5e3d9..ad78779 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Services/InviteListenerHostedService.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Services/InviteListenerHostedService.cs @@ -2,7 +2,7 @@ using System.Diagnostics.CodeAnalysis; using LibMatrix.Filters; using LibMatrix.Helpers; using LibMatrix.Homeservers; -using LibMatrix.Responses; +using LibMatrix.Utilities.Bot.Interfaces; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -13,9 +13,10 @@ public class InviteHandlerHostedService( ILogger logger, AuthenticatedHomeserverGeneric hs, InviteHandlerHostedService.InviteListenerSyncConfiguration listenerSyncConfiguration, - Func inviteHandler + Func inviteHandler ) : IHostedService { private Task? _listenerTask; + private CancellationTokenSource _cts = new(); private readonly SyncHelper _syncHelper = new(hs, logger) { Timeout = listenerSyncConfiguration.Timeout ?? 30_000, @@ -37,14 +38,15 @@ public class InviteHandlerHostedService( _syncHelper.Filter = listenerSyncConfiguration.Filter; } else { - _syncHelper.FilterId = await hs.NamedCaches.FilterCache.GetOrSetValueAsync("gay.rory.libmatrix.utilities.bot.invite_listener_syncfilter.dev", new SyncFilter() { - AccountData = new SyncFilter.EventFilter(types: [], limit: 1), - Presence = new SyncFilter.EventFilter(types: ["*"]), + _syncHelper.FilterId = await hs.NamedCaches.FilterCache.GetOrSetValueAsync("gay.rory.libmatrix.utilities.bot.invite_listener_syncfilter.dev0", new SyncFilter() { + AccountData = SyncFilter.EventFilter.Empty, + Presence = SyncFilter.EventFilter.Empty, Room = new SyncFilter.RoomFilter { - AccountData = new SyncFilter.RoomFilter.StateFilter(types: [], limit: 1), - Ephemeral = new SyncFilter.RoomFilter.StateFilter(types: [], limit: 1), - State = new SyncFilter.RoomFilter.StateFilter(types: []), + AccountData = SyncFilter.RoomFilter.StateFilter.Empty, + Ephemeral = SyncFilter.RoomFilter.StateFilter.Empty, + State = SyncFilter.RoomFilter.StateFilter.Empty, Timeline = new SyncFilter.RoomFilter.StateFilter(types: [], notSenders: [hs.WhoAmI.UserId]), + IncludeLeave = false } }); } @@ -55,7 +57,7 @@ public class InviteHandlerHostedService( _syncHelper.InviteReceivedHandlers.Add(async invite => { logger.LogInformation("Received invite to room {}", invite.Key); - var inviteEventArgs = new InviteEventArgs() { + var inviteEventArgs = new RoomInviteContext() { RoomId = invite.Key, InviteData = invite.Value, MemberEvent = invite.Value.InviteState?.Events?.First(x => x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId) @@ -70,7 +72,7 @@ public class InviteHandlerHostedService( if (!listenerSyncConfiguration.InitialSyncOnStartup) _syncHelper.SyncReceivedHandlers.Add(sync => File.WriteAllTextAsync(nextBatchFile, sync.NextBatch, cancellationToken)); - await _syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken); + await _syncHelper.RunSyncLoopAsync(cancellationToken: _cts.Token); } /// Triggered when the application host is performing a graceful shutdown. @@ -82,19 +84,10 @@ public class InviteHandlerHostedService( return; } - await _listenerTask.WaitAsync(cancellationToken); + await _cts.CancelAsync(); } - public class InviteEventArgs { - public required string RoomId { get; init; } - public required AuthenticatedHomeserverGeneric Homeserver { get; init; } - public required StateEventResponse MemberEvent { get; init; } - public required SyncResponse.RoomsDataStructure.InvitedRoomDataStructure InviteData { get; init; } - } - public interface IInviteHandler { - public Task HandleInviteAsync(InviteEventArgs invite); - } [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Configuration")] [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global", Justification = "Configuration")] -- cgit 1.5.1