Skip to content

Commit

Permalink
chore: tidy up
Browse files Browse the repository at this point in the history
  • Loading branch information
GZTimeWalker committed Oct 24, 2023
1 parent 8f8e27e commit 5c67c79
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 41 deletions.
15 changes: 6 additions & 9 deletions src/GZCTF/Controllers/AssetsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,13 @@ public async Task<IActionResult> Upload(List<IFormFile> files, [FromQuery] strin
try
{
List<LocalFile> results = new();
foreach (IFormFile file in files)
foreach (var file in files.Where(file => file.Length > 0))
{
if (file.Length > 0)
{
LocalFile res = await fileService.CreateOrUpdateFile(file, filename, token);
logger.SystemLog(
Program.StaticLocalizer[nameof(Resources.Program.Assets_UpdateFile), res.Hash[..8], filename ?? file.FileName, file.Length],
TaskStatus.Success, LogLevel.Debug);
results.Add(res);
}
LocalFile res = await fileService.CreateOrUpdateFile(file, filename, token);
logger.SystemLog(
Program.StaticLocalizer[nameof(Resources.Program.Assets_UpdateFile), res.Hash[..8], filename ?? file.FileName, file.Length],
TaskStatus.Success, LogLevel.Debug);
results.Add(res);
}

return Ok(results);
Expand Down
2 changes: 1 addition & 1 deletion src/GZCTF/Controllers/GameController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ public async Task<IActionResult> SubmissionSheet([FromRoute] int id, [FromServic

Submission[] submissions = await submissionRepository.GetSubmissions(game, count: 0, token: token);

MemoryStream stream = excelHelper.GetSubmissionExcel(submissions, localizer);
MemoryStream stream = excelHelper.GetSubmissionExcel(submissions);
stream.Seek(0, SeekOrigin.Begin);

return File(stream,
Expand Down
4 changes: 2 additions & 2 deletions src/GZCTF/Controllers/ProxyController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ async Task<IActionResult> DoContainerProxy(Guid id, IPEndPoint client, IPEndPoin
}
}
catch (TaskCanceledException) { }
finally { cts.Cancel(); }
finally { await cts.CancelAsync(); }
}, ct);

Task receiver = Task.Run(async () =>
Expand All @@ -233,7 +233,7 @@ async Task<IActionResult> DoContainerProxy(Guid id, IPEndPoint client, IPEndPoin
}
}
catch (TaskCanceledException) { }
finally { cts.Cancel(); }
finally { await cts.CancelAsync(); }
}, ct);

await Task.WhenAny(sender, receiver);
Expand Down
19 changes: 11 additions & 8 deletions src/GZCTF/Repositories/FileRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class FileRepository(AppDbContext context, ILogger<FileRepository> logger
public async Task<LocalFile> CreateOrUpdateFile(IFormFile file, string? fileName = null,
CancellationToken token = default)
{
await using Stream tmp = GetStream(file.Length);
await using Stream tmp = GetTempStream(file.Length);

logger.SystemLog(Program.StaticLocalizer[nameof(Resources.Program.FileRepository_CacheLocation), tmp.GetType()], TaskStatus.Pending,
LogLevel.Trace);
Expand All @@ -33,7 +33,7 @@ public async Task<LocalFile> CreateOrUpdateFile(IFormFile file, string? fileName
{
await using Stream webpStream = new MemoryStream();

await using (Stream tmp = GetStream(file.Length))
await using (Stream tmp = GetTempStream(file.Length))
{
await file.CopyToAsync(tmp, token);
tmp.Position = 0;
Expand Down Expand Up @@ -117,16 +117,19 @@ public Task<LocalFile[]> GetFiles(int count, int skip, CancellationToken token =

public async Task DeleteAttachment(Attachment? attachment, CancellationToken token = default)
{
if (attachment is null)
return;

if (attachment is { Type: FileType.Local, LocalFile: not null })
await DeleteFile(attachment.LocalFile, token);
switch (attachment)
{
case null:
return;
case { Type: FileType.Local, LocalFile: not null }:
await DeleteFile(attachment.LocalFile, token);
break;
}

Context.Remove(attachment);
}

static Stream GetStream(long bufferSize)
static Stream GetTempStream(long bufferSize)
{
if (bufferSize <= 16 * 1024 * 1024)
return new MemoryStream();
Expand Down
15 changes: 4 additions & 11 deletions src/GZCTF/Utils/DigitalSignature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ public static class DigitalSignature
{
public static string GenerateSignature(string data, AsymmetricKeyParameter privateKey, SignAlgorithm signAlgorithm)
{
if (string.IsNullOrEmpty(data))
throw new ArgumentNullException(nameof(data));

ArgumentException.ThrowIfNullOrEmpty(data);
ArgumentNullException.ThrowIfNull(privateKey);

var byteData = Encoding.UTF8.GetBytes(data);
Expand All @@ -36,14 +34,9 @@ public static string GenerateSignature(string data, AsymmetricKeyParameter priva
public static bool VerifySignature(string data, string sign, AsymmetricKeyParameter publicKey,
SignAlgorithm signAlgorithm)
{
if (string.IsNullOrEmpty(data))
throw new ArgumentNullException(nameof(data));

if (string.IsNullOrEmpty(sign))
throw new ArgumentNullException(nameof(sign));

if (publicKey == null)
throw new ArgumentNullException(nameof(publicKey));
ArgumentException.ThrowIfNullOrEmpty(data);
ArgumentException.ThrowIfNullOrEmpty(sign);
ArgumentNullException.ThrowIfNull(publicKey);

var signBytes = Base64.Decode(sign);
var plainBytes = Encoding.UTF8.GetBytes(data);
Expand Down
6 changes: 3 additions & 3 deletions src/GZCTF/Utils/ExcelHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ public MemoryStream GetScoreboardExcel(ScoreboardModel scoreboard, Game game)
return stream;
}

public MemoryStream GetSubmissionExcel(IEnumerable<Submission> submissions, IStringLocalizer<Program> localizer)
public MemoryStream GetSubmissionExcel(IEnumerable<Submission> submissions)
{
var workbook = new XSSFWorkbook();
ISheet? subSheet = workbook.CreateSheet(localizer[nameof(Resources.Program.Scoreboard_AllSubmissions)]);
ICellStyle headerStyle = GetHeaderStyle(workbook);
WriteSubmissionHeader(subSheet, headerStyle);
WriteSubmissionContent(subSheet, submissions, localizer);
WriteSubmissionContent(subSheet, submissions);

var stream = new MemoryStream();
workbook.Write(stream, true);
Expand Down Expand Up @@ -80,7 +80,7 @@ void WriteSubmissionHeader(ISheet sheet, ICellStyle style)
}
}

void WriteSubmissionContent(ISheet sheet, IEnumerable<Submission> submissions, IStringLocalizer<Program> localizer)
void WriteSubmissionContent(ISheet sheet, IEnumerable<Submission> submissions)
{
var rowIndex = 1;

Expand Down
11 changes: 4 additions & 7 deletions src/GZCTF/Utils/LogHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public static void Log<T>(this ILogger<T> logger, string msg, string uname, stri
logger.Log(level ?? LogLevel.Information, msg);
}
}

public static void UseRequestLogging(this WebApplication app) =>
app.UseSerilogRequestLogging(options =>
{
Expand Down Expand Up @@ -136,20 +136,17 @@ public static ILogger GetLogger(IConfiguration configuration, IServiceProvider s
.Filter.ByExcluding(
Matching.WithProperty<string>("RequestPath", v =>
"/healthz".Equals(v, StringComparison.OrdinalIgnoreCase) ||
v.StartsWith("/assets", StringComparison.OrdinalIgnoreCase)
)
)
.MinimumLevel.Debug()
v.StartsWith("/assets", StringComparison.OrdinalIgnoreCase)))
.Filter.ByExcluding(logEvent =>
logEvent.Exception != null &&
logEvent.Exception.GetType() == typeof(OperationCanceledException))
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("AspNetCoreRateLimit", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning)
.WriteTo.Async(t => t.Console(
new ExpressionTemplate(LogTemplate, theme: TemplateTheme.Literate),
LogEventLevel.Debug
))
LogEventLevel.Debug))
.WriteTo.Async(t => t.File(
path: $"{FilePath.Logs}/log_.log",
formatter: new ExpressionTemplate(LogTemplate),
Expand Down

0 comments on commit 5c67c79

Please sign in to comment.