diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-12-01 12:34:30 +0100 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-12-01 12:34:30 +0100 |
commit | 0b662d36de30c4bdd3d9be97d08ace8d4d7be588 (patch) | |
tree | 475e4ea94cb5179236614bf5052d3164d1f2ff3b | |
parent | Add more code (diff) | |
download | MxApiExtensions-0b662d36de30c4bdd3d9be97d08ace8d4d7be588.tar.xz |
Reformat
21 files changed, 53 insertions, 57 deletions
diff --git a/MxApiExtensions.Classes.LibMatrix/RoomInfoEntry.cs b/MxApiExtensions.Classes.LibMatrix/RoomInfoEntry.cs index 1a84fd2..9f72bb6 100644 --- a/MxApiExtensions.Classes.LibMatrix/RoomInfoEntry.cs +++ b/MxApiExtensions.Classes.LibMatrix/RoomInfoEntry.cs @@ -1,4 +1,4 @@ -using LibMatrix; +using LibMatrix; using LibMatrix.Responses; namespace MxApiExtensions.Classes.LibMatrix; diff --git a/MxApiExtensions/Classes/CustomLogFormatter.cs b/MxApiExtensions/Classes/CustomLogFormatter.cs index 69812e5..c351c6a 100644 --- a/MxApiExtensions/Classes/CustomLogFormatter.cs +++ b/MxApiExtensions/Classes/CustomLogFormatter.cs @@ -1,7 +1,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Console; -namespace MxApiExtensions.Classes; +namespace MxApiExtensions.Classes; public class CustomLogFormatter : ConsoleFormatter { public CustomLogFormatter(string name) : base(name) { } @@ -9,4 +9,4 @@ public class CustomLogFormatter : ConsoleFormatter { public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) { Console.WriteLine("Log message"); } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Classes/MxApiExtensionsUserConfiguration.cs b/MxApiExtensions/Classes/MxApiExtensionsUserConfiguration.cs index db83637..895c5eb 100644 --- a/MxApiExtensions/Classes/MxApiExtensionsUserConfiguration.cs +++ b/MxApiExtensions/Classes/MxApiExtensionsUserConfiguration.cs @@ -1,7 +1,7 @@ using LibMatrix.EventTypes; using LibMatrix.Interfaces; -namespace MxApiExtensions.Classes; +namespace MxApiExtensions.Classes; [MatrixEvent(EventName = EventId)] public class MxApiExtensionsUserConfiguration : EventContent { @@ -18,4 +18,4 @@ public class MxApiExtensionsUserConfiguration : EventContent { public bool DisableVoip { get; set; } = false; public bool AutoFollowTombstones { get; set; } = false; } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Classes/SyncFilter.cs b/MxApiExtensions/Classes/SyncFilter.cs index 7f2bd08..a15cbcc 100644 --- a/MxApiExtensions/Classes/SyncFilter.cs +++ b/MxApiExtensions/Classes/SyncFilter.cs @@ -1,7 +1,7 @@ using LibMatrix.Responses; -namespace MxApiExtensions.Classes; +namespace MxApiExtensions.Classes; public interface ISyncFilter { public Task<SyncResponse> Apply(SyncResponse syncResponse); -} \ No newline at end of file +} diff --git a/MxApiExtensions/Classes/SyncState.cs b/MxApiExtensions/Classes/SyncState.cs index 733f26d..50aa0bd 100644 --- a/MxApiExtensions/Classes/SyncState.cs +++ b/MxApiExtensions/Classes/SyncState.cs @@ -28,7 +28,7 @@ public class SyncState { [JsonIgnore] public AuthenticatedHomeserverGeneric Homeserver { get; set; } -#region Debug stuff + #region Debug stuff public object NextSyncResponseTaskInfo => new { NextSyncResponse?.Id, @@ -39,10 +39,10 @@ public class SyncState { Status = NextSyncResponse?.Status.GetDisplayName() }; -#endregion + #endregion public SyncResponse SendEphemeralTimelineEventInRoom(string roomId, StateEventResponse @event, SyncResponse? existingResponse = null) { - if(existingResponse is null) + if (existingResponse is null) SyncQueue.Enqueue(existingResponse = new()); existingResponse.Rooms ??= new(); existingResponse.Rooms.Join ??= new(); @@ -54,7 +54,7 @@ public class SyncState { } public SyncResponse SendStatusMessage(string text, SyncResponse? existingResponse = null) { - if(existingResponse is null) + if (existingResponse is null) SyncQueue.Enqueue(existingResponse = new()); existingResponse.Presence ??= new(); // existingResponse.Presence.Events ??= new(); @@ -73,4 +73,4 @@ public class SyncState { }); return existingResponse; } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Controllers/Client/LoginController.cs b/MxApiExtensions/Controllers/Client/LoginController.cs index 009aaef..bf44af1 100644 --- a/MxApiExtensions/Controllers/Client/LoginController.cs +++ b/MxApiExtensions/Controllers/Client/LoginController.cs @@ -70,4 +70,4 @@ public class LoginController(ILogger<LoginController> logger, HomeserverProvider } }; } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Controllers/Client/Room/RoomController.cs b/MxApiExtensions/Controllers/Client/Room/RoomController.cs index a3e433d..7e7bfc1 100644 --- a/MxApiExtensions/Controllers/Client/Room/RoomController.cs +++ b/MxApiExtensions/Controllers/Client/Room/RoomController.cs @@ -48,4 +48,4 @@ public class RoomController(ILogger<LoginController> logger, HomeserverResolverS } } } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Controllers/Client/Room/RoomsSendMessageController.cs b/MxApiExtensions/Controllers/Client/Room/RoomsSendMessageController.cs index e882c8a..b800ec6 100644 --- a/MxApiExtensions/Controllers/Client/Room/RoomsSendMessageController.cs +++ b/MxApiExtensions/Controllers/Client/Room/RoomsSendMessageController.cs @@ -70,4 +70,4 @@ public class RoomsSendMessageController(ILogger<LoginController> logger, UserCon EventId = "$" + string.Join("", Random.Shared.GetItems("abcdefghijklmnopqrstuvwxyzABCDEFGHIJLKMNOPQRSTUVWXYZ0123456789".ToCharArray(), 100)) }); } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Controllers/Client/SyncController.cs b/MxApiExtensions/Controllers/Client/SyncController.cs index 615502b..3a759fc 100644 --- a/MxApiExtensions/Controllers/Client/SyncController.cs +++ b/MxApiExtensions/Controllers/Client/SyncController.cs @@ -291,4 +291,4 @@ public class SyncController(ILogger<SyncController> logger, MxApiExtensionsConfi syncState.SyncQueue.Enqueue(syncResponse); // _roomDataSemaphore.Release(); } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Controllers/Extensions/DebugController.cs b/MxApiExtensions/Controllers/Extensions/DebugController.cs index 0a54481..6f87e51 100644 --- a/MxApiExtensions/Controllers/Extensions/DebugController.cs +++ b/MxApiExtensions/Controllers/Extensions/DebugController.cs @@ -46,4 +46,4 @@ public class DebugController(ILogger<ProxyConfigurationController> logger, MxApi UserContextService.UserContextStore }; } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs b/MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs index 9383390..07420d7 100644 --- a/MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs +++ b/MxApiExtensions/Controllers/Extensions/JoinedRoomListController.cs @@ -56,11 +56,11 @@ public class JoinedRoomListController : ControllerBase { if (hs is not null) { Response.ContentType = "application/json"; - Response.Headers.Add("Cache-Control", "public, max-age=60"); - Response.Headers.Add("Expires", DateTime.Now.AddMinutes(1).ToString("R")); - Response.Headers.Add("Last-Modified", DateTime.Now.ToString("R")); - Response.Headers.Add("X-Matrix-Server", hs.ServerName); - Response.Headers.Add("X-Matrix-User", hs.UserId); + Response.Headers.Append("Cache-Control", "public, max-age=60"); + Response.Headers.Append("Expires", DateTime.Now.AddMinutes(1).ToString("R")); + Response.Headers.Append("Last-Modified", DateTime.Now.ToString("R")); + Response.Headers.Append("X-Matrix-Server", hs.ServerName); + Response.Headers.Append("X-Matrix-User", hs.UserId); // await Response.StartAsync(); var cachedRooms = _roomInfoCache @@ -99,8 +99,8 @@ public class JoinedRoomListController : ControllerBase { result.StateCount++; if (@event.Type != "m.room.member") result.RoomState.Add(@event); else { - if(!result.MemberCounts.ContainsKey((@event.TypedContent as RoomMemberEventContent)?.Membership)) result.MemberCounts.Add((@event.TypedContent as RoomMemberEventContent)?.Membership, 0); - result.MemberCounts[(@event.TypedContent as RoomMemberEventContent)?.Membership]++; + if (!result.MemberCounts.ContainsKey((@event.TypedContent as RoomMemberEventContent)?.Membership)) result.MemberCounts.Add((@event.TypedContent as RoomMemberEventContent)?.Membership, 0); + result.MemberCounts[(@event.TypedContent as RoomMemberEventContent)?.Membership]++; } } @@ -119,7 +119,7 @@ public class JoinedRoomListController : ControllerBase { [HttpGet("joined_rooms_with_info_cache")] public async Task<object> GetRoomInfoCache() { var mxid = await _authenticationService.GetMxidFromToken(); - if(!_config.Admins.Contains(mxid)) { + if (!_config.Admins.Contains(mxid)) { Response.StatusCode = StatusCodes.Status403Forbidden; Response.ContentType = "application/json"; diff --git a/MxApiExtensions/Controllers/Extensions/ProxyConfigurationController.cs b/MxApiExtensions/Controllers/Extensions/ProxyConfigurationController.cs index 0dcc3bb..b9d7e84 100644 --- a/MxApiExtensions/Controllers/Extensions/ProxyConfigurationController.cs +++ b/MxApiExtensions/Controllers/Extensions/ProxyConfigurationController.cs @@ -24,7 +24,7 @@ public class ProxyConfigurationController : ControllerBase { [HttpGet("proxy_config")] public async Task<MxApiExtensionsConfiguration> GetConfig() { var mxid = await _authenticationService.GetMxidFromToken(); - if(!_config.Admins.Contains(mxid)) { + if (!_config.Admins.Contains(mxid)) { _logger.LogWarning("Got proxy config request for {user}, but they are not an admin", mxid); Response.StatusCode = StatusCodes.Status403Forbidden; Response.ContentType = "application/json"; diff --git a/MxApiExtensions/Controllers/Other/GenericProxyController.cs b/MxApiExtensions/Controllers/Other/GenericProxyController.cs index 36ceab7..26c6371 100644 --- a/MxApiExtensions/Controllers/Other/GenericProxyController.cs +++ b/MxApiExtensions/Controllers/Other/GenericProxyController.cs @@ -188,4 +188,4 @@ public class GenericController(ILogger<GenericController> logger, MxApiExtension await Response.CompleteAsync(); } } -} \ No newline at end of file +} diff --git a/MxApiExtensions/Controllers/Other/MediaProxyController.cs b/MxApiExtensions/Controllers/Other/MediaProxyController.cs index d4c4ea0..7dea73b 100644 --- a/MxApiExtensions/Controllers/Other/MediaProxyController.cs +++ b/MxApiExtensions/Controllers/Other/MediaProxyController.cs @@ -21,7 +21,7 @@ public class MediaProxyController(ILogger<GenericController> logger, MxApiExtens private static Dictionary<string, MediaCacheEntry> _mediaCache = new(); private static SemaphoreSlim _semaphore = new(1, 1); - + [HttpGet("/_matrix/media/{_}/download/{serverName}/{mediaId}")] public async Task ProxyMedia(string? _, string serverName, string mediaId) { try { @@ -34,13 +34,13 @@ public class MediaProxyController(ILogger<GenericController> logger, MxApiExtens List<RemoteHomeserver> FeasibleHomeservers = new(); { var a = await authenticatedHomeserverProviderService.TryGetRemoteHomeserver(); - if(a is not null) + if (a is not null) FeasibleHomeservers.Add(a); if (a is AuthenticatedHomeserverGeneric ahg) { var rooms = await ahg.GetJoinedRooms(); foreach (var room in rooms) { - var ahs = (await room.GetMembersByHomeserverAsync()).Keys.Select(x=>x.ToString()).ToList(); + var ahs = (await room.GetMembersByHomeserverAsync()).Keys.Select(x => x.ToString()).ToList(); foreach (var ah in ahs) { try { if (!FeasibleHomeservers.Any(x => x.BaseUrl == ah)) { @@ -52,19 +52,19 @@ public class MediaProxyController(ILogger<GenericController> logger, MxApiExtens } } } - + FeasibleHomeservers.Add(await hsProvider.GetRemoteHomeserver(serverName)); - - + + foreach (var homeserver in FeasibleHomeservers) { var resp = await homeserver.ClientHttpClient.GetAsync($"{Request.Path}"); - if(!resp.IsSuccessStatusCode) continue; + if (!resp.IsSuccessStatusCode) continue; entry.ContentType = resp.Content.Headers.ContentType?.ToString() ?? "application/json"; entry.Data = await resp.Content.ReadAsByteArrayAsync(); - if (entry.Data is not { Length: >0 }) throw new NullReferenceException("No data received?"); + if (entry.Data is not { Length: > 0 }) throw new NullReferenceException("No data received?"); break; } - if (entry.Data is not { Length: >0 }) throw new NullReferenceException("No data received from any homeserver?"); + if (entry.Data is not { Length: > 0 }) throw new NullReferenceException("No data received from any homeserver?"); } else if (_mediaCache[$"{serverName}/{mediaId}"].Data is not { Length: > 0 }) { _mediaCache.Remove($"{serverName}/{mediaId}"); @@ -74,7 +74,7 @@ public class MediaProxyController(ILogger<GenericController> logger, MxApiExtens else entry = _mediaCache[$"{serverName}/{mediaId}"]; if (entry.Data is null) throw new NullReferenceException("No data?"); _semaphore.Release(); - + Response.StatusCode = 200; Response.ContentType = entry.ContentType; await Response.StartAsync(); diff --git a/MxApiExtensions/Extensions/HttpResponseExtensions.cs b/MxApiExtensions/Extensions/HttpResponseExtensions.cs index 1dd1c00..3f776ec 100644 --- a/MxApiExtensions/Extensions/HttpResponseExtensions.cs +++ b/MxApiExtensions/Extensions/HttpResponseExtensions.cs @@ -2,10 +2,10 @@ namespace MxApiExtensions.Extensions; public static class HttpResponseExtensions { public static async Task WriteHttpResponse(this HttpResponse response, HttpResponseMessage message) { - response.StatusCode = (int) message.StatusCode; + response.StatusCode = (int)message.StatusCode; //copy all headers foreach (var header in message.Headers) { - response.Headers.Add(header.Key, header.Value.ToArray()); + response.Headers.Append(header.Key, header.Value.ToArray()); } await response.StartAsync(); diff --git a/MxApiExtensions/FileStorageProvider.cs b/MxApiExtensions/FileStorageProvider.cs index c2bb267..9ca330a 100644 --- a/MxApiExtensions/FileStorageProvider.cs +++ b/MxApiExtensions/FileStorageProvider.cs @@ -17,7 +17,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)) { + if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } } diff --git a/MxApiExtensions/MxApiExtensions.csproj b/MxApiExtensions/MxApiExtensions.csproj index 73565db..78607b2 100644 --- a/MxApiExtensions/MxApiExtensions.csproj +++ b/MxApiExtensions/MxApiExtensions.csproj @@ -10,14 +10,12 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="ArcaneLibs" Version="1.0.0-preview6437853305.78f6d30" /> <PackageReference Include="EasyCompressor.LZMA" Version="1.4.0" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" /> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj" /> <ProjectReference Include="..\..\LibMatrix\LibMatrix\LibMatrix.csproj" /> <ProjectReference Include="..\MxApiExtensions.Classes.LibMatrix\MxApiExtensions.Classes.LibMatrix.csproj" /> <ProjectReference Include="..\MxApiExtensions.Classes\MxApiExtensions.Classes.csproj" /> diff --git a/MxApiExtensions/Program.cs b/MxApiExtensions/Program.cs index b08061e..b44129e 100644 --- a/MxApiExtensions/Program.cs +++ b/MxApiExtensions/Program.cs @@ -71,17 +71,15 @@ var app = builder.Build(); // Configure the HTTP request pipeline. // if (app.Environment.IsDevelopment()) { - app.UseSwagger(); - app.UseSwaggerUI(); +app.UseSwagger(); +app.UseSwaggerUI(); // } // app.UseHttpsRedirection(); app.UseCors("Open"); -app.UseExceptionHandler(exceptionHandlerApp => -{ - exceptionHandlerApp.Run(async context => - { +app.UseExceptionHandler(exceptionHandlerApp => { + exceptionHandlerApp.Run(async context => { var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>(); @@ -110,4 +108,4 @@ app.UseExceptionHandler(exceptionHandlerApp => app.MapControllers(); -app.Run(); \ No newline at end of file +app.Run(); diff --git a/MxApiExtensions/Services/AuthenticatedHomeserverProviderService.cs b/MxApiExtensions/Services/AuthenticatedHomeserverProviderService.cs index 741beb3..296663d 100644 --- a/MxApiExtensions/Services/AuthenticatedHomeserverProviderService.cs +++ b/MxApiExtensions/Services/AuthenticatedHomeserverProviderService.cs @@ -15,7 +15,7 @@ public class AuthenticatedHomeserverProviderService(AuthenticationService authen return null; } } - + public async Task<RemoteHomeserver> GetRemoteHomeserver() { try { return await GetHomeserver(); @@ -23,7 +23,7 @@ public class AuthenticatedHomeserverProviderService(AuthenticationService authen catch (MxApiMatrixException e) { if (e is not { ErrorCode: "M_MISSING_TOKEN" }) throw; if (request is null) throw new MxApiMatrixException() { ErrorCode = "M_UNKNOWN", Error = "[MxApiExtensions] Request was null for unauthenticated request!" }; - if (!_context.Request.Headers.Keys.Any(x=>x.ToUpper() == "MXAE_UPSTREAM")) + if (!_context.Request.Headers.Keys.Any(x => x.ToUpper() == "MXAE_UPSTREAM")) throw new MxApiMatrixException() { ErrorCode = "MXAE_MISSING_UPSTREAM", Error = "[MxApiExtensions] Missing MXAE_UPSTREAM header for unauthenticated request, this should be a server_name!" diff --git a/MxApiExtensions/Services/AuthenticationService.cs b/MxApiExtensions/Services/AuthenticationService.cs index 7430fcd..6a45214 100644 --- a/MxApiExtensions/Services/AuthenticationService.cs +++ b/MxApiExtensions/Services/AuthenticationService.cs @@ -42,11 +42,11 @@ public class AuthenticationService(ILogger<AuthenticationService> logger, MxApiE return "@anonymous:*"; } - if(_tokenMap is not { Count: >0 } && File.Exists("token_map")) { + if (_tokenMap is not { Count: > 0 } && File.Exists("token_map")) { _tokenMap = (await File.ReadAllLinesAsync("token_map")) .Select(l => l.Split('\t')) .ToDictionary(l => l[0], l => l[1]); - + //THIS IS BROKEN, DO NOT USE! // foreach (var (mapToken, mapUser) in _tokenMap) { // try { @@ -62,7 +62,7 @@ public class AuthenticationService(ILogger<AuthenticationService> logger, MxApiE // _tokenMap.RemoveAll((x, y) => string.IsNullOrWhiteSpace(y)); // await File.WriteAllTextAsync("token_map", _tokenMap.Aggregate("", (x, y) => $"{y.Key}\t{y.Value}\n")); } - + if (_tokenMap.TryGetValue(token, out var mxid)) return mxid; @@ -73,12 +73,12 @@ public class AuthenticationService(ILogger<AuthenticationService> logger, MxApiE await lookupTasks[homeserver].WaitAsync(TimeSpan.FromMilliseconds(500)); if (lookupTasks[homeserver].IsCompletedSuccessfully && !string.IsNullOrWhiteSpace(lookupTasks[homeserver].Result)) break; } - catch {} + catch { } } await Task.WhenAll(lookupTasks.Values); mxid = lookupTasks.Values.FirstOrDefault(x => x.Result != null)?.Result; - if(mxid is null) { + if (mxid is null) { throw new MxApiMatrixException { ErrorCode = "M_UNKNOWN_TOKEN", Error = "Token not found on any configured homeservers: " + string.Join(", ", config.AuthHomeservers) diff --git a/MxApiExtensions/Services/UserContextService.cs b/MxApiExtensions/Services/UserContextService.cs index d5ef282..7c96990 100644 --- a/MxApiExtensions/Services/UserContextService.cs +++ b/MxApiExtensions/Services/UserContextService.cs @@ -41,4 +41,4 @@ public class UserContextService(MxApiExtensionsConfiguration config, Authenticat // _getUserContextSemaphore.Release(); return ucs; } -} \ No newline at end of file +} |