about summary refs log tree commit diff
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--LibMatrix/Extensions/HttpClientExtensions.cs2
-rw-r--r--LibMatrix/RoomTypes/GenericRoom.cs48
-rw-r--r--LibMatrix/Services/HomeserverProviderService.cs11
3 files changed, 44 insertions, 17 deletions
diff --git a/LibMatrix/Extensions/HttpClientExtensions.cs b/LibMatrix/Extensions/HttpClientExtensions.cs
index c0366fb..a7d49c0 100644
--- a/LibMatrix/Extensions/HttpClientExtensions.cs
+++ b/LibMatrix/Extensions/HttpClientExtensions.cs
@@ -45,7 +45,7 @@ public class MatrixHttpClient : HttpClient {
             request.RequestUri = request.RequestUri.AddQuery(key, value);
         }
 
-        Console.WriteLine($"Sending request to {request.RequestUri}");
+        // Console.WriteLine($"Sending request to {request.RequestUri}");
 
         try {
             var webAssemblyEnableStreamingResponseKey =
diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs
index bfb7f43..f5cbc51 100644
--- a/LibMatrix/RoomTypes/GenericRoom.cs
+++ b/LibMatrix/RoomTypes/GenericRoom.cs
@@ -2,6 +2,7 @@ using System.Collections.Frozen;
 using System.Diagnostics;
 using System.Net.Http.Json;
 using System.Text.Json;
+using System.Text.Json.Nodes;
 using System.Text.Json.Serialization;
 using System.Web;
 using ArcaneLibs.Extensions;
@@ -41,25 +42,12 @@ public class GenericRoom {
         Homeserver.ClientHttpClient.GetFromJsonAsync<List<StateEventResponse>>($"/_matrix/client/v3/rooms/{RoomId}/state");
 
     public async Task<T?> GetStateAsync<T>(string type, string stateKey = "") {
-        var url = $"/_matrix/client/v3/rooms/{RoomId}/state";
-        if (!string.IsNullOrEmpty(type)) url += $"/{type}";
+        if (string.IsNullOrEmpty(type)) throw new ArgumentNullException(nameof(type), "Event type must be specified");
+        var url = $"/_matrix/client/v3/rooms/{RoomId}/state/{type}";
         if (!string.IsNullOrEmpty(stateKey)) url += $"/{stateKey}";
         try {
-#if DEBUG && false
-            var resp = await _httpClient.GetFromJsonAsync<JsonObject>(url);
-            try {
-                _homeServer._httpClient.PostAsJsonAsync(
-                    "http://localhost:5116/validate/" + typeof(T).AssemblyQualifiedName, resp);
-            }
-            catch (Exception e) {
-                Console.WriteLine("[!!] Checking state response failed: " + e);
-            }
-
-            return resp.Deserialize<T>();
-#else
             var resp = await Homeserver.ClientHttpClient.GetFromJsonAsync<T>(url);
             return resp;
-#endif
         }
         catch (MatrixException e) {
             // if (e is not { ErrorCodode: "M_NOT_FOUND" }) {
@@ -81,6 +69,36 @@ public class GenericRoom {
         }
     }
 
+    public async Task<StateEventResponse> GetStateEventAsync(string type, string stateKey = "") {
+        if (string.IsNullOrEmpty(type)) throw new ArgumentNullException(nameof(type), "Event type must be specified");
+        var url = $"/_matrix/client/v3/rooms/{RoomId}/state/{type}";
+        if (!string.IsNullOrEmpty(stateKey)) url += $"/{stateKey}";
+        url += "?format=event";
+        try {
+            var resp = await Homeserver.ClientHttpClient.GetFromJsonAsync<JsonObject>(url);
+            if(resp["type"]?.GetValue<string>() != type) throw new InvalidDataException("Returned event type does not match requested type, or server does not support passing `format`.");
+            return resp.Deserialize<StateEventResponse>();
+        }
+        catch (MatrixException e) {
+            // if (e is not { ErrorCodode: "M_NOT_FOUND" }) {
+            throw;
+            // }
+
+            // Console.WriteLine(e);
+            // return default;
+        }
+    }
+
+    public async Task<StateEventResponse?> GetStateEventOrNullAsync(string type, string stateKey = "") {
+        try {
+            return await GetStateEventAsync(type, stateKey);
+        }
+        catch (MatrixException e) {
+            if (e.ErrorCode == "M_NOT_FOUND") return default;
+            throw;
+        }
+    }
+
     public async Task<MessagesResponse> GetMessagesAsync(string from = "", int? limit = null, string dir = "b", string filter = "") {
         var url = $"/_matrix/client/v3/rooms/{RoomId}/messages?dir={dir}";
         if (!string.IsNullOrWhiteSpace(from)) url += $"&from={from}";
diff --git a/LibMatrix/Services/HomeserverProviderService.cs b/LibMatrix/Services/HomeserverProviderService.cs
index 4cf74d1..5ac47f1 100644
--- a/LibMatrix/Services/HomeserverProviderService.cs
+++ b/LibMatrix/Services/HomeserverProviderService.cs
@@ -38,11 +38,20 @@ public class HomeserverProviderService(ILogger<HomeserverProviderService> logger
             logger.LogInformation("Homeserver {homeserver} proxied via {proxy}...", homeserver, proxy);
         logger.LogInformation("{homeserver}: {clientVersions}", homeserver, clientVersions.ToJson());
 
+        ServerVersionResponse serverVersion;
+        try {
+            serverVersion = serverVersion = await (rhs.FederationClient?.GetServerVersionAsync() ?? Task.FromResult<ServerVersionResponse?>(null)!);
+        }
+        catch (Exception e) {
+            logger.LogError(e, "Failed to get server version for {homeserver}", homeserver);
+            sem.Release();
+            throw;
+        }
+        
         try {
             if (clientVersions.UnstableFeatures.TryGetValue("gay.rory.mxapiextensions.v0", out bool a) && a)
                 hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverMxApiExtended>(homeserver, accessToken, proxy);
             else {
-                var serverVersion = await (rhs.FederationClient?.GetServerVersionAsync() ?? Task.FromResult<ServerVersionResponse?>(null));
                 if (serverVersion is { Server.Name: "Synapse" })
                     hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverSynapse>(homeserver, accessToken, proxy);
                 else