about summary refs log tree commit diff
path: root/LibMatrix/Services
diff options
context:
space:
mode:
Diffstat (limited to 'LibMatrix/Services')
-rw-r--r--LibMatrix/Services/HomeserverProviderService.cs44
-rw-r--r--LibMatrix/Services/HomeserverResolverService.cs31
-rw-r--r--LibMatrix/Services/TieredStorageService.cs11
3 files changed, 43 insertions, 43 deletions
diff --git a/LibMatrix/Services/HomeserverProviderService.cs b/LibMatrix/Services/HomeserverProviderService.cs
index a43f518..5c8827c 100644
--- a/LibMatrix/Services/HomeserverProviderService.cs
+++ b/LibMatrix/Services/HomeserverProviderService.cs
@@ -6,15 +6,7 @@ using Microsoft.Extensions.Logging;
 
 namespace LibMatrix.Services;
 
-public class HomeserverProviderService {
-    private readonly ILogger<HomeserverProviderService> _logger;
-    private readonly HomeserverResolverService _homeserverResolverService;
-
-    public HomeserverProviderService(ILogger<HomeserverProviderService> logger, HomeserverResolverService homeserverResolverService) {
-        _logger = logger;
-        _homeserverResolverService = homeserverResolverService;
-    }
-
+public class HomeserverProviderService(ILogger<HomeserverProviderService> logger, HomeserverResolverService homeserverResolverService) {
     private static Dictionary<string, SemaphoreSlim> _authenticatedHomeserverSemaphore = new();
     private static Dictionary<string, AuthenticatedHomeserverGeneric> _authenticatedHomeserverCache = new();
 
@@ -22,40 +14,44 @@ public class HomeserverProviderService {
     private static Dictionary<string, RemoteHomeserver> _remoteHomeserverCache = new();
 
     public async Task<AuthenticatedHomeserverGeneric> GetAuthenticatedWithToken(string homeserver, string accessToken, string? proxy = null) {
-        var sem = _authenticatedHomeserverSemaphore.GetOrCreate(homeserver + accessToken, _ => new SemaphoreSlim(1, 1));
+        var cacheKey = homeserver + accessToken + proxy;
+        var sem = _authenticatedHomeserverSemaphore.GetOrCreate(cacheKey, _ => new SemaphoreSlim(1, 1));
         await sem.WaitAsync();
+        AuthenticatedHomeserverGeneric? hs;
         lock (_authenticatedHomeserverCache) {
-            if (_authenticatedHomeserverCache.ContainsKey(homeserver + accessToken)) {
+            if (_authenticatedHomeserverCache.TryGetValue(cacheKey, out hs)) {
                 sem.Release();
-                return _authenticatedHomeserverCache[homeserver + accessToken];
+                return hs;
             }
         }
 
         // var domain = proxy ?? (await _homeserverResolverService.ResolveHomeserverFromWellKnown(homeserver)).client;
 
-        var rhs = await RemoteHomeserver.Create(homeserver);
-        var serverVersion = await rhs.GetServerVersionAsync();
-        
+        var rhs = await RemoteHomeserver.Create(homeserver, proxy);
+        var clientVersions = await rhs.GetClientVersionsAsync();
+        if(proxy is not null)
+            Console.WriteLine($"Homeserver {homeserver} proxied via {proxy}...");
+        Console.WriteLine($"{homeserver}: " + clientVersions.ToJson());
 
-        AuthenticatedHomeserverGeneric hs;
-        if (true) {
-            hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverMxApiExtended>(homeserver, accessToken);
-        }
+        if (clientVersions.UnstableFeatures.TryGetValue("gay.rory.mxapiextensions.v0", out bool a) && a)
+            hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverMxApiExtended>(homeserver, accessToken, proxy);
         else {
-            hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverSynapse>(homeserver, accessToken);
+            var serverVersion = await rhs.GetServerVersionAsync();
+            if (serverVersion is { Server.Name: "Synapse" })
+                hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverSynapse>(homeserver, accessToken, proxy);
+            else
+                hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverGeneric>(homeserver, accessToken, proxy);
         }
 
-        // (() => hs.WhoAmI) = (await hs._httpClient.GetFromJsonAsync<WhoAmIResponse>("/_matrix/client/v3/account/whoami"))!;
-
         lock (_authenticatedHomeserverCache)
-            _authenticatedHomeserverCache[homeserver + accessToken] = hs;
+            _authenticatedHomeserverCache[cacheKey] = hs;
         sem.Release();
 
         return hs;
     }
 
     public async Task<RemoteHomeserver> GetRemoteHomeserver(string homeserver, string? proxy = null) {
-        var hs = await RemoteHomeserver.Create(proxy ?? homeserver);
+        var hs = await RemoteHomeserver.Create(homeserver, proxy);
         // hs._httpClient.Dispose();
         // hs._httpClient = new MatrixHttpClient { BaseAddress = new Uri(hs.ServerName) };
         // hs._httpClient.Timeout = TimeSpan.FromSeconds(120);
diff --git a/LibMatrix/Services/HomeserverResolverService.cs b/LibMatrix/Services/HomeserverResolverService.cs
index 06771b0..c8b6bb7 100644
--- a/LibMatrix/Services/HomeserverResolverService.cs
+++ b/LibMatrix/Services/HomeserverResolverService.cs
@@ -1,3 +1,4 @@
+using System.Collections.Concurrent;
 using System.Text.Json;
 using ArcaneLibs.Extensions;
 using LibMatrix.Extensions;
@@ -8,13 +9,11 @@ namespace LibMatrix.Services;
 public class HomeserverResolverService(ILogger<HomeserverResolverService>? logger = null) {
     private readonly MatrixHttpClient _httpClient = new();
 
-    private static readonly Dictionary<string, (string, string)> _wellKnownCache = new();
-    private static readonly Dictionary<string, SemaphoreSlim> _wellKnownSemaphores = new();
+    private static readonly ConcurrentDictionary<string, WellKnownUris> _wellKnownCache = new();
+    private static readonly ConcurrentDictionary<string, SemaphoreSlim> _wellKnownSemaphores = new();
 
-    public async Task<(string client, string server)> ResolveHomeserverFromWellKnown(string homeserver) {
+    public async Task<WellKnownUris> ResolveHomeserverFromWellKnown(string homeserver) {
         if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
-        // 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)) {
@@ -23,11 +22,11 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
         }
         
         logger?.LogInformation("Resolving homeserver: {}", homeserver);
-        var res = (
-            await _tryResolveFromClientWellknown(homeserver),
-            await _tryResolveFromServerWellknown(homeserver)
-        );
-        _wellKnownCache.Add(homeserver, res!);
+        var res = new WellKnownUris {
+            Client = await _tryResolveFromClientWellknown(homeserver),
+            Server = await _tryResolveFromServerWellknown(homeserver)
+        };
+        _wellKnownCache.TryAdd(homeserver, res);
         _wellKnownSemaphores[homeserver].Release();
         return res;
     }
@@ -54,6 +53,11 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
             return hs;
         }
 
+        // fallback: most servers host these on the same location
+        var clientUrl = await _tryResolveFromClientWellknown(homeserver);
+        if (clientUrl is not null && await _httpClient.CheckSuccessStatus($"{clientUrl}/_matrix/federation/v1/version"))
+            return clientUrl;
+
         logger?.LogInformation("No server well-known...");
         return null;
     }
@@ -62,7 +66,12 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
         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)).client;
+        homeserver = (await ResolveHomeserverFromWellKnown(homeserver)).Client;
         return mxc.Replace("mxc://", $"{homeserver}/_matrix/media/v3/download/");
     }
+
+    public class WellKnownUris {
+        public string? Client { get; set; }
+        public string? Server { get; set; }
+    }
 }
diff --git a/LibMatrix/Services/TieredStorageService.cs b/LibMatrix/Services/TieredStorageService.cs
index f242785..280340e 100644
--- a/LibMatrix/Services/TieredStorageService.cs
+++ b/LibMatrix/Services/TieredStorageService.cs
@@ -2,12 +2,7 @@ using LibMatrix.Interfaces.Services;
 
 namespace LibMatrix.Services;
 
-public class TieredStorageService {
-    public IStorageProvider? CacheStorageProvider { get; }
-    public IStorageProvider? DataStorageProvider { get; }
-
-    public TieredStorageService(IStorageProvider? cacheStorageProvider, IStorageProvider? dataStorageProvider) {
-        CacheStorageProvider = cacheStorageProvider;
-        DataStorageProvider = dataStorageProvider;
-    }
+public class TieredStorageService(IStorageProvider? cacheStorageProvider, IStorageProvider? dataStorageProvider) {
+    public IStorageProvider? CacheStorageProvider { get; } = cacheStorageProvider;
+    public IStorageProvider? DataStorageProvider { get; } = dataStorageProvider;
 }