This commit is contained in:
2020-08-07 21:19:54 +00:00
parent b90236b81e
commit a993d4d18b
4 changed files with 72 additions and 149 deletions

View File

@@ -46,10 +46,7 @@ namespace AyaNova.Api.Controllers
public async Task<IActionResult> GetGlobalBizSettings() public async Task<IActionResult> GetGlobalBizSettings()
{ {
if (serverState.IsClosed) if (serverState.IsClosed)
{
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
}
//Instantiate the business object handler //Instantiate the business object handler
GlobalBizSettingsBiz biz = GlobalBizSettingsBiz.GetBiz(ct, HttpContext); GlobalBizSettingsBiz biz = GlobalBizSettingsBiz.GetBiz(ct, HttpContext);

View File

@@ -36,6 +36,7 @@ namespace AyaNova.Api.Controllers
private readonly AyContext ct; private readonly AyContext ct;
private readonly ILogger<LogoController> log; private readonly ILogger<LogoController> log;
private readonly ApiServerState serverState; private readonly ApiServerState serverState;
private const int MAXIMUM_LOGO_SIZE = 512000;//We really don't want it too big or it will slow the fuck down for everything
/// <summary> /// <summary>
@@ -66,67 +67,61 @@ namespace AyaNova.Api.Controllers
{ {
if (serverState.IsClosed) if (serverState.IsClosed)
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
if (!ModelState.IsValid) if (!ModelState.IsValid)
{
return BadRequest(new ApiErrorResponse(ModelState)); return BadRequest(new ApiErrorResponse(ModelState));
}
if (string.IsNullOrWhiteSpace(size))
return BadRequest(new ApiErrorResponse(ApiErrorCode.VALIDATION_REQUIRED, "size", "Size is required and must be one of 'small', 'medium' or 'large'"));
size = size.ToLowerInvariant();
if (size != "small" && size != "medium" && size != "large")
return BadRequest(new ApiErrorResponse(ApiErrorCode.VALIDATION_INVALID_VALUE, "size", "Size parameter must be one of 'small', 'medium' or 'large'"));
var logo = await ct.Logo.SingleOrDefaultAsync();
var o = await ct.Logo.Include(z => z.LogoItems).SingleOrDefaultAsync(z => z.Id == id); if (logo == null)
//turn into correct format and then send as file
if (o == null)
{
return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND)); return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
}
var asText = Newtonsoft.Json.JsonConvert.SerializeObject(
o,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings { ContractResolver = new ShouldSerializeContractResolver(new string[] { "Concurrency", "Id", "LogoId" }) });
var bytes = System.Text.Encoding.UTF8.GetBytes(asText);
var file = new FileContentResult(bytes, "application/octet-stream");
file.FileDownloadName = Util.FileUtil.StringToSafeFileName(o.Name) + ".json";
return file;
}
public class ShouldSerializeContractResolver : DefaultContractResolver switch (size)
{ {
private readonly IEnumerable<string> _excludePropertyNames; case "small":
return new FileStreamResult(new MemoryStream(logo.Small), Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse(logo.SmallType));
case "medium":
return new FileStreamResult(new MemoryStream(logo.Medium), Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse(logo.MediumType));
case "large":
return new FileStreamResult(new MemoryStream(logo.Large), Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse(logo.LargeType));
public ShouldSerializeContractResolver(IEnumerable<string> excludePropertyNames)
{
_excludePropertyNames = excludePropertyNames;
} }
return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
// only serializer properties that start with the specified character // var asText = Newtonsoft.Json.JsonConvert.SerializeObject(
properties = // o,
properties.Where(p => !_excludePropertyNames.Any(p2 => p2 == p.PropertyName)).ToList(); // Newtonsoft.Json.Formatting.None,
// new JsonSerializerSettings { ContractResolver = new ShouldSerializeContractResolver(new string[] { "Concurrency", "Id", "LogoId" }) });
return properties; // var bytes = System.Text.Encoding.UTF8.GetBytes(asText);
} // var file = new FileContentResult(bytes, "application/octet-stream");
// file.FileDownloadName = Util.FileUtil.StringToSafeFileName(o.Name) + ".json";
// return file;
} }
/// <summary> /// <summary>
/// Upload Logo /// Upload Logo
/// Max 15mb total /// Max 500 KiB total (512000 bytes)
/// Must have full rights to Global object
/// </summary> /// </summary>
/// <param name="size">One of "small", "medium", "large"</param> /// <param name="size">One of "small", "medium", "large"</param>
/// <param name="uploadFile">Logo image file</param>
/// <returns>Accepted</returns> /// <returns>Accepted</returns>
[Authorize] [Authorize]
[HttpPost("{size}")] [HttpPost("{size}")]
[DisableFormValueModelBinding] [DisableFormValueModelBinding]
[RequestSizeLimit(15000000)]//currently export file is 200kb * 50 maximum at a time = 15mb https://github.com/aspnet/Announcements/issues/267 [RequestSizeLimit(MAXIMUM_LOGO_SIZE)]//currently export file is 200kb * 50 maximum at a time = 15mb https://github.com/aspnet/Announcements/issues/267
public async Task<IActionResult> UploadAsync([FromRoute] string size, IFormFile uploadFile) public async Task<IActionResult> UploadAsync([FromRoute] string size, IFormFile uploadFile)
{ {
@@ -135,120 +130,48 @@ namespace AyaNova.Api.Controllers
if (!serverState.IsOpen) if (!serverState.IsOpen)
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
if (!Authorized.HasReadFullRole(HttpContext.Items, AyaType.Global))
return StatusCode(403, new ApiNotAuthorizedResponse());
if (string.IsNullOrWhiteSpace(size))
return BadRequest(new ApiErrorResponse(ApiErrorCode.VALIDATION_REQUIRED, "size", "Size is required and must be one of 'small', 'medium' or 'large'"));
size = size.ToLowerInvariant();
if (size != "small" && size != "medium" && size != "large")
return BadRequest(new ApiErrorResponse(ApiErrorCode.VALIDATION_INVALID_VALUE, "size", "Size parameter must be one of 'small', 'medium' or 'large'"));
//get the one and only logo object
var logo = await ct.Logo.FirstOrDefaultAsync();
if (logo == null)
{
logo = new Logo();
ct.Logo.Add(logo);
await ct.SaveChangesAsync();
}
using (var memoryStream = new MemoryStream()) using (var memoryStream = new MemoryStream())
{ {
await uploadFile.CopyToAsync(memoryStream); await uploadFile.CopyToAsync(memoryStream);
// Upload the file if less than 2 MB
if (memoryStream.Length < 2097152) if (memoryStream.Length < 2097152)
return BadRequest(new ApiErrorResponse(ApiErrorCode.VALIDATION_LENGTH_EXCEEDED, null, "Logo files must be smaller than 500KiB maximum"));
switch (size)
{ {
var logo = new Logo() case "small":
{ logo.Small = memoryStream.ToArray();
Content = memoryStream.ToArray() logo.SmallType = uploadFile.ContentType;
}; break;
case "medium":
_dbContext.File.Add(file); logo.Medium = memoryStream.ToArray();
logo.MediumType = uploadFile.ContentType;
await _dbContext.SaveChangesAsync(); break;
} case "large":
else logo.Large = memoryStream.ToArray();
{ logo.LargeType = uploadFile.ContentType;
ModelState.AddModelError("File", "The file is too large."); break;
}
}
// AyaTypeId attachToObject = null;
ApiUploadProcessor.ApiUploadedFilesResult uploadFormData = null;
try
{
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
return BadRequest(new ApiErrorResponse(ApiErrorCode.INVALID_OPERATION, null, $"Expected a multipart request, but got {Request.ContentType}"));
//Save uploads to disk under temporary file names until we decide how to handle them
uploadFormData = await ApiUploadProcessor.ProcessUploadAsync(HttpContext);
bool badRequest = false;
string UploadObjectType = string.Empty;
string UploadObjectId = string.Empty;
string errorMessage = string.Empty;
string Notes = string.Empty;
List<UploadFileData> FileData = new List<UploadFileData>();
if (
!uploadFormData.FormFieldData.ContainsKey("FileData"))//only filedata is required
{
badRequest = true;
errorMessage = "Missing required FormFieldData value: FileData";
}
if (!badRequest)
{
if (uploadFormData.FormFieldData.ContainsKey("ObjectType"))
UploadObjectType = uploadFormData.FormFieldData["ObjectType"].ToString();
if (uploadFormData.FormFieldData.ContainsKey("ObjectId"))
UploadObjectId = uploadFormData.FormFieldData["ObjectId"].ToString();
if (uploadFormData.FormFieldData.ContainsKey("Notes"))
Notes = uploadFormData.FormFieldData["Notes"].ToString();
//fileData in JSON stringify format which contains the actual last modified dates etc
//"[{\"name\":\"Client.csv\",\"lastModified\":1582822079618},{\"name\":\"wmi4fu06nrs41.jpg\",\"lastModified\":1586900220990}]"
FileData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<UploadFileData>>(uploadFormData.FormFieldData["FileData"].ToString());
} }
await ct.SaveChangesAsync();
// long UserId = UserIdFromContext.Id(HttpContext.Items);
//Instantiate the business object handler
LogoBiz biz = LogoBiz.GetBiz(ct, HttpContext);
//We have our files now can parse and insert into db
if (uploadFormData.UploadedFiles.Count > 0)
{
//deserialize each file and import
foreach (UploadedFileInfo a in uploadFormData.UploadedFiles)
{
JObject o = JObject.Parse(System.IO.File.ReadAllText(a.InitialUploadedPathName));
if (!await biz.ImportAsync(o))
{
//delete all the files temporarily uploaded and return bad request
DeleteTempUploadFile(uploadFormData);
return BadRequest(new ApiErrorResponse(biz.Errors));
} }
}
}
}
catch (System.IO.InvalidDataException ex)
{
return BadRequest(new ApiErrorResponse(ApiErrorCode.INVALID_OPERATION, null, ex.Message));
}
finally
{
//delete all the files temporarily uploaded and return bad request
DeleteTempUploadFile(uploadFormData);
}
//Return the list of attachment ids and filenames
return Accepted(); return Accepted();
} }
private static void DeleteTempUploadFile(ApiUploadProcessor.ApiUploadedFilesResult uploadFormData)
{
if (uploadFormData.UploadedFiles.Count > 0)
{
foreach (UploadedFileInfo a in uploadFormData.UploadedFiles)
{
System.IO.File.Delete(a.InitialUploadedPathName);
}
}
}
} }
} }

View File

@@ -12,8 +12,11 @@ namespace AyaNova.Models
{ {
public long Id { get; set; } public long Id { get; set; }
public byte[] Large { get; set; } public byte[] Large { get; set; }
public string LargeType {get;set;}
public byte[] Medium { get; set; } public byte[] Medium { get; set; }
public string MediumType {get;set;}
public byte[] Small { get; set; } public byte[] Small { get; set; }
public string SmallType {get;set;}
} }

View File

@@ -712,7 +712,7 @@ $BODY$;
LogUpdateMessage(log); LogUpdateMessage(log);
await ExecQueryAsync("CREATE TABLE alogo (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, " + await ExecQueryAsync("CREATE TABLE alogo (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, " +
"large bytea, medium bytea, small bytea)"); "large bytea, largetype text, medium bytea, mediumtype text, small bytea, smalltype text)");
await SetSchemaLevelAsync(++currentSchema); await SetSchemaLevelAsync(++currentSchema);
} }