Compare commits

...

74 Commits

Author SHA1 Message Date
Thomas Fransolet
4ee0eb8e87 Code for fort migration 2024-10-11 16:39:33 +02:00
Thomas Fransolet
aedd5f33fa Added methods for mdlf migration in MyInfomate + firebase service (linked) 2024-08-16 16:59:31 +02:00
Thomas Fransolet
9ff5a7fec8 fix issue 2024-04-24 15:23:34 +02:00
Thomas Fransolet
c237c69c56 Added main image to geopoint + localication center to mapDTO 2024-04-18 17:13:27 +02:00
Thomas Fransolet
1fa4e188fa Update weather result (in all configuration's section) 2024-04-11 17:37:10 +02:00
Thomas Fransolet
68b45333da Update weather section on get configuration detail 2024-04-10 17:15:10 +02:00
Thomas Fransolet
b87256e29d Added id to categorie to fix bug 2024-04-10 11:34:24 +02:00
Thomas Fransolet
0ccfda46a1 Update default IsSectionImageBackground default value 2024-04-10 10:37:01 +02:00
Thomas Fransolet
747ce5f064 missing files 2024-04-10 09:20:59 +02:00
Thomas Fransolet
1db418e708 Added WeatherDTO + fix export issue + config layout values (rounded, isPictureBackground and ScreenPercentage) + values for mapDTO 2024-04-10 09:20:51 +02:00
Thomas Fransolet
b5a3336670 Export fix 2024-03-21 16:02:31 +01:00
Thomas Fransolet
fe48dddce2 Update section objects to support multiple PDF at once + MapBox in Map + MapProvider in Agenda 2024-03-12 22:49:32 +01:00
Thomas Fransolet
466c18a6b2 fix issue 2024-03-08 17:17:41 +01:00
Thomas Fransolet
2421ce6fa5 fix issues 2024-02-28 16:47:39 +01:00
Thomas Fransolet
aa25e0d4a0 Update agenda (multiple languages) 2024-02-28 11:56:53 +01:00
Thomas Fransolet
8cd69c7d8b Add weather result 2024-02-24 22:42:41 +01:00
Thomas Fransolet
78f402a840 Fix hash issue 2024-02-14 14:57:09 +01:00
Thomas Fransolet
8825795ff5 Add loader image in export 2024-01-26 16:53:26 +01:00
Thomas Fransolet
52e5d85d2e Add resourceId to export (pdf and agenda) 2024-01-26 15:11:42 +01:00
Thomas Fransolet
b193763e73 Added weather fields + Added JSONUrl resourceType 2024-01-23 17:49:31 +01:00
Thomas Fransolet
4d85ad7c86 update packages + fix bug 2024-01-19 15:13:31 +01:00
Thomas Fransolet
b91bf7921b Add rows and cols for PuzzleDTO 2023-12-29 14:05:55 +01:00
Thomas Fransolet
4954d2ce44 Add order to CategorieDTO 2023-12-27 17:39:02 +01:00
Thomas Fransolet
2e62983375 Rename in categorieDTO 2023-12-27 15:56:24 +01:00
Thomas Fransolet
22ffe09dd8 Add TranslationAndResource 2023-12-27 15:06:31 +01:00
Thomas Fransolet
9f1740c129 Update service DTOs 2023-12-27 11:08:56 +01:00
Thomas Fransolet
53cf5509d4 Add handling PDF, Puzzle and Agenda subsection type 2023-12-26 15:49:57 +01:00
Thomas Fransolet
ab562f886c Add isHour, IsDate to config + Resource to response in quizz 2023-12-26 11:42:10 +01:00
Thomas Fransolet
27e20568d8 Clean 2023-12-22 15:59:41 +01:00
Thomas Fransolet
04c6e01e50 Add loader image + weather city to configuration + clean config 2023-12-22 15:25:13 +01:00
Thomas Fransolet
cc89f7b717 redirect to 1.2.0 + update entities and other for visitNamur 2023-12-15 17:00:07 +01:00
Thomas Fransolet
17f9cd2334 Update all object to visitNamur request 2023-12-14 17:49:07 +01:00
Thomas Fransolet
369b789abb WIP add Agenda, pdf, puzzle objects 2023-12-09 23:53:31 +01:00
Thomas Fransolet
2866c12985 Add MQTT events 2023-12-05 15:40:51 +01:00
Thomas Fransolet
0b0b54c6af Add pinCode to TokenDTO 2023-12-05 14:08:00 +01:00
Thomas Fransolet
eb0263dee8 Fix mqtt credentials 2023-11-30 17:09:50 +01:00
Thomas Fransolet
1e31ebe094 Add pinCode to instance + endpoints 2023-11-30 15:42:18 +01:00
19d84b4417 Configurations orderBy date creation 2023-03-30 16:59:55 +02:00
eb50590684 Update file download (add file name) + update max audio and other file size 2023-03-10 19:46:37 +01:00
f5921180cf Clean GetAllBeaconsForInstance accept return empty list 2023-02-20 14:43:35 +01:00
33f782346b Add nullable int beaconId + ensure ressource has no duplicate 2023-02-17 16:53:24 +01:00
042949ec60 BeaconId string to int 2023-02-16 18:02:33 +01:00
ca1d71a846 Update for doc 2023-02-15 17:13:42 +01:00
74101d9939 Add sectionIds to ConfigurationDTO 2023-02-15 10:16:18 +01:00
a0b2d5ba9c Update encoding + add from query language 2023-02-10 17:33:59 +01:00
88ab87c9ee Add audio in export configuration 2023-02-10 17:06:23 +01:00
52ec413761 Add get beacons method 2023-01-28 01:23:35 +01:00
006aa541cd Fix image url not working 2023-01-27 21:10:15 +01:00
52d5467b85 Add watermark and shrink images only if fort 2023-01-26 17:09:48 +01:00
63654bdcf9 Allow all file size for image 2023-01-13 17:47:08 +01:00
bdab0dc286 Add support for Arab and Ukrainian 2023-01-12 16:19:51 +01:00
9e8109225a Clean code + add Beacon handling 2022-12-27 21:47:52 +01:00
fc9d38c3c1 Update article to handle multiple audioIds 2022-12-22 14:31:49 +01:00
85ca1368a2 Add resize image + small fixs 2022-12-20 17:34:15 +01:00
3e6439433e Update get ressources endpoint by adding types filter 2022-10-27 13:31:38 +02:00
5b56c677ef Update docker file 2022-10-26 22:18:11 +02:00
cf2d7759de Split resource in Resource and resourceData + Add Audio ResourceType 2022-10-26 17:11:45 +02:00
390852ce4f import => support instanceId + Delete resource, delete imageId and ref for configuration 2022-10-21 17:38:17 +02:00
499065bdb7 Add instanceId to ToSectionDTO and ToResourceDTO + update device controller for instanceId 2022-10-20 16:37:37 +02:00
79be291113 Add instanceId to config, section and resource 2022-10-20 16:09:34 +02:00
3b6c480cc6 Add instance model, dto, controller and service + update other objects and controllers 2022-10-06 17:07:11 +02:00
35e2d8296b Add password verification ! 2022-10-06 15:14:08 +02:00
9328318468 Docker compose mymuseum 2022-09-29 17:56:08 +02:00
ee021510c8 add docker file + change for prod 2022-09-29 16:54:44 +02:00
1725376623 Add title and image to configuration 2022-09-17 22:43:24 +02:00
afdd538a3b Fix Article default value when creation 2022-06-22 18:55:20 +02:00
4f1902984b Add IsTablet and remove Title and Description from Article 2022-06-22 17:01:09 +02:00
55a612fd0c Add new subsection ArticleDTO + add offline and mobile option 2022-06-11 20:58:43 +02:00
820de792a5 Release 2022-03-29 19:00:09 +02:00
8c2e276d1c Update export to download json file 2022-03-25 17:38:32 +01:00
e5bfed2ff6 Import and export quizzDTO to test ! 2022-03-24 21:47:14 +01:00
e157cd1cb0 Fix delete ressource for quizz 2022-03-24 21:39:35 +01:00
474e9ce719 New realease version 2022-03-23 20:54:40 +01:00
e61b334f02 Add quizz ! 2022-03-19 01:24:17 +01:00
206 changed files with 16395 additions and 173 deletions

View File

@ -22,20 +22,25 @@ namespace Manager.Framework.Business
_logger = logger; _logger = logger;
} }
public bool Authenticate(string email, string password) public void TestPassword(string email, string userPassword, string password)
{ {
if (string.IsNullOrWhiteSpace(email)) if (string.IsNullOrWhiteSpace(email))
{ {
_logger.LogError($"Authenticate error: No e-mail provided"); _logger.LogError($"Authenticate error: No e-mail provided");
throw new UnauthorizedAccessException("Authentication error"); throw new UnauthorizedAccessException("Authentication error");
} }
if (string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(password))
{ {
_logger.LogError($"Authenticate error: No password provided"); _logger.LogError($"Authenticate error: No password provided");
throw new UnauthorizedAccessException("Authentication error"); throw new UnauthorizedAccessException("Authentication error");
} }
return true; if (!PasswordUtils.Compare(userPassword, password, PasswordsPepper))
{
_logger.LogError($"Authenticate error: passwords doesn't match");
throw new UnauthorizedAccessException("Authentication error");
}
} }
/// <summary> /// <summary>

View File

@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
<PackageReference Include="Scrypt.NET" Version="1.3.0" /> <PackageReference Include="Scrypt.NET" Version="1.3.0" />
</ItemGroup> </ItemGroup>

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Xml.Linq;
namespace Manager.Interfaces.DTO namespace Manager.Interfaces.DTO
{ {
@ -8,9 +9,37 @@ namespace Manager.Interfaces.DTO
{ {
public string id { get; set; } public string id { get; set; }
public string label { get; set; } public string label { get; set; }
public List<TranslationDTO> title { get; set; }
public string imageId { get; set; } // == ResourceId
public string imageSource { get; set; } // == Image url
public string primaryColor { get; set; } public string primaryColor { get; set; }
public string secondaryColor { get; set; } public string secondaryColor { get; set; }
public List<string> languages { get; set; } // fr, en, de, nl => Sélection dans une liste déjà établie dans l'application ! public List<string> languages { get; set; } // fr, en, de, nl => Sélection dans une liste déjà établie dans l'application !
public DateTime dateCreation { get; set; } public DateTime dateCreation { get; set; }
public bool isMobile { get; set; } // MyVisit - True if for mobile (MyVisit)
public bool isTablet { get; set; }
public bool isOffline { get; set; } // MyVisit - True if MyVisit is full offline
/*public string latitude { get; set; } // MyVisit - latitude of visit ? (MyVisit)
public string longitude { get; set; } // MyVisit - True if for mobile (MyVisit)*/
public string instanceId { get; set; }
public List<string> sectionIds { get; set; }
public string loaderImageId { get; set; } // == ResourceId
public string loaderImageUrl { get; set; } // == Image url
public string weatherCity { get; set; } // Weather City // TODO REMOVE
public DateTimeOffset? weatherUpdatedDate { get; set; } // Weather date update (to only refresh) // TODO REMOVE
public string weatherResult { get; set; } // Weather result // TODO REMOVE
public bool isWeather // TODO REMOVE
{
get
{
return weatherCity != null && weatherCity.Trim().Length > 0;
}
}
public bool isDate { get; set; }
public bool isHour { get; set; }
public bool isSectionImageBackground { get; set; } // Use to display background for section main image (or not)
public int? roundedValue { get; set; } // Use to set rounded decoration value
public int? screenPercentageSectionsMainPage { get; set; } // Use to set percentage of screen will be used to show sections (base on center)
} }
} }

View File

@ -16,6 +16,7 @@ namespace Manager.Interfaces.DTO
public bool connected{ get; set; } public bool connected{ get; set; }
public DateTime dateCreation{ get; set; } public DateTime dateCreation{ get; set; }
public DateTime dateUpdate { get; set; } public DateTime dateUpdate { get; set; }
public string instanceId { get; set; }
} }
public class DeviceDetailDTO : DeviceDTO public class DeviceDetailDTO : DeviceDTO

View File

@ -1,5 +1,4 @@
using DevExpress.Xpo; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Manager.Interfaces.DTO namespace Manager.Interfaces.DTO

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class InstanceDTO
{
public string id { get; set; }
public string name { get; set; }
public DateTime dateCreation { get; set; }
public int? pinCode { get; set; }
}
}

View File

@ -10,7 +10,17 @@ namespace Manager.Interfaces.DTO
public string id { get; set; } public string id { get; set; }
public ResourceType type { get; set; } public ResourceType type { get; set; }
public string label { get; set; } public string label { get; set; }
public string url { get; set; } // firebase url
public DateTime dateCreation { get; set; } public DateTime dateCreation { get; set; }
public string data { get; set; } public string instanceId { get; set; }
}
public class ResourceOLDDTO
{
public MongoId _id { get; set; }
public ResourceType Type { get; set; }
public string Label { get; set; }
public DateCustom DateCreation { get; set; }
public string InstanceId { get; set; }
} }
} }

View File

@ -1,7 +1,10 @@
using Manager.Interfaces.Models; using Manager.Interfaces.Models;
using MongoDB.Bson.IO;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Manager.Interfaces.DTO namespace Manager.Interfaces.DTO
{ {
@ -19,6 +22,46 @@ namespace Manager.Interfaces.DTO
public SectionType type { get; set; } // !! If IsSubSection == true => Type can't not be menu ! public SectionType type { get; set; } // !! If IsSubSection == true => Type can't not be menu !
public string data { get; set; } // == Include section type info public string data { get; set; } // == Include section type info
public DateTime dateCreation { get; set; } // == Include section type info public DateTime dateCreation { get; set; } // == Include section type info
public int order { get; set; } // Order to show public int? order { get; set; } // Order to show
public string instanceId { get; set; }
public string latitude { get; set; } // MyVisit - Use to launch automatic content when current location is near
public string longitude { get; set; } // MyVisit - Use to launch automatic content when current location is near
public int? meterZoneGPS { get; set; } // MyVisit - Nbr of meters of the zone to launch content
public bool isBeacon { get; set; } // MyVisit - True if section use beacon, false otherwise
public int? beaconId { get; set; } // MyVisit - Beacon' identifier
}
public class SectionForJsonDTO
{
public MongoId _id { get; set; } // Correspond à l'objet _id dans le JSON
public string Label { get; set; } // Correspond à "Label" dans le JSON
public List<TranslationDTO> Title { get; set; } // Correspond à "Title" dans le JSON
public List<TranslationDTO> Description { get; set; } // Correspond à "Description" dans le JSON
public string ImageId { get; set; } // Correspond à "ImageId" dans le JSON
public string ImageSource { get; set; } // Correspond à "ImageSource" dans le JSON
public string ConfigurationId { get; set; } // Correspond à "ConfigurationId" dans le JSON
public bool IsSubSection { get; set; } // Correspond à "IsSubSection" dans le JSON
public string ParentId { get; set; } // Correspond à "ParentId" dans le JSON
public int Type { get; set; } // Correspond à "Type" dans le JSON
public string Data { get; set; } // Correspond à "Data" dans le JSON
public DateCustom DateCreation { get; set; }
public int? Order { get; set; } // Correspond à "Order" dans le JSON
public string InstanceId { get; set; } // Correspond à "InstanceId" dans le JSON
public bool IsBeacon { get; set; } // Correspond à "IsBeacon" dans le JSON
public string BeaconId { get; set; } // Correspond à "BeaconId" dans le JSON
public string Latitude { get; set; } // Correspond à "Latitude" dans le JSON
public string Longitude { get; set; } // Correspond à "Longitude" dans le JSON
public int? MeterZoneGPS { get; set; } // Correspond à "MeterZoneGPS" dans le JSON
}
public class MongoId
{
public string oid { get; set; } // Correspond à "$oid" dans le JSON
}
public class DateCustom
{
public DateTime date { get; set; } // Correspond à "$oid" dans le JSON
} }
} }

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class AgendaDTO
{
public List<TranslationDTO> resourceIds { get; set; } // All json files for all languages
public MapProvider? mapProvider { get; set; } // Default = Google
}
}

View File

@ -0,0 +1,16 @@
using Manager.Interfaces.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class ArticleDTO
{
public List<TranslationDTO> content { get; set; }
public bool isContentTop { get; set; } // MyVisit - True if content is displayed at top, false otherwise
public List<TranslationDTO> audioIds { get; set; }
public bool isReadAudioAuto { get; set; } // MyVisit - True for audio play when open the article / false otherwise
public List<ContentDTO> contents { get; set; }
}
}

View File

@ -8,26 +8,52 @@ namespace Manager.Interfaces.DTO
public class MapDTO public class MapDTO
{ {
public int zoom { get; set; } // Default = 18 public int zoom { get; set; } // Default = 18
public MapTypeApp mapType { get; set; } // Default = Hybrid public MapTypeApp? mapType { get; set; } // Default = Hybrid for Google
public MapTypeMapBox? mapTypeMapbox { get; set; } // Default = standard for MapBox
public MapProvider? mapProvider { get; set; } // Default = Google
public List<GeoPointDTO> points { get; set; } public List<GeoPointDTO> points { get; set; }
public string iconResourceId { get; set; } public string iconResourceId { get; set; }
public string iconSource { get; set; } // url to resource id (local) or on internet public string iconSource { get; set; } // url to firebase storage or on internet
public List<CategorieDTO> categories { get; set; }
public string latitude { get; set; } // Center on
public string longitude { get; set; } // Center on
} }
public class GeoPointDTO public class GeoPointDTO
{ {
public int id { get; set; } public int? id { get; set; }
public List<TranslationDTO> title { get; set; } public List<TranslationDTO> title { get; set; }
public List<TranslationDTO> description { get; set; } public List<TranslationDTO> description { get; set; }
public List<ImageGeoPoint> images { get; set; } public List<ContentGeoPoint> contents { get; set; }
public CategorieDTO categorie { get; set; } // TO DELETE IN FUTURE
public int? categorieId { get; set; }
public string latitude { get; set; } public string latitude { get; set; }
public string longitude { get; set; } public string longitude { get; set; }
public string imageResourceId { get; set; }
public string imageUrl { get; set; }
public List<TranslationDTO> schedules { get; set; }
public List<TranslationDTO> prices { get; set; }
public List<TranslationDTO> phone { get; set; }
public List<TranslationDTO> email { get; set; }
public List<TranslationDTO> site { get; set; }
} }
public class ImageGeoPoint public class CategorieDTO
{ {
public string imageResourceId { get; set; } public int? id { get; set; }
public string imageSource { get; set; } // url to resource id (local) or on internet public List<TranslationDTO> label { get; set; }
public string icon { get; set; } // icon material
public string iconResourceId { get; set; } // icon point geo
public string iconUrl { get; set; } // url to firebase storage or on internet
public int? order { get; set; } // Order to show
}
public class ContentGeoPoint
{
public string resourceId { get; set; }
public ResourceType resourceType { get; set; }
public string resourceUrl { get; set; } // url to firebase storage or on internet
public string resourceName { get; set; }
} }
public enum MapTypeApp public enum MapTypeApp
@ -38,4 +64,21 @@ namespace Manager.Interfaces.DTO
terrain, terrain,
hybrid hybrid
} }
public enum MapProvider
{
Google,
MapBox
}
public enum MapTypeMapBox
{
standard,
streets,
outdoors,
light,
dark,
satellite,
satellite_streets
}
} }

View File

@ -0,0 +1,25 @@
using Manager.Interfaces.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class OldArticleDTO
{
public List<TranslationDTO> content { get; set; }
public bool isContentTop { get; set; } // MyVisit - True if content is displayed at top, false otherwise
public List<TranslationDTO> audioIds { get; set; }
public bool isReadAudioAuto { get; set; } // MyVisit - True for audio play when open the article / false otherwise
public List<OldContentDTO> images { get; set; }
}
public class OldContentDTO
{
public List<TranslationDTO> title { get; set; }
public List<TranslationDTO> description { get; set; }
public string resourceId { get; set; }
public string source { get; set; }
public int order { get; set; } // Order to show
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class PdfDTO
{
public List<PDFFileDTO> pdfs { get; set; }
}
public class PDFFileDTO
{
public List<TranslationAndResourceDTO> pdfFilesAndTitles { get; set; }
public int? order { get; set; } // Order to show
}
}

View File

@ -0,0 +1,16 @@
using Manager.Interfaces.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class PuzzleDTO
{
public List<TranslationAndResourceDTO> messageDebut { get; set; }
public List<TranslationAndResourceDTO> messageFin { get; set; }
public ContentDTO image { get; set; } // But only image is possible
public int rows { get; set; } = 3;
public int cols { get; set; } = 3;
}
}

View File

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Security.AccessControl;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class QuizzDTO
{
public List<QuestionDTO> questions { get; set; }
public LevelDTO bad_level { get; set; }
public LevelDTO medium_level { get; set; }
public LevelDTO good_level { get; set; }
public LevelDTO great_level { get; set; }
}
public class QuestionDTO
{
public List<TranslationAndResourceDTO> label { get; set; }
public List<ResponseDTO> responses { get; set; }
public string imageBackgroundResourceId { get; set; } // question image background
public ResourceType? imageBackgroundResourceType { get; set; }
public string imageBackgroundResourceUrl { get; set; } // url to firebase storage or on internet
public int order { get; set; } // Order to show
}
public class ResponseDTO
{
public List<TranslationAndResourceDTO> label { get; set; }
public bool isGood { get; set; }
public int order { get; set; } // Order to show
}
public class LevelDTO
{
public List<TranslationAndResourceDTO> label { get; set; }
}
}

View File

@ -7,14 +7,16 @@ namespace Manager.Interfaces.DTO
{ {
public class SliderDTO public class SliderDTO
{ {
public List<ImageDTO> images { get; set; } public List<ContentDTO> contents { get; set; }
} }
public class ImageDTO { public class ContentDTO
{
public List<TranslationDTO> title { get; set; } public List<TranslationDTO> title { get; set; }
public List<TranslationDTO> description { get; set; } public List<TranslationDTO> description { get; set; }
public string resourceId { get; set; } public string resourceId { get; set; }
public string source { get; set; } // url to resource id (local) or on internet public string resourceUrl { get; set; } // url to firebase storage or on internet
public int order { get; set; } // Order to show public int order { get; set; } // Order to show
public ResourceType resourceType { get; set; }
} }
} }

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class WeatherDTO
{
public string city { get; set; } // Weather City
public DateTimeOffset? updatedDate { get; set; } // Weather date update (to only refresh)
public string result { get; set; } // Weather result
}
}

View File

@ -10,5 +10,7 @@ namespace Manager.Interfaces.DTO
public string token_type { get; set; } public string token_type { get; set; }
public int expires_in { get; set; } public int expires_in { get; set; }
public DateTimeOffset expiration { get; set; } public DateTimeOffset expiration { get; set; }
public string instanceId { get; set; }
public int? pinCode { get; set; }
} }
} }

View File

@ -0,0 +1,16 @@
using Manager.Interfaces.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.DTO
{
public class TranslationAndResourceDTO
{
public string language { get; set; }
public string value { get; set; }
public string resourceId { get; set; } // question image, audio or video
public ResourceType? resourceType { get; set; }
public string resourceUrl { get; set; } // url to firebase storage or on internet
}
}

View File

@ -1,4 +1,5 @@
using System; using Manager.Interfaces.Models;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;

View File

@ -1,11 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="DevExpress.Xpo" Version="20.1.8" />
<PackageReference Include="MongoDB.Bson" Version="2.12.1" /> <PackageReference Include="MongoDB.Bson" Version="2.12.1" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Manager.Interfaces.Models
{
public class CityData
{
//[JsonProperty("lat")]
public double Lat { get; set; }
//[JsonProperty("lon")]
public double Lon { get; set; }
}
}

View File

@ -2,6 +2,7 @@
using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Attributes;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
namespace Manager.Interfaces.Models namespace Manager.Interfaces.Models
@ -19,6 +20,16 @@ namespace Manager.Interfaces.Models
[BsonRequired] [BsonRequired]
public string Label { get; set; } public string Label { get; set; }
[BsonElement("Title")]
[BsonRequired]
public List<TranslationDTO> Title { get; set; }
[BsonElement("ImageId")]
public string ImageId { get; set; }
[BsonElement("ImageSource")]
public string ImageSource { get; set; }
[BsonElement("PrimaryColor")] [BsonElement("PrimaryColor")]
public string PrimaryColor { get; set; } public string PrimaryColor { get; set; }
@ -31,16 +42,77 @@ namespace Manager.Interfaces.Models
[BsonElement("DateCreation")] [BsonElement("DateCreation")]
public DateTime DateCreation { get; set; } public DateTime DateCreation { get; set; }
public ConfigurationDTO ToDTO() [BsonElement("IsMobile")]
public bool IsMobile { get; set; }
[BsonElement("IsTablet")]
public bool IsTablet { get; set; }
[BsonElement("IsOffline")]
public bool IsOffline { get; set; }
[BsonElement("InstanceId")]
[BsonRequired]
public string InstanceId { get; set; }
[BsonElement("LoaderImageId")]
public string LoaderImageId { get; set; }
[BsonElement("LoaderImageUrl")]
public string LoaderImageUrl { get; set; }
[BsonElement("WeatherCity")]
public string WeatherCity { get; set; }
[BsonElement("WeatherUpdatedDate")]
public DateTimeOffset? WeatherUpdatedDate { get; set; }
[BsonElement("WeatherResult")]
public string WeatherResult { get; set; }
[BsonElement("IsDate")]
public bool IsDate { get; set; }
[BsonElement("IsHour")]
public bool IsHour { get; set; }
[BsonElement("IsSectionImageBackground")]
public bool IsSectionImageBackground { get; set; }
[BsonElement("RoundedValue")]
public int? RoundedValue { get; set; }
[BsonElement("ScreenPercentageSectionsMainPage")]
public int? ScreenPercentageSectionsMainPage { get; set; }
public ConfigurationDTO ToDTO(List<string> sectionIds)
{ {
return new ConfigurationDTO() return new ConfigurationDTO()
{ {
id = Id, id = Id,
label = Label, label = Label,
title = Title,
imageId = ImageId,
imageSource = ImageSource,
loaderImageId = LoaderImageId,
loaderImageUrl = LoaderImageUrl,
weatherCity = WeatherCity,
weatherUpdatedDate = WeatherUpdatedDate,
weatherResult = WeatherResult,
dateCreation = DateCreation, dateCreation = DateCreation,
primaryColor = PrimaryColor, primaryColor = PrimaryColor,
languages = Languages, languages = Languages,
secondaryColor = SecondaryColor secondaryColor = SecondaryColor,
isMobile = IsMobile,
isTablet = IsTablet,
isOffline = IsOffline,
instanceId = InstanceId,
isDate = IsDate,
isHour = IsHour,
isSectionImageBackground = IsSectionImageBackground,
roundedValue = RoundedValue,
screenPercentageSectionsMainPage = ScreenPercentageSectionsMainPage,
sectionIds = sectionIds
}; };
} }
@ -49,12 +121,27 @@ namespace Manager.Interfaces.Models
{ {
id = Id, id = Id,
label = Label, label = Label,
title= Title,
imageId = ImageId,
imageSource = ImageSource,
loaderImageId = LoaderImageId,
loaderImageUrl = LoaderImageUrl,
weatherCity = WeatherCity,
dateCreation = DateCreation, dateCreation = DateCreation,
primaryColor = PrimaryColor, primaryColor = PrimaryColor,
languages = Languages, languages = Languages,
secondaryColor = SecondaryColor, secondaryColor = SecondaryColor,
isMobile = IsMobile,
isTablet = IsTablet,
isOffline = IsOffline,
sections = sections, sections = sections,
resources = resources resources = resources,
instanceId = InstanceId,
isDate = IsDate,
isSectionImageBackground = IsSectionImageBackground,
roundedValue = RoundedValue,
screenPercentageSectionsMainPage = ScreenPercentageSectionsMainPage,
sectionIds = sections.Select(s => s.id).ToList()
}; };
} }
} }

View File

@ -60,6 +60,9 @@ namespace Manager.Interfaces.Models
[BsonElement("LastConnectionLevel")] [BsonElement("LastConnectionLevel")]
public DateTime LastConnectionLevel { get; set; } public DateTime LastConnectionLevel { get; set; }
[BsonElement("InstanceId")]
[BsonRequired]
public string InstanceId { get; set; }
public DeviceDTO ToDTO() public DeviceDTO ToDTO()
{ {
@ -74,7 +77,8 @@ namespace Manager.Interfaces.Models
configuration = Configuration, configuration = Configuration,
configurationId = ConfigurationId, configurationId = ConfigurationId,
dateUpdate = DateUpdate, dateUpdate = DateUpdate,
dateCreation = DateCreation dateCreation = DateCreation,
instanceId = InstanceId
}; };
} }
@ -95,7 +99,8 @@ namespace Manager.Interfaces.Models
batteryLevel = BatteryLevel, batteryLevel = BatteryLevel,
lastBatteryLevel = LastBatteryLevel, lastBatteryLevel = LastBatteryLevel,
dateUpdate = DateUpdate, dateUpdate = DateUpdate,
dateCreation = DateCreation dateCreation = DateCreation,
instanceId = InstanceId
}; };
} }
} }

View File

@ -0,0 +1,40 @@
using Manager.Interfaces.DTO;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Text;
namespace Manager.Interfaces.Models
{
/// <summary>
/// Instance Information
/// </summary>
public class Instance
{
[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("Name")]
[BsonRequired]
public string Name { get; set; } // UNIQUE !..
[BsonElement("DateCreation")]
public DateTime DateCreation { get; set; }
[BsonElement("PinCode")]
public int? PinCode { get; set; }
public InstanceDTO ToDTO()
{
return new InstanceDTO()
{
id = Id,
name = Name,
dateCreation = DateCreation,
pinCode = PinCode
};
}
}
}

View File

@ -27,19 +27,23 @@ namespace Manager.Interfaces.Models
[BsonElement("DateCreation")] [BsonElement("DateCreation")]
public DateTime DateCreation { get; set; } public DateTime DateCreation { get; set; }
[BsonElement("Data")] [BsonElement("InstanceId")]
[BsonRequired] [BsonRequired]
public string Data { get; set; } public string InstanceId { get; set; }
public ResourceDTO ToDTO(bool isExport = false) [BsonElement("URL")]
public string Url { get; set; } // Firebase url
public ResourceDTO ToDTO()
{ {
return new ResourceDTO() return new ResourceDTO()
{ {
id = Id, id = Id,
label = Label, label = Label,
type = Type, type = Type,
data = isExport ? Data : null, url = Url,
dateCreation = DateCreation dateCreation = DateCreation,
instanceId = InstanceId
}; };
} }
} }
@ -49,6 +53,10 @@ namespace Manager.Interfaces.Models
Image, Image,
Video, Video,
ImageUrl, ImageUrl,
VideoUrl VideoUrl,
Audio,
PDF,
JSON,
JSONUrl
} }
} }

View File

@ -61,6 +61,25 @@ namespace Manager.Interfaces.Models
[BsonRequired] [BsonRequired]
public string Data { get; set; } // Json encapsulated section info public string Data { get; set; } // Json encapsulated section info
[BsonElement("InstanceId")]
[BsonRequired]
public string InstanceId { get; set; }
[BsonElement("IsBeacon")]
public bool IsBeacon { get; set; }
[BsonElement("BeaconId")]
public int? BeaconId { get; set; }
[BsonElement("Latitude")]
public string Latitude { get; set; }
[BsonElement("Longitude")]
public string Longitude { get; set; }
[BsonElement("MeterZoneGPS")]
public int? MeterZoneGPS { get; set; }
public SectionDTO ToDTO() public SectionDTO ToDTO()
{ {
return new SectionDTO() return new SectionDTO()
@ -77,7 +96,13 @@ namespace Manager.Interfaces.Models
isSubSection = IsSubSection, isSubSection = IsSubSection,
parentId = ParentId, parentId = ParentId,
data = Data, data = Data,
dateCreation = DateCreation dateCreation = DateCreation,
instanceId = InstanceId,
isBeacon = IsBeacon,
beaconId = BeaconId,
latitude = Latitude,
longitude = Longitude,
meterZoneGPS = MeterZoneGPS,
}; };
} }
} }
@ -88,6 +113,12 @@ namespace Manager.Interfaces.Models
Slider, Slider,
Video, Video,
Web, Web,
Menu Menu,
Quizz,
Article,
PDF,
Puzzle,
Agenda,
Weather
} }
} }

View File

@ -38,6 +38,10 @@ namespace Manager.Interfaces.Models
[BsonElement("DateCreation")] [BsonElement("DateCreation")]
public DateTime DateCreation { get; set; } public DateTime DateCreation { get; set; }
[BsonElement("InstanceId")]
[BsonRequired]
public string InstanceId { get; set; }
public UserDetailDTO ToDTO() public UserDetailDTO ToDTO()
{ {
return new UserDetailDTO() return new UserDetailDTO()

View File

@ -51,16 +51,16 @@ namespace ManagerService.Service.Controllers
{ {
#if DEBUG #if DEBUG
email = "test@email.be"; email = "test@email.be";
password = "W/7aj4NB60i3YFKJq50pbw=="; // password = "kljqsdkljqsd"; password = "kljqsdkljqsd"; // password = "kljqsdkljqsd"; // W/7aj4NB60i3YFKJq50pbw==
#endif #endif
var token = _tokensService.Authenticate(email.ToLower(), password);
// Set user token ? // Set user token ?
var user = _UserDatabaseService.GetByEmail(email.ToLower()); var user = _UserDatabaseService.GetByEmail(email.ToLower());
if (user == null) if (user == null)
throw new KeyNotFoundException("User not found"); throw new KeyNotFoundException("User not found");
var token = _tokensService.Authenticate(user, password);
MqttClientService.SetServices(_DeviceDatabaseService, _ConfigurationDatabaseService); MqttClientService.SetServices(_DeviceDatabaseService, _ConfigurationDatabaseService);
return new OkObjectResult(token); return new OkObjectResult(token);

View File

@ -1,13 +1,18 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Manager.Helpers;
using Manager.Interfaces.DTO; using Manager.Interfaces.DTO;
using Manager.Interfaces.Models; using Manager.Interfaces.Models;
using Manager.Services; using Manager.Services;
using ManagerService.Service.Services; using ManagerService.Service.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Mqtt.Client.AspNetCore.Services; using Mqtt.Client.AspNetCore.Services;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -21,15 +26,19 @@ namespace ManagerService.Controllers
public class ConfigurationController : ControllerBase public class ConfigurationController : ControllerBase
{ {
private ConfigurationDatabaseService _configurationService; private ConfigurationDatabaseService _configurationService;
private InstanceDatabaseService _instanceService;
private SectionDatabaseService _sectionService; private SectionDatabaseService _sectionService;
private ResourceDatabaseService _resourceService; private ResourceDatabaseService _resourceService;
private DeviceDatabaseService _deviceService; private DeviceDatabaseService _deviceService;
private readonly ILogger<ConfigurationController> _logger; private readonly ILogger<ConfigurationController> _logger;
private readonly IConfiguration _configuration;
public ConfigurationController(ILogger<ConfigurationController> logger, ConfigurationDatabaseService configurationService, SectionDatabaseService sectionService, ResourceDatabaseService resourceService, DeviceDatabaseService deviceService) public ConfigurationController(IConfiguration configuration, ILogger<ConfigurationController> logger, ConfigurationDatabaseService configurationService, InstanceDatabaseService instanceService, SectionDatabaseService sectionService, ResourceDatabaseService resourceService, DeviceDatabaseService deviceService)
{ {
_logger = logger; _logger = logger;
_configuration = configuration;
_configurationService = configurationService; _configurationService = configurationService;
_instanceService = instanceService;
_sectionService = sectionService; _sectionService = sectionService;
_resourceService = resourceService; _resourceService = resourceService;
_deviceService = deviceService; _deviceService = deviceService;
@ -38,17 +47,27 @@ namespace ManagerService.Controllers
/// <summary> /// <summary>
/// Get a list of all configuration (summary) /// Get a list of all configuration (summary)
/// </summary> /// </summary>
/// <param name="id">id instance</param>
[AllowAnonymous] [AllowAnonymous]
[ProducesResponseType(typeof(List<ConfigurationDTO>), 200)] [ProducesResponseType(typeof(List<ConfigurationDTO>), 200)]
[ProducesResponseType(typeof(string), 500)] [ProducesResponseType(typeof(string), 500)]
[HttpGet] [HttpGet]
public ObjectResult Get() public ObjectResult Get([FromQuery] string instanceId)
{ {
try try
{ {
List<Configuration> configurations = _configurationService.GetAll(); List<Configuration> configurations = _configurationService.GetAll(instanceId);
return new OkObjectResult(configurations.Select(r => r.ToDTO())); 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) catch (Exception ex)
{ {
@ -56,6 +75,39 @@ namespace ManagerService.Controllers
} }
} }
/// <summary>
/// Get Confuguration list by instanceId' pincode
/// </summary>
/// <param name="pinCode">Code pin</param>
[AllowAnonymous]
[ProducesResponseType(typeof(List<ConfigurationDTO>), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("byPin")]
public ObjectResult GetConfigurationsByPinCode([FromQuery] int pinCode)
{
try
{
Instance instance = _instanceService.GetByPinCode(pinCode);
if (instance == null)
throw new KeyNotFoundException("None instance is linked to this pin code");
List<Configuration> configurations = _configurationService.GetAll(instance.Id);
List<ConfigurationDTO> configurationDTOs = new List<ConfigurationDTO>();
foreach (var configuration in configurations)
{
List<string> sectionIds = _sectionService.GetAllIdsFromConfiguration(configuration.Id);
configurationDTOs.Add(configuration.ToDTO(sectionIds));
}
return new OkObjectResult(configurationDTOs);
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary> /// <summary>
/// Get a specific display configuration /// Get a specific display configuration
@ -66,7 +118,7 @@ namespace ManagerService.Controllers
[ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)] [ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}")] [HttpGet("{id}")]
public ObjectResult GetDetail(string id) public async Task<ObjectResult> GetDetailAsync(string id)
{ {
try try
{ {
@ -75,7 +127,73 @@ namespace ManagerService.Controllers
if (configuration == null) if (configuration == null)
throw new KeyNotFoundException("This configuration was not found"); throw new KeyNotFoundException("This configuration was not found");
return new OkObjectResult(configuration.ToDTO()); List<string> sectionIds = _sectionService.GetAllIdsFromConfiguration(id);
try
{
var weatherSections = _sectionService.GetAllWeatherSectionsFromConfiguration(id);
foreach (var weatherSection in weatherSections)
{
WeatherDTO weatherDTO = JsonConvert.DeserializeObject<WeatherDTO>(weatherSection.Data);
if (weatherDTO.city != null && weatherDTO.city.Length >= 2 &&
(weatherDTO.updatedDate == null || weatherDTO.updatedDate.Value.AddHours(3) < DateTimeOffset.Now)) // Update all 4 hours
{
// Call Openweather api with token from appSettings and update result with json
var apiKey = _configuration.GetSection("OpenWeatherApiKey").Get<string>();
if (apiKey != null && apiKey.Length > 0)
{
string url = $"http://api.openweathermap.org/geo/1.0/direct?q={weatherDTO.city}&limit=1&appid={apiKey}";
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
List<CityData> cities = JsonConvert.DeserializeObject<List<CityData>>(responseBody);
if (cities.Count > 0)
{
double lat = cities[0].Lat;
double lon = cities[0].Lon;
//string onecallUrl = $"https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&appid={apiKey}";
string callUrl = $"https://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&units=metric&appid={apiKey}";
HttpResponseMessage callResponse = await client.GetAsync(callUrl);
callResponse.EnsureSuccessStatusCode();
string callResponseBody = await callResponse.Content.ReadAsStringAsync();
weatherDTO.updatedDate = DateTimeOffset.Now;
weatherDTO.result = callResponseBody;
weatherSection.Data = JsonConvert.SerializeObject(weatherDTO);
_sectionService.Update(weatherSection.Id, weatherSection);
}
else
{
Console.WriteLine("Aucune ville trouvée.");
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"Une erreur s'est produite lors de la requête HTTP : {e.Message}");
}
}
}
}
}
} catch (Exception e)
{
Console.WriteLine($"Une erreur s'est produite lors de la mise à jour des sections de type météo : {e.Message}");
}
return new OkObjectResult(configuration.ToDTO(sectionIds));
} }
catch (KeyNotFoundException ex) catch (KeyNotFoundException ex)
{ {
@ -105,15 +223,37 @@ namespace ManagerService.Controllers
// Todo add some verification ? // Todo add some verification ?
Configuration configuration = new Configuration(); Configuration configuration = new Configuration();
configuration.InstanceId = newConfiguration.instanceId;
configuration.Label = newConfiguration.label; configuration.Label = newConfiguration.label;
configuration.Title = new List<TranslationDTO>();
configuration.ImageId = newConfiguration.imageId;
configuration.ImageSource = newConfiguration.imageSource;
configuration.PrimaryColor = newConfiguration.primaryColor; configuration.PrimaryColor = newConfiguration.primaryColor;
configuration.SecondaryColor = newConfiguration.secondaryColor; configuration.SecondaryColor = newConfiguration.secondaryColor;
configuration.Languages = new List<string> { "FR", "NL", "EN", "DE" }; // by default all languages configuration.LoaderImageId = newConfiguration.loaderImageId;
configuration.LoaderImageUrl = newConfiguration.loaderImageUrl;
configuration.WeatherCity = newConfiguration.weatherCity;
configuration.WeatherUpdatedDate = null;
configuration.WeatherResult = null;
configuration.IsDate = newConfiguration.isDate;
configuration.IsHour = newConfiguration.isHour;
configuration.IsSectionImageBackground = true;
configuration.RoundedValue = newConfiguration.roundedValue;
configuration.ScreenPercentageSectionsMainPage = newConfiguration.screenPercentageSectionsMainPage;
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.DateCreation = DateTime.Now;
configuration.IsMobile = newConfiguration.isMobile;
configuration.IsTablet = newConfiguration.isTablet;
configuration.IsOffline = newConfiguration.isOffline;
Configuration configurationCreated = _configurationService.Create(configuration); Configuration configurationCreated = _configurationService.Create(configuration);
return new OkObjectResult(configurationCreated.ToDTO()); return new OkObjectResult(configurationCreated.ToDTO(new List<string>())); // Empty list
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
@ -152,16 +292,38 @@ namespace ManagerService.Controllers
throw new KeyNotFoundException("Configuration does not exist"); throw new KeyNotFoundException("Configuration does not exist");
// Todo add some verification ? // Todo add some verification ?
configuration.InstanceId = updatedConfiguration.instanceId;
configuration.Label = updatedConfiguration.label; configuration.Label = updatedConfiguration.label;
configuration.Title = updatedConfiguration.title;
configuration.ImageId = updatedConfiguration.imageId;
configuration.ImageSource = updatedConfiguration.imageSource;
configuration.PrimaryColor = updatedConfiguration.primaryColor; configuration.PrimaryColor = updatedConfiguration.primaryColor;
configuration.SecondaryColor = updatedConfiguration.secondaryColor; configuration.SecondaryColor = updatedConfiguration.secondaryColor;
configuration.Languages = updatedConfiguration.languages; configuration.Languages = updatedConfiguration.languages;
configuration.IsMobile = updatedConfiguration.isMobile;
configuration.IsTablet = updatedConfiguration.isTablet;
configuration.IsOffline = updatedConfiguration.isOffline;
configuration.LoaderImageId = updatedConfiguration.loaderImageId;
configuration.LoaderImageUrl = updatedConfiguration.loaderImageUrl;
configuration.WeatherCity = updatedConfiguration.weatherCity;
if (configuration.WeatherCity != updatedConfiguration.weatherCity)
{
configuration.WeatherUpdatedDate = null;
configuration.WeatherResult = null;
}
configuration.IsDate = updatedConfiguration.isDate;
configuration.IsHour = updatedConfiguration.isHour;
configuration.IsSectionImageBackground = updatedConfiguration.isSectionImageBackground;
configuration.RoundedValue = updatedConfiguration.roundedValue;
configuration.ScreenPercentageSectionsMainPage = updatedConfiguration.screenPercentageSectionsMainPage;
Configuration configurationModified = _configurationService.Update(updatedConfiguration.id, configuration); Configuration configurationModified = _configurationService.Update(updatedConfiguration.id, configuration);
MqttClientService.PublishMessage($"config/{configurationModified.Id}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true })); MqttClientService.PublishMessage($"config/{configurationModified.Id}", JsonConvert.SerializeObject(new PlayerMessageDTO() { configChanged = true }));
return new OkObjectResult(configurationModified.ToDTO()); List<string> sectionIds = _sectionService.GetAllIdsFromConfiguration(configuration.Id);
return new OkObjectResult(configurationModified.ToDTO(sectionIds));
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
@ -233,12 +395,14 @@ namespace ManagerService.Controllers
/// Export a configuration /// Export a configuration
/// </summary> /// </summary>
/// <param name="id">Id of configuration to export</param> /// <param name="id">Id of configuration to export</param>
[ProducesResponseType(typeof(ExportConfigurationDTO), 200)] /// <param name="language">Language to export</param>
[AllowAnonymous]
[ProducesResponseType(typeof(FileContentResult), 200)]
[ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)] [ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}/export")] [HttpGet("{id}/export")]
public ObjectResult Export(string id) public FileContentResult Export(string id, [FromQuery] string language)
{ {
try try
{ {
@ -246,12 +410,23 @@ namespace ManagerService.Controllers
throw new ArgumentNullException("Configuration param is null"); throw new ArgumentNullException("Configuration param is null");
Configuration configuration = _configurationService.GetById(id); Configuration configuration = _configurationService.GetById(id);
if (configuration == null) if (configuration == null)
throw new KeyNotFoundException("Configuration does not exist"); throw new KeyNotFoundException("Configuration does not exist");
List<SectionDTO> sectionDTOs = _sectionService.GetAllFromConfiguration(configuration.Id).Select(s => s.ToDTO()).ToList(); List<SectionDTO> sectionDTOs = _sectionService.GetAllFromConfigurationEvenSubsection(configuration.Id).Select(s => s.ToDTO()).ToList();
List<ResourceDTO> resourceDTOs = new List<ResourceDTO>(); List<ResourceDTO> resourceDTOs = new List<ResourceDTO>();
if (configuration.ImageId != null)
{
addResourceToList(resourceDTOs, configuration.ImageId);
}
if (configuration.LoaderImageId != null)
{
addResourceToList(resourceDTOs, configuration.LoaderImageId);
}
foreach (var section in sectionDTOs) foreach (var section in sectionDTOs)
{ {
if (section.imageId != null) { if (section.imageId != null) {
@ -267,10 +442,25 @@ namespace ManagerService.Controllers
} }
foreach (var point in mapDTO.points) { foreach (var point in mapDTO.points) {
foreach (var image in point.images) { if (point.imageResourceId != null)
if (image.imageResourceId != null)
{ {
addResourceToList(resourceDTOs, image.imageResourceId); addResourceToList(resourceDTOs, point.imageResourceId);
}
foreach (var content in point.contents) {
if (content.resourceId != null)
{
addResourceToList(resourceDTOs, content.resourceId);
}
}
}
if (mapDTO.categories != null && mapDTO.categories.Count > 0)
{
foreach (var categorie in mapDTO.categories)
{
if (categorie.iconResourceId != null)
{
addResourceToList(resourceDTOs, categorie.iconResourceId);
} }
} }
} }
@ -278,36 +468,154 @@ namespace ManagerService.Controllers
break; break;
case SectionType.Slider: case SectionType.Slider:
SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.data); SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.data);
foreach (var image in sliderDTO.images) foreach (var content in sliderDTO.contents)
{ {
if (image.resourceId != null) if (content.resourceId != null)
{ {
addResourceToList(resourceDTOs, image.resourceId); addResourceToList(resourceDTOs, content.resourceId);
}
}
break;
case SectionType.Quizz:
QuizzDTO quizzDTO = JsonConvert.DeserializeObject<QuizzDTO>(section.data);
foreach (var question in quizzDTO.questions)
{
if (question.label != null)
{
foreach (var questionLabel in question.label)
{
addResourceToList(resourceDTOs, questionLabel.resourceId);
}
}
if (question.imageBackgroundResourceId != null)
{
addResourceToList(resourceDTOs, question.imageBackgroundResourceId);
}
foreach (var response in question.responses)
{
if (response.label != null)
{
foreach (var responseLabel in response.label)
{
addResourceToList(resourceDTOs, responseLabel.resourceId);
}
}
}
}
if (quizzDTO.bad_level != null)
{
if (quizzDTO.bad_level.label != null)
{
foreach (var badLevelLabel in quizzDTO.bad_level.label)
{
addResourceToList(resourceDTOs, badLevelLabel.resourceId);
}
}
}
if (quizzDTO.medium_level != null)
{
if (quizzDTO.medium_level.label != null)
{
foreach (var medium_levelLabel in quizzDTO.medium_level.label)
{
addResourceToList(resourceDTOs, medium_levelLabel.resourceId);
}
}
}
if (quizzDTO.good_level != null)
{
if (quizzDTO.good_level.label != null)
{
foreach (var good_levelLabel in quizzDTO.good_level.label)
{
addResourceToList(resourceDTOs, good_levelLabel.resourceId);
}
}
}
if (quizzDTO.great_level != null)
{
if (quizzDTO.great_level.label != null)
{
foreach (var great_levelLabel in quizzDTO.great_level.label)
{
addResourceToList(resourceDTOs, great_levelLabel.resourceId);
}
}
}
break;
case SectionType.Article:
ArticleDTO articleDTO = JsonConvert.DeserializeObject<ArticleDTO>(section.data);
foreach (var content in articleDTO.contents)
{
if (content.resourceId != null)
{
addResourceToList(resourceDTOs, content.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)
{
addResourceToList(resourceDTOs, audio.value);
}
}
break;
case SectionType.PDF:
PdfDTO pdfDTO = JsonConvert.DeserializeObject<PdfDTO>(section.data);
foreach (var pdf in pdfDTO.pdfs)
{
foreach (var pdfFileAndTitle in pdf.pdfFilesAndTitles)
{
addResourceToList(resourceDTOs, pdfFileAndTitle.resourceId);
}
}
break;
case SectionType.Agenda:
AgendaDTO agendaDTO = JsonConvert.DeserializeObject<AgendaDTO>(section.data);
var resourceIds = language != null ? agendaDTO.resourceIds.Where(a => a.language == language) : agendaDTO.resourceIds;
foreach (var resourceId in resourceIds)
{
if (resourceId.value != null && resourceId.value.Trim().Length > 0)
{
addResourceToList(resourceDTOs, resourceId.value);
} }
} }
break; break;
case SectionType.Menu: case SectionType.Menu:
case SectionType.Web: case SectionType.Web:
case SectionType.Video: case SectionType.Video:
case SectionType.Weather:
default: default:
break; break;
} }
} }
ExportConfigurationDTO toDownload = configuration.ToExportDTO(sectionDTOs, resourceDTOs);
return new OkObjectResult(configuration.ToExportDTO(sectionDTOs, resourceDTOs)); string jsonString = JsonConvert.SerializeObject(toDownload);
var fileName = $"{configuration.Label}.json";
var mimeType = "application/json";
var fileBytes = Encoding.UTF8.GetBytes(jsonString);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
return new BadRequestObjectResult(ex.Message) { }; return null;
//return new BadRequestObjectResult(ex.Message) { };
} }
catch (KeyNotFoundException ex) catch (KeyNotFoundException ex)
{ {
return new NotFoundObjectResult(ex.Message) { }; return null;
//return new NotFoundObjectResult(ex.Message) { };
} }
catch (Exception ex) catch (Exception ex)
{ {
return new ObjectResult(ex.Message) { StatusCode = 500 }; return null;
//return new ObjectResult(ex.Message) { StatusCode = 500 };
} }
} }
@ -334,11 +642,38 @@ namespace ManagerService.Controllers
configuration = new Configuration(); configuration = new Configuration();
configuration.Id = exportConfiguration.id; configuration.Id = exportConfiguration.id;
configuration.InstanceId = exportConfiguration.instanceId;
configuration.Label = exportConfiguration.label; 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.DateCreation = exportConfiguration.dateCreation;
configuration.PrimaryColor = exportConfiguration.primaryColor; configuration.PrimaryColor = exportConfiguration.primaryColor;
configuration.SecondaryColor = exportConfiguration.secondaryColor; configuration.SecondaryColor = exportConfiguration.secondaryColor;
configuration.Languages = exportConfiguration.languages; configuration.Languages = exportConfiguration.languages;
configuration.IsMobile = exportConfiguration.isMobile;
configuration.IsTablet = exportConfiguration.isTablet;
configuration.IsOffline = exportConfiguration.isOffline;
configuration.LoaderImageId = exportConfiguration.loaderImageId;
configuration.LoaderImageUrl = exportConfiguration.loaderImageUrl;
if (configuration.LoaderImageId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == configuration.LoaderImageId).FirstOrDefault());
}
configuration.WeatherCity = exportConfiguration.weatherCity;
configuration.IsDate = exportConfiguration.isDate;
configuration.IsHour = exportConfiguration.isHour;
configuration.IsSectionImageBackground = exportConfiguration.isSectionImageBackground;
configuration.RoundedValue = exportConfiguration.roundedValue;
configuration.ScreenPercentageSectionsMainPage = exportConfiguration.screenPercentageSectionsMainPage;
_configurationService.Create(configuration); _configurationService.Create(configuration);
@ -346,10 +681,11 @@ namespace ManagerService.Controllers
{ {
Section newSection = new Section(); Section newSection = new Section();
newSection.Id = section.id; newSection.Id = section.id;
newSection.InstanceId = section.instanceId;
newSection.Label = section.label; newSection.Label = section.label;
newSection.Title = section.title; newSection.Title = section.title;
newSection.Description = section.description; newSection.Description = section.description;
newSection.Order = section.order; // if one day we can use same section in multiple configuration, need to change that newSection.Order = section.order.GetValueOrDefault(); // if one day we can use same section in multiple configuration, need to change that
newSection.Type = section.type; newSection.Type = section.type;
newSection.ImageId = section.imageId; newSection.ImageId = section.imageId;
newSection.ImageSource = section.imageSource; newSection.ImageSource = section.imageSource;
@ -358,6 +694,11 @@ namespace ManagerService.Controllers
newSection.ParentId = section.parentId; newSection.ParentId = section.parentId;
newSection.Data = section.data; newSection.Data = section.data;
newSection.DateCreation = section.dateCreation; 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) if (newSection.ImageId != null)
{ {
@ -377,29 +718,119 @@ namespace ManagerService.Controllers
foreach (var point in mapDTO.points) foreach (var point in mapDTO.points)
{ {
foreach (var image in point.images) if (point.imageResourceId != null)
{ {
if (image.imageResourceId != null) createResource(exportConfiguration.resources.Where(r => r.id == point.imageResourceId).FirstOrDefault());
{
createResource(exportConfiguration.resources.Where(r => r.id == image.imageResourceId).FirstOrDefault());
} }
foreach (var content in point.contents)
{
if (content.resourceId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == content.resourceId).FirstOrDefault());
}
}
}
foreach (var categorie in mapDTO.categories)
{
if (categorie.iconResourceId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == categorie.iconResourceId).FirstOrDefault());
} }
} }
break; break;
case SectionType.Slider: case SectionType.Slider:
SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.data); SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.data);
foreach (var image in sliderDTO.images) foreach (var content in sliderDTO.contents)
{ {
if (image.resourceId != null) if (content.resourceId != null)
{ {
createResource(exportConfiguration.resources.Where(r => r.id == image.resourceId).FirstOrDefault()); createResource(exportConfiguration.resources.Where(r => r.id == content.resourceId).FirstOrDefault());
}
}
break;
case SectionType.Quizz:
QuizzDTO quizzDTO = JsonConvert.DeserializeObject<QuizzDTO>(section.data);
foreach (var question in quizzDTO.questions)
{
if (question.label != null)
{
foreach (var questionLabel in question.label)
{
createResource(exportConfiguration.resources.Where(r => r.id == questionLabel.resourceId).FirstOrDefault());
}
}
if (question.imageBackgroundResourceId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == question.imageBackgroundResourceId).FirstOrDefault());
}
foreach (var response in question.responses)
{
if (response.label != null)
{
foreach (var responseLabel in response.label)
{
createResource(exportConfiguration.resources.Where(r => r.id == responseLabel.resourceId).FirstOrDefault());
}
}
}
}
if (quizzDTO.bad_level != null)
{
if(quizzDTO.bad_level.label != null)
{
foreach (var balLevelLabel in quizzDTO.bad_level.label)
{
createResource(exportConfiguration.resources.Where(r => r.id == balLevelLabel.resourceId).FirstOrDefault());
}
}
}
if (quizzDTO.medium_level != null)
{
if (quizzDTO.medium_level.label != null)
{
foreach (var medium_levelLabel in quizzDTO.medium_level.label)
{
createResource(exportConfiguration.resources.Where(r => r.id == medium_levelLabel.resourceId).FirstOrDefault());
}
}
}
if (quizzDTO.good_level != null)
{
if (quizzDTO.good_level.label != null)
{
foreach (var good_levelLabel in quizzDTO.good_level.label)
{
createResource(exportConfiguration.resources.Where(r => r.id == good_levelLabel.resourceId).FirstOrDefault());
}
}
}
if (quizzDTO.great_level != null)
{
if (quizzDTO.great_level.label != null)
{
foreach (var great_levelLabel in quizzDTO.great_level.label)
{
createResource(exportConfiguration.resources.Where(r => r.id == great_levelLabel.resourceId).FirstOrDefault());
}
}
}
break;
case SectionType.Article:
ArticleDTO articleDTO = JsonConvert.DeserializeObject<ArticleDTO>(section.data);
foreach (var content in articleDTO.contents)
{
if (content.resourceId != null)
{
createResource(exportConfiguration.resources.Where(r => r.id == content.resourceId).FirstOrDefault());
} }
} }
break; break;
case SectionType.Menu: case SectionType.Menu:
case SectionType.Web: case SectionType.Web:
case SectionType.Video: case SectionType.Video:
case SectionType.Weather:
default: default:
break; break;
} }
@ -432,10 +863,11 @@ namespace ManagerService.Controllers
{ {
Resource resource = new Resource(); Resource resource = new Resource();
resource.Id = resourceExport.id; resource.Id = resourceExport.id;
resource.InstanceId = resourceExport.instanceId;
resource.Type = resourceExport.type; resource.Type = resourceExport.type;
resource.Label = resourceExport.label; resource.Label = resourceExport.label;
resource.DateCreation = resourceExport.dateCreation; resource.DateCreation = resourceExport.dateCreation;
resource.Data = resourceExport.data; //resource.Data = resourceExport.data;
if (!_resourceService.IsExist(resourceExport.id)) if (!_resourceService.IsExist(resourceExport.id))
_resourceService.Create(resource); _resourceService.Create(resource);
@ -446,8 +878,8 @@ namespace ManagerService.Controllers
if (!resourceDTOs.Select(r => r.id).Contains(resourceId)) { if (!resourceDTOs.Select(r => r.id).Contains(resourceId)) {
Resource resource = _resourceService.GetById(resourceId); Resource resource = _resourceService.GetById(resourceId);
if (resource != null) { if (resource != null && !resourceDTOs.Any(r => r.id == resource.Id)) {
resourceDTOs.Add(resource.ToDTO(true)); resourceDTOs.Add(resource.ToDTO());
} }
} }
return resourceDTOs; return resourceDTOs;

View File

@ -37,14 +37,15 @@ namespace ManagerService.Controllers
/// <summary> /// <summary>
/// Get a list of all devices /// Get a list of all devices
/// </summary> /// </summary>
/// <param name="id">id instance</param>
[ProducesResponseType(typeof(List<DeviceDTO>), 200)] [ProducesResponseType(typeof(List<DeviceDTO>), 200)]
[ProducesResponseType(typeof(string), 500)] [ProducesResponseType(typeof(string), 500)]
[HttpGet] [HttpGet]
public ObjectResult Get() public ObjectResult Get([FromQuery] string instanceId)
{ {
try try
{ {
List<Device> devices = _deviceService.GetAll(); List<Device> devices = _deviceService.GetAll(instanceId);
return new OkObjectResult(devices.Select(d => d.ToDTO())); return new OkObjectResult(devices.Select(d => d.ToDTO()));
} }
@ -121,6 +122,7 @@ namespace ManagerService.Controllers
device.DateCreation = DateTime.Now; device.DateCreation = DateTime.Now;
} }
device.InstanceId = newDevice.instanceId;
device.Name = newDevice.name; device.Name = newDevice.name;
device.Configuration = configuration.Label; device.Configuration = configuration.Label;
device.ConfigurationId = newDevice.configurationId; device.ConfigurationId = newDevice.configurationId;
@ -178,6 +180,7 @@ namespace ManagerService.Controllers
// Todo add some verification ? // Todo add some verification ?
device.Name = updatedDevice.name; device.Name = updatedDevice.name;
device.InstanceId = updatedDevice.instanceId;
device.Identifier = updatedDevice.identifier; device.Identifier = updatedDevice.identifier;
device.IpAddressWLAN = updatedDevice.ipAddressWLAN; device.IpAddressWLAN = updatedDevice.ipAddressWLAN;
device.IpAddressETH = updatedDevice.ipAddressETH; device.IpAddressETH = updatedDevice.ipAddressETH;

View File

@ -0,0 +1,246 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Manager.Framework.Business;
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 NSwag.Annotations;
namespace ManagerService.Controllers
{
[Authorize] // TODO Add ROLES (Roles = "Admin")
[ApiController, Route("api/[controller]")]
[OpenApiTag("Instance", Description = "Instance management")]
public class InstanceController : ControllerBase
{
private InstanceDatabaseService _instanceService;
private UserDatabaseService _userService;
private readonly ILogger<InstanceController> _logger;
private readonly ProfileLogic _profileLogic;
public InstanceController(ILogger<InstanceController> logger, InstanceDatabaseService instanceService, UserDatabaseService userService, ProfileLogic profileLogic)
{
_logger = logger;
_instanceService = instanceService;
_userService = userService;
_profileLogic = profileLogic;
}
/// <summary>
/// Get a list of instance
/// </summary>
[ProducesResponseType(typeof(List<Instance>), 200)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet]
public ObjectResult Get()
{
try
{
List<Instance> instances = _instanceService.GetAll();
return new OkObjectResult(instances);
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a specific instance
/// </summary>
/// <param name="id">id instance</param>
[ProducesResponseType(typeof(InstanceDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}")]
public ObjectResult GetDetail(string id)
{
try
{
Instance instance = _instanceService.GetById(id);
if (instance == null)
throw new KeyNotFoundException("This instance was not found");
return new OkObjectResult(instance.ToDTO());
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Create an instance
/// </summary>
/// <param name="newInstance">New instance info</param>
//[AllowAnonymous]
[ProducesResponseType(typeof(InstanceDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost]
public ObjectResult CreateInstance([FromBody] Instance newInstance)
{
try
{
if (newInstance == null)
throw new ArgumentNullException("instance param is null");
newInstance.DateCreation = DateTime.Now;
List<Instance> instances = _instanceService.GetAll();
if (instances.Select(i => i.Name).Contains(newInstance.Name))
throw new InvalidOperationException("This name is already used");
Instance instanceCreated = _instanceService.Create(newInstance);
return new OkObjectResult(instanceCreated.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 an instance
/// </summary>
/// <param name="updatedinstance">instance to update</param>
[ProducesResponseType(typeof(InstanceDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut]
public ObjectResult Updateinstance([FromBody] Instance updatedInstance)
{
try
{
if (updatedInstance == null)
throw new ArgumentNullException("instance param is null");
Instance instance = _instanceService.GetById(updatedInstance.Id);
if (instance == null)
throw new KeyNotFoundException("instance does not exist");
Instance instanceModified = _instanceService.Update(updatedInstance.Id, instance);
return new OkObjectResult(instanceModified.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>
/// Get Instance by pincode
/// </summary>
/// <param name="pinCode">Code pin</param>
[AllowAnonymous]
[ProducesResponseType(typeof(InstanceDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("byPin")]
public ObjectResult GetInstanceByPinCode([FromQuery] int pinCode)
{
try
{
Instance instance = _instanceService.GetByPinCode(pinCode);
if (instance == null)
throw new KeyNotFoundException("Instance was not found");
return new OkObjectResult(instance.ToDTO());
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Delete an instance
/// </summary>
/// <param name="id">Id of instance to delete</param>
[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpDelete("{id}")]
public ObjectResult DeleteInstance(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("instance param is null");
Instance instance = _instanceService.GetById(id);
// Delete all user in instance
List<User> users = _userService.GetByInstanceId(instance.Id);
foreach(var user in users)
{
_userService.Remove(user.Id);
}
if (instance == null)
throw new KeyNotFoundException("instance does not exist");
_instanceService.Remove(id);
return new ObjectResult("The instance 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 };
}
}
}
}

View File

@ -11,12 +11,18 @@ using System.Threading.Tasks;
using Manager.Interfaces.DTO; using Manager.Interfaces.DTO;
using Manager.Interfaces.Models; using Manager.Interfaces.Models;
using Manager.Services; using Manager.Services;
using ManagerService.Helpers;
using ManagerService.Service.Services; using ManagerService.Service.Services;
using ManagerService.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.IIS.Core;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MongoDB.Bson.Serialization.Serializers;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NSwag.Annotations; using NSwag.Annotations;
using static System.Net.Mime.MediaTypeNames;
namespace ManagerService.Controllers namespace ManagerService.Controllers
{ {
@ -27,28 +33,57 @@ namespace ManagerService.Controllers
{ {
private ResourceDatabaseService _resourceService; private ResourceDatabaseService _resourceService;
private SectionDatabaseService _sectionService; private SectionDatabaseService _sectionService;
private ConfigurationDatabaseService _configurationService;
private FirebaseService _firebaseService;
private FirebaseStorageService _firebaseStorageService;
private readonly ILogger<ResourceController> _logger; private readonly ILogger<ResourceController> _logger;
public ResourceController(ILogger<ResourceController> logger, ResourceDatabaseService resourceService, SectionDatabaseService sectionService) private static int MaxWidth = 1024;
private static int MaxHeight = 1024;
public ResourceController(ILogger<ResourceController> logger, ResourceDatabaseService resourceService, SectionDatabaseService sectionService, ConfigurationDatabaseService configurationService, FirebaseService firebaseService, FirebaseStorageService firebaseStorageService)
{ {
_logger = logger; _logger = logger;
_resourceService = resourceService; _resourceService = resourceService;
_sectionService = sectionService; _sectionService = sectionService;
_configurationService = configurationService;
_firebaseService = firebaseService;
_firebaseStorageService = firebaseStorageService;
} }
/// <summary> /// <summary>
/// Get a list of all resources (summary) /// Get a list of all resources (summary)
/// </summary> /// </summary>
/// <param name="id">id instance</param>
/// <param name="types">types of resource</param>
[ProducesResponseType(typeof(List<ResourceDTO>), 200)] [ProducesResponseType(typeof(List<ResourceDTO>), 200)]
[ProducesResponseType(typeof(string), 500)] [ProducesResponseType(typeof(string), 500)]
[HttpGet] [HttpGet]
public ObjectResult Get() public ObjectResult Get([FromQuery] string instanceId, [FromQuery] List<ResourceType> types)
{ {
try try
{ {
List<Resource> resources = _resourceService.GetAll(); if (instanceId == null)
throw new ArgumentNullException("InstanceId needed");
List<Resource> resources = new List<Resource>();
if (types.Count > 0)
{
resources = _resourceService.GetAllByType(instanceId, types);
}
else
{
resources = _resourceService.GetAll(instanceId);
}
return new OkObjectResult(resources.Select(r => r.ToDTO(r.Type == ResourceType.ImageUrl))); List<ResourceDTO> resourceDTOs = new List<ResourceDTO>();
foreach (var resource in resources)
{
ResourceDTO resourceDTO = new ResourceDTO();
resourceDTO = resource.ToDTO();
resourceDTOs.Add(resourceDTO);
}
return new OkObjectResult(resourceDTOs.OrderByDescending(r => r.dateCreation));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -56,7 +91,6 @@ namespace ManagerService.Controllers
} }
} }
/// <summary> /// <summary>
/// Get a specific resource /// Get a specific resource
/// </summary> /// </summary>
@ -75,11 +109,41 @@ namespace ManagerService.Controllers
if (resource == null) if (resource == null)
throw new KeyNotFoundException("This resource was not found"); throw new KeyNotFoundException("This resource was not found");
return new OkObjectResult(resource.ToDTO(resource.Type == ResourceType.ImageUrl)); ResourceDTO resourceDTO = new ResourceDTO();
resourceDTO = resource.ToDTO();
/*if (resource.Type == ResourceType.ImageUrl)
{
var resourceData = _resourceDataService.GetByResourceId(resource.Id);
resourceDTO.data = resourceData != null ? resourceData.Data : null;
}*/
// RESIZE IMAGE
/*byte[] imageBytes = Convert.FromBase64String(resourceData.Data);
using (MemoryStream originalImageMemoryStream = new MemoryStream(imageBytes))
{
using (Image image = Image.FromStream(originalImageMemoryStream))
{
var width = image.Width;
var height = image.Height;
if (image.Width > MaxWidth || image.Height > MaxHeight)
{
Size newSize = ImageResizer.ResizeKeepAspect(image.Size, MaxWidth, MaxHeight);
byte[] resizedImage = ImageResizer.ResizeImage(image, newSize.Width, newSize.Height, image.Width, image.Height);
resourceData.Data = Convert.ToBase64String(resizedImage);
ResourceData resourceModified = _resourceDataService.Update(resourceData.Id, resourceData);
}
}
}*/
return new OkObjectResult(resourceDTO);
} }
catch (KeyNotFoundException ex) catch (KeyNotFoundException ex)
{ {
return new NotFoundObjectResult(ex.Message) {}; return new NotFoundObjectResult(ex.Message) { };
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -101,22 +165,48 @@ namespace ManagerService.Controllers
try try
{ {
Resource resource = _resourceService.GetById(id); Resource resource = _resourceService.GetById(id);
if (resource == null) if (resource == null)
throw new KeyNotFoundException("This resource was not found"); throw new KeyNotFoundException("This resource was not found");
var file = Convert.FromBase64String(resource.Data); //var file = Convert.FromBase64String(resourceData.Data);
if (resource.Type == ResourceType.Image) // RESIZE IMAGE
/*using (MemoryStream originalImageMemoryStream = new MemoryStream(file))
{ {
return new FileContentResult(file, "image/png"); using (Image image = Image.FromStream(originalImageMemoryStream))
{
var width = image.Width;
var height = image.Height;
if(image.Width > MaxWidth || image.Height > MaxHeight)
{
Size newSize = ImageResizer.ResizeKeepAspect(image.Size, MaxWidth, MaxHeight);
byte[] resizedImage = ImageResizer.ResizeImage(image, newSize.Width, newSize.Height, image.Width, image.Height);
resourceData.Data = Convert.ToBase64String(resizedImage);
ResourceData resourceModified = _resourceDataService.Update(resourceData.Id, resourceData);
} }
if (resource.Type == ResourceType.Video) }
}*/
/*if (resource.Type == ResourceType.Image)
{ {
return new FileContentResult(file, "application/octet-stream"); return new FileContentResult(file, "image/png")
{
FileDownloadName = resource.Label + ".png"
};
}
if (resource.Type == ResourceType.Video || resource.Type == ResourceType.Audio)
{
return new FileContentResult(file, "application/octet-stream")
{
FileDownloadName = resource.Type == ResourceType.Audio ? resource.Label + ".mp3" : resource.Label + ".mp4",
};
} }
return new FileContentResult(file, "image/png"); return new FileContentResult(file, "image/png");*/
return new NotFoundObjectResult("No more supported") { };
} }
catch (KeyNotFoundException ex) catch (KeyNotFoundException ex)
{ {
@ -128,6 +218,7 @@ namespace ManagerService.Controllers
} }
} }
// OLD VERSION
/// <summary> /// <summary>
/// Upload a specific resource (picture or video) /// Upload a specific resource (picture or video)
/// </summary> /// </summary>
@ -135,16 +226,14 @@ namespace ManagerService.Controllers
[ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)] [ProducesResponseType(typeof(string), 500)]
[HttpPost("upload"), DisableRequestSizeLimit] [HttpPost("upload"), DisableRequestSizeLimit]
public IActionResult Upload([FromForm] string label, [FromForm] string type) // Create but with local //[FromBody] ResourceDetailDTO uploadResource public IActionResult Upload([FromForm] string label, [FromForm] string type, [FromForm] string instanceId) // Create but with local //[FromBody] ResourceDetailDTO uploadResource
{ {
try try
{ {
if (label == null || type == null) if (label == null || type == null || instanceId == null)
throw new ArgumentNullException("One of resource params is null"); throw new ArgumentNullException("One of resource params is null");
ResourceDTO uploadResource = new ResourceDTO();
uploadResource.type = (ResourceType) Enum.Parse(typeof(ResourceType), type);
uploadResource.label = label;
var resourceType = (ResourceType)Enum.Parse(typeof(ResourceType), type);
List<Resource> resources = new List<Resource>(); List<Resource> resources = new List<Resource>();
foreach (var file in Request.Form.Files) foreach (var file in Request.Form.Files)
@ -152,21 +241,35 @@ namespace ManagerService.Controllers
if (file.Length > 0) if (file.Length > 0)
{ {
var stringResult = ""; var stringResult = "";
if (file.Length > 0) double fileSizeibMbs = (double)((double)file.Length) / (1024 * 1024);
if (fileSizeibMbs <= 1.5 || resourceType == ResourceType.Image)
{ {
using (var ms = new MemoryStream()) using (var ms = new MemoryStream())
{ {
file.CopyTo(ms); file.CopyTo(ms);
var fileBytes = ms.ToArray(); var fileBytes = ms.ToArray();
if (resourceType == ResourceType.Image)
{
bool isFort = instanceId == "633ee379d9405f32f166f047"; // If fort saint heribert, TODO add watermark in configuration and model
if (isFort) // TODO We need to know for which purpose (mobile or tablet)
{
fileBytes = ImageHelper.ResizeAndAddWatermark(fileBytes, isFort, MaxWidth, MaxHeight);
}
}
stringResult = Convert.ToBase64String(fileBytes); stringResult = Convert.ToBase64String(fileBytes);
} }
} }
else
{
throw new FileLoadException(message: "Fichier inexistant ou trop volumineux (max 4Mb)");
}
// Todo add some verification ? // Todo add some verification ?
Resource resource = new Resource(); Resource resource = new Resource();
resource.Label = uploadResource.label; resource.Label = label;
resource.Type = uploadResource.type; resource.Type = resourceType;
resource.DateCreation = DateTime.Now; resource.DateCreation = DateTime.Now;
resource.Data = stringResult; resource.InstanceId = instanceId;
Resource resourceCreated = _resourceService.Create(resource); Resource resourceCreated = _resourceService.Create(resource);
resources.Add(resourceCreated); resources.Add(resourceCreated);
} }
@ -177,6 +280,10 @@ namespace ManagerService.Controllers
{ {
return new BadRequestObjectResult(ex.Message) { }; return new BadRequestObjectResult(ex.Message) { };
} }
catch (FileLoadException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
return new ConflictObjectResult(ex.Message) { }; return new ConflictObjectResult(ex.Message) { };
@ -205,22 +312,25 @@ namespace ManagerService.Controllers
// Todo add some verification ? // Todo add some verification ?
Resource resource = new Resource(); Resource resource = new Resource();
resource.InstanceId = newResource.instanceId;
resource.Label = newResource.label; resource.Label = newResource.label;
resource.Type = newResource.type; resource.Type = newResource.type;
resource.Url = newResource.url;
resource.DateCreation = DateTime.Now; resource.DateCreation = DateTime.Now;
resource.Data = newResource.data; //resource.Data = newResource.data;
resource.InstanceId = newResource.instanceId;
Resource resourceCreated = _resourceService.Create(resource); Resource resourceCreated = _resourceService.Create(resource);
return new OkObjectResult(resourceCreated.ToDTO(resource.Type == ResourceType.ImageUrl)); return new OkObjectResult(resourceCreated.ToDTO()); // WITHOUT DATA
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
return new BadRequestObjectResult(ex.Message) {}; return new BadRequestObjectResult(ex.Message) { };
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
return new ConflictObjectResult(ex.Message) {}; return new ConflictObjectResult(ex.Message) { };
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -251,9 +361,11 @@ namespace ManagerService.Controllers
throw new KeyNotFoundException("Resource does not exist"); throw new KeyNotFoundException("Resource does not exist");
// Todo add some verification ? // Todo add some verification ?
resource.InstanceId = updatedResource.instanceId;
resource.Label = updatedResource.label; resource.Label = updatedResource.label;
resource.Type = updatedResource.type; resource.Type = updatedResource.type;
resource.Data = updatedResource.data; resource.Url = updatedResource.url;
//resource.Data = updatedResource.data; // NOT ALLOWED
Resource resourceModified = _resourceService.Update(updatedResource.id, resource); Resource resourceModified = _resourceService.Update(updatedResource.id, resource);
@ -261,11 +373,11 @@ namespace ManagerService.Controllers
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
return new BadRequestObjectResult(ex.Message) {}; return new BadRequestObjectResult(ex.Message) { };
} }
catch (KeyNotFoundException ex) catch (KeyNotFoundException ex)
{ {
return new NotFoundObjectResult(ex.Message) {}; return new NotFoundObjectResult(ex.Message) { };
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -290,12 +402,23 @@ namespace ManagerService.Controllers
if (id == null) if (id == null)
throw new ArgumentNullException("Resource param is null"); throw new ArgumentNullException("Resource param is null");
if (!_resourceService.IsExist(id)) var ressource = _resourceService.GetById(id);
if (ressource == null)
throw new KeyNotFoundException("Resource does not exist"); throw new KeyNotFoundException("Resource does not exist");
foreach (var configuration in _configurationService.GetAll(ressource.InstanceId))
{
if (configuration.ImageId == id)
{
configuration.ImageId = null;
configuration.ImageSource = null;
}
}
// Delete all resource occurence // Delete all resource occurence
foreach (var section in _sectionService.GetAll()) foreach (var section in _sectionService.GetAll(ressource.InstanceId))
{ {
if (section.ImageId == id) if (section.ImageId == id)
{ {
@ -310,25 +433,117 @@ namespace ManagerService.Controllers
mapDTO.iconResourceId = mapDTO.iconResourceId == id ? null : mapDTO.iconResourceId; mapDTO.iconResourceId = mapDTO.iconResourceId == id ? null : mapDTO.iconResourceId;
foreach (var point in mapDTO.points) foreach (var point in mapDTO.points)
{ {
foreach (var image in point.images) point.imageResourceId = point.imageResourceId == id ? null : point.imageResourceId;
foreach (var content in point.contents)
{ {
image.imageSource = image.imageResourceId == id ? null : image.imageSource; content.resourceUrl = content.resourceId == id ? null : content.resourceUrl;
image.imageResourceId = image.imageResourceId == id ? null : image.imageResourceId; content.resourceId = content.resourceId == id ? null : content.resourceId;
} }
} }
foreach (var categorie in mapDTO.categories)
{
categorie.iconUrl = categorie.iconResourceId == id ? null : categorie.iconUrl;
categorie.iconResourceId = categorie.iconResourceId == id ? null : categorie.iconResourceId;
}
section.Data = JsonConvert.SerializeObject(mapDTO); section.Data = JsonConvert.SerializeObject(mapDTO);
break; break;
case SectionType.Slider: case SectionType.Slider:
SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.Data); SliderDTO sliderDTO = JsonConvert.DeserializeObject<SliderDTO>(section.Data);
List<ImageDTO> imagesToKeep = new List<ImageDTO>(); List<ContentDTO> contentsToKeep = new List<ContentDTO>();
foreach (var image in sliderDTO.images) foreach (var content in sliderDTO.contents)
{ {
if (image.resourceId != id) if (content.resourceId != id)
imagesToKeep.Add(image); contentsToKeep.Add(content);
} }
sliderDTO.images = imagesToKeep; sliderDTO.contents = contentsToKeep;
section.Data = JsonConvert.SerializeObject(sliderDTO); section.Data = JsonConvert.SerializeObject(sliderDTO);
break; break;
case SectionType.Quizz:
QuizzDTO quizzDTO = JsonConvert.DeserializeObject<QuizzDTO>(section.Data);
foreach (var question in quizzDTO.questions)
{
if (question.label != null)
{
foreach (var questionLabel in question.label)
{
questionLabel.resourceUrl = questionLabel.resourceId == id ? null : questionLabel.resourceUrl;
questionLabel.resourceId = questionLabel.resourceId == id ? null : questionLabel.resourceId;
}
}
question.imageBackgroundResourceUrl = question.imageBackgroundResourceId == id ? null : question.imageBackgroundResourceUrl;
question.imageBackgroundResourceId = question.imageBackgroundResourceId == id ? null : question.imageBackgroundResourceId;
foreach (var response in question.responses)
{
if (response.label != null)
{
foreach (var responseLabel in response.label)
{
responseLabel.resourceUrl = responseLabel.resourceId == id ? null : responseLabel.resourceUrl;
responseLabel.resourceId = responseLabel.resourceId == id ? null : responseLabel.resourceId;
}
}
}
}
if (quizzDTO.bad_level != null)
{
if (quizzDTO.bad_level.label != null)
{
foreach (var badLevelLabel in quizzDTO.bad_level.label)
{
badLevelLabel.resourceUrl = badLevelLabel.resourceId == id ? null : badLevelLabel.resourceUrl;
badLevelLabel.resourceId = badLevelLabel.resourceId == id ? null : badLevelLabel.resourceId;
}
}
}
if (quizzDTO.medium_level != null)
{
if (quizzDTO.medium_level.label != null)
{
foreach (var medium_levelLabel in quizzDTO.medium_level.label)
{
medium_levelLabel.resourceUrl = medium_levelLabel.resourceId == id ? null : medium_levelLabel.resourceUrl;
medium_levelLabel.resourceId = medium_levelLabel.resourceId == id ? null : medium_levelLabel.resourceId;
}
}
}
if (quizzDTO.good_level != null)
{
if (quizzDTO.good_level.label != null)
{
foreach (var gooLevelLabel in quizzDTO.good_level.label)
{
gooLevelLabel.resourceUrl = gooLevelLabel.resourceId == id ? null : gooLevelLabel.resourceUrl;
gooLevelLabel.resourceId = gooLevelLabel.resourceId == id ? null : gooLevelLabel.resourceId;
}
}
}
if (quizzDTO.great_level != null)
{
if (quizzDTO.great_level.label != null)
{
foreach (var greatLevelLabel in quizzDTO.great_level.label)
{
greatLevelLabel.resourceUrl = greatLevelLabel.resourceId == id ? null : greatLevelLabel.resourceUrl;
greatLevelLabel.resourceId = greatLevelLabel.resourceId == id ? null : greatLevelLabel.resourceId;
}
}
}
section.Data = JsonConvert.SerializeObject(quizzDTO);
break;
case SectionType.Article:
ArticleDTO articleDTO = JsonConvert.DeserializeObject<ArticleDTO>(section.Data);
List<ContentDTO> contentsArticleToKeep = new List<ContentDTO>();
foreach (var content in articleDTO.contents)
{
if (content.resourceId != id)
contentsArticleToKeep.Add(content);
}
articleDTO.contents = contentsArticleToKeep;
section.Data = JsonConvert.SerializeObject(articleDTO);
break;
} }
_sectionService.Update(section.Id, section); _sectionService.Update(section.Id, section);
@ -352,5 +567,93 @@ namespace ManagerService.Controllers
return new ObjectResult(ex.Message) { StatusCode = 500 }; return new ObjectResult(ex.Message) { StatusCode = 500 };
} }
} }
/// <summary>
/// Create new ressources 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 async Task<ObjectResult> CreateFromJSON()
{
try
{
string json = System.IO.File.ReadAllText("C:/Users/ThomasFransolet/Documents/Documents/Perso/UNOV/MongoDB 10-10-24 - MyMuseum before migration/TabletDb.Resources.json");
var resourceAll = JsonConvert.DeserializeObject<List<ResourceOLDDTO>>(json); // Désérialiser en liste d'objets
using (StreamReader dataFile = new StreamReader("C:/Users/ThomasFransolet/Documents/Documents/Perso/UNOV/MongoDB 10-10-24 - MyMuseum before migration/TabletDb.ResourcesData.json"))
using (JsonTextReader dataReader = new JsonTextReader(dataFile))
{
while (dataReader.Read())
{
if (dataReader.TokenType == JsonToken.StartObject)
{
JObject resourceData = JObject.Load(dataReader);
Resource newResource = new Resource();
newResource.Id = (string)resourceData["ResourceId"];
var test = _resourceService.GetById(newResource.Id);
if (test == null)
{
// Rechercher la ressource correspondante dans resourceAll
var resource = resourceAll.FirstOrDefault(r => r._id.oid == newResource.Id);
if (resource != null && resource.InstanceId == "633ee379d9405f32f166f047")
{
newResource.Type = resource.Type;
newResource.DateCreation = resource.DateCreation.date;
newResource.Label = resource.Label;
newResource.InstanceId = resource.InstanceId;
var dataTest = (string)resourceData["Data"];
try {
// Uncomment if needed
/*var downloadUrl = await _firebaseStorageService.UploadBase64Async(dataTest, newResource.Id, newResource.InstanceId);
newResource.Url = downloadUrl;
Resource createdResource = _resourceService.Create(newResource);*/
}
catch (Exception e)
{
Console.WriteLine("resource id " + newResource.Id);
Console.WriteLine(e);
}
}
}
else
{
// Rechercher la ressource correspondante dans resourceAll
var resource = resourceAll.FirstOrDefault(r => r._id.oid == newResource.Id);
if (resource.Type != test.Type)
{
test.Type = resource.Type;
//_resourceService.Update(test.Id, test);
}
}
}
}
}
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 };
}
}
} }
} }

View File

@ -1,15 +1,21 @@
using Manager.Interfaces.DTO; using Manager.Helpers;
using Manager.Interfaces.DTO;
using Manager.Interfaces.Models; using Manager.Interfaces.Models;
using Manager.Services; using Manager.Services;
using ManagerService.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Mqtt.Client.AspNetCore.Services; using Mqtt.Client.AspNetCore.Services;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NSwag.Annotations; using NSwag.Annotations;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using System.Linq; using System.Linq;
using static System.Net.Mime.MediaTypeNames;
namespace ManagerService.Controllers namespace ManagerService.Controllers
{ {
@ -18,13 +24,17 @@ namespace ManagerService.Controllers
[OpenApiTag("Section", Description = "Section management")] [OpenApiTag("Section", Description = "Section management")]
public class SectionController : ControllerBase public class SectionController : ControllerBase
{ {
private ResourceDatabaseService _resourceService;
private SectionDatabaseService _sectionService; private SectionDatabaseService _sectionService;
private ConfigurationDatabaseService _configurationService; private ConfigurationDatabaseService _configurationService;
private readonly ILogger<SectionController> _logger; private readonly ILogger<SectionController> _logger;
private readonly IConfiguration _configuration;
public SectionController(ILogger<SectionController> logger, SectionDatabaseService sectionService, ConfigurationDatabaseService configurationService) public SectionController(IConfiguration configuration, ILogger<SectionController> logger, SectionDatabaseService sectionService, ConfigurationDatabaseService configurationService, ResourceDatabaseService resourceService)
{ {
_logger = logger; _logger = logger;
_configuration = configuration;
_resourceService = resourceService;
_sectionService = sectionService; _sectionService = sectionService;
_configurationService = configurationService; _configurationService = configurationService;
} }
@ -32,14 +42,35 @@ namespace ManagerService.Controllers
/// <summary> /// <summary>
/// Get a list of all section (summary) /// Get a list of all section (summary)
/// </summary> /// </summary>
/// <param name="id">id instance</param>
[ProducesResponseType(typeof(List<SectionDTO>), 200)] [ProducesResponseType(typeof(List<SectionDTO>), 200)]
[ProducesResponseType(typeof(string), 500)] [ProducesResponseType(typeof(string), 500)]
[HttpGet] [HttpGet]
public ObjectResult Get() public ObjectResult Get([FromQuery] string instanceId)
{ {
try try
{ {
List<Section> sections = _sectionService.GetAll(); 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())); return new OkObjectResult(sections.Select(r => r.ToDTO()));
} }
@ -205,6 +236,35 @@ namespace ManagerService.Controllers
} }
} }
/// <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> /// <summary>
/// Create a new section /// Create a new section
/// </summary> /// </summary>
@ -229,6 +289,7 @@ namespace ManagerService.Controllers
// Todo add some verification ? // Todo add some verification ?
Section section = new Section(); Section section = new Section();
section.InstanceId = newSection.instanceId;
section.Label = newSection.label; section.Label = newSection.label;
section.ImageId = newSection.imageId; section.ImageId = newSection.imageId;
section.ImageSource = newSection.imageSource; section.ImageSource = newSection.imageSource;
@ -240,40 +301,59 @@ namespace ManagerService.Controllers
section.Title = new List<TranslationDTO>(); section.Title = new List<TranslationDTO>();
section.Description = new List<TranslationDTO>(); section.Description = new List<TranslationDTO>();
section.Order = _sectionService.GetAllFromConfiguration(newSection.configurationId).Count; 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 // Preparation
List<string> languages = new List<string> { "FR", "NL", "EN", "DE" };//_configurationService.GetById(newSection.ConfigurationId).Languages; List<string> languages = _configuration.GetSection("SupportedLanguages").Get<List<string>>();
var contentArticle = new List<TranslationDTO>();
var mapDTO = new MapDTO(); // For menu dto var mapDTO = new MapDTO(); // For menu dto
var sliderDTO = new SliderDTO(); // For menu dto var sliderDTO = new SliderDTO(); // For menu dto
foreach (var language in languages) 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 title = new TranslationDTO();
TranslationDTO description = new TranslationDTO(); TranslationDTO description = new TranslationDTO();
TranslationDTO content = new TranslationDTO();
title.language = language.ToUpper(); title.language = language.ToUpper();
description.language = language.ToUpper(); description.language = language.ToUpper();
content.language = language.ToUpper();
switch (language.ToUpper()) switch (language.ToUpper())
{ {
case "FR": case "FR":
title.value = "Titre en français"; title.value = "Titre en français";
description.value = "Description en français"; description.value = "Description en français";
content.value = "Contenu en français";
break; break;
case "EN": case "EN":
title.value = "Title in english"; title.value = "Title in english";
description.value = "Description en anglais"; description.value = "Description en anglais";
content.value = "Contenu en anglais";
break; break;
case "NL": case "NL":
title.value = "Titre in dutch"; title.value = "Titre in dutch";
description.value = "Description en néerlandais"; description.value = "Description en néerlandais";
content.value = "Contenu en néerlandais";
break; break;
case "DE": case "DE":
title.value = "Titre en allemand"; title.value = "Titre en allemand";
description.value = "Description en allemand"; description.value = "Description en allemand";
content.value = "Contenu en allemand";
break; break;
} }
section.Title.Add(title); section.Title.Add(title);
section.Description.Add(description); section.Description.Add(description);
} contentArticle.Add(content);
}*/
section.Title = section.Title.OrderBy(t => t.language).ToList(); section.Title = section.Title.OrderBy(t => t.language).ToList();
section.Description = section.Description.OrderBy(d => d.language).ToList(); section.Description = section.Description.OrderBy(d => d.language).ToList();
@ -282,15 +362,18 @@ namespace ManagerService.Controllers
case SectionType.Map: case SectionType.Map:
mapDTO = new MapDTO(); mapDTO = new MapDTO();
mapDTO.mapType = MapTypeApp.hybrid; mapDTO.mapType = MapTypeApp.hybrid;
mapDTO.mapTypeMapbox = MapTypeMapBox.standard;
mapDTO.mapProvider = MapProvider.Google;
mapDTO.zoom = 18; mapDTO.zoom = 18;
mapDTO.points = new List<GeoPointDTO>(); mapDTO.points = new List<GeoPointDTO>();
mapDTO.categories = new List<CategorieDTO>();
section.Data = JsonConvert.SerializeObject(mapDTO); // Include all info from specific section as JSON section.Data = JsonConvert.SerializeObject(mapDTO); // Include all info from specific section as JSON
break; break;
case SectionType.Slider: case SectionType.Slider:
sliderDTO = new SliderDTO(); sliderDTO = new SliderDTO();
sliderDTO.images = new List<ImageDTO>(); sliderDTO.contents = new List<ContentDTO>();
section.Data = JsonConvert.SerializeObject(sliderDTO); // Include all info from specific section as JSON section.Data = JsonConvert.SerializeObject(sliderDTO); // Include all info from specific section as JSON
break; break;
@ -333,6 +416,35 @@ namespace ManagerService.Controllers
menuDTO.Sections.Add(section1DTO);*/ menuDTO.Sections.Add(section1DTO);*/
section.Data = JsonConvert.SerializeObject(menuDTO); // Include all info from specific section as JSON section.Data = JsonConvert.SerializeObject(menuDTO); // Include all info from specific section as JSON
break; 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); Section sectionCreated = _sectionService.Create(section);
@ -427,6 +539,7 @@ namespace ManagerService.Controllers
throw new KeyNotFoundException("Section does not exist"); throw new KeyNotFoundException("Section does not exist");
// Todo add some verification ? // Todo add some verification ?
section.InstanceId = updatedSection.instanceId;
section.Label = updatedSection.label; section.Label = updatedSection.label;
section.Title = updatedSection.title; section.Title = updatedSection.title;
section.Description = updatedSection.description; section.Description = updatedSection.description;
@ -437,6 +550,11 @@ namespace ManagerService.Controllers
section.IsSubSection = updatedSection.isSubSection; section.IsSubSection = updatedSection.isSubSection;
section.ParentId = updatedSection.parentId; section.ParentId = updatedSection.parentId;
section.Data = updatedSection.data; 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); Section sectionModified = _sectionService.Update(updatedSection.id, section);
@ -483,7 +601,7 @@ namespace ManagerService.Controllers
foreach (var updatedSection in updatedSectionsOrder) foreach (var updatedSection in updatedSectionsOrder)
{ {
Section section = _sectionService.GetById(updatedSection.id); Section section = _sectionService.GetById(updatedSection.id);
section.Order = updatedSection.order; section.Order = updatedSection.order.GetValueOrDefault();
_sectionService.Update(section.Id, section); _sectionService.Update(section.Id, section);
} }
@ -547,6 +665,471 @@ namespace ManagerService.Controllers
} }
} }
/// <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("633ee379d9405f32f166f047"); // get by instance ID (hardcoded Fort)
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;
case SectionType.Article:
var articleData = JsonConvert.DeserializeObject<ArticleDTO>(section.Data);
foreach (var content in articleData.contents)
{
content.resourceUrl = CheckAndUpdateURL(content.resourceUrl, _resourceService);
}
section.Data = JsonConvert.SerializeObject(articleData); // Include all info from specific section as JSON
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") || sourceURL.Contains("https://api.mymuseum.be")))
{
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
{
var i = 1;
string json = System.IO.File.ReadAllText("C:/Users/ThomasFransolet/Documents/Documents/Perso/UNOV/MongoDB 10-10-24 - MyMuseum before migration/TabletDb.Sections.json");
var sections = JsonConvert.DeserializeObject<SectionForJsonDTO[]>(json);
foreach (var sectionJSON in sections.Where(s => s.InstanceId == "633ee379d9405f32f166f047"))
{
// Todo add some verification ?
Section section = new Section();
section.Id = sectionJSON._id.oid;
section.InstanceId = "633ee379d9405f32f166f047"; // Fort hardcoded
section.Label = sectionJSON.Label;
section.ImageId = sectionJSON.ImageId;
section.ImageSource = sectionJSON.ImageSource;
section.ConfigurationId = sectionJSON.ConfigurationId;
section.DateCreation = sectionJSON.DateCreation.date;
section.IsSubSection = sectionJSON.IsSubSection;
section.ParentId = sectionJSON.ParentId;
section.Type = (SectionType)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:
// Fort don't use quizz for now piouf :)
/*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:
try {
var sectionArticle = JsonConvert.DeserializeObject<OldArticleDTO>(sectionJSON.Data);
ArticleDTO newArticle = new ArticleDTO();
newArticle.content = sectionArticle.content;
newArticle.isContentTop = sectionArticle.isContentTop;
newArticle.audioIds = sectionArticle.audioIds;
newArticle.isReadAudioAuto = sectionArticle.isReadAudioAuto;
newArticle.contents = new List<ContentDTO>();
foreach (var image in sectionArticle.images) // Migrate old images to contents
{
ContentDTO contentDTO = new ContentDTO();
contentDTO.title = image.title;
contentDTO.description = image.description;
contentDTO.resourceId = image.resourceId;
contentDTO.order = image.order;
contentDTO.resourceType = ResourceType.Image;
contentDTO.resourceUrl = image.source;
newArticle.contents.Add(contentDTO);
}
section.Data = JsonConvert.SerializeObject(newArticle); // Include all info from specific section as JSON
} catch (Exception e)
{
Console.WriteLine("Issue in article with id " + sectionJSON._id + e);
}
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;*/
}
if (_configurationService.IsExist(section.ConfigurationId))
{
i += 1;
//Section sectionCreated = _sectionService.Create(section);
}
else
{
}
}
var test = i;
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> /// <summary>
/// Useless, just to generate dto code /// Useless, just to generate dto code
/// </summary> /// </summary>
@ -606,5 +1189,65 @@ namespace ManagerService.Controllers
{ {
return new ObjectResult("PlayerMessageDTO") { StatusCode = 200 }; 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 };
}
} }
} }

View File

@ -86,7 +86,7 @@ namespace ManagerService.Controllers
/// Create an user /// Create an user
/// </summary> /// </summary>
/// <param name="newUser">New user info</param> /// <param name="newUser">New user info</param>
[AllowAnonymous] //[AllowAnonymous]
[ProducesResponseType(typeof(UserDetailDTO), 200)] [ProducesResponseType(typeof(UserDetailDTO), 200)]
[ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)] [ProducesResponseType(typeof(string), 409)]
@ -99,6 +99,9 @@ namespace ManagerService.Controllers
if (newUser == null) if (newUser == null)
throw new ArgumentNullException("User param is null"); throw new ArgumentNullException("User param is null");
if (newUser.InstanceId == null)
throw new ArgumentNullException("InstanceId is null");
newUser.Token = _tokenService.GenerateToken(newUser.Email).ToString(); newUser.Token = _tokenService.GenerateToken(newUser.Email).ToString();
newUser.DateCreation = DateTime.Now; newUser.DateCreation = DateTime.Now;

25
ManagerService/Dockerfile Normal file
View File

@ -0,0 +1,25 @@
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
RUN apt-get update && apt-get install -y apt-utils libgdiplus libc6-dev
WORKDIR /app
EXPOSE 80
VOLUME ["/etc/managerservice"]
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["ManagerService/ManagerService.csproj", "ManagerService/"]
COPY ["Manager.Interfaces/Manager.Interfaces.csproj", "Manager.Interfaces/"]
COPY ["Manager.Framework/Manager.Framework.csproj", "Manager.Framework/"]
RUN dotnet restore "ManagerService/ManagerService.csproj"
COPY . .
WORKDIR "/src/ManagerService"
RUN dotnet build "ManagerService.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "ManagerService.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ManagerService.dll"]

View File

@ -27,9 +27,9 @@ namespace Mqtt.Client.AspNetCore.Services
public MqttClientService(IMqttClientOptions options) public MqttClientService(IMqttClientOptions options)
{ {
var server = "localhost"; var server = "myinfomate.be";
#if DEBUG #if DEBUG
server = "localhost";//"192.168.31.96"; server = "myinfomate.be";//"192.168.31.96";
#endif #endif
this.options = options; this.options = options;
this.options = new MqttClientOptionsBuilder() this.options = new MqttClientOptionsBuilder()
@ -141,7 +141,7 @@ namespace Mqtt.Client.AspNetCore.Services
.WithRetainFlag(false) .WithRetainFlag(false)
.Build(); .Build();
if (mqttClient.IsConnected) if (mqttClient != null && mqttClient.IsConnected)
await mqttClient.PublishAsync(mqttMessage); await mqttClient.PublishAsync(mqttMessage);
} }

View File

@ -0,0 +1,125 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace ManagerService.Helpers
{
public static class ImageHelper
{
public static Size ResizeKeepAspect(this Size src, int maxWidth, int maxHeight, bool enlarge = false)
{
maxWidth = enlarge ? maxWidth : Math.Min(maxWidth, src.Width);
maxHeight = enlarge ? maxHeight : Math.Min(maxHeight, src.Height);
decimal rnd = Math.Min(maxWidth / (decimal)src.Width, maxHeight / (decimal)src.Height);
return new Size((int)Math.Round(src.Width * rnd), (int)Math.Round(src.Height * rnd));
}
// TO Byte[] or Image type
public static dynamic ResizeImage(Image image,
/* note changed names */
int canvasWidth, int canvasHeight,
/* new */
int originalWidth, int originalHeight, bool isImage = false)
{
byte[] convertedToBytes;
System.Drawing.Image thumbnail =
new Bitmap(canvasWidth, canvasHeight); // changed parm names
System.Drawing.Graphics graphic =
System.Drawing.Graphics.FromImage(thumbnail);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
/* ------------------ new code --------------- */
// Figure out the ratio
double ratioX = (double)canvasWidth / (double)originalWidth;
double ratioY = (double)canvasHeight / (double)originalHeight;
// use whichever multiplier is smaller
double ratio = ratioX < ratioY ? ratioX : ratioY;
// now we can get the new height and width
int newHeight = Convert.ToInt32(originalHeight * ratio);
int newWidth = Convert.ToInt32(originalWidth * ratio);
// Now calculate the X,Y position of the upper-left corner
// (one of these will always be zero)
int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2);
int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2);
graphic.Clear(Color.White); // white padding
graphic.DrawImage(image, posX, posY, newWidth, newHeight);
/* ------------- end new code ---------------- */
System.Drawing.Imaging.ImageCodecInfo[] info =
ImageCodecInfo.GetImageEncoders();
EncoderParameters encoderParameters;
encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,
100L);
if (isImage)
{
return thumbnail;
}
using (MemoryStream updatedImageMemorySteam = new MemoryStream())
{
thumbnail.Save(updatedImageMemorySteam, System.Drawing.Imaging.ImageFormat.Jpeg);
convertedToBytes = updatedImageMemorySteam.ToArray();
}
return convertedToBytes;
}
public static byte[] ResizeAndAddWatermark(Byte[] bytes, bool watermark, int maxWidth, int maxHeight)
{
byte[] convertedToBytes;
using (MemoryStream originalImageMemoryStream = new MemoryStream(bytes))
{
using (Image image = Image.FromStream(originalImageMemoryStream))
{
Image currentImage = image;
if (image.Width > maxWidth || image.Height > maxHeight)
{
Size newSize = ResizeKeepAspect(image.Size, maxWidth, maxHeight);
Image resizedImage = ImageHelper.ResizeImage(image, newSize.Width, newSize.Height, image.Width, image.Height, true);
currentImage = resizedImage;
}
if(watermark)
{
Font font = new Font("Arial", 25, FontStyle.Italic, GraphicsUnit.Pixel);
Color color = Color.DarkBlue;
Point point = new Point(currentImage.Width /2, (int)Math.Round(currentImage.Height - currentImage.Height * 0.1));
SolidBrush brush = new SolidBrush(color);
using (Graphics graphics = Graphics.FromImage(currentImage))
{
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
graphics.DrawString("fortsaintheribert.be", font, brush, point, stringFormat);
}
}
using (MemoryStream updatedImageMemorySteam = new MemoryStream())
{
currentImage.Save(updatedImageMemorySteam, System.Drawing.Imaging.ImageFormat.Jpeg);
convertedToBytes = updatedImageMemorySteam.ToArray();
}
}
}
return convertedToBytes;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Manager.Interfaces.DTO;
using Manager.Interfaces.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
namespace Manager.Helpers
{
public class LanguageInit
{
public static List<TranslationDTO> Init(string label, List<string> languages, bool toNull = false)
{
List<TranslationDTO> translations = new List<TranslationDTO>();
foreach (var language in languages)
{
var value = toNull ? null : $"{language} - {label}";
translations.Add(new TranslationDTO() { language = language.ToUpper(), value = value });
}
return translations;
}
}
}

View File

@ -1,17 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<UserSecretsId>d2e1a747-e204-4b43-bf93-abbd19c46417</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.1.2" /> <PackageReference Include="FirebaseAdmin" Version="3.0.0" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.10.0" /> <PackageReference Include="FirebaseStorage.net" Version="1.0.3" />
<PackageReference Include="MongoDB.Driver" Version="2.12.1" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.1.30" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="7.2.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
<PackageReference Include="MongoDB.Driver" Version="2.19.0" />
<PackageReference Include="MQTTnet.AspNetCore" Version="3.0.13" /> <PackageReference Include="MQTTnet.AspNetCore" Version="3.0.13" />
<PackageReference Include="NSwag.AspNetCore" Version="13.10.8" /> <PackageReference Include="NSwag.AspNetCore" Version="13.10.8" />
<PackageReference Include="System.Drawing.Common" Version="5.0.2" /> <PackageReference Include="System.Drawing.Common" Version="6.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.10.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.2.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<WebPublishMethod>Custom</WebPublishMethod>
<DockerPublish>true</DockerPublish>
<RegistryUrl>https://registry.unov.be</RegistryUrl>
<UserName>admin</UserName>
<PublishImageTag>version-2.0.0</PublishImageTag>
<PublishProvider>ContainerRegistry</PublishProvider>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<ProjectGuid>042e0bc4-8dcf-4eec-8420-c71aa85d4d99</ProjectGuid>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<WebPublishMethod>Custom</WebPublishMethod>
<DockerPublish>true</DockerPublish>
<RegistryUrl>https://registry.unov.be</RegistryUrl>
<UserName />
<PublishImageTag>latest</PublishImageTag>
<PublishProvider>ContainerRegistry</PublishProvider>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<ProjectGuid>042e0bc4-8dcf-4eec-8420-c71aa85d4d99</ProjectGuid>
</PropertyGroup>
</Project>

View File

@ -1,4 +1,5 @@
{ {
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": { "iisSettings": {
"windowsAuthentication": false, "windowsAuthentication": false,
"anonymousAuthentication": true, "anonymousAuthentication": true,
@ -7,15 +8,14 @@
"sslPort": 0 "sslPort": 0
} }
}, },
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": { "profiles": {
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "swagger", "launchUrl": "swagger",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_URLS": "http://*:5000/", "ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_URLS": "http://*:5000/"
} }
}, },
"ManagerService": { "ManagerService": {
@ -26,6 +26,22 @@
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
}, },
"applicationUrl": "https://localhost:5001;http://localhost:5000" "applicationUrl": "https://localhost:5001;http://localhost:5000"
},
"WSL": {
"commandName": "WSL2",
"launchBrowser": true,
"launchUrl": "https://localhost:5001/weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "https://localhost:5001;http://localhost:5000"
},
"distributionName": ""
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"publishAllPorts": true
} }
} }
} }

View File

@ -18,9 +18,9 @@ namespace Manager.Services
var database = client.GetDatabase("TabletDb"); var database = client.GetDatabase("TabletDb");
_Configurations = database.GetCollection<Configuration>("Configurations"); _Configurations = database.GetCollection<Configuration>("Configurations");
} }
public List<Configuration> GetAll() public List<Configuration> GetAll(string instanceId)
{ {
return _Configurations.Find(d => true).ToList(); return _Configurations.Find(d => d.InstanceId == instanceId).ToList();
} }
public Configuration GetById(string id) public Configuration GetById(string id)

View File

@ -19,9 +19,9 @@ namespace Manager.Services
_Devices = database.GetCollection<Device>("Devices"); _Devices = database.GetCollection<Device>("Devices");
} }
public List<Device> GetAll() public List<Device> GetAll(string instanceId)
{ {
return _Devices.Find(d => true).ToList(); return _Devices.Find(d => d.InstanceId == instanceId).ToList();
} }
public List<Device> GetAllConnected() public List<Device> GetAllConnected()

View File

@ -0,0 +1,18 @@
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
namespace ManagerService.Services
{
public class FirebaseService
{
public FirebaseService()
{
// Remplace le chemin par le chemin vers ton fichier JSON
var pathToKey = "C:/Users/ThomasFransolet/Documents/Documents/Perso/MuseeDeLaFraise/mymuseum-3b97f-firebase-adminsdk-sdbbn-7ec3e24a91.json";
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(pathToKey),
});
}
}
}

View File

@ -0,0 +1,64 @@
using Firebase.Storage;
using System;
using System.IO;
using System.Threading.Tasks;
namespace ManagerService.Services
{
public class FirebaseStorageService
{
private readonly FirebaseStorage _firebaseStorage;
public FirebaseStorageService()
{
// Remplace "your-project-id.appspot.com" par l'identifiant de ton bucket Firebase Storage
_firebaseStorage = new FirebaseStorage("mymuseum-3b97f.appspot.com");
}
public async Task<string> UploadFileAsync(Stream fileStream, string fileName, string instanceId)
{
// Téléversement du fichier dans le dossier "uploads"
var task = _firebaseStorage
.Child("pictures")
.Child(instanceId)
.Child(fileName)
.PutAsync(fileStream);
// Optionnel: Suivre la progression du téléversement
task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %");
// Attendre la fin du téléversement
var downloadUrl = await task;
return downloadUrl;
}
public async Task<string> UploadBase64Async(string base64String, string fileName, string instanceId)
{
// Convertir la chaîne base64 en un tableau de bytes
byte[] bytes = Convert.FromBase64String(base64String);
// Créer un flux de mémoire à partir des bytes
using (var stream = new MemoryStream(bytes))
{
// Téléversement du fichier dans le dossier "uploads"
var task = _firebaseStorage
.Child("pictures")
.Child(instanceId)
.Child(fileName)
.PutAsync(stream);
// Optionnel: Suivre la progression du téléversement
task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %");
// Attendre la fin du téléversement
var downloadUrl = await task;
return downloadUrl;
}
}
}
}

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Manager.Interfaces.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
namespace Manager.Services
{
public class InstanceDatabaseService
{
private readonly IMongoCollection<Instance> _Instances;
public InstanceDatabaseService(IConfiguration config)
{
var client = new MongoClient(config.GetConnectionString("TabletDb"));
var database = client.GetDatabase("TabletDb");
_Instances = database.GetCollection<Instance>("Instances");
}
public List<Instance> GetAll()
{
return _Instances.Find(m => true).ToList();
}
public Instance GetByName(string name)
{
return _Instances.Find<Instance>(i => i.Name == name).FirstOrDefault();
}
public Instance GetById(string id)
{
return _Instances.Find<Instance>(i => i.Id == id).FirstOrDefault();
}
public Instance GetByPinCode(int pinCode)
{
return _Instances.Find<Instance>(c => c.PinCode == pinCode).FirstOrDefault();
}
public bool IsExist(string id)
{
return _Instances.Find<Instance>(i => i.Id == id).FirstOrDefault() != null ? true : false;
}
public Instance Create(Instance instance)
{
_Instances.InsertOne(instance);
return instance;
}
public Instance Update(string id, Instance instanceIn)
{
_Instances.ReplaceOne(instance => instance.Id == id, instanceIn);
return instanceIn;
}
public void Remove(string id)
{
_Instances.DeleteOne(instance => instance.Id == id);
}
}
}

View File

@ -18,14 +18,14 @@ namespace Manager.Services
var database = client.GetDatabase("TabletDb"); var database = client.GetDatabase("TabletDb");
_Resources = database.GetCollection<Resource>("Resources"); _Resources = database.GetCollection<Resource>("Resources");
} }
public List<Resource> GetAll() public List<Resource> GetAll(string instanceId)
{ {
return _Resources.Find(r => true).ToList(); return _Resources.Find(r => r.InstanceId == instanceId).ToList();
} }
public Resource GetByType(ResourceType type) public List<Resource> GetAllByType(string instanceId, List<ResourceType> types)
{ {
return _Resources.Find<Resource>(r => r.Type == type).FirstOrDefault(); return _Resources.Find<Resource>(r => r.InstanceId == instanceId && types.Contains(r.Type)).ToList();
} }
public Resource GetById(string id) public Resource GetById(string id)

View File

@ -19,9 +19,9 @@ namespace Manager.Services
_Sections = database.GetCollection<Section>("Sections"); _Sections = database.GetCollection<Section>("Sections");
} }
public List<Section> GetAll() public List<Section> GetAll(string instanceId)
{ {
return _Sections.Find(s => !s.IsSubSection).ToList(); return _Sections.Find(s => !s.IsSubSection && s.InstanceId == instanceId).ToList();
} }
public List<Section> GetAllFromConfiguration(string configurationId) public List<Section> GetAllFromConfiguration(string configurationId)
@ -29,6 +29,21 @@ namespace Manager.Services
return _Sections.Find(s => !s.IsSubSection && s.ConfigurationId == configurationId).ToList(); return _Sections.Find(s => !s.IsSubSection && s.ConfigurationId == configurationId).ToList();
} }
public List<Section> GetAllFromConfigurationEvenSubsection(string configurationId)
{
return _Sections.Find(s => s.ConfigurationId == configurationId).ToList();
}
public List<string> GetAllIdsFromConfiguration(string configurationId)
{
return _Sections.Find(s => !s.IsSubSection && s.ConfigurationId == configurationId).ToList().Select(s => s.Id).ToList();
}
public List<Section> GetAllWeatherSectionsFromConfiguration(string configurationId)
{
return _Sections.Find(s => s.ConfigurationId == configurationId && s.Type == SectionType.Weather).ToList();
}
public List<Section> GetAllSubSection(string parentId) public List<Section> GetAllSubSection(string parentId)
{ {
return _Sections.Find(s => s.IsSubSection && s.ParentId == parentId).ToList(); return _Sections.Find(s => s.IsSubSection && s.ParentId == parentId).ToList();

View File

@ -13,6 +13,7 @@ using Microsoft.IdentityModel.Tokens;
using Manager.Framework.Business; using Manager.Framework.Business;
using Manager.Interfaces.DTO; using Manager.Interfaces.DTO;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using Manager.Services;
namespace ManagerService.Service.Services namespace ManagerService.Service.Services
{ {
@ -24,6 +25,7 @@ namespace ManagerService.Service.Services
private readonly ILogger<TokensService> _logger; private readonly ILogger<TokensService> _logger;
private readonly TokensSettings _tokenSettings; private readonly TokensSettings _tokenSettings;
private readonly ProfileLogic _profileLogic; private readonly ProfileLogic _profileLogic;
private InstanceDatabaseService _instanceService;
private readonly SigningCredentials _signingCredentials; private readonly SigningCredentials _signingCredentials;
@ -35,11 +37,12 @@ namespace ManagerService.Service.Services
/// <param name="context">Database context</param> /// <param name="context">Database context</param>
/// <param name="profileLogic">Profile logic</param> /// <param name="profileLogic">Profile logic</param>
/// <param name="emailClient">Email client</param> /// <param name="emailClient">Email client</param>
public TokensService(ILogger<TokensService> logger, IOptions<TokensSettings> tokenSettings, ProfileLogic profileLogic) public TokensService(ILogger<TokensService> logger, IOptions<TokensSettings> tokenSettings, ProfileLogic profileLogic, InstanceDatabaseService instanceService)
{ {
_logger = logger; _logger = logger;
_tokenSettings = tokenSettings.Value; _tokenSettings = tokenSettings.Value;
_profileLogic = profileLogic; _profileLogic = profileLogic;
_instanceService = instanceService;
var key = Encoding.UTF8.GetBytes(_tokenSettings.Secret); var key = Encoding.UTF8.GetBytes(_tokenSettings.Secret);
_signingCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature); _signingCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);
@ -51,17 +54,16 @@ namespace ManagerService.Service.Services
/// <param name="email">Email</param> /// <param name="email">Email</param>
/// <param name="password">Password</param> /// <param name="password">Password</param>
/// <returns>Token DTO in case of success</returns> /// <returns>Token DTO in case of success</returns>
public TokenDTO Authenticate(string email, string password) public TokenDTO Authenticate(User user, string password)
{ {
try try
{ {
var claims = new List<System.Security.Claims.Claim>(); var claims = new List<System.Security.Claims.Claim>();
var expiration = DateTime.UtcNow.AddMinutes(_tokenSettings.AccessTokenExpiration); var expiration = DateTime.UtcNow.AddMinutes(_tokenSettings.AccessTokenExpiration);
// Todo nothing good here.. _profileLogic.TestPassword(user.Email, user.Password, password);
var profile = _profileLogic.Authenticate(email, password);
claims.Add(new Claim(ClaimTypes.Email, email)); claims.Add(new Claim(ClaimTypes.Email, user.Email));
// TODO: add refresh token support // TODO: add refresh token support
@ -74,30 +76,34 @@ namespace ManagerService.Service.Services
}; };
var token = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.CreateToken(tokenDescriptor);
var instance = _instanceService.GetById(user.InstanceId);
return new TokenDTO() return new TokenDTO()
{ {
access_token = tokenHandler.WriteToken(token), access_token = tokenHandler.WriteToken(token),
expires_in = _tokenSettings.AccessTokenExpiration * 60, expires_in = _tokenSettings.AccessTokenExpiration * 60,
expiration = new DateTimeOffset(token.ValidTo), expiration = new DateTimeOffset(token.ValidTo),
token_type = "Bearer", token_type = "Bearer",
scope = Security.Scope scope = Security.Scope,
instanceId = user.InstanceId,
pinCode = instance.PinCode
}; };
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger?.LogError(ex, $"Authenticate error for user '{email}': unauthorized access"); _logger?.LogError(ex, $"Authenticate error for user '{user.Email}': unauthorized access");
throw; throw;
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger?.LogError(ex, $"Authenticate error for user '{email}': {ex.Message}"); _logger?.LogError(ex, $"Authenticate error for user '{user.Email}': {ex.Message}");
throw; throw;
} }
} }
public object GenerateToken(string username) public object GenerateToken(string username)
{ {
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("WVD[&vAwis9=#883bM$FRc0Mw8h")); // Put the secret in a file or something var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenSettings.Secret)); // Put the secret in a file or something
var claims = new Claim[] { var claims = new Claim[] {
new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Name, username),

View File

@ -20,22 +20,27 @@ namespace Manager.Services
} }
public List<User> GetAll() public List<User> GetAll()
{ {
return _Users.Find(m => true).ToList(); return _Users.Find(u => true).ToList();
} }
public User GetByEmail(string email) public User GetByEmail(string email)
{ {
return _Users.Find<User>(m => m.Email == email).FirstOrDefault(); return _Users.Find<User>(u => u.Email == email).FirstOrDefault();
} }
public User GetById(string id) public User GetById(string id)
{ {
return _Users.Find<User>(m => m.Id == id).FirstOrDefault(); return _Users.Find<User>(u => u.Id == id).FirstOrDefault();
}
public List<User> GetByInstanceId(string id)
{
return _Users.Find<User>(u => u.InstanceId == id).ToList();
} }
public bool IsExist(string id) public bool IsExist(string id)
{ {
return _Users.Find<User>(d => d.Id == id).FirstOrDefault() != null ? true : false; return _Users.Find<User>(u => u.Id == id).FirstOrDefault() != null ? true : false;
} }
public User Create(User user) public User Create(User user)

View File

@ -1,10 +1,13 @@
using Firebase.Storage;
using Manager.Framework.Business; using Manager.Framework.Business;
using Manager.Framework.Models; using Manager.Framework.Models;
using Manager.Helpers;
using Manager.Interfaces.Models; using Manager.Interfaces.Models;
using Manager.Services; using Manager.Services;
using ManagerService.Extensions; using ManagerService.Extensions;
using ManagerService.Service; using ManagerService.Service;
using ManagerService.Service.Services; using ManagerService.Service.Services;
using ManagerService.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Diagnostics;
@ -132,14 +135,20 @@ namespace ManagerService
}; };
}); });
#if RELEASE
services.AddMqttClientHostedService(); services.AddMqttClientHostedService();
#endif
services.AddScoped(typeof(ProfileLogic)); services.AddScoped(typeof(ProfileLogic));
services.AddScoped<TokensService>(); services.AddScoped<TokensService>();
services.AddScoped<UserDatabaseService>(); services.AddScoped<UserDatabaseService>();
services.AddScoped<SectionDatabaseService>(); services.AddScoped<SectionDatabaseService>();
services.AddScoped<ConfigurationDatabaseService>(); services.AddScoped<ConfigurationDatabaseService>();
services.AddScoped<ResourceDatabaseService>(); services.AddScoped<ResourceDatabaseService>();
services.AddScoped<LanguageInit>();
services.AddScoped<DeviceDatabaseService>(); services.AddScoped<DeviceDatabaseService>();
services.AddScoped<InstanceDatabaseService>();
services.AddScoped<FirebaseService>();
services.AddScoped<FirebaseStorageService>();
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -151,11 +160,12 @@ namespace ManagerService
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
//app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseExceptionHandler(HandleError);
} }
app.UseHttpsRedirection(); app.UseExceptionHandler(HandleError);
//app.UseHttpsRedirection();
app.UseRouting(); app.UseRouting();
app.UseAuthentication(); app.UseAuthentication();

View File

@ -1,8 +1,11 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
//"TabletDb": "mongodb://admin:MioTech4ever!@localhost:27017" //DEV //"TabletDb": "mongodb://admin:MioTech4ever!@localhost:27017" //DEV
//"TabletDb": "mongodb://admin:MioTech4ever!@localhost:27017" //PROD - Thomas //"TabletDb": "mongodb://admin:MioTech4ever!@localhost:27017", //PROD - Thomas
"TabletDb": "mongodb://admin:mdlf2021!@localhost:27017" //PROD //"TabletDb": "mongodb://admin:MioTech4ever!@192.168.31.140:27017" //PROD - Thomas
//"TabletDb": "mongodb://admin:mdlf2021!@localhost:27017" //PROD MDLF
//"TabletDb": "mongodb://admin:MyMuseum2022!@51.77.222.154:27017", //PROD MyMuseum
"TabletDb": "mongodb://admin:MyInfoMate2023!@135.125.232.116:27017" //PROD MyInfoMate
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
@ -13,7 +16,7 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"Tokens": { "Tokens": {
"Secret": "WVD[&vAwis9=#883bM$FRc0Mw8h", "Secret": "WVD[&vAwis9=#883bM$FRc0kdKJdfkkjlksd4554qsasadd54df875ds4fqsf5Mw8h",
"AccessTokenExpiration": 86400, "AccessTokenExpiration": 86400,
"RefreshTokenExpiration": 518400 "RefreshTokenExpiration": 518400
}, },
@ -30,8 +33,10 @@
}, },
"ClientSettings": { "ClientSettings": {
"Id": "ManagerService", "Id": "ManagerService",
"UserName": "admin", "UserName": "user1", //admin
"Password": "mdlf2021!" "Password": "MyInfoMate2023!" //mdlf2021!
}, },
"Urls": "http://localhost:5002" "SupportedLanguages": [ "FR", "NL", "EN", "DE", "IT", "ES", "PL", "CN", "AR", "UK" ],
"OpenWeatherApiKey": "d489973b4c09ddc5fb56bd7b9270bbef"
//"Urls": "http://[::]:80"
} }

View File

@ -0,0 +1 @@
Ajout du quizz

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,8 @@
{
"runtimeOptions": {
"additionalProbingPaths": [
"C:\\Users\\thoma\\.dotnet\\store\\|arch|\\|tfm|",
"C:\\Users\\thoma\\.nuget\\packages"
]
}
}

View File

@ -0,0 +1,14 @@
{
"runtimeOptions": {
"tfm": "netcoreapp3.1",
"framework": {
"name": "Microsoft.AspNetCore.App",
"version": "3.1.0"
},
"configProperties": {
"System.GC.Server": true,
"System.Reflection.Metadata.MetadataUpdater.IsSupported": false,
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More