manager-service/ManagerService/Controllers/ConfigurationController.cs
2021-08-04 18:07:21 +02:00

445 lines
18 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
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 Mqtt.Client.AspNetCore.Services;
using Newtonsoft.Json;
using NSwag.Annotations;
namespace ManagerService.Controllers
{
[Authorize] // TODO Add ROLES (Roles = "Admin")
[ApiController, Route("api/[controller]")]
[OpenApiTag("Configuration", Description = "Configuration management")]
public class ConfigurationController : ControllerBase
{
private ConfigurationDatabaseService _configurationService;
private SectionDatabaseService _sectionService;
private ResourceDatabaseService _resourceService;
private readonly ILogger<ConfigurationController> _logger;
public ConfigurationController(ILogger<ConfigurationController> logger, ConfigurationDatabaseService configurationService, SectionDatabaseService sectionService, ResourceDatabaseService resourceService)
{
_logger = logger;
_configurationService = configurationService;
_sectionService = sectionService;
_resourceService = resourceService;
}
/// <summary>
/// Get a list of all configuration (summary)
/// </summary>
[AllowAnonymous]
[ProducesResponseType(typeof(List<ConfigurationDTO>), 200)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet]
public ObjectResult Get()
{
try
{
List<Configuration> configurations = _configurationService.GetAll();
return new OkObjectResult(configurations.Select(r => r.ToDTO()));
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a specific display configuration
/// </summary>
/// <param name="id">id configuration</param>
[AllowAnonymous]
[ProducesResponseType(typeof(ConfigurationDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}")]
public ObjectResult GetDetail(string id)
{
try
{
Configuration configuration = _configurationService.GetById(id);
if (configuration == null)
throw new KeyNotFoundException("This configuration was not found");
return new OkObjectResult(configuration.ToDTO());
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Create a new configuration
/// </summary>
/// <param name="newConfiguration">New configuration info</param>
[ProducesResponseType(typeof(ConfigurationDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost]
public ObjectResult Create([FromBody] ConfigurationDTO newConfiguration)
{
try
{
if (newConfiguration == null)
throw new ArgumentNullException("Configuration param is null");
// Todo add some verification ?
Configuration configuration = new Configuration();
configuration.Label = newConfiguration.label;
configuration.PrimaryColor = newConfiguration.primaryColor;
configuration.SecondaryColor = newConfiguration.secondaryColor;
configuration.Languages = new List<string> { "FR", "NL", "EN", "DE" }; // by default all languages
configuration.DateCreation = DateTime.Now;
Configuration configurationCreated = _configurationService.Create(configuration);
return new OkObjectResult(configurationCreated.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 configuration
/// </summary>
/// <param name="updatedConfiguration">Configuration to update</param>
[ProducesResponseType(typeof(ConfigurationDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut]
public ObjectResult Update([FromBody] ConfigurationDTO updatedConfiguration)
{
try
{
if (updatedConfiguration == null)
throw new ArgumentNullException("configuration param is null");
Configuration configuration = _configurationService.GetById(updatedConfiguration.id);
if (configuration == null)
throw new KeyNotFoundException("Configuration does not exist");
// Todo add some verification ?
configuration.Label = updatedConfiguration.label;
configuration.PrimaryColor = updatedConfiguration.primaryColor;
configuration.SecondaryColor = updatedConfiguration.secondaryColor;
configuration.Languages = updatedConfiguration.languages;
Configuration configurationModified = _configurationService.Update(updatedConfiguration.id, configuration);
MqttClientService.PublishMessage($"config/{configurationModified.Id}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));
return new OkObjectResult(configurationModified.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 configuration
/// </summary>
/// <param name="id">Id of configuration 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("Configuration param is null");
if (!_configurationService.IsExist(id))
throw new KeyNotFoundException("Configuration does not exist");
_configurationService.Remove(id);
MqttClientService.PublishMessage($"config/{id}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true, isDeleted = true }));
return new ObjectResult("The configuration 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 };
}
}
/// <summary>
/// Export a configuration
/// </summary>
/// <param name="id">Id of configuration to export</param>
[ProducesResponseType(typeof(ExportConfigurationDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}/export")]
public ObjectResult Export(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("Configuration param is null");
Configuration configuration = _configurationService.GetById(id);
if (configuration == null)
throw new KeyNotFoundException("Configuration does not exist");
List<SectionDTO> sectionDTOs = _sectionService.GetAllFromConfiguration(configuration.Id).Select(s => s.ToDTO()).ToList();
List<ResourceDTO> resourceDTOs = new List<ResourceDTO>();
foreach (var section in sectionDTOs)
{
if (section.imageId != null) {
addResourceToList(resourceDTOs, section.imageId);
}
switch (section.type) {
case SectionType.Map:
MapDTO mapDTO = JsonConvert.DeserializeObject<MapDTO>(section.data);
if (mapDTO.iconResourceId != null)
{
addResourceToList(resourceDTOs, mapDTO.iconResourceId);
}
foreach (var point in mapDTO.points) {
foreach (var image in point.images) {
if (image.imageResourceId != null)
{
addResourceToList(resourceDTOs, image.imageResourceId);
}
}
}
break;
case SectionType.Slider:
SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.data);
foreach (var image in sliderDTO.images)
{
if (image.resourceId != null)
{
addResourceToList(resourceDTOs, image.resourceId);
}
}
break;
case SectionType.Menu:
case SectionType.Web:
case SectionType.Video:
default:
break;
}
}
return new OkObjectResult(configuration.ToExportDTO(sectionDTOs, resourceDTOs));
}
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>
/// Import a configuration
/// </summary>
/// <param name="exportConfiguration">Configuration to import</param>
[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost("import")]
public ObjectResult Import([FromBody] ExportConfigurationDTO exportConfiguration)
{
try
{
if (exportConfiguration == null)
throw new ArgumentNullException("File to import is null");
Configuration configuration = _configurationService.GetById(exportConfiguration.id);
if (configuration != null)
throw new InvalidOperationException("Configuration already exist in the system");
configuration = new Configuration();
configuration.Id = exportConfiguration.id;
configuration.Label = exportConfiguration.label;
configuration.DateCreation = exportConfiguration.dateCreation;
configuration.PrimaryColor = exportConfiguration.primaryColor;
configuration.SecondaryColor = exportConfiguration.secondaryColor;
configuration.Languages = exportConfiguration.languages;
_configurationService.Create(configuration);
foreach (var section in exportConfiguration.sections.Where(s => !_sectionService.IsExist(s.id)))
{
Section newSection = new Section();
newSection.Id = section.id;
newSection.Label = section.label;
newSection.Title = section.title;
newSection.Description = section.description;
newSection.Order = section.order; // if one day we can use same section in multiple configuration, need to change that
newSection.Type = section.type;
newSection.ImageId = section.imageId;
newSection.ImageSource = section.imageSource;
newSection.ConfigurationId = section.configurationId;
newSection.IsSubSection = section.isSubSection;
newSection.ParentId = section.parentId;
newSection.Data = section.data;
newSection.DateCreation = section.dateCreation;
if (newSection.ImageId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == newSection.ImageId).FirstOrDefault());
}
_sectionService.Create(newSection);
switch (section.type)
{
case SectionType.Map:
MapDTO mapDTO = JsonConvert.DeserializeObject<MapDTO>(section.data);
if (mapDTO.iconResourceId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == mapDTO.iconResourceId).FirstOrDefault());
}
foreach (var point in mapDTO.points)
{
foreach (var image in point.images)
{
if (image.imageResourceId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == image.imageResourceId).FirstOrDefault());
}
}
}
break;
case SectionType.Slider:
SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.data);
foreach (var image in sliderDTO.images)
{
if (image.resourceId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == image.resourceId).FirstOrDefault());
}
}
break;
case SectionType.Menu:
case SectionType.Web:
case SectionType.Video:
default:
break;
}
}
return new ObjectResult("The configuration has been successfully imported") { StatusCode = 202 };
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (InvalidOperationException ex)
{
return new ConflictObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
private void createResource(ResourceDTO resourceExport)
{
if (resourceExport != null)
{
Resource resource = new Resource();
resource.Id = resourceExport.id;
resource.Type = resourceExport.type;
resource.Label = resourceExport.label;
resource.DateCreation = resourceExport.dateCreation;
resource.Data = resourceExport.data;
if (!_resourceService.IsExist(resourceExport.id))
_resourceService.Create(resource);
}
}
private List<ResourceDTO> addResourceToList(List<ResourceDTO> resourceDTOs, string resourceId) {
if (!resourceDTOs.Select(r => r.id).Contains(resourceId)) {
Resource resource = _resourceService.GetById(resourceId);
if (resource != null) {
resourceDTOs.Add(resource.ToDTO(true));
}
}
return resourceDTOs;
}
}
}