Cleaned up interfaces. Extracted server state machine trigger handler to seperated classes. Removed legacy code

This commit is contained in:
2025-09-06 15:34:35 +02:00
parent 7587a7e8e3
commit 348e9560ab
97 changed files with 1256 additions and 4670 deletions

View File

@@ -1,9 +1,9 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Models;
using MoonCore.Models;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Mappers;
@@ -28,56 +28,57 @@ public class NodeAllocationsController : Controller
AllocationRepository = allocationRepository;
}
[HttpGet("")]
[HttpGet]
[Authorize(Policy = "permissions:admin.servers.nodes.get")]
public async Task<IPagedData<NodeAllocationResponse>> Get(
public async Task<ActionResult<IPagedData<NodeAllocationResponse>>> Get(
[FromRoute] int nodeId,
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
[FromQuery] PagedOptions options
)
{
var count = await AllocationRepository.Get().CountAsync(x => x.Node.Id == nodeId);
var count = await AllocationRepository
.Get()
.CountAsync(x => x.Node.Id == nodeId);
var allocations = await AllocationRepository
.Get()
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.Where(x => x.Node.Id == nodeId)
.AsNoTracking()
.ProjectToAdminResponse()
.ToArrayAsync();
var mappedAllocations = allocations
.Select(AllocationMapper.ToNodeAllocation)
.ToArray();
return new PagedData<NodeAllocationResponse>()
{
Items = mappedAllocations,
CurrentPage = page,
PageSize = pageSize,
Items = allocations,
CurrentPage = options.Page,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : (count - 1) / pageSize
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
[HttpGet("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.nodes.get")]
public async Task<NodeAllocationResponse> GetSingle([FromRoute] int nodeId, [FromRoute] int id)
public async Task<ActionResult<NodeAllocationResponse>> GetSingle([FromRoute] int nodeId, [FromRoute] int id)
{
var allocation = await AllocationRepository
.Get()
.Where(x => x.Node.Id == nodeId)
.AsNoTracking()
.ProjectToAdminResponse()
.FirstOrDefaultAsync(x => x.Id == id);
if (allocation == null)
throw new HttpApiException("No allocation with that id found", 404);
return Problem("No allocation with that id found", statusCode: 400);
return AllocationMapper.ToNodeAllocation(allocation);
return allocation;
}
[HttpPost("")]
[HttpPost]
[Authorize(Policy = "permissions:admin.servers.nodes.create")]
public async Task<NodeAllocationResponse> Create(
public async Task<ActionResult<NodeAllocationResponse>> Create(
[FromRoute] int nodeId,
[FromBody] CreateNodeAllocationRequest request
)
@@ -87,7 +88,7 @@ public class NodeAllocationsController : Controller
.FirstOrDefaultAsync(x => x.Id == nodeId);
if (node == null)
throw new HttpApiException("No node with that id found", 404);
return Problem("No node with that id found", statusCode: 404);
var allocation = AllocationMapper.ToAllocation(request);
@@ -97,7 +98,7 @@ public class NodeAllocationsController : Controller
}
[HttpPatch("{id:int}")]
public async Task<NodeAllocationResponse> Update(
public async Task<ActionResult<NodeAllocationResponse>> Update(
[FromRoute] int nodeId,
[FromRoute] int id,
[FromBody] UpdateNodeAllocationRequest request
@@ -109,7 +110,7 @@ public class NodeAllocationsController : Controller
.FirstOrDefaultAsync(x => x.Id == id);
if (allocation == null)
throw new HttpApiException("No allocation with that id found", 404);
return Problem("No allocation with that id found", statusCode: 404);
AllocationMapper.Merge(request, allocation);
await AllocationRepository.Update(allocation);
@@ -118,7 +119,7 @@ public class NodeAllocationsController : Controller
}
[HttpDelete("{id:int}")]
public async Task Delete([FromRoute] int nodeId, [FromRoute] int id)
public async Task<ActionResult> Delete([FromRoute] int nodeId, [FromRoute] int id)
{
var allocation = await AllocationRepository
.Get()
@@ -126,32 +127,44 @@ public class NodeAllocationsController : Controller
.FirstOrDefaultAsync(x => x.Id == id);
if (allocation == null)
throw new HttpApiException("No allocation with that id found", 404);
return Problem("No allocation with that id found", statusCode: 404);
await AllocationRepository.Remove(allocation);
return NoContent();
}
[HttpPost("range")]
public async Task CreateRange([FromRoute] int nodeId, [FromBody] CreateNodeAllocationRangeRequest rangeRequest)
public async Task<ActionResult> CreateRange(
[FromRoute] int nodeId,
[FromBody] CreateNodeAllocationRangeRequest request
)
{
if (request.Start > request.End)
return Problem("Invalid start and end specified", statusCode: 400);
if (request.End - request.Start == 0)
return Problem("Empty range specified", statusCode: 400);
var node = await NodeRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == nodeId);
if (node == null)
throw new HttpApiException("No node with that id found", 404);
return Problem("No node with that id found", statusCode: 404);
var existingAllocations = AllocationRepository
var existingAllocations = await AllocationRepository
.Get()
.Where(x => x.Node.Id == nodeId)
.ToArray();
.Where(x => x.Port >= request.Start && x.Port <= request.End &&
x.IpAddress == request.IpAddress)
.AsNoTracking()
.ToArrayAsync();
var ports = new List<int>();
for (var i = rangeRequest.Start; i < rangeRequest.End; i++)
for (var i = request.Start; i < request.End; i++)
{
// Skip existing allocations
if (existingAllocations.Any(x => x.Port == i && x.IpAddress == rangeRequest.IpAddress))
if (existingAllocations.Any(x => x.Port == i))
continue;
ports.Add(i);
@@ -160,17 +173,18 @@ public class NodeAllocationsController : Controller
var allocations = ports
.Select(port => new Allocation()
{
IpAddress = rangeRequest.IpAddress,
IpAddress = request.IpAddress,
Port = port,
Node = node
})
.ToArray();
await AllocationRepository.RunTransaction(async set => { await set.AddRangeAsync(allocations); });
return NoContent();
}
[HttpDelete("all")]
public async Task DeleteAll([FromRoute] int nodeId)
public async Task<ActionResult> DeleteAll([FromRoute] int nodeId)
{
var allocations = AllocationRepository
.Get()
@@ -178,14 +192,14 @@ public class NodeAllocationsController : Controller
.ToArray();
await AllocationRepository.RunTransaction(set => { set.RemoveRange(allocations); });
return NoContent();
}
[HttpGet("free")]
[Authorize(Policy = "permissions:admin.servers.nodes.get")]
public async Task<IPagedData<NodeAllocationResponse>> GetFree(
[FromRoute] int nodeId,
[FromQuery] int page,
[FromQuery] [Range(1, 100)] int pageSize,
[FromQuery] PagedOptions options,
[FromQuery] int serverId = -1
)
{
@@ -202,19 +216,21 @@ public class NodeAllocationsController : Controller
.Where(x => x.Server == null || x.Server.Id == serverId);
var count = await freeAllocationsQuery.CountAsync();
var allocations = await freeAllocationsQuery.ToArrayAsync();
var mappedAllocations = allocations
.Select(AllocationMapper.ToNodeAllocation)
.ToArray();
var allocations = await freeAllocationsQuery
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.AsNoTracking()
.ProjectToAdminResponse()
.ToArrayAsync();
return new PagedData<NodeAllocationResponse>()
{
Items = mappedAllocations,
CurrentPage = page,
PageSize = pageSize,
Items = allocations,
CurrentPage = options.Page,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : (count - 1) / pageSize
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
}

View File

@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Services;
using MoonlightServers.Shared.Http.Responses.Admin.Nodes.Sys;
@@ -24,10 +25,13 @@ public class NodeStatusController : Controller
[HttpGet("{nodeId:int}/system/status")]
[Authorize(Policy = "permissions:admin.servers.nodes.status")]
public async Task<NodeSystemStatusResponse> GetStatus([FromRoute] int nodeId)
public async Task<ActionResult<NodeSystemStatusResponse>> GetStatus([FromRoute] int nodeId)
{
var node = GetNode(nodeId);
var node = await GetNode(nodeId);
if (node.Value == null)
return node.Result ?? Problem("Unable to retrieve node");
NodeSystemStatusResponse response;
var sw = new Stopwatch();
@@ -35,7 +39,7 @@ public class NodeStatusController : Controller
try
{
var statusResponse = await NodeService.GetSystemStatus(node);
var statusResponse = await NodeService.GetSystemStatus(node.Value);
sw.Stop();
@@ -65,14 +69,14 @@ public class NodeStatusController : Controller
return response;
}
private Node GetNode(int nodeId)
private async Task<ActionResult<Node>> GetNode(int nodeId)
{
var result = NodeRepository
var result = await NodeRepository
.Get()
.FirstOrDefault(x => x.Id == nodeId);
.FirstOrDefaultAsync(x => x.Id == nodeId);
if (result == null)
throw new HttpApiException("A node with this id could not be found", 404);
return Problem("A node with this id could not be found", statusCode: 404);
return result;
}

View File

@@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore;
using MoonCore.Extended.Abstractions;
using Microsoft.AspNetCore.Authorization;
using MoonCore.Exceptions;
using MoonCore.Extended.Models;
using MoonCore.Helpers;
using MoonCore.Models;
using MoonlightServers.ApiServer.Database.Entities;
@@ -19,62 +20,55 @@ public class NodesController : Controller
{
private readonly DatabaseRepository<Node> NodeRepository;
public NodesController(
DatabaseRepository<Node> nodeRepository
)
public NodesController(DatabaseRepository<Node> nodeRepository)
{
NodeRepository = nodeRepository;
}
[HttpGet]
[Authorize(Policy = "permissions:admin.servers.nodes.get")]
public async Task<IPagedData<NodeResponse>> Get(
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
)
public async Task<IPagedData<NodeResponse>> Get([FromQuery] PagedOptions options)
{
var query = NodeRepository
.Get();
var count = await NodeRepository.Get().CountAsync();
var count = await query.CountAsync();
var items = await query
var items = await NodeRepository
.Get()
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.AsNoTracking()
.ProjectToAdminResponse()
.ToArrayAsync();
var mappedItems = items
.Select(NodeMapper.ToAdminNodeResponse)
.ToArray();
return new PagedData<NodeResponse>()
{
Items = mappedItems,
CurrentPage = page,
PageSize = pageSize,
Items = items,
CurrentPage = options.Page,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : count / pageSize
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
[HttpGet("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.nodes.get")]
public async Task<NodeResponse> GetSingle([FromRoute] int id)
public async Task<ActionResult<NodeResponse>> GetSingle([FromRoute] int id)
{
var node = await NodeRepository
.Get()
.AsNoTracking()
.ProjectToAdminResponse()
.FirstOrDefaultAsync(x => x.Id == id);
if (node == null)
throw new HttpApiException("No node with this id found", 404);
return NodeMapper.ToAdminNodeResponse(node);
return Problem("No node with this id found", statusCode: 404);
return node;
}
[HttpPost]
[Authorize(Policy = "permissions:admin.servers.nodes.create")]
public async Task<NodeResponse> Create([FromBody] CreateNodeRequest request)
public async Task<ActionResult<NodeResponse>> Create([FromBody] CreateNodeRequest request)
{
var node = NodeMapper.ToNode(request);
@@ -88,14 +82,14 @@ public class NodesController : Controller
[HttpPatch("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.nodes.update")]
public async Task<NodeResponse> Update([FromRoute] int id, [FromBody] UpdateNodeRequest request)
public async Task<ActionResult<NodeResponse>> Update([FromRoute] int id, [FromBody] UpdateNodeRequest request)
{
var node = await NodeRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id);
if (node == null)
throw new HttpApiException("No node with this id found", 404);
return Problem("No node with this id found", statusCode: 404);
NodeMapper.Merge(request, node);
await NodeRepository.Update(node);
@@ -105,15 +99,16 @@ public class NodesController : Controller
[HttpDelete("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.nodes.delete")]
public async Task Delete([FromRoute] int id)
public async Task<ActionResult> Delete([FromRoute] int id)
{
var node = await NodeRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id);
if (node == null)
throw new HttpApiException("No node with this id found", 404);
return Problem("No node with this id found", statusCode: 404);
await NodeRepository.Remove(node);
return Ok();
}
}

View File

@@ -27,12 +27,16 @@ public class StatisticsController : Controller
[HttpGet]
[SuppressMessage("ReSharper.DPA", "DPA0011: High execution time of MVC action", MessageId = "time: 1142ms",
Justification = "The daemon has an artificial delay of one second to calculate accurate cpu usage values")]
public async Task<StatisticsResponse> Get([FromRoute] int nodeId)
public async Task<ActionResult<StatisticsResponse>> Get([FromRoute] int nodeId)
{
var node = await GetNode(nodeId);
var statistics = await NodeService.GetStatistics(node);
return new()
if (node.Value == null)
return node.Result ?? Problem("Unable to retrieve node");
var statistics = await NodeService.GetStatistics(node.Value);
return new StatisticsResponse()
{
Cpu = new()
{
@@ -62,12 +66,16 @@ public class StatisticsController : Controller
}
[HttpGet("docker")]
public async Task<DockerStatisticsResponse> GetDocker([FromRoute] int nodeId)
public async Task<ActionResult<DockerStatisticsResponse>> GetDocker([FromRoute] int nodeId)
{
var node = await GetNode(nodeId);
var statistics = await NodeService.GetDockerStatistics(node);
return new()
if (node.Value == null)
return node.Result ?? Problem("Unable to retrieve node");
var statistics = await NodeService.GetDockerStatistics(node.Value);
return new DockerStatisticsResponse()
{
BuildCacheReclaimable = statistics.BuildCacheReclaimable,
BuildCacheUsed = statistics.BuildCacheUsed,
@@ -79,14 +87,14 @@ public class StatisticsController : Controller
};
}
private async Task<Node> GetNode(int nodeId)
private async Task<ActionResult<Node>> GetNode(int nodeId)
{
var result = await NodeRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == nodeId);
if (result == null)
throw new HttpApiException("A node with this id could not be found", 404);
return Problem("A node with this id could not be found", statusCode: 404);
return result;
}

View File

@@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Models;
using MoonCore.Models;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Mappers;
@@ -18,8 +19,10 @@ public class ServerVariablesController : Controller
private readonly DatabaseRepository<ServerVariable> VariableRepository;
private readonly DatabaseRepository<Server> ServerRepository;
public ServerVariablesController(DatabaseRepository<ServerVariable> variableRepository,
DatabaseRepository<Server> serverRepository)
public ServerVariablesController(
DatabaseRepository<ServerVariable> variableRepository,
DatabaseRepository<Server> serverRepository
)
{
VariableRepository = variableRepository;
ServerRepository = serverRepository;
@@ -27,10 +30,9 @@ public class ServerVariablesController : Controller
[HttpGet("{serverId:int}/variables")]
[Authorize(Policy = "permissions:admin.servers.read")]
public async Task<PagedData<ServerVariableResponse>> Get(
public async Task<ActionResult<PagedData<ServerVariableResponse>>> Get(
[FromRoute] int serverId,
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
[FromQuery] PagedOptions options
)
{
var serverExists = await ServerRepository
@@ -38,20 +40,29 @@ public class ServerVariablesController : Controller
.AnyAsync(x => x.Id == serverId);
if (!serverExists)
throw new HttpApiException("No server with this id found", 404);
return Problem("No server with this id found", statusCode: 404);
var variables = await VariableRepository
var query = VariableRepository
.Get()
.Where(x => x.Server.Id == serverId)
.Where(x => x.Server.Id == serverId);
var count = await query.CountAsync();
var variables = await query
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.AsNoTracking()
.ProjectToAdminResponse()
.ToArrayAsync();
var castedVariables = variables
.Select(ServerVariableMapper.ToAdminResponse)
.ToArray();
return PagedData<ServerVariableResponse>.Create(castedVariables, page, pageSize);
return new PagedData<ServerVariableResponse>()
{
Items = variables,
CurrentPage = options.Page,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
}

View File

@@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Helpers;
using MoonCore.Extended.Models;
using MoonCore.Helpers;
using MoonCore.Models;
using Moonlight.ApiServer.Database.Entities;
@@ -53,41 +54,36 @@ public class ServersController : Controller
[HttpGet]
[Authorize(Policy = "permissions:admin.servers.read")]
public async Task<IPagedData<ServerResponse>> Get(
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
)
public async Task<ActionResult<IPagedData<ServerResponse>>> Get([FromQuery] PagedOptions options)
{
var count = await ServerRepository.Get().CountAsync();
var items = await ServerRepository
var servers = await ServerRepository
.Get()
.Include(x => x.Node)
.Include(x => x.Allocations)
.Include(x => x.Variables)
.Include(x => x.Star)
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.AsNoTracking()
.ProjectToAdminResponse()
.ToArrayAsync();
var mappedItems = items
.Select(ServerMapper.ToAdminServerResponse)
.ToArray();
return new PagedData<ServerResponse>()
{
Items = mappedItems,
CurrentPage = page,
PageSize = pageSize,
Items = servers,
CurrentPage = options.Page,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : count / pageSize
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
[HttpGet("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.read")]
public async Task<ServerResponse> GetSingle([FromRoute] int id)
public async Task<ActionResult<ServerResponse>> GetSingle([FromRoute] int id)
{
var server = await ServerRepository
.Get()
@@ -95,21 +91,23 @@ public class ServersController : Controller
.Include(x => x.Allocations)
.Include(x => x.Variables)
.Include(x => x.Star)
.AsNoTracking()
.ProjectToAdminResponse()
.FirstOrDefaultAsync(x => x.Id == id);
if (server == null)
throw new HttpApiException("No server with that id found", 404);
return ServerMapper.ToAdminServerResponse(server);
return Problem("No server with that id found", statusCode: 404);
return server;
}
[HttpPost]
[Authorize(Policy = "permissions:admin.servers.write")]
public async Task<ServerResponse> Create([FromBody] CreateServerRequest request)
public async Task<ActionResult<ServerResponse>> Create([FromBody] CreateServerRequest request)
{
// Check if owner user exist
if (UserRepository.Get().All(x => x.Id != request.OwnerId))
throw new HttpApiException("No user with this id found", 400);
return Problem("No user with this id found", statusCode: 400);
// Check if the star exists
var star = await StarRepository
@@ -119,14 +117,14 @@ public class ServersController : Controller
.FirstOrDefaultAsync(x => x.Id == request.StarId);
if (star == null)
throw new HttpApiException("No star with this id found", 400);
return Problem("No star with this id found", statusCode: 400);
var node = await NodeRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == request.NodeId);
if (node == null)
throw new HttpApiException("No node with this id found", 400);
return Problem("No node with this id found", statusCode: 400);
var allocations = new List<Allocation>();
@@ -161,13 +159,13 @@ public class ServersController : Controller
if (allocations.Count < star.RequiredAllocations)
{
throw new HttpApiException(
return Problem(
$"Unable to find enough free allocations. Found: {allocations.Count}, Required: {star.RequiredAllocations}",
400
statusCode: 400
);
}
}
var server = ServerMapper.ToServer(request);
// Set allocations
@@ -204,7 +202,7 @@ public class ServersController : Controller
Logger.LogError("Unable to sync server to node the server is assigned to: {e}", e);
// We are deleting the server from the database after the creation has failed
// to ensure we won't have a bugged server in the database which doesnt exist on the node
// to ensure we won't have a bugged server in the database which doesn't exist on the node
await ServerRepository.Remove(finalServer);
throw;
@@ -215,7 +213,7 @@ public class ServersController : Controller
[HttpPatch("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.write")]
public async Task<ServerResponse> Update([FromRoute] int id, [FromBody] UpdateServerRequest request)
public async Task<ActionResult<ServerResponse>> Update([FromRoute] int id, [FromBody] UpdateServerRequest request)
{
//TODO: Handle shrinking virtual disk
@@ -228,7 +226,7 @@ public class ServersController : Controller
.FirstOrDefaultAsync(x => x.Id == id);
if (server == null)
throw new HttpApiException("No server with that id found", 404);
return Problem("No server with that id found", statusCode: 404);
ServerMapper.Merge(request, server);
@@ -255,9 +253,9 @@ public class ServersController : Controller
// Check if the specified allocations are enough for the star
if (allocations.Count < server.Star.RequiredAllocations)
{
throw new HttpApiException(
return Problem(
$"You need to specify at least {server.Star.RequiredAllocations} allocation(s)",
400
statusCode: 400
);
}
@@ -287,7 +285,7 @@ public class ServersController : Controller
}
[HttpDelete("{id:int}")]
public async Task Delete([FromRoute] int id, [FromQuery] bool force = false)
public async Task<ActionResult> Delete([FromRoute] int id, [FromQuery] bool force = false)
{
var server = await ServerRepository
.Get()
@@ -299,12 +297,12 @@ public class ServersController : Controller
.FirstOrDefaultAsync(x => x.Id == id);
if (server == null)
throw new HttpApiException("No server with that id found", 404);
return Problem("No server with that id found", statusCode: 404);
server.Variables.Clear();
server.Backups.Clear();
server.Allocations.Clear();
try
{
// If the sync fails on the node and we aren't forcing the deletion,
@@ -325,5 +323,6 @@ public class ServersController : Controller
}
await ServerRepository.Remove(server);
return NoContent();
}
}

View File

@@ -5,6 +5,7 @@ using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Helpers;
using Microsoft.AspNetCore.Authorization;
using MoonCore.Extended.Models;
using MoonCore.Helpers;
using MoonCore.Models;
using MoonlightServers.ApiServer.Database.Entities;
@@ -32,10 +33,9 @@ public class StarDockerImagesController : Controller
[HttpGet]
[Authorize(Policy = "permissions:admin.servers.stars.get")]
public async Task<IPagedData<StarDockerImageDetailResponse>> Get(
public async Task<ActionResult<IPagedData<StarDockerImageResponse>>> Get(
[FromRoute] int starId,
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
[FromQuery] PagedOptions options
)
{
var starExists = StarRepository
@@ -43,7 +43,7 @@ public class StarDockerImagesController : Controller
.Any(x => x.Id == starId);
if (!starExists)
throw new HttpApiException("No star with this id found", 404);
return Problem("No star with this id found", statusCode: 404);
var query = DockerImageRepository
.Get()
@@ -51,50 +51,50 @@ public class StarDockerImagesController : Controller
var count = await query.CountAsync();
var items = await query
var dockerImages = await query
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.AsNoTracking()
.ProjectToAdminResponse()
.ToArrayAsync();
var mappedItems = items
.Select(DockerImageMapper.ToAdminResponse)
.ToArray();
return new PagedData<StarDockerImageDetailResponse>()
return new PagedData<StarDockerImageResponse>()
{
Items = mappedItems,
CurrentPage = page,
PageSize = pageSize,
Items = dockerImages,
CurrentPage = options.Page,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : count / pageSize
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
[HttpGet("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.stars.read")]
public async Task<StarDockerImageDetailResponse> GetSingle([FromRoute] int starId, [FromRoute] int id)
public async Task<ActionResult<StarDockerImageResponse>> GetSingle([FromRoute] int starId, [FromRoute] int id)
{
var starExists = StarRepository
.Get()
.Any(x => x.Id == starId);
if (!starExists)
throw new HttpApiException("No star with this id found", 404);
return Problem("No star with this id found", statusCode: 404);
var dockerImage = await DockerImageRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id && x.Star.Id == starId);
.Where(x => x.Id == id && x.Star.Id == starId)
.ProjectToAdminResponse()
.FirstOrDefaultAsync();
if (dockerImage == null)
throw new HttpApiException("No star docker image with this id found", 404);
return Problem("No star docker image with this id found", statusCode: 404);
return DockerImageMapper.ToAdminResponse(dockerImage);
return dockerImage;
}
[HttpPost("")]
[HttpPost]
[Authorize(Policy = "permissions:admin.servers.stars.write")]
public async Task<StarDockerImageDetailResponse> Create(
public async Task<ActionResult<StarDockerImageResponse>> Create(
[FromRoute] int starId,
[FromBody] CreateStarDockerImageRequest request
)
@@ -104,7 +104,7 @@ public class StarDockerImagesController : Controller
.FirstOrDefaultAsync(x => x.Id == starId);
if (star == null)
throw new HttpApiException("No star with this id found", 404);
return Problem("No star with this id found", statusCode: 404);
var dockerImage = DockerImageMapper.ToDockerImage(request);
dockerImage.Star = star;
@@ -116,7 +116,7 @@ public class StarDockerImagesController : Controller
[HttpPatch("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.stars.write")]
public async Task<StarDockerImageDetailResponse> Update(
public async Task<ActionResult<StarDockerImageResponse>> Update(
[FromRoute] int starId,
[FromRoute] int id,
[FromBody] UpdateStarDockerImageRequest request
@@ -127,14 +127,14 @@ public class StarDockerImagesController : Controller
.Any(x => x.Id == starId);
if (!starExists)
throw new HttpApiException("No star with this id found", 404);
return Problem("No star with this id found", statusCode: 404);
var dockerImage = await DockerImageRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id && x.Star.Id == starId);
if (dockerImage == null)
throw new HttpApiException("No star docker image with this id found", 404);
return Problem("No star docker image with this id found", statusCode: 404);
DockerImageMapper.Merge(request, dockerImage);
await DockerImageRepository.Update(dockerImage);
@@ -144,22 +144,23 @@ public class StarDockerImagesController : Controller
[HttpDelete("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.stars.write")]
public async Task Delete([FromRoute] int starId, [FromRoute] int id)
public async Task<ActionResult> Delete([FromRoute] int starId, [FromRoute] int id)
{
var starExists = StarRepository
.Get()
.Any(x => x.Id == starId);
if (!starExists)
throw new HttpApiException("No star with this id found", 404);
return Problem("No star with this id found", statusCode: 404);
var dockerImage = await DockerImageRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id && x.Star.Id == starId);
if (dockerImage == null)
throw new HttpApiException("No star docker image with this id found", 404);
return Problem("No star docker image with this id found", statusCode: 404);
await DockerImageRepository.Remove(dockerImage);
return NoContent();
}
}

View File

@@ -23,18 +23,15 @@ public class StarImportExportController : Controller
[HttpGet("{starId:int}/export")]
[Authorize(Policy = "permissions:admin.servers.stars.get")]
public async Task Export([FromRoute] int starId)
public async Task<ActionResult> Export([FromRoute] int starId)
{
var exportedStar = await ImportExportService.Export(starId);
Response.StatusCode = 200;
Response.ContentType = "application/json";
await Response.WriteAsync(exportedStar);
return Content(exportedStar, "application/json");
}
[HttpPost("import")]
[Authorize(Policy = "permissions:admin.servers.stars.create")]
public async Task<StarDetailResponse> Import()
public async Task<StarResponse> Import()
{
if (Request.Form.Files.Count == 0)
throw new HttpApiException("No file to import provided", 400);

View File

@@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Models;
using MoonCore.Models;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Mappers;
@@ -29,10 +30,9 @@ public class StarVariablesController : Controller
[HttpGet]
[Authorize(Policy = "permissions:admin.servers.stars.get")]
public async Task<IPagedData<StarVariableDetailResponse>> Get(
public async Task<ActionResult<IPagedData<StarVariableResponse>>> Get(
[FromRoute] int starId,
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
[FromQuery] PagedOptions options
)
{
var starExists = StarRepository
@@ -40,7 +40,7 @@ public class StarVariablesController : Controller
.Any(x => x.Id == starId);
if (!starExists)
throw new HttpApiException("No star with this id found", 404);
return Problem("No star with this id found", statusCode: 404);
var query = VariableRepository
.Get()
@@ -48,29 +48,27 @@ public class StarVariablesController : Controller
var count = await query.CountAsync();
var items = await query
var variables = await query
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.AsNoTracking()
.ProjectToAdminResponse()
.ToArrayAsync();
var mappedItems = items
.Select(StarVariableMapper.ToAdminResponse)
.ToArray();
return new PagedData<StarVariableDetailResponse>()
return new PagedData<StarVariableResponse>()
{
Items = mappedItems,
CurrentPage = page,
PageSize = pageSize,
Items = variables,
CurrentPage = options.Page,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : count / pageSize
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
[HttpGet("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.stars.get")]
public async Task<StarVariableDetailResponse> GetSingle(
public async Task<StarVariableResponse> GetSingle(
[FromRoute] int starId,
[FromRoute] int id
)
@@ -94,7 +92,7 @@ public class StarVariablesController : Controller
[HttpPost("")]
[Authorize(Policy = "permissions:admin.servers.stars.create")]
public async Task<StarVariableDetailResponse> Create([FromRoute] int starId,
public async Task<StarVariableResponse> Create([FromRoute] int starId,
[FromBody] CreateStarVariableRequest request)
{
var star = StarRepository
@@ -114,7 +112,7 @@ public class StarVariablesController : Controller
[HttpPatch("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.stars.update")]
public async Task<StarVariableDetailResponse> Update(
public async Task<StarVariableResponse> Update(
[FromRoute] int starId,
[FromRoute] int id,
[FromBody] UpdateStarVariableRequest request

View File

@@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Models;
using MoonCore.Models;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Mappers;
@@ -25,51 +26,48 @@ public class StarsController : Controller
[HttpGet]
[Authorize(Policy = "permissions:admin.servers.stars.read")]
public async Task<IPagedData<StarDetailResponse>> Get(
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
)
public async Task<ActionResult<IPagedData<StarResponse>>> Get([FromQuery] PagedOptions options)
{
var count = await StarRepository.Get().CountAsync();
var items = await StarRepository
var stars = await StarRepository
.Get()
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.AsNoTracking()
.ProjectToAdminResponse()
.ToArrayAsync();
var mappedItems = items
.Select(StarMapper.ToAdminResponse)
.ToArray();
return new PagedData<StarDetailResponse>()
return new PagedData<StarResponse>()
{
CurrentPage = page,
Items = mappedItems,
PageSize = pageSize,
CurrentPage = options.Page,
Items = stars,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : count / pageSize
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
[HttpGet("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.stars.read")]
public async Task<StarDetailResponse> GetSingle([FromRoute] int id)
public async Task<ActionResult<StarResponse>> GetSingle([FromRoute] int id)
{
var star = await StarRepository
.Get()
.AsNoTracking()
.ProjectToAdminResponse()
.FirstOrDefaultAsync(x => x.Id == id);
if (star == null)
throw new HttpApiException("No star with that id found", 404);
return Problem("No star with that id found", statusCode: 404);
return StarMapper.ToAdminResponse(star);
return star;
}
[HttpPost]
[Authorize(Policy = "permissions:admin.servers.stars.create")]
public async Task<StarDetailResponse> Create([FromBody] CreateStarRequest request)
public async Task<ActionResult<StarResponse>> Create([FromBody] CreateStarRequest request)
{
var star = StarMapper.ToStar(request);
@@ -95,7 +93,7 @@ public class StarsController : Controller
[HttpPatch("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.stars.update")]
public async Task<StarDetailResponse> Update(
public async Task<ActionResult<StarResponse>> Update(
[FromRoute] int id,
[FromBody] UpdateStarRequest request
)
@@ -105,7 +103,7 @@ public class StarsController : Controller
.FirstOrDefaultAsync(x => x.Id == id);
if (star == null)
throw new HttpApiException("No star with that id found", 404);
return Problem("No star with that id found", statusCode: 404);
StarMapper.Merge(request, star);
await StarRepository.Update(star);
@@ -115,15 +113,16 @@ public class StarsController : Controller
[HttpDelete("{id:int}")]
[Authorize(Policy = "permissions:admin.servers.stars.delete")]
public async Task Delete([FromRoute] int id)
public async Task<ActionResult> Delete([FromRoute] int id)
{
var star = await StarRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id);
if (star == null)
throw new HttpApiException("No star with that id found", 404);
return Problem("No star with that id found", statusCode: 404);
await StarRepository.Remove(star);
return NoContent();
}
}