Room controller + update device controller

This commit is contained in:
Thomas Fransolet 2021-01-04 16:33:58 +01:00
parent fda53da013
commit 2dcfa0ebe8
9 changed files with 400 additions and 12 deletions

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyCore.Interfaces.DTO
{
public class RoomSummaryDTO
{
public string Id { get; set; }
public string UserId { get; set; }
public string Name { get; set; }
}
public class RoomDetailDTO
{
public string Id { get; set; }
public string UserId { get; set; }
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
public List<string> DeviceIds { get; set; }
}
public class RoomCreateOrUpdateDetailDTO
{
public string Id { get; set; }
public string UserId { get; set; }
public string Name { get; set; }
public List<string> DeviceIds { get; set; }
}
}

View File

@ -0,0 +1,60 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MyCore.Interfaces.DTO;
using MyCore.Interfaces.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyCore.Interfaces.Models
{
/// <summary>
/// Group of rooms
/// </summary>
public class Room
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("UserId")]
[BsonRequired]
public string UserId { get; set; }
[BsonElement("Name")]
[BsonRequired]
public string Name { get; set; }
[BsonElement("CreatedDate")]
public DateTime CreatedDate { get; set; }
[BsonElement("UpdatedDate")]
public DateTime UpdatedDate { get; set; }
[BsonElement("DevicesIds")]
public List<string> DevicesIds { get; set; }
public RoomSummaryDTO ToSummaryDTO()
{
return new RoomSummaryDTO()
{
Id = Id,
UserId = UserId,
Name = Name
};
}
public RoomDetailDTO ToDTO()
{
return new RoomDetailDTO()
{
Id = Id,
UserId = UserId,
Name = Name,
CreatedDate = CreatedDate,
UpdatedDate = UpdatedDate,
DeviceIds = DevicesIds
};
}
}
}

View File

@ -15,7 +15,7 @@ using MyCore.Services;
using MyCore.Services.Devices; using MyCore.Services.Devices;
using MyCore.Services.MyControlPanel; using MyCore.Services.MyControlPanel;
namespace MyCore.Controllers.Devices namespace MyCore.Controllers
{ {
[Authorize] // TODO Add ROLES (Roles = "Admin") [Authorize] // TODO Add ROLES (Roles = "Admin")
[Route("api/device")] [Route("api/device")]
@ -70,11 +70,10 @@ namespace MyCore.Controllers.Devices
/// <summary> /// <summary>
/// Get a specific device info /// Get a specific device info
/// </summary> /// </summary>
/// <param name="userId">Id of user</param>
/// <param name="deviceId">id of device</param> /// <param name="deviceId">id of device</param>
[ProducesResponseType(typeof(DeviceDetailDTO), 200)] [ProducesResponseType(typeof(DeviceDetailDTO), 200)]
[HttpGet("{deviceId}")] [HttpGet("{deviceId}")]
public ObjectResult GetDetail(string userId, string deviceId) public ObjectResult GetDetail(string deviceId)
{ {
try try
{ {
@ -271,18 +270,17 @@ namespace MyCore.Controllers.Devices
/// <summary> /// <summary>
/// Update a device /// Update a device
/// </summary> /// </summary>
/// <param name="userId">Device Id</param>
/// <param name="deviceDetailDTO">Device to update</param> /// <param name="deviceDetailDTO">Device to update</param>
[ProducesResponseType(typeof(DeviceDetailDTO), 200)] [ProducesResponseType(typeof(DeviceDetailDTO), 200)]
[HttpPut("{deviceId}")] [HttpPut("{deviceId}")]
public ObjectResult Update(string userId, [FromBody] DeviceDetailDTO deviceDetailDTO) public ObjectResult Update([FromBody] DeviceDetailDTO deviceDetailDTO)
{ {
try try
{ {
if (!_DeviceDatabaseService.IsExist(deviceDetailDTO.Id)) if (!_DeviceDatabaseService.IsExist(deviceDetailDTO.Id))
throw new KeyNotFoundException("Device does not exist"); throw new KeyNotFoundException("Device does not exist");
DeviceDetailDTO deviceUpdated = DeviceService.CreateOrUpdate(this._DeviceDatabaseService, this._ProviderDatabaseService, this._LocationDatabaseService, userId, deviceDetailDTO, false); DeviceDetailDTO deviceUpdated = DeviceService.CreateOrUpdate(this._DeviceDatabaseService, this._ProviderDatabaseService, this._LocationDatabaseService, deviceDetailDTO.UserId, deviceDetailDTO, false);
return new OkObjectResult(deviceUpdated); return new OkObjectResult(deviceUpdated);
} }
@ -305,8 +303,13 @@ namespace MyCore.Controllers.Devices
{ {
try try
{ {
// Check if exist if (deviceId != null)
{
if (_DeviceDatabaseService.IsExist(deviceId))
{
_DeviceDatabaseService.Remove(deviceId); _DeviceDatabaseService.Remove(deviceId);
}
}
return new OkObjectResult(201); return new OkObjectResult(201);
} }
@ -317,7 +320,7 @@ namespace MyCore.Controllers.Devices
} }
/// <summary> /// <summary>
/// Delete a device /// Delete all device for a specified
/// </summary> /// </summary>
/// <param name="userId">Id of user</param> /// <param name="userId">Id of user</param>
[HttpDelete("user/{userId}")] [HttpDelete("user/{userId}")]
@ -325,8 +328,13 @@ namespace MyCore.Controllers.Devices
{ {
try try
{ {
// Check if exist if (userId != null)
{
if (_UserDatabaseService.IsExist(userId))
{
_DeviceDatabaseService.RemoveForUser(userId); _DeviceDatabaseService.RemoveForUser(userId);
}
}
return new OkObjectResult(201); return new OkObjectResult(201);
} }

View File

@ -12,7 +12,7 @@ using MyCore.Services;
using MyCore.Services.Devices; using MyCore.Services.Devices;
using MyCore.Services.MyControlPanel; using MyCore.Services.MyControlPanel;
namespace MyCore.Controllers.Devices namespace MyCore.Controllers
{ {
//[Authorize(Roles = "Admin")] //[Authorize(Roles = "Admin")]
[Authorize] [Authorize]

View File

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using Mqtt.Client.AspNetCore.Services;
using MyCore.Interfaces.DTO;
using MyCore.Interfaces.Models;
using MyCore.Services;
using MyCore.Services.Devices;
using MyCore.Services.MyControlPanel;
namespace MyCore.Service.Controllers
{
[Authorize] // TODO Add ROLES (Roles = "Admin")
[Route("api/room")]
[ApiController]
public class RoomController : ControllerBase
{
private UserDatabaseService _UserDatabaseService;
private RoomDatabaseService _RoomDatabaseService;
private readonly IMqttClientService _mqttClientService;
private readonly IMqttOnlineClientService _mqttOnlineClientService;
public RoomController(UserDatabaseService userDatabaseService, RoomDatabaseService roomDatabaseService, MqttClientServiceProvider provider, MqttClientOnlineServiceProvider onlineProvider)
{
this._UserDatabaseService = userDatabaseService;
this._RoomDatabaseService = roomDatabaseService;
this._mqttClientService = provider.MqttClientService;
this._mqttOnlineClientService = onlineProvider.MqttOnlineClientService;
}
/// <summary>
/// Get all rooms for the specified user
/// </summary>
/// <param name="userId">Id of user</param>
[ProducesResponseType(typeof(List<RoomSummaryDTO>), 200)]
[HttpGet("{userId}")]
public ObjectResult GetAll(string userId)
{
try
{
List<Room> Rooms = _RoomDatabaseService.GetAll(userId);
List<RoomSummaryDTO> roomsSummaryDTO = Rooms.Select(d => d.ToSummaryDTO()).ToList();
return new OkObjectResult(roomsSummaryDTO);
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get detail info of a specified room
/// </summary>
/// <param name="roomId">room id</param>
[ProducesResponseType(typeof(RoomDetailDTO), 200)]
[HttpGet("detail/{roomId}")]
public ObjectResult GetDetail(string roomId)
{
try
{
Room room = _RoomDatabaseService.GetById(roomId);
return new OkObjectResult(room.ToDTO());
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Create a room
/// </summary>
/// <param name="roomCreateOrUpdateDetail">Room to create</param>
[ProducesResponseType(typeof(RoomDetailDTO), 200)]
[HttpPost]
public ObjectResult Create([FromBody] RoomCreateOrUpdateDetailDTO roomCreateOrUpdateDetail)
{
try
{
if (roomCreateOrUpdateDetail == null)
throw new KeyNotFoundException("Room is null");
RoomDetailDTO roomCreated = RoomService.CreateOrUpdate(this._RoomDatabaseService, roomCreateOrUpdateDetail.UserId, roomCreateOrUpdateDetail, true);
return new OkObjectResult(roomCreated);
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Update a room
/// </summary>
/// <param name="roomCreateOrUpdateDetail">room to update</param>
[ProducesResponseType(typeof(RoomCreateOrUpdateDetailDTO), 200)]
[HttpPut]
public ObjectResult Update([FromBody] RoomCreateOrUpdateDetailDTO roomCreateOrUpdateDetail)
{
try
{
if (!_RoomDatabaseService.IsExist(roomCreateOrUpdateDetail.Id))
throw new KeyNotFoundException("Room does not exist");
RoomDetailDTO roomUpdated = RoomService.CreateOrUpdate(this._RoomDatabaseService, roomCreateOrUpdateDetail.UserId, roomCreateOrUpdateDetail, false);
return new OkObjectResult(roomUpdated);
}
catch (KeyNotFoundException ex)
{
return new BadRequestObjectResult(ex.Message) { StatusCode = 404 };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Delete a room
/// </summary>
/// <param name="roomId">Id of room to delete</param>
[HttpDelete("{roomId}")]
public ObjectResult Delete(string roomId)
{
try
{
if (roomId != null)
{
if (_RoomDatabaseService.IsExist(roomId))
{
_RoomDatabaseService.Remove(roomId);
}
}
return new OkObjectResult(201);
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Delete all room for a specified
/// </summary>
/// <param name="userId">Id of user</param>
[HttpDelete("user/{userId}")]
public ObjectResult DeleteAllForUser(string userId)
{
try
{
if (userId != null)
{
if (_UserDatabaseService.IsExist(userId))
{
_RoomDatabaseService.RemoveForUser(userId);
}
}
return new OkObjectResult(201);
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
}
}

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MyCore.Interfaces.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
namespace MyCore.Services.MyControlPanel
{
public class RoomDatabaseService
{
private readonly IMongoCollection<Room> _Rooms;
public RoomDatabaseService(IConfiguration config)
{
var client = new MongoClient(config.GetConnectionString("MyCoreDb"));
var database = client.GetDatabase("MyCoreDb");
_Rooms = database.GetCollection<Room>("Rooms");
}
public List<Room> GetAll(string userId)
{
return _Rooms.Find(d => d.UserId == userId).ToList();
}
public Room GetById(string id)
{
return _Rooms.Find<Room>(d => d.Id == id).FirstOrDefault();
}
public bool IsExist(string id)
{
return _Rooms.Find<Room>(d => d.Id == id).FirstOrDefault() != null ? true : false;
}
public Room Create(Room room)
{
_Rooms.InsertOne(room);
return room;
}
public Room Update(string id, Room roomIn)
{
_Rooms.ReplaceOne(room => room.Id == id, roomIn);
return roomIn;
}
public void Remove(string id)
{
_Rooms.DeleteOne(room => room.Id == id);
}
public void RemoveForUser(string userId)
{
_Rooms.DeleteMany(room => room.UserId == userId);
}
}
}

View File

@ -33,6 +33,11 @@ namespace MyCore.Services
return _Users.Find<UserInfo>(m => m.Id == id).FirstOrDefault(); return _Users.Find<UserInfo>(m => m.Id == id).FirstOrDefault();
} }
public bool IsExist(string id)
{
return _Users.Find<UserInfo>(d => d.Id == id).FirstOrDefault() != null ? true : false;
}
public UserInfo Create(UserInfo user) public UserInfo Create(UserInfo user)
{ {
_Users.InsertOne(user); _Users.InsertOne(user);

View File

@ -0,0 +1,34 @@
using MyCore.Interfaces.DTO;
using MyCore.Interfaces.Models;
using MyCore.Services.MyControlPanel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyCore.Service
{
public class RoomService
{
public static RoomDetailDTO CreateOrUpdate(RoomDatabaseService _RoomDatabaseService, string userId, RoomCreateOrUpdateDetailDTO roomCreateOrUpdateDetailDTO, bool create)
{
Room room;
if (create)
room = new Room();
else
{
room = _RoomDatabaseService.GetById(roomCreateOrUpdateDetailDTO.Id);
}
room.UserId = userId;
room.Name = roomCreateOrUpdateDetailDTO.Name;
room.CreatedDate = DateTime.Now;
room.UpdatedDate = DateTime.Now;
if (create)
return _RoomDatabaseService.Create(room).ToDTO();
else
return _RoomDatabaseService.Update(room.Id, room).ToDTO();
}
}
}

View File

@ -202,6 +202,7 @@ namespace MyCore
services.AddScoped<ProviderDatabaseService>(); services.AddScoped<ProviderDatabaseService>();
services.AddScoped<DeviceDatabaseService>(); services.AddScoped<DeviceDatabaseService>();
services.AddScoped<LocationDatabaseService>(); services.AddScoped<LocationDatabaseService>();
services.AddScoped<RoomDatabaseService>();
services.AddMqttClientHostedService(); // Todo client files (a lot are useless) services.AddMqttClientHostedService(); // Todo client files (a lot are useless)
services.AddMqttClientOnlineHostedService(); services.AddMqttClientOnlineHostedService();