about summary refs log tree commit diff
path: root/MatrixContentFilter/Services
diff options
context:
space:
mode:
Diffstat (limited to 'MatrixContentFilter/Services')
-rw-r--r--MatrixContentFilter/Services/AsyncActionQueues/AbstractionAsyncActionQueue.cs1
-rw-r--r--MatrixContentFilter/Services/AsyncActionQueues/FiFoAsyncActionQueue.cs2
-rw-r--r--MatrixContentFilter/Services/BotModeSanityCheckService.cs14
-rw-r--r--MatrixContentFilter/Services/ConfigurationService.cs9
-rw-r--r--MatrixContentFilter/Services/InfoCacheService.cs13
-rw-r--r--MatrixContentFilter/Services/MatrixContentFilterBot.cs5
-rw-r--r--MatrixContentFilter/Services/MatrixContentFilterMetrics.cs16
7 files changed, 42 insertions, 18 deletions
diff --git a/MatrixContentFilter/Services/AsyncActionQueues/AbstractionAsyncActionQueue.cs b/MatrixContentFilter/Services/AsyncActionQueues/AbstractionAsyncActionQueue.cs

index f4c559c..945d264 100644 --- a/MatrixContentFilter/Services/AsyncActionQueues/AbstractionAsyncActionQueue.cs +++ b/MatrixContentFilter/Services/AsyncActionQueues/AbstractionAsyncActionQueue.cs
@@ -1,7 +1,6 @@ using System.Collections.Concurrent; using System.Threading.Channels; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; namespace MatrixContentFilter.Services.AsyncActionQueues; diff --git a/MatrixContentFilter/Services/AsyncActionQueues/FiFoAsyncActionQueue.cs b/MatrixContentFilter/Services/AsyncActionQueues/FiFoAsyncActionQueue.cs
index 3d7c90d..8c67c77 100644 --- a/MatrixContentFilter/Services/AsyncActionQueues/FiFoAsyncActionQueue.cs +++ b/MatrixContentFilter/Services/AsyncActionQueues/FiFoAsyncActionQueue.cs
@@ -1,6 +1,4 @@ -using System.Collections.Concurrent; using System.Threading.Channels; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MatrixContentFilter.Services.AsyncActionQueues; diff --git a/MatrixContentFilter/Services/BotModeSanityCheckService.cs b/MatrixContentFilter/Services/BotModeSanityCheckService.cs
index 55fe9e8..0a99ca1 100644 --- a/MatrixContentFilter/Services/BotModeSanityCheckService.cs +++ b/MatrixContentFilter/Services/BotModeSanityCheckService.cs
@@ -1,13 +1,8 @@ -using System.Diagnostics; -using ArcaneLibs; using ArcaneLibs.Extensions; -using LibMatrix; using LibMatrix.Filters; using LibMatrix.Helpers; using LibMatrix.Homeservers; -using LibMatrix.Responses; using MatrixContentFilter.Abstractions; -using MatrixContentFilter.Handlers.Filters; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -18,19 +13,22 @@ public class BotModeSanityCheckService( AuthenticatedHomeserverGeneric hs, ConfigurationService filterConfigService, IEnumerable<IContentFilter> filters, - AsyncMessageQueue msgQueue + AsyncMessageQueue msgQueue, + MatrixContentFilterConfiguration cfg ) : BackgroundService { /// <summary>Triggered when the application host is ready to start the service.</summary> /// <param name="cancellationToken">Indicates that the start process has been aborted.</param> protected override async Task ExecuteAsync(CancellationToken cancellationToken) { + var semaphore = new SemaphoreSlim(cfg.SanityCheck.MaxConcurrency); while (!cancellationToken.IsCancellationRequested) { - await Task.Delay(10000, cancellationToken); + await Task.Delay(cfg.SanityCheck.Interval, cancellationToken); var rooms = await hs.GetJoinedRooms(); rooms.RemoveAll(x => x.RoomId == filterConfigService.LogRoom.RoomId); rooms.RemoveAll(x => x.RoomId == filterConfigService.ControlRoom.RoomId); var timelineFilter = new SyncFilter.RoomFilter.StateFilter(notTypes: ["m.room.redaction"], limit: 5000); var timelines = rooms.Select(async x => { + await semaphore.WaitAsync(cancellationToken); var room = hs.GetRoom(x.RoomId); // var sync = await room.GetMessagesAsync(null, 1500, filter: timelineFilter.ToJson(ignoreNull: true, indent: false).UrlEncode()); var iter = room.GetManyMessagesAsync(null, 5000, filter: timelineFilter.ToJson(ignoreNull: true, indent: false).UrlEncode(), chunkSize: 250); @@ -49,6 +47,8 @@ public class BotModeSanityCheckService( await tasks; } + + semaphore.Release(); }).ToList(); await Task.WhenAll(timelines); } diff --git a/MatrixContentFilter/Services/ConfigurationService.cs b/MatrixContentFilter/Services/ConfigurationService.cs
index f83c89a..cd2a93d 100644 --- a/MatrixContentFilter/Services/ConfigurationService.cs +++ b/MatrixContentFilter/Services/ConfigurationService.cs
@@ -1,6 +1,6 @@ using ArcaneLibs.Extensions; using LibMatrix; -using LibMatrix.EventTypes.Spec.State; +using LibMatrix.EventTypes.Spec.State.RoomInfo; using LibMatrix.Helpers; using LibMatrix.Homeservers; using LibMatrix.Responses; @@ -28,7 +28,7 @@ public class ConfigurationService(ILogger<ConfigurationService> logger, Authenti await foreach (var sync in syncHelper.EnumerateSyncAsync(stoppingToken).WithCancellation(stoppingToken)) { if (sync is { AccountData: null, Rooms: null }) continue; - logger.LogInformation("Received configuration update: {syncData}", sync.ToJson(ignoreNull: true)); + logger.LogInformation("Received configuration update..."); await OnSyncReceived(sync); } } @@ -165,6 +165,11 @@ public class ConfigurationService(ILogger<ConfigurationService> logger, Authenti _filterConfiguration.UrlFilter ??= new(); _filterConfiguration.UrlFilter.IgnoredUsers ??= Log("url_filter->ignored_users", (List<string>) []); _filterConfiguration.UrlFilter.Allowed ??= Log("url_filter->allowed", false); + + _filterConfiguration.InviteLimiter ??= new(); + _filterConfiguration.InviteLimiter.IgnoredUsers ??= Log("invite_limiter->ignored_users", (List<string>) []); + _filterConfiguration.InviteLimiter.HeuristicTripPoint ??= Log("invite_limiter->heuristic_trip_point", 5); + _filterConfiguration.InviteLimiter.MaxCount ??= Log("invite_limiter->max_count", 15); if (changes.Count > 0) { await hs.SetAccountDataAsync(FilterConfiguration.EventId, _filterConfiguration); diff --git a/MatrixContentFilter/Services/InfoCacheService.cs b/MatrixContentFilter/Services/InfoCacheService.cs
index 974e873..5f7ab10 100644 --- a/MatrixContentFilter/Services/InfoCacheService.cs +++ b/MatrixContentFilter/Services/InfoCacheService.cs
@@ -1,5 +1,6 @@ using ArcaneLibs.Collections; -using LibMatrix.EventTypes.Spec.State; +using LibMatrix; +using LibMatrix.EventTypes.Spec.State.RoomInfo; using LibMatrix.Homeservers; namespace MatrixContentFilter.Services; @@ -11,8 +12,14 @@ public class InfoCacheService(AuthenticatedHomeserverGeneric hs) { public async Task<string> GetDisplayNameAsync(string roomId, string userId) => await DisplayNameCache.GetOrAdd($"{roomId}\t{userId}", async () => { var room = hs.GetRoom(roomId); - var userState = await room.GetStateAsync<RoomMemberEventContent>(RoomMemberEventContent.EventId, userId); - if (!string.IsNullOrWhiteSpace(userState?.DisplayName)) return userState.DisplayName; + try { + var userState = await room.GetStateOrNullAsync<RoomMemberEventContent>(RoomMemberEventContent.EventId, userId); + if (!string.IsNullOrWhiteSpace(userState?.DisplayName)) return userState.DisplayName; + } + catch (MatrixException e) { + if (e is not { ErrorCode: MatrixException.ErrorCodes.M_NOT_FOUND or MatrixException.ErrorCodes.M_FORBIDDEN }) + throw; + } var user = await hs.GetProfileAsync(userId); if (!string.IsNullOrWhiteSpace(user?.DisplayName)) return user.DisplayName; diff --git a/MatrixContentFilter/Services/MatrixContentFilterBot.cs b/MatrixContentFilter/Services/MatrixContentFilterBot.cs
index 321cdd4..12fa5f6 100644 --- a/MatrixContentFilter/Services/MatrixContentFilterBot.cs +++ b/MatrixContentFilter/Services/MatrixContentFilterBot.cs
@@ -6,7 +6,6 @@ using LibMatrix.Helpers; using LibMatrix.Homeservers; using LibMatrix.Responses; using MatrixContentFilter.Abstractions; -using MatrixContentFilter.Handlers.Filters; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -49,7 +48,7 @@ public class MatrixContentFilterBot( var syncFilter = new SyncFilter() { Room = new() { NotRooms = [filterConfigService.LogRoom.RoomId], - Timeline = new(notTypes: ["m.room.redaction"]) + Timeline = new(notTypes: ["m.room.redaction"], limit: 5000) } }; syncHelper = new SyncHelper(hs, logger) { @@ -114,7 +113,7 @@ public class MatrixContentFilterBot( var room = hs.GetRoom(roomId); if (roomData.Timeline?.Limited == true) { msgQueue.EnqueueMessageAsync(filterConfigService.LogRoom, new MessageBuilder("m.notice") - .WithColoredBody("FF0000", $"Room {roomId} has limited timeline, fetching! The room may be getting spammed?") + .WithColoredBody("#FF0000", $"Room {roomId} has limited timeline, fetching! The room may be getting spammed?") .Build()); roomData.Timeline.Events ??= []; var newEvents = await room.GetMessagesAsync(roomData.Timeline.PrevBatch ?? "", 500, filter: timelineFilter.ToJson(ignoreNull: true, indent: false)); diff --git a/MatrixContentFilter/Services/MatrixContentFilterMetrics.cs b/MatrixContentFilter/Services/MatrixContentFilterMetrics.cs new file mode 100644
index 0000000..ff88cad --- /dev/null +++ b/MatrixContentFilter/Services/MatrixContentFilterMetrics.cs
@@ -0,0 +1,16 @@ +using System.Collections.Frozen; +using System.Diagnostics.Metrics; + +namespace MatrixContentFilter.Services; + +public class MatrixContentFilterMetrics { + private readonly Meter meter = new Meter("MatrixContentFilter"); + private FrozenDictionary<string, Counter<int>> _counters = FrozenDictionary<string, Counter<int>>.Empty; + + public void Increment(string counter, int value = 1) { + if(!_counters.TryGetValue(counter, out var c)) { + c = meter.CreateCounter<int>(counter); + _counters = _counters.Concat([new KeyValuePair<string, Counter<int>>(counter, c)]).ToFrozenDictionary(); + } + } +} \ No newline at end of file