about summary refs log tree commit diff
path: root/LibMatrix/Homeservers
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-09-15 09:50:45 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-09-15 09:50:45 +0200
commit6bd02248ccfbcb46960a6f39eaad23888d190eb5 (patch)
tree110578f31b6f9f70a7a1edab32fb3a34d6ad4f1a /LibMatrix/Homeservers
parentMedia moderator PoC works, abstract command handling to library (diff)
downloadLibMatrix-6bd02248ccfbcb46960a6f39eaad23888d190eb5.tar.xz
Some refactoring
Diffstat (limited to 'LibMatrix/Homeservers')
-rw-r--r--LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs52
-rw-r--r--LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs10
-rw-r--r--LibMatrix/Homeservers/RemoteHomeServer.cs18
3 files changed, 46 insertions, 34 deletions
diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs
index 0b3201c..a280c54 100644
--- a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs
+++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs
@@ -2,6 +2,7 @@ using System.Net.Http.Json;
 using System.Text.Json;
 using System.Text.Json.Nodes;
 using System.Text.Json.Serialization;
+using ArcaneLibs.Extensions;
 using LibMatrix.Extensions;
 using LibMatrix.Helpers;
 using LibMatrix.Responses;
@@ -14,21 +15,18 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer {
     public AuthenticatedHomeserverGeneric(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : base(canonicalHomeServerDomain) {
         Storage = storage;
         AccessToken = accessToken.Trim();
-        HomeServerDomain = canonicalHomeServerDomain.Trim();
         SyncHelper = new SyncHelper(this, storage);
-        _httpClient = new MatrixHttpClient();
     }
 
-    public TieredStorageService Storage { get; set; }
-    public SyncHelper SyncHelper { get; init; }
-    public WhoAmIResponse WhoAmI { get; set; } = null!;
-    public string UserId => WhoAmI.UserId;
-    public string AccessToken { get; set; }
+    public virtual TieredStorageService Storage { get; set; }
+    public virtual SyncHelper SyncHelper { get; init; }
+    public virtual WhoAmIResponse WhoAmI { get; set; } = null!;
+    public virtual string UserId => WhoAmI.UserId;
+    public virtual string AccessToken { get; set; }
 
+    public virtual Task<GenericRoom> GetRoom(string roomId) => Task.FromResult<GenericRoom>(new(this, roomId));
 
-    public Task<GenericRoom> GetRoom(string roomId) => Task.FromResult<GenericRoom>(new(this, roomId));
-
-    public async Task<List<GenericRoom>> GetJoinedRooms() {
+    public virtual async Task<List<GenericRoom>> GetJoinedRooms() {
         var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms");
 
         var roomsJson = await roomQuery.Content.ReadFromJsonAsync<JsonElement>();
@@ -39,7 +37,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer {
         return rooms;
     }
 
-    public async Task<string> UploadFile(string fileName, Stream fileStream, string contentType = "application/octet-stream") {
+    public virtual async Task<string> UploadFile(string fileName, Stream fileStream, string contentType = "application/octet-stream") {
         var res = await _httpClient.PostAsync($"/_matrix/media/v3/upload?filename={fileName}", new StreamContent(fileStream));
         if (!res.IsSuccessStatusCode) {
             Console.WriteLine($"Failed to upload file: {await res.Content.ReadAsStringAsync()}");
@@ -50,7 +48,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer {
         return resJson.GetProperty("content_uri").GetString()!;
     }
 
-    public async Task<GenericRoom> CreateRoom(CreateRoomRequest creationEvent) {
+    public virtual async Task<GenericRoom> CreateRoom(CreateRoomRequest creationEvent) {
         creationEvent.CreationContent["creator"] = UserId;
         var res = await _httpClient.PostAsJsonAsync("/_matrix/client/v3/createRoom", creationEvent, new JsonSerializerOptions {
             DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
@@ -60,12 +58,36 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer {
             throw new InvalidDataException($"Failed to create room: {await res.Content.ReadAsStringAsync()}");
         }
 
-        return await GetRoom((await res.Content.ReadFromJsonAsync<JsonObject>())!["room_id"]!.ToString());
+        var room = await GetRoom((await res.Content.ReadFromJsonAsync<JsonObject>())!["room_id"]!.ToString());
+
+        foreach (var user in creationEvent.Invite) {
+            await room.InviteUser(user);
+        }
+
+        return room;
+    }
+
+#region Utility Functions
+    public virtual async IAsyncEnumerable<GenericRoom> GetJoinedRoomsByType(string type) {
+        var rooms = await GetJoinedRooms();
+        var tasks = rooms.Select(async room => {
+            var roomType = await room.GetRoomType();
+            if (roomType == type) {
+                return room;
+            }
+
+            return null;
+        }).ToAsyncEnumerable();
+
+        await foreach (var result in tasks) {
+            if (result is not null) yield return result;
+        }
     }
+#endregion
 
 #region Account Data
 
-    public async Task<T> GetAccountData<T>(string key) {
+    public virtual async Task<T> GetAccountData<T>(string key) {
         // var res = await _httpClient.GetAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}");
         // if (!res.IsSuccessStatusCode) {
         //     Console.WriteLine($"Failed to get account data: {await res.Content.ReadAsStringAsync()}");
@@ -76,7 +98,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer {
         return await _httpClient.GetFromJsonAsync<T>($"/_matrix/client/v3/user/{UserId}/account_data/{key}");
     }
 
-    public async Task SetAccountData(string key, object data) {
+    public virtual async Task SetAccountData(string key, object data) {
         var res = await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}", data);
         if (!res.IsSuccessStatusCode) {
             Console.WriteLine($"Failed to set account data: {await res.Content.ReadAsStringAsync()}");
diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs
index 8ffcfaf..e44d727 100644
--- a/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs
+++ b/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs
@@ -4,11 +4,5 @@ using LibMatrix.Services;
 
 namespace LibMatrix.Homeservers;
 
-public class AuthenticatedHomeserverMxApiExtended : AuthenticatedHomeserverGeneric {
-    public AuthenticatedHomeserverMxApiExtended(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : base(storage, canonicalHomeServerDomain, accessToken) {
-        AccessToken = accessToken.Trim();
-        HomeServerDomain = canonicalHomeServerDomain.Trim();
-        SyncHelper = new SyncHelper(this, storage);
-        _httpClient = new MatrixHttpClient();
-    }
-}
+public class AuthenticatedHomeserverMxApiExtended(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : AuthenticatedHomeserverGeneric(storage, canonicalHomeServerDomain,
+    accessToken);
diff --git a/LibMatrix/Homeservers/RemoteHomeServer.cs b/LibMatrix/Homeservers/RemoteHomeServer.cs
index 923986d..caed397 100644
--- a/LibMatrix/Homeservers/RemoteHomeServer.cs
+++ b/LibMatrix/Homeservers/RemoteHomeServer.cs
@@ -5,28 +5,24 @@ using LibMatrix.StateEventTypes.Spec;
 
 namespace LibMatrix.Homeservers;
 
-public class RemoteHomeServer {
-    public RemoteHomeServer(string canonicalHomeServerDomain) {
-        HomeServerDomain = canonicalHomeServerDomain;
-        _httpClient = new MatrixHttpClient();
-        _httpClient.Timeout = TimeSpan.FromSeconds(5);
-    }
+public class RemoteHomeServer(string canonicalHomeServerDomain) {
+    // _httpClient.Timeout = TimeSpan.FromSeconds(5);
 
     private Dictionary<string, object> _profileCache { get; set; } = new();
-    public string HomeServerDomain { get; set; }
+    public string HomeServerDomain { get; } = canonicalHomeServerDomain.Trim();
     public string FullHomeServerDomain { get; set; }
-    public MatrixHttpClient _httpClient { get; set; }
+    public MatrixHttpClient _httpClient { get; set; } = new();
 
-    public async Task<ProfileResponseEventData> GetProfile(string mxid) {
+    public async Task<ProfileResponseEventContent> GetProfile(string mxid) {
         if(mxid is null) throw new ArgumentNullException(nameof(mxid));
         if (_profileCache.TryGetValue(mxid, out var value)) {
             if (value is SemaphoreSlim s) await s.WaitAsync();
-            if (value is ProfileResponseEventData p) return p;
+            if (value is ProfileResponseEventContent p) return p;
         }
         _profileCache[mxid] = new SemaphoreSlim(1);
 
         var resp = await _httpClient.GetAsync($"/_matrix/client/v3/profile/{mxid}");
-        var data = await resp.Content.ReadFromJsonAsync<ProfileResponseEventData>();
+        var data = await resp.Content.ReadFromJsonAsync<ProfileResponseEventContent>();
         if (!resp.IsSuccessStatusCode) Console.WriteLine("Profile: " + data);
         _profileCache[mxid] = data;