Fix /upload/{hash} endpoint not writing correctly

This commit is contained in:
jvyden 2021-10-21 18:59:30 -04:00
commit f3c6d4a415
No known key found for this signature in database
GPG key ID: 18BCF2BE0262B278
3 changed files with 25 additions and 11 deletions

View file

@ -1,13 +1,13 @@
using System.Buffers;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using LBPUnion.ProjectLighthouse.Helpers;
using LBPUnion.ProjectLighthouse.Serialization;
using LBPUnion.ProjectLighthouse.Types;
using LBPUnion.ProjectLighthouse.Types.Files;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using IOFile = System.IO.File;
@ -60,7 +60,7 @@ namespace LBPUnion.ProjectLighthouse.Controllers {
FileHelper.EnsureDirectoryCreated(assetsDirectory);
if(FileHelper.ResourceExists(hash)) this.Ok(); // no reason to fail if it's already uploaded
LbpFile file = new(this.Request.Body);
LbpFile file = new(await BinaryHelper.ReadFromPipeReader(Request.BodyReader));
if(!FileHelper.IsFileSafe(file)) return this.UnprocessableEntity();

View file

@ -1,7 +1,10 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Text;
using System.Threading.Tasks;
namespace LBPUnion.ProjectLighthouse.Helpers {
public static class BinaryHelper {
@ -34,5 +37,24 @@ namespace LBPUnion.ProjectLighthouse.Helpers {
if(restoreOldPosition) reader.BaseStream.Position = oldPosition;
return data;
}
// Written with reference from
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/request-response?view=aspnetcore-5.0
// Surprisingly doesn't take seconds. (67ms for a 100kb file)
public static async Task<byte[]> ReadFromPipeReader(PipeReader reader) {
List<byte> data = new();
while(true) {
ReadResult readResult = await reader.ReadAsync();
ReadOnlySequence<byte> buffer = readResult.Buffer;
if(readResult.IsCompleted && buffer.Length > 0) data.AddRange(buffer.ToArray());
reader.AdvanceTo(buffer.Start, buffer.End);
if(readResult.IsCompleted) break;
}
return data.ToArray();
}
}
}

View file

@ -7,14 +7,6 @@ namespace LBPUnion.ProjectLighthouse.Types.Files {
this.Data = data;
this.FileType = FileHelper.DetermineFileType(this.Data);
}
public LbpFile(Stream stream) {
using MemoryStream ms = new();
stream.CopyToAsync(ms);
this.Data = ms.ToArray();
this.FileType = FileHelper.DetermineFileType(this.Data);
}
/// <summary>
/// The type of file.