diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-08-14 19:46:11 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-08-14 19:46:11 +0200 |
commit | cb8846a7a3310f8513989da5aadb5202f048a1b3 (patch) | |
tree | cfbcf2506947d0f820208dd4cdb7a56c660ef0f9 | |
parent | Update dependencies (diff) | |
download | LibMatrix-bak-cb8846a7a3310f8513989da5aadb5202f048a1b3.tar.xz |
Code cleanup
21 files changed, 105 insertions, 110 deletions
diff --git a/LibMatrix.DebugDataValidationApi/Controllers/ValidationController.cs b/LibMatrix.DebugDataValidationApi/Controllers/ValidationController.cs index 1599f35..4dbee54 100644 --- a/LibMatrix.DebugDataValidationApi/Controllers/ValidationController.cs +++ b/LibMatrix.DebugDataValidationApi/Controllers/ValidationController.cs @@ -14,13 +14,13 @@ public class ValidationController : ControllerBase { } [HttpPost("/validate/{type}")] - public async Task<bool> Get([FromRoute] string type, [FromBody] JsonElement content) { - Type t = Type.GetType(type); + public Task<bool> Get([FromRoute] string type, [FromBody] JsonElement content) { + var t = Type.GetType(type); if (t is null) { Console.WriteLine($"Type `{type}` does not exist!"); throw new ArgumentException($"Unknown type {type}!"); } Console.WriteLine($"Validating {type}..."); - return content.FindExtraJsonElementFields(t, "$"); + return Task.FromResult(content.FindExtraJsonElementFields(t, "$")); } } diff --git a/LibMatrix.DebugDataValidationApi/Program.cs b/LibMatrix.DebugDataValidationApi/Program.cs index 047dbcf..cf9dc55 100644 --- a/LibMatrix.DebugDataValidationApi/Program.cs +++ b/LibMatrix.DebugDataValidationApi/Program.cs @@ -10,7 +10,7 @@ builder.Services.AddCors(options => { options.AddPolicy( "Open", - builder => builder.AllowAnyOrigin().AllowAnyHeader()); + policy => policy.AllowAnyOrigin().AllowAnyHeader()); }); var app = builder.Build(); diff --git a/LibMatrix.ExampleBot/Bot/Commands/CmdCommand.cs b/LibMatrix.ExampleBot/Bot/Commands/CmdCommand.cs index 7b54b0c..ca10326 100644 --- a/LibMatrix.ExampleBot/Bot/Commands/CmdCommand.cs +++ b/LibMatrix.ExampleBot/Bot/Commands/CmdCommand.cs @@ -1,23 +1,23 @@ using LibMatrix.ExampleBot.Bot.Interfaces; +using LibMatrix.StateEventTypes.Spec; namespace LibMatrix.ExampleBot.Bot.Commands; public class CmdCommand : ICommand { - public string Name { get; } = "cmd"; - public string Description { get; } = "Runs a command on the host system"; + public string Name => "cmd"; + public string Description => "Runs a command on the host system"; - public async Task<bool> CanInvoke(CommandContext ctx) { - return ctx.MessageEvent.Sender.EndsWith(":rory.gay"); + public Task<bool> CanInvoke(CommandContext ctx) { + return Task.FromResult(ctx.MessageEvent.Sender.EndsWith(":rory.gay")); } public async Task Invoke(CommandContext ctx) { - var cmd = "\""; - foreach (var arg in ctx.Args) cmd += arg + " "; + var cmd = ctx.Args.Aggregate("\"", (current, arg) => current + arg + " "); cmd = cmd.Trim(); cmd += "\""; - await ctx.Room.SendMessageEventAsync("m.room.message", new() { + await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventData { Body = $"Command being executed: `{cmd}`" }); @@ -34,7 +34,7 @@ public class CmdCommand : ICommand { msg += output[0] + "\n"; output.RemoveAt(0); if ((output.Count > 0 && (msg + output[0]).Length > 64000) || output.Count == 0) { - await ctx.Room.SendMessageEventAsync("m.room.message", new() { + await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventData { FormattedBody = $"```ansi\n{msg}\n```", // Body = Markdig.Markdown.ToHtml(msg), Format = "org.matrix.custom.html" @@ -43,4 +43,4 @@ public class CmdCommand : ICommand { } } } -} \ No newline at end of file +} diff --git a/LibMatrix.ExampleBot/Bot/Commands/HelpCommand.cs b/LibMatrix.ExampleBot/Bot/Commands/HelpCommand.cs index a259b3e..69766d1 100644 --- a/LibMatrix.ExampleBot/Bot/Commands/HelpCommand.cs +++ b/LibMatrix.ExampleBot/Bot/Commands/HelpCommand.cs @@ -1,28 +1,24 @@ using System.Text; using LibMatrix.ExampleBot.Bot.Interfaces; +using LibMatrix.StateEventTypes.Spec; using Microsoft.Extensions.DependencyInjection; -namespace LibMatrix.ExampleBot.Bot.Commands; - -public class HelpCommand : ICommand { - private readonly IServiceProvider _services; - public HelpCommand(IServiceProvider services) { - _services = services; - } +namespace LibMatrix.ExampleBot.Bot.Commands; +public class HelpCommand(IServiceProvider services) : ICommand { public string Name { get; } = "help"; public string Description { get; } = "Displays this help message"; public async Task Invoke(CommandContext ctx) { var sb = new StringBuilder(); sb.AppendLine("Available commands:"); - var commands = _services.GetServices<ICommand>().ToList(); + var commands = services.GetServices<ICommand>().ToList(); foreach (var command in commands) { sb.AppendLine($"- {command.Name}: {command.Description}"); } - await ctx.Room.SendMessageEventAsync("m.room.message", new() { - Body = sb.ToString(), + await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventData { + Body = sb.ToString() }); } -} \ No newline at end of file +} diff --git a/LibMatrix.ExampleBot/Bot/Commands/PingCommand.cs b/LibMatrix.ExampleBot/Bot/Commands/PingCommand.cs index 664dc53..a7c65b5 100644 --- a/LibMatrix.ExampleBot/Bot/Commands/PingCommand.cs +++ b/LibMatrix.ExampleBot/Bot/Commands/PingCommand.cs @@ -1,17 +1,15 @@ using LibMatrix.ExampleBot.Bot.Interfaces; +using LibMatrix.StateEventTypes.Spec; -namespace LibMatrix.ExampleBot.Bot.Commands; +namespace LibMatrix.ExampleBot.Bot.Commands; public class PingCommand : ICommand { - public PingCommand() { - } - public string Name { get; } = "ping"; public string Description { get; } = "Pong!"; public async Task Invoke(CommandContext ctx) { - await ctx.Room.SendMessageEventAsync("m.room.message", new() { + await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventData { Body = "pong!" }); } -} \ No newline at end of file +} diff --git a/LibMatrix.ExampleBot/Bot/FileStorageProvider.cs b/LibMatrix.ExampleBot/Bot/FileStorageProvider.cs index 249aba3..1e84ab7 100644 --- a/LibMatrix.ExampleBot/Bot/FileStorageProvider.cs +++ b/LibMatrix.ExampleBot/Bot/FileStorageProvider.cs @@ -23,13 +23,16 @@ public class FileStorageProvider : IStorageProvider { } } - public async Task SaveObjectAsync<T>(string key, T value) => await File.WriteAllTextAsync(Path.Join(TargetPath, key), ObjectExtensions.ToJson(value)); + public async Task SaveObjectAsync<T>(string key, T value) => await File.WriteAllTextAsync(Path.Join(TargetPath, key), value?.ToJson()); public async Task<T?> LoadObjectAsync<T>(string key) => JsonSerializer.Deserialize<T>(await File.ReadAllTextAsync(Path.Join(TargetPath, key))); - public async Task<bool> ObjectExistsAsync(string key) => File.Exists(Path.Join(TargetPath, key)); + public Task<bool> ObjectExistsAsync(string key) => Task.FromResult(File.Exists(Path.Join(TargetPath, key))); - public async Task<List<string>> GetAllKeysAsync() => Directory.GetFiles(TargetPath).Select(Path.GetFileName).ToList(); + public Task<List<string>> GetAllKeysAsync() => Task.FromResult(Directory.GetFiles(TargetPath).Select(Path.GetFileName).ToList()); - public async Task DeleteObjectAsync(string key) => File.Delete(Path.Join(TargetPath, key)); + public Task DeleteObjectAsync(string key) { + File.Delete(Path.Join(TargetPath, key)); + return Task.CompletedTask; + } } diff --git a/LibMatrix.ExampleBot/Bot/MRUBot.cs b/LibMatrix.ExampleBot/Bot/MRUBot.cs index eecab84..cdeefe2 100644 --- a/LibMatrix.ExampleBot/Bot/MRUBot.cs +++ b/LibMatrix.ExampleBot/Bot/MRUBot.cs @@ -23,7 +23,7 @@ public class MRUBot : IHostedService { _configuration = configuration; _logger.LogInformation("Getting commands..."); _commands = services.GetServices<ICommand>(); - _logger.LogInformation($"Got {_commands.Count()} commands!"); + _logger.LogInformation("Got {} commands!", _commands.Count()); } /// <summary>Triggered when the application host is ready to start the service.</summary> @@ -37,7 +37,7 @@ public class MRUBot : IHostedService { _configuration.AccessToken); } catch (Exception e) { - _logger.LogError(e.Message); + _logger.LogError("{}", e.Message); throw; } @@ -57,36 +57,36 @@ public class MRUBot : IHostedService { x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId); _logger.LogInformation( $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventData).Reason}"); - if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender == "@mxidupwitch:the-apothecary.club" ) { + if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender == "@mxidupwitch:the-apothecary.club") { try { var senderProfile = await hs.GetProfile(inviteEvent.Sender); await (await hs.GetRoom(args.Key)).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!"); } catch (Exception e) { - _logger.LogError(e.ToString()); + _logger.LogError("{}", e.ToString()); await (await hs.GetRoom(args.Key)).LeaveAsync(reason: "I was unable to join the room: " + e); } } }); hs.SyncHelper.TimelineEventHandlers.Add(async @event => { _logger.LogInformation( - $"Got timeline event in {@event.RoomId}: {@event.ToJson(indent: false, ignoreNull: true)}"); + "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(indent: false, ignoreNull: true)); var room = await hs.GetRoom(@event.RoomId); // _logger.LogInformation(eventResponse.ToJson(indent: false)); if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventData message }) { if (message is { MessageType: "m.text" } && message.Body.StartsWith(_configuration.Prefix)) { - var command = _commands.FirstOrDefault(x => x.Name == message.Body.Split(' ')[0][_configuration.Prefix.Length..]); if (command == null) { await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData() { + new RoomMessageEventData { MessageType = "m.text", Body = "Command not found!" }); return; } - var ctx = new CommandContext() { + + var ctx = new CommandContext { Room = room, MessageEvent = @event }; @@ -95,7 +95,7 @@ public class MRUBot : IHostedService { } else { await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData() { + new RoomMessageEventData { MessageType = "m.text", Body = "You do not have permission to run this command!" }); @@ -108,7 +108,8 @@ public class MRUBot : IHostedService { /// <summary>Triggered when the application host is performing a graceful shutdown.</summary> /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param> - public async Task StopAsync(CancellationToken cancellationToken) { + public Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Shutting down bot!"); + return Task.CompletedTask; } } diff --git a/LibMatrix.ExampleBot/Program.cs b/LibMatrix.ExampleBot/Program.cs index 93a5f27..63610b4 100644 --- a/LibMatrix.ExampleBot/Program.cs +++ b/LibMatrix.ExampleBot/Program.cs @@ -11,7 +11,7 @@ Console.WriteLine("Hello, World!"); var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { services.AddScoped<TieredStorageService>(x => - new( + new TieredStorageService( cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), dataStorageProvider: new FileStorageProvider("bot_data/data/") ) 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; |