about summary refs log tree commit diff
path: root/LibMatrix/Helpers
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-09-05 06:28:52 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-09-05 06:28:52 +0200
commitcf455ed8de20bbee011289223e7d8d5775dfd69e (patch)
treecbdfdbc207af64a105b4d21941a6f0e71ca65e9d /LibMatrix/Helpers
parentAdd start of Media Moderator PoC bot (diff)
downloadLibMatrix-cf455ed8de20bbee011289223e7d8d5775dfd69e.tar.xz
Media moderator PoC works, abstract command handling to library
Diffstat (limited to 'LibMatrix/Helpers')
-rw-r--r--LibMatrix/Helpers/MatrixEventAttribute.cs2
-rw-r--r--LibMatrix/Helpers/MediaResolver.cs7
-rw-r--r--LibMatrix/Helpers/MessageFormatter.cs39
-rw-r--r--LibMatrix/Helpers/SyncHelper.cs34
4 files changed, 57 insertions, 25 deletions
diff --git a/LibMatrix/Helpers/MatrixEventAttribute.cs b/LibMatrix/Helpers/MatrixEventAttribute.cs
index 7556019..7efc039 100644
--- a/LibMatrix/Helpers/MatrixEventAttribute.cs
+++ b/LibMatrix/Helpers/MatrixEventAttribute.cs
@@ -1,5 +1,3 @@
-using System;
-
 namespace LibMatrix.Helpers;
 
 [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
diff --git a/LibMatrix/Helpers/MediaResolver.cs b/LibMatrix/Helpers/MediaResolver.cs
index 6ddb221..5886618 100644
--- a/LibMatrix/Helpers/MediaResolver.cs
+++ b/LibMatrix/Helpers/MediaResolver.cs
@@ -1,6 +1,7 @@
+using LibMatrix.Services;
+
 namespace LibMatrix.Helpers;
 
-public class MediaResolver {
-    public static string ResolveMediaUri(string homeserver, string mxc) =>
-        mxc.Replace("mxc://", $"{homeserver}/_matrix/media/v3/download/");
+public static class MediaResolver {
+    public static string ResolveMediaUri(string homeserver, string mxc) => mxc.Replace("mxc://", $"{homeserver}/_matrix/media/v3/download/");
 }
diff --git a/LibMatrix/Helpers/MessageFormatter.cs b/LibMatrix/Helpers/MessageFormatter.cs
new file mode 100644
index 0000000..ff0a00f
--- /dev/null
+++ b/LibMatrix/Helpers/MessageFormatter.cs
@@ -0,0 +1,39 @@
+using ArcaneLibs.Extensions;
+using LibMatrix.StateEventTypes.Spec;
+
+namespace LibMatrix.Helpers;
+
+public static class MessageFormatter {
+    public static RoomMessageEventData FormatError(string error) {
+        return new RoomMessageEventData(body: error, messageType: "m.text") {
+            FormattedBody = $"<font color=\"#FF0000\">{error}: {error}</font>",
+            Format = "org.matrix.custom.html"
+        };
+    }
+
+    public static RoomMessageEventData FormatException(string error, Exception e) {
+        return new RoomMessageEventData(body: $"{error}: {e.Message}", messageType: "m.text") {
+            FormattedBody = $"<font color=\"#FF0000\">{error}: <pre>{e.Message}</pre>" +
+                            $"</font>",
+            Format = "org.matrix.custom.html"
+        };
+    }
+
+    public static RoomMessageEventData FormatSuccess(string text) {
+        return new RoomMessageEventData(body: text, messageType: "m.text") {
+            FormattedBody = $"<font color=\"#00FF00\">{text}</font>",
+            Format = "org.matrix.custom.html"
+        };
+    }
+
+    public static RoomMessageEventData FormatSuccessJson(string text, object data) {
+        return new RoomMessageEventData(body: text, messageType: "m.text") {
+            FormattedBody = $"<font color=\"#00FF00\">{text}: <pre>{data.ToJson(ignoreNull: true)}</pre></font>",
+            Format = "org.matrix.custom.html"
+        };
+    }
+
+    public static string HtmlFormatMention(string id, string? displayName = null) {
+        return $"<a href=\"https://matrix.to/#/{id}\">{displayName ?? id}</a>";
+    }
+}
diff --git a/LibMatrix/Helpers/SyncHelper.cs b/LibMatrix/Helpers/SyncHelper.cs
index 83b1685..d719184 100644
--- a/LibMatrix/Helpers/SyncHelper.cs
+++ b/LibMatrix/Helpers/SyncHelper.cs
@@ -1,13 +1,7 @@
-using System;
-using System.Collections.Generic;
 using System.Diagnostics.CodeAnalysis;
-using System.Linq;
 using System.Net.Http.Json;
 using System.Text.Json.Serialization;
-using System.Threading;
-using System.Threading.Tasks;
 using ArcaneLibs.Extensions;
-using LibMatrix.Extensions;
 using LibMatrix.Filters;
 using LibMatrix.Homeservers;
 using LibMatrix.Responses;
@@ -15,15 +9,7 @@ using LibMatrix.Services;
 
 namespace LibMatrix.Helpers;
 
-public class SyncHelper {
-    private readonly AuthenticatedHomeserverGeneric _homeserver;
-    private readonly TieredStorageService _storageService;
-
-    public SyncHelper(AuthenticatedHomeserverGeneric homeserver, TieredStorageService storageService) {
-        _homeserver = homeserver;
-        _storageService = storageService;
-    }
-
+public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, TieredStorageService storageService) {
     public async Task<SyncResult?> Sync(
         string? since = null,
         int? timeout = 30000,
@@ -31,7 +17,7 @@ public class SyncHelper {
         SyncFilter? filter = null,
         CancellationToken? cancellationToken = null) {
         var outFileName = "sync-" +
-                          (await _storageService.CacheStorageProvider.GetAllKeysAsync()).Count(
+                          (await storageService.CacheStorageProvider.GetAllKeysAsync()).Count(
                               x => x.StartsWith("sync")) +
                           ".json";
         var url = $"/_matrix/client/v3/sync?timeout={timeout}&set_presence={setPresence}";
@@ -40,7 +26,7 @@ public class SyncHelper {
         // else url += "&full_state=true";
         Console.WriteLine("Calling: " + url);
         try {
-            var req = await _homeserver._httpClient.GetAsync(url, cancellationToken: cancellationToken ?? CancellationToken.None);
+            var req = await homeserver._httpClient.GetAsync(url, cancellationToken: cancellationToken ?? CancellationToken.None);
 
             // var res = await JsonSerializer.DeserializeAsync<SyncResult>(await req.Content.ReadAsStreamAsync());
 
@@ -79,10 +65,10 @@ public class SyncHelper {
         SyncFilter? filter = null,
         CancellationToken? cancellationToken = null
     ) {
-        await Task.WhenAll((await _storageService.CacheStorageProvider.GetAllKeysAsync())
+        await Task.WhenAll((await storageService.CacheStorageProvider.GetAllKeysAsync())
             .Where(x => x.StartsWith("sync"))
             .ToList()
-            .Select(x => _storageService.CacheStorageProvider.DeleteObjectAsync(x)));
+            .Select(x => storageService.CacheStorageProvider.DeleteObjectAsync(x)));
         var nextBatch = since;
         while (cancellationToken is null || !cancellationToken.Value.IsCancellationRequested) {
             var sync = await Sync(since: nextBatch, timeout: timeout, setPresence: setPresence, filter: filter,
@@ -116,7 +102,15 @@ public class SyncHelper {
                     if(updatedRoom.Value.Timeline is null) continue;
                     foreach (var stateEventResponse in updatedRoom.Value.Timeline.Events) {
                         stateEventResponse.RoomId = updatedRoom.Key;
-                        var tasks = TimelineEventHandlers.Select(x => x(stateEventResponse)).ToList();
+                        var tasks = TimelineEventHandlers.Select(x => {
+                            try {
+                                return x(stateEventResponse);
+                            }
+                            catch (Exception e) {
+                                Console.WriteLine(e);
+                                return Task.CompletedTask;
+                            }
+                        }).ToList();
                         await Task.WhenAll(tasks);
                     }
                 }