390 lines
16 KiB
C#
390 lines
16 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Manager.Services;
|
|
using ManagerService.Data;
|
|
using ManagerService.DTOs;
|
|
using ManagerService.Helpers;
|
|
using ManagerService.Services;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using NSwag.Annotations;
|
|
|
|
namespace ManagerService.Controllers
|
|
{
|
|
[Authorize(Policy = ManagerService.Service.Security.Policies.SuperAdmin)]
|
|
[ApiController, Route("api/[controller]")]
|
|
[OpenApiTag("Instance", Description = "Instance management")]
|
|
public class InstanceController : ControllerBase
|
|
{
|
|
private readonly MyInfoMateDbContext _myInfoMateDbContext;
|
|
|
|
private InstanceDatabaseService _instanceService;
|
|
private UserDatabaseService _userService;
|
|
private readonly ILogger<InstanceController> _logger;
|
|
private readonly ProfileLogic _profileLogic;
|
|
private readonly ApiKeyDatabaseService _apiKeyService;
|
|
IHexIdGeneratorService idService = new HexIdGeneratorService();
|
|
|
|
public InstanceController(ILogger<InstanceController> logger, InstanceDatabaseService instanceService, UserDatabaseService userService, ProfileLogic profileLogic, MyInfoMateDbContext myInfoMateDbContext, ApiKeyDatabaseService apiKeyService)
|
|
{
|
|
_logger = logger;
|
|
_instanceService = instanceService;
|
|
_userService = userService;
|
|
_profileLogic = profileLogic;
|
|
_myInfoMateDbContext = myInfoMateDbContext;
|
|
_apiKeyService = apiKeyService;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get a list of instance
|
|
/// </summary>
|
|
[ProducesResponseType(typeof(List<Instance>), 200)]
|
|
[ProducesResponseType(typeof(string), 500)]
|
|
[HttpGet]
|
|
public ObjectResult Get()
|
|
{
|
|
try
|
|
{
|
|
//List<OldInstance> instances = _instanceService.GetAll();
|
|
List<Instance> instances = _myInfoMateDbContext.Instances.ToList();
|
|
|
|
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 = _myInfoMateDbContext.Instances.FirstOrDefault(i => i.Id == id);
|
|
|
|
//OldInstance instance = _instanceService.GetById(id);
|
|
|
|
if (instance == null)
|
|
throw new KeyNotFoundException("This instance was not found");
|
|
|
|
var applicationInstances = _myInfoMateDbContext.ApplicationInstances.Where(ai => ai.InstanceId == instance.Id).ToList();
|
|
|
|
return new OkObjectResult(instance.ToDTO(applicationInstances.Select(ai => ai.ToDTO(_myInfoMateDbContext)).ToList()));
|
|
}
|
|
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] InstanceDTO newInstance)
|
|
{
|
|
try
|
|
{
|
|
if (newInstance == null)
|
|
throw new ArgumentNullException("instance param is null");
|
|
|
|
Instance instance = new Instance().FromDTO(newInstance);
|
|
|
|
instance.DateCreation = DateTime.Now.ToUniversalTime();
|
|
instance.Id = idService.GenerateHexId();
|
|
|
|
// Copier les valeurs du plan comme valeurs par défaut
|
|
if (instance.SubscriptionPlanId != null)
|
|
{
|
|
var plan = _myInfoMateDbContext.SubscriptionPlans.FirstOrDefault(p => p.Id == instance.SubscriptionPlanId);
|
|
if (plan != null)
|
|
{
|
|
instance.StorageQuotaBytes = plan.StorageQuotaBytes;
|
|
instance.AiRequestsPerMonth = plan.AiRequestsPerMonth;
|
|
instance.HasStats = plan.HasStats;
|
|
instance.StatsHistoryDays = plan.StatsHistoryDays;
|
|
instance.HasAdvancedStats = plan.HasAdvancedStats;
|
|
}
|
|
}
|
|
|
|
/*List<OldInstance> instances = _instanceService.GetAll();
|
|
Instance instance = _myInfoMateDbContext.Instances.FirstOrDefault(i => i.Id == id);*/
|
|
|
|
|
|
if (_myInfoMateDbContext.Instances.Any(i => i.Name == instance.Name))
|
|
throw new InvalidOperationException("This name is already used");
|
|
|
|
//OldInstance instanceCreated = _instanceService.Create(newInstance);
|
|
_myInfoMateDbContext.Instances.Add(instance);
|
|
_myInfoMateDbContext.SaveChanges();
|
|
|
|
var applicationInstances = _myInfoMateDbContext.ApplicationInstances.Where(ai => ai.InstanceId == instance.Id).ToList();
|
|
|
|
return new OkObjectResult(instance.ToDTO(applicationInstances.Select(ai => ai.ToDTO(_myInfoMateDbContext)).ToList()));
|
|
}
|
|
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] InstanceDTO updatedInstance)
|
|
{
|
|
try
|
|
{
|
|
if (updatedInstance == null)
|
|
throw new ArgumentNullException("instance param is null");
|
|
|
|
Instance instance = _myInfoMateDbContext.Instances.FirstOrDefault(i => i.Id == updatedInstance.id);
|
|
//OldInstance instance = _instanceService.GetById(updatedInstance.Id);
|
|
|
|
if (instance == null)
|
|
throw new KeyNotFoundException("instance does not exist");
|
|
|
|
instance.DateCreation = updatedInstance.dateCreation ?? instance.DateCreation;
|
|
instance.Name = updatedInstance.name ?? instance.Name;
|
|
instance.PinCode = updatedInstance.pinCode ?? instance.PinCode;
|
|
instance.IsPushNotification = updatedInstance.isPushNotification ?? instance.IsPushNotification;
|
|
instance.IsStatistic = updatedInstance.isStatistic ?? instance.IsStatistic;
|
|
instance.IsMobile = updatedInstance.isMobile ?? instance.IsMobile;
|
|
instance.IsTablet = updatedInstance.isTablet ?? instance.IsTablet;
|
|
instance.IsWeb = updatedInstance.isWeb ?? instance.IsWeb;
|
|
instance.IsVR = updatedInstance.isVR ?? instance.IsVR;
|
|
instance.IsAssistant = updatedInstance.isAssistant ?? instance.IsAssistant;
|
|
if (updatedInstance.subscriptionPlanId == "")
|
|
instance.SubscriptionPlanId = null;
|
|
else if (updatedInstance.subscriptionPlanId != null)
|
|
instance.SubscriptionPlanId = updatedInstance.subscriptionPlanId;
|
|
|
|
//OldInstance instanceModified = _instanceService.Update(updatedInstance.Id, instance);
|
|
_myInfoMateDbContext.SaveChanges();
|
|
|
|
var applicationInstances = _myInfoMateDbContext.ApplicationInstances.Where(ai => ai.InstanceId == instance.Id).ToList();
|
|
|
|
return new OkObjectResult(instance.ToDTO(applicationInstances.Select(ai => ai.ToDTO(_myInfoMateDbContext)).ToList()));
|
|
}
|
|
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] string pinCode)
|
|
{
|
|
try
|
|
{
|
|
//OldInstance instance = _instanceService.GetByPinCode(pinCode);
|
|
Instance instance = _myInfoMateDbContext.Instances.FirstOrDefault(i => i.PinCode == pinCode);
|
|
|
|
if (instance == null)
|
|
throw new KeyNotFoundException("Instance was not found");
|
|
|
|
var applicationInstances = _myInfoMateDbContext.ApplicationInstances.Where(ai => ai.InstanceId == instance.Id).ToList();
|
|
|
|
return new OkObjectResult(instance.ToDTO(applicationInstances.Select(ai => ai.ToDTO(_myInfoMateDbContext)).ToList()));
|
|
}
|
|
catch (KeyNotFoundException ex)
|
|
{
|
|
return new NotFoundObjectResult(ex.Message) { };
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new ObjectResult(ex.Message) { StatusCode = 500 };
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Bootstrap: get (or create) an API key for a Flutter app by PIN code
|
|
/// </summary>
|
|
/// <param name="pinCode">Instance PIN code</param>
|
|
/// <param name="appType">App type (VisitApp, TabletApp, Other)</param>
|
|
[AllowAnonymous]
|
|
[ProducesResponseType(typeof(object), 200)]
|
|
[ProducesResponseType(typeof(string), 404)]
|
|
[ProducesResponseType(typeof(string), 500)]
|
|
[HttpGet("app-key")]
|
|
public async Task<ObjectResult> GetAppKeyByPin([FromQuery] string pinCode, [FromQuery] ApiKeyAppType appType)
|
|
{
|
|
try
|
|
{
|
|
var instance = _myInfoMateDbContext.Instances.FirstOrDefault(i => i.PinCode == pinCode);
|
|
if (instance == null)
|
|
return new NotFoundObjectResult("Instance not found");
|
|
|
|
var key = await _apiKeyService.GetOrCreateByPinAsync(instance.Id, appType);
|
|
return new OkObjectResult(new { key, instanceId = instance.Id });
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new ObjectResult(ex.Message) { StatusCode = 500 };
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get quota usage for an instance
|
|
/// </summary>
|
|
/// <param name="id">Id instance</param>
|
|
[Authorize(Policy = ManagerService.Service.Security.Policies.Viewer)]
|
|
[ProducesResponseType(typeof(InstanceQuotaDTO), 200)]
|
|
[ProducesResponseType(typeof(string), 404)]
|
|
[ProducesResponseType(typeof(string), 500)]
|
|
[HttpGet("{id}/quota")]
|
|
public ObjectResult GetQuota(string id)
|
|
{
|
|
try
|
|
{
|
|
var instance = _myInfoMateDbContext.Instances
|
|
.FirstOrDefault(i => i.Id == id);
|
|
|
|
if (instance == null)
|
|
return new NotFoundObjectResult("Instance not found");
|
|
|
|
var storageUsed = _myInfoMateDbContext.Resources
|
|
.Where(r => r.InstanceId == id)
|
|
.Sum(r => (long?)r.SizeBytes) ?? 0;
|
|
|
|
var monthKey = DateTime.UtcNow.ToString("yyyy-MM");
|
|
var aiUsed = instance.AiUsageMonthKey == monthKey ? instance.AiRequestsThisMonth : 0;
|
|
|
|
var storageQuota = instance.StorageQuotaBytes;
|
|
var aiQuota = instance.AiRequestsPerMonth;
|
|
|
|
if ((storageQuota == 0 || aiQuota == 0) && instance.SubscriptionPlanId != null)
|
|
{
|
|
var plan = _myInfoMateDbContext.SubscriptionPlans.FirstOrDefault(p => p.Id == instance.SubscriptionPlanId);
|
|
if (plan != null)
|
|
{
|
|
if (storageQuota == 0) storageQuota = plan.StorageQuotaBytes;
|
|
if (aiQuota == 0) aiQuota = plan.AiRequestsPerMonth;
|
|
}
|
|
}
|
|
|
|
return new OkObjectResult(new InstanceQuotaDTO
|
|
{
|
|
storageUsedBytes = storageUsed,
|
|
storageQuotaBytes = storageQuota,
|
|
aiRequestsUsed = aiUsed,
|
|
aiRequestsPerMonth = aiQuota
|
|
});
|
|
}
|
|
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");
|
|
|
|
//OldInstance instance = _instanceService.GetById(id);
|
|
Instance instance = _myInfoMateDbContext.Instances.FirstOrDefault(i => i.Id == id);
|
|
|
|
if (instance == null)
|
|
throw new KeyNotFoundException("instance does not exist");
|
|
|
|
// Delete all user in instance
|
|
//List<OldUser> users = _userService.GetByInstanceId(instance.Id);
|
|
List<User> users = _myInfoMateDbContext.Users.Where(u => u.InstanceId == instance.Id).ToList();
|
|
|
|
foreach (var user in users)
|
|
{
|
|
//_userService.Remove(user.Id);
|
|
_myInfoMateDbContext.Users.Remove(user);
|
|
}
|
|
|
|
//_instanceService.Remove(id);
|
|
_myInfoMateDbContext.Instances.Remove(instance);
|
|
|
|
_myInfoMateDbContext.SaveChanges();
|
|
|
|
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 };
|
|
}
|
|
}
|
|
}
|
|
}
|