about summary refs log tree commit diff
path: root/MatrixRoomUtils.Core/Extensions/IEnumerableExtensions.cs
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-06-25 03:07:05 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-06-25 03:07:05 +0200
commitf866946fbbe962c712049327ade9dcbd43900295 (patch)
tree3400fcce20f68a6ef3eb130f4ef57733e346d0e9 /MatrixRoomUtils.Core/Extensions/IEnumerableExtensions.cs
parentWorking sync (diff)
downloadMatrixUtils-f866946fbbe962c712049327ade9dcbd43900295.tar.xz
Working state, refactored Rory&::LibMatrix
Diffstat (limited to 'MatrixRoomUtils.Core/Extensions/IEnumerableExtensions.cs')
-rw-r--r--MatrixRoomUtils.Core/Extensions/IEnumerableExtensions.cs36
1 files changed, 36 insertions, 0 deletions
diff --git a/MatrixRoomUtils.Core/Extensions/IEnumerableExtensions.cs b/MatrixRoomUtils.Core/Extensions/IEnumerableExtensions.cs
new file mode 100644
index 0000000..98b0aab
--- /dev/null
+++ b/MatrixRoomUtils.Core/Extensions/IEnumerableExtensions.cs
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Text.Json;
+using MatrixRoomUtils.Core.Interfaces;
+using MatrixRoomUtils.Core.Responses;
+
+namespace MatrixRoomUtils.Core.Extensions;
+
+public static class IEnumerableExtensions {
+    public static List<StateEventResponse> DeserializeMatrixTypes(this List<JsonElement> stateEvents) {
+        return stateEvents.Select(DeserializeMatrixType).ToList();
+    }
+    
+    public static StateEventResponse DeserializeMatrixType(this JsonElement stateEvent) {
+        var type = stateEvent.GetProperty("type").GetString();
+        var knownType = StateEvent.KnownStateEventTypes.FirstOrDefault(x => x.GetCustomAttribute<MatrixEventAttribute>()?.EventName == type);
+        if (knownType == null) {
+            Console.WriteLine($"Warning: unknown event type '{type}'!");
+            return new StateEventResponse();
+        }
+        
+        var eventInstance = Activator.CreateInstance(typeof(StateEventResponse).MakeGenericType(knownType))!;
+        stateEvent.Deserialize(eventInstance.GetType());
+        
+        return (StateEventResponse) eventInstance;
+    }
+
+    public static void Replace(this List<StateEvent> stateEvents, StateEvent old, StateEvent @new) {
+        var index = stateEvents.IndexOf(old);
+        if (index == -1) return;
+        stateEvents[index] = @new;
+    }
+}
+
+public class MatrixEventAttribute : Attribute {
+    public string EventName { get; set; }
+}
\ No newline at end of file