refactor(backend): use explicit types instead of var by default

This commit is contained in:
sam 2024-12-08 15:07:25 +01:00
parent bc7fd6d804
commit 649988db25
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
52 changed files with 506 additions and 420 deletions

View file

@ -47,13 +47,13 @@ public static class ImageObjectExtensions
if (!uri.StartsWith("data:image/"))
throw new ArgumentException("Not a data URI", nameof(uri));
var split = uri.Remove(0, "data:".Length).Split(";base64,");
var contentType = split[0];
var encoded = split[1];
string[] split = uri.Remove(0, "data:".Length).Split(";base64,");
string contentType = split[0];
string encoded = split[1];
if (!ValidContentTypes.Contains(contentType))
throw new ArgumentException("Invalid content type for image", nameof(uri));
if (!AuthUtils.TryFromBase64String(encoded, out var rawImage))
if (!AuthUtils.TryFromBase64String(encoded, out byte[]? rawImage))
throw new ArgumentException("Invalid base64 string", nameof(uri));
var image = Image.Load(rawImage);
@ -74,7 +74,7 @@ public static class ImageObjectExtensions
await image.SaveAsync(stream, new WebpEncoder { Quality = 95, NearLossless = false });
stream.Seek(0, SeekOrigin.Begin);
var hash = Convert.ToHexString(await SHA256.HashDataAsync(stream)).ToLower();
string hash = Convert.ToHexString(await SHA256.HashDataAsync(stream)).ToLower();
stream.Seek(0, SeekOrigin.Begin);
return (hash, stream);

View file

@ -14,7 +14,7 @@ public static class KeyCacheExtensions
CancellationToken ct = default
)
{
var state = AuthUtils.RandomToken().Replace('+', '-').Replace('/', '_');
string state = AuthUtils.RandomToken().Replace('+', '-').Replace('/', '_');
await keyCacheService.SetKeyAsync($"oauth_state:{state}", "", Duration.FromMinutes(10), ct);
return state;
}
@ -25,7 +25,7 @@ public static class KeyCacheExtensions
CancellationToken ct = default
)
{
var val = await keyCacheService.GetKeyAsync($"oauth_state:{state}", ct: ct);
string? val = await keyCacheService.GetKeyAsync($"oauth_state:{state}", ct: ct);
if (val == null)
throw new ApiError.BadRequest("Invalid OAuth state");
}
@ -38,7 +38,7 @@ public static class KeyCacheExtensions
)
{
// This state is used in links, not just as JSON values, so make it URL-safe
var state = AuthUtils.RandomToken().Replace('+', '-').Replace('/', '_');
string state = AuthUtils.RandomToken().Replace('+', '-').Replace('/', '_');
await keyCacheService.SetKeyAsync(
$"email_state:{state}",
new RegisterEmailState(email, userId),
@ -62,7 +62,7 @@ public static class KeyCacheExtensions
CancellationToken ct = default
)
{
var state = AuthUtils.RandomToken();
string state = AuthUtils.RandomToken();
await keyCacheService.SetKeyAsync(
$"add_account:{state}",
new AddExtraAccountState(authType, userId, instance),
@ -76,12 +76,7 @@ public static class KeyCacheExtensions
this KeyCacheService keyCacheService,
string state,
CancellationToken ct = default
) =>
await keyCacheService.GetKeyAsync<AddExtraAccountState>(
$"add_account:{state}",
delete: true,
ct
);
) => await keyCacheService.GetKeyAsync<AddExtraAccountState>($"add_account:{state}", true, ct);
}
public record RegisterEmailState(

View file

@ -24,9 +24,9 @@ public static class WebApplicationExtensions
/// </summary>
public static WebApplicationBuilder AddSerilog(this WebApplicationBuilder builder)
{
var config = builder.Configuration.Get<Config>() ?? new();
Config config = builder.Configuration.Get<Config>() ?? new Config();
var logCfg = new LoggerConfiguration()
LoggerConfiguration logCfg = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Is(config.Logging.LogEventLevel)
// ASP.NET's built in request logs are extremely verbose, so we use Serilog's instead.
@ -43,10 +43,7 @@ public static class WebApplicationExtensions
if (config.Logging.SeqLogUrl != null)
{
logCfg.WriteTo.Seq(
config.Logging.SeqLogUrl,
restrictedToMinimumLevel: LogEventLevel.Verbose
);
logCfg.WriteTo.Seq(config.Logging.SeqLogUrl, LogEventLevel.Verbose);
}
// AddSerilog doesn't seem to add an ILogger to the service collection, so add that manually.
@ -60,19 +57,19 @@ public static class WebApplicationExtensions
builder.Configuration.Sources.Clear();
builder.Configuration.AddConfiguration();
var config = builder.Configuration.Get<Config>() ?? new();
Config config = builder.Configuration.Get<Config>() ?? new Config();
builder.Services.AddSingleton(config);
return config;
}
public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder builder)
{
var file = Environment.GetEnvironmentVariable("FOXNOUNS_CONFIG_FILE") ?? "config.ini";
string file = Environment.GetEnvironmentVariable("FOXNOUNS_CONFIG_FILE") ?? "config.ini";
return builder
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", true)
.AddIniFile(file, optional: false, reloadOnChange: true)
.AddIniFile(file, false, true)
.AddEnvironmentVariables();
}
@ -142,11 +139,15 @@ public static class WebApplicationExtensions
app.Services.ConfigureQueue()
.LogQueuedTaskProgress(app.Services.GetRequiredService<ILogger<IQueue>>());
await using var scope = app.Services.CreateAsyncScope();
await using AsyncServiceScope scope = app.Services.CreateAsyncScope();
// The types of these variables are obvious from the methods being called to create them
// ReSharper disable SuggestVarOrType_SimpleTypes
var logger = scope
.ServiceProvider.GetRequiredService<ILogger>()
.ForContext<WebApplication>();
var db = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
// ReSharper restore SuggestVarOrType_SimpleTypes
logger.Information(
"Starting Foxnouns.NET {Version} ({Hash})",