318 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Manager.Interfaces.DTO;
using Manager.Interfaces.Models;
using Manager.Services;
using ManagerService.Service.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NSwag.Annotations;
namespace ManagerService.Controllers
{
[Authorize] // TODO Add ROLES (Roles = "Admin")
[ApiController, Route("api/[controller]")]
[OpenApiTag("Resource", Description = "Resource management")]
public class ResourceController : ControllerBase
{
private ResourceDatabaseService _resourceService;
private readonly ILogger<ResourceController> _logger;
public ResourceController(ILogger<ResourceController> logger, ResourceDatabaseService resourceService)
{
_logger = logger;
_resourceService = resourceService;
}
/// <summary>
/// Get a list of all resources (summary)
/// </summary>
[ProducesResponseType(typeof(List<ResourceDTO>), 200)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet]
public ObjectResult Get()
{
try
{
List<Resource> resources = _resourceService.GetAll();
return new OkObjectResult(resources.Select(r => r.ToDTO()));
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a specific resource
/// </summary>
/// <param name="id">id resource</param>
[AllowAnonymous]
[ProducesResponseType(typeof(ResourceDetailDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}/detail")]
public ObjectResult GetDetail(string id)
{
try
{
Resource resource = _resourceService.GetById(id);
if (resource == null)
throw new KeyNotFoundException("This resource was not found");
return new OkObjectResult(resource.ToDetailDTO());
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Show a specific resource (as a picture or video stream)
/// </summary>
/// <param name="id">id resource</param>
[AllowAnonymous]
[ProducesResponseType(typeof(FileResult), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}")]
public ActionResult Show(string id)
{
try
{
Resource resource = _resourceService.GetById(id);
if (resource == null)
throw new KeyNotFoundException("This resource was not found");
var file = Convert.FromBase64String(resource.Data);
if (resource.Type == ResourceType.Image)
{
return new FileContentResult(file, "image/png");
}
if (resource.Type == ResourceType.Video)
{
return new FileContentResult(file, "application/octet-stream");
}
return new FileContentResult(file, "image/png");
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Upload a specific resource (picture or video)
/// </summary>
/// <param name="id">id resource</param>
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost("upload"), DisableRequestSizeLimit]
public IActionResult Upload([FromForm] string label, [FromForm] string type) // Create but with local //[FromBody] ResourceDetailDTO uploadResource
{
try
{
var test = label;
var test0 = type;
/*if (uploadResource == null)
throw new ArgumentNullException("Resource param is null");*/
ResourceDetailDTO uploadResource = new ResourceDetailDTO();
uploadResource.type = (ResourceType) Enum.Parse(typeof(ResourceType), type);
uploadResource.label = label;
var file = Request.Form.Files[0];
if (file.Length > 0)
{
var stringResult = "";
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
stringResult = Convert.ToBase64String(fileBytes);
}
}
// Todo add some verification ?
Resource resource = new Resource();
resource.Label = uploadResource.label;
resource.Type = uploadResource.type;
resource.DateCreation = DateTime.Now;
resource.Data = stringResult;
Resource resourceCreated = _resourceService.Create(resource);
return Ok(resourceCreated.ToDTO());
}
else
{
return BadRequest();
}
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (InvalidOperationException ex)
{
return new ConflictObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Create a new resource
/// </summary>
/// <param name="newResource">New resource info</param>
[ProducesResponseType(typeof(ResourceDetailDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost]
public ObjectResult Create([FromBody] ResourceDetailDTO newResource)
{
try
{
if (newResource == null)
throw new ArgumentNullException("Resource param is null");
// Todo add some verification ?
Resource resource = new Resource();
resource.Label = newResource.label;
resource.Type = newResource.type;
resource.DateCreation = DateTime.Now;
resource.Data = newResource.data;
Resource resourceCreated = _resourceService.Create(resource);
return new OkObjectResult(resourceCreated.ToDTO());
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) {};
}
catch (InvalidOperationException ex)
{
return new ConflictObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Update a resource
/// </summary>
/// <param name="updatedResource">Resource to update</param>
[ProducesResponseType(typeof(ResourceDetailDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut]
public ObjectResult Update([FromBody] ResourceDetailDTO updatedResource)
{
try
{
if (updatedResource == null)
throw new ArgumentNullException("Resource param is null");
Resource resource = _resourceService.GetById(updatedResource.id);
if (resource == null)
throw new KeyNotFoundException("Resource does not exist");
// Todo add some verification ?
resource.Label = updatedResource.label;
resource.Type = updatedResource.type;
resource.Data = updatedResource.data;
Resource resourceModified = _resourceService.Update(updatedResource.id, resource);
return new OkObjectResult(resourceModified.ToDTO());
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) {};
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Delete a resource
/// </summary>
/// <param name="id">Id of resource to delete</param>
[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpDelete("{id}")]
public ObjectResult Delete(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("Resource param is null");
if (!_resourceService.IsExist(id))
throw new KeyNotFoundException("Resource does not exist");
_resourceService.Remove(id);
return new ObjectResult("The resource has been deleted") { StatusCode = 202 };
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
}
}