about summary refs log tree commit diff
path: root/LibMatrix/Homeservers
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-09-04 02:17:10 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-09-04 02:17:10 +0200
commit21da6cde79ccd0cb7f895a29e3d8cab959ef11ba (patch)
treefb0b89566b64ae907d7ca3ea8a29adcf0c0361d0 /LibMatrix/Homeservers
parentClean up some extension functions (diff)
downloadLibMatrix-21da6cde79ccd0cb7f895a29e3d8cab959ef11ba.tar.xz
Too many changes to name...
Diffstat (limited to '')
-rw-r--r--LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs89
-rw-r--r--LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs14
-rw-r--r--LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs (renamed from LibMatrix/AuthenticatedHomeServer.cs)89
-rw-r--r--LibMatrix/Homeservers/RemoteHomeServer.cs46
4 files changed, 162 insertions, 76 deletions
diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs
new file mode 100644
index 0000000..ecac4e4
--- /dev/null
+++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs
@@ -0,0 +1,89 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Threading.Tasks;
+using LibMatrix.Extensions;
+using LibMatrix.Helpers;
+using LibMatrix.Responses;
+using LibMatrix.RoomTypes;
+using LibMatrix.Services;
+
+namespace LibMatrix.Homeservers;
+
+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 Task<GenericRoom> GetRoom(string roomId) => Task.FromResult<GenericRoom>(new(this, roomId));
+
+    public async Task<List<GenericRoom>> GetJoinedRooms() {
+        var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms");
+
+        var roomsJson = await roomQuery.Content.ReadFromJsonAsync<JsonElement>();
+        var rooms = roomsJson.GetProperty("joined_rooms").EnumerateArray().Select(room => new GenericRoom(this, room.GetString()!)).ToList();
+
+        Console.WriteLine($"Fetched {rooms.Count} rooms");
+
+        return rooms;
+    }
+
+    public 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()}");
+            throw new InvalidDataException($"Failed to upload file: {await res.Content.ReadAsStringAsync()}");
+        }
+
+        var resJson = await res.Content.ReadFromJsonAsync<JsonElement>();
+        return resJson.GetProperty("content_uri").GetString()!;
+    }
+
+    public async Task<GenericRoom> CreateRoom(CreateRoomRequest creationEvent) {
+        var res = await _httpClient.PostAsJsonAsync("/_matrix/client/v3/createRoom", creationEvent);
+        if (!res.IsSuccessStatusCode) {
+            Console.WriteLine($"Failed to create room: {await res.Content.ReadAsStringAsync()}");
+            throw new InvalidDataException($"Failed to create room: {await res.Content.ReadAsStringAsync()}");
+        }
+
+        return await GetRoom((await res.Content.ReadFromJsonAsync<JsonObject>())!["room_id"]!.ToString());
+    }
+
+#region Account Data
+
+    public 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()}");
+            throw new InvalidDataException($"Failed to get account data: {await res.Content.ReadAsStringAsync()}");
+        }
+
+        return await res.Content.ReadFromJsonAsync<T>();
+    }
+
+    public 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()}");
+            throw new InvalidDataException($"Failed to set account data: {await res.Content.ReadAsStringAsync()}");
+        }
+    }
+
+#endregion
+}
diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs
new file mode 100644
index 0000000..8ffcfaf
--- /dev/null
+++ b/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs
@@ -0,0 +1,14 @@
+using LibMatrix.Extensions;
+using LibMatrix.Helpers;
+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();
+    }
+}
diff --git a/LibMatrix/AuthenticatedHomeServer.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs
index a99dc27..3b0bc10 100644
--- a/LibMatrix/AuthenticatedHomeServer.cs
+++ b/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs
@@ -1,75 +1,18 @@
-using System.Net.Http.Json;
-using System.Text.Json;
-using System.Text.Json.Nodes;
-using System.Text.Json.Serialization;
-using LibMatrix.Extensions;
+using System;
+using System.Collections.Generic;
+using ArcaneLibs.Extensions;
 using LibMatrix.Filters;
-using LibMatrix.Helpers;
-using LibMatrix.Interfaces;
-using LibMatrix.Responses;
 using LibMatrix.Responses.Admin;
-using LibMatrix.RoomTypes;
 using LibMatrix.Services;
 
-namespace LibMatrix;
+namespace LibMatrix.Homeservers;
 
-public class AuthenticatedHomeServer : IHomeServer {
-    private readonly TieredStorageService _storage;
-    public readonly HomeserverAdminApi Admin;
-    public readonly SyncHelper SyncHelper;
+public class AuthenticatedHomeserverSynapse : AuthenticatedHomeserverGeneric {
+    public readonly SynapseAdminApi Admin;
+    public class SynapseAdminApi {
+        private readonly AuthenticatedHomeserverGeneric _authenticatedHomeserver;
 
-    public AuthenticatedHomeServer(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) {
-        _storage = storage;
-        AccessToken = accessToken.Trim();
-        HomeServerDomain = canonicalHomeServerDomain.Trim();
-        Admin = new HomeserverAdminApi(this);
-        SyncHelper = new SyncHelper(this, storage);
-        _httpClient = new MatrixHttpClient();
-    }
-
-    public WhoAmIResponse WhoAmI { get; set; } = null!;
-    public string UserId => WhoAmI.UserId;
-    public string AccessToken { get; set; }
-
-
-    public Task<GenericRoom> GetRoom(string roomId) => Task.FromResult<GenericRoom>(new(this, roomId));
-
-    public async Task<List<GenericRoom>> GetJoinedRooms() {
-        var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms");
-
-        var roomsJson = await roomQuery.Content.ReadFromJsonAsync<JsonElement>();
-        var rooms = roomsJson.GetProperty("joined_rooms").EnumerateArray().Select(room => new GenericRoom(this, room.GetString()!)).ToList();
-
-        Console.WriteLine($"Fetched {rooms.Count} rooms");
-
-        return rooms;
-    }
-
-    public 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()}");
-            throw new InvalidDataException($"Failed to upload file: {await res.Content.ReadAsStringAsync()}");
-        }
-
-        var resJson = await res.Content.ReadFromJsonAsync<JsonElement>();
-        return resJson.GetProperty("content_uri").GetString()!;
-    }
-
-    public async Task<GenericRoom> CreateRoom(CreateRoomRequest creationEvent) {
-        var res = await _httpClient.PostAsJsonAsync("/_matrix/client/v3/createRoom", creationEvent);
-        if (!res.IsSuccessStatusCode) {
-            Console.WriteLine($"Failed to create room: {await res.Content.ReadAsStringAsync()}");
-            throw new InvalidDataException($"Failed to create room: {await res.Content.ReadAsStringAsync()}");
-        }
-
-        return await GetRoom((await res.Content.ReadFromJsonAsync<JsonObject>())!["room_id"]!.ToString());
-    }
-
-    public class HomeserverAdminApi {
-        private readonly AuthenticatedHomeServer _authenticatedHomeServer;
-
-        public HomeserverAdminApi(AuthenticatedHomeServer authenticatedHomeServer) => _authenticatedHomeServer = authenticatedHomeServer;
+        public SynapseAdminApi(AuthenticatedHomeserverGeneric authenticatedHomeserver) => _authenticatedHomeserver = authenticatedHomeserver;
 
         public async IAsyncEnumerable<AdminRoomListingResult.AdminRoomListingResultRoom> SearchRoomsAsync(int limit = int.MaxValue, string orderBy = "name", string dir = "f", string? searchTerm = null, LocalRoomQueryFilter? localFilter = null) {
             AdminRoomListingResult? res = null;
@@ -83,7 +26,7 @@ public class AuthenticatedHomeServer : IHomeServer {
 
                 Console.WriteLine($"--- ADMIN Querying Room List with URL: {url} - Already have {i} items... ---");
 
-                res = await _authenticatedHomeServer._httpClient.GetFromJsonAsync<AdminRoomListingResult>(url);
+                res = await _authenticatedHomeserver._httpClient.GetFromJsonAsync<AdminRoomListingResult>(url);
                 totalRooms ??= res?.TotalRooms;
                 Console.WriteLine(res.ToJson(false));
                 foreach (var room in res.Rooms) {
@@ -160,14 +103,8 @@ public class AuthenticatedHomeServer : IHomeServer {
             } while (i < Math.Min(limit, totalRooms ?? limit));
         }
     }
-}
 
-public class WhoAmIResponse {
-    [JsonPropertyName("user_id")]
-    public string UserId { get; set; } = null!;
-
-    [JsonPropertyName("device_id")]
-    public string? DeviceId { get; set; }
-    [JsonPropertyName("is_guest")]
-    public bool? IsGuest { get; set; }
+    public AuthenticatedHomeserverSynapse(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : base(storage, canonicalHomeServerDomain, accessToken) {
+        Admin = new(this);
+    }
 }
diff --git a/LibMatrix/Homeservers/RemoteHomeServer.cs b/LibMatrix/Homeservers/RemoteHomeServer.cs
new file mode 100644
index 0000000..fc31f4f
--- /dev/null
+++ b/LibMatrix/Homeservers/RemoteHomeServer.cs
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using System.Net.Http.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using LibMatrix.Extensions;
+using LibMatrix.Responses;
+using LibMatrix.StateEventTypes.Spec;
+
+namespace LibMatrix.Homeservers;
+
+public class RemoteHomeServer {
+    public RemoteHomeServer(string canonicalHomeServerDomain) {
+        HomeServerDomain = canonicalHomeServerDomain;
+        _httpClient = new MatrixHttpClient();
+        _httpClient.Timeout = TimeSpan.FromSeconds(5);
+    }
+
+    private Dictionary<string, object> _profileCache { get; set; } = new();
+    public string HomeServerDomain { get; set; }
+    public string FullHomeServerDomain { get; set; }
+    public MatrixHttpClient _httpClient { get; set; }
+
+    public async Task<ProfileResponseEventData> 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;
+        }
+        _profileCache[mxid] = new SemaphoreSlim(1);
+
+        var resp = await _httpClient.GetAsync($"/_matrix/client/v3/profile/{mxid}");
+        var data = await resp.Content.ReadFromJsonAsync<ProfileResponseEventData>();
+        if (!resp.IsSuccessStatusCode) Console.WriteLine("Profile: " + data);
+        _profileCache[mxid] = data;
+
+        return data;
+    }
+
+    public async Task<ClientVersionsResponse> GetClientVersions() {
+        var resp = await _httpClient.GetAsync($"/_matrix/client/versions");
+        var data = await resp.Content.ReadFromJsonAsync<ClientVersionsResponse>();
+        if (!resp.IsSuccessStatusCode) Console.WriteLine("ClientVersions: " + data);
+        return data;
+    }
+}