From f35c89f861c0dc1f3a11daefb1f9a499b61a2e78 Mon Sep 17 00:00:00 2001 From: Thomas Fransolet Date: Sat, 28 Mar 2020 19:01:41 +0100 Subject: [PATCH] Add Provider controller.. Call a DBService in service is null.. Blocked. --- .../Controllers/Devices/DeviceController.cs | 11 +- .../Controllers/Devices/ProviderController.cs | 134 ++++++++++++++++++ .../MyControlPanel/TokenController.cs | 4 +- .../MyControlPanel/UserController.cs | 12 +- MyCore/DTO/MyControlPanel/ProviderDTO.cs | 1 + .../{ => Database}/Automation.cs | 0 .../MyControlPanel/{ => Database}/Device.cs | 5 +- .../MyControlPanel/{ => Database}/Group.cs | 0 .../{ => Database}/Information.cs | 0 .../MyControlPanel/{ => Database}/Location.cs | 0 .../MyControlPanel/{ => Database}/Provider.cs | 4 + .../MyControlPanel/{ => Database}/UserInfo.cs | 5 +- MyCore/Services/Devices/DeviceService.cs | 22 +-- .../{ => SupportedDevices}/ArloService.cs | 58 ++++---- .../{ => SupportedDevices}/MerossService.cs | 0 .../{ => SupportedDevices}/YeelightService.cs | 0 .../Database/ProviderDatabaseService.cs | 8 +- .../MyControlPanel/ProviderService.cs | 79 +++++++++++ 18 files changed, 287 insertions(+), 56 deletions(-) create mode 100644 MyCore/Controllers/Devices/ProviderController.cs rename MyCore/Models/MyControlPanel/{ => Database}/Automation.cs (100%) rename MyCore/Models/MyControlPanel/{ => Database}/Device.cs (91%) rename MyCore/Models/MyControlPanel/{ => Database}/Group.cs (100%) rename MyCore/Models/MyControlPanel/{ => Database}/Information.cs (100%) rename MyCore/Models/MyControlPanel/{ => Database}/Location.cs (100%) rename MyCore/Models/MyControlPanel/{ => Database}/Provider.cs (91%) rename MyCore/Models/MyControlPanel/{ => Database}/UserInfo.cs (94%) rename MyCore/Services/Devices/{ => SupportedDevices}/ArloService.cs (89%) rename MyCore/Services/Devices/{ => SupportedDevices}/MerossService.cs (100%) rename MyCore/Services/Devices/{ => SupportedDevices}/YeelightService.cs (100%) create mode 100644 MyCore/Services/MyControlPanel/ProviderService.cs diff --git a/MyCore/Controllers/Devices/DeviceController.cs b/MyCore/Controllers/Devices/DeviceController.cs index 91d9f3a..efaae18 100644 --- a/MyCore/Controllers/Devices/DeviceController.cs +++ b/MyCore/Controllers/Devices/DeviceController.cs @@ -114,13 +114,14 @@ namespace MyCore.Controllers.Devices { try { - if (providerId == null) - throw new KeyNotFoundException("Provider id is null"); - if (userId == null && UserService.IsExist(userId)) throw new KeyNotFoundException("User not found"); - List devicesCreated = DeviceService.CreateFromProvider(providerId); + Provider provider = ProviderService.GetProviderById(userId, providerId); + if (provider != null) + throw new KeyNotFoundException("Provider id is null"); + + List devicesCreated = DeviceService.CreateFromProvider(provider); return new OkObjectResult(devicesCreated); @@ -147,7 +148,7 @@ namespace MyCore.Controllers.Devices try { if (!_DeviceDatabaseService.IsExist(deviceId)) - throw new KeyNotFoundException("Location does not exist"); + throw new KeyNotFoundException("Device does not exist"); DeviceDetailDTO deviceUpdated = DeviceService.CreateOrUpdate(deviceDetailDTO, false); diff --git a/MyCore/Controllers/Devices/ProviderController.cs b/MyCore/Controllers/Devices/ProviderController.cs new file mode 100644 index 0000000..9569220 --- /dev/null +++ b/MyCore/Controllers/Devices/ProviderController.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using MongoDB.Bson; +using MyCore.DTO.Common; +using MyCore.DTO.MyControlPanel; +using MyCore.Models; +using MyCore.Models.MyControlPanel; +using MyCore.Services; +using MyCore.Services.Devices; +using MyCore.Services.MyControlPanel; + +namespace MyCore.Controllers.Devices +{ + //[Authorize(Roles = "Admin")] + [Authorize] + [Route("api/provider")] + [ApiController] + public class ProviderController : ControllerBase + { + + // GET: Devices + /// + /// Get all user providers + /// + [ProducesResponseType(typeof(List), 200)] + [HttpGet] + public ObjectResult GetAll(string userId) + { + try + { + List providers = ProviderService.GetAll(userId); + + List providersDTO = providers.Select(p => p.ToDTO()).ToList(); + + return new OkObjectResult(providersDTO); + } + catch (Exception ex) + { + return new ObjectResult(ex.Message) { StatusCode = 500 }; + } + } + + /// + /// Create a provider + /// + /// User Id + /// Provider to create + [ProducesResponseType(typeof(ProviderDTO), 200)] + [HttpPost] + public ObjectResult Create(string userId, [FromBody] ProviderDTO providerDTO) + { + try + { + + if (userId == null && UserService.IsExist(userId)) + throw new KeyNotFoundException("User not found"); + + if (providerDTO == null) + throw new KeyNotFoundException("Provider is null"); + + ProviderDTO providerCreated = ProviderService.CreateOrUpdate(userId, providerDTO, true); + + return new OkObjectResult(providerCreated); + + } + catch (KeyNotFoundException ex) + { + return new BadRequestObjectResult(ex.Message) { StatusCode = 404 }; + } + catch (Exception ex) + { + return new ObjectResult(ex.Message) { StatusCode = 500 }; + } + } + + /// + /// Update a provider + /// + /// User Id + /// Provider to update + [ProducesResponseType(typeof(DeviceDetailDTO), 200)] + [HttpPut("{deviceId}")] + public ObjectResult Update(string userId, [FromBody] ProviderDTO providerDTO) + { + try + { + if (userId == null && UserService.IsExist(userId)) + throw new KeyNotFoundException("User not found"); + + if (!ProviderService.IsExist(userId, providerDTO.Id)) + throw new KeyNotFoundException("Provider does not exist"); + + ProviderDTO providerUpdated = ProviderService.CreateOrUpdate(userId, providerDTO, false); + + return new OkObjectResult(providerUpdated); + } + catch (KeyNotFoundException ex) + { + return new BadRequestObjectResult(ex.Message) { StatusCode = 404 }; + } + catch (Exception ex) + { + return new ObjectResult(ex.Message) { StatusCode = 500 }; + } + } + + /// + /// Delete a provider + /// + /// Id of provider to delete + [HttpDelete("{providerId}")] + public ObjectResult Delete(string providerId) + { + try + { + // Check if exist + // TODO + // ProviderDatabaseService.Remove(providerId); + + return new OkObjectResult(201); + } + catch (Exception ex) + { + return new ObjectResult(ex.Message) { StatusCode = 500 }; + } + } + } + } + diff --git a/MyCore/Controllers/MyControlPanel/TokenController.cs b/MyCore/Controllers/MyControlPanel/TokenController.cs index b2730f0..3e93f80 100644 --- a/MyCore/Controllers/MyControlPanel/TokenController.cs +++ b/MyCore/Controllers/MyControlPanel/TokenController.cs @@ -38,7 +38,7 @@ namespace MyCore.Controllers if (IsValidUserAndPasswordCombination(tokenDTO.Email, tokenDTO.Password)) { - UserInfo user = _userService.GetUserByEmail(tokenDTO.Email); + UserInfo user = _userService.GetByEmail(tokenDTO.Email); user.Token = _tokenService.GenerateToken(tokenDTO.Email).ToString(); return user; @@ -49,7 +49,7 @@ namespace MyCore.Controllers private bool IsValidUserAndPasswordCombination(string email, string password) { // Test if is database and is correct - List users = _userService.GetUsers(); + List users = _userService.GetAll(); UserInfo user = users.Where(u => u.Email == email).FirstOrDefault(); diff --git a/MyCore/Controllers/MyControlPanel/UserController.cs b/MyCore/Controllers/MyControlPanel/UserController.cs index 8e3fdb7..641d986 100644 --- a/MyCore/Controllers/MyControlPanel/UserController.cs +++ b/MyCore/Controllers/MyControlPanel/UserController.cs @@ -49,14 +49,14 @@ namespace MyCore.Controllers { if (id != null) { - List users = _userService.GetUsers(); + List users = _userService.GetAll(); if (!users.Select(u => u.Id).Contains(id)) { return Conflict("This user was not found"); } - return _userService.GetUserById(id); + return _userService.GetById(id); } return StatusCode(500); } @@ -74,14 +74,14 @@ namespace MyCore.Controllers newUser.Token = _tokenService.GenerateToken(newUser.Email).ToString(); newUser.DateCreation = DateTime.Now; - List users = _userService.GetUsers(); + List users = _userService.GetAll(); if (users.Select(u => u.Email).Contains(newUser.Email)) { return Conflict("This Email is already used"); } - UserInfo userCreated = _userService.CreateUser(newUser); + UserInfo userCreated = _userService.Create(newUser); return userCreated; } @@ -98,7 +98,7 @@ namespace MyCore.Controllers { if (updatedUser != null) { - List users = _userService.GetUsers(); + List users = _userService.GetAll(); if (!users.Select(u => u.Email).Contains(updatedUser.Email)) { @@ -119,7 +119,7 @@ namespace MyCore.Controllers { if (id != null) { - List users = _userService.GetUsers(); + List users = _userService.GetAll(); if (!users.Select(u => u.Id).Contains(id)) { diff --git a/MyCore/DTO/MyControlPanel/ProviderDTO.cs b/MyCore/DTO/MyControlPanel/ProviderDTO.cs index 2c51d11..522ef4e 100644 --- a/MyCore/DTO/MyControlPanel/ProviderDTO.cs +++ b/MyCore/DTO/MyControlPanel/ProviderDTO.cs @@ -9,6 +9,7 @@ namespace MyCore.DTO.MyControlPanel { public string Id { get; set; } public string Name { get; set; } + public string UserId { get; set; } public string Username { get; set; } public string Password { get; set; } // TODO ENCRYPTED public string ApiKey { get; set; } // TODO ENCRYPTED diff --git a/MyCore/Models/MyControlPanel/Automation.cs b/MyCore/Models/MyControlPanel/Database/Automation.cs similarity index 100% rename from MyCore/Models/MyControlPanel/Automation.cs rename to MyCore/Models/MyControlPanel/Database/Automation.cs diff --git a/MyCore/Models/MyControlPanel/Device.cs b/MyCore/Models/MyControlPanel/Database/Device.cs similarity index 91% rename from MyCore/Models/MyControlPanel/Device.cs rename to MyCore/Models/MyControlPanel/Database/Device.cs index 8494c5e..ab6438e 100644 --- a/MyCore/Models/MyControlPanel/Device.cs +++ b/MyCore/Models/MyControlPanel/Database/Device.cs @@ -14,7 +14,6 @@ namespace MyCore.Models.MyControlPanel /// public class Device { - private LocationDatabaseService _LocationDatabaseService; [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } @@ -71,7 +70,7 @@ namespace MyCore.Models.MyControlPanel Id = Id, Name = Name, ConnectionStatus = ConnectionStatus, - Location = _LocationDatabaseService.GetById(LocationId).ToDTO(), // Check if correct way + //Location = _LocationDatabaseService.GetById(LocationId).ToDTO(), // Check if correct way Battery = Battery, BatteryStatus = BatteryStatus }; @@ -84,7 +83,7 @@ namespace MyCore.Models.MyControlPanel Id = Id, Name = Name, ConnectionStatus = ConnectionStatus, - Location = _LocationDatabaseService.GetById(LocationId).ToDTO(), // Check if correct way + //Location = _LocationDatabaseService.GetById(LocationId).ToDTO(), // Check if correct way MeansOfCommunications = MeansOfCommunications, CreatedDate = CreatedDate, UpdatedDate = UpdatedDate, diff --git a/MyCore/Models/MyControlPanel/Group.cs b/MyCore/Models/MyControlPanel/Database/Group.cs similarity index 100% rename from MyCore/Models/MyControlPanel/Group.cs rename to MyCore/Models/MyControlPanel/Database/Group.cs diff --git a/MyCore/Models/MyControlPanel/Information.cs b/MyCore/Models/MyControlPanel/Database/Information.cs similarity index 100% rename from MyCore/Models/MyControlPanel/Information.cs rename to MyCore/Models/MyControlPanel/Database/Information.cs diff --git a/MyCore/Models/MyControlPanel/Location.cs b/MyCore/Models/MyControlPanel/Database/Location.cs similarity index 100% rename from MyCore/Models/MyControlPanel/Location.cs rename to MyCore/Models/MyControlPanel/Database/Location.cs diff --git a/MyCore/Models/MyControlPanel/Provider.cs b/MyCore/Models/MyControlPanel/Database/Provider.cs similarity index 91% rename from MyCore/Models/MyControlPanel/Provider.cs rename to MyCore/Models/MyControlPanel/Database/Provider.cs index e2de1f3..0aa7482 100644 --- a/MyCore/Models/MyControlPanel/Provider.cs +++ b/MyCore/Models/MyControlPanel/Database/Provider.cs @@ -16,6 +16,10 @@ namespace MyCore.Models.MyControlPanel [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } + [BsonElement("UserId")] + [BsonRequired] + public string UserId { get; set; } + [BsonElement("Name")] [BsonRequired] public string Name { get; set; } diff --git a/MyCore/Models/MyControlPanel/UserInfo.cs b/MyCore/Models/MyControlPanel/Database/UserInfo.cs similarity index 94% rename from MyCore/Models/MyControlPanel/UserInfo.cs rename to MyCore/Models/MyControlPanel/Database/UserInfo.cs index 3220133..12374ba 100644 --- a/MyCore/Models/MyControlPanel/UserInfo.cs +++ b/MyCore/Models/MyControlPanel/Database/UserInfo.cs @@ -81,12 +81,11 @@ namespace MyCore.Models [BsonElement("Groups")] public Group[] Groups { get; set; } - // TODO - /*[BsonElement("ScreenConfigurationIds")] + [BsonElement("ScreenConfigurationIds")] public ScreenConfiguration[] ScreenConfigurationIds { get; set; } [BsonElement("DeviceIds")] - public ScreenDevice[] DeviceIds { get; set; }*/ + public ScreenDevice[] DeviceIds { get; set; } } } diff --git a/MyCore/Services/Devices/DeviceService.cs b/MyCore/Services/Devices/DeviceService.cs index a898e56..c04d94a 100644 --- a/MyCore/Services/Devices/DeviceService.cs +++ b/MyCore/Services/Devices/DeviceService.cs @@ -16,6 +16,13 @@ namespace MyCore.Services.Devices private static ProviderDatabaseService _ProviderDatabaseService; private static LocationDatabaseService _LocationDatabaseService; + public DeviceService(DeviceDatabaseService DeviceDatabaseService, ProviderDatabaseService ProviderDatabaseService, LocationDatabaseService LocationDatabaseService) + { + _DeviceDatabaseService = DeviceDatabaseService; + _ProviderDatabaseService = ProviderDatabaseService; + _LocationDatabaseService = LocationDatabaseService; + } + public static DeviceDetailDTO CreateOrUpdate(DeviceDetailDTO deviceDetailDTO, bool create) { Device device; @@ -55,27 +62,24 @@ namespace MyCore.Services.Devices return _DeviceDatabaseService.Update(device.Id, device).ToDTO(); } - public static List CreateFromProvider(string providerId) + public static List CreateFromProvider(Provider provider) { - // TODO ! Device device = new Device(); - Provider provider = new Provider(); - if (_ProviderDatabaseService.IsExist(providerId)) - provider = _ProviderDatabaseService.GetById(providerId); - else - throw new KeyNotFoundException("Provider does not exist"); + if (!ProviderService.IsProviderSupported(provider.Name)) + throw new KeyNotFoundException("Provider is not yet supported"); switch (provider.Name) { case "Arlo": + ArloService arloService = new ArloService(provider.Username, provider.Password); break; case "Meross": + break; case "Yeelight": + break; - default: - throw new KeyNotFoundException("Provider is not yet supported"); } List createdDevice = new List(); diff --git a/MyCore/Services/Devices/ArloService.cs b/MyCore/Services/Devices/SupportedDevices/ArloService.cs similarity index 89% rename from MyCore/Services/Devices/ArloService.cs rename to MyCore/Services/Devices/SupportedDevices/ArloService.cs index b40d0b7..2e08de7 100644 --- a/MyCore/Services/Devices/ArloService.cs +++ b/MyCore/Services/Devices/SupportedDevices/ArloService.cs @@ -107,11 +107,13 @@ namespace MyCore.Services LIBRARY } - public ArloService() + public ArloService(string username, string password) { - try { + /*_email = username; + _password = password;*/ + // LOGIN var loginTask = Task.Run(() => RequestURI(new Uri(_loginUrl), RequestType.Post, Request.LOGIN)); loginTask.Wait(); @@ -122,28 +124,6 @@ namespace MyCore.Services var data = ((JObject)JsonConvert.DeserializeObject(loginTask.Result))["data"]; resultToken = JsonConvert.DeserializeObject(data.ToString()); - // GET DEVICE LIST - var deviceTask = Task.Run(() => RequestURI(new Uri(_userDevicesUrl), RequestType.Get, Request.DEVICES)); - deviceTask.Wait(); - - if (deviceTask.Result != "") - { - data = ((JObject)JsonConvert.DeserializeObject(deviceTask.Result))["data"]; - // RETRIEVE ALL ARLO DEVICES - allArloDevices = JsonConvert.DeserializeObject>(data.ToString()); - } - - // GET USER LIBRARY - var libraryTask = Task.Run(() => RequestURI(new Uri(_userLibraryUrl), RequestType.Post, Request.LIBRARY)); - libraryTask.Wait(); - - if (libraryTask.Result != "") - { - data = ((JObject)JsonConvert.DeserializeObject(libraryTask.Result))["data"]; - // RETRIEVE ALL DATA IN USER LIBRARY - allUserMedias = JsonConvert.DeserializeObject>(data.ToString()); - } - //SSE CONNEXION ConnexionToSSE(); } @@ -207,6 +187,36 @@ namespace MyCore.Services } } + public List GetAllDevices() { + // GET DEVICE LIST + var deviceTask = Task.Run(() => RequestURI(new Uri(_userDevicesUrl), RequestType.Get, Request.DEVICES)); + deviceTask.Wait(); + + if (deviceTask.Result != "") + { + var data = ((JObject)JsonConvert.DeserializeObject(deviceTask.Result))["data"]; + // RETRIEVE ALL ARLO DEVICES + allArloDevices = JsonConvert.DeserializeObject>(data.ToString()); + } + + return allArloDevices; + } + + public List GetUserLibrary() { + // GET USER LIBRARY + var libraryTask = Task.Run(() => RequestURI(new Uri(_userLibraryUrl), RequestType.Post, Request.LIBRARY)); + libraryTask.Wait(); + + if (libraryTask.Result != "") + { + var data = ((JObject)JsonConvert.DeserializeObject(libraryTask.Result))["data"]; + // RETRIEVE ALL DATA IN USER LIBRARY + allUserMedias = JsonConvert.DeserializeObject>(data.ToString()); + } + + return allUserMedias; + } + public void ConnexionToSSE() { /*var sseClient = new ServerEventsClient($"{_clientSubscribeUrl}?token={resultToken.token}", new string[] { "EventStream" }) diff --git a/MyCore/Services/Devices/MerossService.cs b/MyCore/Services/Devices/SupportedDevices/MerossService.cs similarity index 100% rename from MyCore/Services/Devices/MerossService.cs rename to MyCore/Services/Devices/SupportedDevices/MerossService.cs diff --git a/MyCore/Services/Devices/YeelightService.cs b/MyCore/Services/Devices/SupportedDevices/YeelightService.cs similarity index 100% rename from MyCore/Services/Devices/YeelightService.cs rename to MyCore/Services/Devices/SupportedDevices/YeelightService.cs diff --git a/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs b/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs index 3e86a0e..856ce67 100644 --- a/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs +++ b/MyCore/Services/MyControlPanel/Database/ProviderDatabaseService.cs @@ -18,14 +18,14 @@ namespace MyCore.Services.MyControlPanel var database = client.GetDatabase("MyCoreDb"); _Providers = database.GetCollection("Providers"); } - public List GetAll() + public List GetAll(string userId) { - return _Providers.Find(p => true).ToList(); + return _Providers.Find(p => p.UserId == userId).ToList(); } - public Provider GetById(string id) + public Provider GetById(string userId, string id) { - return _Providers.Find(p => p.Id == id).FirstOrDefault(); + return _Providers.Find(p => p.Id == id && p.UserId == userId).FirstOrDefault(); } public Provider GetByName(string name) diff --git a/MyCore/Services/MyControlPanel/ProviderService.cs b/MyCore/Services/MyControlPanel/ProviderService.cs new file mode 100644 index 0000000..037b7af --- /dev/null +++ b/MyCore/Services/MyControlPanel/ProviderService.cs @@ -0,0 +1,79 @@ +using Microsoft.Extensions.Configuration; +using MyCore.DTO.MyControlPanel; +using MyCore.Models.MyControlPanel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace MyCore.Services.MyControlPanel +{ + public class ProviderService + { + static List supportedProviders = new List() { + "Arlo", + "Meross", + "Yeelight", + "ZigBee" + }; + + private readonly ProviderDatabaseService _ProviderDatabaseService; + + public ProviderService(ProviderDatabaseService ProviderDatabaseService) + { + _ProviderDatabaseService = ProviderDatabaseService; + } + + public static bool IsExist(string userId, string providerId) + { + return _ProviderDatabaseService.GetById(userId, providerId) != null ? true : false; + } + + public static List GetAll(string userId) + { + return _ProviderDatabaseService.GetAll(userId); + } + + public static ProviderDTO CreateOrUpdate(string userId, ProviderDTO providerDTO, bool create) + { + Provider provider; + if (create) + provider = new Provider(); + else + { + provider = _ProviderDatabaseService.GetById(userId, providerDTO.Id); + } + + if (!IsProviderSupported(providerDTO.Name)) + throw new KeyNotFoundException("Provider is not yet supported"); + + provider.Name = providerDTO.Name; + provider.UserId = providerDTO.UserId; + provider.Username = providerDTO.Username; + provider.Password = providerDTO.Password; + provider.ApiKey = providerDTO.ApiKey; + + if (create) + return _ProviderDatabaseService.Create(provider).ToDTO(); + else + return _ProviderDatabaseService.Update(provider.Id, provider).ToDTO(); + } + + public static Provider GetProviderById(string userId, string providerId) + { + return _ProviderDatabaseService.GetById(userId, providerId); + } + + // TODO Get supported services + public static List GetSupportedProvider() + { + return supportedProviders; + } + + public static bool IsProviderSupported(string providerName) + { + return supportedProviders.Contains(providerName) ? true : false; + } + } +} +