diff options
Diffstat (limited to '')
50 files changed, 198 insertions, 245 deletions
diff --git a/.editorconfig b/.editorconfig index e98e832..1a3cf7e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -373,7 +373,8 @@ dotnet_style_qualification_for_field = false:suggestion dotnet_style_qualification_for_method = false:suggestion dotnet_style_qualification_for_property = false:suggestion dotnet_style_require_accessibility_modifiers = for_non_interface_members:error -file_header_template = # ReSharper properties +file_header_template = # ReSharper properties + resharper_alignment_tab_fill_style = use_spaces resharper_align_first_arg_by_paren = false @@ -608,8 +609,8 @@ resharper_line_break_before_requires_clause = do_not_change resharper_linkage_specification_braces = end_of_line resharper_linkage_specification_indentation = none resharper_local_function_body = expression_body -resharper_macro_block_begin = -resharper_macro_block_end = +resharper_macro_block_begin = +resharper_macro_block_end = resharper_max_array_initializer_elements_on_line = 10000 resharper_max_attribute_length_for_same_line = 38 resharper_max_enum_members_on_line = 3 @@ -624,7 +625,7 @@ resharper_new_line_before_catch = true resharper_new_line_before_else = true resharper_new_line_before_enumerators = true resharper_normalize_tag_names = false -resharper_no_indent_inside_elements = +resharper_no_indent_inside_elements = resharper_no_indent_inside_if_element_longer_than = 2000000 resharper_null_checking_pattern_style = not_null_pattern resharper_object_creation_when_type_evident = target_typed @@ -677,7 +678,7 @@ resharper_requires_expression_braces = next_line resharper_resx_allow_far_alignment = false resharper_resx_attribute_indent = single_indent resharper_resx_insert_final_newline = false -resharper_resx_linebreak_before_elements = +resharper_resx_linebreak_before_elements = resharper_resx_max_blank_lines_between_tags = 0 resharper_resx_max_line_length = 2147483647 resharper_resx_pi_attribute_style = do_not_touch @@ -904,7 +905,7 @@ resharper_xmldoc_wrap_text = true resharper_xml_allow_far_alignment = false resharper_xml_attribute_indent = align_by_first_attribute resharper_xml_insert_final_newline = false -resharper_xml_linebreak_before_elements = +resharper_xml_linebreak_before_elements = resharper_xml_max_blank_lines_between_tags = 2 resharper_xml_max_line_length = 180 resharper_xml_pi_attribute_style = do_not_touch diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs index 6f21e9f..02f3e3a 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs @@ -246,7 +246,7 @@ public class AuthenticatedHomeserverGeneric(string serverName, string accessToke var differenceFound = false; if (syncCount++ >= targetSyncCount) { var profiles = GetRoomProfilesAsync(); - await foreach ((var roomId, var profile) in profiles) { + await foreach (var (roomId, profile) in profiles) { if (!expectedRoomProfiles.ContainsKey(roomId)) { Console.WriteLine($"Skipping profile check for {roomId} because its not in override list?"); continue; diff --git a/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs b/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs index 8a976a7..c9727d6 100644 --- a/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs +++ b/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs @@ -9,8 +9,8 @@ public static class HomeserverAbstraction { var rhs = await RemoteHomeserver.Create("https://matrixunittests.rory.gay"); // string username = Guid.NewGuid().ToString(); // string password = Guid.NewGuid().ToString(); - string username = "@f1a2d2d6-1924-421b-91d0-893b347b2a49:matrixunittests.rory.gay"; - string password = "d6d782d6-8bc9-4fac-9cd8-78e101b4298b"; + var username = "@f1a2d2d6-1924-421b-91d0-893b347b2a49:matrixunittests.rory.gay"; + var password = "d6d782d6-8bc9-4fac-9cd8-78e101b4298b"; LoginResponse reg; try { reg = await rhs.LoginAsync(username, password); @@ -46,7 +46,7 @@ public static class HomeserverAbstraction { public static async Task<AuthenticatedHomeserverGeneric> GetRandomHomeserver() { var rhs = await RemoteHomeserver.Create("https://matrixunittests.rory.gay"); - LoginResponse reg = await rhs.RegisterAsync(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Unit tests!"); + var reg = await rhs.RegisterAsync(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Unit tests!"); var hs = await reg.GetAuthenticatedHomeserver("https://matrixunittests.rory.gay"); // var rooms = await hs.GetJoinedRooms(); @@ -66,8 +66,6 @@ public static class HomeserverAbstraction { var createRandomUserTasks = Enumerable .Range(0, count) .Select(_ => GetRandomHomeserver()).ToAsyncEnumerable(); - await foreach (var hs in createRandomUserTasks) { - yield return hs; - } + await foreach (var hs in createRandomUserTasks) yield return hs; } -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs b/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs index 0cbcf75..2a380fc 100644 --- a/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs +++ b/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs @@ -14,7 +14,7 @@ public static class RoomAbstraction { // Visibility = CreateRoomVisibility.Public, RoomAliasName = Guid.NewGuid().ToString() }; - crq.InitialState ??= new(); + crq.InitialState ??= new List<StateEvent>(); crq.InitialState.Add(new StateEvent() { Type = "m.room.topic", StateKey = "", @@ -47,7 +47,7 @@ public static class RoomAbstraction { }); var testRoom = await hs.CreateRoom(crq); - await testRoom.SendStateEventAsync("gay.rory.libmatrix.unit_test_room", new()); + await testRoom.SendStateEventAsync("gay.rory.libmatrix.unit_test_room", new object()); return testRoom; } @@ -55,16 +55,15 @@ public static class RoomAbstraction { private static SemaphoreSlim _spaceSemaphore = null!; public static async Task<SpaceRoom> GetTestSpace(AuthenticatedHomeserverGeneric hs, int roomCount = 100, bool addSpaces = false, int spaceSizeReduction = 10) { - _spaceSemaphore ??= new(roomCount / spaceSizeReduction, roomCount / spaceSizeReduction); + _spaceSemaphore ??= new SemaphoreSlim(roomCount / spaceSizeReduction, roomCount / spaceSizeReduction); var crq = new CreateRoomRequest() { Name = $"LibMatrix Test Space ({roomCount} children)", // Visibility = CreateRoomVisibility.Public, RoomAliasName = Guid.NewGuid().ToString(), - InitialState = new() + InitialState = new List<StateEvent>() }; crq.CreationContentBaseType.Type = "m.space"; - var createRoomTasks = Enumerable.Range(0, roomCount) .Select(_ => hs.CreateRoom(new CreateRoomRequest() { Name = $"LibMatrix Test Room {Guid.NewGuid()}", @@ -72,38 +71,36 @@ public static class RoomAbstraction { RoomAliasName = Guid.NewGuid().ToString() })).ToAsyncEnumerable(); - await foreach (var room in createRoomTasks) { - crq.InitialState.Add(new() { + await foreach (var room in createRoomTasks) + crq.InitialState.Add(new StateEvent { Type = "m.space.child", StateKey = room.RoomId, TypedContent = new SpaceChildEventContent() { - Via = new() { + Via = new List<string> { room.RoomId.Split(":")[1] } } }); - } - if (addSpaces) { - for (int i = 0; i < roomCount; i++) { + if (addSpaces) + for (var i = 0; i < roomCount; i++) { var space = await GetTestSpace(hs, roomCount - spaceSizeReduction, true, spaceSizeReduction); - crq.InitialState.Add(new() { + crq.InitialState.Add(new StateEvent { Type = "m.space.child", StateKey = space.RoomId, TypedContent = new SpaceChildEventContent() { - Via = new() { + Via = new List<string> { space.RoomId.Split(":")[1] } } }); } - } var testSpace = (await hs.CreateRoom(crq)).AsSpace; - await testSpace.SendStateEventAsync("gay.rory.libmatrix.unit_test_room", new()); + await testSpace.SendStateEventAsync("gay.rory.libmatrix.unit_test_room", new object()); // _spaceSemaphore.Release(); return testSpace; } -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Config.cs b/Tests/LibMatrix.Tests/Config.cs index fb4ef02..ddbf705 100644 --- a/Tests/LibMatrix.Tests/Config.cs +++ b/Tests/LibMatrix.Tests/Config.cs @@ -8,10 +8,11 @@ public class Config { public string? TestRoomAlias { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_ROOM_ALIAS") ?? null; public Dictionary<string, string> ExpectedHomeserverMappings { get; set; } = new() { - {"matrix.org", "https://matrix-client.matrix.org"}, - {"rory.gay", "https://matrix.rory.gay"} + { "matrix.org", "https://matrix-client.matrix.org" }, + { "rory.gay", "https://matrix.rory.gay" } }; + public Dictionary<string, string> ExpectedAliasMappings { get; set; } = new() { - {"#libmatrix:rory.gay", "!tuiLEoMqNOQezxILzt:rory.gay"} + { "#libmatrix:rory.gay", "!tuiLEoMqNOQezxILzt:rory.gay" } }; -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs b/Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs index 056cd3c..e1da3d5 100644 --- a/Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs +++ b/Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs @@ -7,4 +7,4 @@ public static class WhoAmITests { if (!isAppservice) Assert.NotNull(obj.DeviceId); } -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs b/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs index ef49b3e..35c8704 100644 --- a/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs +++ b/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs @@ -11,8 +11,8 @@ public class TestFixture : TestBedFixture { protected override void AddServices(IServiceCollection services, IConfiguration? configuration) { services.AddSingleton<TieredStorageService>(x => new TieredStorageService( - cacheStorageProvider: null, - dataStorageProvider: null + null, + null ) ); @@ -34,4 +34,4 @@ public class TestFixture : TestBedFixture { protected override IEnumerable<TestAppSettings> GetTestAppSettings() { yield return new TestAppSettings { Filename = "appsettings.json", IsOptional = true }; } -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/GlobalUsings.cs b/Tests/LibMatrix.Tests/GlobalUsings.cs index c802f44..8c927eb 100644 --- a/Tests/LibMatrix.Tests/GlobalUsings.cs +++ b/Tests/LibMatrix.Tests/GlobalUsings.cs @@ -1 +1 @@ -global using Xunit; +global using Xunit; \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj index 3f7bc87..d833d8b 100644 --- a/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj +++ b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj @@ -10,11 +10,11 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /> - - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0-preview-23531-01" /> - <PackageReference Include="xunit" Version="2.6.1" /> - <PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="7.0.10" /> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/> + + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0-preview-23531-01"/> + <PackageReference Include="xunit" Version="2.6.1"/> + <PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="7.0.10"/> <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> @@ -23,11 +23,11 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="Xunit.SkippableFact" Version="1.4.13" /> + <PackageReference Include="Xunit.SkippableFact" Version="1.4.13"/> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/> </ItemGroup> <ItemGroup> @@ -35,5 +35,5 @@ <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> - + </Project> diff --git a/Tests/LibMatrix.Tests/Tests/AuthTests.cs b/Tests/LibMatrix.Tests/Tests/AuthTests.cs index 5476b84..67ba8eb 100644 --- a/Tests/LibMatrix.Tests/Tests/AuthTests.cs +++ b/Tests/LibMatrix.Tests/Tests/AuthTests.cs @@ -68,4 +68,4 @@ public class AuthTests : TestBed<TestFixture> { Assert.NotNull(hs.AccessToken); await hs.Logout(); } -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/ResolverTest.cs b/Tests/LibMatrix.Tests/Tests/ResolverTest.cs index 804ad6c..700aa96 100644 --- a/Tests/LibMatrix.Tests/Tests/ResolverTest.cs +++ b/Tests/LibMatrix.Tests/Tests/ResolverTest.cs @@ -10,6 +10,7 @@ public class ResolverTest : TestBed<TestFixture> { private readonly HomeserverResolverService _resolver; private readonly Config _config; private readonly HomeserverProviderService _provider; + public ResolverTest(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { _fixture = fixture; _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); @@ -51,4 +52,4 @@ public class ResolverTest : TestBed<TestFixture> { var profile = await hs.GetProfileAsync("@alice-is-:matrix.org"); Assert.NotNull(profile); } -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomEventTests.cs b/Tests/LibMatrix.Tests/Tests/RoomEventTests.cs index 060e6f2..932909f 100644 --- a/Tests/LibMatrix.Tests/Tests/RoomEventTests.cs +++ b/Tests/LibMatrix.Tests/Tests/RoomEventTests.cs @@ -20,9 +20,7 @@ public class RoomEventTests : TestBed<TestFixture> { _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); } - private async Task<AuthenticatedHomeserverGeneric> GetHomeserver() { - return await HomeserverAbstraction.GetHomeserver(); - } + private async Task<AuthenticatedHomeserverGeneric> GetHomeserver() => await HomeserverAbstraction.GetHomeserver(); [Fact] public async Task GetNameAsync() { @@ -153,5 +151,4 @@ public class RoomEventTests : TestBed<TestFixture> { Assert.NotNull(power.Users); // Assert.NotNull(power.Events); } - -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests.cs index bec8d18..4f7ac17 100644 --- a/Tests/LibMatrix.Tests/Tests/RoomTests.cs +++ b/Tests/LibMatrix.Tests/Tests/RoomTests.cs @@ -23,9 +23,7 @@ public class RoomTests : TestBed<TestFixture> { _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); } - private async Task<AuthenticatedHomeserverGeneric> GetHomeserver() { - return await HomeserverAbstraction.GetHomeserver(); - } + private async Task<AuthenticatedHomeserverGeneric> GetHomeserver() => await HomeserverAbstraction.GetHomeserver(); [Fact] public async Task GetJoinedRoomsAsync() { @@ -43,7 +41,6 @@ public class RoomTests : TestBed<TestFixture> { await hs.Logout(); } - [Fact] public async Task GetMembersAsync() { Assert.True(StateEvent.KnownStateEventTypes is { Count: > 0 }, "StateEvent.KnownStateEventTypes is empty!"); @@ -54,7 +51,7 @@ public class RoomTests : TestBed<TestFixture> { Assert.NotNull(room); var members = room.GetMembersEnumerableAsync(); Assert.NotNull(members); - bool hitMembers = false; + var hitMembers = false; await foreach (var member in members) { Assert.NotNull(member); Assert.NotNull(member.StateKey); @@ -211,7 +208,7 @@ public class RoomTests : TestBed<TestFixture> { Assert.NotNull(room); var res = await room.SendFileAsync("test.txt", new MemoryStream(Encoding.UTF8.GetBytes("This test was written by Emma [it/its], member of the Rory& system." + - "\nIf you are reading this on matrix, it means the unit test for uploading a file works!"))); + "\nIf you are reading this on matrix, it means the unit test for uploading a file works!"))); Assert.NotNull(res); Assert.NotNull(res.EventId); } @@ -223,10 +220,8 @@ public class RoomTests : TestBed<TestFixture> { Assert.NotNull(space); var children = space.GetChildrenAsync(); Assert.NotNull(children); - int found = 0; - await foreach (var room in children) { - found++; - } + var found = 0; + await foreach (var room in children) found++; Assert.Equal(2, found); } @@ -240,15 +235,14 @@ public class RoomTests : TestBed<TestFixture> { // var expectedCount = 1; var tasks = new List<Task>(); - await foreach (var otherUser in otherUsers) { + await foreach (var otherUser in otherUsers) tasks.Add(Task.Run(async () => { await room.InviteUserAsync(otherUser.UserId); await otherUser.GetRoom(room.RoomId).JoinAsync(); })); - } await Task.WhenAll(tasks); var states = await room.GetMembersListAsync(false); Assert.Equal(16, states.Count); } -} +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/TestCleanup.cs b/Tests/LibMatrix.Tests/Tests/TestCleanup.cs index d056345..7fc7c64 100644 --- a/Tests/LibMatrix.Tests/Tests/TestCleanup.cs +++ b/Tests/LibMatrix.Tests/Tests/TestCleanup.cs @@ -71,4 +71,4 @@ public class TestCleanup : TestBed<TestFixture> { Assert.NotNull(hs); await hs.Logout(); } -} +} \ No newline at end of file diff --git a/Tests/TestDataGenerator/Bot/DataFetcher.cs b/Tests/TestDataGenerator/Bot/DataFetcher.cs index 5e8c1a1..66b8a03 100644 --- a/Tests/TestDataGenerator/Bot/DataFetcher.cs +++ b/Tests/TestDataGenerator/Bot/DataFetcher.cs @@ -36,19 +36,18 @@ public class DataFetcher(AuthenticatedHomeserverGeneric hs, ILogger<DataFetcher> var roomAliasTasks = rooms.Select(room => room.GetCanonicalAliasAsync()).ToAsyncEnumerable(); List<Task<(string, string)>> aliasResolutionTasks = new(); - await foreach (var @event in roomAliasTasks) { + await foreach (var @event in roomAliasTasks) if (@event?.Alias != null) { - await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Fetched room alias {(@event).Alias}!")); + await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Fetched room alias {@event.Alias}!")); aliasResolutionTasks.Add(Task.Run(async () => { var alias = await hs.ResolveRoomAliasAsync(@event.Alias); return (@event.Alias, alias.RoomId); }, cancellationToken)); } - } + var aliasResolutionTaskEnumerator = aliasResolutionTasks.ToAsyncEnumerable(); - await foreach (var result in aliasResolutionTaskEnumerator) { + await foreach (var result in aliasResolutionTaskEnumerator) await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Resolved room alias {result.Item1} to {result.Item2}!")); - } } /// <summary>Triggered when the application host is performing a graceful shutdown.</summary> @@ -57,4 +56,4 @@ public class DataFetcher(AuthenticatedHomeserverGeneric hs, ILogger<DataFetcher> logger.LogInformation("Shutting down bot!"); _listenerTask?.Dispose(); } -} +} \ No newline at end of file diff --git a/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs b/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs index a586d05..4f53a2a 100644 --- a/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs +++ b/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs @@ -6,4 +6,4 @@ public class DataFetcherConfiguration { public DataFetcherConfiguration(IConfiguration config) => config.GetRequiredSection("DataFetcher").Bind(this); // public string -} +} \ No newline at end of file diff --git a/Tests/TestDataGenerator/Program.cs b/Tests/TestDataGenerator/Program.cs index 5d36215..5c20958 100644 --- a/Tests/TestDataGenerator/Program.cs +++ b/Tests/TestDataGenerator/Program.cs @@ -11,17 +11,17 @@ Console.WriteLine("Hello, World!"); var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { services.AddScoped<TieredStorageService>(_ => new TieredStorageService( - cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), - dataStorageProvider: new FileStorageProvider("bot_data/data/") + new FileStorageProvider("bot_data/cache/"), + new FileStorageProvider("bot_data/data/") ) ); // services.AddSingleton<DataFetcherConfiguration>(); services.AddSingleton<AppServiceConfiguration>(); services.AddRoryLibMatrixServices(); - services.AddBot(withCommands: false); + services.AddBot(false); services.AddHostedService<DataFetcher>(); }).UseConsoleLifetime().Build(); -await host.RunAsync(); +await host.RunAsync(); \ No newline at end of file diff --git a/Tests/TestDataGenerator/Properties/launchSettings.json b/Tests/TestDataGenerator/Properties/launchSettings.json index 997e294..6c504ff 100644 --- a/Tests/TestDataGenerator/Properties/launchSettings.json +++ b/Tests/TestDataGenerator/Properties/launchSettings.json @@ -5,7 +5,6 @@ "commandName": "Project", "dotnetRunMessages": true, "environmentVariables": { - } }, "Development": { diff --git a/Tests/TestDataGenerator/TestDataGenerator.csproj b/Tests/TestDataGenerator/TestDataGenerator.csproj index cf212de..879693e 100644 --- a/Tests/TestDataGenerator/TestDataGenerator.csproj +++ b/Tests/TestDataGenerator/TestDataGenerator.csproj @@ -17,7 +17,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/> </ItemGroup> <ItemGroup> <Content Include="appsettings*.json"> @@ -25,8 +25,8 @@ </Content> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> - <ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj" /> - <ProjectReference Include="..\LibMatrix.Tests\LibMatrix.Tests.csproj" /> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/> + <ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj"/> + <ProjectReference Include="..\LibMatrix.Tests\LibMatrix.Tests.csproj"/> </ItemGroup> </Project> diff --git a/Tests/TestDataGenerator/appsettings.json b/Tests/TestDataGenerator/appsettings.json index 6ba02f3..e203e94 100644 --- a/Tests/TestDataGenerator/appsettings.json +++ b/Tests/TestDataGenerator/appsettings.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" } + } } diff --git a/Utilities/LibMatrix.DebugDataValidationApi/Controllers/ValidationController.cs b/Utilities/LibMatrix.DebugDataValidationApi/Controllers/ValidationController.cs index 1b93614..3420e56 100644 --- a/Utilities/LibMatrix.DebugDataValidationApi/Controllers/ValidationController.cs +++ b/Utilities/LibMatrix.DebugDataValidationApi/Controllers/ValidationController.cs @@ -7,7 +7,6 @@ namespace LibMatrix.DebugDataValidationApi.Controllers; [ApiController] [Route("/")] public class ValidationController(ILogger<ValidationController> logger) : ControllerBase { - [HttpPost("/validate/{type}")] public Task<bool> Get([FromRoute] string type, [FromBody] JsonElement content) { var t = Type.GetType(type); @@ -15,7 +14,8 @@ public class ValidationController(ILogger<ValidationController> logger) : Contro logger.LogWarning($"Type `{type}` does not exist!"); throw new ArgumentException($"Unknown type {type}!"); } + logger.LogInformation($"Validating {type}..."); return Task.FromResult(content.FindExtraJsonElementFields(t, "$")); } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DebugDataValidationApi/LibMatrix.DebugDataValidationApi.csproj b/Utilities/LibMatrix.DebugDataValidationApi/LibMatrix.DebugDataValidationApi.csproj index e14b7a1..24fd617 100644 --- a/Utilities/LibMatrix.DebugDataValidationApi/LibMatrix.DebugDataValidationApi.csproj +++ b/Utilities/LibMatrix.DebugDataValidationApi/LibMatrix.DebugDataValidationApi.csproj @@ -9,12 +9,12 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" /> - <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> + <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0"/> + <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/> </ItemGroup> </Project> diff --git a/Utilities/LibMatrix.DebugDataValidationApi/Program.cs b/Utilities/LibMatrix.DebugDataValidationApi/Program.cs index 2c324d8..1d913b4 100644 --- a/Utilities/LibMatrix.DebugDataValidationApi/Program.cs +++ b/Utilities/LibMatrix.DebugDataValidationApi/Program.cs @@ -28,4 +28,4 @@ app.UseAuthorization(); app.MapControllers(); -app.Run(); +app.Run(); \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs index e690890..89a9033 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs @@ -8,9 +8,7 @@ public class CmdCommand : ICommand { public string Name => "cmd"; public string Description => "Runs a command on the host system"; - public Task<bool> CanInvoke(CommandContext ctx) { - return Task.FromResult(ctx.MessageEvent.Sender.EndsWith(":rory.gay") || ctx.MessageEvent.Sender.EndsWith(":conduit.rory.gay")); - } + public Task<bool> CanInvoke(CommandContext ctx) => Task.FromResult(ctx.MessageEvent.Sender.EndsWith(":rory.gay") || ctx.MessageEvent.Sender.EndsWith(":conduit.rory.gay")); public async Task Invoke(CommandContext ctx) { var cmd = ctx.Args.Aggregate("\"", (current, arg) => current + arg + " "); @@ -27,7 +25,7 @@ public class CmdCommand : ICommand { // .Split("\n").ToList(); var msg = ""; - EventIdResponse? msgId = await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent { + var msgId = await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent { FormattedBody = $"Waiting for command output...", Body = msg.RemoveAnsi(), Format = "m.notice" @@ -69,4 +67,4 @@ public class CmdCommand : ICommand { // } // } } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs index c526847..f75c863 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs @@ -11,26 +11,22 @@ public class DbgAniRainbowTest(IServiceProvider services, HomeserverProviderServ public string Name { get; } = "ani-rainbow"; public string Description { get; } = "[Debug] animated rainbow :)"; - public async Task<bool> CanInvoke(CommandContext ctx) { - return ctx.Room.RoomId == "!hLEefBaYvNfJwcTjmt:rory.gay"; - } + public async Task<bool> CanInvoke(CommandContext ctx) => ctx.Room.RoomId == "!hLEefBaYvNfJwcTjmt:rory.gay"; public async Task Invoke(CommandContext ctx) { //255 long string // var rainbow = "🟥🟧🟨🟩🟦🟪"; var rainbow = "M"; var chars = rainbow; - for (var i = 0; i < 76; i++) { - chars += rainbow[i % rainbow.Length]; - } + for (var i = 0; i < 76; i++) chars += rainbow[i % rainbow.Length]; Task.Run(async () => { - int i = 0; - var msg = new MessageBuilder(msgType: "m.notice").WithRainbowString(chars).Build(); + var i = 0; + var msg = new MessageBuilder("m.notice").WithRainbowString(chars).Build(); var msgEvent = await ctx.Room.SendMessageEventAsync(msg); while (true) { - msg = new MessageBuilder(msgType: "m.notice").WithRainbowString(chars, offset: i * 5).Build(); + msg = new MessageBuilder("m.notice").WithRainbowString(chars, offset: i * 5).Build(); if (i % 50 == 0) { msg.NewContent = null; msg.RelatesTo = null; diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs index 23c4fe2..7ecbeb3 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs @@ -13,10 +13,8 @@ public class HelpCommand(IServiceProvider services) : ICommand { var sb = new StringBuilder(); sb.AppendLine("Available commands:"); var commands = services.GetServices<ICommand>().ToList(); - foreach (var command in commands) { - sb.AppendLine($"- {command.Name}: {command.Description}"); - } + foreach (var command in commands) sb.AppendLine($"- {command.Name}: {command.Description}"); await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: sb.ToString())); } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs index ba242fe..85c86a3 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs @@ -7,7 +7,5 @@ public class PingCommand : ICommand { public string Name { get; } = "ping"; public string Description { get; } = "Pong!"; - public async Task Invoke(CommandContext ctx) { - await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!")); - } -} + public async Task Invoke(CommandContext ctx) => await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!")); +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs b/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs index 678df27..fa80bfd 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs @@ -20,7 +20,7 @@ public class DevTestBot : IHostedService { public DevTestBot(HomeserverProviderService homeserverProviderService, ILogger<DevTestBot> logger, DevTestBotConfiguration configuration, IServiceProvider services) { - logger.LogInformation("{} instantiated!", this.GetType().Name); + logger.LogInformation("{} instantiated!", GetType().Name); _homeserverProviderService = homeserverProviderService; _logger = logger; _configuration = configuration; @@ -49,7 +49,7 @@ public class DevTestBot : IHostedService { var syncHelper = new SyncHelper(hs); - await (hs.GetRoom("!DoHEdFablOLjddKWIp:rory.gay")).JoinAsync(); + await hs.GetRoom("!DoHEdFablOLjddKWIp:rory.gay").JoinAsync(); // foreach (var room in await hs.GetJoinedRooms()) { // if(room.RoomId is "!OGEhHVWSdvArJzumhm:matrix.org") continue; @@ -65,29 +65,28 @@ public class DevTestBot : IHostedService { x.Type == "m.room.member" && x.StateKey == hs.UserId); _logger.LogInformation( $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventContent).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.GetProfileAsync(inviteEvent.Sender); - await (hs.GetRoom(args.Key)).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!"); + await hs.GetRoom(args.Key).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!"); } catch (Exception e) { _logger.LogError("{}", e.ToString()); - await (hs.GetRoom(args.Key)).LeaveAsync(reason: "I was unable to join the room: " + e); + await hs.GetRoom(args.Key).LeaveAsync("I was unable to join the room: " + e); } - } }); 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(false, true)); var room = hs.GetRoom(@event.RoomId); // _logger.LogInformation(eventResponse.ToJson(indent: false)); - if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) { + if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent 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( - new RoomMessageEventContent(messageType: "m.text", body: "Command not found!")); + new RoomMessageEventContent("m.text", "Command not found!")); return; } @@ -95,15 +94,12 @@ public class DevTestBot : IHostedService { Room = room, MessageEvent = @event }; - if (await command.CanInvoke(ctx)) { + if (await command.CanInvoke(ctx)) await command.Invoke(ctx); - } - else { + else await room.SendMessageEventAsync( - new RoomMessageEventContent(messageType: "m.text", body: "You do not have permission to run this command!")); - } + new RoomMessageEventContent("m.text", "You do not have permission to run this command!")); } - } }); await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken); } @@ -114,4 +110,4 @@ public class DevTestBot : IHostedService { _logger.LogInformation("Shutting down bot!"); return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/DevTestBotConfiguration.cs b/Utilities/LibMatrix.DevTestBot/Bot/DevTestBotConfiguration.cs index ef203cd..dcbc670 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/DevTestBotConfiguration.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/DevTestBotConfiguration.cs @@ -3,10 +3,8 @@ using Microsoft.Extensions.Configuration; namespace LibMatrix.ExampleBot.Bot; public class DevTestBotConfiguration { - public DevTestBotConfiguration(IConfiguration config) { - config.GetRequiredSection("Bot").Bind(this); - } + public DevTestBotConfiguration(IConfiguration config) => config.GetRequiredSection("Bot").Bind(this); public string Homeserver { get; set; } = ""; public string AccessToken { get; set; } = ""; public string Prefix { get; set; } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/FileStorageProvider.cs b/Utilities/LibMatrix.DevTestBot/Bot/FileStorageProvider.cs index 2c014de..cc866e6 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/FileStorageProvider.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/FileStorageProvider.cs @@ -18,9 +18,7 @@ public class FileStorageProvider : IStorageProvider { new Logger<FileStorageProvider>(new LoggerFactory()).LogInformation("test"); Console.WriteLine($"Initialised FileStorageProvider with path {targetPath}"); TargetPath = targetPath; - if (!Directory.Exists(targetPath)) { - Directory.CreateDirectory(targetPath); - } + if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath); } public async Task SaveObjectAsync<T>(string key, T value) => await File.WriteAllTextAsync(Path.Join(TargetPath, key), value?.ToJson()); @@ -35,4 +33,4 @@ public class FileStorageProvider : IStorageProvider { File.Delete(Path.Join(TargetPath, key)); return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs b/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs index 6dbb7f9..90a95e4 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs @@ -8,4 +8,4 @@ public class CommandContext { public StateEventResponse MessageEvent { get; set; } public string CommandName => (MessageEvent.TypedContent as RoomMessageEventContent).Body.Split(' ')[0][1..]; public string[] Args => (MessageEvent.TypedContent as RoomMessageEventContent).Body.Split(' ')[1..]; -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs index 2ba5a27..a6dc8da 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs @@ -4,9 +4,7 @@ public interface ICommand { public string Name { get; } public string Description { get; } - public Task<bool> CanInvoke(CommandContext ctx) { - return Task.FromResult(true); - } + public Task<bool> CanInvoke(CommandContext ctx) => Task.FromResult(true); public Task Invoke(CommandContext ctx); -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs b/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs index 0c04d27..253eb37 100644 --- a/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs +++ b/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs @@ -36,23 +36,19 @@ public class ServerRoomSizeCalulator : IHostedService { throw; } - await (hs.GetRoom("!DoHEdFablOLjddKWIp:rory.gay")).JoinAsync(); + await hs.GetRoom("!DoHEdFablOLjddKWIp:rory.gay").JoinAsync(); Dictionary<string, int> totalRoomSize = new(); foreach (var room in await hs.GetJoinedRooms()) { var stateList = room.GetFullStateAsync().ToBlockingEnumerable().ToList(); var roomSize = stateList.Count; - if (roomSize > 10000) { - await File.AppendAllLinesAsync("large_rooms.txt", new[] { $"{{ \"{room.RoomId}\", {roomSize} }}," }, cancellationToken); - } + if (roomSize > 10000) await File.AppendAllLinesAsync("large_rooms.txt", new[] { $"{{ \"{room.RoomId}\", {roomSize} }}," }, cancellationToken); var roomHs = room.RoomId.Split(":")[1]; - if (totalRoomSize.ContainsKey(roomHs)) { + if (totalRoomSize.ContainsKey(roomHs)) totalRoomSize[roomHs] += roomSize; - } - else { + else totalRoomSize.Add(roomHs, roomSize); - } _logger.LogInformation($"Got room state for {room.RoomId}!"); } @@ -66,4 +62,4 @@ public class ServerRoomSizeCalulator : IHostedService { _logger.LogInformation("Shutting down bot!"); return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj b/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj index c0be661..6518c67 100644 --- a/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj +++ b/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj @@ -1,33 +1,33 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <OutputType>Exe</OutputType> - <TargetFramework>net8.0</TargetFramework> - <LangVersion>preview</LangVersion> - <ImplicitUsings>enable</ImplicitUsings> - <Nullable>enable</Nullable> - <PublishAot>false</PublishAot> - <InvariantGlobalization>true</InvariantGlobalization> - <RootNamespace>LibMatrix.ExampleBot</RootNamespace> -<!-- <PublishTrimmed>true</PublishTrimmed>--> -<!-- <PublishReadyToRun>true</PublishReadyToRun>--> -<!-- <PublishSingleFile>true</PublishSingleFile>--> -<!-- <PublishReadyToRunShowWarnings>true</PublishReadyToRunShowWarnings>--> -<!-- <PublishTrimmedShowLinkerSizeComparison>true</PublishTrimmedShowLinkerSizeComparison>--> -<!-- <PublishTrimmedShowLinkerSizeComparisonWarnings>true</PublishTrimmedShowLinkerSizeComparisonWarnings>--> - </PropertyGroup> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net8.0</TargetFramework> + <LangVersion>preview</LangVersion> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + <PublishAot>false</PublishAot> + <InvariantGlobalization>true</InvariantGlobalization> + <RootNamespace>LibMatrix.ExampleBot</RootNamespace> + <!-- <PublishTrimmed>true</PublishTrimmed>--> + <!-- <PublishReadyToRun>true</PublishReadyToRun>--> + <!-- <PublishSingleFile>true</PublishSingleFile>--> + <!-- <PublishReadyToRunShowWarnings>true</PublishReadyToRunShowWarnings>--> + <!-- <PublishTrimmedShowLinkerSizeComparison>true</PublishTrimmedShowLinkerSizeComparison>--> + <!-- <PublishTrimmedShowLinkerSizeComparisonWarnings>true</PublishTrimmedShowLinkerSizeComparisonWarnings>--> + </PropertyGroup> - <ItemGroup> - <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> - </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/> + </ItemGroup> - <ItemGroup> - <PackageReference Include="ArcaneLibs.StringNormalisation" Version="1.0.0-preview7205256004.28c0e5a" /> - <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /> - </ItemGroup> - <ItemGroup> - <Content Include="appsettings*.json"> - <CopyToOutputDirectory>Always</CopyToOutputDirectory> - </Content> - </ItemGroup> + <ItemGroup> + <PackageReference Include="ArcaneLibs.StringNormalisation" Version="1.0.0-preview7205256004.28c0e5a"/> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/> + </ItemGroup> + <ItemGroup> + <Content Include="appsettings*.json"> + <CopyToOutputDirectory>Always</CopyToOutputDirectory> + </Content> + </ItemGroup> </Project> diff --git a/Utilities/LibMatrix.DevTestBot/Program.cs b/Utilities/LibMatrix.DevTestBot/Program.cs index b53bbfb..eb5ad76 100644 --- a/Utilities/LibMatrix.DevTestBot/Program.cs +++ b/Utilities/LibMatrix.DevTestBot/Program.cs @@ -11,10 +11,10 @@ Console.WriteLine("Hello, World!"); var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { // services.AddScoped<TieredStorageService>(x => - // new TieredStorageService( - // cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), - // dataStorageProvider: new FileStorageProvider("bot_data/data/") - // ) + // new TieredStorageService( + // cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), + // dataStorageProvider: new FileStorageProvider("bot_data/data/") + // ) // ); services.AddScoped<DevTestBotConfiguration>(); services.AddRoryLibMatrixServices(); @@ -27,4 +27,4 @@ var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { services.AddHostedService<DevTestBot>(); }).UseConsoleLifetime().Build(); -await host.RunAsync(); +await host.RunAsync(); \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/Properties/launchSettings.json b/Utilities/LibMatrix.DevTestBot/Properties/launchSettings.json index 997e294..6c504ff 100644 --- a/Utilities/LibMatrix.DevTestBot/Properties/launchSettings.json +++ b/Utilities/LibMatrix.DevTestBot/Properties/launchSettings.json @@ -5,7 +5,6 @@ "commandName": "Project", "dotnetRunMessages": true, "environmentVariables": { - } }, "Development": { diff --git a/Utilities/LibMatrix.DevTestBot/appsettings.Development.json b/Utilities/LibMatrix.DevTestBot/appsettings.Development.json index 27bbd50..f999bc2 100644 --- a/Utilities/LibMatrix.DevTestBot/appsettings.Development.json +++ b/Utilities/LibMatrix.DevTestBot/appsettings.Development.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" } + } } \ No newline at end of file diff --git a/Utilities/LibMatrix.DevTestBot/appsettings.json b/Utilities/LibMatrix.DevTestBot/appsettings.json index 6613979..db64c22 100644 --- a/Utilities/LibMatrix.DevTestBot/appsettings.json +++ b/Utilities/LibMatrix.DevTestBot/appsettings.json @@ -1,14 +1,14 @@ { - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - }, - "Bot": { - "Homeserver": "rory.gay", - "AccessToken": "syt_xxxxxxxxxxxxxxxxx", - "Prefix": "!" + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" } + }, + "Bot": { + "Homeserver": "rory.gay", + "AccessToken": "syt_xxxxxxxxxxxxxxxxx", + "Prefix": "!" + } } \ No newline at end of file diff --git a/Utilities/LibMatrix.JsonSerializerContextGenerator/LibMatrix.JsonSerializerContextGenerator.csproj b/Utilities/LibMatrix.JsonSerializerContextGenerator/LibMatrix.JsonSerializerContextGenerator.csproj index b90bf20..35cb9f8 100644 --- a/Utilities/LibMatrix.JsonSerializerContextGenerator/LibMatrix.JsonSerializerContextGenerator.csproj +++ b/Utilities/LibMatrix.JsonSerializerContextGenerator/LibMatrix.JsonSerializerContextGenerator.csproj @@ -8,8 +8,8 @@ </PropertyGroup> <ItemGroup> - <ProjectReference Include="..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj" /> - <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> + <ProjectReference Include="..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj"/> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/> </ItemGroup> </Project> diff --git a/Utilities/LibMatrix.JsonSerializerContextGenerator/Program.cs b/Utilities/LibMatrix.JsonSerializerContextGenerator/Program.cs index 0c0277b..f33efeb 100644 --- a/Utilities/LibMatrix.JsonSerializerContextGenerator/Program.cs +++ b/Utilities/LibMatrix.JsonSerializerContextGenerator/Program.cs @@ -23,7 +23,7 @@ stream.WriteString("\n\nnamespace LibMatrix.Generated;\n\n[JsonSourceGenerationO // // """))); -stream.WriteString(string.Join('\n', eventContentTypes//.DistinctBy(x => x.Namespace) +stream.WriteString(string.Join('\n', eventContentTypes //.DistinctBy(x => x.Namespace) .Select(x => $"[JsonSerializable(typeof({x.Name}))]"))); stream.WriteString("\ninternal partial class EventTypeSerializerContext : JsonSerializerContext { }"); diff --git a/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs index d8d1094..afda89e 100644 --- a/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs +++ b/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs @@ -84,4 +84,4 @@ public class AppServiceConfiguration { return yaml; } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs index 25a8d92..eb67424 100644 --- a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs +++ b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs @@ -34,6 +34,7 @@ public static class BotCommandInstaller { services.AddHostedService<CommandListenerHostedService>(); // services.AddSingleton<IHostedService, CommandListenerHostedService>(); } + return services; } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs b/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs index 4fe1038..9937b3c 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs @@ -13,10 +13,8 @@ public class HelpCommand(IServiceProvider services) : ICommand { var sb = new StringBuilder(); sb.AppendLine("Available commands:"); var commands = services.GetServices<ICommand>().ToList(); - foreach (var command in commands) { - sb.AppendLine($"- {command.Name}: {command.Description}"); - } + foreach (var command in commands) sb.AppendLine($"- {command.Name}: {command.Description}"); - await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(messageType: "m.notice", body: sb.ToString())); + await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent("m.notice", sb.ToString())); } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs b/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs index 16712ea..b5fb868 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs @@ -7,7 +7,5 @@ public class PingCommand : ICommand { public string Name { get; } = "ping"; public string Description { get; } = "Pong!"; - public async Task Invoke(CommandContext ctx) { - await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!")); - } -} + public async Task Invoke(CommandContext ctx) => await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!")); +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/FileStorageProvider.cs b/Utilities/LibMatrix.Utilities.Bot/FileStorageProvider.cs index b66fbf5..b762937 100644 --- a/Utilities/LibMatrix.Utilities.Bot/FileStorageProvider.cs +++ b/Utilities/LibMatrix.Utilities.Bot/FileStorageProvider.cs @@ -14,9 +14,7 @@ public class FileStorageProvider : IStorageProvider { public FileStorageProvider(string targetPath) { Console.WriteLine($"Initialised FileStorageProvider with path {targetPath}"); TargetPath = targetPath; - if (!Directory.Exists(targetPath)) { - Directory.CreateDirectory(targetPath); - } + if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath); } public async Task SaveObjectAsync<T>(string key, T value) => await File.WriteAllTextAsync(Path.Join(TargetPath, key), value?.ToJson()); @@ -31,4 +29,4 @@ public class FileStorageProvider : IStorageProvider { File.Delete(Path.Join(TargetPath, key)); return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs index 94ea846..e65f86d 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs @@ -19,4 +19,4 @@ public class CommandContext { public required AuthenticatedHomeserverGeneric Homeserver { get; set; } public async Task<EventIdResponse> Reply(RoomMessageEventContent content) => await Room.SendMessageEventAsync(content); -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/Interfaces/ICommand.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/ICommand.cs index 82439e8..453a8fe 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Interfaces/ICommand.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/ICommand.cs @@ -4,9 +4,7 @@ public interface ICommand { public string Name { get; } public string Description { get; } - public Task<bool> CanInvoke(CommandContext ctx) { - return Task.FromResult(true); - } + public Task<bool> CanInvoke(CommandContext ctx) => Task.FromResult(true); public Task Invoke(CommandContext ctx); -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/LibMatrix.Utilities.Bot.csproj b/Utilities/LibMatrix.Utilities.Bot/LibMatrix.Utilities.Bot.csproj index e16c00c..89ea5af 100644 --- a/Utilities/LibMatrix.Utilities.Bot/LibMatrix.Utilities.Bot.csproj +++ b/Utilities/LibMatrix.Utilities.Bot/LibMatrix.Utilities.Bot.csproj @@ -8,13 +8,13 @@ </PropertyGroup> <ItemGroup> - <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/> </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" /> - <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0"/> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/> + <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0"/> </ItemGroup> diff --git a/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs index 27ce06b..d607637 100644 --- a/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs +++ b/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs @@ -8,4 +8,4 @@ public class LibMatrixBotConfiguration { public string AccessToken { get; set; } = ""; public string Prefix { get; set; } = "?"; public string? LogRoom { get; set; } -} +} \ No newline at end of file diff --git a/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs b/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs index 9949631..11ee740 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs @@ -18,7 +18,7 @@ public class CommandListenerHostedService : IHostedService { public CommandListenerHostedService(AuthenticatedHomeserverGeneric hs, ILogger<CommandListenerHostedService> logger, IServiceProvider services, LibMatrixBotConfiguration config) { - logger.LogInformation("{} instantiated!", this.GetType().Name); + logger.LogInformation("{} instantiated!", GetType().Name); _hs = hs; _logger = logger; _config = config; @@ -44,7 +44,7 @@ public class CommandListenerHostedService : IHostedService { try { var room = _hs.GetRoom(@event.RoomId); // _logger.LogInformation(eventResponse.ToJson(indent: false)); - if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) { + if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) if (message is { MessageType: "m.text" }) { var messageContentWithoutReply = message.Body.Split('\n', StringSplitOptions.RemoveEmptyEntries).SkipWhile(x => x.StartsWith(">")).Aggregate((x, y) => $"{x}\n{y}"); @@ -52,7 +52,7 @@ public class CommandListenerHostedService : IHostedService { var command = _commands.FirstOrDefault(x => x.Name == messageContentWithoutReply.Split(' ')[0][_config.Prefix.Length..]); if (command == null) { await room.SendMessageEventAsync( - new RoomMessageEventContent(messageType: "m.notice", body: "Command not found!")); + new RoomMessageEventContent("m.notice", "Command not found!")); return; } @@ -62,7 +62,7 @@ public class CommandListenerHostedService : IHostedService { Homeserver = _hs }; - if (await command.CanInvoke(ctx)) { + if (await command.CanInvoke(ctx)) try { await command.Invoke(ctx); } @@ -70,14 +70,11 @@ public class CommandListenerHostedService : IHostedService { await room.SendMessageEventAsync( MessageFormatter.FormatException("An error occurred during the execution of this command", e)); } - } - else { + else await room.SendMessageEventAsync( - new RoomMessageEventContent(messageType: "m.notice", body: "You do not have permission to run this command!")); - } + new RoomMessageEventContent("m.notice", "You do not have permission to run this command!")); } } - } } catch (Exception e) { _logger.LogError(e, "Error in command listener!"); @@ -94,6 +91,7 @@ public class CommandListenerHostedService : IHostedService { _logger.LogError("Could not shut down command listener task because it was null!"); return; } + await _listenerTask.WaitAsync(cancellationToken); } -} +} \ No newline at end of file |