1213 lines
56 KiB
C#

using Manager.Helpers;
using Manager.Interfaces.DTO;
using Manager.Interfaces.Models;
using Manager.Services;
using ManagerService.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 Newtonsoft.Json.Linq;
using NSwag.Annotations;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using static System.Net.Mime.MediaTypeNames;
namespace ManagerService.Controllers
{
[Authorize] // TODO Add ROLES (Roles = "Admin")
[ApiController, Route("api/[controller]")]
[OpenApiTag("Section", Description = "Section management")]
public class SectionController : ControllerBase
{
private ResourceDatabaseService _resourceService;
private SectionDatabaseService _sectionService;
private ConfigurationDatabaseService _configurationService;
private readonly ILogger<SectionController> _logger;
private readonly IConfiguration _configuration;
public SectionController(IConfiguration configuration, ILogger<SectionController> logger, SectionDatabaseService sectionService, ConfigurationDatabaseService configurationService, ResourceDatabaseService resourceService)
{
_logger = logger;
_configuration = configuration;
_resourceService = resourceService;
_sectionService = sectionService;
_configurationService = configurationService;
}
/// <summary>
/// Get a list of all section (summary)
/// </summary>
/// <param name="id">id instance</param>
[ProducesResponseType(typeof(List<SectionDTO>), 200)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet]
public ObjectResult Get([FromQuery] string instanceId)
{
try
{
List<Section> sections = _sectionService.GetAll(instanceId);
/* CLEAN ARTICLE AUDIO - Init new field AudioIds */
/*foreach (var article in sections.Where(s => s.Type == SectionType.Article))
{
try
{
ArticleDTO articleDTO = JsonConvert.DeserializeObject<ArticleDTO>(article.Data);
List<string> languages = _configuration.GetSection("SupportedLanguages").Get<List<string>>();
articleDTO.audioIds = LanguageInit.Init("Audio", languages, true);
article.Data = JsonConvert.SerializeObject(articleDTO); // Include all info from specific section as JSON
Section sectionModified = _sectionService.Update(article.Id, article);
}
catch (Exception ex)
{
}
}*/
return new OkObjectResult(sections.Select(r => r.ToDTO()));
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a list of all section from a specific configuration
/// </summary>
/// <param name="id">configuration id</param>
[AllowAnonymous]
[ProducesResponseType(typeof(List<SectionDTO>), 200)]
[ProducesResponseType(typeof(string), 500)]
[ProducesResponseType(typeof(string), 400)]
[HttpGet("configuration/{id}")]
public ObjectResult GetFromConfiguration(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("Param is null");
if (_configurationService.IsExist(id))
{
List<Section> sections = _sectionService.GetAllFromConfiguration(id);
return new OkObjectResult(sections.Select(r => r.ToDTO()));
}
else
return new NotFoundObjectResult("Configuration not found");
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Delete all section from a specific configuration
/// </summary>
/// <param name="id">configuration id</param>
[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 500)]
[ProducesResponseType(typeof(string), 400)]
[HttpDelete("configuration/{id}")]
public ObjectResult DeleteAllForConfiguration(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("Param is null");
_sectionService.DeleteAllFromConfiguration(id);
return new ObjectResult("All section from the specified configuration has been deleted") { StatusCode = 202 };
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a list of all subsection (summary) of a specific section
/// </summary>
/// <param name="id">section id</param>
[ProducesResponseType(typeof(List<object>), 200)]
[ProducesResponseType(typeof(string), 500)]
[ProducesResponseType(typeof(string), 400)]
[HttpGet("{id}/subsections")]
public ObjectResult GetAllSectionSubSections(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("Param is null");
List<Section> sections = _sectionService.GetAllSubSection(id);
return new OkObjectResult(sections.Select(r => r.ToDTO()));
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a specific section
/// </summary>
/// <param name="id">section id</param>
[AllowAnonymous]
[ProducesResponseType(typeof(SectionDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}")]
public ObjectResult GetDetail(string id)
{
try
{
Section section = _sectionService.GetById(id);
if (section == null)
throw new KeyNotFoundException("This section was not found");
return new OkObjectResult(section.ToDTO());
/*switch (section.Type) {
case SectionType.Map:
MapDTO mapDTO = JsonConvert.DeserializeObject<MapDTO>(section.Data);
mapDTO.Id = section.Id;
mapDTO.Label = section.Label;
mapDTO.Description = section.Description;
mapDTO.Type = section.Type;
mapDTO.ImageId = section.ImageId;
mapDTO.IsSubSection = section.IsSubSection;
mapDTO.DateCreation = section.DateCreation;
mapDTO.Data = section.Data;
return new OkObjectResult(mapDTO);
case SectionType.Slider:
SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.Data);
sliderDTO.Id = section.Id;
sliderDTO.Label = section.Label;
sliderDTO.Description = section.Description;
sliderDTO.Type = section.Type;
sliderDTO.ImageId = section.ImageId;
sliderDTO.IsSubSection = section.IsSubSection;
sliderDTO.DateCreation = section.DateCreation;
sliderDTO.Data = section.Data;
return new OkObjectResult(section.ToDTO());
case SectionType.Menu:
return new OkObjectResult(section.ToDTO());
case SectionType.Web:
return new OkObjectResult(section.ToDTO());
case SectionType.Video:
return new OkObjectResult(section.ToDTO());
default:
return new OkObjectResult(section.ToDTO());
}*/
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get all section with beacon
/// </summary>
/// <param name="instanceId">Instance id</param>
[AllowAnonymous]
[ProducesResponseType(typeof(List<SectionDTO>), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("beacons/{instanceId}")]
public ObjectResult GetAllBeaconsForInstance(string instanceId)
{
try
{
List<Section> sections = _sectionService.GetAll(instanceId);
sections = sections.Where(s => s.IsBeacon && s.BeaconId != null).ToList();
return new OkObjectResult(sections.Select(s => s.ToDTO()));
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Create a new section
/// </summary>
/// <param name="newSection">New section info</param>
[ProducesResponseType(typeof(SectionDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost()]
public ObjectResult Create([FromBody] SectionDTO newSection)
{
try
{
if (newSection == null)
throw new ArgumentNullException("Section param is null");
if (newSection.configurationId == null)
throw new ArgumentNullException("Configuration param is null");
if (!_configurationService.IsExist(newSection.configurationId) )
throw new KeyNotFoundException("Configuration does not exist");
// Todo add some verification ?
Section section = new Section();
section.InstanceId = newSection.instanceId;
section.Label = newSection.label;
section.ImageId = newSection.imageId;
section.ImageSource = newSection.imageSource;
section.ConfigurationId = newSection.configurationId;
section.DateCreation = DateTime.Now;
section.IsSubSection = newSection.isSubSection;
section.ParentId = newSection.parentId;
section.Type = newSection.type;
section.Title = new List<TranslationDTO>();
section.Description = new List<TranslationDTO>();
section.Order = _sectionService.GetAllFromConfiguration(newSection.configurationId).Count;
section.IsBeacon = newSection.isBeacon;
section.BeaconId = newSection.beaconId;
section.Latitude = newSection.latitude;
section.Longitude = newSection.longitude;
section.MeterZoneGPS = newSection.meterZoneGPS;
// Preparation
List<string> languages = _configuration.GetSection("SupportedLanguages").Get<List<string>>();
var contentArticle = new List<TranslationDTO>();
var mapDTO = new MapDTO(); // For menu dto
var sliderDTO = new SliderDTO(); // For menu dto
section.Title = LanguageInit.Init("Title", languages);
section.Description = LanguageInit.Init("Description", languages);
contentArticle = LanguageInit.Init("Content", languages);
/*foreach (var language in languages)
{
TranslationDTO title = new TranslationDTO();
TranslationDTO description = new TranslationDTO();
TranslationDTO content = new TranslationDTO();
title.language = language.ToUpper();
description.language = language.ToUpper();
content.language = language.ToUpper();
switch (language.ToUpper())
{
case "FR":
title.value = "Titre en français";
description.value = "Description en français";
content.value = "Contenu en français";
break;
case "EN":
title.value = "Title in english";
description.value = "Description en anglais";
content.value = "Contenu en anglais";
break;
case "NL":
title.value = "Titre in dutch";
description.value = "Description en néerlandais";
content.value = "Contenu en néerlandais";
break;
case "DE":
title.value = "Titre en allemand";
description.value = "Description en allemand";
content.value = "Contenu en allemand";
break;
}
section.Title.Add(title);
section.Description.Add(description);
contentArticle.Add(content);
}*/
section.Title = section.Title.OrderBy(t => t.language).ToList();
section.Description = section.Description.OrderBy(d => d.language).ToList();
switch (newSection.type) {
case SectionType.Map:
mapDTO = new MapDTO();
mapDTO.mapType = MapTypeApp.hybrid;
mapDTO.mapTypeMapbox = MapTypeMapBox.standard;
mapDTO.mapProvider = MapProvider.Google;
mapDTO.zoom = 18;
mapDTO.points = new List<GeoPointDTO>();
mapDTO.categories = new List<CategorieDTO>();
section.Data = JsonConvert.SerializeObject(mapDTO); // Include all info from specific section as JSON
break;
case SectionType.Slider:
sliderDTO = new SliderDTO();
sliderDTO.contents = new List<ContentDTO>();
section.Data = JsonConvert.SerializeObject(sliderDTO); // Include all info from specific section as JSON
break;
case SectionType.Video:
VideoDTO videoDTO = new VideoDTO();
videoDTO.source = "";
section.Data = JsonConvert.SerializeObject(videoDTO); // Include all info from specific section as JSON
break;
case SectionType.Web:
WebDTO webDTO = new WebDTO();
webDTO.source = "";
section.Data = JsonConvert.SerializeObject(webDTO); // Include all info from specific section as JSON
break;
case SectionType.Menu:
MenuDTO menuDTO = new MenuDTO();
menuDTO.sections = new List<SectionDTO>();
/*SectionDTO section0DTO = new SectionDTO();
section0DTO.IsSubSection = true;
section0DTO.Label = newSection.Label;
section0DTO.ImageId = newSection.ImageId;
section0DTO.ConfigurationId = newSection.ConfigurationId;
section0DTO.DateCreation = DateTime.Now;
section0DTO.ParentId = null;
section0DTO.Type = SectionType.Map;
section0DTO.Data = JsonConvert.SerializeObject(mapDTO);
SectionDTO section1DTO = new SectionDTO();
section0DTO.IsSubSection = true;
section0DTO.Label = newSection.Label;
section0DTO.ImageId = newSection.ImageId;
section0DTO.ConfigurationId = newSection.ConfigurationId;
section0DTO.DateCreation = DateTime.Now;
section0DTO.ParentId = null;
section0DTO.Type = SectionType.Slider;
section1DTO.IsSubSection = true;
section1DTO.Data = JsonConvert.SerializeObject(sliderDTO);*/
/*menuDTO.Sections.Add(section0DTO);
menuDTO.Sections.Add(section1DTO);*/
section.Data = JsonConvert.SerializeObject(menuDTO); // Include all info from specific section as JSON
break;
case SectionType.Quizz:
QuizzDTO quizzDTO = new QuizzDTO();
quizzDTO.questions = new List<QuestionDTO>();
section.Data = JsonConvert.SerializeObject(quizzDTO); // Include all info from specific section as JSON
break;
case SectionType.Article:
ArticleDTO articleDTO = new ArticleDTO();
articleDTO.contents = new List<ContentDTO>();
articleDTO.content = contentArticle;
articleDTO.audioIds = LanguageInit.Init("Audio", languages, true);
section.Data = JsonConvert.SerializeObject(articleDTO); // Include all info from specific section as JSON
break;
case SectionType.PDF:
PdfDTO pdfDTO = new PdfDTO();
section.Data = JsonConvert.SerializeObject(pdfDTO); // Include all info from specific section as JSON
break;
case SectionType.Puzzle:
PuzzleDTO puzzleDTO = new PuzzleDTO();
section.Data = JsonConvert.SerializeObject(puzzleDTO); // Include all info from specific section as JSON
break;
case SectionType.Agenda:
AgendaDTO agendaDTO = new AgendaDTO();
section.Data = JsonConvert.SerializeObject(agendaDTO); // Include all info from specific section as JSON
break;
case SectionType.Weather:
WeatherDTO weatherDTO = new WeatherDTO();
section.Data = JsonConvert.SerializeObject(weatherDTO); // Include all info from specific section as JSON
break;
}
Section sectionCreated = _sectionService.Create(section);
return new OkObjectResult(sectionCreated.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>
/// Create a new section - slider
/// </summary>
/// <param name="newSection">New section info - slider</param>
[ProducesResponseType(typeof(SliderDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost("Slider")]
public ObjectResult CreateSlider([FromBody] SliderDTO newSectionSlider)
{
try
{
if (newSectionSlider == null)
throw new ArgumentNullException("Section param is null");
// Todo add some verification ?
Slider sliderSection = new Slider();
sliderSection.Label = newSectionSlider.Label;
sliderSection.ImageId = newSectionSlider.ImageId;
sliderSection.DateCreation = DateTime.Now;
sliderSection.IsSubSection = false;
sliderSection.ParentId = null;
sliderSection.Type = SectionType.Slider;
sliderSection.Images = newSectionSlider.Images.Select(p =>
new Image()
{
Title = p.Title,
Description = p.Description,
Source = p.Source,
}).ToList();
Slider sectionCreated = _sectionService.CreateSlider(sliderSection);
return new OkObjectResult(sectionCreated.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 section
/// </summary>
/// <param name="updatedSection">Section to update</param>
[ProducesResponseType(typeof(SectionDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut]
public ObjectResult Update([FromBody] SectionDTO updatedSection)
{
try
{
if (updatedSection == null)
throw new ArgumentNullException("Section param is null");
Section section = _sectionService.GetById(updatedSection.id);
if (section == null)
throw new KeyNotFoundException("Section does not exist");
// Todo add some verification ?
section.InstanceId = updatedSection.instanceId;
section.Label = updatedSection.label;
section.Title = updatedSection.title;
section.Description = updatedSection.description;
section.Type = updatedSection.type;
section.ImageId = updatedSection.imageId;
section.ImageSource = updatedSection.imageSource;
section.ConfigurationId = updatedSection.configurationId;
section.IsSubSection = updatedSection.isSubSection;
section.ParentId = updatedSection.parentId;
section.Data = updatedSection.data;
section.IsBeacon = updatedSection.isBeacon;
section.BeaconId = updatedSection.beaconId;
section.Latitude = updatedSection.latitude;
section.Longitude = updatedSection.longitude;
section.MeterZoneGPS = updatedSection.meterZoneGPS;
Section sectionModified = _sectionService.Update(updatedSection.id, section);
MqttClientService.PublishMessage($"config/{sectionModified.ConfigurationId}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));
return new OkObjectResult(sectionModified.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>
/// Update sections order
/// </summary>
/// <param name="updatedSectionsOrder">New sections order</param>
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut("order")]
public ObjectResult UpdateOrder([FromBody] List<SectionDTO> updatedSectionsOrder)
{
try
{
if (updatedSectionsOrder == null)
throw new ArgumentNullException("Sections param is null");
foreach (var section in updatedSectionsOrder)
{
if (!_sectionService.IsExist(section.id))
throw new KeyNotFoundException($"Section {section.label} with id {section.id} does not exist");
}
foreach (var updatedSection in updatedSectionsOrder)
{
Section section = _sectionService.GetById(updatedSection.id);
section.Order = updatedSection.order.GetValueOrDefault();
_sectionService.Update(section.Id, section);
}
if (updatedSectionsOrder.Count > 0) {
MqttClientService.PublishMessage($"config/{updatedSectionsOrder[0].configurationId}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));
}
return new ObjectResult("Sections order has been successfully modified") { StatusCode = 200 };
}
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 section
/// </summary>
/// <param name="id">Id of section 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("Section param is null");
if (!_sectionService.IsExist(id))
throw new KeyNotFoundException("Section does not exist");
_sectionService.Remove(id);
return new ObjectResult("The section 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>
/// Update section image url order
/// </summary>
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut("imageURL")]
public ObjectResult UpdateImageURL()
{
try
{
List<Section> sections = _sectionService.GetAll("65ccc67265373befd15be511"); // get by instance ID (hardcoded MDLF)
foreach (var section in sections)
{
section.ImageSource = CheckAndUpdateURL(section.ImageSource, _resourceService);
switch (section.Type)
{
case SectionType.Map:
var mapSection = JsonConvert.DeserializeObject<MapDTO>(section.Data);
mapSection.iconSource = CheckAndUpdateURL(mapSection.iconSource, _resourceService);
foreach (var point in mapSection.points)
{
point.imageUrl = CheckAndUpdateURL(point.imageUrl, _resourceService);
foreach (var content in point.contents)
{
content.resourceUrl = CheckAndUpdateURL(content.resourceUrl, _resourceService);
}
}
section.Data = JsonConvert.SerializeObject(mapSection); // Include all info from specific section as JSON
break;
case SectionType.Slider:
var sliderData = JsonConvert.DeserializeObject<SliderDTO>(section.Data);
foreach (var content in sliderData.contents)
{
content.resourceUrl = CheckAndUpdateURL(content.resourceUrl, _resourceService);
}
section.Data = JsonConvert.SerializeObject(sliderData); // Include all info from specific section as JSON
break;
case SectionType.Video:
break;
case SectionType.Web:
break;
case SectionType.Quizz:
var quizData = JsonConvert.DeserializeObject<QuizzDTO>(section.Data);
foreach (var badLevelLabel in quizData.bad_level.label)
{
badLevelLabel.resourceUrl = CheckAndUpdateURL(badLevelLabel.resourceUrl, _resourceService);
}
foreach (var mediumLevelLabel in quizData.medium_level.label)
{
mediumLevelLabel.resourceUrl = CheckAndUpdateURL(mediumLevelLabel.resourceUrl, _resourceService);
}
foreach (var goodLevelLabel in quizData.good_level.label)
{
goodLevelLabel.resourceUrl = CheckAndUpdateURL(goodLevelLabel.resourceUrl, _resourceService);
}
foreach (var greatLevelLabel in quizData.great_level.label)
{
greatLevelLabel.resourceUrl = CheckAndUpdateURL(greatLevelLabel.resourceUrl, _resourceService);
}
foreach (var question in quizData.questions)
{
question.imageBackgroundResourceUrl = CheckAndUpdateURL(question.imageBackgroundResourceUrl, _resourceService);
foreach (var labelQuestion in question.label)
{
labelQuestion.resourceUrl = CheckAndUpdateURL(labelQuestion.resourceUrl, _resourceService);
}
foreach (var labelResponse in question.responses)
{
foreach (var LabelResponseLabel in labelResponse.label)
{
LabelResponseLabel.resourceUrl = CheckAndUpdateURL(LabelResponseLabel.resourceUrl, _resourceService);
}
}
}
section.Data = JsonConvert.SerializeObject(quizData); // Include all info from specific section as JSON
break;
case SectionType.Menu:
break;
}
// Update DB
//_sectionService.Update(section.Id, section);
}
return new ObjectResult("OK, done") { StatusCode = 200 };
}
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 };
}
}
private string CheckAndUpdateURL(string sourceURL, ResourceDatabaseService resourceDatabaseService)
{
if (sourceURL != null && (sourceURL.Contains("192.168.1.19") || sourceURL.Contains("localhost")))
{
if (sourceURL.Contains("localhost"))
{
}
string[] segments = sourceURL.Split('/');
string sourceIDFromURL = segments[segments.Length - 1];
Resource resource = resourceDatabaseService.GetById(sourceIDFromURL);
return resource != null ? resource.Url : sourceURL;
} else return sourceURL;
}
/// <summary>
/// Create a new sections from json
/// </summary>
/// <param name="newSection">New section info</param>
[ProducesResponseType(typeof(SectionDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost("json")]
public ObjectResult CreateFromJSON()
{
try
{
string json = System.IO.File.ReadAllText("C:/Users/ThomasFransolet/Documents/Documents/Perso/MuseeDeLaFraise/Aout 2024/TabletDb.Sections.json");
var sections = JsonConvert.DeserializeObject<SectionDTO[]>(json);
foreach (var sectionJSON in sections)
{
// Todo add some verification ?
Section section = new Section();
section.Id = sectionJSON.id;
section.InstanceId = "65ccc67265373befd15be511"; // MDLF hardcoded
section.Label = sectionJSON.label;
section.ImageId = sectionJSON.imageId;
section.ImageSource = sectionJSON.imageSource;
section.ConfigurationId = sectionJSON.configurationId;
section.DateCreation = sectionJSON.dateCreation;
section.IsSubSection = sectionJSON.isSubSection;
section.ParentId = sectionJSON.parentId;
section.Type = sectionJSON.type;
section.Title = sectionJSON.title;
section.Description = sectionJSON.description;
section.Order = _sectionService.GetAllFromConfiguration(section.ConfigurationId).Count;
section.IsBeacon = false;
// Preparation
//List<string> languages = _configuration.GetSection("SupportedLanguages").Get<List<string>>();
var contentArticle = new List<TranslationDTO>();
/*section.Title = LanguageInit.Init("Title", languages);
section.Description = LanguageInit.Init("Description", languages);
contentArticle = LanguageInit.Init("Content", languages);
section.Title = section.Title.OrderBy(t => t.language).ToList();
section.Description = section.Description.OrderBy(d => d.language).ToList();*/
switch (section.Type)
{
case SectionType.Map:
var sectionDataMap = JsonConvert.DeserializeObject<MapDTO>(sectionJSON.data);
var mapDTO = new MapDTO();
mapDTO.mapType = sectionDataMap.mapType;
mapDTO.mapProvider = MapProvider.Google;
mapDTO.zoom = sectionDataMap.zoom;
mapDTO.iconSource = sectionDataMap.iconSource;
mapDTO.iconResourceId = sectionDataMap.iconResourceId;
//mapDTO.points = sectionDataMap.points ?? new List<GeoPointDTO>();
List<GeoPointDTO> geoPoints = new List<GeoPointDTO>();
JObject sectionMapp = JObject.Parse(sectionJSON.data);
foreach (var point in sectionMapp["points"])
{
GeoPointDTO pointDTO = new GeoPointDTO();
pointDTO.id = (int)point["id"];
pointDTO.latitude = (string)point["latitude"];
pointDTO.longitude = (string)point["longitude"];
pointDTO.title = JsonConvert.DeserializeObject<List<TranslationDTO>>(point["title"].ToString());
pointDTO.description = JsonConvert.DeserializeObject<List<TranslationDTO>>(point["description"].ToString());
List<ContentGeoPoint> contents = new List<ContentGeoPoint>();
foreach (var image in point["images"])
{
ContentGeoPoint contentDTO = new ContentGeoPoint();
contentDTO.resourceType = ResourceType.Image; // ce n'est que des images..
contentDTO.resourceId = (string)image["imageResourceId"];
contentDTO.resourceUrl = (string)image["imageSource"];
contents.Add(contentDTO);
}
pointDTO.contents = contents;
geoPoints.Add(pointDTO);
}
mapDTO.points = geoPoints;
mapDTO.categories = new List<CategorieDTO>();
section.Data = JsonConvert.SerializeObject(mapDTO); // Include all info from specific section as JSON
break;
case SectionType.Slider:
//var sectionSlider = JsonConvert.DeserializeObject(sectionJSON.data);
var sliderDTO = new SliderDTO();
JObject sectionSlider = JObject.Parse(sectionJSON.data);
List<ContentDTO> newContents = new List<ContentDTO>();
if (sectionSlider["images"].Count() > 0)
{
}
foreach (var image in sectionSlider["images"])
{
ContentDTO newContent = new ContentDTO();
int order = (int)image["order"];
string resourceId = (string)image["resourceId"];
string source = (string)image["source"];
newContent.order = order;
newContent.resourceId = resourceId;
newContent.resourceUrl = source;
newContent.resourceType = ResourceType.Image; // ONLY IMAGE WAS POSSIBLE
newContent.title = JsonConvert.DeserializeObject<List<TranslationDTO>>(image["title"].ToString());
newContent.description = JsonConvert.DeserializeObject<List<TranslationDTO>>(image["description"].ToString());
newContents.Add(newContent);
}
sliderDTO.contents = newContents;
section.Data = JsonConvert.SerializeObject(sliderDTO); // Include all info from specific section as JSON
break;
case SectionType.Video:
var sectionVideo = JsonConvert.DeserializeObject<VideoDTO>(sectionJSON.data);
VideoDTO videoDTO = new VideoDTO();
videoDTO.source = sectionVideo.source;
section.Data = JsonConvert.SerializeObject(videoDTO); // Include all info from specific section as JSON
break;
case SectionType.Web:
var sectionWeb = JsonConvert.DeserializeObject<WebDTO>(sectionJSON.data);
WebDTO webDTO = new WebDTO();
webDTO.source = sectionWeb.source;
section.Data = JsonConvert.SerializeObject(webDTO); // Include all info from specific section as JSON
break;
case SectionType.Menu:
var sectionMenu = JsonConvert.DeserializeObject<MenuDTO>(sectionJSON.data);
MenuDTO menuDTO = new MenuDTO();
menuDTO.sections = sectionMenu.sections;
foreach (var sectionMenuu in menuDTO.sections)
{
sectionMenuu.instanceId = section.InstanceId;
switch (sectionMenuu.type)
{
case SectionType.Map:
var sectionMAPSub = JsonConvert.DeserializeObject<MapDTO>(sectionMenuu.data);
var mapDTOSUB = new MapDTO();
mapDTOSUB.mapType = sectionMAPSub.mapType;
mapDTOSUB.mapProvider = MapProvider.Google;
mapDTOSUB.zoom = sectionMAPSub.zoom;
mapDTOSUB.iconSource = sectionMAPSub.iconSource;
mapDTOSUB.iconResourceId = sectionMAPSub.iconResourceId;
List<GeoPointDTO> geoPointsSUB = new List<GeoPointDTO>();
JObject sectionMappSUB = JObject.Parse(sectionMenuu.data);
foreach (var pointSUB in sectionMappSUB["points"])
{
GeoPointDTO pointDTOSUB = new GeoPointDTO();
pointDTOSUB.id = (int)pointSUB["id"];
pointDTOSUB.latitude = (string)pointSUB["latitude"];
pointDTOSUB.longitude = (string)pointSUB["longitude"];
pointDTOSUB.title = JsonConvert.DeserializeObject<List<TranslationDTO>>(pointSUB["title"].ToString());
pointDTOSUB.description = JsonConvert.DeserializeObject<List<TranslationDTO>>(pointSUB["description"].ToString());
List<ContentGeoPoint> contentsSUB = new List<ContentGeoPoint>();
foreach (var imageSUB in pointSUB["images"])
{
ContentGeoPoint contentDTOSUB = new ContentGeoPoint();
contentDTOSUB.resourceType = ResourceType.Image; // ce n'est que des images..
contentDTOSUB.resourceId = (string)imageSUB["imageResourceId"];
contentDTOSUB.resourceUrl = (string)imageSUB["imageSource"];
contentsSUB.Add(contentDTOSUB);
}
pointDTOSUB.contents = contentsSUB;
geoPointsSUB.Add(pointDTOSUB);
}
mapDTOSUB.points = geoPointsSUB;
mapDTOSUB.categories = new List<CategorieDTO>();
section.Data = JsonConvert.SerializeObject(mapDTOSUB); // Include all info from specific section as JSON
break;
case SectionType.Slider:
var sliderDTOSUB = new SliderDTO();
JObject sliderSUB = JObject.Parse(sectionMenuu.data);
List<ContentDTO> newContentsSUB = new List<ContentDTO>();
foreach (var image in sliderSUB["images"])
{
ContentDTO newContentSUB = new ContentDTO();
int order = (int)image["order"];
string resourceId = (string)image["resourceId"];
string source = (string)image["source"]; // TODO REPLACE SOURCE.. UPLOAD TO FIREBASE WHEN UPLOAD RESSOURCE FROM JSON..
newContentSUB.order = order;
newContentSUB.resourceId = resourceId;
newContentSUB.resourceUrl = source;
newContentSUB.resourceType = ResourceType.Image; // ONLY IMAGE WAS POSSIBLE
newContentSUB.title = JsonConvert.DeserializeObject<List<TranslationDTO>>(image["title"].ToString());
newContentSUB.description = JsonConvert.DeserializeObject<List<TranslationDTO>>(image["description"].ToString());
newContentsSUB.Add(newContentSUB);
}
sliderDTOSUB.contents = newContentsSUB;
sectionMenuu.data = JsonConvert.SerializeObject(sliderDTOSUB);
break;
case SectionType.Video:
var sectionVideoSUB = JsonConvert.DeserializeObject<VideoDTO>(sectionMenuu.data);
VideoDTO videoDTOSUB = new VideoDTO();
videoDTOSUB.source = sectionVideoSUB.source;
section.Data = JsonConvert.SerializeObject(videoDTOSUB); // Include all info from specific section as JSON
break;
case SectionType.Web:
var sectionWebSUB = JsonConvert.DeserializeObject<WebDTO>(sectionMenuu.data);
WebDTO webDTOSUB = new WebDTO();
webDTOSUB.source = sectionWebSUB.source;
section.Data = JsonConvert.SerializeObject(webDTOSUB); // Include all info from specific section as JSON
break;
case SectionType.Quizz:
var sectionSUBQuizz = JsonConvert.DeserializeObject<QuizzDTO>(sectionMenuu.data);
var quizzSUBDTO = new QuizzDTO();
quizzSUBDTO.questions = sectionSUBQuizz.questions;
quizzSUBDTO.bad_level = sectionSUBQuizz.bad_level;
quizzSUBDTO.medium_level = sectionSUBQuizz.medium_level;
quizzSUBDTO.good_level = sectionSUBQuizz.medium_level;
quizzSUBDTO.great_level = sectionSUBQuizz.great_level;
sectionMenuu.data = JsonConvert.SerializeObject(quizzSUBDTO); // Include all info from specific section as JSON
break;
}
}
section.Data = JsonConvert.SerializeObject(menuDTO); // Include all info from specific section as JSON
break;
case SectionType.Quizz:
var sectionQuizz = JsonConvert.DeserializeObject<QuizzDTO>(sectionJSON.data);
QuizzDTO quizzDTO = new QuizzDTO();
quizzDTO.questions = sectionQuizz.questions;
quizzDTO.bad_level = sectionQuizz.bad_level;
quizzDTO.medium_level = sectionQuizz.medium_level;
quizzDTO.good_level = sectionQuizz.medium_level;
quizzDTO.great_level = sectionQuizz.great_level;
section.Data = JsonConvert.SerializeObject(quizzDTO); // Include all info from specific section as JSON
break;
// NEW CONTENTS AFTER MDLF
case SectionType.Article:
ArticleDTO articleDTO = new ArticleDTO();
articleDTO.contents = new List<ContentDTO>();
articleDTO.content = contentArticle;
//articleDTO.audioIds = LanguageInit.Init("Audio", languages, true);
section.Data = JsonConvert.SerializeObject(articleDTO); // Include all info from specific section as JSON
break;
case SectionType.PDF:
PdfDTO pdfDTO = new PdfDTO();
section.Data = JsonConvert.SerializeObject(pdfDTO); // Include all info from specific section as JSON
break;
case SectionType.Puzzle:
PuzzleDTO puzzleDTO = new PuzzleDTO();
section.Data = JsonConvert.SerializeObject(puzzleDTO); // Include all info from specific section as JSON
break;
case SectionType.Agenda:
AgendaDTO agendaDTO = new AgendaDTO();
section.Data = JsonConvert.SerializeObject(agendaDTO); // Include all info from specific section as JSON
break;
case SectionType.Weather:
WeatherDTO weatherDTO = new WeatherDTO();
section.Data = JsonConvert.SerializeObject(weatherDTO); // Include all info from specific section as JSON
break;
}
//Section sectionCreated = _sectionService.Create(section);
}
return new OkObjectResult(true);
}
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>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(MapDTO), 200)]
[HttpGet("MapDTO")]
public ObjectResult GetMapDTO()
{
return new ObjectResult("MapDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(SliderDTO), 200)]
[HttpGet("SliderDTO")]
public ObjectResult GetSliderDTO()
{
return new ObjectResult("SliderDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(VideoDTO), 200)]
[HttpGet("VideoDTO")]
public ObjectResult GetVideoDTO()
{
return new ObjectResult("VideoDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(WebDTO), 200)]
[HttpGet("WebDTO")]
public ObjectResult GetWebDTO()
{
return new ObjectResult("WebDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(MenuDTO), 200)]
[HttpGet("MenuDTO")]
public ObjectResult GetMenuDTO()
{
return new ObjectResult("MenuDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(PlayerMessageDTO), 200)]
[HttpGet("PlayerMessageDTO")]
public ObjectResult PlayerMessageDTO()
{
return new ObjectResult("PlayerMessageDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(QuizzDTO), 200)]
[HttpGet("QuizzDTO")]
public ObjectResult GetQuizzDTO()
{
return new ObjectResult("QuizzDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(ArticleDTO), 200)]
[HttpGet("ArticleDTO")]
public ObjectResult GetArticleDTO()
{
return new ObjectResult("ArticleDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(PdfDTO), 200)]
[HttpGet("PdfDTO")]
public ObjectResult GetPdfDTO()
{
return new ObjectResult("PdfDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(PuzzleDTO), 200)]
[HttpGet("PuzzleDTO")]
public ObjectResult GetPuzzleDTO()
{
return new ObjectResult("PuzzleDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(AgendaDTO), 200)]
[HttpGet("AgendaDTO")]
public ObjectResult GetAgendaDTO()
{
return new ObjectResult("AgendaDTO") { StatusCode = 200 };
}
/// <summary>
/// Useless, just to generate dto code
/// </summary>
[ProducesResponseType(typeof(WeatherDTO), 200)]
[HttpGet("WeatherDTO")]
public ObjectResult GetWeatherDTO()
{
return new ObjectResult("WeatherDTO") { StatusCode = 200 };
}
}
}