about summary refs log tree commit diff
path: root/LibMatrix/Services
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--LibMatrix/Services/HomeserverProviderService.cs31
-rw-r--r--LibMatrix/Services/HomeserverResolverService.cs63
2 files changed, 36 insertions, 58 deletions
diff --git a/LibMatrix/Services/HomeserverProviderService.cs b/LibMatrix/Services/HomeserverProviderService.cs
index c7fa5c3..a43f518 100644
--- a/LibMatrix/Services/HomeserverProviderService.cs
+++ b/LibMatrix/Services/HomeserverProviderService.cs
@@ -16,23 +16,26 @@ public class HomeserverProviderService {
     }
 
     private static Dictionary<string, SemaphoreSlim> _authenticatedHomeserverSemaphore = new();
-    private static Dictionary<string, AuthenticatedHomeserverGeneric> _authenticatedHomeServerCache = new();
+    private static Dictionary<string, AuthenticatedHomeserverGeneric> _authenticatedHomeserverCache = new();
 
     private static Dictionary<string, SemaphoreSlim> _remoteHomeserverSemaphore = new();
-    private static Dictionary<string, RemoteHomeServer> _remoteHomeServerCache = new();
+    private static Dictionary<string, RemoteHomeserver> _remoteHomeserverCache = new();
 
-    public async Task<AuthenticatedHomeserverGeneric> GetAuthenticatedWithToken(string homeserver, string accessToken,
-        string? proxy = null) {
+    public async Task<AuthenticatedHomeserverGeneric> GetAuthenticatedWithToken(string homeserver, string accessToken, string? proxy = null) {
         var sem = _authenticatedHomeserverSemaphore.GetOrCreate(homeserver + accessToken, _ => new SemaphoreSlim(1, 1));
         await sem.WaitAsync();
-        lock (_authenticatedHomeServerCache) {
-            if (_authenticatedHomeServerCache.ContainsKey(homeserver + accessToken)) {
+        lock (_authenticatedHomeserverCache) {
+            if (_authenticatedHomeserverCache.ContainsKey(homeserver + accessToken)) {
                 sem.Release();
-                return _authenticatedHomeServerCache[homeserver + accessToken];
+                return _authenticatedHomeserverCache[homeserver + accessToken];
             }
         }
 
-        var domain = proxy ?? await _homeserverResolverService.ResolveHomeserverFromWellKnown(homeserver);
+        // var domain = proxy ?? (await _homeserverResolverService.ResolveHomeserverFromWellKnown(homeserver)).client;
+
+        var rhs = await RemoteHomeserver.Create(homeserver);
+        var serverVersion = await rhs.GetServerVersionAsync();
+        
 
         AuthenticatedHomeserverGeneric hs;
         if (true) {
@@ -44,15 +47,15 @@ public class HomeserverProviderService {
 
         // (() => hs.WhoAmI) = (await hs._httpClient.GetFromJsonAsync<WhoAmIResponse>("/_matrix/client/v3/account/whoami"))!;
 
-        lock(_authenticatedHomeServerCache)
-            _authenticatedHomeServerCache[homeserver + accessToken] = hs;
+        lock (_authenticatedHomeserverCache)
+            _authenticatedHomeserverCache[homeserver + accessToken] = hs;
         sem.Release();
 
         return hs;
     }
 
-    public async Task<RemoteHomeServer> GetRemoteHomeserver(string homeserver, string? proxy = null) {
-        var hs = await RemoteHomeServer.Create(proxy ?? await _homeserverResolverService.ResolveHomeserverFromWellKnown(homeserver));
+    public async Task<RemoteHomeserver> GetRemoteHomeserver(string homeserver, string? proxy = null) {
+        var hs = await RemoteHomeserver.Create(proxy ?? homeserver);
         // hs._httpClient.Dispose();
         // hs._httpClient = new MatrixHttpClient { BaseAddress = new Uri(hs.ServerName) };
         // hs._httpClient.Timeout = TimeSpan.FromSeconds(120);
@@ -65,8 +68,8 @@ public class HomeserverProviderService {
             Identifier = new LoginRequest.LoginIdentifier { User = user },
             Password = password
         };
-        var resp = await hs._httpClient.PostAsJsonAsync("/_matrix/client/v3/login", payload);
+        var resp = await hs.ClientHttpClient.PostAsJsonAsync("/_matrix/client/v3/login", payload);
         var data = await resp.Content.ReadFromJsonAsync<LoginResponse>();
         return data!;
     }
-}
+}
\ No newline at end of file
diff --git a/LibMatrix/Services/HomeserverResolverService.cs b/LibMatrix/Services/HomeserverResolverService.cs
index 75545db..06771b0 100644
--- a/LibMatrix/Services/HomeserverResolverService.cs
+++ b/LibMatrix/Services/HomeserverResolverService.cs
@@ -8,42 +8,28 @@ namespace LibMatrix.Services;
 public class HomeserverResolverService(ILogger<HomeserverResolverService>? logger = null) {
     private readonly MatrixHttpClient _httpClient = new();
 
-    private static readonly Dictionary<string, string> _wellKnownCache = new();
+    private static readonly Dictionary<string, (string, string)> _wellKnownCache = new();
     private static readonly Dictionary<string, SemaphoreSlim> _wellKnownSemaphores = new();
 
-    public async Task<string> ResolveHomeserverFromWellKnown(string homeserver) {
+    public async Task<(string client, string server)> ResolveHomeserverFromWellKnown(string homeserver) {
         if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
-        if(_wellKnownCache.TryGetValue(homeserver, out var known)) return known;
-        logger?.LogInformation("Resolving homeserver: {}", homeserver);
-        var res = await _resolveHomeserverFromWellKnown(homeserver);
-        if (!res.StartsWith("http")) res = "https://" + res;
-        if (res.EndsWith(":443")) res = res[..^4];
-        return res;
-    }
-
-    private async Task<string> _resolveHomeserverFromWellKnown(string homeserver) {
-        if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
-        var sem = _wellKnownSemaphores.GetOrCreate(homeserver, _ => new SemaphoreSlim(1, 1));
-        if(_wellKnownCache.TryGetValue(homeserver, out var wellKnown)) return wellKnown;
-        await sem.WaitAsync();
+        // if(!_wellKnownSemaphores.ContainsKey(homeserver))
+            // _wellKnownSemaphores[homeserver] = new(1, 1);
+        _wellKnownSemaphores.TryAdd(homeserver, new(1, 1));
+        await _wellKnownSemaphores[homeserver].WaitAsync();
         if (_wellKnownCache.TryGetValue(homeserver, out var known)) {
-            sem.Release();
+            _wellKnownSemaphores[homeserver].Release();
             return known;
         }
-
-        string? result = null;
-        logger?.LogInformation("Attempting to resolve homeserver: {}", homeserver);
-        result ??= await _tryResolveFromClientWellknown(homeserver);
-        result ??= await _tryResolveFromServerWellknown(homeserver);
-        result ??= await _tryCheckIfDomainHasHomeserver(homeserver);
-
-        if (result is null) throw new InvalidDataException($"Failed to resolve homeserver for {homeserver}! Is it online and configured correctly?");
-
-        //success!
-        logger?.LogInformation("Resolved homeserver: {} -> {}", homeserver, result);
-        _wellKnownCache[homeserver] = result;
-        sem.Release();
-        return result;
+        
+        logger?.LogInformation("Resolving homeserver: {}", homeserver);
+        var res = (
+            await _tryResolveFromClientWellknown(homeserver),
+            await _tryResolveFromServerWellknown(homeserver)
+        );
+        _wellKnownCache.Add(homeserver, res!);
+        _wellKnownSemaphores[homeserver].Release();
+        return res;
     }
 
     private async Task<string?> _tryResolveFromClientWellknown(string homeserver) {
@@ -63,6 +49,8 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
         if (await _httpClient.CheckSuccessStatus($"{homeserver}/.well-known/matrix/server")) {
             var resp = await _httpClient.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/server");
             var hs = resp.GetProperty("m.server").GetString();
+            if (!hs.StartsWithAnyOf("http://", "https://"))
+                hs = $"https://{hs}";
             return hs;
         }
 
@@ -70,24 +58,11 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
         return null;
     }
 
-    private async Task<string?> _tryCheckIfDomainHasHomeserver(string homeserver) {
-        logger?.LogInformation("Checking if {} hosts a homeserver...", homeserver);
-        if (await _httpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions"))
-            return homeserver;
-        logger?.LogInformation("No homeserver on shortname...");
-        return null;
-    }
-
-    private async Task<string?> _tryCheckIfSubDomainHasHomeserver(string homeserver, string subdomain) {
-        homeserver = homeserver.Replace("https://", $"https://{subdomain}.");
-        return await _tryCheckIfDomainHasHomeserver(homeserver);
-    }
-
     public async Task<string?> ResolveMediaUri(string homeserver, string mxc) {
         if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
         if (mxc is null) throw new ArgumentNullException(nameof(mxc));
         if (!mxc.StartsWith("mxc://")) throw new InvalidDataException("mxc must start with mxc://");
-        homeserver = await ResolveHomeserverFromWellKnown(homeserver);
+        homeserver = (await ResolveHomeserverFromWellKnown(homeserver)).client;
         return mxc.Replace("mxc://", $"{homeserver}/_matrix/media/v3/download/");
     }
 }