about summary refs log tree commit diff
path: root/LibMatrix
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2024-10-03 20:51:53 +0200
committerRory& <root@rory.gay>2024-10-03 20:52:10 +0200
commit77650d16a9cc66fdfe393320164cd8248cdff389 (patch)
treef18bcde29714a96816b4919475f112b0d3a64421 /LibMatrix
parentUpdate ArcaneLibs versioning scheme (diff)
downloadLibMatrix-77650d16a9cc66fdfe393320164cd8248cdff389.tar.xz
More reliable room name fetching, disable room predecessor in creation content schema
Diffstat (limited to '')
-rw-r--r--LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs4
-rw-r--r--LibMatrix/RoomTypes/GenericRoom.cs31
-rw-r--r--LibMatrix/StateEvent.cs37
3 files changed, 52 insertions, 20 deletions
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs
index c619d0e..f26b8e5 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs
@@ -15,8 +15,8 @@ public class RoomCreateEventContent : EventContent {
     [JsonPropertyName("m.federate")]
     public bool? Federate { get; set; }
 
-    [JsonPropertyName("predecessor")]
-    public RoomCreatePredecessor? Predecessor { get; set; }
+    // [JsonPropertyName("predecessor")]
+    // public RoomCreatePredecessor? Predecessor { get; set; }
 
     [JsonPropertyName("type")]
     public string? Type { get; set; }
diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs
index b9d98bd..2ec8571 100644
--- a/LibMatrix/RoomTypes/GenericRoom.cs
+++ b/LibMatrix/RoomTypes/GenericRoom.cs
@@ -106,7 +106,7 @@ public class GenericRoom {
                 Console.WriteLine("WARNING: Homeserver does not support getting event ID from state events, falling back to sync");
                 var sh = new SyncHelper(Homeserver);
                 var emptyFilter = new SyncFilter.EventFilter(types: [], limit: 1, senders: [], notTypes: ["*"]);
-                var emptyStateFilter = new SyncFilter.RoomFilter.StateFilter(types: [], limit: 1, senders: [], notTypes: ["*"], rooms:[]);
+                var emptyStateFilter = new SyncFilter.RoomFilter.StateFilter(types: [], limit: 1, senders: [], notTypes: ["*"], rooms: []);
                 sh.Filter = new() {
                     Presence = emptyFilter,
                     AccountData = emptyFilter,
@@ -121,10 +121,11 @@ public class GenericRoom {
                 var sync = await sh.SyncAsync();
                 var state = sync.Rooms.Join[RoomId].State.Events;
                 var stateEvent = state.FirstOrDefault(x => x.Type == type && x.StateKey == stateKey);
-                if (stateEvent is null) throw new LibMatrixException() {
-                    ErrorCode = LibMatrixException.ErrorCodes.M_NOT_FOUND,
-                    Error = "State event not found in sync response"
-                };
+                if (stateEvent is null)
+                    throw new LibMatrixException() {
+                        ErrorCode = LibMatrixException.ErrorCodes.M_NOT_FOUND,
+                        Error = "State event not found in sync response"
+                    };
                 return stateEvent.EventId;
             }
 
@@ -232,7 +233,7 @@ public class GenericRoom {
         // var sw = Stopwatch.StartNew();
         var res = await Homeserver.ClientHttpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members");
         // if (sw.ElapsedMilliseconds > 1000)
-            // Console.WriteLine($"Members call responded in {sw.GetElapsedAndRestart()}");
+        // Console.WriteLine($"Members call responded in {sw.GetElapsedAndRestart()}");
         // else sw.Restart();
         // var resText = await res.Content.ReadAsStringAsync();
         // Console.WriteLine($"Members call response read in {sw.GetElapsedAndRestart()}");
@@ -240,7 +241,7 @@ public class GenericRoom {
             TypeInfoResolver = ChunkedStateEventResponseSerializerContext.Default
         });
         // if (sw.ElapsedMilliseconds > 100)
-            // Console.WriteLine($"Members call deserialised in {sw.GetElapsedAndRestart()}");
+        // Console.WriteLine($"Members call deserialised in {sw.GetElapsedAndRestart()}");
         // else sw.Restart();
         foreach (var resp in result.Chunk) {
             if (resp?.Type != "m.room.member") continue;
@@ -249,14 +250,14 @@ public class GenericRoom {
         }
 
         // if (sw.ElapsedMilliseconds > 100)
-            // Console.WriteLine($"Members call iterated in {sw.GetElapsedAndRestart()}");
+        // Console.WriteLine($"Members call iterated in {sw.GetElapsedAndRestart()}");
     }
 
     public async Task<FrozenSet<StateEventResponse>> GetMembersListAsync(bool joinedOnly = true) {
         // var sw = Stopwatch.StartNew();
         var res = await Homeserver.ClientHttpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members");
         // if (sw.ElapsedMilliseconds > 1000)
-            // Console.WriteLine($"Members call responded in {sw.GetElapsedAndRestart()}");
+        // Console.WriteLine($"Members call responded in {sw.GetElapsedAndRestart()}");
         // else sw.Restart();
         // var resText = await res.Content.ReadAsStringAsync();
         // Console.WriteLine($"Members call response read in {sw.GetElapsedAndRestart()}");
@@ -264,7 +265,7 @@ public class GenericRoom {
             TypeInfoResolver = ChunkedStateEventResponseSerializerContext.Default
         });
         // if (sw.ElapsedMilliseconds > 100)
-            // Console.WriteLine($"Members call deserialised in {sw.GetElapsedAndRestart()}");
+        // Console.WriteLine($"Members call deserialised in {sw.GetElapsedAndRestart()}");
         // else sw.Restart();
         var members = new List<StateEventResponse>();
         foreach (var resp in result.Chunk) {
@@ -274,7 +275,7 @@ public class GenericRoom {
         }
 
         // if (sw.ElapsedMilliseconds > 100)
-            // Console.WriteLine($"Members call iterated in {sw.GetElapsedAndRestart()}");
+        // Console.WriteLine($"Members call iterated in {sw.GetElapsedAndRestart()}");
         return members.ToFrozenSet();
     }
 
@@ -320,7 +321,9 @@ public class GenericRoom {
     [Obsolete("This method will be merged into GetNameAsync() in the future.")]
     public async Task<string> GetNameOrFallbackAsync(int maxMemberNames = 2) {
         try {
-            return await GetNameAsync();
+            var name = await GetNameAsync();
+            if (!string.IsNullOrEmpty(name)) return name;
+            throw new();
         }
         catch {
             try {
@@ -376,7 +379,7 @@ public class GenericRoom {
 
     public async Task UnbanAsync(string userId, string? reason = null) =>
         await Homeserver.ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/unban",
-            new UserIdAndReason { UserId = userId, Reason = reason});
+            new UserIdAndReason { UserId = userId, Reason = reason });
 
     public async Task InviteUserAsync(string userId, string? reason = null, bool skipExisting = true) {
         if (skipExisting && await GetStateOrNullAsync<RoomMemberEventContent>("m.room.member", userId) is not null)
@@ -510,7 +513,7 @@ public class GenericRoom {
 
         var uri = new Uri(path, UriKind.Relative);
         if (dir == "b" || dir == "f") uri = uri.AddQuery("dir", dir);
-        else if(!string.IsNullOrWhiteSpace(dir)) throw new ArgumentException("Invalid direction", nameof(dir));
+        else if (!string.IsNullOrWhiteSpace(dir)) throw new ArgumentException("Invalid direction", nameof(dir));
         if (!string.IsNullOrEmpty(from)) uri = uri.AddQuery("from", from);
         if (chunkLimit is not null) uri = uri.AddQuery("limit", chunkLimit.Value.ToString());
         if (recurse is not null) uri = uri.AddQuery("recurse", recurse.Value.ToString());
diff --git a/LibMatrix/StateEvent.cs b/LibMatrix/StateEvent.cs
index 073d26d..8b44d2c 100644
--- a/LibMatrix/StateEvent.cs
+++ b/LibMatrix/StateEvent.cs
@@ -44,6 +44,7 @@ public class StateEvent {
     public string FriendlyTypeNamePlural => MappedType.GetFriendlyNamePluralOrNull() ?? Type;
 
     private static readonly JsonSerializerOptions TypedContentSerializerOptions = new() {
+        // We need these, NumberHandling covers other number types that we don't want to convert
         Converters = {
             new JsonFloatStringConverter(),
             new JsonDoubleStringConverter(),
@@ -55,9 +56,6 @@ public class StateEvent {
     [SuppressMessage("ReSharper", "PropertyCanBeMadeInitOnly.Global")]
     public EventContent? TypedContent {
         get {
-            // if (Type == "m.receipt") {
-            // return null;
-            // }
             try {
                 var mappedType = GetStateEventType(Type);
                 if (mappedType == typeof(UnknownEventContent))
@@ -81,6 +79,18 @@ public class StateEvent {
         }
     }
 
+    public T? ContentAs<T>() {
+        try {
+            return RawContent.Deserialize<T>(TypedContentSerializerOptions)!;
+        }
+        catch (JsonException e) {
+            Console.WriteLine(e);
+            Console.WriteLine("Content:\n" + (RawContent?.ToJson() ?? "null"));
+        }
+
+        return default;
+    }
+
     [JsonPropertyName("state_key")]
     public string? StateKey { get; set; }
 
@@ -254,4 +264,23 @@ public class StateEventContentPolymorphicTypeInfoResolver : DefaultJsonTypeInfoR
 }
 */
 
-#endregion
\ No newline at end of file
+#endregion
+
+/*
+public class ForgivingObjectConverter<T> : JsonConverter<T> where T : new() {
+    public override T? Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) {
+        try {
+            var text = JsonDocument.ParseValue(ref reader).RootElement.GetRawText();
+            return JsonSerializer.Deserialize<T>(text, options);
+        }
+        catch (JsonException ex) {
+            Console.WriteLine(ex);
+            return null;
+        }
+    }
+
+    public override bool CanConvert(Type typeToConvert) => true;
+
+    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
+        => JsonSerializer.Serialize<T>(writer, value, options);
+}*/
\ No newline at end of file