From 1d6399d7f4649472333da946669ce9f1fa349b89 Mon Sep 17 00:00:00 2001 From: TheArcaneBrony Date: Sun, 5 Nov 2023 18:17:11 +0100 Subject: Cleanup, fixes, fix proxy support --- .../Homeservers/AuthenticatedHomeserverGeneric.cs | 46 +++++++++------------- .../Homeservers/AuthenticatedHomeserverSynapse.cs | 10 ++--- LibMatrix/Homeservers/RemoteHomeServer.cs | 36 +++++++++++------ 3 files changed, 47 insertions(+), 45 deletions(-) (limited to 'LibMatrix/Homeservers') diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs index c3684a1..37696eb 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs @@ -13,43 +13,41 @@ using LibMatrix.Services; namespace LibMatrix.Homeservers; -public class AuthenticatedHomeserverGeneric(string baseUrl, string accessToken) : RemoteHomeserver(baseUrl) { - public static async Task Create(string baseUrl, string accessToken) where T : AuthenticatedHomeserverGeneric { - var instance = Activator.CreateInstance(typeof(T), baseUrl, accessToken) as T +public class AuthenticatedHomeserverGeneric(string serverName, string accessToken) : RemoteHomeserver(serverName) { + public static async Task Create(string serverName, string accessToken, string? proxy = null) where T : AuthenticatedHomeserverGeneric { + var instance = Activator.CreateInstance(typeof(T), serverName, accessToken) as T ?? throw new InvalidOperationException($"Failed to create instance of {typeof(T).Name}"); - var urls = await new HomeserverResolverService().ResolveHomeserverFromWellKnown(baseUrl); - + HomeserverResolverService.WellKnownUris? urls = null; + if(proxy is null) + urls = await new HomeserverResolverService().ResolveHomeserverFromWellKnown(serverName); + instance.ClientHttpClient = new() { - BaseAddress = new Uri(urls.client - ?? throw new InvalidOperationException("Failed to resolve homeserver")), + BaseAddress = new Uri(proxy ?? urls?.Client + ?? throw new InvalidOperationException("Failed to resolve homeserver")), Timeout = TimeSpan.FromMinutes(15), DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", accessToken) } }; instance.ServerHttpClient = new() { - BaseAddress = new Uri(urls.server - ?? throw new InvalidOperationException("Failed to resolve homeserver")), + BaseAddress = new Uri(proxy ?? urls?.Server + ?? throw new InvalidOperationException("Failed to resolve homeserver")), Timeout = TimeSpan.FromMinutes(15), DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", accessToken) } }; + instance.WhoAmI = await instance.ClientHttpClient.GetFromJsonAsync("/_matrix/client/v3/account/whoami"); + + if (proxy is not null) { + instance.ClientHttpClient.DefaultRequestHeaders.Add("MXAE_UPSTREAM", serverName); + instance.ServerHttpClient.DefaultRequestHeaders.Add("MXAE_UPSTREAM", serverName); + } + return instance; } - // Activator.CreateInstance(baseUrl, accessToken) { - // _httpClient = new() { - // BaseAddress = new Uri(await new HomeserverResolverService().ResolveHomeserverFromWellKnown(baseUrl) - // ?? throw new InvalidOperationException("Failed to resolve homeserver")), - // Timeout = TimeSpan.FromMinutes(15), - // DefaultRequestHeaders = { - // Authorization = new AuthenticationHeaderValue("Bearer", accessToken) - // } - // } - // }; - public WhoAmIResponse? WhoAmI { get; set; } public string? UserId => WhoAmI?.UserId; public string? UserLocalpart => UserId?.Split(":")[0][1..]; @@ -176,12 +174,6 @@ public class AuthenticatedHomeserverGeneric(string baseUrl, string accessToken) #endregion - public string? ResolveMediaUri(string? mxcUri) { - if (mxcUri is null) return null; - if (mxcUri.StartsWith("https://")) return mxcUri; - return $"{ClientHttpClient.BaseAddress}/_matrix/media/v3/download/{mxcUri.Replace("mxc://", "")}".Replace("//_matrix", "/_matrix"); - } - public async Task UpdateProfileAsync(UserProfileResponse? newProfile, bool preserveCustomRoomProfile = true) { if (newProfile is null) return; Console.WriteLine($"Updating profile for {WhoAmI.UserId} to {newProfile.ToJson(ignoreNull: true)} (preserving room profiles: {preserveCustomRoomProfile})"); @@ -247,7 +239,7 @@ public class AuthenticatedHomeserverGeneric(string baseUrl, string accessToken) if (sync.Rooms is null) break; List tasks = new(); foreach (var (roomId, roomData) in sync.Rooms.Join) { - if (roomData.State is { Events: { Count: > 0 } }) { + if (roomData.State is { Events.Count: > 0 }) { var incommingRoomProfile = roomData.State?.Events?.FirstOrDefault(x => x.Type == "m.room.member" && x.StateKey == WhoAmI.UserId)?.TypedContent as RoomMemberEventContent; if (incommingRoomProfile is null) continue; diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs index 0910cbe..15e5b65 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs @@ -6,11 +6,7 @@ namespace LibMatrix.Homeservers; public class AuthenticatedHomeserverSynapse : AuthenticatedHomeserverGeneric { public readonly SynapseAdminApi Admin; - public class SynapseAdminApi { - private readonly AuthenticatedHomeserverGeneric _authenticatedHomeserver; - - public SynapseAdminApi(AuthenticatedHomeserverGeneric authenticatedHomeserver) => _authenticatedHomeserver = authenticatedHomeserver; - + public class SynapseAdminApi(AuthenticatedHomeserverSynapse authenticatedHomeserver) { public async IAsyncEnumerable SearchRoomsAsync(int limit = int.MaxValue, string orderBy = "name", string dir = "f", string? searchTerm = null, LocalRoomQueryFilter? localFilter = null) { AdminRoomListingResult? res = null; var i = 0; @@ -23,7 +19,7 @@ public class AuthenticatedHomeserverSynapse : AuthenticatedHomeserverGeneric { Console.WriteLine($"--- ADMIN Querying Room List with URL: {url} - Already have {i} items... ---"); - res = await _authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync(url); + res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync(url); totalRooms ??= res?.TotalRooms; Console.WriteLine(res.ToJson(false)); foreach (var room in res.Rooms) { @@ -101,7 +97,7 @@ public class AuthenticatedHomeserverSynapse : AuthenticatedHomeserverGeneric { } } - public AuthenticatedHomeserverSynapse(string baseUrl, string accessToken) : base(baseUrl, accessToken) { + public AuthenticatedHomeserverSynapse(string serverName, string accessToken) : base(serverName, accessToken) { Admin = new(this); } } diff --git a/LibMatrix/Homeservers/RemoteHomeServer.cs b/LibMatrix/Homeservers/RemoteHomeServer.cs index 0757f6e..55a3a02 100644 --- a/LibMatrix/Homeservers/RemoteHomeServer.cs +++ b/LibMatrix/Homeservers/RemoteHomeServer.cs @@ -10,24 +10,31 @@ using LibMatrix.Services; namespace LibMatrix.Homeservers; public class RemoteHomeserver(string baseUrl) { - public static async Task Create(string baseUrl) { - var urls = await new HomeserverResolverService().ResolveHomeserverFromWellKnown(baseUrl); - return new RemoteHomeserver(baseUrl) { - ClientHttpClient = new() { - BaseAddress = new Uri(urls.client ?? throw new InvalidOperationException("Failed to resolve homeserver")), - Timeout = TimeSpan.FromSeconds(120) - }, - ServerHttpClient = new() { - BaseAddress = new Uri(urls.server ?? throw new InvalidOperationException("Failed to resolve homeserver")), - Timeout = TimeSpan.FromSeconds(120) - } + public static async Task Create(string baseUrl, string? proxy = null) { + var homeserver = new RemoteHomeserver(baseUrl); + homeserver.WellKnownUris = await new HomeserverResolverService().ResolveHomeserverFromWellKnown(baseUrl); + homeserver.ClientHttpClient = new() { + BaseAddress = new Uri(proxy ?? homeserver.WellKnownUris.Client ?? throw new InvalidOperationException("Failed to resolve homeserver")), + Timeout = TimeSpan.FromSeconds(120) + }; + homeserver.ServerHttpClient = new() { + BaseAddress = new Uri(proxy ?? homeserver.WellKnownUris.Server ?? throw new InvalidOperationException("Failed to resolve homeserver")), + Timeout = TimeSpan.FromSeconds(120) }; + + if (proxy is not null) { + homeserver.ClientHttpClient.DefaultRequestHeaders.Add("MXAE_UPSTREAM", baseUrl); + homeserver.ServerHttpClient.DefaultRequestHeaders.Add("MXAE_UPSTREAM", baseUrl); + } + + return homeserver; } private Dictionary _profileCache { get; set; } = new(); public string BaseUrl { get; } = baseUrl; public MatrixHttpClient ClientHttpClient { get; set; } public MatrixHttpClient ServerHttpClient { get; set; } + public HomeserverResolverService.WellKnownUris WellKnownUris { get; set; } public async Task GetProfileAsync(string mxid) { if (mxid is null) throw new ArgumentNullException(nameof(mxid)); @@ -100,6 +107,13 @@ public class RemoteHomeserver(string baseUrl) { public async Task GetServerVersionAsync() { return await ServerHttpClient.GetFromJsonAsync("/_matrix/federation/v1/version"); } + + + public string? ResolveMediaUri(string? mxcUri) { + if (mxcUri is null) return null; + if (mxcUri.StartsWith("https://")) return mxcUri; + return $"{ClientHttpClient.BaseAddress}/_matrix/media/v3/download/{mxcUri.Replace("mxc://", "")}".Replace("//_matrix", "/_matrix"); + } } public class ServerVersionResponse { -- cgit 1.4.1