diff --git a/MatrixRoomUtils.Core/AuthenticatedHomeServer.cs b/MatrixRoomUtils.Core/AuthenticatedHomeServer.cs
index dd9aa25..031b6b6 100644
--- a/MatrixRoomUtils.Core/AuthenticatedHomeServer.cs
+++ b/MatrixRoomUtils.Core/AuthenticatedHomeServer.cs
@@ -1,8 +1,10 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
+using MatrixRoomUtils.Core.Extensions;
+using MatrixRoomUtils.Core.Interfaces;
-namespace MatrixRoomUtils;
+namespace MatrixRoomUtils.Core;
public class AuthenticatedHomeServer : IHomeServer
{
@@ -15,18 +17,20 @@ public class AuthenticatedHomeServer : IHomeServer
AccessToken = accessToken;
HomeServerDomain = canonicalHomeServerDomain;
_httpClient = new HttpClient();
-
- var rhsfwt = ResolveHomeserverFromWellKnown(canonicalHomeServerDomain);
- rhsfwt.ContinueWith(_ =>
- {
- FullHomeServerDomain = rhsfwt.Result;
- _httpClient.Dispose();
- _httpClient = new HttpClient {BaseAddress = new Uri(FullHomeServerDomain)};
- _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
- Console.WriteLine("[AHS] Finished setting up http client :)");
- });
}
+ public async Task<AuthenticatedHomeServer> Configure()
+ {
+ FullHomeServerDomain = await ResolveHomeserverFromWellKnown(HomeServerDomain);
+ _httpClient.Dispose();
+ _httpClient = new HttpClient { BaseAddress = new Uri(FullHomeServerDomain) };
+ _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
+ Console.WriteLine("[AHS] Finished setting up http client");
+
+ return this;
+ }
+
+
public async Task<Room> GetRoom(string roomId)
{
return new Room(_httpClient, roomId);
@@ -35,19 +39,27 @@ public class AuthenticatedHomeServer : IHomeServer
public async Task<List<Room>> GetJoinedRooms()
{
var rooms = new List<Room>();
- var _rooms = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms");
- if (!_rooms.IsSuccessStatusCode)
+ var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms");
+ if (!roomQuery.IsSuccessStatusCode)
{
- Console.WriteLine($"Failed to get rooms: {await _rooms.Content.ReadAsStringAsync()}");
- throw new InvalidDataException($"Failed to get rooms: {await _rooms.Content.ReadAsStringAsync()}");
+ Console.WriteLine($"Failed to get rooms: {await roomQuery.Content.ReadAsStringAsync()}");
+ throw new InvalidDataException($"Failed to get rooms: {await roomQuery.Content.ReadAsStringAsync()}");
}
+
- var roomsJson = await _rooms.Content.ReadFromJsonAsync<JsonElement>();
+ var roomsJson = await roomQuery.Content.ReadFromJsonAsync<JsonElement>();
foreach (var room in roomsJson.GetProperty("joined_rooms").EnumerateArray())
{
rooms.Add(new Room(_httpClient, room.GetString()));
}
+
+ Console.WriteLine($"Fetched {rooms.Count} rooms");
return rooms;
}
+
+ public async Task<string> ResolveMediaUri(string mxc)
+ {
+ return mxc.Replace("mxc://", $"{FullHomeServerDomain}/_matrix/media/r0/download/");
+ }
}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Core/Authentication/MatrixAuth.cs b/MatrixRoomUtils.Core/Authentication/MatrixAuth.cs
index 687ea07..e744c4f 100644
--- a/MatrixRoomUtils.Core/Authentication/MatrixAuth.cs
+++ b/MatrixRoomUtils.Core/Authentication/MatrixAuth.cs
@@ -1,15 +1,15 @@
using System.Net.Http.Json;
using System.Text.Json;
-using MatrixRoomUtils.Responses;
+using MatrixRoomUtils.Core.Responses;
-namespace MatrixRoomUtils.Authentication;
+namespace MatrixRoomUtils.Core.Authentication;
public class MatrixAuth
{
public static async Task<LoginResponse> Login(string homeserver, string username, string password)
{
Console.WriteLine($"Logging in to {homeserver} as {username}...");
- homeserver = await ResolveHomeserverFromWellKnown(homeserver);
+ homeserver = (await new RemoteHomeServer(homeserver).Configure()).FullHomeServerDomain;
var hc = new HttpClient();
var payload = new
{
@@ -39,42 +39,8 @@ public class MatrixAuth
//return token;
}
- public static async Task<ProfileResponse> GetProfile(string homeserver, string mxid)
- {
- Console.WriteLine($"Fetching profile for {mxid} on {homeserver}...");
- homeserver = await ResolveHomeserverFromWellKnown(homeserver);
- using var hc = new HttpClient();
- var resp = await hc.GetAsync($"{homeserver}/_matrix/client/r0/profile/{mxid}");
- var data = await resp.Content.ReadFromJsonAsync<JsonElement>();
- if (!resp.IsSuccessStatusCode) Console.WriteLine("Profile: " + data.ToString());
- return data.Deserialize<ProfileResponse>();
- }
-
- [Obsolete("Use IHomeServer")]
- public static async Task<string> ResolveHomeserverFromWellKnown(string homeserver)
- {
- using var hc = new HttpClient();
- Console.WriteLine($"Resolving homeserver: {homeserver}");
- if (!homeserver.StartsWith("http")) homeserver = "https://" + homeserver;
-
- if (await CheckSuccessStatus($"{homeserver}/.well-known/matrix/client"))
- {
- var resp = await hc.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/client");
- var hs = resp.GetProperty("m.homeserver").GetProperty("base_url").GetString();
- return hs;
- }
- Console.WriteLine($"No client well-known...");
- if (await CheckSuccessStatus($"{homeserver}/.well-known/matrix/server"))
- {
- var resp = await hc.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/server");
- var hs = resp.GetProperty("m.server").GetString();
- return hs;
- }
- Console.WriteLine($"No server well-known...");
- if (await CheckSuccessStatus($"{homeserver}/_matrix/client/versions")) return homeserver;
- Console.WriteLine($"Failed to resolve homeserver, not on {homeserver}, nor do client or server well-knowns exist!");
- throw new InvalidDataException($"Failed to resolve homeserver, not on {homeserver}, nor do client or server well-knowns exist!");
- }
+ public static async Task<ProfileResponse> GetProfile(string homeserver, string mxid) =>
+ await (await new RemoteHomeServer(homeserver).Configure()).GetProfile(mxid);
private static async Task<bool> CheckSuccessStatus(string url)
{
diff --git a/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs b/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs
index 66a5133..8eb0226 100644
--- a/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs
+++ b/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs
@@ -1,4 +1,4 @@
-namespace MatrixRoomUtils.Extensions;
+namespace MatrixRoomUtils.Core.Extensions;
public static class HttpClientExtensions
{
diff --git a/MatrixRoomUtils.Core/Extensions/ObjectExtensions.cs b/MatrixRoomUtils.Core/Extensions/ObjectExtensions.cs
index cf798ce..aa1832d 100644
--- a/MatrixRoomUtils.Core/Extensions/ObjectExtensions.cs
+++ b/MatrixRoomUtils.Core/Extensions/ObjectExtensions.cs
@@ -1,6 +1,6 @@
using System.Text.Json;
-namespace MatrixRoomUtils.Extensions;
+namespace MatrixRoomUtils.Core.Extensions;
public static class ObjectExtensions
{
diff --git a/MatrixRoomUtils.Core/Extensions/StringExtensions.cs b/MatrixRoomUtils.Core/Extensions/StringExtensions.cs
index 27d8265..7bed7a3 100644
--- a/MatrixRoomUtils.Core/Extensions/StringExtensions.cs
+++ b/MatrixRoomUtils.Core/Extensions/StringExtensions.cs
@@ -1,17 +1,17 @@
-using MatrixRoomUtils.Authentication;
+using MatrixRoomUtils.Core.Authentication;
-namespace MatrixRoomUtils.Extensions;
+namespace MatrixRoomUtils.Core.Extensions;
public static class StringExtensions
{
- public static async Task<string> GetMediaUrl(this string MxcUrl)
- {
- //MxcUrl: mxc://rory.gay/ocRVanZoUTCcifcVNwXgbtTg
- //target: https://matrix.rory.gay/_matrix/media/v3/download/rory.gay/ocRVanZoUTCcifcVNwXgbtTg
-
- var server = MxcUrl.Split('/')[2];
- var mediaId = MxcUrl.Split('/')[3];
- return $"{await MatrixAuth.ResolveHomeserverFromWellKnown(server)}/_matrix/media/v3/download/{server}/{mediaId}";
- }
+ // public static async Task<string> GetMediaUrl(this string MxcUrl)
+ // {
+ // //MxcUrl: mxc://rory.gay/ocRVanZoUTCcifcVNwXgbtTg
+ // //target: https://matrix.rory.gay/_matrix/media/v3/download/rory.gay/ocRVanZoUTCcifcVNwXgbtTg
+ //
+ // var server = MxcUrl.Split('/')[2];
+ // var mediaId = MxcUrl.Split('/')[3];
+ // return $"{(await new RemoteHomeServer(server).Configure()).FullHomeServerDomain}/_matrix/media/v3/download/{server}/{mediaId}";
+ // }
}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Core/Interfaces/IHomeServer.cs b/MatrixRoomUtils.Core/Interfaces/IHomeServer.cs
index 84714f7..438709f 100644
--- a/MatrixRoomUtils.Core/Interfaces/IHomeServer.cs
+++ b/MatrixRoomUtils.Core/Interfaces/IHomeServer.cs
@@ -1,8 +1,8 @@
using System.Net.Http.Json;
using System.Text.Json;
-using MatrixRoomUtils.Extensions;
+using MatrixRoomUtils.Core.Extensions;
-namespace MatrixRoomUtils;
+namespace MatrixRoomUtils.Core.Interfaces;
public class IHomeServer
{
@@ -10,8 +10,21 @@ public class IHomeServer
public string FullHomeServerDomain { get; set; }
private protected HttpClient _httpClient { get; set; } = new();
+
public async Task<string> ResolveHomeserverFromWellKnown(string homeserver)
{
+ if (RuntimeCache.HomeserverResolutionCache.ContainsKey(homeserver))
+ {
+ if (RuntimeCache.HomeserverResolutionCache[homeserver].ResolutionTime < DateTime.Now.AddHours(1))
+ {
+ Console.WriteLine($"Found cached homeserver: {RuntimeCache.HomeserverResolutionCache[homeserver].Result}");
+ return RuntimeCache.HomeserverResolutionCache[homeserver].Result;
+ }
+ RuntimeCache.HomeserverResolutionCache.Remove(homeserver);
+ }
+ //throw new NotImplementedException();
+
+ string result = null;
Console.WriteLine($"Resolving homeserver: {homeserver}");
if (!homeserver.StartsWith("http")) homeserver = "https://" + homeserver;
if (await _httpClient.CheckSuccessStatus($"{homeserver}/.well-known/matrix/client"))
@@ -20,18 +33,40 @@ public class IHomeServer
var resp = await _httpClient.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/client");
Console.WriteLine($"Response: {resp.ToString()}");
var hs = resp.GetProperty("m.homeserver").GetProperty("base_url").GetString();
- return hs;
+ result = hs;
}
- Console.WriteLine($"No client well-known...");
- if (await _httpClient.CheckSuccessStatus($"{homeserver}/.well-known/matrix/server"))
+ else
+ {
+ Console.WriteLine($"No client well-known...");
+ 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();
+ result = hs;
+ }
+ else
+ {
+ Console.WriteLine($"No server well-known...");
+ if (await _httpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions")) result = homeserver;
+ else
+ {
+ Console.WriteLine("No homeserver on shortname...");
+ if (await _httpClient.CheckSuccessStatus($"{homeserver.Replace("//", "//matrix.")}/_matrix/client/versions")) result = homeserver.Replace("//", "//matrix.");
+ else Console.WriteLine($"Failed to resolve homeserver, not on {homeserver}, nor do client or server well-knowns exist!");
+ }
+ }
+ }
+
+ if (result != null)
{
- var resp = await _httpClient.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/server");
- var hs = resp.GetProperty("m.server").GetString();
- return hs;
+ Console.WriteLine($"Resolved homeserver: {homeserver} -> {result}");
+ RuntimeCache.HomeserverResolutionCache.TryAdd(homeserver, new()
+ {
+ Result = result,
+ ResolutionTime = DateTime.Now
+ });
+ return result;
}
- Console.WriteLine($"No server well-known...");
- if (await _httpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions")) return homeserver;
- Console.WriteLine($"Failed to resolve homeserver, not on {homeserver}, nor do client or server well-knowns exist!");
throw new InvalidDataException($"Failed to resolve homeserver, not on {homeserver}, nor do client or server well-knowns exist!");
}
}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Core/RatelimitedHttpClient.cs b/MatrixRoomUtils.Core/RatelimitedHttpClient.cs
index f4ad9c9..61eab07 100644
--- a/MatrixRoomUtils.Core/RatelimitedHttpClient.cs
+++ b/MatrixRoomUtils.Core/RatelimitedHttpClient.cs
@@ -1,4 +1,4 @@
-namespace MatrixRoomUtils;
+namespace MatrixRoomUtils.Core;
public class RatelimitedHttpClient : HttpClient
{
diff --git a/MatrixRoomUtils.Core/RemoteHomeServer.cs b/MatrixRoomUtils.Core/RemoteHomeServer.cs
new file mode 100644
index 0000000..6bd2251
--- /dev/null
+++ b/MatrixRoomUtils.Core/RemoteHomeServer.cs
@@ -0,0 +1,57 @@
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using MatrixRoomUtils.Core.Extensions;
+using MatrixRoomUtils.Core.Interfaces;
+using MatrixRoomUtils.Core.Responses;
+
+namespace MatrixRoomUtils.Core;
+
+public class RemoteHomeServer : IHomeServer
+{
+ public RemoteHomeServer(string canonicalHomeServerDomain)
+ {
+ HomeServerDomain = canonicalHomeServerDomain;
+ _httpClient = new HttpClient();
+ }
+ public async Task<RemoteHomeServer> Configure()
+ {
+ FullHomeServerDomain = await ResolveHomeserverFromWellKnown(HomeServerDomain);
+ _httpClient.Dispose();
+ _httpClient = new HttpClient { BaseAddress = new Uri(FullHomeServerDomain) };
+ Console.WriteLine("[RHS] Finished setting up http client");
+
+ return this;
+ }
+ public async Task<ProfileResponse> GetProfile(string mxid)
+ {
+ var resp = await _httpClient.GetAsync($"/_matrix/client/r0/profile/{mxid}");
+ var data = await resp.Content.ReadFromJsonAsync<JsonElement>();
+ if(!resp.IsSuccessStatusCode) Console.WriteLine("Profile: " + data.ToString());
+ return data.Deserialize<ProfileResponse>();
+ }
+
+ public async Task<Room> GetRoom(string roomId)
+ {
+ return new Room(_httpClient, roomId);
+ }
+
+ public async Task<List<Room>> GetJoinedRooms()
+ {
+ var rooms = new List<Room>();
+ var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms");
+ if (!roomQuery.IsSuccessStatusCode)
+ {
+ Console.WriteLine($"Failed to get rooms: {await roomQuery.Content.ReadAsStringAsync()}");
+ throw new InvalidDataException($"Failed to get rooms: {await roomQuery.Content.ReadAsStringAsync()}");
+ }
+
+ var roomsJson = await roomQuery.Content.ReadFromJsonAsync<JsonElement>();
+ foreach (var room in roomsJson.GetProperty("joined_rooms").EnumerateArray())
+ {
+ rooms.Add(new Room(_httpClient, room.GetString()));
+ }
+
+ return rooms;
+ }
+}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Core/Responses/LoginResponse.cs b/MatrixRoomUtils.Core/Responses/LoginResponse.cs
index 5a7514e..4012d32 100644
--- a/MatrixRoomUtils.Core/Responses/LoginResponse.cs
+++ b/MatrixRoomUtils.Core/Responses/LoginResponse.cs
@@ -1,9 +1,9 @@
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
-using MatrixRoomUtils.Authentication;
+using MatrixRoomUtils.Core.Authentication;
-namespace MatrixRoomUtils.Responses;
+namespace MatrixRoomUtils.Core.Responses;
public class LoginResponse
{
@@ -26,6 +26,6 @@ public class LoginResponse
}
public async Task<string> GetCanonicalHomeserverUrl()
{
- return await MatrixAuth.ResolveHomeserverFromWellKnown(HomeServer);
+ return (await new RemoteHomeServer(HomeServer).Configure()).FullHomeServerDomain;
}
}
\ No newline at end of file
diff --git a/MatrixRoomUtils.Core/Responses/ProfileResponse.cs b/MatrixRoomUtils.Core/Responses/ProfileResponse.cs
index ab6cc92..f8026cb 100644
--- a/MatrixRoomUtils.Core/Responses/ProfileResponse.cs
+++ b/MatrixRoomUtils.Core/Responses/ProfileResponse.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace MatrixRoomUtils.Authentication;
+namespace MatrixRoomUtils.Core.Responses;
public class ProfileResponse
{
diff --git a/MatrixRoomUtils.Core/Room.cs b/MatrixRoomUtils.Core/Room.cs
index 2a5abb4..44364c6 100644
--- a/MatrixRoomUtils.Core/Room.cs
+++ b/MatrixRoomUtils.Core/Room.cs
@@ -1,7 +1,7 @@
using System.Net.Http.Json;
using System.Text.Json;
-namespace MatrixRoomUtils;
+namespace MatrixRoomUtils.Core;
public class Room
{
diff --git a/MatrixRoomUtils.Core/RuntimeCache.cs b/MatrixRoomUtils.Core/RuntimeCache.cs
index 3e9eebc..586cf88 100644
--- a/MatrixRoomUtils.Core/RuntimeCache.cs
+++ b/MatrixRoomUtils.Core/RuntimeCache.cs
@@ -1,18 +1,16 @@
-using MatrixRoomUtils.Authentication;
-using MatrixRoomUtils.Responses;
+using MatrixRoomUtils.Core.Responses;
-namespace MatrixRoomUtils;
+namespace MatrixRoomUtils.Core;
public class RuntimeCache
{
public static bool WasLoaded = false;
- public static string AccessToken { get; set; }
- public static string? CurrentHomeserver { get; set; }
+ public static string? LastUsedToken { get; set; }
public static AuthenticatedHomeServer CurrentHomeServer { get; set; }
public static Dictionary<string, UserInfo> LoginSessions { get; set; } = new();
public static Dictionary<string, HomeServerResolutionResult> HomeserverResolutionCache { get; set; } = new();
- public static Dictionary<string, (DateTime cachedAt, ProfileResponse response)> ProfileCache { get; set; } = new();
+ // public static Dictionary<string, (DateTime cachedAt, ProfileResponse response)> ProfileCache { get; set; } = new();
}
@@ -20,7 +18,7 @@ public class UserInfo
{
public ProfileResponse Profile { get; set; } = new();
public LoginResponse LoginResponse { get; set; }
- public string AccessToken { get; set; }
+ public string AccessToken { get => LoginResponse.AccessToken; }
}
public class HomeServerResolutionResult
diff --git a/MatrixRoomUtils.Core/StateEvent.cs b/MatrixRoomUtils.Core/StateEvent.cs
index 34cefe4..df7267d 100644
--- a/MatrixRoomUtils.Core/StateEvent.cs
+++ b/MatrixRoomUtils.Core/StateEvent.cs
@@ -1,4 +1,4 @@
-namespace MatrixRoomUtils;
+namespace MatrixRoomUtils.Core;
public class StateEvent
{
diff --git a/MatrixRoomUtils.Core/StateEventStruct.cs b/MatrixRoomUtils.Core/StateEventStruct.cs
index e5424cf..bfda594 100644
--- a/MatrixRoomUtils.Core/StateEventStruct.cs
+++ b/MatrixRoomUtils.Core/StateEventStruct.cs
@@ -1,4 +1,4 @@
-namespace MatrixRoomUtils;
+namespace MatrixRoomUtils.Core;
public struct StateEventStruct
{
diff --git a/MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs b/MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs
index 45063cc..108bb4d 100644
--- a/MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs
+++ b/MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace MatrixRoomUtils.StateEventTypes;
+namespace MatrixRoomUtils.Core.StateEventTypes;
public class PolicyRuleStateEventData
{
|