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();
}
}

View File

@@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using Moonlight.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Services;
using MoonlightServers.DaemonShared.Enums;
@@ -38,11 +37,14 @@ public class FilesController : Controller
}
[HttpGet("list")]
public async Task<ServerFilesEntryResponse[]> List([FromRoute] int serverId, [FromQuery] string path)
public async Task<ActionResult<ServerFilesEntryResponse[]>> List([FromRoute] int serverId, [FromQuery] string path)
{
var server = await GetServerById(serverId, ServerPermissionLevel.Read);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var entries = await ServerFileSystemService.List(server, path);
var entries = await ServerFileSystemService.List(server.Value, path);
return entries.Select(x => new ServerFilesEntryResponse()
{
@@ -55,41 +57,62 @@ public class FilesController : Controller
}
[HttpPost("move")]
public async Task Move([FromRoute] int serverId, [FromQuery] string oldPath, [FromQuery] string newPath)
public async Task<ActionResult> Move([FromRoute] int serverId, [FromQuery] string oldPath, [FromQuery] string newPath)
{
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerFileSystemService.Move(server, oldPath, newPath);
await ServerFileSystemService.Move(server.Value, oldPath, newPath);
return NoContent();
}
[HttpDelete("delete")]
public async Task Delete([FromRoute] int serverId, [FromQuery] string path)
public async Task<ActionResult> Delete([FromRoute] int serverId, [FromQuery] string path)
{
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerFileSystemService.Delete(server, path);
await ServerFileSystemService.Delete(server.Value, path);
return NoContent();
}
[HttpPost("mkdir")]
public async Task Mkdir([FromRoute] int serverId, [FromQuery] string path)
public async Task<ActionResult> Mkdir([FromRoute] int serverId, [FromQuery] string path)
{
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerFileSystemService.Mkdir(server, path);
await ServerFileSystemService.Mkdir(server.Value, path);
return NoContent();
}
[HttpPost("touch")]
public async Task Touch([FromRoute] int serverId, [FromQuery] string path)
public async Task<ActionResult> Touch([FromRoute] int serverId, [FromQuery] string path)
{
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerFileSystemService.Mkdir(server, path);
await ServerFileSystemService.Mkdir(server.Value, path);
return NoContent();
}
[HttpGet("upload")]
public async Task<ServerFilesUploadResponse> Upload([FromRoute] int serverId)
public async Task<ActionResult<ServerFilesUploadResponse>> Upload([FromRoute] int serverId)
{
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
var serverResult = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (serverResult.Value == null)
return serverResult.Result ?? Problem("Unable to retrieve server");
var server = serverResult.Value;
var accessToken = NodeService.CreateAccessToken(
server.Node,
@@ -114,9 +137,14 @@ public class FilesController : Controller
}
[HttpGet("download")]
public async Task<ServerFilesDownloadResponse> Download([FromRoute] int serverId, [FromQuery] string path)
public async Task<ActionResult<ServerFilesDownloadResponse>> Download([FromRoute] int serverId, [FromQuery] string path)
{
var server = await GetServerById(serverId, ServerPermissionLevel.Read);
var serverResult = await GetServerById(serverId, ServerPermissionLevel.Read);
if (serverResult.Value == null)
return serverResult.Result ?? Problem("Unable to retrieve server");
var server = serverResult.Value;
var accessToken = NodeService.CreateAccessToken(
server.Node,
@@ -142,28 +170,36 @@ public class FilesController : Controller
}
[HttpPost("compress")]
public async Task Compress([FromRoute] int serverId, [FromBody] ServerFilesCompressRequest request)
public async Task<ActionResult> Compress([FromRoute] int serverId, [FromBody] ServerFilesCompressRequest request)
{
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
if (!Enum.TryParse(request.Type, true, out CompressType type))
throw new HttpApiException("Invalid compress type provided", 400);
return Problem("Invalid compress type provided", statusCode: 400);
await ServerFileSystemService.Compress(server, type, request.Items, request.Destination);
await ServerFileSystemService.Compress(server.Value, type, request.Items, request.Destination);
return Ok();
}
[HttpPost("decompress")]
public async Task Decompress([FromRoute] int serverId, [FromBody] ServerFilesDecompressRequest request)
public async Task<ActionResult> Decompress([FromRoute] int serverId, [FromBody] ServerFilesDecompressRequest request)
{
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
if (!Enum.TryParse(request.Type, true, out CompressType type))
throw new HttpApiException("Invalid compress type provided", 400);
return Problem("Invalid decompress type provided", statusCode: 400);
await ServerFileSystemService.Decompress(server, type, request.Path, request.Destination);
await ServerFileSystemService.Decompress(server.Value, type, request.Path, request.Destination);
return NoContent();
}
private async Task<Server> GetServerById(int serverId, ServerPermissionLevel level)
private async Task<ActionResult<Server>> GetServerById(int serverId, ServerPermissionLevel level)
{
var server = await ServerRepository
.Get()
@@ -171,7 +207,7 @@ public class FilesController : Controller
.FirstOrDefaultAsync(x => x.Id == serverId);
if (server == null)
throw new HttpApiException("No server with this id found", 404);
return Problem("No server with this id found", statusCode: 404);
var authorizeResult = await AuthorizeService.Authorize(
User, server,
@@ -181,9 +217,9 @@ public class FilesController : Controller
if (!authorizeResult.Succeeded)
{
throw new HttpApiException(
return Problem(
authorizeResult.Message ?? "No permission for the requested resource",
403
statusCode: 403
);
}

View File

@@ -14,7 +14,7 @@ namespace MoonlightServers.ApiServer.Http.Controllers.Client;
[ApiController]
[Authorize]
[Route("api/client/servers")]
[Route("api/client/servers/{serverId:int}")]
public class PowerController : Controller
{
private readonly DatabaseRepository<Server> ServerRepository;
@@ -32,31 +32,46 @@ public class PowerController : Controller
AuthorizeService = authorizeService;
}
[HttpPost("{serverId:int}/start")]
[HttpPost("start")]
[Authorize]
public async Task Start([FromRoute] int serverId)
public async Task<ActionResult> Start([FromRoute] int serverId)
{
var server = await GetServerById(serverId);
await ServerService.Start(server);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerService.Start(server.Value);
return NoContent();
}
[HttpPost("{serverId:int}/stop")]
[HttpPost("stop")]
[Authorize]
public async Task Stop([FromRoute] int serverId)
public async Task<ActionResult> Stop([FromRoute] int serverId)
{
var server = await GetServerById(serverId);
await ServerService.Stop(server);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerService.Stop(server.Value);
return NoContent();
}
[HttpPost("{serverId:int}/kill")]
[HttpPost("kill")]
[Authorize]
public async Task Kill([FromRoute] int serverId)
public async Task<ActionResult> Kill([FromRoute] int serverId)
{
var server = await GetServerById(serverId);
await ServerService.Kill(server);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerService.Kill(server.Value);
return NoContent();
}
private async Task<Server> GetServerById(int serverId)
private async Task<ActionResult<Server>> GetServerById(int serverId)
{
var server = await ServerRepository
.Get()
@@ -64,7 +79,7 @@ public class PowerController : Controller
.FirstOrDefaultAsync(x => x.Id == serverId);
if (server == null)
throw new HttpApiException("No server with this id found", 404);
return Problem("No server with this id found", statusCode: 404);
var authorizeResult = await AuthorizeService.Authorize(
User, server,
@@ -74,9 +89,9 @@ public class PowerController : Controller
if (!authorizeResult.Succeeded)
{
throw new HttpApiException(
return Problem(
authorizeResult.Message ?? "No permission for the requested resource",
403
statusCode: 403
);
}

View File

@@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Models;
using MoonCore.Models;
using Moonlight.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Database.Entities;
@@ -51,15 +52,12 @@ public class ServersController : Controller
}
[HttpGet]
public async Task<PagedData<ServerDetailResponse>> GetAll(
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(0, 100)] int pageSize
)
public async Task<ActionResult<PagedData<ServerDetailResponse>>> GetAll([FromQuery] PagedOptions options)
{
var userIdClaim = User.FindFirstValue("userId");
var userIdClaim = User.FindFirstValue("UserId");
if (string.IsNullOrEmpty(userIdClaim))
throw new HttpApiException("Only users are able to use this endpoint", 400);
return Problem("Only users are able to use this endpoint", statusCode: 400);
var userId = int.Parse(userIdClaim);
@@ -71,11 +69,12 @@ public class ServersController : Controller
.Where(x => x.OwnerId == userId);
var count = await query.CountAsync();
var items = await query
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.AsNoTracking()
.ToArrayAsync();
var mappedItems = items.Select(x => new ServerDetailResponse()
@@ -98,23 +97,20 @@ public class ServersController : Controller
return new PagedData<ServerDetailResponse>()
{
Items = mappedItems,
CurrentPage = page,
PageSize = pageSize,
CurrentPage = options.Page,
TotalItems = count,
TotalPages = count == 0 ? 0 : count / pageSize
PageSize = options.PageSize,
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
[HttpGet("shared")]
public async Task<PagedData<ServerDetailResponse>> GetAllShared(
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(0, 100)] int pageSize
)
public async Task<ActionResult<PagedData<ServerDetailResponse>>> GetAllShared([FromQuery] PagedOptions options)
{
var userIdClaim = User.FindFirstValue("userId");
var userIdClaim = User.FindFirstValue("UserId");
if (string.IsNullOrEmpty(userIdClaim))
throw new HttpApiException("Only users are able to use this endpoint", 400);
return Problem("Only users are able to use this endpoint", statusCode: 400);
var userId = int.Parse(userIdClaim);
@@ -129,11 +125,11 @@ public class ServersController : Controller
.Where(x => x.UserId == userId);
var count = await query.CountAsync();
var items = await query
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.ToArrayAsync();
var ownerIds = items
@@ -171,15 +167,15 @@ public class ServersController : Controller
return new PagedData<ServerDetailResponse>()
{
Items = mappedItems,
CurrentPage = page,
PageSize = pageSize,
CurrentPage = options.Page,
TotalItems = count,
TotalPages = count == 0 ? 0 : count / pageSize
PageSize = options.PageSize,
TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize)
};
}
[HttpGet("{serverId:int}")]
public async Task<ServerDetailResponse> Get([FromRoute] int serverId)
public async Task<ActionResult<ServerDetailResponse>> Get([FromRoute] int serverId)
{
var server = await ServerRepository
.Get()
@@ -189,7 +185,7 @@ public class ServersController : Controller
.FirstOrDefaultAsync(x => x.Id == serverId);
if (server == null)
throw new HttpApiException("No server with this id found", 404);
return Problem("No server with this id found", statusCode: 404);
var authorizationResult = await AuthorizeService.Authorize(
User,
@@ -200,9 +196,9 @@ public class ServersController : Controller
if (!authorizationResult.Succeeded)
{
throw new HttpApiException(
return Problem(
authorizationResult.Message ?? "No server with this id found",
404
statusCode: 404
);
}
@@ -242,15 +238,18 @@ public class ServersController : Controller
}
[HttpGet("{serverId:int}/status")]
public async Task<ServerStatusResponse> GetStatus([FromRoute] int serverId)
public async Task<ActionResult<ServerStatusResponse>> GetStatus([FromRoute] int serverId)
{
var server = await GetServerById(
serverId,
ServerPermissionConstants.Console,
ServerPermissionLevel.None
);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var status = await ServerService.GetStatus(server);
var status = await ServerService.GetStatus(server.Value);
return new ServerStatusResponse()
{
@@ -259,13 +258,18 @@ public class ServersController : Controller
}
[HttpGet("{serverId:int}/ws")]
public async Task<ServerWebSocketResponse> GetWebSocket([FromRoute] int serverId)
public async Task<ActionResult<ServerWebSocketResponse>> GetWebSocket([FromRoute] int serverId)
{
var server = await GetServerById(
var serverResult = await GetServerById(
serverId,
ServerPermissionConstants.Console,
ServerPermissionLevel.Read
);
if (serverResult.Value == null)
return serverResult.Result ?? Problem("Unable to retrieve server");
var server = serverResult.Value;
// TODO: Handle transparent node proxy
@@ -288,15 +292,18 @@ public class ServersController : Controller
}
[HttpGet("{serverId:int}/logs")]
public async Task<ServerLogsResponse> GetLogs([FromRoute] int serverId)
public async Task<ActionResult<ServerLogsResponse>> GetLogs([FromRoute] int serverId)
{
var server = await GetServerById(
serverId,
ServerPermissionConstants.Console,
ServerPermissionLevel.Read
);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var logs = await ServerService.GetLogs(server);
var logs = await ServerService.GetLogs(server.Value);
return new ServerLogsResponse()
{
@@ -305,15 +312,18 @@ public class ServersController : Controller
}
[HttpGet("{serverId:int}/stats")]
public async Task<ServerStatsResponse> GetStats([FromRoute] int serverId)
public async Task<ActionResult<ServerStatsResponse>> GetStats([FromRoute] int serverId)
{
var server = await GetServerById(
serverId,
ServerPermissionConstants.Console,
ServerPermissionLevel.Read
);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var stats = await ServerService.GetStats(server);
var stats = await ServerService.GetStats(server.Value);
return new ServerStatsResponse()
{
@@ -327,7 +337,7 @@ public class ServersController : Controller
}
[HttpPost("{serverId:int}/command")]
public async Task Command([FromRoute] int serverId, [FromBody] ServerCommandRequest request)
public async Task<ActionResult> Command([FromRoute] int serverId, [FromBody] ServerCommandRequest request)
{
var server = await GetServerById(
serverId,
@@ -335,10 +345,15 @@ public class ServersController : Controller
ServerPermissionLevel.ReadWrite
);
await ServerService.RunCommand(server, request.Command);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerService.RunCommand(server.Value, request.Command);
return NoContent();
}
private async Task<Server> GetServerById(int serverId, string permissionId, ServerPermissionLevel level)
private async Task<ActionResult<Server>> GetServerById(int serverId, string permissionId, ServerPermissionLevel level)
{
var server = await ServerRepository
.Get()
@@ -346,15 +361,15 @@ public class ServersController : Controller
.FirstOrDefaultAsync(x => x.Id == serverId);
if (server == null)
throw new HttpApiException("No server with this id found", 404);
return Problem("No server with this id found", statusCode: 404);
var authorizeResult = await AuthorizeService.Authorize(User, server, permissionId, level);
if (!authorizeResult.Succeeded)
{
throw new HttpApiException(
return Problem(
authorizeResult.Message ?? "No permission for the requested resource",
403
statusCode: 403
);
}

View File

@@ -32,13 +32,18 @@ public class SettingsController : Controller
[HttpPost("{serverId:int}/install")]
[Authorize]
public async Task Install([FromRoute] int serverId)
public async Task<ActionResult> Install([FromRoute] int serverId)
{
var server = await GetServerById(serverId);
await ServerService.Install(server);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
await ServerService.Install(server.Value);
return NoContent();
}
private async Task<Server> GetServerById(int serverId)
private async Task<ActionResult<Server>> GetServerById(int serverId)
{
var server = await ServerRepository
.Get()
@@ -46,7 +51,7 @@ public class SettingsController : Controller
.FirstOrDefaultAsync(x => x.Id == serverId);
if (server == null)
throw new HttpApiException("No server with this id found", 404);
return Problem("No server with this id found", statusCode: 404);
var authorizeResult = await AuthorizeService.Authorize(
User, server,
@@ -56,9 +61,9 @@ public class SettingsController : Controller
if (!authorizeResult.Succeeded)
{
throw new HttpApiException(
return Problem(
authorizeResult.Message ?? "No permission for the requested resource",
403
statusCode: 403
);
}

View File

@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Models;
using MoonCore.Models;
using Moonlight.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Database.Entities;
@@ -41,24 +42,26 @@ public class SharesController : Controller
}
[HttpGet]
public async Task<PagedData<ServerShareResponse>> GetAll(
public async Task<ActionResult<IPagedData<ServerShareResponse>>> GetAll(
[FromRoute] int serverId,
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
[FromQuery] PagedOptions options
)
{
var server = await GetServerById(serverId);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var query = ShareRepository
.Get()
.Where(x => x.Server.Id == server.Id);
.Where(x => x.Server.Id == server.Value.Id);
var count = await query.CountAsync();
var items = await query
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.ToArrayAsync();
var userIds = items
@@ -81,27 +84,30 @@ public class SharesController : Controller
return new PagedData<ServerShareResponse>()
{
Items = mappedItems,
CurrentPage = page,
PageSize = pageSize,
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}")]
public async Task<ServerShareResponse> Get(
public async Task<ActionResult<ServerShareResponse>> Get(
[FromRoute] int serverId,
[FromRoute] int id
)
{
var server = await GetServerById(serverId);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var share = await ShareRepository
.Get()
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.Id == id);
.FirstOrDefaultAsync(x => x.Server.Id == server.Value.Id && x.Id == id);
if (share == null)
throw new HttpApiException("A share with that id cannot be found", 404);
return Problem("A share with that id cannot be found", statusCode: 404);
var user = await UserRepository
.Get()
@@ -118,23 +124,26 @@ public class SharesController : Controller
}
[HttpPost]
public async Task<ServerShareResponse> Create(
public async Task<ActionResult<ServerShareResponse>> Create(
[FromRoute] int serverId,
[FromBody] CreateShareRequest request
)
{
var server = await GetServerById(serverId);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var user = await UserRepository
.Get()
.FirstOrDefaultAsync(x => x.Username == request.Username);
if (user == null)
throw new HttpApiException("A user with that username could not be found", 400);
return Problem("A user with that username could not be found", statusCode: 400);
var share = new ServerShare()
{
Server = server,
Server = server.Value,
Content = ShareMapper.MapToServerShareContent(request.Permissions),
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow,
@@ -154,20 +163,23 @@ public class SharesController : Controller
}
[HttpPatch("{id:int}")]
public async Task<ServerShareResponse> Update(
public async Task<ActionResult<ServerShareResponse>> Update(
[FromRoute] int serverId,
[FromRoute] int id,
[FromBody] UpdateShareRequest request
)
{
var server = await GetServerById(serverId);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var share = await ShareRepository
.Get()
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.Id == id);
.FirstOrDefaultAsync(x => x.Server.Id == server.Value.Id && x.Id == id);
if (share == null)
throw new HttpApiException("A share with that id cannot be found", 404);
return Problem("A share with that id cannot be found", statusCode: 404);
share.Content = ShareMapper.MapToServerShareContent(request.Permissions);
@@ -180,7 +192,7 @@ public class SharesController : Controller
.FirstOrDefaultAsync(x => x.Id == share.UserId);
if (user == null)
throw new HttpApiException("A user with that id could not be found", 400);
return Problem("A user with that id could not be found", statusCode: 400);
var mappedItem = new ServerShareResponse()
{
@@ -193,31 +205,35 @@ public class SharesController : Controller
}
[HttpDelete("{id:int}")]
public async Task Delete(
public async Task<ActionResult> Delete(
[FromRoute] int serverId,
[FromRoute] int id
)
{
var server = await GetServerById(serverId);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var share = await ShareRepository
.Get()
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.Id == id);
.FirstOrDefaultAsync(x => x.Server.Id == server.Value.Id && x.Id == id);
if (share == null)
throw new HttpApiException("A share with that id cannot be found", 404);
return Problem("A share with that id cannot be found", statusCode: 404);
await ShareRepository.Remove(share);
return NoContent();
}
private async Task<Server> GetServerById(int serverId)
private async Task<ActionResult<Server>> GetServerById(int serverId)
{
var server = await ServerRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == serverId);
if (server == null)
throw new HttpApiException("No server with this id found", 404);
return Problem("No server with this id found", statusCode: 404);
var authorizeResult = await AuthorizeService.Authorize(
User, server,
@@ -227,9 +243,9 @@ public class SharesController : Controller
if (!authorizeResult.Succeeded)
{
throw new HttpApiException(
return Problem(
authorizeResult.Message ?? "No permission for the requested resource",
403
statusCode: 403
);
}

View File

@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Models;
using MoonCore.Models;
using Moonlight.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Database.Entities;
@@ -40,24 +41,26 @@ public class VariablesController : Controller
}
[HttpGet]
public async Task<PagedData<ServerVariableDetailResponse>> Get(
public async Task<ActionResult<PagedData<ServerVariableDetailResponse>>> Get(
[FromRoute] int serverId,
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
[FromQuery] PagedOptions options
)
{
var server = await GetServerById(serverId, ServerPermissionLevel.Read);
if (server.Value == null)
return server.Result ?? Problem("Unable to retrieve server");
var query = StarVariableRepository
.Get()
.Where(x => x.Star.Id == server.Star.Id);
.Where(x => x.Star.Id == server.Value.Star.Id);
var count = await query.CountAsync();
var starVariables = await query
.OrderBy(x => x.Id)
.Skip(page * pageSize)
.Take(pageSize)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.ToArrayAsync();
var starVariableKeys = starVariables
@@ -66,7 +69,7 @@ public class VariablesController : Controller
var serverVariables = await ServerVariableRepository
.Get()
.Where(x => x.Server.Id == server.Id && starVariableKeys.Contains(x.Key))
.Where(x => x.Server.Id == server.Value.Id && starVariableKeys.Contains(x.Key))
.ToArrayAsync();
var responses = starVariables.Select(starVariable =>
@@ -87,22 +90,27 @@ public class VariablesController : Controller
return new PagedData<ServerVariableDetailResponse>()
{
Items = responses,
CurrentPage = page,
PageSize = pageSize,
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)
};
}
[HttpPut]
public async Task<ServerVariableDetailResponse> UpdateSingle(
public async Task<ActionResult<ServerVariableDetailResponse>> UpdateSingle(
[FromRoute] int serverId,
[FromBody] UpdateServerVariableRequest request
)
{
// TODO: Handle filter
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
var serverResult = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (serverResult.Value == null)
return serverResult.Result ?? Problem("Unable to retrieve server");
var server = serverResult.Value;
var serverVariable = server.Variables.FirstOrDefault(x => x.Key == request.Key);
var starVariable = server.Star.Variables.FirstOrDefault(x => x.Key == request.Key);
@@ -125,12 +133,17 @@ public class VariablesController : Controller
}
[HttpPatch]
public async Task<ServerVariableDetailResponse[]> Update(
public async Task<ActionResult<ServerVariableDetailResponse[]>> Update(
[FromRoute] int serverId,
[FromBody] UpdateServerVariableRangeRequest request
)
{
var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
var serverResult = await GetServerById(serverId, ServerPermissionLevel.ReadWrite);
if (serverResult.Value == null)
return serverResult.Result ?? Problem("Unable to retrieve server");
var server = serverResult.Value;
foreach (var variable in request.Variables)
{
@@ -164,15 +177,17 @@ public class VariablesController : Controller
}).ToArray();
}
private async Task<Server> GetServerById(int serverId, ServerPermissionLevel level)
private async Task<ActionResult<Server>> GetServerById(int serverId, ServerPermissionLevel level)
{
var server = await ServerRepository
.Get()
.Include(x => x.Star)
.ThenInclude(x => x.Variables)
.Include(x => x.Variables)
.FirstOrDefaultAsync(x => x.Id == serverId);
if (server == null)
throw new HttpApiException("No server with this id found", 404);
return Problem("No server with this id found", statusCode: 404);
var authorizeResult = await AuthorizeService.Authorize(
User, server,
@@ -182,9 +197,9 @@ public class VariablesController : Controller
if (!authorizeResult.Succeeded)
{
throw new HttpApiException(
return Problem(
authorizeResult.Message ?? "No permission for the requested resource",
403
statusCode: 403
);
}

View File

@@ -19,7 +19,7 @@ public class OwnerAuthFilter : IServerAuthorizationFilter
ServerPermissionLevel requiredLevel
)
{
var userIdValue = user.FindFirstValue("userId");
var userIdValue = user.FindFirstValue("UserId");
if (string.IsNullOrEmpty(userIdValue)) // This is the case for api keys
return Task.FromResult<ServerAuthorizationResult?>(null);

View File

@@ -11,4 +11,8 @@ public static partial class AllocationMapper
public static partial NodeAllocationResponse ToNodeAllocation(Allocation allocation);
public static partial Allocation ToAllocation(CreateNodeAllocationRequest request);
public static partial void Merge(UpdateNodeAllocationRequest request, Allocation allocation);
// EF Projections
public static partial IQueryable<NodeAllocationResponse> ProjectToAdminResponse(this IQueryable<Allocation> allocations);
}

View File

@@ -8,7 +8,11 @@ namespace MoonlightServers.ApiServer.Mappers;
[Mapper(AllowNullPropertyAssignment = false)]
public static partial class DockerImageMapper
{
public static partial StarDockerImageDetailResponse ToAdminResponse(StarDockerImage dockerImage);
public static partial StarDockerImageResponse ToAdminResponse(StarDockerImage dockerImage);
public static partial StarDockerImage ToDockerImage(CreateStarDockerImageRequest request);
public static partial void Merge(UpdateStarDockerImageRequest request, StarDockerImage variable);
// EF Migrations
public static partial IQueryable<StarDockerImageResponse> ProjectToAdminResponse(this IQueryable<StarDockerImage> dockerImages);
}

View File

@@ -11,4 +11,8 @@ public static partial class NodeMapper
public static partial NodeResponse ToAdminNodeResponse(Node node);
public static partial Node ToNode(CreateNodeRequest request);
public static partial void Merge(UpdateNodeRequest request, Node node);
// EF Projections
public static partial IQueryable<NodeResponse> ProjectToAdminResponse(this IQueryable<Node> nodes);
}

View File

@@ -1,6 +1,7 @@
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.Shared.Http.Requests.Admin.Servers;
using MoonlightServers.Shared.Http.Responses.Admin.Servers;
using MoonlightServers.Shared.Http.Responses.Client.Servers;
using Riok.Mapperly.Abstractions;
namespace MoonlightServers.ApiServer.Mappers;
@@ -20,6 +21,11 @@ public static partial class ServerMapper
private static partial ServerResponse ToAdminServerResponse_Internal(Server server);
[MapperIgnoreSource(nameof(CreateServerRequest.Variables))]
public static partial Server ToServer(CreateServerRequest request);
public static partial void Merge(UpdateServerRequest request, Server server);
// EF Projections
public static partial IQueryable<ServerResponse> ProjectToAdminResponse(this IQueryable<Server> servers);
}

View File

@@ -8,4 +8,8 @@ namespace MoonlightServers.ApiServer.Mappers;
public static partial class ServerVariableMapper
{
public static partial ServerVariableResponse ToAdminResponse(ServerVariable serverVariable);
// EF Projections
public static partial IQueryable<ServerVariableResponse> ProjectToAdminResponse(this IQueryable<ServerVariable> variables);
}

View File

@@ -9,7 +9,11 @@ namespace MoonlightServers.ApiServer.Mappers;
[Mapper(AllowNullPropertyAssignment = false)]
public static partial class StarMapper
{
public static partial StarDetailResponse ToAdminResponse(Star star);
public static partial StarResponse ToAdminResponse(Star star);
public static partial Star ToStar(CreateStarRequest request);
public static partial void Merge(UpdateStarRequest request, Star star);
// EF Projections
public static partial IQueryable<StarResponse> ProjectToAdminResponse(this IQueryable<Star> stars);
}

View File

@@ -8,7 +8,11 @@ namespace MoonlightServers.ApiServer.Mappers;
[Mapper(AllowNullPropertyAssignment = false)]
public static partial class StarVariableMapper
{
public static partial StarVariableDetailResponse ToAdminResponse(StarVariable variable);
public static partial StarVariableResponse ToAdminResponse(StarVariable variable);
public static partial StarVariable ToStarVariable(CreateStarVariableRequest request);
public static partial void Merge(UpdateStarVariableRequest request, StarVariable variable);
// EF Projections
public static partial IQueryable<StarVariableResponse> ProjectToAdminResponse(this IQueryable<StarVariable> variables);
}