Files
raven/server/AyaNova/Controllers/ImportController.cs
2020-10-26 20:58:58 +00:00

142 lines
5.2 KiB
C#

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using AyaNova.Models;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;
using AyaNova.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.IO.Compression;
using ChoETL;
namespace AyaNova.Api.Controllers
{
[ApiController]
[ApiVersion("8.0")]
[Route("api/v{version:apiVersion}/import")]
[Produces("application/json")]
[Authorize]
public class ImportController : ControllerBase
{
private readonly AyContext ct;
private readonly ILogger<ImportController> log;
private readonly ApiServerState serverState;
/// <summary>
/// ctor
/// </summary>
/// <param name="dbcontext"></param>
/// <param name="logger"></param>
/// <param name="apiServerState"></param>
public ImportController(AyContext dbcontext, ILogger<ImportController> logger, ApiServerState apiServerState)
{
ct = dbcontext;
log = logger;
serverState = apiServerState;
}
/// <summary>
/// Upload and import file
/// Max 100mb total
/// </summary>
/// <returns>Accepted</returns>
[Authorize]
[HttpPost("upload")]
[DisableFormValueModelBinding]
[RequestSizeLimit(100000000)]//100mb limit https://github.com/aspnet/Announcements/issues/267
public async Task<IActionResult> UploadAsync()
{
//Adapted from the example found here: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads#uploading-large-files-with-streaming
if (!serverState.IsOpen)
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
// 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 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();
//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());
}
//Instantiate the business object handler
AyaType TheType = System.Enum.Parse<AyaType>(UploadObjectType, true);
log.LogDebug($"Instantiating biz object handler for {TheType}");
var biz = BizObjectFactory.GetBizObject(TheType, ct);
//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)
{
JArray ja = JArray.Parse(System.IO.File.ReadAllText(a.InitialUploadedPathName));
await ((IImportAbleObject)biz).ImportData(ja);
}
}
}
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
ApiUploadProcessor.DeleteTempUploadFile(uploadFormData);
}
//TODO: Return results of operation here
return Accepted();
}
//-----------------------------------------
}//eoc
}//eons