Skip to content

Commit

Permalink
chore: tidy up
Browse files Browse the repository at this point in the history
  • Loading branch information
GZTimeWalker committed May 13, 2024
1 parent 6894dbd commit 322adba
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 37 deletions.
67 changes: 35 additions & 32 deletions src/GZCTF/Extensions/ConfigurationExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Encodings.Web;
using System.Net.Mime;
using System.Text.Encodings.Web;
using GZCTF.Models.Internal;
using GZCTF.Providers;
using GZCTF.Services.Cache;
Expand All @@ -16,18 +17,23 @@ public static class ConfigurationExtensions
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(7)
};

public static IConfigurationBuilder AddEntityConfiguration(this IConfigurationBuilder builder,
public static void AddEntityConfiguration(this IConfigurationBuilder builder,
Action<DbContextOptionsBuilder> optionsAction) =>
builder.Add(new EntityConfigurationSource(optionsAction));

public static void UseCustomFavicon(this WebApplication app) =>
app.MapGet("/favicon.webp", FaviconHandler);

public static async Task UseHomePageAsync(this WebApplication app)
public static async Task UseIndexAsync(this WebApplication app)
{
if (app.Environment.IsDevelopment())
if (!File.Exists(Path.Join(app.Environment.WebRootPath, "index.html")))
{
app.MapFallbackToFile("index.html");
app.MapFallback(context =>
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
context.Response.ContentType = MediaTypeNames.Text.Html;
return Task.CompletedTask;
});
return;
}

Expand All @@ -37,7 +43,7 @@ public static async Task UseHomePageAsync(this WebApplication app)
using var streamReader = new StreamReader(stream);
var template = await streamReader.ReadToEndAsync();

app.MapFallback(HomePageHandler(template));
app.MapFallback(IndexHandler(template));
}

static string GetETag(string hash) => $"\"favicon-{hash[..8]}\"";
Expand All @@ -46,14 +52,12 @@ static async Task<IResult> FaviconHandler(HttpContext context, IDistributedCache
IOptionsSnapshot<GlobalConfig> globalConfig, CancellationToken token = default)
{
var hash = await cache.GetStringAsync(CacheKey.Favicon, token);
if (hash is not null)
goto WriteCustomIcon;

hash = globalConfig.Value.FaviconHash;
if (hash is null || !Codec.FileHashRegex().IsMatch(hash))
goto FallbackToDefaultIcon;

WriteCustomIcon:
if (hash is null)
{
hash = globalConfig.Value.FaviconHash;
if (hash is null || !Codec.FileHashRegex().IsMatch(hash))
goto FallbackToDefaultIcon;
}

var eTag = GetETag(hash[..8]);
if (context.Request.Headers.IfNoneMatch == eTag)
Expand All @@ -70,7 +74,7 @@ static async Task<IResult> FaviconHandler(HttpContext context, IDistributedCache

return Results.File(
path,
"image/webp",
MediaTypeNames.Image.Webp,
"favicon.webp",
entityTag: EntityTagHeaderValue.Parse(eTag));

Expand All @@ -83,30 +87,29 @@ static async Task<IResult> FaviconHandler(HttpContext context, IDistributedCache

return Results.File(
Program.DefaultFavicon,
"image/webp",
MediaTypeNames.Image.Webp,
"favicon.webp",
entityTag: EntityTagHeaderValue.Parse(eTag));
}

static HomePageHandlerDelegate HomePageHandler(string template)
=> async (
IDistributedCache cache,
IOptionsSnapshot<GlobalConfig> globalConfig,
CancellationToken token = default) =>
{
var content = await cache.GetStringAsync(CacheKey.Index, token);
static HomePageHandlerDelegate IndexHandler(string template) => async (
IDistributedCache cache,
IOptionsSnapshot<GlobalConfig> globalConfig,
CancellationToken token = default) =>
{
var content = await cache.GetStringAsync(CacheKey.Index, token);
if (content is not null)
return Results.Text(content, "text/html");
if (content is not null)
return Results.Text(content, MediaTypeNames.Text.Html);
GlobalConfig config = globalConfig.Value;
var title = HtmlEncoder.Default.Encode(config.Platform);
var descr = HtmlEncoder.Default.Encode(config.Description ?? GlobalConfig.DefaultDescription);
content = template.Replace("%title%", title).Replace("%description%", descr);
GlobalConfig config = globalConfig.Value;
var title = HtmlEncoder.Default.Encode(config.Platform);
var descr = HtmlEncoder.Default.Encode(config.Description ?? GlobalConfig.DefaultDescription);
content = template.Replace("%title%", title).Replace("%description%", descr);
await cache.SetStringAsync(CacheKey.Index, content, token);
return Results.Text(content, "text/html");
};
await cache.SetStringAsync(CacheKey.Index, content, token);
return Results.Text(content, MediaTypeNames.Text.Html);
};

delegate Task<IResult> HomePageHandlerDelegate(IDistributedCache cache, IOptionsSnapshot<GlobalConfig> globalConfig,
CancellationToken token = default);
Expand Down
14 changes: 11 additions & 3 deletions src/GZCTF/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
global using AppDbContext = GZCTF.Models.AppDbContext;
global using TaskStatus = GZCTF.Utils.TaskStatus;
using System.Globalization;
using System.Net.Mime;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
Expand Down Expand Up @@ -263,7 +264,12 @@
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
["application/json", "text/javascript", "text/html", "text/css"]
[
MediaTypeNames.Application.Json,
MediaTypeNames.Text.Html,
MediaTypeNames.Text.JavaScript,
MediaTypeNames.Text.Css
]
);
});

Expand Down Expand Up @@ -338,7 +344,7 @@
app.MapHub<MonitorHub>("/hub/monitor");
app.MapHub<AdminHub>("/hub/admin");

await app.UseHomePageAsync();
await app.UseIndexAsync();

#endregion Middlewares

Expand Down Expand Up @@ -369,8 +375,10 @@ public class Program
{
static Program()
{
using Stream stream = typeof(Program).Assembly.GetManifestResourceStream("GZCTF.Resources.favicon.webp")!;
using Stream stream = typeof(Program).Assembly
.GetManifestResourceStream("GZCTF.Resources.favicon.webp")!;
DefaultFavicon = new byte[stream.Length];

stream.ReadExactly(DefaultFavicon);
DefaultFaviconHash = BitConverter.ToString(SHA256.HashData(DefaultFavicon))
.Replace("-", "").ToLowerInvariant();
Expand Down
3 changes: 1 addition & 2 deletions src/GZCTF/Utils/PrelaunchHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,8 @@ await context.Posts.AddAsync(new()

if (!cache.CacheCheck())
Program.ExitWithFatalMessage(Program.StaticLocalizer[nameof(Resources.Program.Init_InvalidCacheConfig)]);

await cache.RemoveAsync(CacheKey.Index);
await cache.RemoveAsync(CacheKey.Favicon);
}

static bool CacheCheck(this IDistributedCache cache)
Expand Down

0 comments on commit 322adba

Please sign in to comment.