summary refs log tree commit diff
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-08-14 19:45:52 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-08-14 19:45:52 +0200
commit8253ca8cb96154f95854b1c1e5dd3ba53f41e5ec (patch)
tree34976d3e005f91ba479ce8286a9ffa6ac9651237
parentInitial commit (diff)
downloadMxApiExtensions-8253ca8cb96154f95854b1c1e5dd3ba53f41e5ec.tar.xz
Code cleanup
-rw-r--r--MxApiExtensions/Auth.cs10
-rw-r--r--MxApiExtensions/Controllers/GenericProxyController.cs14
-rw-r--r--MxApiExtensions/Controllers/SyncController.cs26
-rw-r--r--MxApiExtensions/MatrixException.cs7
-rw-r--r--MxApiExtensions/Program.cs5
5 files changed, 31 insertions, 31 deletions
diff --git a/MxApiExtensions/Auth.cs b/MxApiExtensions/Auth.cs

index 1f0cc80..cc60a99 100644 --- a/MxApiExtensions/Auth.cs +++ b/MxApiExtensions/Auth.cs
@@ -27,7 +27,7 @@ public class Auth { } if (token == null && fail) { - throw new MatrixException() { + throw new MatrixException { ErrorCode = "M_MISSING_TOKEN", Error = "Missing access token" }; @@ -40,7 +40,7 @@ public class Auth { var token = GetToken(fail); if (token == null) { if(fail) { - throw new MatrixException() { + throw new MatrixException { ErrorCode = "M_MISSING_TOKEN", Error = "Missing access token" }; @@ -60,14 +60,14 @@ public class Auth { hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var resp = hc.GetAsync($"{_config.Homeserver}/_matrix/client/v3/account/whoami").Result; if (!resp.IsSuccessStatusCode) { - throw new MatrixException() { + throw new MatrixException { ErrorCode = "M_UNKNOWN", Error = "[Rory&::MxSyncCache] Whoami request failed" }; } if (resp.Content is null) { - throw new MatrixException() { + throw new MatrixException { ErrorCode = "M_UNKNOWN", Error = "No content in response" }; @@ -75,7 +75,7 @@ public class Auth { var json = JsonDocument.Parse(resp.Content.ReadAsStream()).RootElement; var mxid = json.GetProperty("user_id").GetString()!; - _logger.LogInformation($"Got mxid {mxid} from token {token}"); + _logger.LogInformation("Got mxid {} from token {}", mxid, token); return mxid; } diff --git a/MxApiExtensions/Controllers/GenericProxyController.cs b/MxApiExtensions/Controllers/GenericProxyController.cs
index 91ae55a..f0ad4e7 100644 --- a/MxApiExtensions/Controllers/GenericProxyController.cs +++ b/MxApiExtensions/Controllers/GenericProxyController.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Mvc; namespace MxApiExtensions.Controllers; [ApiController] -[Route("/")] +[Route("/{*_}")] public class GenericController : ControllerBase { private readonly ILogger<GenericController> _logger; private readonly CacheConfiguration _config; @@ -17,13 +17,13 @@ public class GenericController : ControllerBase { _auth = auth; } - [HttpGet("{*_}")] + [HttpGet] public async Task Proxy([FromQuery] string? access_token, string _) { try { access_token ??= _auth.GetToken(fail: false); var mxid = _auth.GetUserId(fail: false); - _logger.LogInformation($"Proxying request for {mxid}: {Request.Path}{Request.QueryString}"); + _logger.LogInformation("Proxying request for {}: {}{}", mxid, Request.Path, Request.QueryString); using var hc = new HttpClient(); hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token); @@ -71,13 +71,13 @@ public class GenericController : ControllerBase { } } - [HttpPost("{*_}")] + [HttpPost] public async Task ProxyPost([FromQuery] string? access_token, string _) { try { access_token ??= _auth.GetToken(fail: false); var mxid = _auth.GetUserId(fail: false); - _logger.LogInformation($"Proxying request for {mxid}: {Request.Path}{Request.QueryString}"); + _logger.LogInformation("Proxying request for {}: {}{}", mxid, Request.Path, Request.QueryString); using var hc = new HttpClient(); hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token); @@ -89,10 +89,10 @@ public class GenericController : ControllerBase { .Replace($"access_token={access_token}", "") ); - var resp = await hc.SendAsync(new() { + var resp = await hc.SendAsync(new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri($"{_config.Homeserver}{Request.Path}{Request.QueryString}"), - Content = new StreamContent(Request.Body), + Content = new StreamContent(Request.Body) }); if (resp.Content is null) { diff --git a/MxApiExtensions/Controllers/SyncController.cs b/MxApiExtensions/Controllers/SyncController.cs
index e2b724f..d883377 100644 --- a/MxApiExtensions/Controllers/SyncController.cs +++ b/MxApiExtensions/Controllers/SyncController.cs
@@ -38,7 +38,7 @@ public class SyncController : ControllerBase { // var resp = await hs._httpClient.GetAsync($"/_matrix/client/v3/sync?since={since}"); if (resp.Content is null) { - throw new MatrixException() { + throw new MatrixException { ErrorCode = "M_UNKNOWN", Error = "No content in response" }; @@ -49,7 +49,7 @@ public class SyncController : ControllerBase { await Response.StartAsync(); await using var stream = await resp.Content.ReadAsStreamAsync(); await using var target = System.IO.File.OpenWrite(cacheFile); - byte[] buffer = new byte[1]; + var buffer = new byte[1]; int bytesRead; while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) { @@ -78,17 +78,15 @@ public class SyncController : ControllerBase { } private async Task<bool> TrySendCached(string cacheFile) { - if (System.IO.File.Exists(cacheFile)) { - Response.StatusCode = 200; - Response.ContentType = "application/json"; - await Response.StartAsync(); - await using var stream = System.IO.File.OpenRead(cacheFile); - await stream.CopyToAsync(Response.Body); - await Response.CompleteAsync(); - return true; - } - - return false; + if (!System.IO.File.Exists(cacheFile)) return false; + + Response.StatusCode = 200; + Response.ContentType = "application/json"; + await Response.StartAsync(); + await using var stream = System.IO.File.OpenRead(cacheFile); + await stream.CopyToAsync(Response.Body); + await Response.CompleteAsync(); + return true; } #region Cache management @@ -98,7 +96,7 @@ public class SyncController : ControllerBase { Directory.CreateDirectory(cacheDir); var cacheFile = Path.Join(cacheDir, $"sync-{since}.json"); if (!Path.GetFullPath(cacheFile).StartsWith(Path.GetFullPath(cacheDir))) { - throw new MatrixException() { + throw new MatrixException { ErrorCode = "M_UNKNOWN", Error = "[Rory&::MxSyncCache] Cache file path is not in cache directory" }; diff --git a/MxApiExtensions/MatrixException.cs b/MxApiExtensions/MatrixException.cs
index 1daf5d1..568c5a9 100644 --- a/MxApiExtensions/MatrixException.cs +++ b/MxApiExtensions/MatrixException.cs
@@ -21,9 +21,10 @@ public class MatrixException : Exception { //turn this into json public JsonObject GetAsJson() { - var jsonObject = new JsonObject(); - jsonObject["errcode"] = ErrorCode; - jsonObject["error"] = Error; + var jsonObject = new JsonObject { + ["errcode"] = ErrorCode, + ["error"] = Error + }; if(SoftLogout is not null) jsonObject["soft_logout"] = SoftLogout; if(RetryAfterMs is not null) jsonObject["retry_after_ms"] = RetryAfterMs; return jsonObject; diff --git a/MxApiExtensions/Program.cs b/MxApiExtensions/Program.cs
index 00afe09..11fe114 100644 --- a/MxApiExtensions/Program.cs +++ b/MxApiExtensions/Program.cs
@@ -1,3 +1,4 @@ +using Microsoft.AspNetCore.Http.Timeouts; using MxApiExtensions; var builder = WebApplication.CreateBuilder(args); @@ -15,13 +16,13 @@ builder.Services.AddSingleton<CacheConfiguration>(); builder.Services.AddScoped<Auth>(); builder.Services.AddRequestTimeouts(x => { - x.DefaultPolicy = new() { + x.DefaultPolicy = new RequestTimeoutPolicy { Timeout = TimeSpan.FromMinutes(10), WriteTimeoutResponse = async context => { context.Response.StatusCode = 504; context.Response.ContentType = "application/json"; await context.Response.StartAsync(); - await context.Response.WriteAsJsonAsync(new MatrixException() { + await context.Response.WriteAsJsonAsync(new MatrixException { ErrorCode = "M_TIMEOUT", Error = "Request timed out" }.GetAsJson());