823 lines
37 KiB
C#
823 lines
37 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Manager.Helpers;
|
|
using Manager.Interfaces.DTO;
|
|
using Manager.Interfaces.Models;
|
|
using Manager.Services;
|
|
using ManagerService.Helpers;
|
|
using ManagerService.Service.Services;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Extensions.Configuration;
|
|
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 ResourceDataDatabaseService _resourceDataService;
|
|
private DeviceDatabaseService _deviceService;
|
|
private readonly ILogger<ConfigurationController> _logger;
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public ConfigurationController(IConfiguration configuration, ILogger<ConfigurationController> logger, ConfigurationDatabaseService configurationService, SectionDatabaseService sectionService, ResourceDatabaseService resourceService, ResourceDataDatabaseService resourceDataService, DeviceDatabaseService deviceService)
|
|
{
|
|
_logger = logger;
|
|
_configuration = configuration;
|
|
_configurationService = configurationService;
|
|
_sectionService = sectionService;
|
|
_resourceService = resourceService;
|
|
_resourceDataService = resourceDataService;
|
|
_deviceService = deviceService;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get a list of all configuration (summary)
|
|
/// </summary>
|
|
/// <param name="id">id instance</param>
|
|
[AllowAnonymous]
|
|
[ProducesResponseType(typeof(List<ConfigurationDTO>), 200)]
|
|
[ProducesResponseType(typeof(string), 500)]
|
|
[HttpGet]
|
|
public ObjectResult Get([FromQuery] string instanceId)
|
|
{
|
|
try
|
|
{
|
|
List<Configuration> configurations = _configurationService.GetAll(instanceId);
|
|
|
|
List<ConfigurationDTO> configurationDTOs = new List<ConfigurationDTO>();
|
|
|
|
foreach(var configuration in configurations)
|
|
{
|
|
List<string> sectionIds = _sectionService.GetAllIdsFromConfiguration(configuration.Id);
|
|
ConfigurationDTO configurationDTO = configuration.ToDTO(sectionIds);
|
|
configurationDTOs.Add(configurationDTO);
|
|
}
|
|
|
|
return new OkObjectResult(configurationDTOs.OrderBy(c => c.dateCreation));
|
|
}
|
|
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");
|
|
|
|
List<string> sectionIds = _sectionService.GetAllIdsFromConfiguration(id);
|
|
|
|
return new OkObjectResult(configuration.ToDTO(sectionIds));
|
|
}
|
|
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.InstanceId = newConfiguration.instanceId;
|
|
configuration.Label = newConfiguration.label;
|
|
configuration.Title = new List<TranslationDTO>();
|
|
configuration.ImageId = newConfiguration.imageId;
|
|
configuration.ImageSource = newConfiguration.imageSource;
|
|
configuration.PrimaryColor = newConfiguration.primaryColor;
|
|
configuration.SecondaryColor = newConfiguration.secondaryColor;
|
|
|
|
configuration.Languages = _configuration.GetSection("SupportedLanguages").Get<List<string>>();
|
|
|
|
//configuration.Languages = new List<string> { "FR", "NL", "EN", "DE" }; // by default all languages
|
|
configuration.Title = LanguageInit.Init("Title", configuration.Languages);
|
|
|
|
configuration.DateCreation = DateTime.Now;
|
|
configuration.IsMobile = newConfiguration.isMobile;
|
|
configuration.IsTablet = newConfiguration.isTablet;
|
|
configuration.IsOffline = newConfiguration.isOffline;
|
|
|
|
Configuration configurationCreated = _configurationService.Create(configuration);
|
|
|
|
return new OkObjectResult(configurationCreated.ToDTO(new List<string>())); // Empty list
|
|
}
|
|
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.InstanceId = updatedConfiguration.instanceId;
|
|
configuration.Label = updatedConfiguration.label;
|
|
configuration.Title = updatedConfiguration.title;
|
|
configuration.ImageId = updatedConfiguration.imageId;
|
|
configuration.ImageSource = updatedConfiguration.imageSource;
|
|
configuration.PrimaryColor = updatedConfiguration.primaryColor;
|
|
configuration.SecondaryColor = updatedConfiguration.secondaryColor;
|
|
configuration.Languages = updatedConfiguration.languages;
|
|
configuration.IsMobile = updatedConfiguration.isMobile;
|
|
configuration.IsTablet = updatedConfiguration.isTablet;
|
|
configuration.IsOffline = updatedConfiguration.isOffline;
|
|
|
|
Configuration configurationModified = _configurationService.Update(updatedConfiguration.id, configuration);
|
|
|
|
// TODO HANDLE MqttClientService.PublishMessage($"config/{configurationModified.Id}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));
|
|
|
|
List<string> sectionIds = _sectionService.GetAllIdsFromConfiguration(configuration.Id);
|
|
|
|
return new OkObjectResult(configurationModified.ToDTO(sectionIds));
|
|
}
|
|
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);
|
|
|
|
// Delete config for all devices
|
|
List<Device> devices = _deviceService.GetAllWithConfig(id);
|
|
|
|
foreach (var device in devices)
|
|
{
|
|
device.Configuration = null;
|
|
device.ConfigurationId = null;
|
|
_deviceService.Update(device.Id, device);
|
|
}
|
|
|
|
// TODO 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>
|
|
/// <param name="language">Language to export</param>
|
|
[AllowAnonymous]
|
|
[ProducesResponseType(typeof(FileContentResult), 200)]
|
|
[ProducesResponseType(typeof(string), 400)]
|
|
[ProducesResponseType(typeof(string), 404)]
|
|
[ProducesResponseType(typeof(string), 500)]
|
|
[HttpGet("{id}/export")]
|
|
public ActionResult Export(string id, [FromQuery] string language)
|
|
{
|
|
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<string> resourceIds = new List<string>();
|
|
|
|
var mimeType = "application/json";
|
|
|
|
string currentDirectory = System.IO.Directory.GetCurrentDirectory();
|
|
Console.WriteLine($"currentDirectory: {currentDirectory}");
|
|
currentDirectory = Path.Combine(currentDirectory, "service-data");
|
|
System.IO.Directory.CreateDirectory(currentDirectory.ToString());
|
|
Console.WriteLine($"createdDiretory: {currentDirectory}");
|
|
#if RELEASE
|
|
//Console.WriteLine($"currentDirectory: {Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}");
|
|
//currentDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "service-data");
|
|
|
|
#endif
|
|
|
|
var resourcesDirectory = Path.Combine(currentDirectory, "resources");
|
|
System.IO.Directory.CreateDirectory(resourcesDirectory.ToString());
|
|
Console.WriteLine($"resourcesDirectory: {resourcesDirectory}");
|
|
|
|
var configurationsDirectory = Path.Combine(currentDirectory, "configurations");
|
|
System.IO.Directory.CreateDirectory(configurationsDirectory.ToString());
|
|
Console.WriteLine($"configurationsDirectory: {configurationsDirectory}");
|
|
|
|
if (configuration.ImageId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, configuration.ImageId);
|
|
}
|
|
|
|
foreach (var section in sectionDTOs)
|
|
{
|
|
if (section.imageId != null) {
|
|
addResourceIdToList(resourceIds, section.imageId);
|
|
}
|
|
|
|
switch (section.type) {
|
|
case SectionType.Map:
|
|
MapDTO mapDTO = JsonConvert.DeserializeObject<MapDTO>(section.data);
|
|
if (mapDTO.iconResourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, mapDTO.iconResourceId);
|
|
}
|
|
|
|
foreach (var point in mapDTO.points) {
|
|
foreach (var image in point.images) {
|
|
if (image.imageResourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, image.imageResourceId);
|
|
}
|
|
}
|
|
}
|
|
|
|
break;
|
|
case SectionType.Slider:
|
|
SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.data);
|
|
foreach (var image in sliderDTO.images)
|
|
{
|
|
if (image.resourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, image.resourceId);
|
|
}
|
|
}
|
|
break;
|
|
case SectionType.Quizz:
|
|
QuizzDTO quizzDTO = JsonConvert.DeserializeObject<QuizzDTO>(section.data);
|
|
foreach (var question in quizzDTO.questions)
|
|
{
|
|
if (question.resourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, question.resourceId);
|
|
}
|
|
}
|
|
if (quizzDTO.bad_level != null)
|
|
{
|
|
if (quizzDTO.bad_level.resourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, quizzDTO.bad_level.resourceId);
|
|
}
|
|
}
|
|
if (quizzDTO.medium_level != null)
|
|
{
|
|
if (quizzDTO.medium_level.resourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, quizzDTO.medium_level.resourceId);
|
|
}
|
|
}
|
|
if (quizzDTO.good_level != null)
|
|
{
|
|
if (quizzDTO.good_level.resourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, quizzDTO.good_level.resourceId);
|
|
}
|
|
}
|
|
if (quizzDTO.great_level != null)
|
|
{
|
|
if (quizzDTO.great_level.resourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, quizzDTO.great_level.resourceId);
|
|
}
|
|
}
|
|
break;
|
|
case SectionType.Article:
|
|
ArticleDTO articleDTO = JsonConvert.DeserializeObject<ArticleDTO>(section.data);
|
|
foreach (var image in articleDTO.images)
|
|
{
|
|
if (image.resourceId != null)
|
|
{
|
|
addResourceIdToList(resourceIds, image.resourceId);
|
|
}
|
|
}
|
|
|
|
// If not a language is used for export in manager, if one is the myvisit app
|
|
var audios = language != null ? articleDTO.audioIds.Where(a => a.language == language) : articleDTO.audioIds;
|
|
foreach (var audio in audios)
|
|
{
|
|
if (audio.value != null)
|
|
{
|
|
addResourceIdToList(resourceIds, audio.value);
|
|
}
|
|
}
|
|
break;
|
|
case SectionType.Menu:
|
|
case SectionType.Web:
|
|
case SectionType.Video:
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (language == null)
|
|
{
|
|
// EXPORT IN ZIP
|
|
getResourceDTOFromIds(resourcesDirectory, resourceIds);
|
|
|
|
ExportConfigurationDTO toDownload = configuration.ToExportDTO(sectionDTOs, null); // intentionnaly putting null to get only data
|
|
string jsonString = JsonConvert.SerializeObject(toDownload);
|
|
|
|
var fileBytes = Encoding.UTF8.GetBytes(jsonString);
|
|
|
|
var configFileMainTitle = $"config-{configuration.Label.Trim().Replace(" ", "_")}.json";
|
|
string configFileMainData = Path.Combine(configurationsDirectory, configFileMainTitle);
|
|
|
|
// Create the file.
|
|
createFile(configFileMainData, fileBytes);
|
|
|
|
byte[] exportFile = FileHelper.CreateZipArchive(currentDirectory);
|
|
|
|
var fileName0 = $"{configuration.Label.Trim().Replace(" ", "_")}";
|
|
|
|
return File(exportFile, "application/zip", $"{fileName0}_{DateTime.Now:yyyyMMdd}.zip");
|
|
}
|
|
|
|
var fileName = $"{configuration.Label.Trim().Replace(" ","_")}.json";
|
|
string configFile = Path.Combine(configurationsDirectory, fileName);
|
|
|
|
if (!System.IO.File.Exists(configFile))
|
|
{
|
|
|
|
List<ResourceDTO> resourceDTOs = getResourceDTOFromIds(resourcesDirectory, resourceIds);
|
|
|
|
ExportConfigurationDTO toDownload = configuration.ToExportDTO(sectionDTOs, resourceDTOs);
|
|
string jsonString = JsonConvert.SerializeObject(toDownload);
|
|
|
|
var fileBytes = Encoding.UTF8.GetBytes(jsonString);
|
|
|
|
// Create the file.
|
|
createFile(configFile, fileBytes);
|
|
|
|
return new FileContentResult(fileBytes, mimeType)
|
|
{
|
|
FileDownloadName = fileName
|
|
};
|
|
}
|
|
else
|
|
{
|
|
// Get file from folder
|
|
//byte[] readText = System.IO.File.ReadAllBytes(configFile);
|
|
byte[] readText;
|
|
using (var stream = new FileStream(configFile, FileMode.Open, FileAccess.Read))
|
|
{
|
|
var buffer = new byte[4096];
|
|
using (var ms = new MemoryStream())
|
|
{
|
|
int bytesRead;
|
|
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
|
|
{
|
|
ms.Write(buffer, 0, bytesRead);
|
|
}
|
|
readText = ms.ToArray();
|
|
}
|
|
}
|
|
|
|
string exportInString = Encoding.UTF8.GetString(readText);
|
|
|
|
//string exportInString = Encoding.UTF8.GetString(readText);
|
|
|
|
ExportConfigurationDTO exportConfigurationFromFile = JsonConvert.DeserializeObject<ExportConfigurationDTO>(exportInString);
|
|
|
|
// Get all ids that are not in the existing file
|
|
List<string> resourceIdsToDownload = resourceIds.Where(r => !exportConfigurationFromFile.resources.Select(r => r.id).Distinct().ToList().Contains(r)).ToList();
|
|
|
|
List<ResourceDTO> resourceDTOs = getResourceDTOFromIds(resourcesDirectory, resourceIdsToDownload);
|
|
|
|
exportConfigurationFromFile.resources.AddRange(resourceDTOs);
|
|
|
|
//exportConfigurationFromFile.resources.AddRange(exportConfigurationFromFile.resources.Distinct());
|
|
ExportConfigurationDTO exportWithAll = configuration.ToExportDTO(sectionDTOs, exportConfigurationFromFile.resources);
|
|
string jsonStringWithAll = JsonConvert.SerializeObject(exportWithAll);
|
|
|
|
ExportConfigurationDTO toDownload = configuration.ToExportDTO(sectionDTOs, exportConfigurationFromFile.resources.Where(r => resourceIds.Contains(r.id)).ToList()); //Only download from resourceIds (only language ask (or not)
|
|
|
|
string jsonString = JsonConvert.SerializeObject(toDownload);
|
|
readText = Encoding.UTF8.GetBytes(jsonString);
|
|
|
|
// Check if difference
|
|
if (exportInString != jsonStringWithAll)
|
|
{
|
|
// Delete file
|
|
System.IO.File.Delete(configFile);
|
|
|
|
var fileBytes = Encoding.UTF8.GetBytes(jsonStringWithAll);
|
|
|
|
// Recreate file with new content
|
|
createFile(configFile, fileBytes);
|
|
}
|
|
|
|
return new FileContentResult(readText, mimeType)
|
|
{
|
|
FileDownloadName = fileName
|
|
};
|
|
}
|
|
}
|
|
catch (ArgumentNullException ex)
|
|
{
|
|
return null;
|
|
//return new BadRequestObjectResult(ex.Message) { };
|
|
}
|
|
catch (KeyNotFoundException ex)
|
|
{
|
|
return null;
|
|
//return new NotFoundObjectResult(ex.Message) { };
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error: {ex.Message}");
|
|
return null;
|
|
//return new ObjectResult(ex.Message) { StatusCode = 500 };
|
|
}
|
|
}
|
|
|
|
private List<ResourceDTO> getResourceDTOFromIds(string resourcesDirectory, List<string> resourceIds)
|
|
{
|
|
List<ResourceDTO> resourceDTOs = new List<ResourceDTO>();
|
|
|
|
foreach (var resourceId in resourceIds)
|
|
{
|
|
string resourceFile = Path.Combine(resourcesDirectory, resourceId)+".json";
|
|
if (System.IO.File.Exists(resourceFile))
|
|
{
|
|
// FILE EXIST, JUST GET IT FROM FILE
|
|
byte[] readText = System.IO.File.ReadAllBytes(resourceFile);
|
|
string resourceInString = Encoding.UTF8.GetString(readText);
|
|
ResourceDTO resourceDTO = JsonConvert.DeserializeObject<ResourceDTO>(resourceInString);
|
|
resourceDTOs.Add(resourceDTO);
|
|
}
|
|
else
|
|
{
|
|
// FILE DO NOT EXIST
|
|
Resource resource = _resourceService.GetById(resourceId);
|
|
ResourceData resourceData = _resourceDataService.GetByResourceId(resourceId);
|
|
|
|
if (resource != null && resourceData != null && !resourceDTOs.Any(r => r.id == resource.Id)) // Check if file already exist
|
|
{
|
|
resourceDTOs.Add(resource.ToDTO(resourceData.Data));
|
|
|
|
// Put resource in resources folder
|
|
string resourceJsonString = JsonConvert.SerializeObject(resource.ToDTO(resourceData.Data));
|
|
byte[] resourceBytes = Encoding.UTF8.GetBytes(resourceJsonString);
|
|
|
|
createFile(resourceFile, resourceBytes);
|
|
}
|
|
}
|
|
}
|
|
|
|
return resourceDTOs;
|
|
}
|
|
|
|
private void createFile(String fileName, byte[] fileBytes)
|
|
{
|
|
try
|
|
{
|
|
using (FileStream fs = System.IO.File.Create(fileName))
|
|
{
|
|
|
|
Console.WriteLine($"Try to create file at : {fileName}");
|
|
|
|
// Add some information to the file.
|
|
fs.Write(fileBytes, 0, fileBytes.Length);
|
|
|
|
Console.WriteLine($"Created file: {fileName}");
|
|
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"An error occured during file creation: {fileName} - {ex.Message}");
|
|
}
|
|
}
|
|
|
|
/// <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.InstanceId = exportConfiguration.instanceId;
|
|
configuration.Label = exportConfiguration.label;
|
|
configuration.Title = exportConfiguration.title;
|
|
configuration.ImageId = exportConfiguration.imageId;
|
|
configuration.ImageSource = exportConfiguration.imageSource;
|
|
|
|
if (configuration.ImageId != null)
|
|
{
|
|
createResource(exportConfiguration.resources.Where(r => r.id == configuration.ImageId).FirstOrDefault());
|
|
}
|
|
|
|
configuration.DateCreation = exportConfiguration.dateCreation;
|
|
configuration.PrimaryColor = exportConfiguration.primaryColor;
|
|
configuration.SecondaryColor = exportConfiguration.secondaryColor;
|
|
configuration.Languages = exportConfiguration.languages;
|
|
configuration.IsMobile = exportConfiguration.isMobile;
|
|
configuration.IsTablet = exportConfiguration.isTablet;
|
|
configuration.IsOffline = exportConfiguration.isOffline;
|
|
|
|
_configurationService.Create(configuration);
|
|
|
|
foreach (var section in exportConfiguration.sections.Where(s => !_sectionService.IsExist(s.id)))
|
|
{
|
|
Section newSection = new Section();
|
|
newSection.Id = section.id;
|
|
newSection.InstanceId = section.instanceId;
|
|
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;
|
|
newSection.IsBeacon = section.isBeacon;
|
|
newSection.BeaconId = section.beaconId;
|
|
newSection.Latitude = section.latitude;
|
|
newSection.Longitude = section.longitude;
|
|
newSection.MeterZoneGPS = section.meterZoneGPS;
|
|
|
|
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.Quizz:
|
|
QuizzDTO quizzDTO = JsonConvert.DeserializeObject<QuizzDTO>(section.data);
|
|
foreach (var question in quizzDTO.questions)
|
|
{
|
|
if (question.resourceId != null)
|
|
{
|
|
createResource(exportConfiguration.resources.Where(r => r.id == question.resourceId).FirstOrDefault());
|
|
}
|
|
}
|
|
if (quizzDTO.bad_level != null)
|
|
{
|
|
if(quizzDTO.bad_level.resourceId != null)
|
|
{
|
|
createResource(exportConfiguration.resources.Where(r => r.id == quizzDTO.bad_level.resourceId).FirstOrDefault());
|
|
}
|
|
}
|
|
if (quizzDTO.medium_level != null)
|
|
{
|
|
if (quizzDTO.medium_level.resourceId != null)
|
|
{
|
|
createResource(exportConfiguration.resources.Where(r => r.id == quizzDTO.medium_level.resourceId).FirstOrDefault());
|
|
}
|
|
}
|
|
if (quizzDTO.good_level != null)
|
|
{
|
|
if (quizzDTO.good_level.resourceId != null)
|
|
{
|
|
createResource(exportConfiguration.resources.Where(r => r.id == quizzDTO.good_level.resourceId).FirstOrDefault());
|
|
}
|
|
}
|
|
if (quizzDTO.great_level != null)
|
|
{
|
|
if (quizzDTO.great_level.resourceId != null)
|
|
{
|
|
createResource(exportConfiguration.resources.Where(r => r.id == quizzDTO.great_level.resourceId).FirstOrDefault());
|
|
}
|
|
}
|
|
break;
|
|
case SectionType.Article:
|
|
ArticleDTO articleDTO = JsonConvert.DeserializeObject<ArticleDTO>(section.data);
|
|
foreach (var image in articleDTO.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.InstanceId = resourceExport.instanceId;
|
|
resource.Type = resourceExport.type;
|
|
resource.Label = resourceExport.label;
|
|
resource.DateCreation = resourceExport.dateCreation;
|
|
//resource.Data = resourceExport.data;
|
|
|
|
ResourceData resourceData = new ResourceData();
|
|
resourceData.ResourceId = resourceExport.id;
|
|
resourceData.InstanceId = resourceExport.instanceId;
|
|
resourceData.Data = resourceExport.data;
|
|
|
|
if (!_resourceService.IsExist(resourceExport.id))
|
|
_resourceService.Create(resource);
|
|
|
|
if (!_resourceDataService.IsExist(resourceExport.id))
|
|
_resourceDataService.Create(resourceData);
|
|
}
|
|
}
|
|
|
|
private List<string> addResourceIdToList(List<string> resourceIds, string resourceId) {
|
|
if (!resourceIds.Contains(resourceId))
|
|
{
|
|
resourceIds.Add(resourceId);
|
|
}
|
|
|
|
return resourceIds;
|
|
}
|
|
}
|
|
}
|