about summary refs log tree commit diff
path: root/LibMatrix
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-08-14 19:46:11 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-08-14 19:46:11 +0200
commitcb8846a7a3310f8513989da5aadb5202f048a1b3 (patch)
treecfbcf2506947d0f820208dd4cdb7a56c660ef0f9 /LibMatrix
parentUpdate dependencies (diff)
downloadLibMatrix-cb8846a7a3310f8513989da5aadb5202f048a1b3.tar.xz
Code cleanup
Diffstat (limited to 'LibMatrix')
-rw-r--r--LibMatrix/AuthenticatedHomeServer.cs5
-rw-r--r--LibMatrix/Extensions/DictionaryExtensions.cs3
-rw-r--r--LibMatrix/Extensions/HttpClientExtensions.cs38
-rw-r--r--LibMatrix/Extensions/JsonElementExtensions.cs4
-rw-r--r--LibMatrix/Filters/LocalRoomQueryFilter.cs6
-rw-r--r--LibMatrix/Helpers/SyncHelper.cs5
-rw-r--r--LibMatrix/Responses/StateEventResponse.cs2
-rw-r--r--LibMatrix/RoomTypes/GenericRoom.cs10
-rw-r--r--LibMatrix/RoomTypes/SpaceRoom.cs2
-rw-r--r--LibMatrix/Services/HomeserverProviderService.cs9
-rw-r--r--LibMatrix/Services/HomeserverResolverService.cs21
-rw-r--r--LibMatrix/Services/ServiceInstaller.cs16
-rw-r--r--LibMatrix/StateEvent.cs6
13 files changed, 62 insertions, 65 deletions
diff --git a/LibMatrix/AuthenticatedHomeServer.cs b/LibMatrix/AuthenticatedHomeServer.cs
index 102d448..a99dc27 100644
--- a/LibMatrix/AuthenticatedHomeServer.cs
+++ b/LibMatrix/AuthenticatedHomeServer.cs
@@ -32,14 +32,13 @@ public class AuthenticatedHomeServer : IHomeServer {
     public string AccessToken { get; set; }
 
 
-    public async Task<GenericRoom> GetRoom(string roomId) => new(this, roomId);
+    public Task<GenericRoom> GetRoom(string roomId) => Task.FromResult<GenericRoom>(new(this, roomId));
 
     public async Task<List<GenericRoom>> GetJoinedRooms() {
-        var rooms = new List<GenericRoom>();
         var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms");
 
         var roomsJson = await roomQuery.Content.ReadFromJsonAsync<JsonElement>();
-        foreach (var room in roomsJson.GetProperty("joined_rooms").EnumerateArray()) rooms.Add(new GenericRoom(this, room.GetString()));
+        var rooms = roomsJson.GetProperty("joined_rooms").EnumerateArray().Select(room => new GenericRoom(this, room.GetString()!)).ToList();
 
         Console.WriteLine($"Fetched {rooms.Count} rooms");
 
diff --git a/LibMatrix/Extensions/DictionaryExtensions.cs b/LibMatrix/Extensions/DictionaryExtensions.cs
index fbc5cf5..f01cf68 100644
--- a/LibMatrix/Extensions/DictionaryExtensions.cs
+++ b/LibMatrix/Extensions/DictionaryExtensions.cs
@@ -3,8 +3,7 @@ namespace LibMatrix.Extensions;
 public static class DictionaryExtensions {
     public static bool ChangeKey<TKey, TValue>(this IDictionary<TKey, TValue> dict,
         TKey oldKey, TKey newKey) {
-        TValue value;
-        if (!dict.Remove(oldKey, out value))
+        if (!dict.Remove(oldKey, out var value))
             return false;
 
         dict[newKey] = value; // or dict.Add(newKey, value) depending on ur comfort
diff --git a/LibMatrix/Extensions/HttpClientExtensions.cs b/LibMatrix/Extensions/HttpClientExtensions.cs
index 797a077..d4017ed 100644
--- a/LibMatrix/Extensions/HttpClientExtensions.cs
+++ b/LibMatrix/Extensions/HttpClientExtensions.cs
@@ -1,3 +1,4 @@
+using System.Diagnostics;
 using System.Net.Http.Headers;
 using System.Reflection;
 using System.Text.Json;
@@ -23,7 +24,7 @@ public class MatrixHttpClient : HttpClient {
         CancellationToken cancellationToken) {
         Console.WriteLine($"Sending request to {request.RequestUri}");
         try {
-            HttpRequestOptionsKey<bool> WebAssemblyEnableStreamingResponseKey =
+            var WebAssemblyEnableStreamingResponseKey =
                 new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse");
             request.Options.Set(WebAssemblyEnableStreamingResponseKey, true);
         }
@@ -33,26 +34,23 @@ public class MatrixHttpClient : HttpClient {
         }
 
         var a = await base.SendAsync(request, cancellationToken);
-        if (!a.IsSuccessStatusCode) {
-            var content = await a.Content.ReadAsStringAsync(cancellationToken);
-            if (content.StartsWith('{')) {
-                var ex = JsonSerializer.Deserialize<MatrixException>(content);
-                ex.RawContent = content;
-                // Console.WriteLine($"Failed to send request: {ex}");
-                if (ex?.RetryAfterMs is not null) {
-                    await Task.Delay(ex.RetryAfterMs.Value, cancellationToken);
-                    typeof(HttpRequestMessage).GetField("_sendStatus", BindingFlags.NonPublic | BindingFlags.Instance)
-                        ?.SetValue(request, 0);
-                    return await SendAsync(request, cancellationToken);
-                }
+        if (a.IsSuccessStatusCode) return a;
 
-                throw ex!;
-            }
+        //error handling
+        var content = await a.Content.ReadAsStringAsync(cancellationToken);
+        if (!content.StartsWith('{')) throw new InvalidDataException("Encountered invalid data:\n" + content);
+        //we have a matrix error
+        var ex = JsonSerializer.Deserialize<MatrixException>(content);
+        Debug.Assert(ex != null, nameof(ex) + " != null");
+        ex.RawContent = content;
+        // Console.WriteLine($"Failed to send request: {ex}");
+        if (ex?.RetryAfterMs is null) throw ex!;
+        //we have a ratelimit error
+        await Task.Delay(ex.RetryAfterMs.Value, cancellationToken);
+        typeof(HttpRequestMessage).GetField("_sendStatus", BindingFlags.NonPublic | BindingFlags.Instance)
+            ?.SetValue(request, 0);
+        return await SendAsync(request, cancellationToken);
 
-            throw new InvalidDataException("Encountered invalid data:\n" + content);
-        }
-
-        return a;
     }
 
     // GetFromJsonAsync
@@ -66,7 +64,7 @@ public class MatrixHttpClient : HttpClient {
     }
 
     // GetStreamAsync
-    public async Task<Stream> GetStreamAsync(string requestUri, CancellationToken cancellationToken = default) {
+    public new async Task<Stream> GetStreamAsync(string requestUri, CancellationToken cancellationToken = default) {
         var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
         request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         var response = await SendAsync(request, cancellationToken);
diff --git a/LibMatrix/Extensions/JsonElementExtensions.cs b/LibMatrix/Extensions/JsonElementExtensions.cs
index caf96e1..f39f300 100644
--- a/LibMatrix/Extensions/JsonElementExtensions.cs
+++ b/LibMatrix/Extensions/JsonElementExtensions.cs
@@ -14,7 +14,7 @@ public static class JsonElementExtensions {
         //     return false;
 
         Console.WriteLine($"{objectType.Name} {objectPropertyName}");
-        bool unknownPropertyFound = false;
+        var unknownPropertyFound = false;
         var mappedPropsDict = objectType.GetProperties()
             .Where(x => x.GetCustomAttribute<JsonPropertyNameAttribute>() is not null)
             .ToDictionary(x => x.GetCustomAttribute<JsonPropertyNameAttribute>()!.Name, x => x);
@@ -61,7 +61,7 @@ public static class JsonElementExtensions {
             propertyType = propertyType.GetGenericArguments()[0];
         }
 
-        bool switchResult = false;
+        var switchResult = false;
         switch (field.Value.ValueKind) {
             case JsonValueKind.Array:
                 switchResult = field.Value.EnumerateArray().Aggregate(switchResult,
diff --git a/LibMatrix/Filters/LocalRoomQueryFilter.cs b/LibMatrix/Filters/LocalRoomQueryFilter.cs
index 668d408..6673716 100644
--- a/LibMatrix/Filters/LocalRoomQueryFilter.cs
+++ b/LibMatrix/Filters/LocalRoomQueryFilter.cs
@@ -14,12 +14,12 @@ public class LocalRoomQueryFilter {
     public bool Federatable { get; set; } = true;
     public bool Public { get; set; } = true;
 
-    public int JoinedMembersGreaterThan { get; set; } = 0;
+    public int JoinedMembersGreaterThan { get; set; }
     public int JoinedMembersLessThan { get; set; } = int.MaxValue;
 
-    public int JoinedLocalMembersGreaterThan { get; set; } = 0;
+    public int JoinedLocalMembersGreaterThan { get; set; }
     public int JoinedLocalMembersLessThan { get; set; } = int.MaxValue;
-    public int StateEventsGreaterThan { get; set; } = 0;
+    public int StateEventsGreaterThan { get; set; }
     public int StateEventsLessThan { get; set; } = int.MaxValue;
 
 
diff --git a/LibMatrix/Helpers/SyncHelper.cs b/LibMatrix/Helpers/SyncHelper.cs
index 2015eaa..b957c0c 100644
--- a/LibMatrix/Helpers/SyncHelper.cs
+++ b/LibMatrix/Helpers/SyncHelper.cs
@@ -76,10 +76,9 @@ public class SyncHelper {
             .Where(x => x.StartsWith("sync"))
             .ToList()
             .Select(x => _storageService.CacheStorageProvider.DeleteObjectAsync(x)));
-        SyncResult? sync = null;
-        string? nextBatch = since;
+        var nextBatch = since;
         while (cancellationToken is null || !cancellationToken.Value.IsCancellationRequested) {
-            sync = await Sync(since: nextBatch, timeout: timeout, setPresence: setPresence, filter: filter,
+            var sync = await Sync(since: nextBatch, timeout: timeout, setPresence: setPresence, filter: filter,
                 cancellationToken: cancellationToken);
             nextBatch = sync?.NextBatch ?? nextBatch;
             if (sync is null) continue;
diff --git a/LibMatrix/Responses/StateEventResponse.cs b/LibMatrix/Responses/StateEventResponse.cs
index b3d5b96..c60d71c 100644
--- a/LibMatrix/Responses/StateEventResponse.cs
+++ b/LibMatrix/Responses/StateEventResponse.cs
@@ -23,7 +23,7 @@ public class StateEventResponse : StateEvent {
     public string UserId { get; set; }
 
     [JsonPropertyName("replaces_state")]
-    public string ReplacesState { get; set; }
+    public new string ReplacesState { get; set; }
 
     public class UnsignedData {
         [JsonPropertyName("age")]
diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs
index b935b9d..df1eb52 100644
--- a/LibMatrix/RoomTypes/GenericRoom.cs
+++ b/LibMatrix/RoomTypes/GenericRoom.cs
@@ -100,8 +100,8 @@ public class GenericRoom {
     public async IAsyncEnumerable<StateEventResponse> GetMembersAsync(bool joinedOnly = true) {
         var res = GetFullStateAsync();
         await foreach (var member in res) {
-            if (member.Type != "m.room.member") continue;
-            if (joinedOnly && (member.TypedContent as RoomMemberEventData).Membership is not "join") continue;
+            if (member?.Type != "m.room.member") continue;
+            if (joinedOnly && (member.TypedContent as RoomMemberEventData)?.Membership is not "join") continue;
             yield return member;
         }
     }
@@ -147,15 +147,15 @@ public class GenericRoom {
 
     public async Task KickAsync(string userId, string? reason = null) =>
         await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/kick",
-            new UserIdAndReason() { UserId = userId, Reason = reason });
+            new UserIdAndReason { UserId = userId, Reason = reason });
 
     public async Task BanAsync(string userId, string? reason = null) =>
         await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/ban",
-            new UserIdAndReason() { UserId = userId, Reason = reason });
+            new UserIdAndReason { UserId = userId, Reason = reason });
 
     public async Task UnbanAsync(string userId) =>
         await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/unban",
-            new UserIdAndReason() { UserId = userId });
+            new UserIdAndReason { UserId = userId });
 
     public async Task<EventIdResponse> SendStateEventAsync(string eventType, object content) =>
         await (await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}", content))
diff --git a/LibMatrix/RoomTypes/SpaceRoom.cs b/LibMatrix/RoomTypes/SpaceRoom.cs
index ff2c228..5393ee7 100644
--- a/LibMatrix/RoomTypes/SpaceRoom.cs
+++ b/LibMatrix/RoomTypes/SpaceRoom.cs
@@ -3,7 +3,7 @@ using LibMatrix.Extensions;
 namespace LibMatrix.RoomTypes;
 
 public class SpaceRoom : GenericRoom {
-    private readonly AuthenticatedHomeServer _homeServer;
+    private new readonly AuthenticatedHomeServer _homeServer;
     private readonly GenericRoom _room;
 
     public SpaceRoom(AuthenticatedHomeServer homeServer, string roomId) : base(homeServer, roomId) {
diff --git a/LibMatrix/Services/HomeserverProviderService.cs b/LibMatrix/Services/HomeserverProviderService.cs
index 61c449a..366f0ca 100644
--- a/LibMatrix/Services/HomeserverProviderService.cs
+++ b/LibMatrix/Services/HomeserverProviderService.cs
@@ -14,12 +14,11 @@ public class HomeserverProviderService {
 
     public HomeserverProviderService(TieredStorageService tieredStorageService,
         ILogger<HomeserverProviderService> logger, HomeserverResolverService homeserverResolverService) {
-        Console.WriteLine("Homeserver provider service instantiated!");
         _tieredStorageService = tieredStorageService;
         _logger = logger;
         _homeserverResolverService = homeserverResolverService;
-        logger.LogDebug(
-            $"New HomeserverProviderService created with TieredStorageService<{string.Join(", ", tieredStorageService.GetType().GetProperties().Select(x => x.Name))}>!");
+        logger.LogDebug("New HomeserverProviderService created with TieredStorageService<{}>!",
+            string.Join(", ", tieredStorageService.GetType().GetProperties().Select(x => x.Name)));
     }
 
     private static Dictionary<string, SemaphoreSlim> _authenticatedHomeserverSemaphore = new();
@@ -27,7 +26,7 @@ public class HomeserverProviderService {
 
     public async Task<AuthenticatedHomeServer> GetAuthenticatedWithToken(string homeserver, string accessToken,
         string? overrideFullDomain = null) {
-        SemaphoreSlim sem = _authenticatedHomeserverSemaphore.GetOrCreate(homeserver+accessToken, _ => new SemaphoreSlim(1, 1));
+        var sem = _authenticatedHomeserverSemaphore.GetOrCreate(homeserver+accessToken, _ => new SemaphoreSlim(1, 1));
         await sem.WaitAsync();
         if (_authenticatedHomeServerCache.ContainsKey(homeserver+accessToken)) {
             sem.Release();
@@ -64,7 +63,7 @@ public class HomeserverProviderService {
         string? overrideFullDomain = null) {
         var hs = await GetRemoteHomeserver(homeserver, overrideFullDomain);
         var payload = new LoginRequest {
-            Identifier = new() { User = user },
+            Identifier = new LoginRequest.LoginIdentifier { User = user },
             Password = password
         };
         var resp = await hs._httpClient.PostAsJsonAsync("/_matrix/client/v3/login", payload);
diff --git a/LibMatrix/Services/HomeserverResolverService.cs b/LibMatrix/Services/HomeserverResolverService.cs
index 4d3bc46..78c5c37 100644
--- a/LibMatrix/Services/HomeserverResolverService.cs
+++ b/LibMatrix/Services/HomeserverResolverService.cs
@@ -18,13 +18,13 @@ public class HomeserverResolverService {
     public async Task<string> ResolveHomeserverFromWellKnown(string homeserver) {
         var res = await _resolveHomeserverFromWellKnown(homeserver);
         if (!res.StartsWith("http")) res = "https://" + res;
-        if (res.EndsWith(":443")) res = res.Substring(0, res.Length - 4);
+        if (res.EndsWith(":443")) res = res[..^4];
         return res;
     }
 
     private async Task<string> _resolveHomeserverFromWellKnown(string homeserver) {
         if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
-        SemaphoreSlim sem = _wellKnownSemaphores.GetOrCreate(homeserver, _ => new SemaphoreSlim(1, 1));
+        var sem = _wellKnownSemaphores.GetOrCreate(homeserver, _ => new SemaphoreSlim(1, 1));
         await sem.WaitAsync();
         if (_wellKnownCache.ContainsKey(homeserver)) {
             sem.Release();
@@ -32,19 +32,18 @@ public class HomeserverResolverService {
         }
 
         string? result = null;
-        _logger.LogInformation($"Attempting to resolve homeserver: {homeserver}");
+        _logger.LogInformation("Attempting to resolve homeserver: {}", homeserver);
         result ??= await _tryResolveFromClientWellknown(homeserver);
         result ??= await _tryResolveFromServerWellknown(homeserver);
         result ??= await _tryCheckIfDomainHasHomeserver(homeserver);
 
-        if (result is not null) {
-            _logger.LogInformation($"Resolved homeserver: {homeserver} -> {result}");
-            _wellKnownCache[homeserver] = result;
-            sem.Release();
-            return result;
-        }
+        if (result is null) throw new InvalidDataException($"Failed to resolve homeserver for {homeserver}! Is it online and configured correctly?");
 
-        throw new InvalidDataException($"Failed to resolve homeserver for {homeserver}! Is it online and configured correctly?");
+        //success!
+        _logger.LogInformation("Resolved homeserver: {} -> {}", homeserver, result);
+        _wellKnownCache[homeserver] = result;
+        sem.Release();
+        return result;
     }
 
     private async Task<string?> _tryResolveFromClientWellknown(string homeserver) {
@@ -72,7 +71,7 @@ public class HomeserverResolverService {
     }
 
     private async Task<string?> _tryCheckIfDomainHasHomeserver(string homeserver) {
-        _logger.LogInformation($"Checking if {homeserver} hosts a homeserver...");
+        _logger.LogInformation("Checking if {} hosts a homeserver...", homeserver);
         if (await _httpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions"))
             return homeserver;
         _logger.LogInformation("No homeserver on shortname...");
diff --git a/LibMatrix/Services/ServiceInstaller.cs b/LibMatrix/Services/ServiceInstaller.cs
index 96a1963..b1c98e1 100644
--- a/LibMatrix/Services/ServiceInstaller.cs
+++ b/LibMatrix/Services/ServiceInstaller.cs
@@ -9,14 +9,18 @@ public static class ServiceInstaller {
         if (!services.Any(x => x.ServiceType == typeof(TieredStorageService)))
             throw new Exception("[MRUCore/DI] No TieredStorageService has been registered!");
         //Add config
-        if(config is not null)
-            services.AddSingleton(config);
-        else {
-            services.AddSingleton(new RoryLibMatrixConfiguration());
-        }
+        services.AddSingleton(config ?? new RoryLibMatrixConfiguration());
+
         //Add services
-        services.AddSingleton<HomeserverProviderService>();
         services.AddSingleton<HomeserverResolverService>();
+
+        if (services.First(x => x.ServiceType == typeof(TieredStorageService)).Lifetime == ServiceLifetime.Singleton) {
+            services.AddSingleton<HomeserverProviderService>();
+        }
+        else {
+            services.AddScoped<HomeserverProviderService>();
+        }
+
         // services.AddScoped<MatrixHttpClient>();
         return services;
     }
diff --git a/LibMatrix/StateEvent.cs b/LibMatrix/StateEvent.cs
index 5efeaf5..a2f951b 100644
--- a/LibMatrix/StateEvent.cs
+++ b/LibMatrix/StateEvent.cs
@@ -29,7 +29,7 @@ public class StateEvent {
             }
             catch (JsonException e) {
                 Console.WriteLine(e);
-                Console.WriteLine("Content:\n" + ObjectExtensions.ToJson(RawContent));
+                Console.WriteLine("Content:\n" + (RawContent?.ToJson() ?? "null"));
             }
 
             return null;
@@ -72,7 +72,7 @@ public class StateEvent {
     }
 
     [JsonIgnore]
-    public Type GetType {
+    public new Type GetType {
         get {
             var type = GetStateEventType(Type);
 
@@ -106,7 +106,7 @@ public class StateEvent {
     public string dtype {
         get {
             var res = GetType().Name switch {
-                "StateEvent`1" => $"StateEvent",
+                "StateEvent`1" => "StateEvent",
                 _ => GetType().Name
             };
             return res;