summary refs log tree commit diff
path: root/MxApiExtensions
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-10-17 17:05:49 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-10-17 17:05:49 +0200
commit72b8f014866be5d0631a5b432b9d55569554e524 (patch)
tree8329792b9400449ca9519f4714475c08cbf7a52a /MxApiExtensions
parentRefactors (diff)
downloadMxApiExtensions-72b8f014866be5d0631a5b432b9d55569554e524.tar.xz
Refactors
Diffstat (limited to 'MxApiExtensions')
-rw-r--r--MxApiExtensions/Classes/SyncState.cs7
-rw-r--r--MxApiExtensions/Controllers/ClientVersionsController.cs2
-rw-r--r--MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs16
-rw-r--r--MxApiExtensions/Controllers/SyncController.cs64
-rw-r--r--MxApiExtensions/MxApiExtensions.csproj2
5 files changed, 45 insertions, 46 deletions
diff --git a/MxApiExtensions/Classes/SyncState.cs b/MxApiExtensions/Classes/SyncState.cs
index 7f07894..6950954 100644
--- a/MxApiExtensions/Classes/SyncState.cs
+++ b/MxApiExtensions/Classes/SyncState.cs
@@ -1,14 +1,15 @@
 using System.Collections.Concurrent;
 using LibMatrix.Helpers;
 using LibMatrix.Homeservers;
+using LibMatrix.Responses;
 
 namespace MxApiExtensions.Classes;
 
 public class SyncState {
     public string? NextBatch { get; set; }
-    public ConcurrentQueue<SyncResult> SyncQueue { get; set; } = new();
+    public ConcurrentQueue<SyncResponse> SyncQueue { get; set; } = new();
     public bool IsInitialSync { get; set; }
-    public Task? NextSyncResult { get; set; }
-    public DateTime NextSyncResultStartedAt { get; set; } = DateTime.Now;
+    public Task? NextSyncResponse { get; set; }
+    public DateTime NextSyncResponseStartedAt { get; set; } = DateTime.Now;
     public AuthenticatedHomeserverGeneric Homeserver { get; set; }
 }
diff --git a/MxApiExtensions/Controllers/ClientVersionsController.cs b/MxApiExtensions/Controllers/ClientVersionsController.cs
index 518b954..d29e3b2 100644
--- a/MxApiExtensions/Controllers/ClientVersionsController.cs
+++ b/MxApiExtensions/Controllers/ClientVersionsController.cs
@@ -40,7 +40,7 @@ public class ClientVersionsController : ControllerBase {
         };
         try {
             var hs = await _authenticatedHomeserverProviderService.GetHomeserver();
-            clientVersions = await hs.GetClientVersions();
+            clientVersions = await hs.GetClientVersionsAsync();
 
             _logger.LogInformation("Fetching client versions for {}: {}{}", hs.WhoAmI.UserId, Request.Path, Request.QueryString);
         }
diff --git a/MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs b/MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs
index 912d1da..9383390 100644
--- a/MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs
+++ b/MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs
@@ -1,9 +1,9 @@
 using System.Collections.Concurrent;
 using System.Net.Http.Headers;
 using ArcaneLibs.Extensions;
+using LibMatrix.EventTypes.Spec.State;
 using LibMatrix.Homeservers;
 using LibMatrix.RoomTypes;
-using LibMatrix.StateEventTypes.Spec;
 using Microsoft.AspNetCore.Mvc;
 using MxApiExtensions.Classes.LibMatrix;
 using MxApiExtensions.Services;
@@ -34,7 +34,7 @@ public class JoinedRoomListController : ControllerBase {
         AuthenticatedHomeserverGeneric? hs = null;
         try {
             hs = await _authenticatedHomeserverProviderService.GetHomeserver();
-            _logger.LogInformation("Got room list with info request for {user} ({hs})", hs.UserId, hs.FullHomeServerDomain);
+            _logger.LogInformation("Got room list with info request for {user} ({hs})", hs.UserId, hs.ServerName);
             rooms = await hs.GetJoinedRooms();
         }
         catch (MxApiMatrixException e) {
@@ -59,7 +59,7 @@ public class JoinedRoomListController : ControllerBase {
             Response.Headers.Add("Cache-Control", "public, max-age=60");
             Response.Headers.Add("Expires", DateTime.Now.AddMinutes(1).ToString("R"));
             Response.Headers.Add("Last-Modified", DateTime.Now.ToString("R"));
-            Response.Headers.Add("X-Matrix-Server", hs.FullHomeServerDomain);
+            Response.Headers.Add("X-Matrix-Server", hs.ServerName);
             Response.Headers.Add("X-Matrix-User", hs.UserId);
             // await Response.StartAsync();
 
@@ -70,21 +70,21 @@ public class JoinedRoomListController : ControllerBase {
 
             foreach (var room in cachedRooms) {
                 yield return room.Value;
-                _logger.LogInformation("Sent cached room info for {room} for {user} ({hs})", room.Key, hs.UserId, hs.FullHomeServerDomain);
+                _logger.LogInformation("Sent cached room info for {room} for {user} ({hs})", room.Key, hs.UserId, hs.ServerName);
             }
 
             var tasks = rooms.Select(r => GetRoomInfo(hs, r.RoomId)).ToAsyncEnumerable();
 
             await foreach (var result in tasks) {
                 yield return result;
-                _logger.LogInformation("Sent room info for {room} for {user} ({hs})", result.RoomId, hs.UserId, hs.FullHomeServerDomain);
+                _logger.LogInformation("Sent room info for {room} for {user} ({hs})", result.RoomId, hs.UserId, hs.ServerName);
             }
         }
     }
 
     private async Task<RoomInfoEntry> GetRoomInfo(AuthenticatedHomeserverGeneric hs, string roomId) {
-        _logger.LogInformation("Getting room info for {room} for {user} ({hs})", roomId, hs.UserId, hs.FullHomeServerDomain);
-        var room = await hs.GetRoom(roomId);
+        _logger.LogInformation("Getting room info for {room} for {user} ({hs})", roomId, hs.UserId, hs.ServerName);
+        var room = hs.GetRoom(roomId);
         var state = room.GetFullStateAsync();
         var result = new RoomInfoEntry {
             RoomId = roomId,
@@ -106,7 +106,7 @@ public class JoinedRoomListController : ControllerBase {
 
         result.ExpiresAt = result.ExpiresAt.AddMilliseconds(100 * result.StateCount);
 
-        _logger.LogInformation("Got room info for {room} for {user} ({hs})", roomId, hs.UserId, hs.FullHomeServerDomain);
+        _logger.LogInformation("Got room info for {room} for {user} ({hs})", roomId, hs.UserId, hs.ServerName);
         while (!_roomInfoCache.TryAdd(roomId, result)) {
             _logger.LogWarning("Failed to add room info for {room} to cache, retrying...", roomId);
             await Task.Delay(100);
diff --git a/MxApiExtensions/Controllers/SyncController.cs b/MxApiExtensions/Controllers/SyncController.cs
index 2bc47c1..bd41021 100644
--- a/MxApiExtensions/Controllers/SyncController.cs
+++ b/MxApiExtensions/Controllers/SyncController.cs
@@ -1,15 +1,13 @@
 using System.Collections.Concurrent;
-using System.Net.Http.Headers;
-using System.Text.Encodings.Web;
 using System.Text.Json;
 using System.Text.Json.Serialization;
 using System.Web;
 using LibMatrix;
+using LibMatrix.EventTypes.Spec.State;
 using LibMatrix.Helpers;
 using LibMatrix.Homeservers;
 using LibMatrix.Responses;
 using LibMatrix.RoomTypes;
-using LibMatrix.StateEventTypes.Spec;
 using Microsoft.AspNetCore.Mvc;
 using MxApiExtensions.Classes;
 using MxApiExtensions.Classes.LibMatrix;
@@ -49,7 +47,7 @@ public class SyncController : ControllerBase {
         qs.Remove("access_token");
 
         if (!_config.FastInitialSync.Enabled) {
-            _logger.LogInformation("Starting sync for {} on {} ({})", hs.WhoAmI.UserId, hs.HomeServerDomain, hs.AccessToken);
+            _logger.LogInformation("Starting sync for {} on {} ({})", hs.WhoAmI.UserId, hs.ServerName, hs.AccessToken);
             var result = await hs._httpClient.GetAsync($"{Request.Path}?{qs}");
             await Response.WriteHttpResponse(result);
             return;
@@ -57,30 +55,30 @@ public class SyncController : ControllerBase {
 
         try {
             var syncState = _syncStates.GetOrAdd(hs.AccessToken, _ => {
-                _logger.LogInformation("Started tracking sync state for {} on {} ({})", hs.WhoAmI.UserId, hs.HomeServerDomain, hs.AccessToken);
+                _logger.LogInformation("Started tracking sync state for {} on {} ({})", hs.WhoAmI.UserId, hs.ServerName, hs.AccessToken);
                 return new SyncState {
                     IsInitialSync = string.IsNullOrWhiteSpace(since),
                     Homeserver = hs
                 };
             });
 
-            if (syncState.NextSyncResult is null) {
-                _logger.LogInformation("Starting sync for {} on {} ({})", hs.WhoAmI.UserId, hs.HomeServerDomain, hs.AccessToken);
+            if (syncState.NextSyncResponse is null) {
+                _logger.LogInformation("Starting sync for {} on {} ({})", hs.WhoAmI.UserId, hs.ServerName, hs.AccessToken);
 
                 if (syncState.IsInitialSync) {
                     preloadTask = EnqueuePreloadData(syncState);
                 }
 
-                syncState.NextSyncResultStartedAt = DateTime.Now;
-                syncState.NextSyncResult = Task.Delay(30_000);
-                syncState.NextSyncResult.ContinueWith(x => {
-                    _logger.LogInformation("Sync for {} on {} ({}) starting", hs.WhoAmI.UserId, hs.HomeServerDomain, hs.AccessToken);
-                    syncState.NextSyncResult = hs._httpClient.GetAsync($"{Request.Path}?{qs}");
+                syncState.NextSyncResponseStartedAt = DateTime.Now;
+                syncState.NextSyncResponse = Task.Delay(30_000);
+                syncState.NextSyncResponse.ContinueWith(x => {
+                    _logger.LogInformation("Sync for {} on {} ({}) starting", hs.WhoAmI.UserId, hs.ServerName, hs.AccessToken);
+                    syncState.NextSyncResponse = hs._httpClient.GetAsync($"{Request.Path}?{qs}");
                 });
             }
 
             if (syncState.SyncQueue.Count > 0) {
-                _logger.LogInformation("Sync for {} on {} ({}) has {} queued results", hs.WhoAmI.UserId, hs.HomeServerDomain, hs.AccessToken, syncState.SyncQueue.Count);
+                _logger.LogInformation("Sync for {} on {} ({}) has {} queued results", hs.WhoAmI.UserId, hs.ServerName, hs.AccessToken, syncState.SyncQueue.Count);
                 syncState.SyncQueue.TryDequeue(out var result);
 
                 Response.StatusCode = StatusCodes.Status200OK;
@@ -95,32 +93,32 @@ public class SyncController : ControllerBase {
             }
 
             timeout = Math.Clamp(timeout, 0, 100);
-            _logger.LogInformation("Sync for {} on {} ({}) is still running, waiting for {}ms, {} elapsed", hs.WhoAmI.UserId, hs.HomeServerDomain, hs.AccessToken, timeout,
-                DateTime.Now.Subtract(syncState.NextSyncResultStartedAt));
+            _logger.LogInformation("Sync for {} on {} ({}) is still running, waiting for {}ms, {} elapsed", hs.WhoAmI.UserId, hs.ServerName, hs.AccessToken, timeout,
+                DateTime.Now.Subtract(syncState.NextSyncResponseStartedAt));
 
             try {
-                await syncState.NextSyncResult.WaitAsync(TimeSpan.FromMilliseconds(timeout));
+                await syncState.NextSyncResponse.WaitAsync(TimeSpan.FromMilliseconds(timeout));
             }
             catch { }
 
-            if (syncState.NextSyncResult is Task<HttpResponseMessage> { IsCompleted: true } response) {
-                _logger.LogInformation("Sync for {} on {} ({}) completed", hs.WhoAmI.UserId, hs.HomeServerDomain, hs.AccessToken);
+            if (syncState.NextSyncResponse is Task<HttpResponseMessage> { IsCompleted: true } response) {
+                _logger.LogInformation("Sync for {} on {} ({}) completed", hs.WhoAmI.UserId, hs.ServerName, hs.AccessToken);
                 var resp = await response;
                 await Response.WriteHttpResponse(resp);
                 return;
             }
 
             // await Task.Delay(timeout);
-            _logger.LogInformation("Sync for {} on {} ({}): sending bogus response", hs.WhoAmI.UserId, hs.HomeServerDomain, hs.AccessToken);
+            _logger.LogInformation("Sync for {} on {} ({}): sending bogus response", hs.WhoAmI.UserId, hs.ServerName, hs.AccessToken);
             Response.StatusCode = StatusCodes.Status200OK;
             Response.ContentType = "application/json";
             await Response.StartAsync();
-            var syncResult = new SyncResult {
+            var SyncResponse = new SyncResponse {
                 // NextBatch = "MxApiExtensions::Next" + Random.Shared.NextInt64(),
                 NextBatch = since ?? "",
                 Presence = new() {
                     Events = new() {
-                        await GetStatusMessage(syncState, $"{DateTime.Now.Subtract(syncState.NextSyncResultStartedAt)} {syncState.NextSyncResult.Status}")
+                        await GetStatusMessage(syncState, $"{DateTime.Now.Subtract(syncState.NextSyncResponseStartedAt)} {syncState.NextSyncResponse.Status}")
                     }
                 },
                 Rooms = new() {
@@ -128,7 +126,7 @@ public class SyncController : ControllerBase {
                     Join = new()
                 }
             };
-            await JsonSerializer.SerializeAsync(Response.Body, syncResult, new JsonSerializerOptions {
+            await JsonSerializer.SerializeAsync(Response.Body, SyncResponse, new JsonSerializerOptions {
                 WriteIndented = true,
                 DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
             });
@@ -136,7 +134,7 @@ public class SyncController : ControllerBase {
         }
         catch (MxApiMatrixException e) {
             _logger.LogError(e, "Error while syncing for {} on {} ({})", _hs.GetHomeserver().Result.WhoAmI.UserId,
-                _hs.GetHomeserver().Result.HomeServerDomain, _hs.GetHomeserver().Result.AccessToken);
+                _hs.GetHomeserver().Result.ServerName, _hs.GetHomeserver().Result.AccessToken);
 
             Response.StatusCode = StatusCodes.Status500InternalServerError;
             Response.ContentType = "application/json";
@@ -149,13 +147,13 @@ public class SyncController : ControllerBase {
             //catch SSL connection errors and retry
             if (e.InnerException is HttpRequestException && e.InnerException.Message.Contains("The SSL connection could not be established")) {
                 _logger.LogWarning("Caught SSL connection error, retrying sync for {} on {} ({})", _hs.GetHomeserver().Result.WhoAmI.UserId,
-                    _hs.GetHomeserver().Result.HomeServerDomain, _hs.GetHomeserver().Result.AccessToken);
+                    _hs.GetHomeserver().Result.ServerName, _hs.GetHomeserver().Result.AccessToken);
                 await Sync(since, timeout);
                 return;
             }
 
             _logger.LogError(e, "Error while syncing for {} on {} ({})", _hs.GetHomeserver().Result.WhoAmI.UserId,
-                _hs.GetHomeserver().Result.HomeServerDomain, _hs.GetHomeserver().Result.AccessToken);
+                _hs.GetHomeserver().Result.ServerName, _hs.GetHomeserver().Result.AccessToken);
 
             Response.StatusCode = StatusCodes.Status500InternalServerError;
             Response.ContentType = "text/plain";
@@ -171,7 +169,7 @@ public class SyncController : ControllerBase {
 
     private async Task EnqueuePreloadData(SyncState syncState) {
         var rooms = await syncState.Homeserver.GetJoinedRooms();
-        var dm_rooms = (await syncState.Homeserver.GetAccountData<Dictionary<string, List<string>>>("m.direct")).Aggregate(new List<string>(), (list, entry) => {
+        var dm_rooms = (await syncState.Homeserver.GetAccountDataAsync<Dictionary<string, List<string>>>("m.direct")).Aggregate(new List<string>(), (list, entry) => {
             list.AddRange(entry.Value);
             return list;
         });
@@ -185,7 +183,7 @@ public class SyncController : ControllerBase {
             return 5000;
         }).ToList();
         var roomDataTasks = rooms.Select(room => EnqueueRoomData(syncState, room)).ToList();
-        _logger.LogInformation("Preloading data for {} rooms on {} ({})", roomDataTasks.Count, syncState.Homeserver.HomeServerDomain, syncState.Homeserver.AccessToken);
+        _logger.LogInformation("Preloading data for {} rooms on {} ({})", roomDataTasks.Count, syncState.Homeserver.ServerName, syncState.Homeserver.AccessToken);
 
         await Task.WhenAll(roomDataTasks);
     }
@@ -197,12 +195,12 @@ public class SyncController : ControllerBase {
         var roomState = room.GetFullStateAsync();
         var timeline = await room.GetMessagesAsync(limit: 100, dir: "b");
         timeline.Chunk.Reverse();
-        var syncResult = new SyncResult {
+        var SyncResponse = new SyncResponse {
             Rooms = new() {
                 Join = new() {
                     {
                         room.RoomId,
-                        new SyncResult.RoomsDataStructure.JoinedRoomDataStructure {
+                        new SyncResponse.RoomsDataStructure.JoinedRoomDataStructure {
                             AccountData = new() {
                                 Events = new()
                             },
@@ -232,17 +230,17 @@ public class SyncController : ControllerBase {
             },
             Presence = new() {
                 Events = new() {
-                    await GetStatusMessage(syncState, $"{DateTime.Now.Subtract(syncState.NextSyncResultStartedAt)} {syncState.NextSyncResult.Status} {room.RoomId}")
+                    await GetStatusMessage(syncState, $"{DateTime.Now.Subtract(syncState.NextSyncResponseStartedAt)} {syncState.NextSyncResponse.Status} {room.RoomId}")
                 }
             },
             NextBatch = ""
         };
 
         await foreach (var stateEvent in roomState) {
-            syncResult.Rooms.Join[room.RoomId].State.Events.Add(stateEvent);
+            SyncResponse.Rooms.Join[room.RoomId].State.Events.Add(stateEvent);
         }
 
-        var joinRoom = syncResult.Rooms.Join[room.RoomId];
+        var joinRoom = SyncResponse.Rooms.Join[room.RoomId];
         joinRoom.Summary.Heroes.AddRange(joinRoom.State.Events
             .Where(x =>
                 x.Type == "m.room.member"
@@ -252,7 +250,7 @@ public class SyncController : ControllerBase {
             .Select(x => x.StateKey));
         joinRoom.Summary.JoinedMemberCount = joinRoom.Summary.Heroes.Count;
 
-        syncState.SyncQueue.Enqueue(syncResult);
+        syncState.SyncQueue.Enqueue(SyncResponse);
         _roomDataSemaphore.Release();
     }
 
diff --git a/MxApiExtensions/MxApiExtensions.csproj b/MxApiExtensions/MxApiExtensions.csproj
index 3939012..92474e0 100644
--- a/MxApiExtensions/MxApiExtensions.csproj
+++ b/MxApiExtensions/MxApiExtensions.csproj
@@ -9,7 +9,7 @@
     </PropertyGroup>
 
     <ItemGroup>
-        <PackageReference Include="ArcaneLibs" Version="1.0.0-preview6067543155.b32af48" />
+        <PackageReference Include="ArcaneLibs" Version="1.0.0-preview6437853305.78f6d30" />
         <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0-preview.7.23375.9" />
         <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
     </ItemGroup>