From 85392208c4412774edcec3d76a919d8ddc4c7d07 Mon Sep 17 00:00:00 2001 From: ChiaraBm Date: Mon, 22 Sep 2025 12:13:57 +0200 Subject: [PATCH] Updated to latest moonlight and mooncore version. Done refactoring to async scheme and other changes. Recreated database migrations and cleaned models --- .../MoonlightServers.ApiServer.Runtime.csproj | 2 +- MoonlightServers.ApiServer.Runtime/Program.cs | 6 +- .../Database/Entities/Node.cs | 4 - .../Database/Entities/Server.cs | 2 - ...createdMigrationsForPostgresql.Designer.cs | 452 ---------- ...250301142415_AddedTokenIdField.Designer.cs | 456 ---------- .../20250301142415_AddedTokenIdField.cs | 29 - .../Migrations/20250606121013_AddedShares.cs | 51 -- ...31_RecreatedModelsInNewSchema.Designer.cs} | 47 +- ...50922091731_RecreatedModelsInNewSchema.cs} | 193 +++-- .../ServersDataContextModelSnapshot.cs | 43 +- .../Database/ServersDataContext.cs | 38 +- .../Extensions/ServerStateExtensions.cs | 2 - .../Admin/Nodes/NodeAllocationsController.cs | 69 +- .../Admin/Nodes/NodeStatusController.cs | 9 +- .../Admin/Nodes/NodesController.cs | 42 +- .../Admin/Nodes/StatisticsController.cs | 15 +- .../Servers/ServerVariablesController.cs | 24 +- .../Admin/Servers/ServersController.cs | 51 +- .../Admin/Stars/StarDockerImagesController.cs | 37 +- .../Admin/Stars/StarImportExportController.cs | 10 +- .../Admin/Stars/StarVariablesController.cs | 37 +- .../Admin/Stars/StarsController.cs | 44 +- .../Controllers/Client/FilesController.cs | 55 +- .../Controllers/Client/PowerController.cs | 25 +- .../Controllers/Client/ServersController.cs | 92 +- .../Controllers/Client/SettingsController.cs | 11 +- .../Controllers/Client/SharesController.cs | 53 +- .../Controllers/Client/VariablesController.cs | 43 +- .../Remote/Nodes/NodeTripController.cs | 2 +- .../Controllers/Remote/ServersController.cs | 25 +- .../ServerAuthFilters/AdminAuthFilter.cs | 4 +- .../ServerAuthFilters/OwnerAuthFilter.cs | 4 +- .../ServerAuthFilters/ShareAuthFilter.cs | 4 +- .../Interfaces/IServerAuthorizationFilter.cs | 2 +- .../Mappers/ServerMapper.cs | 1 - .../Mappers/StarMapper.cs | 1 - .../MoonlightServers.ApiServer.csproj | 2 +- .../Services/NodeService.cs | 8 +- .../Services/ServerAuthorizeService.cs | 4 +- .../Services/ServerFileSystemService.cs | 30 +- .../Services/ServerService.cs | 43 +- .../Services/StarImportExportService.cs | 22 +- .../Startup/PluginStartup.cs | 6 +- .../Configuration/AppConfiguration.cs | 2 - .../ServerConfigurationExtensions.cs | 2 - .../Helpers/HostSystemHelper.cs | 14 +- .../Helpers/ServerFileSystem.cs | 21 +- .../Helpers/UnsafeDockerClient.cs | 6 +- .../Controllers/Servers/PowerController.cs | 8 +- .../Controllers/Servers/ServersController.cs | 11 +- .../Statistics/StatisticsController.cs | 8 +- .../Statistics/StatisticsDockerController.cs | 6 +- .../Controllers/Sys/SystemStatusController.cs | 4 +- .../Mappers/ServerConfigurationMapper.cs | 2 - .../Models/Cache/ServerConfiguration.cs | 2 - .../Models/ServerConsole.cs | 4 +- .../MoonlightServers.Daemon.csproj | 5 +- MoonlightServers.Daemon/Program.cs | 2 +- .../ServerSystem/Docker/DockerConsole.cs | 12 +- .../ServerSystem/Docker/DockerInstallation.cs | 4 +- .../ServerSystem/Docker/DockerRuntime.cs | 4 +- .../Handlers/InstallationHandler.cs | 2 +- .../ServerSystem/Handlers/StartupHandler.cs | 2 +- .../ServerSystem/Interfaces/IInstallation.cs | 2 +- .../ServerSystem/Interfaces/IRuntime.cs | 2 +- .../ServerSystem/Models/ServerContext.cs | 1 - .../ServerSystem/Server.cs | 1 - .../Services/DockerEventService.cs | 5 - .../Services/DockerImageService.cs | 2 +- .../Services/DockerInfoService.cs | 6 +- .../Services/RemoteService.cs | 15 +- .../Services/ServerService.cs | 19 +- MoonlightServers.Daemon/Startup.cs | 90 +- .../Http/Responses/ServerDataResponse.cs | 3 - .../MoonlightServers.Frontend.Runtime.csproj | 4 +- MoonlightServers.Frontend.Runtime/Program.cs | 6 +- .../Styles/extract-classes.js | 4 +- .../Styles/styles.css | 26 +- .../Helpers/ServerFsAccess.cs | 28 +- .../DefaultPermissionProvider.cs | 2 +- .../DefaultServerTabProvider.cs | 2 +- .../Interfaces/IServerPermissionProvider.cs | 2 +- .../Interfaces/IServerTabProvider.cs | 2 +- MoonlightServers.Frontend/Models/ServerTab.cs | 1 - .../MoonlightServers.Frontend.csproj | 5 +- .../MoonlightServers.Frontend.targets | 8 + .../Services/NodeService.cs | 6 +- .../Services/ServerFileSystemService.cs | 19 +- .../Services/ServerService.cs | 42 +- .../Services/ServerShareService.cs | 14 +- .../Startup/PluginStartup.cs | 4 +- .../Styles/Moonlight.Client/classes.map | 58 ++ .../Styles/mappings/classes.map | 790 ++++++++++++++++++ .../UI/Components/Forms/Switch.razor | 1 - .../UI/Components/FullScreenModal.razor | 13 +- .../Nodes/Modals/CreateAllocationModal.razor | 49 +- .../CreateMultipleAllocationModal.razor | 58 +- .../Nodes/Modals/UpdateAllocationModal.razor | 49 +- .../Nodes/UpdatePartials/Advanced.razor | 21 +- .../Nodes/UpdatePartials/Allocations.razor | 117 +-- .../Nodes/UpdatePartials/Overview.razor | 18 +- .../Servers/CreatePartials/Advanced.razor | 22 +- .../Servers/CreatePartials/Allocations.razor | 11 +- .../Servers/CreatePartials/General.razor | 30 +- .../Servers/CreatePartials/Variables.razor | 15 +- .../Components/Servers/CreateShareModal.razor | 62 +- .../Components/Servers/PermissionEditor.razor | 14 +- .../UI/Components/Servers/ServerCard.razor | 4 +- .../Servers/ServerTabs/ConsoleTab.razor | 6 +- .../Servers/ServerTabs/SettingsTab.razor | 8 +- .../Servers/ServerTabs/SharesTab.razor | 52 +- .../Servers/ServerTabs/VariablesTab.razor | 18 +- .../Servers/UpdatePartials/Advanced.razor | 6 - .../Servers/UpdatePartials/Allocations.razor | 10 +- .../Servers/UpdatePartials/General.razor | 10 +- .../Servers/UpdatePartials/Variables.razor | 20 +- .../Components/Servers/UpdateShareModal.razor | 55 +- .../Stars/Modals/CreateDockerImageModal.razor | 58 +- .../Stars/Modals/CreateParseConfigModal.razor | 86 +- .../Stars/Modals/CreateVariableModal.razor | 120 +-- .../Stars/Modals/UpdateDockerImageModal.razor | 58 +- .../Stars/Modals/UpdateParseConfigModal.razor | 83 +- .../Stars/Modals/UpdateVariableModal.razor | 120 +-- .../Stars/UpdatePartials/DockerImage.razor | 40 +- .../Stars/UpdatePartials/Installation.razor | 2 +- .../Stars/UpdatePartials/Misc.razor | 10 +- .../Stars/UpdatePartials/ParseConfig.razor | 24 +- .../Stars/UpdatePartials/Variables.razor | 38 +- .../UI/Components/XtermConsole.razor | 35 +- .../UI/Views/Admin/All/Create.razor | 4 +- .../UI/Views/Admin/All/Index.razor | 188 +++-- .../UI/Views/Admin/All/Update.razor | 9 +- .../UI/Views/Admin/Nodes/Create.razor | 4 +- .../UI/Views/Admin/Nodes/Index.razor | 273 +++--- .../UI/Views/Admin/Nodes/Update.razor | 10 +- .../UI/Views/Admin/Stars/Create.razor | 4 +- .../UI/Views/Admin/Stars/Index.razor | 140 ++-- .../UI/Views/Admin/Stars/Update.razor | 8 +- .../UI/Views/Client/Index.razor | 16 +- .../UI/Views/Client/Manage.razor | 38 +- .../Requests/Admin/Nodes/CreateNodeRequest.cs | 3 - .../Requests/Admin/Nodes/UpdateNodeRequest.cs | 3 - .../Admin/Servers/CreateServerRequest.cs | 5 - .../Admin/Servers/UpdateServerRequest.cs | 3 - .../Requests/Admin/Stars/CreateStarRequest.cs | 1 - .../Servers/Shares/CreateShareRequest.cs | 1 - .../Responses/Admin/Stars/StarResponse.cs | 3 - .../Client/Servers/ServerDetailResponse.cs | 1 - .../Servers/Shares/ServerShareResponse.cs | 1 - 150 files changed, 2722 insertions(+), 2726 deletions(-) delete mode 100644 MoonlightServers.ApiServer/Database/Migrations/20250226210232_RecreatedMigrationsForPostgresql.Designer.cs delete mode 100644 MoonlightServers.ApiServer/Database/Migrations/20250301142415_AddedTokenIdField.Designer.cs delete mode 100644 MoonlightServers.ApiServer/Database/Migrations/20250301142415_AddedTokenIdField.cs delete mode 100644 MoonlightServers.ApiServer/Database/Migrations/20250606121013_AddedShares.cs rename MoonlightServers.ApiServer/Database/Migrations/{20250606121013_AddedShares.Designer.cs => 20250922091731_RecreatedModelsInNewSchema.Designer.cs} (92%) rename MoonlightServers.ApiServer/Database/Migrations/{20250226210232_RecreatedMigrationsForPostgresql.cs => 20250922091731_RecreatedModelsInNewSchema.cs} (64%) create mode 100644 MoonlightServers.Frontend/MoonlightServers.Frontend.targets create mode 100644 MoonlightServers.Frontend/Styles/mappings/classes.map diff --git a/MoonlightServers.ApiServer.Runtime/MoonlightServers.ApiServer.Runtime.csproj b/MoonlightServers.ApiServer.Runtime/MoonlightServers.ApiServer.Runtime.csproj index d14c8a7..002a910 100644 --- a/MoonlightServers.ApiServer.Runtime/MoonlightServers.ApiServer.Runtime.csproj +++ b/MoonlightServers.ApiServer.Runtime/MoonlightServers.ApiServer.Runtime.csproj @@ -13,7 +13,7 @@ - + diff --git a/MoonlightServers.ApiServer.Runtime/Program.cs b/MoonlightServers.ApiServer.Runtime/Program.cs index 944f9a0..7ba1fd9 100644 --- a/MoonlightServers.ApiServer.Runtime/Program.cs +++ b/MoonlightServers.ApiServer.Runtime/Program.cs @@ -6,15 +6,15 @@ pluginLoader.Initialize(); var cs = new Startup(); -await cs.Initialize(args, pluginLoader.Instances); +await cs.InitializeAsync(args, pluginLoader.Instances); var builder = WebApplication.CreateBuilder(args); -await cs.AddMoonlight(builder); +await cs.AddMoonlightAsync(builder); var app = builder.Build(); -await cs.AddMoonlight(app); +await cs.AddMoonlightAsync(app); // Handle setup of wasm app hosting in the runtime // so the Moonlight.ApiServer doesn't need the wasm package diff --git a/MoonlightServers.ApiServer/Database/Entities/Node.cs b/MoonlightServers.ApiServer/Database/Entities/Node.cs index 7ef1d75..c53f578 100644 --- a/MoonlightServers.ApiServer/Database/Entities/Node.cs +++ b/MoonlightServers.ApiServer/Database/Entities/Node.cs @@ -18,8 +18,4 @@ public class Node public int HttpPort { get; set; } public int FtpPort { get; set; } public bool UseSsl { get; set; } - - // Misc - public bool EnableTransparentMode { get; set; } - public bool EnableDynamicFirewall { get; set; } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Database/Entities/Server.cs b/MoonlightServers.ApiServer/Database/Entities/Server.cs index 66feafb..f7a6b34 100644 --- a/MoonlightServers.ApiServer/Database/Entities/Server.cs +++ b/MoonlightServers.ApiServer/Database/Entities/Server.cs @@ -24,6 +24,4 @@ public class Server public int Cpu { get; set; } public int Memory { get; set; } public int Disk { get; set; } - public bool UseVirtualDisk { get; set; } - public int Bandwidth { get; set; } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Database/Migrations/20250226210232_RecreatedMigrationsForPostgresql.Designer.cs b/MoonlightServers.ApiServer/Database/Migrations/20250226210232_RecreatedMigrationsForPostgresql.Designer.cs deleted file mode 100644 index 3ea509c..0000000 --- a/MoonlightServers.ApiServer/Database/Migrations/20250226210232_RecreatedMigrationsForPostgresql.Designer.cs +++ /dev/null @@ -1,452 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using MoonlightServers.ApiServer.Database; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -#nullable disable - -namespace MoonlightServers.ApiServer.Database.Migrations -{ - [DbContext(typeof(ServersDataContext))] - [Migration("20250226210232_RecreatedMigrationsForPostgresql")] - partial class RecreatedMigrationsForPostgresql - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "8.0.11") - .HasAnnotation("Relational:MaxIdentifierLength", 63); - - NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Allocation", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("IpAddress") - .IsRequired() - .HasColumnType("text"); - - b.Property("NodeId") - .HasColumnType("integer"); - - b.Property("Port") - .HasColumnType("integer"); - - b.Property("ServerId") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("NodeId"); - - b.HasIndex("ServerId"); - - b.ToTable("Servers_Allocations", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Node", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("EnableDynamicFirewall") - .HasColumnType("boolean"); - - b.Property("EnableTransparentMode") - .HasColumnType("boolean"); - - b.Property("Fqdn") - .IsRequired() - .HasColumnType("text"); - - b.Property("FtpPort") - .HasColumnType("integer"); - - b.Property("HttpPort") - .HasColumnType("integer"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("Token") - .IsRequired() - .HasColumnType("text"); - - b.Property("UseSsl") - .HasColumnType("boolean"); - - b.HasKey("Id"); - - b.ToTable("Servers_Nodes", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Server", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("Bandwidth") - .HasColumnType("integer"); - - b.Property("Cpu") - .HasColumnType("integer"); - - b.Property("Disk") - .HasColumnType("integer"); - - b.Property("DockerImageIndex") - .HasColumnType("integer"); - - b.Property("Memory") - .HasColumnType("integer"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("NodeId") - .HasColumnType("integer"); - - b.Property("OwnerId") - .HasColumnType("integer"); - - b.Property("StarId") - .HasColumnType("integer"); - - b.Property("StartupOverride") - .HasColumnType("text"); - - b.Property("UseVirtualDisk") - .HasColumnType("boolean"); - - b.HasKey("Id"); - - b.HasIndex("NodeId"); - - b.HasIndex("StarId"); - - b.ToTable("Servers_Servers", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerBackup", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("Completed") - .HasColumnType("boolean"); - - b.Property("CompletedAt") - .HasColumnType("timestamp with time zone"); - - b.Property("CreatedAt") - .HasColumnType("timestamp with time zone"); - - b.Property("ServerId") - .HasColumnType("integer"); - - b.Property("Size") - .HasColumnType("bigint"); - - b.Property("Successful") - .HasColumnType("boolean"); - - b.HasKey("Id"); - - b.HasIndex("ServerId"); - - b.ToTable("Servers_ServerBackups", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerVariable", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("Key") - .IsRequired() - .HasColumnType("text"); - - b.Property("ServerId") - .HasColumnType("integer"); - - b.Property("Value") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("Id"); - - b.HasIndex("ServerId"); - - b.ToTable("Servers_ServerVariables", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Star", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("AllowDockerImageChange") - .HasColumnType("boolean"); - - b.Property("Author") - .IsRequired() - .HasColumnType("text"); - - b.Property("DefaultDockerImage") - .HasColumnType("integer"); - - b.Property("DonateUrl") - .HasColumnType("text"); - - b.Property("InstallDockerImage") - .IsRequired() - .HasColumnType("text"); - - b.Property("InstallScript") - .IsRequired() - .HasColumnType("text"); - - b.Property("InstallShell") - .IsRequired() - .HasColumnType("text"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("OnlineDetection") - .IsRequired() - .HasColumnType("text"); - - b.Property("ParseConfiguration") - .IsRequired() - .HasColumnType("text"); - - b.Property("RequiredAllocations") - .HasColumnType("integer"); - - b.Property("StartupCommand") - .IsRequired() - .HasColumnType("text"); - - b.Property("StopCommand") - .IsRequired() - .HasColumnType("text"); - - b.Property("UpdateUrl") - .HasColumnType("text"); - - b.Property("Version") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Servers_Stars", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarDockerImage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("AutoPulling") - .HasColumnType("boolean"); - - b.Property("DisplayName") - .IsRequired() - .HasColumnType("text"); - - b.Property("Identifier") - .IsRequired() - .HasColumnType("text"); - - b.Property("StarId") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("StarId"); - - b.ToTable("Servers_StarDockerImages", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarVariable", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("AllowEditing") - .HasColumnType("boolean"); - - b.Property("AllowViewing") - .HasColumnType("boolean"); - - b.Property("DefaultValue") - .IsRequired() - .HasColumnType("text"); - - b.Property("Description") - .IsRequired() - .HasColumnType("text"); - - b.Property("Filter") - .HasColumnType("text"); - - b.Property("Key") - .IsRequired() - .HasColumnType("text"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("StarId") - .HasColumnType("integer"); - - b.Property("Type") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("StarId"); - - b.ToTable("Servers_StarVariables", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Allocation", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Node", "Node") - .WithMany("Allocations") - .HasForeignKey("NodeId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Server", "Server") - .WithMany("Allocations") - .HasForeignKey("ServerId"); - - b.Navigation("Node"); - - b.Navigation("Server"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Server", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Node", "Node") - .WithMany("Servers") - .HasForeignKey("NodeId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Star", "Star") - .WithMany() - .HasForeignKey("StarId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Node"); - - b.Navigation("Star"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerBackup", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Server", null) - .WithMany("Backups") - .HasForeignKey("ServerId"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerVariable", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Server", "Server") - .WithMany("Variables") - .HasForeignKey("ServerId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Server"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarDockerImage", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Star", "Star") - .WithMany("DockerImages") - .HasForeignKey("StarId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Star"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarVariable", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Star", "Star") - .WithMany("Variables") - .HasForeignKey("StarId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Star"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Node", b => - { - b.Navigation("Allocations"); - - b.Navigation("Servers"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Server", b => - { - b.Navigation("Allocations"); - - b.Navigation("Backups"); - - b.Navigation("Variables"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Star", b => - { - b.Navigation("DockerImages"); - - b.Navigation("Variables"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/MoonlightServers.ApiServer/Database/Migrations/20250301142415_AddedTokenIdField.Designer.cs b/MoonlightServers.ApiServer/Database/Migrations/20250301142415_AddedTokenIdField.Designer.cs deleted file mode 100644 index 438e78a..0000000 --- a/MoonlightServers.ApiServer/Database/Migrations/20250301142415_AddedTokenIdField.Designer.cs +++ /dev/null @@ -1,456 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using MoonlightServers.ApiServer.Database; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -#nullable disable - -namespace MoonlightServers.ApiServer.Database.Migrations -{ - [DbContext(typeof(ServersDataContext))] - [Migration("20250301142415_AddedTokenIdField")] - partial class AddedTokenIdField - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "8.0.11") - .HasAnnotation("Relational:MaxIdentifierLength", 63); - - NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Allocation", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("IpAddress") - .IsRequired() - .HasColumnType("text"); - - b.Property("NodeId") - .HasColumnType("integer"); - - b.Property("Port") - .HasColumnType("integer"); - - b.Property("ServerId") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("NodeId"); - - b.HasIndex("ServerId"); - - b.ToTable("Servers_Allocations", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Node", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("EnableDynamicFirewall") - .HasColumnType("boolean"); - - b.Property("EnableTransparentMode") - .HasColumnType("boolean"); - - b.Property("Fqdn") - .IsRequired() - .HasColumnType("text"); - - b.Property("FtpPort") - .HasColumnType("integer"); - - b.Property("HttpPort") - .HasColumnType("integer"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("Token") - .IsRequired() - .HasColumnType("text"); - - b.Property("TokenId") - .IsRequired() - .HasColumnType("text"); - - b.Property("UseSsl") - .HasColumnType("boolean"); - - b.HasKey("Id"); - - b.ToTable("Servers_Nodes", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Server", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("Bandwidth") - .HasColumnType("integer"); - - b.Property("Cpu") - .HasColumnType("integer"); - - b.Property("Disk") - .HasColumnType("integer"); - - b.Property("DockerImageIndex") - .HasColumnType("integer"); - - b.Property("Memory") - .HasColumnType("integer"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("NodeId") - .HasColumnType("integer"); - - b.Property("OwnerId") - .HasColumnType("integer"); - - b.Property("StarId") - .HasColumnType("integer"); - - b.Property("StartupOverride") - .HasColumnType("text"); - - b.Property("UseVirtualDisk") - .HasColumnType("boolean"); - - b.HasKey("Id"); - - b.HasIndex("NodeId"); - - b.HasIndex("StarId"); - - b.ToTable("Servers_Servers", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerBackup", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("Completed") - .HasColumnType("boolean"); - - b.Property("CompletedAt") - .HasColumnType("timestamp with time zone"); - - b.Property("CreatedAt") - .HasColumnType("timestamp with time zone"); - - b.Property("ServerId") - .HasColumnType("integer"); - - b.Property("Size") - .HasColumnType("bigint"); - - b.Property("Successful") - .HasColumnType("boolean"); - - b.HasKey("Id"); - - b.HasIndex("ServerId"); - - b.ToTable("Servers_ServerBackups", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerVariable", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("Key") - .IsRequired() - .HasColumnType("text"); - - b.Property("ServerId") - .HasColumnType("integer"); - - b.Property("Value") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("Id"); - - b.HasIndex("ServerId"); - - b.ToTable("Servers_ServerVariables", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Star", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("AllowDockerImageChange") - .HasColumnType("boolean"); - - b.Property("Author") - .IsRequired() - .HasColumnType("text"); - - b.Property("DefaultDockerImage") - .HasColumnType("integer"); - - b.Property("DonateUrl") - .HasColumnType("text"); - - b.Property("InstallDockerImage") - .IsRequired() - .HasColumnType("text"); - - b.Property("InstallScript") - .IsRequired() - .HasColumnType("text"); - - b.Property("InstallShell") - .IsRequired() - .HasColumnType("text"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("OnlineDetection") - .IsRequired() - .HasColumnType("text"); - - b.Property("ParseConfiguration") - .IsRequired() - .HasColumnType("text"); - - b.Property("RequiredAllocations") - .HasColumnType("integer"); - - b.Property("StartupCommand") - .IsRequired() - .HasColumnType("text"); - - b.Property("StopCommand") - .IsRequired() - .HasColumnType("text"); - - b.Property("UpdateUrl") - .HasColumnType("text"); - - b.Property("Version") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Servers_Stars", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarDockerImage", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("AutoPulling") - .HasColumnType("boolean"); - - b.Property("DisplayName") - .IsRequired() - .HasColumnType("text"); - - b.Property("Identifier") - .IsRequired() - .HasColumnType("text"); - - b.Property("StarId") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("StarId"); - - b.ToTable("Servers_StarDockerImages", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarVariable", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("AllowEditing") - .HasColumnType("boolean"); - - b.Property("AllowViewing") - .HasColumnType("boolean"); - - b.Property("DefaultValue") - .IsRequired() - .HasColumnType("text"); - - b.Property("Description") - .IsRequired() - .HasColumnType("text"); - - b.Property("Filter") - .HasColumnType("text"); - - b.Property("Key") - .IsRequired() - .HasColumnType("text"); - - b.Property("Name") - .IsRequired() - .HasColumnType("text"); - - b.Property("StarId") - .HasColumnType("integer"); - - b.Property("Type") - .HasColumnType("integer"); - - b.HasKey("Id"); - - b.HasIndex("StarId"); - - b.ToTable("Servers_StarVariables", (string)null); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Allocation", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Node", "Node") - .WithMany("Allocations") - .HasForeignKey("NodeId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Server", "Server") - .WithMany("Allocations") - .HasForeignKey("ServerId"); - - b.Navigation("Node"); - - b.Navigation("Server"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Server", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Node", "Node") - .WithMany("Servers") - .HasForeignKey("NodeId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Star", "Star") - .WithMany() - .HasForeignKey("StarId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Node"); - - b.Navigation("Star"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerBackup", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Server", null) - .WithMany("Backups") - .HasForeignKey("ServerId"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerVariable", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Server", "Server") - .WithMany("Variables") - .HasForeignKey("ServerId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Server"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarDockerImage", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Star", "Star") - .WithMany("DockerImages") - .HasForeignKey("StarId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Star"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarVariable", b => - { - b.HasOne("MoonlightServers.ApiServer.Database.Entities.Star", "Star") - .WithMany("Variables") - .HasForeignKey("StarId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Star"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Node", b => - { - b.Navigation("Allocations"); - - b.Navigation("Servers"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Server", b => - { - b.Navigation("Allocations"); - - b.Navigation("Backups"); - - b.Navigation("Variables"); - }); - - modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Star", b => - { - b.Navigation("DockerImages"); - - b.Navigation("Variables"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/MoonlightServers.ApiServer/Database/Migrations/20250301142415_AddedTokenIdField.cs b/MoonlightServers.ApiServer/Database/Migrations/20250301142415_AddedTokenIdField.cs deleted file mode 100644 index b802de4..0000000 --- a/MoonlightServers.ApiServer/Database/Migrations/20250301142415_AddedTokenIdField.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace MoonlightServers.ApiServer.Database.Migrations -{ - /// - public partial class AddedTokenIdField : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AddColumn( - name: "TokenId", - table: "Servers_Nodes", - type: "text", - nullable: false, - defaultValue: ""); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropColumn( - name: "TokenId", - table: "Servers_Nodes"); - } - } -} diff --git a/MoonlightServers.ApiServer/Database/Migrations/20250606121013_AddedShares.cs b/MoonlightServers.ApiServer/Database/Migrations/20250606121013_AddedShares.cs deleted file mode 100644 index fe5dd2c..0000000 --- a/MoonlightServers.ApiServer/Database/Migrations/20250606121013_AddedShares.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -#nullable disable - -namespace MoonlightServers.ApiServer.Database.Migrations -{ - /// - public partial class AddedShares : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Servers_ServerShares", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - UserId = table.Column(type: "integer", nullable: false), - ServerId = table.Column(type: "integer", nullable: false), - CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), - UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false), - Content = table.Column(type: "jsonb", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Servers_ServerShares", x => x.Id); - table.ForeignKey( - name: "FK_Servers_ServerShares_Servers_Servers_ServerId", - column: x => x.ServerId, - principalTable: "Servers_Servers", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_Servers_ServerShares_ServerId", - table: "Servers_ServerShares", - column: "ServerId"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Servers_ServerShares"); - } - } -} diff --git a/MoonlightServers.ApiServer/Database/Migrations/20250606121013_AddedShares.Designer.cs b/MoonlightServers.ApiServer/Database/Migrations/20250922091731_RecreatedModelsInNewSchema.Designer.cs similarity index 92% rename from MoonlightServers.ApiServer/Database/Migrations/20250606121013_AddedShares.Designer.cs rename to MoonlightServers.ApiServer/Database/Migrations/20250922091731_RecreatedModelsInNewSchema.Designer.cs index 570c6b5..7ecbcb4 100644 --- a/MoonlightServers.ApiServer/Database/Migrations/20250606121013_AddedShares.Designer.cs +++ b/MoonlightServers.ApiServer/Database/Migrations/20250922091731_RecreatedModelsInNewSchema.Designer.cs @@ -12,15 +12,16 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MoonlightServers.ApiServer.Database.Migrations { [DbContext(typeof(ServersDataContext))] - [Migration("20250606121013_AddedShares")] - partial class AddedShares + [Migration("20250922091731_RecreatedModelsInNewSchema")] + partial class RecreatedModelsInNewSchema { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "9.0.5") + .HasDefaultSchema("servers") + .HasAnnotation("ProductVersion", "9.0.9") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); @@ -52,7 +53,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("ServerId"); - b.ToTable("Servers_Allocations", (string)null); + b.ToTable("Allocations", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Node", b => @@ -63,12 +64,6 @@ namespace MoonlightServers.ApiServer.Database.Migrations NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - b.Property("EnableDynamicFirewall") - .HasColumnType("boolean"); - - b.Property("EnableTransparentMode") - .HasColumnType("boolean"); - b.Property("Fqdn") .IsRequired() .HasColumnType("text"); @@ -96,7 +91,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasKey("Id"); - b.ToTable("Servers_Nodes", (string)null); + b.ToTable("Nodes", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Server", b => @@ -107,9 +102,6 @@ namespace MoonlightServers.ApiServer.Database.Migrations NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - b.Property("Bandwidth") - .HasColumnType("integer"); - b.Property("Cpu") .HasColumnType("integer"); @@ -138,16 +130,13 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.Property("StartupOverride") .HasColumnType("text"); - b.Property("UseVirtualDisk") - .HasColumnType("boolean"); - b.HasKey("Id"); b.HasIndex("NodeId"); b.HasIndex("StarId"); - b.ToTable("Servers_Servers", (string)null); + b.ToTable("Servers", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerBackup", b => @@ -180,7 +169,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("ServerId"); - b.ToTable("Servers_ServerBackups", (string)null); + b.ToTable("ServerBackups", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerShare", b => @@ -207,7 +196,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("ServerId"); - b.ToTable("Servers_ServerShares", (string)null); + b.ToTable("ServerShares", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerVariable", b => @@ -233,7 +222,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("ServerId"); - b.ToTable("Servers_ServerVariables", (string)null); + b.ToTable("ServerVariables", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Star", b => @@ -301,7 +290,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasKey("Id"); - b.ToTable("Servers_Stars", (string)null); + b.ToTable("Stars", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarDockerImage", b => @@ -330,7 +319,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("StarId"); - b.ToTable("Servers_StarDockerImages", (string)null); + b.ToTable("StarDockerImages", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarVariable", b => @@ -376,7 +365,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("StarId"); - b.ToTable("Servers_StarVariables", (string)null); + b.ToTable("StarVariables", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Allocation", b => @@ -437,14 +426,14 @@ namespace MoonlightServers.ApiServer.Database.Migrations b1.HasKey("ServerShareId"); - b1.ToTable("Servers_ServerShares"); + b1.ToTable("ServerShares", "servers"); b1.ToJson("Content"); b1.WithOwner() .HasForeignKey("ServerShareId"); - b1.OwnsMany("MoonlightServers.ApiServer.Models.ServerSharePermission", "Permissions", b2 => + b1.OwnsMany("MoonlightServers.ApiServer.Models.ServerShareContent+SharePermission", "Permissions", b2 => { b2.Property("ServerShareContentServerShareId") .HasColumnType("integer"); @@ -453,16 +442,16 @@ namespace MoonlightServers.ApiServer.Database.Migrations .ValueGeneratedOnAdd() .HasColumnType("integer"); - b2.Property("Name") + b2.Property("Identifier") .IsRequired() .HasColumnType("text"); - b2.Property("Type") + b2.Property("Level") .HasColumnType("integer"); b2.HasKey("ServerShareContentServerShareId", "__synthesizedOrdinal"); - b2.ToTable("Servers_ServerShares"); + b2.ToTable("ServerShares", "servers"); b2.WithOwner() .HasForeignKey("ServerShareContentServerShareId"); diff --git a/MoonlightServers.ApiServer/Database/Migrations/20250226210232_RecreatedMigrationsForPostgresql.cs b/MoonlightServers.ApiServer/Database/Migrations/20250922091731_RecreatedModelsInNewSchema.cs similarity index 64% rename from MoonlightServers.ApiServer/Database/Migrations/20250226210232_RecreatedMigrationsForPostgresql.cs rename to MoonlightServers.ApiServer/Database/Migrations/20250922091731_RecreatedModelsInNewSchema.cs index cf9b503..facb456 100644 --- a/MoonlightServers.ApiServer/Database/Migrations/20250226210232_RecreatedMigrationsForPostgresql.cs +++ b/MoonlightServers.ApiServer/Database/Migrations/20250922091731_RecreatedModelsInNewSchema.cs @@ -7,13 +7,17 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MoonlightServers.ApiServer.Database.Migrations { /// - public partial class RecreatedMigrationsForPostgresql : Migration + public partial class RecreatedModelsInNewSchema : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { + migrationBuilder.EnsureSchema( + name: "servers"); + migrationBuilder.CreateTable( - name: "Servers_Nodes", + name: "Nodes", + schema: "servers", columns: table => new { Id = table.Column(type: "integer", nullable: false) @@ -21,19 +25,19 @@ namespace MoonlightServers.ApiServer.Database.Migrations Name = table.Column(type: "text", nullable: false), Fqdn = table.Column(type: "text", nullable: false), Token = table.Column(type: "text", nullable: false), + TokenId = table.Column(type: "text", nullable: false), HttpPort = table.Column(type: "integer", nullable: false), FtpPort = table.Column(type: "integer", nullable: false), - UseSsl = table.Column(type: "boolean", nullable: false), - EnableTransparentMode = table.Column(type: "boolean", nullable: false), - EnableDynamicFirewall = table.Column(type: "boolean", nullable: false) + UseSsl = table.Column(type: "boolean", nullable: false) }, constraints: table => { - table.PrimaryKey("PK_Servers_Nodes", x => x.Id); + table.PrimaryKey("PK_Nodes", x => x.Id); }); migrationBuilder.CreateTable( - name: "Servers_Stars", + name: "Stars", + schema: "servers", columns: table => new { Id = table.Column(type: "integer", nullable: false) @@ -56,11 +60,12 @@ namespace MoonlightServers.ApiServer.Database.Migrations }, constraints: table => { - table.PrimaryKey("PK_Servers_Stars", x => x.Id); + table.PrimaryKey("PK_Stars", x => x.Id); }); migrationBuilder.CreateTable( - name: "Servers_Servers", + name: "Servers", + schema: "servers", columns: table => new { Id = table.Column(type: "integer", nullable: false) @@ -73,29 +78,30 @@ namespace MoonlightServers.ApiServer.Database.Migrations DockerImageIndex = table.Column(type: "integer", nullable: false), Cpu = table.Column(type: "integer", nullable: false), Memory = table.Column(type: "integer", nullable: false), - Disk = table.Column(type: "integer", nullable: false), - UseVirtualDisk = table.Column(type: "boolean", nullable: false), - Bandwidth = table.Column(type: "integer", nullable: false) + Disk = table.Column(type: "integer", nullable: false) }, constraints: table => { - table.PrimaryKey("PK_Servers_Servers", x => x.Id); + table.PrimaryKey("PK_Servers", x => x.Id); table.ForeignKey( - name: "FK_Servers_Servers_Servers_Nodes_NodeId", + name: "FK_Servers_Nodes_NodeId", column: x => x.NodeId, - principalTable: "Servers_Nodes", + principalSchema: "servers", + principalTable: "Nodes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( - name: "FK_Servers_Servers_Servers_Stars_StarId", + name: "FK_Servers_Stars_StarId", column: x => x.StarId, - principalTable: "Servers_Stars", + principalSchema: "servers", + principalTable: "Stars", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( - name: "Servers_StarDockerImages", + name: "StarDockerImages", + schema: "servers", columns: table => new { Id = table.Column(type: "integer", nullable: false) @@ -107,17 +113,19 @@ namespace MoonlightServers.ApiServer.Database.Migrations }, constraints: table => { - table.PrimaryKey("PK_Servers_StarDockerImages", x => x.Id); + table.PrimaryKey("PK_StarDockerImages", x => x.Id); table.ForeignKey( - name: "FK_Servers_StarDockerImages_Servers_Stars_StarId", + name: "FK_StarDockerImages_Stars_StarId", column: x => x.StarId, - principalTable: "Servers_Stars", + principalSchema: "servers", + principalTable: "Stars", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( - name: "Servers_StarVariables", + name: "StarVariables", + schema: "servers", columns: table => new { Id = table.Column(type: "integer", nullable: false) @@ -134,17 +142,19 @@ namespace MoonlightServers.ApiServer.Database.Migrations }, constraints: table => { - table.PrimaryKey("PK_Servers_StarVariables", x => x.Id); + table.PrimaryKey("PK_StarVariables", x => x.Id); table.ForeignKey( - name: "FK_Servers_StarVariables_Servers_Stars_StarId", + name: "FK_StarVariables_Stars_StarId", column: x => x.StarId, - principalTable: "Servers_Stars", + principalSchema: "servers", + principalTable: "Stars", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( - name: "Servers_Allocations", + name: "Allocations", + schema: "servers", columns: table => new { Id = table.Column(type: "integer", nullable: false) @@ -156,22 +166,25 @@ namespace MoonlightServers.ApiServer.Database.Migrations }, constraints: table => { - table.PrimaryKey("PK_Servers_Allocations", x => x.Id); + table.PrimaryKey("PK_Allocations", x => x.Id); table.ForeignKey( - name: "FK_Servers_Allocations_Servers_Nodes_NodeId", + name: "FK_Allocations_Nodes_NodeId", column: x => x.NodeId, - principalTable: "Servers_Nodes", + principalSchema: "servers", + principalTable: "Nodes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( - name: "FK_Servers_Allocations_Servers_Servers_ServerId", + name: "FK_Allocations_Servers_ServerId", column: x => x.ServerId, - principalTable: "Servers_Servers", + principalSchema: "servers", + principalTable: "Servers", principalColumn: "Id"); }); migrationBuilder.CreateTable( - name: "Servers_ServerBackups", + name: "ServerBackups", + schema: "servers", columns: table => new { Id = table.Column(type: "integer", nullable: false) @@ -185,16 +198,43 @@ namespace MoonlightServers.ApiServer.Database.Migrations }, constraints: table => { - table.PrimaryKey("PK_Servers_ServerBackups", x => x.Id); + table.PrimaryKey("PK_ServerBackups", x => x.Id); table.ForeignKey( - name: "FK_Servers_ServerBackups_Servers_Servers_ServerId", + name: "FK_ServerBackups_Servers_ServerId", column: x => x.ServerId, - principalTable: "Servers_Servers", + principalSchema: "servers", + principalTable: "Servers", principalColumn: "Id"); }); migrationBuilder.CreateTable( - name: "Servers_ServerVariables", + name: "ServerShares", + schema: "servers", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + UserId = table.Column(type: "integer", nullable: false), + ServerId = table.Column(type: "integer", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false), + Content = table.Column(type: "jsonb", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ServerShares", x => x.Id); + table.ForeignKey( + name: "FK_ServerShares_Servers_ServerId", + column: x => x.ServerId, + principalSchema: "servers", + principalTable: "Servers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ServerVariables", + schema: "servers", columns: table => new { Id = table.Column(type: "integer", nullable: false) @@ -205,53 +245,68 @@ namespace MoonlightServers.ApiServer.Database.Migrations }, constraints: table => { - table.PrimaryKey("PK_Servers_ServerVariables", x => x.Id); + table.PrimaryKey("PK_ServerVariables", x => x.Id); table.ForeignKey( - name: "FK_Servers_ServerVariables_Servers_Servers_ServerId", + name: "FK_ServerVariables_Servers_ServerId", column: x => x.ServerId, - principalTable: "Servers_Servers", + principalSchema: "servers", + principalTable: "Servers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( - name: "IX_Servers_Allocations_NodeId", - table: "Servers_Allocations", + name: "IX_Allocations_NodeId", + schema: "servers", + table: "Allocations", column: "NodeId"); migrationBuilder.CreateIndex( - name: "IX_Servers_Allocations_ServerId", - table: "Servers_Allocations", + name: "IX_Allocations_ServerId", + schema: "servers", + table: "Allocations", column: "ServerId"); migrationBuilder.CreateIndex( - name: "IX_Servers_ServerBackups_ServerId", - table: "Servers_ServerBackups", + name: "IX_ServerBackups_ServerId", + schema: "servers", + table: "ServerBackups", column: "ServerId"); migrationBuilder.CreateIndex( - name: "IX_Servers_Servers_NodeId", - table: "Servers_Servers", + name: "IX_Servers_NodeId", + schema: "servers", + table: "Servers", column: "NodeId"); migrationBuilder.CreateIndex( - name: "IX_Servers_Servers_StarId", - table: "Servers_Servers", + name: "IX_Servers_StarId", + schema: "servers", + table: "Servers", column: "StarId"); migrationBuilder.CreateIndex( - name: "IX_Servers_ServerVariables_ServerId", - table: "Servers_ServerVariables", + name: "IX_ServerShares_ServerId", + schema: "servers", + table: "ServerShares", column: "ServerId"); migrationBuilder.CreateIndex( - name: "IX_Servers_StarDockerImages_StarId", - table: "Servers_StarDockerImages", + name: "IX_ServerVariables_ServerId", + schema: "servers", + table: "ServerVariables", + column: "ServerId"); + + migrationBuilder.CreateIndex( + name: "IX_StarDockerImages_StarId", + schema: "servers", + table: "StarDockerImages", column: "StarId"); migrationBuilder.CreateIndex( - name: "IX_Servers_StarVariables_StarId", - table: "Servers_StarVariables", + name: "IX_StarVariables_StarId", + schema: "servers", + table: "StarVariables", column: "StarId"); } @@ -259,28 +314,40 @@ namespace MoonlightServers.ApiServer.Database.Migrations protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( - name: "Servers_Allocations"); + name: "Allocations", + schema: "servers"); migrationBuilder.DropTable( - name: "Servers_ServerBackups"); + name: "ServerBackups", + schema: "servers"); migrationBuilder.DropTable( - name: "Servers_ServerVariables"); + name: "ServerShares", + schema: "servers"); migrationBuilder.DropTable( - name: "Servers_StarDockerImages"); + name: "ServerVariables", + schema: "servers"); migrationBuilder.DropTable( - name: "Servers_StarVariables"); + name: "StarDockerImages", + schema: "servers"); migrationBuilder.DropTable( - name: "Servers_Servers"); + name: "StarVariables", + schema: "servers"); migrationBuilder.DropTable( - name: "Servers_Nodes"); + name: "Servers", + schema: "servers"); migrationBuilder.DropTable( - name: "Servers_Stars"); + name: "Nodes", + schema: "servers"); + + migrationBuilder.DropTable( + name: "Stars", + schema: "servers"); } } } diff --git a/MoonlightServers.ApiServer/Database/Migrations/ServersDataContextModelSnapshot.cs b/MoonlightServers.ApiServer/Database/Migrations/ServersDataContextModelSnapshot.cs index e136036..da45a02 100644 --- a/MoonlightServers.ApiServer/Database/Migrations/ServersDataContextModelSnapshot.cs +++ b/MoonlightServers.ApiServer/Database/Migrations/ServersDataContextModelSnapshot.cs @@ -17,7 +17,8 @@ namespace MoonlightServers.ApiServer.Database.Migrations { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "9.0.5") + .HasDefaultSchema("servers") + .HasAnnotation("ProductVersion", "9.0.9") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); @@ -49,7 +50,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("ServerId"); - b.ToTable("Servers_Allocations", (string)null); + b.ToTable("Allocations", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Node", b => @@ -60,12 +61,6 @@ namespace MoonlightServers.ApiServer.Database.Migrations NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - b.Property("EnableDynamicFirewall") - .HasColumnType("boolean"); - - b.Property("EnableTransparentMode") - .HasColumnType("boolean"); - b.Property("Fqdn") .IsRequired() .HasColumnType("text"); @@ -93,7 +88,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasKey("Id"); - b.ToTable("Servers_Nodes", (string)null); + b.ToTable("Nodes", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Server", b => @@ -104,9 +99,6 @@ namespace MoonlightServers.ApiServer.Database.Migrations NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - b.Property("Bandwidth") - .HasColumnType("integer"); - b.Property("Cpu") .HasColumnType("integer"); @@ -135,16 +127,13 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.Property("StartupOverride") .HasColumnType("text"); - b.Property("UseVirtualDisk") - .HasColumnType("boolean"); - b.HasKey("Id"); b.HasIndex("NodeId"); b.HasIndex("StarId"); - b.ToTable("Servers_Servers", (string)null); + b.ToTable("Servers", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerBackup", b => @@ -177,7 +166,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("ServerId"); - b.ToTable("Servers_ServerBackups", (string)null); + b.ToTable("ServerBackups", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerShare", b => @@ -204,7 +193,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("ServerId"); - b.ToTable("Servers_ServerShares", (string)null); + b.ToTable("ServerShares", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.ServerVariable", b => @@ -230,7 +219,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("ServerId"); - b.ToTable("Servers_ServerVariables", (string)null); + b.ToTable("ServerVariables", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Star", b => @@ -298,7 +287,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasKey("Id"); - b.ToTable("Servers_Stars", (string)null); + b.ToTable("Stars", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarDockerImage", b => @@ -327,7 +316,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("StarId"); - b.ToTable("Servers_StarDockerImages", (string)null); + b.ToTable("StarDockerImages", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.StarVariable", b => @@ -373,7 +362,7 @@ namespace MoonlightServers.ApiServer.Database.Migrations b.HasIndex("StarId"); - b.ToTable("Servers_StarVariables", (string)null); + b.ToTable("StarVariables", "servers"); }); modelBuilder.Entity("MoonlightServers.ApiServer.Database.Entities.Allocation", b => @@ -434,14 +423,14 @@ namespace MoonlightServers.ApiServer.Database.Migrations b1.HasKey("ServerShareId"); - b1.ToTable("Servers_ServerShares"); + b1.ToTable("ServerShares", "servers"); b1.ToJson("Content"); b1.WithOwner() .HasForeignKey("ServerShareId"); - b1.OwnsMany("MoonlightServers.ApiServer.Models.ServerSharePermission", "Permissions", b2 => + b1.OwnsMany("MoonlightServers.ApiServer.Models.ServerShareContent+SharePermission", "Permissions", b2 => { b2.Property("ServerShareContentServerShareId") .HasColumnType("integer"); @@ -450,16 +439,16 @@ namespace MoonlightServers.ApiServer.Database.Migrations .ValueGeneratedOnAdd() .HasColumnType("integer"); - b2.Property("Name") + b2.Property("Identifier") .IsRequired() .HasColumnType("text"); - b2.Property("Type") + b2.Property("Level") .HasColumnType("integer"); b2.HasKey("ServerShareContentServerShareId", "__synthesizedOrdinal"); - b2.ToTable("Servers_ServerShares"); + b2.ToTable("ServerShares", "servers"); b2.WithOwner() .HasForeignKey("ServerShareContentServerShareId"); diff --git a/MoonlightServers.ApiServer/Database/ServersDataContext.cs b/MoonlightServers.ApiServer/Database/ServersDataContext.cs index 498852f..696e9e1 100644 --- a/MoonlightServers.ApiServer/Database/ServersDataContext.cs +++ b/MoonlightServers.ApiServer/Database/ServersDataContext.cs @@ -1,17 +1,12 @@ -using System.Text.Json; using Microsoft.EntityFrameworkCore; -using MoonCore.Extended.SingleDb; using Moonlight.ApiServer.Configuration; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Models; -using MoonlightServers.Shared.Models; namespace MoonlightServers.ApiServer.Database; -public class ServersDataContext : DatabaseContext +public class ServersDataContext : DbContext { - public override string Prefix { get; } = "Servers"; - public DbSet Allocations { get; set; } public DbSet Nodes { get; set; } public DbSet Servers { get; set; } @@ -22,20 +17,37 @@ public class ServersDataContext : DatabaseContext public DbSet StarDockerImages { get; set; } public DbSet StarVariables { get; set; } + private readonly AppConfiguration Configuration; + private readonly string Schema = "servers"; + public ServersDataContext(AppConfiguration configuration) { - Options = new() + Configuration = configuration; + } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if(optionsBuilder.IsConfigured) + return; + + var database = Configuration.Database; + + var connectionString = $"Host={database.Host};" + + $"Port={database.Port};" + + $"Database={database.Database};" + + $"Username={database.Username};" + + $"Password={database.Password}"; + + optionsBuilder.UseNpgsql(connectionString, builder => { - Host = configuration.Database.Host, - Port = configuration.Database.Port, - Username = configuration.Database.Username, - Password = configuration.Database.Password, - Database = configuration.Database.Database - }; + builder.MigrationsHistoryTable("MigrationsHistory", Schema); + }); } protected override void OnModelCreating(ModelBuilder modelBuilder) { + modelBuilder.Model.SetDefaultSchema(Schema); + base.OnModelCreating(modelBuilder); #region Shares diff --git a/MoonlightServers.ApiServer/Extensions/ServerStateExtensions.cs b/MoonlightServers.ApiServer/Extensions/ServerStateExtensions.cs index 71b000f..ea2b732 100644 --- a/MoonlightServers.ApiServer/Extensions/ServerStateExtensions.cs +++ b/MoonlightServers.ApiServer/Extensions/ServerStateExtensions.cs @@ -1,5 +1,3 @@ -using MoonlightServers.DaemonShared.Enums; -using MoonlightServers.Shared.Enums; using ServerState = MoonlightServers.Shared.Enums.ServerState; namespace MoonlightServers.ApiServer.Extensions; diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodeAllocationsController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodeAllocationsController.cs index 098ece0..15f3287 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodeAllocationsController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodeAllocationsController.cs @@ -1,9 +1,7 @@ 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; @@ -30,38 +28,39 @@ public class NodeAllocationsController : Controller [HttpGet] [Authorize(Policy = "permissions:admin.servers.nodes.get")] - public async Task>> Get( + public async Task>> GetAsync( [FromRoute] int nodeId, - [FromQuery] PagedOptions options + [FromQuery] int startIndex, + [FromQuery] int count ) { - var count = await AllocationRepository + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + + var totalCount = await AllocationRepository .Get() .CountAsync(x => x.Node.Id == nodeId); var allocations = await AllocationRepository .Get() .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .Where(x => x.Node.Id == nodeId) .AsNoTracking() .ProjectToAdminResponse() .ToArrayAsync(); - return new PagedData() + return new CountedData() { Items = allocations, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("{id:int}")] [Authorize(Policy = "permissions:admin.servers.nodes.get")] - public async Task> GetSingle([FromRoute] int nodeId, [FromRoute] int id) + public async Task> GetSingleAsync([FromRoute] int nodeId, [FromRoute] int id) { var allocation = await AllocationRepository .Get() @@ -78,7 +77,7 @@ public class NodeAllocationsController : Controller [HttpPost] [Authorize(Policy = "permissions:admin.servers.nodes.create")] - public async Task> Create( + public async Task> CreateAsync( [FromRoute] int nodeId, [FromBody] CreateNodeAllocationRequest request ) @@ -92,13 +91,13 @@ public class NodeAllocationsController : Controller var allocation = AllocationMapper.ToAllocation(request); - var finalAllocation = await AllocationRepository.Add(allocation); + var finalAllocation = await AllocationRepository.AddAsync(allocation); return AllocationMapper.ToNodeAllocation(finalAllocation); } [HttpPatch("{id:int}")] - public async Task> Update( + public async Task> UpdateAsync( [FromRoute] int nodeId, [FromRoute] int id, [FromBody] UpdateNodeAllocationRequest request @@ -113,13 +112,13 @@ public class NodeAllocationsController : Controller return Problem("No allocation with that id found", statusCode: 404); AllocationMapper.Merge(request, allocation); - await AllocationRepository.Update(allocation); + await AllocationRepository.UpdateAsync(allocation); return AllocationMapper.ToNodeAllocation(allocation); } [HttpDelete("{id:int}")] - public async Task Delete([FromRoute] int nodeId, [FromRoute] int id) + public async Task DeleteAsync([FromRoute] int nodeId, [FromRoute] int id) { var allocation = await AllocationRepository .Get() @@ -129,12 +128,12 @@ public class NodeAllocationsController : Controller if (allocation == null) return Problem("No allocation with that id found", statusCode: 404); - await AllocationRepository.Remove(allocation); + await AllocationRepository.RemoveAsync(allocation); return NoContent(); } [HttpPost("range")] - public async Task CreateRange( + public async Task CreateRangeAsync( [FromRoute] int nodeId, [FromBody] CreateNodeAllocationRangeRequest request ) @@ -179,58 +178,60 @@ public class NodeAllocationsController : Controller }) .ToArray(); - await AllocationRepository.RunTransaction(async set => { await set.AddRangeAsync(allocations); }); + await AllocationRepository.RunTransactionAsync(async set => { await set.AddRangeAsync(allocations); }); return NoContent(); } [HttpDelete("all")] - public async Task DeleteAll([FromRoute] int nodeId) + public async Task DeleteAllAsync([FromRoute] int nodeId) { var allocations = AllocationRepository .Get() .Where(x => x.Node.Id == nodeId) .ToArray(); - await AllocationRepository.RunTransaction(set => { set.RemoveRange(allocations); }); + await AllocationRepository.RunTransactionAsync(set => { set.RemoveRange(allocations); }); return NoContent(); } [HttpGet("free")] [Authorize(Policy = "permissions:admin.servers.nodes.get")] - public async Task> GetFree( + public async Task>> GetFreeAsync( [FromRoute] int nodeId, - [FromQuery] PagedOptions options, + [FromQuery] int startIndex, + [FromQuery] int count, [FromQuery] int serverId = -1 ) { + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + var node = NodeRepository .Get() .FirstOrDefault(x => x.Id == nodeId); if (node == 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); var freeAllocationsQuery = AllocationRepository .Get() + .OrderBy(x => x.Id) .Where(x => x.Node.Id == node.Id) .Where(x => x.Server == null || x.Server.Id == serverId); - var count = await freeAllocationsQuery.CountAsync(); + var totalCount = await freeAllocationsQuery.CountAsync(); var allocations = await freeAllocationsQuery - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .AsNoTracking() .ProjectToAdminResponse() .ToArrayAsync(); - return new PagedData() + return new CountedData() { Items = allocations, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodeStatusController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodeStatusController.cs index 74f55a4..2a1130b 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodeStatusController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodeStatusController.cs @@ -1,6 +1,5 @@ using System.Diagnostics; using Microsoft.AspNetCore.Mvc; -using MoonCore.Exceptions; using MoonCore.Extended.Abstractions; using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; @@ -25,9 +24,9 @@ public class NodeStatusController : Controller [HttpGet("{nodeId:int}/system/status")] [Authorize(Policy = "permissions:admin.servers.nodes.status")] - public async Task> GetStatus([FromRoute] int nodeId) + public async Task> GetStatusAsync([FromRoute] int nodeId) { - var node = await GetNode(nodeId); + var node = await GetNodeAsync(nodeId); if (node.Value == null) return node.Result ?? Problem("Unable to retrieve node"); @@ -39,7 +38,7 @@ public class NodeStatusController : Controller try { - var statusResponse = await NodeService.GetSystemStatus(node.Value); + var statusResponse = await NodeService.GetSystemStatusAsync(node.Value); sw.Stop(); @@ -69,7 +68,7 @@ public class NodeStatusController : Controller return response; } - private async Task> GetNode(int nodeId) + private async Task> GetNodeAsync(int nodeId) { var result = await NodeRepository .Get() diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodesController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodesController.cs index b17b958..d80d6b4 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodesController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/NodesController.cs @@ -1,10 +1,7 @@ -using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; 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; @@ -27,32 +24,35 @@ public class NodesController : Controller [HttpGet] [Authorize(Policy = "permissions:admin.servers.nodes.get")] - public async Task> Get([FromQuery] PagedOptions options) + public async Task>> GetAsync( + [FromQuery] int startIndex, + [FromQuery] int count + ) { - var count = await NodeRepository.Get().CountAsync(); + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + + var totalCount = await NodeRepository.Get().CountAsync(); var items = await NodeRepository .Get() .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .AsNoTracking() .ProjectToAdminResponse() .ToArrayAsync(); - return new PagedData() + return new CountedData() { Items = items, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("{id:int}")] [Authorize(Policy = "permissions:admin.servers.nodes.get")] - public async Task> GetSingle([FromRoute] int id) + public async Task> GetSingleAsync([FromRoute] int id) { var node = await NodeRepository .Get() @@ -62,27 +62,27 @@ public class NodesController : Controller if (node == null) return Problem("No node with this id found", statusCode: 404); - + return node; } [HttpPost] [Authorize(Policy = "permissions:admin.servers.nodes.create")] - public async Task> Create([FromBody] CreateNodeRequest request) + public async Task> CreateAsync([FromBody] CreateNodeRequest request) { var node = NodeMapper.ToNode(request); node.TokenId = Formatter.GenerateString(6); node.Token = Formatter.GenerateString(32); - var finalNode = await NodeRepository.Add(node); + var finalNode = await NodeRepository.AddAsync(node); return NodeMapper.ToAdminNodeResponse(finalNode); } [HttpPatch("{id:int}")] [Authorize(Policy = "permissions:admin.servers.nodes.update")] - public async Task> Update([FromRoute] int id, [FromBody] UpdateNodeRequest request) + public async Task> UpdateAsync([FromRoute] int id, [FromBody] UpdateNodeRequest request) { var node = await NodeRepository .Get() @@ -92,14 +92,14 @@ public class NodesController : Controller return Problem("No node with this id found", statusCode: 404); NodeMapper.Merge(request, node); - await NodeRepository.Update(node); + await NodeRepository.UpdateAsync(node); return NodeMapper.ToAdminNodeResponse(node); } [HttpDelete("{id:int}")] [Authorize(Policy = "permissions:admin.servers.nodes.delete")] - public async Task Delete([FromRoute] int id) + public async Task DeleteAsync([FromRoute] int id) { var node = await NodeRepository .Get() @@ -107,8 +107,8 @@ public class NodesController : Controller if (node == null) return Problem("No node with this id found", statusCode: 404); - - await NodeRepository.Remove(node); + + await NodeRepository.RemoveAsync(node); return Ok(); } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/StatisticsController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/StatisticsController.cs index 18d869f..78f2467 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/StatisticsController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Nodes/StatisticsController.cs @@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using MoonCore.Exceptions; using MoonCore.Extended.Abstractions; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Services; @@ -27,14 +26,14 @@ 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> Get([FromRoute] int nodeId) + public async Task> GetAsync([FromRoute] int nodeId) { - var node = await GetNode(nodeId); + var node = await GetNodeAsync(nodeId); if (node.Value == null) return node.Result ?? Problem("Unable to retrieve node"); - var statistics = await NodeService.GetStatistics(node.Value); + var statistics = await NodeService.GetStatisticsAsync(node.Value); return new StatisticsResponse() { @@ -66,14 +65,14 @@ public class StatisticsController : Controller } [HttpGet("docker")] - public async Task> GetDocker([FromRoute] int nodeId) + public async Task> GetDockerAsync([FromRoute] int nodeId) { - var node = await GetNode(nodeId); + var node = await GetNodeAsync(nodeId); if (node.Value == null) return node.Result ?? Problem("Unable to retrieve node"); - var statistics = await NodeService.GetDockerStatistics(node.Value); + var statistics = await NodeService.GetDockerStatisticsAsync(node.Value); return new DockerStatisticsResponse() { @@ -87,7 +86,7 @@ public class StatisticsController : Controller }; } - private async Task> GetNode(int nodeId) + private async Task> GetNodeAsync(int nodeId) { var result = await NodeRepository .Get() diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Servers/ServerVariablesController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Servers/ServerVariablesController.cs index f91ea79..1bd0f40 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Servers/ServerVariablesController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Servers/ServerVariablesController.cs @@ -1,10 +1,7 @@ -using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; 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; @@ -30,11 +27,15 @@ public class ServerVariablesController : Controller [HttpGet("{serverId:int}/variables")] [Authorize(Policy = "permissions:admin.servers.read")] - public async Task>> Get( + public async Task>> GetAsync( [FromRoute] int serverId, - [FromQuery] PagedOptions options + [FromQuery] int startIndex, + [FromQuery] int count ) { + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + var serverExists = await ServerRepository .Get() .AnyAsync(x => x.Id == serverId); @@ -46,23 +47,20 @@ public class ServerVariablesController : Controller .Get() .Where(x => x.Server.Id == serverId); - var count = await query.CountAsync(); + var totalCount = await query.CountAsync(); var variables = await query .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .AsNoTracking() .ProjectToAdminResponse() .ToArrayAsync(); - return new PagedData() + return new CountedData() { Items = variables, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Servers/ServersController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Servers/ServersController.cs index b3c8388..b4a3c7c 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Servers/ServersController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Servers/ServersController.cs @@ -1,13 +1,8 @@ -using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Authorization; 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; using MoonlightServers.ApiServer.Database.Entities; @@ -54,9 +49,15 @@ public class ServersController : Controller [HttpGet] [Authorize(Policy = "permissions:admin.servers.read")] - public async Task>> Get([FromQuery] PagedOptions options) + public async Task>> GetAsync( + [FromQuery] int startIndex, + [FromQuery] int count + ) { - var count = await ServerRepository.Get().CountAsync(); + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + + var totalCount = await ServerRepository.Get().CountAsync(); var servers = await ServerRepository .Get() @@ -65,25 +66,22 @@ public class ServersController : Controller .Include(x => x.Variables) .Include(x => x.Star) .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .AsNoTracking() .ProjectToAdminResponse() .ToArrayAsync(); - return new PagedData() + return new CountedData() { Items = servers, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("{id:int}")] [Authorize(Policy = "permissions:admin.servers.read")] - public async Task> GetSingle([FromRoute] int id) + public async Task> GetSingleAsync([FromRoute] int id) { var server = await ServerRepository .Get() @@ -104,7 +102,7 @@ public class ServersController : Controller [HttpPost] [Authorize(Policy = "permissions:admin.servers.write")] - public async Task> Create([FromBody] CreateServerRequest request) + public async Task> CreateAsync([FromBody] CreateServerRequest request) { // Check if owner user exist if (UserRepository.Get().All(x => x.Id != request.OwnerId)) @@ -192,11 +190,11 @@ public class ServersController : Controller server.Node = node; server.Star = star; - var finalServer = await ServerRepository.Add(server); + var finalServer = await ServerRepository.AddAsync(server); try { - await ServerService.Sync(finalServer); + await ServerService.SyncAsync(finalServer); } catch (Exception e) { @@ -204,7 +202,7 @@ public class ServersController : Controller // 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 doesn't exist on the node - await ServerRepository.Remove(finalServer); + await ServerRepository.RemoveAsync(finalServer); throw; } @@ -214,7 +212,10 @@ public class ServersController : Controller [HttpPatch("{id:int}")] [Authorize(Policy = "permissions:admin.servers.write")] - public async Task> Update([FromRoute] int id, [FromBody] UpdateServerRequest request) + public async Task> UpdateAsync( + [FromRoute] int id, + [FromBody] UpdateServerRequest request + ) { //TODO: Handle shrinking virtual disk @@ -277,16 +278,16 @@ public class ServersController : Controller serverVar.Value = variable.Value; } - await ServerRepository.Update(server); + await ServerRepository.UpdateAsync(server); // Notify the node about the changes - await ServerService.Sync(server); + await ServerService.SyncAsync(server); return ServerMapper.ToAdminServerResponse(server); } [HttpDelete("{id:int}")] - public async Task Delete([FromRoute] int id, [FromQuery] bool force = false) + public async Task DeleteAsync([FromRoute] int id, [FromQuery] bool force = false) { var server = await ServerRepository .Get() @@ -308,7 +309,7 @@ public class ServersController : Controller { // If the sync fails on the node and we aren't forcing the deletion, // we don't want to delete it from the database yet - await ServerService.SyncDelete(server); + await ServerService.SyncDeleteAsync(server); } catch (Exception e) { @@ -323,7 +324,7 @@ public class ServersController : Controller throw; } - await ServerRepository.Remove(server); + await ServerRepository.RemoveAsync(server); return NoContent(); } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarDockerImagesController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarDockerImagesController.cs index 06440a3..a27f8e4 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarDockerImagesController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarDockerImagesController.cs @@ -1,12 +1,7 @@ -using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -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; using MoonlightServers.ApiServer.Mappers; @@ -33,9 +28,10 @@ public class StarDockerImagesController : Controller [HttpGet] [Authorize(Policy = "permissions:admin.servers.stars.get")] - public async Task>> Get( + public async Task>> GetAsync( [FromRoute] int starId, - [FromQuery] PagedOptions options + [FromQuery] int startIndex, + [FromQuery] int count ) { var starExists = StarRepository @@ -49,29 +45,26 @@ public class StarDockerImagesController : Controller .Get() .Where(x => x.Star.Id == starId); - var count = await query.CountAsync(); + var totalCount = await query.CountAsync(); var dockerImages = await query .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .AsNoTracking() .ProjectToAdminResponse() .ToArrayAsync(); - return new PagedData() + return new CountedData() { Items = dockerImages, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.read")] - public async Task> GetSingle([FromRoute] int starId, [FromRoute] int id) + public async Task> GetSingleAsync([FromRoute] int starId, [FromRoute] int id) { var starExists = StarRepository .Get() @@ -94,7 +87,7 @@ public class StarDockerImagesController : Controller [HttpPost] [Authorize(Policy = "permissions:admin.servers.stars.write")] - public async Task> Create( + public async Task> CreateAsync( [FromRoute] int starId, [FromBody] CreateStarDockerImageRequest request ) @@ -109,14 +102,14 @@ public class StarDockerImagesController : Controller var dockerImage = DockerImageMapper.ToDockerImage(request); dockerImage.Star = star; - var finalDockerImage = await DockerImageRepository.Add(dockerImage); + var finalDockerImage = await DockerImageRepository.AddAsync(dockerImage); return DockerImageMapper.ToAdminResponse(finalDockerImage); } [HttpPatch("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.write")] - public async Task> Update( + public async Task> UpdateAsync( [FromRoute] int starId, [FromRoute] int id, [FromBody] UpdateStarDockerImageRequest request @@ -137,14 +130,14 @@ public class StarDockerImagesController : Controller return Problem("No star docker image with this id found", statusCode: 404); DockerImageMapper.Merge(request, dockerImage); - await DockerImageRepository.Update(dockerImage); + await DockerImageRepository.UpdateAsync(dockerImage); return DockerImageMapper.ToAdminResponse(dockerImage); } [HttpDelete("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.write")] - public async Task Delete([FromRoute] int starId, [FromRoute] int id) + public async Task DeleteAsync([FromRoute] int starId, [FromRoute] int id) { var starExists = StarRepository .Get() @@ -160,7 +153,7 @@ public class StarDockerImagesController : Controller if (dockerImage == null) return Problem("No star docker image with this id found", statusCode: 404); - await DockerImageRepository.Remove(dockerImage); + await DockerImageRepository.RemoveAsync(dockerImage); return NoContent(); } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarImportExportController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarImportExportController.cs index e64c458..53102f5 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarImportExportController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarImportExportController.cs @@ -1,9 +1,7 @@ using System.Text; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; using MoonCore.Exceptions; -using MoonCore.Helpers; using MoonlightServers.ApiServer.Mappers; using MoonlightServers.ApiServer.Services; using MoonlightServers.Shared.Http.Responses.Admin.Stars; @@ -23,15 +21,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 ExportAsync([FromRoute] int starId) { - var exportedStar = await ImportExportService.Export(starId); + var exportedStar = await ImportExportService.ExportAsync(starId); return Content(exportedStar, "application/json"); } [HttpPost("import")] [Authorize(Policy = "permissions:admin.servers.stars.create")] - public async Task Import() + public async Task ImportAsync() { if (Request.Form.Files.Count == 0) throw new HttpApiException("No file to import provided", 400); @@ -44,7 +42,7 @@ public class StarImportExportController : Controller using var sr = new StreamReader(stream, Encoding.UTF8); var content = await sr.ReadToEndAsync(); - var star = await ImportExportService.Import(content); + var star = await ImportExportService.ImportAsync(content); return StarMapper.ToAdminResponse(star); } diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarVariablesController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarVariablesController.cs index f8815e2..bb20b34 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarVariablesController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarVariablesController.cs @@ -1,10 +1,8 @@ -using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; 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; @@ -30,11 +28,15 @@ public class StarVariablesController : Controller [HttpGet] [Authorize(Policy = "permissions:admin.servers.stars.get")] - public async Task>> Get( + public async Task>> GetAsync( [FromRoute] int starId, - [FromQuery] PagedOptions options + [FromQuery] int startIndex, + [FromQuery] int count ) { + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + var starExists = StarRepository .Get() .Any(x => x.Id == starId); @@ -46,29 +48,26 @@ public class StarVariablesController : Controller .Get() .Where(x => x.Star.Id == starId); - var count = await query.CountAsync(); + var totalCount = await query.CountAsync(); var variables = await query .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .AsNoTracking() .ProjectToAdminResponse() .ToArrayAsync(); - return new PagedData() + return new CountedData() { Items = variables, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.get")] - public async Task GetSingle( + public async Task GetSingleAsync( [FromRoute] int starId, [FromRoute] int id ) @@ -92,7 +91,7 @@ public class StarVariablesController : Controller [HttpPost("")] [Authorize(Policy = "permissions:admin.servers.stars.create")] - public async Task Create([FromRoute] int starId, + public async Task CreateAsync([FromRoute] int starId, [FromBody] CreateStarVariableRequest request) { var star = StarRepository @@ -105,14 +104,14 @@ public class StarVariablesController : Controller var starVariable = StarVariableMapper.ToStarVariable(request); starVariable.Star = star; - await VariableRepository.Add(starVariable); + await VariableRepository.AddAsync(starVariable); return StarVariableMapper.ToAdminResponse(starVariable); } [HttpPatch("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.update")] - public async Task Update( + public async Task UpdateAsync( [FromRoute] int starId, [FromRoute] int id, [FromBody] UpdateStarVariableRequest request @@ -133,14 +132,14 @@ public class StarVariablesController : Controller throw new HttpApiException("No variable with this id found", 404); StarVariableMapper.Merge(request, starVariable); - await VariableRepository.Update(starVariable); + await VariableRepository.UpdateAsync(starVariable); return StarVariableMapper.ToAdminResponse(starVariable); } [HttpDelete("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.delete")] - public async Task Delete([FromRoute] int starId, [FromRoute] int id) + public async Task DeleteAsync([FromRoute] int starId, [FromRoute] int id) { var starExists = StarRepository .Get() @@ -156,6 +155,6 @@ public class StarVariablesController : Controller if (starVariable == null) throw new HttpApiException("No variable with this id found", 404); - await VariableRepository.Remove(starVariable); + await VariableRepository.RemoveAsync(starVariable); } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarsController.cs b/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarsController.cs index d72f143..54f1afa 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarsController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Admin/Stars/StarsController.cs @@ -1,10 +1,7 @@ -using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; 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; @@ -26,32 +23,35 @@ public class StarsController : Controller [HttpGet] [Authorize(Policy = "permissions:admin.servers.stars.read")] - public async Task>> Get([FromQuery] PagedOptions options) + public async Task>> GetAsync( + [FromQuery] int startIndex, + [FromQuery] int count + ) { - var count = await StarRepository.Get().CountAsync(); + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + + var totalCount = await StarRepository.Get().CountAsync(); var stars = await StarRepository .Get() .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .AsNoTracking() .ProjectToAdminResponse() .ToArrayAsync(); - return new PagedData() + return new CountedData() { - CurrentPage = options.Page, Items = stars, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.read")] - public async Task> GetSingle([FromRoute] int id) + public async Task> GetSingleAsync([FromRoute] int id) { var star = await StarRepository .Get() @@ -67,7 +67,7 @@ public class StarsController : Controller [HttpPost] [Authorize(Policy = "permissions:admin.servers.stars.create")] - public async Task> Create([FromBody] CreateStarRequest request) + public async Task> CreateAsync([FromBody] CreateStarRequest request) { var star = StarMapper.ToStar(request); @@ -86,14 +86,14 @@ public class StarsController : Controller star.DefaultDockerImage = -1; star.ParseConfiguration = "[]"; - var finalStar = await StarRepository.Add(star); + var finalStar = await StarRepository.AddAsync(star); return StarMapper.ToAdminResponse(finalStar); } [HttpPatch("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.update")] - public async Task> Update( + public async Task> UpdateAsync( [FromRoute] int id, [FromBody] UpdateStarRequest request ) @@ -104,16 +104,16 @@ public class StarsController : Controller if (star == null) return Problem("No star with that id found", statusCode: 404); - + StarMapper.Merge(request, star); - await StarRepository.Update(star); - + await StarRepository.UpdateAsync(star); + return StarMapper.ToAdminResponse(star); } [HttpDelete("{id:int}")] [Authorize(Policy = "permissions:admin.servers.stars.delete")] - public async Task Delete([FromRoute] int id) + public async Task DeleteAsync([FromRoute] int id) { var star = await StarRepository .Get() @@ -121,8 +121,8 @@ public class StarsController : Controller if (star == null) return Problem("No star with that id found", statusCode: 404); - - await StarRepository.Remove(star); + + await StarRepository.RemoveAsync(star); return NoContent(); } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Http/Controllers/Client/FilesController.cs b/MoonlightServers.ApiServer/Http/Controllers/Client/FilesController.cs index 6132295..7211ac5 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Client/FilesController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Client/FilesController.cs @@ -1,7 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using MoonCore.Exceptions; using MoonCore.Extended.Abstractions; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Services; @@ -37,14 +36,14 @@ public class FilesController : Controller } [HttpGet("list")] - public async Task> List([FromRoute] int serverId, [FromQuery] string path) + public async Task> ListAsync([FromRoute] int serverId, [FromQuery] string path) { - var server = await GetServerById(serverId, ServerPermissionLevel.Read); + var server = await GetServerByIdAsync(serverId, ServerPermissionLevel.Read); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - var entries = await ServerFileSystemService.List(server.Value, path); + var entries = await ServerFileSystemService.ListAsync(server.Value, path); return entries.Select(x => new ServerFilesEntryResponse() { @@ -57,57 +56,57 @@ public class FilesController : Controller } [HttpPost("move")] - public async Task Move([FromRoute] int serverId, [FromQuery] string oldPath, [FromQuery] string newPath) + public async Task MoveAsync([FromRoute] int serverId, [FromQuery] string oldPath, [FromQuery] string newPath) { - var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var server = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerFileSystemService.Move(server.Value, oldPath, newPath); + await ServerFileSystemService.MoveAsync(server.Value, oldPath, newPath); return NoContent(); } [HttpDelete("delete")] - public async Task Delete([FromRoute] int serverId, [FromQuery] string path) + public async Task DeleteAsync([FromRoute] int serverId, [FromQuery] string path) { - var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var server = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerFileSystemService.Delete(server.Value, path); + await ServerFileSystemService.DeleteAsync(server.Value, path); return NoContent(); } [HttpPost("mkdir")] - public async Task Mkdir([FromRoute] int serverId, [FromQuery] string path) + public async Task MkdirAsync([FromRoute] int serverId, [FromQuery] string path) { - var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var server = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerFileSystemService.Mkdir(server.Value, path); + await ServerFileSystemService.MkdirAsync(server.Value, path); return NoContent(); } [HttpPost("touch")] - public async Task Touch([FromRoute] int serverId, [FromQuery] string path) + public async Task TouchAsync([FromRoute] int serverId, [FromQuery] string path) { - var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var server = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerFileSystemService.Mkdir(server.Value, path); + await ServerFileSystemService.MkdirAsync(server.Value, path); return NoContent(); } [HttpGet("upload")] - public async Task> Upload([FromRoute] int serverId) + public async Task> UploadAsync([FromRoute] int serverId) { - var serverResult = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var serverResult = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (serverResult.Value == null) return serverResult.Result ?? Problem("Unable to retrieve server"); @@ -137,9 +136,9 @@ public class FilesController : Controller } [HttpGet("download")] - public async Task> Download([FromRoute] int serverId, [FromQuery] string path) + public async Task> DownloadAsync([FromRoute] int serverId, [FromQuery] string path) { - var serverResult = await GetServerById(serverId, ServerPermissionLevel.Read); + var serverResult = await GetServerByIdAsync(serverId, ServerPermissionLevel.Read); if (serverResult.Value == null) return serverResult.Result ?? Problem("Unable to retrieve server"); @@ -170,9 +169,9 @@ public class FilesController : Controller } [HttpPost("compress")] - public async Task Compress([FromRoute] int serverId, [FromBody] ServerFilesCompressRequest request) + public async Task CompressAsync([FromRoute] int serverId, [FromBody] ServerFilesCompressRequest request) { - var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var server = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); @@ -180,14 +179,14 @@ public class FilesController : Controller if (!Enum.TryParse(request.Type, true, out CompressType type)) return Problem("Invalid compress type provided", statusCode: 400); - await ServerFileSystemService.Compress(server.Value, type, request.Items, request.Destination); + await ServerFileSystemService.CompressAsync(server.Value, type, request.Items, request.Destination); return Ok(); } [HttpPost("decompress")] - public async Task Decompress([FromRoute] int serverId, [FromBody] ServerFilesDecompressRequest request) + public async Task DecompressAsync([FromRoute] int serverId, [FromBody] ServerFilesDecompressRequest request) { - var server = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var server = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); @@ -195,11 +194,11 @@ public class FilesController : Controller if (!Enum.TryParse(request.Type, true, out CompressType type)) return Problem("Invalid decompress type provided", statusCode: 400); - await ServerFileSystemService.Decompress(server.Value, type, request.Path, request.Destination); + await ServerFileSystemService.DecompressAsync(server.Value, type, request.Path, request.Destination); return NoContent(); } - private async Task> GetServerById(int serverId, ServerPermissionLevel level) + private async Task> GetServerByIdAsync(int serverId, ServerPermissionLevel level) { var server = await ServerRepository .Get() @@ -209,7 +208,7 @@ public class FilesController : Controller if (server == null) return Problem("No server with this id found", statusCode: 404); - var authorizeResult = await AuthorizeService.Authorize( + var authorizeResult = await AuthorizeService.AuthorizeAsync( User, server, ServerPermissionConstants.Files, level diff --git a/MoonlightServers.ApiServer/Http/Controllers/Client/PowerController.cs b/MoonlightServers.ApiServer/Http/Controllers/Client/PowerController.cs index 11a15f6..9bf9ecb 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Client/PowerController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Client/PowerController.cs @@ -1,10 +1,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using MoonCore.Exceptions; using MoonCore.Extended.Abstractions; -using MoonCore.Helpers; -using Moonlight.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Services; using MoonlightServers.Shared.Constants; @@ -34,44 +31,44 @@ public class PowerController : Controller [HttpPost("start")] [Authorize] - public async Task Start([FromRoute] int serverId) + public async Task StartAsync([FromRoute] int serverId) { - var server = await GetServerById(serverId); + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerService.Start(server.Value); + await ServerService.StartAsync(server.Value); return NoContent(); } [HttpPost("stop")] [Authorize] - public async Task Stop([FromRoute] int serverId) + public async Task StopAsync([FromRoute] int serverId) { - var server = await GetServerById(serverId); + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerService.Stop(server.Value); + await ServerService.StopAsync(server.Value); return NoContent(); } [HttpPost("kill")] [Authorize] - public async Task Kill([FromRoute] int serverId) + public async Task KillAsync([FromRoute] int serverId) { - var server = await GetServerById(serverId); + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerService.Kill(server.Value); + await ServerService.KillAsync(server.Value); return NoContent(); } - private async Task> GetServerById(int serverId) + private async Task> GetServerByIdAsync(int serverId) { var server = await ServerRepository .Get() @@ -81,7 +78,7 @@ public class PowerController : Controller if (server == null) return Problem("No server with this id found", statusCode: 404); - var authorizeResult = await AuthorizeService.Authorize( + var authorizeResult = await AuthorizeService.AuthorizeAsync( User, server, ServerPermissionConstants.Power, ServerPermissionLevel.ReadWrite diff --git a/MoonlightServers.ApiServer/Http/Controllers/Client/ServersController.cs b/MoonlightServers.ApiServer/Http/Controllers/Client/ServersController.cs index b4b9ded..f616bbf 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Client/ServersController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Client/ServersController.cs @@ -1,24 +1,19 @@ -using System.ComponentModel.DataAnnotations; using System.Security.Claims; 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 Moonlight.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Extensions; using MoonlightServers.ApiServer.Mappers; -using MoonlightServers.ApiServer.Models; using MoonlightServers.ApiServer.Services; using MoonlightServers.Shared.Constants; using MoonlightServers.Shared.Enums; using MoonlightServers.Shared.Http.Requests.Client.Servers; using MoonlightServers.Shared.Http.Responses.Client.Servers; using MoonlightServers.Shared.Http.Responses.Client.Servers.Allocations; -using MoonlightServers.Shared.Models; namespace MoonlightServers.ApiServer.Http.Controllers.Client; @@ -52,8 +47,14 @@ public class ServersController : Controller } [HttpGet] - public async Task>> GetAll([FromQuery] PagedOptions options) + public async Task>> GetAllAsync( + [FromQuery] int startIndex, + [FromQuery] int count + ) { + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + var userIdClaim = User.FindFirstValue("UserId"); if (string.IsNullOrEmpty(userIdClaim)) @@ -68,12 +69,12 @@ public class ServersController : Controller .Include(x => x.Node) .Where(x => x.OwnerId == userId); - var count = await query.CountAsync(); + var totalCount = await query.CountAsync(); var items = await query .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .AsNoTracking() .ToArrayAsync(); @@ -94,19 +95,22 @@ public class ServersController : Controller }).ToArray() }).ToArray(); - return new PagedData() + return new CountedData() { Items = mappedItems, - CurrentPage = options.Page, - TotalItems = count, - PageSize = options.PageSize, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("shared")] - public async Task>> GetAllShared([FromQuery] PagedOptions options) + public async Task>> GetAllSharedAsync( + [FromQuery] int startIndex, + [FromQuery] int count + ) { + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + var userIdClaim = User.FindFirstValue("UserId"); if (string.IsNullOrEmpty(userIdClaim)) @@ -124,12 +128,12 @@ public class ServersController : Controller .ThenInclude(x => x.Allocations) .Where(x => x.UserId == userId); - var count = await query.CountAsync(); + var totalCount = await query.CountAsync(); var items = await query .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .ToArrayAsync(); var ownerIds = items @@ -164,18 +168,15 @@ public class ServersController : Controller } }).ToArray(); - return new PagedData() + return new CountedData() { Items = mappedItems, - CurrentPage = options.Page, - TotalItems = count, - PageSize = options.PageSize, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("{serverId:int}")] - public async Task> Get([FromRoute] int serverId) + public async Task> GetAsync([FromRoute] int serverId) { var server = await ServerRepository .Get() @@ -187,7 +188,7 @@ public class ServersController : Controller if (server == null) return Problem("No server with this id found", statusCode: 404); - var authorizationResult = await AuthorizeService.Authorize( + var authorizationResult = await AuthorizeService.AuthorizeAsync( User, server, String.Empty, @@ -238,18 +239,18 @@ public class ServersController : Controller } [HttpGet("{serverId:int}/status")] - public async Task> GetStatus([FromRoute] int serverId) + public async Task> GetStatusAsync([FromRoute] int serverId) { - var server = await GetServerById( + var server = await GetServerByIdAsync( serverId, ServerPermissionConstants.Console, ServerPermissionLevel.None ); - + if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - var status = await ServerService.GetStatus(server.Value); + var status = await ServerService.GetStatusAsync(server.Value); return new ServerStatusResponse() { @@ -258,14 +259,14 @@ public class ServersController : Controller } [HttpGet("{serverId:int}/ws")] - public async Task> GetWebSocket([FromRoute] int serverId) + public async Task> GetWebSocketAsync([FromRoute] int serverId) { - var serverResult = await GetServerById( + var serverResult = await GetServerByIdAsync( serverId, ServerPermissionConstants.Console, ServerPermissionLevel.Read ); - + if (serverResult.Value == null) return serverResult.Result ?? Problem("Unable to retrieve server"); @@ -292,18 +293,18 @@ public class ServersController : Controller } [HttpGet("{serverId:int}/logs")] - public async Task> GetLogs([FromRoute] int serverId) + public async Task> GetLogsAsync([FromRoute] int serverId) { - var server = await GetServerById( + var server = await GetServerByIdAsync( serverId, ServerPermissionConstants.Console, ServerPermissionLevel.Read ); - + if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - var logs = await ServerService.GetLogs(server.Value); + var logs = await ServerService.GetLogsAsync(server.Value); return new ServerLogsResponse() { @@ -312,18 +313,18 @@ public class ServersController : Controller } [HttpGet("{serverId:int}/stats")] - public async Task> GetStats([FromRoute] int serverId) + public async Task> GetStatsAsync([FromRoute] int serverId) { - var server = await GetServerById( + var server = await GetServerByIdAsync( serverId, ServerPermissionConstants.Console, ServerPermissionLevel.Read ); - + if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - var stats = await ServerService.GetStats(server.Value); + var stats = await ServerService.GetStatsAsync(server.Value); return new ServerStatsResponse() { @@ -337,9 +338,9 @@ public class ServersController : Controller } [HttpPost("{serverId:int}/command")] - public async Task Command([FromRoute] int serverId, [FromBody] ServerCommandRequest request) + public async Task CommandAsync([FromRoute] int serverId, [FromBody] ServerCommandRequest request) { - var server = await GetServerById( + var server = await GetServerByIdAsync( serverId, ServerPermissionConstants.Console, ServerPermissionLevel.ReadWrite @@ -348,12 +349,13 @@ public class ServersController : Controller if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerService.RunCommand(server.Value, request.Command); + await ServerService.RunCommandAsync(server.Value, request.Command); return NoContent(); } - private async Task> GetServerById(int serverId, string permissionId, ServerPermissionLevel level) + private async Task> GetServerByIdAsync(int serverId, string permissionId, + ServerPermissionLevel level) { var server = await ServerRepository .Get() @@ -363,7 +365,7 @@ public class ServersController : Controller if (server == null) return Problem("No server with this id found", statusCode: 404); - var authorizeResult = await AuthorizeService.Authorize(User, server, permissionId, level); + var authorizeResult = await AuthorizeService.AuthorizeAsync(User, server, permissionId, level); if (!authorizeResult.Succeeded) { diff --git a/MoonlightServers.ApiServer/Http/Controllers/Client/SettingsController.cs b/MoonlightServers.ApiServer/Http/Controllers/Client/SettingsController.cs index 62f9b95..141327b 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Client/SettingsController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Client/SettingsController.cs @@ -1,7 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using MoonCore.Exceptions; using MoonCore.Extended.Abstractions; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Services; @@ -32,18 +31,18 @@ public class SettingsController : Controller [HttpPost("{serverId:int}/install")] [Authorize] - public async Task Install([FromRoute] int serverId) + public async Task InstallAsync([FromRoute] int serverId) { - var server = await GetServerById(serverId); + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); - await ServerService.Install(server.Value); + await ServerService.InstallAsync(server.Value); return NoContent(); } - private async Task> GetServerById(int serverId) + private async Task> GetServerByIdAsync(int serverId) { var server = await ServerRepository .Get() @@ -53,7 +52,7 @@ public class SettingsController : Controller if (server == null) return Problem("No server with this id found", statusCode: 404); - var authorizeResult = await AuthorizeService.Authorize( + var authorizeResult = await AuthorizeService.AuthorizeAsync( User, server, ServerPermissionConstants.Settings, ServerPermissionLevel.ReadWrite diff --git a/MoonlightServers.ApiServer/Http/Controllers/Client/SharesController.cs b/MoonlightServers.ApiServer/Http/Controllers/Client/SharesController.cs index 4d2fcfa..2945b61 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Client/SharesController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Client/SharesController.cs @@ -1,15 +1,11 @@ -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 Moonlight.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Mappers; -using MoonlightServers.ApiServer.Models; using MoonlightServers.ApiServer.Services; using MoonlightServers.Shared.Constants; using MoonlightServers.Shared.Enums; @@ -42,12 +38,16 @@ public class SharesController : Controller } [HttpGet] - public async Task>> GetAll( + public async Task>> GetAllAsync( [FromRoute] int serverId, - [FromQuery] PagedOptions options + [FromQuery] int startIndex, + [FromQuery] int count ) { - var server = await GetServerById(serverId); + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); @@ -56,12 +56,12 @@ public class SharesController : Controller .Get() .Where(x => x.Server.Id == server.Value.Id); - var count = await query.CountAsync(); + var totalCount = await query.CountAsync(); var items = await query .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .ToArrayAsync(); var userIds = items @@ -81,23 +81,20 @@ public class SharesController : Controller Permissions = ShareMapper.MapToPermissionLevels(x.Content) }).ToArray(); - return new PagedData() + return new CountedData() { Items = mappedItems, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpGet("{id:int}")] - public async Task> Get( + public async Task> GetAsync( [FromRoute] int serverId, [FromRoute] int id ) { - var server = await GetServerById(serverId); + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); @@ -124,12 +121,12 @@ public class SharesController : Controller } [HttpPost] - public async Task> Create( + public async Task> CreateAsync( [FromRoute] int serverId, [FromBody] CreateShareRequest request ) { - var server = await GetServerById(serverId); + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); @@ -150,7 +147,7 @@ public class SharesController : Controller UserId = user.Id }; - var finalShare = await ShareRepository.Add(share); + var finalShare = await ShareRepository.AddAsync(share); var mappedItem = new ServerShareResponse() { @@ -163,13 +160,13 @@ public class SharesController : Controller } [HttpPatch("{id:int}")] - public async Task> Update( + public async Task> UpdateAsync( [FromRoute] int serverId, [FromRoute] int id, [FromBody] UpdateShareRequest request ) { - var server = await GetServerById(serverId); + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); @@ -185,7 +182,7 @@ public class SharesController : Controller share.UpdatedAt = DateTime.UtcNow; - await ShareRepository.Update(share); + await ShareRepository.UpdateAsync(share); var user = await UserRepository .Get() @@ -205,12 +202,12 @@ public class SharesController : Controller } [HttpDelete("{id:int}")] - public async Task Delete( + public async Task DeleteAsync( [FromRoute] int serverId, [FromRoute] int id ) { - var server = await GetServerById(serverId); + var server = await GetServerByIdAsync(serverId); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); @@ -222,11 +219,11 @@ public class SharesController : Controller if (share == null) return Problem("A share with that id cannot be found", statusCode: 404); - await ShareRepository.Remove(share); + await ShareRepository.RemoveAsync(share); return NoContent(); } - private async Task> GetServerById(int serverId) + private async Task> GetServerByIdAsync(int serverId) { var server = await ServerRepository .Get() @@ -235,7 +232,7 @@ public class SharesController : Controller if (server == null) return Problem("No server with this id found", statusCode: 404); - var authorizeResult = await AuthorizeService.Authorize( + var authorizeResult = await AuthorizeService.AuthorizeAsync( User, server, ServerPermissionConstants.Shares, ServerPermissionLevel.ReadWrite diff --git a/MoonlightServers.ApiServer/Http/Controllers/Client/VariablesController.cs b/MoonlightServers.ApiServer/Http/Controllers/Client/VariablesController.cs index df5ff0c..39d7968 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Client/VariablesController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Client/VariablesController.cs @@ -1,18 +1,14 @@ -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 Moonlight.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Services; using MoonlightServers.Shared.Constants; using MoonlightServers.Shared.Enums; using MoonlightServers.Shared.Http.Requests.Client.Servers.Variables; -using MoonlightServers.Shared.Http.Responses.Client.Servers.Shares; using MoonlightServers.Shared.Http.Responses.Client.Servers.Variables; namespace MoonlightServers.ApiServer.Http.Controllers.Client; @@ -41,12 +37,16 @@ public class VariablesController : Controller } [HttpGet] - public async Task>> Get( + public async Task>> GetAsync( [FromRoute] int serverId, - [FromQuery] PagedOptions options + [FromQuery] int startIndex, + [FromQuery] int count ) { - var server = await GetServerById(serverId, ServerPermissionLevel.Read); + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + + var server = await GetServerByIdAsync(serverId, ServerPermissionLevel.Read); if (server.Value == null) return server.Result ?? Problem("Unable to retrieve server"); @@ -55,12 +55,12 @@ public class VariablesController : Controller .Get() .Where(x => x.Star.Id == server.Value.Star.Id); - var count = await query.CountAsync(); + var totalCount = await query.CountAsync(); var starVariables = await query .OrderBy(x => x.Id) - .Skip(options.Page * options.PageSize) - .Take(options.PageSize) + .Skip(startIndex) + .Take(count) .ToArrayAsync(); var starVariableKeys = starVariables @@ -87,25 +87,22 @@ public class VariablesController : Controller }; }).ToArray(); - return new PagedData() + return new CountedData() { Items = responses, - CurrentPage = options.Page, - PageSize = options.PageSize, - TotalItems = count, - TotalPages = (int)Math.Ceiling(Math.Max(0, count) / (double)options.PageSize) + TotalCount = totalCount }; } [HttpPut] - public async Task> UpdateSingle( + public async Task> UpdateSingleAsync( [FromRoute] int serverId, [FromBody] UpdateServerVariableRequest request ) { // TODO: Handle filter - var serverResult = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var serverResult = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (serverResult.Value == null) return serverResult.Result ?? Problem("Unable to retrieve server"); @@ -119,7 +116,7 @@ public class VariablesController : Controller throw new HttpApiException($"No variable with the key found: {request.Key}", 400); serverVariable.Value = request.Value; - await ServerRepository.Update(server); + await ServerRepository.UpdateAsync(server); return new ServerVariableDetailResponse() { @@ -133,12 +130,12 @@ public class VariablesController : Controller } [HttpPatch] - public async Task> Update( + public async Task> UpdateAsync( [FromRoute] int serverId, [FromBody] UpdateServerVariableRangeRequest request ) { - var serverResult = await GetServerById(serverId, ServerPermissionLevel.ReadWrite); + var serverResult = await GetServerByIdAsync(serverId, ServerPermissionLevel.ReadWrite); if (serverResult.Value == null) return serverResult.Result ?? Problem("Unable to retrieve server"); @@ -158,7 +155,7 @@ public class VariablesController : Controller serverVariable.Value = variable.Value; } - await ServerRepository.Update(server); + await ServerRepository.UpdateAsync(server); return request.Variables.Select(requestVariable => { @@ -177,7 +174,7 @@ public class VariablesController : Controller }).ToArray(); } - private async Task> GetServerById(int serverId, ServerPermissionLevel level) + private async Task> GetServerByIdAsync(int serverId, ServerPermissionLevel level) { var server = await ServerRepository .Get() @@ -189,7 +186,7 @@ public class VariablesController : Controller if (server == null) return Problem("No server with this id found", statusCode: 404); - var authorizeResult = await AuthorizeService.Authorize( + var authorizeResult = await AuthorizeService.AuthorizeAsync( User, server, ServerPermissionConstants.Variables, level diff --git a/MoonlightServers.ApiServer/Http/Controllers/Remote/Nodes/NodeTripController.cs b/MoonlightServers.ApiServer/Http/Controllers/Remote/Nodes/NodeTripController.cs index 1d393e2..543951e 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Remote/Nodes/NodeTripController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Remote/Nodes/NodeTripController.cs @@ -9,5 +9,5 @@ namespace MoonlightServers.ApiServer.Http.Controllers.Remote.Nodes; public class NodeTripController : Controller { [HttpGet("trip")] - public Task Get() => Task.CompletedTask; + public Task GetAsync() => Task.CompletedTask; } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Http/Controllers/Remote/ServersController.cs b/MoonlightServers.ApiServer/Http/Controllers/Remote/ServersController.cs index f4d6096..20befca 100644 --- a/MoonlightServers.ApiServer/Http/Controllers/Remote/ServersController.cs +++ b/MoonlightServers.ApiServer/Http/Controllers/Remote/ServersController.cs @@ -31,8 +31,14 @@ public class ServersController : Controller } [HttpGet] - public async Task> Get([FromQuery] int page, [FromQuery] int pageSize) + public async Task>> GetAsync( + [FromQuery] int startIndex, + [FromQuery] int count + ) { + if (count > 100) + return Problem("Only 100 items can be fetched at a time", statusCode: 400); + // Load the node via the id var nodeId = int.Parse(User.Claims.First(x => x.Type == "nodeId").Value); @@ -52,8 +58,8 @@ public class ServersController : Controller .ThenInclude(x => x.DockerImages) .Include(x => x.Variables) .Include(x => x.Allocations) - .Skip(page * pageSize) - .Take(pageSize) + .Skip(startIndex) + .Take(count) .ToArrayAsync(); var serverData = new List(); @@ -68,18 +74,15 @@ public class ServersController : Controller serverData.Add(convertedData); } - return new PagedData() + return new CountedData() { Items = serverData.ToArray(), - CurrentPage = page, - PageSize = pageSize, - TotalItems = total, - TotalPages = total == 0 ? 0 : total / pageSize + TotalCount = total }; } [HttpGet("{id:int}")] - public async Task Get([FromRoute] int id) + public async Task GetAsync([FromRoute] int id) { // Load the node via the id var nodeId = int.Parse(User.Claims.First(x => x.Type == "nodeId").Value); @@ -111,7 +114,7 @@ public class ServersController : Controller } [HttpGet("{id:int}/install")] - public async Task GetInstall([FromRoute] int id) + public async Task GetInstallAsync([FromRoute] int id) { // Load the node via the id var nodeId = int.Parse(User.Claims.First(x => x.Type == "nodeId").Value); @@ -180,7 +183,6 @@ public class ServersController : Controller Port = x.Port }).ToArray(), Variables = server.Variables.ToDictionary(x => x.Key, x => x.Value), - Bandwidth = server.Bandwidth, Cpu = server.Cpu, Disk = server.Disk, Memory = server.Memory, @@ -189,7 +191,6 @@ public class ServersController : Controller PullDockerImage = dockerImage.AutoPulling, ParseConiguration = server.Star.ParseConfiguration, StopCommand = server.Star.StopCommand, - UseVirtualDisk = server.UseVirtualDisk }; } } \ No newline at end of file diff --git a/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/AdminAuthFilter.cs b/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/AdminAuthFilter.cs index c4c224f..c6afeee 100644 --- a/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/AdminAuthFilter.cs +++ b/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/AdminAuthFilter.cs @@ -1,11 +1,9 @@ using System.Security.Claims; using Microsoft.AspNetCore.Authorization; -using MoonCore.Attributes; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Interfaces; using MoonlightServers.ApiServer.Models; using MoonlightServers.Shared.Enums; -using MoonlightServers.Shared.Models; namespace MoonlightServers.ApiServer.Implementations.ServerAuthFilters; @@ -20,7 +18,7 @@ public class AdminAuthFilter : IServerAuthorizationFilter AuthorizationService = authorizationService; } - public async Task Process( + public async Task ProcessAsync( ClaimsPrincipal user, Server server, string permissionId, diff --git a/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/OwnerAuthFilter.cs b/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/OwnerAuthFilter.cs index a2b88a3..83ff9c7 100644 --- a/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/OwnerAuthFilter.cs +++ b/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/OwnerAuthFilter.cs @@ -1,10 +1,8 @@ using System.Security.Claims; -using MoonCore.Attributes; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Interfaces; using MoonlightServers.ApiServer.Models; using MoonlightServers.Shared.Enums; -using MoonlightServers.Shared.Models; namespace MoonlightServers.ApiServer.Implementations.ServerAuthFilters; @@ -12,7 +10,7 @@ public class OwnerAuthFilter : IServerAuthorizationFilter { public int Priority => 0; - public Task Process( + public Task ProcessAsync( ClaimsPrincipal user, Server server, string permissionId, diff --git a/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/ShareAuthFilter.cs b/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/ShareAuthFilter.cs index 5dedd62..690d67b 100644 --- a/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/ShareAuthFilter.cs +++ b/MoonlightServers.ApiServer/Implementations/ServerAuthFilters/ShareAuthFilter.cs @@ -1,12 +1,10 @@ using System.Security.Claims; using Microsoft.EntityFrameworkCore; -using MoonCore.Attributes; using MoonCore.Extended.Abstractions; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Interfaces; using MoonlightServers.ApiServer.Models; using MoonlightServers.Shared.Enums; -using MoonlightServers.Shared.Models; namespace MoonlightServers.ApiServer.Implementations.ServerAuthFilters; @@ -21,7 +19,7 @@ public class ShareAuthFilter : IServerAuthorizationFilter public int Priority => 0; - public async Task Process( + public async Task ProcessAsync( ClaimsPrincipal user, Server server, string permissionId, diff --git a/MoonlightServers.ApiServer/Interfaces/IServerAuthorizationFilter.cs b/MoonlightServers.ApiServer/Interfaces/IServerAuthorizationFilter.cs index 62e63a5..fad756e 100644 --- a/MoonlightServers.ApiServer/Interfaces/IServerAuthorizationFilter.cs +++ b/MoonlightServers.ApiServer/Interfaces/IServerAuthorizationFilter.cs @@ -12,7 +12,7 @@ public interface IServerAuthorizationFilter public int Priority { get; } - public Task Process( + public Task ProcessAsync( ClaimsPrincipal user, Server server, string permissionId, diff --git a/MoonlightServers.ApiServer/Mappers/ServerMapper.cs b/MoonlightServers.ApiServer/Mappers/ServerMapper.cs index 2242acd..a92df9e 100644 --- a/MoonlightServers.ApiServer/Mappers/ServerMapper.cs +++ b/MoonlightServers.ApiServer/Mappers/ServerMapper.cs @@ -1,7 +1,6 @@ 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; diff --git a/MoonlightServers.ApiServer/Mappers/StarMapper.cs b/MoonlightServers.ApiServer/Mappers/StarMapper.cs index f1f7f34..bf7dd9a 100644 --- a/MoonlightServers.ApiServer/Mappers/StarMapper.cs +++ b/MoonlightServers.ApiServer/Mappers/StarMapper.cs @@ -1,5 +1,4 @@ using MoonlightServers.ApiServer.Database.Entities; -using MoonlightServers.Shared.Http.Requests.Admin.StarDockerImages; using MoonlightServers.Shared.Http.Requests.Admin.Stars; using MoonlightServers.Shared.Http.Responses.Admin.Stars; using Riok.Mapperly.Abstractions; diff --git a/MoonlightServers.ApiServer/MoonlightServers.ApiServer.csproj b/MoonlightServers.ApiServer/MoonlightServers.ApiServer.csproj index 7fa187a..9340a1c 100644 --- a/MoonlightServers.ApiServer/MoonlightServers.ApiServer.csproj +++ b/MoonlightServers.ApiServer/MoonlightServers.ApiServer.csproj @@ -16,7 +16,7 @@ - + diff --git a/MoonlightServers.ApiServer/Services/NodeService.cs b/MoonlightServers.ApiServer/Services/NodeService.cs index 6570bb4..168eff9 100644 --- a/MoonlightServers.ApiServer/Services/NodeService.cs +++ b/MoonlightServers.ApiServer/Services/NodeService.cs @@ -1,9 +1,7 @@ using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.Tokens; using MoonCore.Attributes; -using MoonCore.Extended.Helpers; using MoonCore.Helpers; using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.DaemonShared.DaemonSide.Http.Responses.Statistics; @@ -41,7 +39,7 @@ public class NodeService return jwtSecurityTokenHandler.WriteToken(securityToken); } - public async Task GetSystemStatus(Node node) + public async Task GetSystemStatusAsync(Node node) { using var apiClient = CreateApiClient(node); return await apiClient.GetJson("api/system/status"); @@ -49,13 +47,13 @@ public class NodeService #region Statistics - public async Task GetStatistics(Node node) + public async Task GetStatisticsAsync(Node node) { using var apiClient = CreateApiClient(node); return await apiClient.GetJson("api/statistics"); } - public async Task GetDockerStatistics(Node node) + public async Task GetDockerStatisticsAsync(Node node) { using var apiClient = CreateApiClient(node); return await apiClient.GetJson("api/statistics/docker"); diff --git a/MoonlightServers.ApiServer/Services/ServerAuthorizeService.cs b/MoonlightServers.ApiServer/Services/ServerAuthorizeService.cs index a7e5037..d25f93c 100644 --- a/MoonlightServers.ApiServer/Services/ServerAuthorizeService.cs +++ b/MoonlightServers.ApiServer/Services/ServerAuthorizeService.cs @@ -19,7 +19,7 @@ public class ServerAuthorizeService AuthorizationFilters = authorizationFilters.ToArray(); } - public async Task Authorize( + public async Task AuthorizeAsync( ClaimsPrincipal user, Server server, string permissionIdentifier, @@ -28,7 +28,7 @@ public class ServerAuthorizeService { foreach (var authorizationFilter in AuthorizationFilters) { - var result = await authorizationFilter.Process( + var result = await authorizationFilter.ProcessAsync( user, server, permissionIdentifier, diff --git a/MoonlightServers.ApiServer/Services/ServerFileSystemService.cs b/MoonlightServers.ApiServer/Services/ServerFileSystemService.cs index 5daee51..b571e3a 100644 --- a/MoonlightServers.ApiServer/Services/ServerFileSystemService.cs +++ b/MoonlightServers.ApiServer/Services/ServerFileSystemService.cs @@ -24,54 +24,54 @@ public class ServerFileSystemService ServerRepository = serverRepository; } - public async Task List(Server server, string path) + public async Task ListAsync(Server server, string path) { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); return await apiClient.GetJson( $"api/servers/{server.Id}/files/list?path={path}" ); } - public async Task Move(Server server, string oldPath, string newPath) + public async Task MoveAsync(Server server, string oldPath, string newPath) { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post( $"api/servers/{server.Id}/files/move?oldPath={oldPath}&newPath={newPath}" ); } - public async Task Delete(Server server, string path) + public async Task DeleteAsync(Server server, string path) { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Delete( $"api/servers/{server.Id}/files/delete?path={path}" ); } - public async Task Mkdir(Server server, string path) + public async Task MkdirAsync(Server server, string path) { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post( $"api/servers/{server.Id}/files/mkdir?path={path}" ); } - public async Task Touch(Server server, string path) + public async Task TouchAsync(Server server, string path) { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post( $"api/servers/{server.Id}/files/touch?path={path}" ); } - public async Task Compress(Server server, CompressType type, string[] items, string destination) + public async Task CompressAsync(Server server, CompressType type, string[] items, string destination) { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post( $"api/servers/{server.Id}/files/compress", @@ -84,9 +84,9 @@ public class ServerFileSystemService ); } - public async Task Decompress(Server server, CompressType type, string path, string destination) + public async Task DecompressAsync(Server server, CompressType type, string path, string destination) { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post( $"api/servers/{server.Id}/files/decompress", @@ -101,7 +101,7 @@ public class ServerFileSystemService #region Helpers - private async Task GetApiClient(Server server) + private async Task GetApiClientAsync(Server server) { var serverWithNode = server; diff --git a/MoonlightServers.ApiServer/Services/ServerService.cs b/MoonlightServers.ApiServer/Services/ServerService.cs index 26d863d..f1c3b1f 100644 --- a/MoonlightServers.ApiServer/Services/ServerService.cs +++ b/MoonlightServers.ApiServer/Services/ServerService.cs @@ -1,4 +1,3 @@ -using System.Text.Json; using Microsoft.EntityFrameworkCore; using MoonCore.Attributes; using MoonCore.Exceptions; @@ -25,11 +24,11 @@ public class ServerService #region Power Actions - public async Task Start(Server server) + public async Task StartAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post($"api/servers/{server.Id}/start"); } catch (HttpRequestException e) @@ -38,11 +37,11 @@ public class ServerService } } - public async Task Stop(Server server) + public async Task StopAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post($"api/servers/{server.Id}/stop"); } catch (HttpRequestException e) @@ -51,11 +50,11 @@ public class ServerService } } - public async Task Kill(Server server) + public async Task KillAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post($"api/servers/{server.Id}/kill"); } catch (HttpRequestException e) @@ -66,11 +65,11 @@ public class ServerService #endregion - public async Task Install(Server server) + public async Task InstallAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post($"api/servers/{server.Id}/install"); } catch (HttpRequestException e) @@ -79,11 +78,11 @@ public class ServerService } } - public async Task Sync(Server server) + public async Task SyncAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post($"api/servers/{server.Id}/sync"); } catch (HttpRequestException e) @@ -92,11 +91,11 @@ public class ServerService } } - public async Task SyncDelete(Server server) + public async Task SyncDeleteAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Delete($"api/servers/{server.Id}"); } catch (HttpRequestException e) @@ -105,11 +104,11 @@ public class ServerService } } - public async Task GetStatus(Server server) + public async Task GetStatusAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); return await apiClient.GetJson($"api/servers/{server.Id}/status"); } catch (HttpRequestException e) @@ -118,11 +117,11 @@ public class ServerService } } - public async Task GetLogs(Server server) + public async Task GetLogsAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); return await apiClient.GetJson($"api/servers/{server.Id}/logs"); } catch (HttpRequestException e) @@ -131,11 +130,11 @@ public class ServerService } } - public async Task GetStats(Server server) + public async Task GetStatsAsync(Server server) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); return await apiClient.GetJson($"api/servers/{server.Id}/stats"); } catch (HttpRequestException) @@ -144,11 +143,11 @@ public class ServerService } } - public async Task RunCommand(Server server, string command) + public async Task RunCommandAsync(Server server, string command) { try { - using var apiClient = await GetApiClient(server); + using var apiClient = await GetApiClientAsync(server); await apiClient.Post( $"api/servers/{server.Id}/command", @@ -174,7 +173,7 @@ public class ServerService return PermissionHelper.HasPermission(user.Permissions, "admin.servers.get"); } - private async Task GetApiClient(Server server) + private async Task GetApiClientAsync(Server server) { var serverWithNode = server; diff --git a/MoonlightServers.ApiServer/Services/StarImportExportService.cs b/MoonlightServers.ApiServer/Services/StarImportExportService.cs index 91825a4..13a0327 100644 --- a/MoonlightServers.ApiServer/Services/StarImportExportService.cs +++ b/MoonlightServers.ApiServer/Services/StarImportExportService.cs @@ -23,7 +23,7 @@ public class StarImportExportService Logger = logger; } - public async Task Export(int id) + public async Task ExportAsync(int id) { var star = StarRepository .Get() @@ -78,20 +78,20 @@ public class StarImportExportService return json; } - public async Task Import(string json) + public async Task ImportAsync(string json) { // Determine which importer to use based on simple patterns if (json.Contains("RequiredAllocations")) - return await ImportStar(json); + return await ImportStarAsync(json); else if (json.Contains("AllocationsNeeded")) - return await ImportImage(json); + return await ImportImageAsync(json); else if (json.Contains("_comment")) - return await ImportEgg(json); + return await ImportEggAsync(json); else throw new HttpApiException("Unable to determine the format of the imported star/image/egg", 400); } - public async Task ImportStar(string json) + public async Task ImportStarAsync(string json) { try { @@ -138,7 +138,7 @@ public class StarImportExportService }).ToList() }; - var finalStar = await StarRepository.Add(star); + var finalStar = await StarRepository.AddAsync(star); return finalStar; } @@ -149,7 +149,7 @@ public class StarImportExportService } } - public async Task ImportImage(string json) + public async Task ImportImageAsync(string json) { try { @@ -235,7 +235,7 @@ public class StarImportExportService #endregion - var finalStar = await StarRepository.Add(star); + var finalStar = await StarRepository.AddAsync(star); return finalStar; } @@ -246,7 +246,7 @@ public class StarImportExportService } } - public async Task ImportEgg(string json) + public async Task ImportEggAsync(string json) { // Create result var star = new Star(); @@ -403,7 +403,7 @@ public class StarImportExportService star.AllowDockerImageChange = true; // Finally save it to the db - var finalStar = await StarRepository.Add(star); + var finalStar = await StarRepository.AddAsync(star); return finalStar; } diff --git a/MoonlightServers.ApiServer/Startup/PluginStartup.cs b/MoonlightServers.ApiServer/Startup/PluginStartup.cs index c3ba11f..13470d7 100644 --- a/MoonlightServers.ApiServer/Startup/PluginStartup.cs +++ b/MoonlightServers.ApiServer/Startup/PluginStartup.cs @@ -15,7 +15,7 @@ namespace MoonlightServers.ApiServer.Startup; public class PluginStartup : IPluginStartup { - public Task BuildApplication(IServiceProvider serviceProvider, IHostApplicationBuilder builder) + public Task BuildApplicationAsync(IServiceProvider serviceProvider, IHostApplicationBuilder builder) { // Scan the current plugin assembly for di services builder.Services.AutoAddServices(); @@ -51,9 +51,9 @@ public class PluginStartup : IPluginStartup return Task.CompletedTask; } - public Task ConfigureApplication(IServiceProvider serviceProvider, IApplicationBuilder app) + public Task ConfigureApplicationAsync(IServiceProvider serviceProvider, IApplicationBuilder app) => Task.CompletedTask; - public Task ConfigureEndpoints(IServiceProvider serviceProvider, IEndpointRouteBuilder routeBuilder) + public Task ConfigureEndpointsAsync(IServiceProvider serviceProvider, IEndpointRouteBuilder routeBuilder) => Task.CompletedTask; } \ No newline at end of file diff --git a/MoonlightServers.Daemon/Configuration/AppConfiguration.cs b/MoonlightServers.Daemon/Configuration/AppConfiguration.cs index 5a77082..5851246 100644 --- a/MoonlightServers.Daemon/Configuration/AppConfiguration.cs +++ b/MoonlightServers.Daemon/Configuration/AppConfiguration.cs @@ -1,5 +1,3 @@ -using MoonCore.Helpers; - namespace MoonlightServers.Daemon.Configuration; public class AppConfiguration diff --git a/MoonlightServers.Daemon/Extensions/ServerConfigurationExtensions.cs b/MoonlightServers.Daemon/Extensions/ServerConfigurationExtensions.cs index 65b15a8..53d2627 100644 --- a/MoonlightServers.Daemon/Extensions/ServerConfigurationExtensions.cs +++ b/MoonlightServers.Daemon/Extensions/ServerConfigurationExtensions.cs @@ -23,8 +23,6 @@ public static class ServerConfigurationExtensions Variables = response.Variables, OnlineDetection = response.OnlineDetection, DockerImage = response.DockerImage, - UseVirtualDisk = response.UseVirtualDisk, - Bandwidth = response.Bandwidth, Cpu = response.Cpu, Disk = response.Disk, Memory = response.Memory, diff --git a/MoonlightServers.Daemon/Helpers/HostSystemHelper.cs b/MoonlightServers.Daemon/Helpers/HostSystemHelper.cs index 985843b..42e0dc9 100644 --- a/MoonlightServers.Daemon/Helpers/HostSystemHelper.cs +++ b/MoonlightServers.Daemon/Helpers/HostSystemHelper.cs @@ -57,18 +57,18 @@ public class HostSystemHelper #region CPU Usage - public async Task GetCpuUsage() + public async Task GetCpuUsageAsync() { var result = new CpuUsageDetails(); var perCoreUsages = new List(); // Initial read - var (cpuLastStats, cpuLastSums) = await ReadAllCpuStats(); + var (cpuLastStats, cpuLastSums) = await ReadAllCpuStatsAsync(); await Task.Delay(1000); // Second read - var (cpuNowStats, cpuNowSums) = await ReadAllCpuStats(); + var (cpuNowStats, cpuNowSums) = await ReadAllCpuStatsAsync(); for (var i = 0; i < cpuNowStats.Length; i++) { @@ -94,7 +94,7 @@ public class HostSystemHelper return result; } - private async Task<(long[][] cpuStatsList, long[] cpuSums)> ReadAllCpuStats() + private async Task<(long[][] cpuStatsList, long[] cpuSums)> ReadAllCpuStatsAsync() { var lines = await File.ReadAllLinesAsync("/proc/stat"); @@ -128,12 +128,12 @@ public class HostSystemHelper #region Memory - public async Task ClearCachedMemory() + public async Task ClearCachedMemoryAsync() { await File.WriteAllTextAsync("/proc/sys/vm/drop_caches", "3"); } - public async Task GetMemoryUsage() + public async Task GetMemoryUsageAsync() { var details = new MemoryUsageDetails(); @@ -194,7 +194,7 @@ public class HostSystemHelper #region Disks - public async Task GetDiskUsages() + public async Task GetDiskUsagesAsync() { var details = new List(); diff --git a/MoonlightServers.Daemon/Helpers/ServerFileSystem.cs b/MoonlightServers.Daemon/Helpers/ServerFileSystem.cs index 952be5f..bf7f05a 100644 --- a/MoonlightServers.Daemon/Helpers/ServerFileSystem.cs +++ b/MoonlightServers.Daemon/Helpers/ServerFileSystem.cs @@ -3,7 +3,6 @@ using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using ICSharpCode.SharpZipLib.Zip; using Mono.Unix.Native; -using MoonCore.Unix.Exceptions; using MoonCore.Unix.SecureFs; using MoonlightServers.DaemonShared.DaemonSide.Http.Responses.Servers; using MoonlightServers.DaemonShared.Enums; @@ -19,7 +18,7 @@ public class ServerFileSystem FileSystem = fileSystem; } - public Task List(string inputPath) + public Task ListAsync(string inputPath) { var path = Normalize(inputPath); var entries = FileSystem.ReadDir(path); @@ -45,7 +44,7 @@ public class ServerFileSystem return Task.FromResult(result); } - public Task Move(string inputOldPath, string inputNewPath) + public Task MoveAsync(string inputOldPath, string inputNewPath) { var oldPath = Normalize(inputOldPath); var newPath = Normalize(inputNewPath); @@ -55,7 +54,7 @@ public class ServerFileSystem return Task.CompletedTask; } - public Task Delete(string inputPath) + public Task DeleteAsync(string inputPath) { var path = Normalize(inputPath); @@ -64,7 +63,7 @@ public class ServerFileSystem return Task.CompletedTask; } - public Task Mkdir(string inputPath) + public Task MkdirAsync(string inputPath) { var path = Normalize(inputPath); @@ -73,7 +72,7 @@ public class ServerFileSystem return Task.CompletedTask; } - public Task Touch(string inputPath) + public Task TouchAsync(string inputPath) { var path = Normalize(inputPath); @@ -91,7 +90,7 @@ public class ServerFileSystem return Task.CompletedTask; } - public Task CreateChunk(string inputPath, long totalSize, long positionToSkip, Stream chunkStream) + public Task CreateChunkAsync(string inputPath, long totalSize, long positionToSkip, Stream chunkStream) { var path = Normalize(inputPath); @@ -114,7 +113,7 @@ public class ServerFileSystem return Task.CompletedTask; } - public Task Create(string inputPath, Stream dataStream) + public Task CreateAsync(string inputPath, Stream dataStream) { var path = Normalize(inputPath); @@ -134,7 +133,7 @@ public class ServerFileSystem return Task.CompletedTask; } - public Task Read(string inputPath, Func onHandle) + public Task ReadAsync(string inputPath, Func onHandle) { var path = Normalize(inputPath); @@ -149,7 +148,7 @@ public class ServerFileSystem #region Compression - public Task Compress(string[] itemsInput, string destinationInput, CompressType type) + public Task CompressAsync(string[] itemsInput, string destinationInput, CompressType type) { var destination = Normalize(destinationInput); var items = itemsInput.Select(Normalize); @@ -191,7 +190,7 @@ public class ServerFileSystem return Task.CompletedTask; } - public Task Decompress(string pathInput, string destinationInput, CompressType type) + public Task DecompressAsync(string pathInput, string destinationInput, CompressType type) { var path = Normalize(pathInput); var destination = Normalize(destinationInput); diff --git a/MoonlightServers.Daemon/Helpers/UnsafeDockerClient.cs b/MoonlightServers.Daemon/Helpers/UnsafeDockerClient.cs index 8178929..9a529fc 100644 --- a/MoonlightServers.Daemon/Helpers/UnsafeDockerClient.cs +++ b/MoonlightServers.Daemon/Helpers/UnsafeDockerClient.cs @@ -17,7 +17,7 @@ public class UnsafeDockerClient Configuration = configuration; } - public Task CreateHttpClient() + public Task CreateHttpClientAsync() { var client = new HttpClient(new SocketsHttpHandler() { @@ -35,9 +35,9 @@ public class UnsafeDockerClient return Task.FromResult(client); } - public async Task GetDataUsage() + public async Task GetDataUsageAsync() { - using var client = await CreateHttpClient(); + using var client = await CreateHttpClientAsync(); var responseJson = await client.GetStringAsync("http://some.random.domain/v1.47/system/df"); var response = JsonSerializer.Deserialize(responseJson)!; diff --git a/MoonlightServers.Daemon/Http/Controllers/Servers/PowerController.cs b/MoonlightServers.Daemon/Http/Controllers/Servers/PowerController.cs index e7185bf..f2b8c0b 100644 --- a/MoonlightServers.Daemon/Http/Controllers/Servers/PowerController.cs +++ b/MoonlightServers.Daemon/Http/Controllers/Servers/PowerController.cs @@ -16,7 +16,7 @@ public class PowerController : Controller } [HttpPost("start")] - public async Task Start([FromRoute] int id) + public async Task StartAsync([FromRoute] int id) { var server = ServerService.GetById(id); @@ -31,7 +31,7 @@ public class PowerController : Controller } [HttpPost("stop")] - public async Task Stop([FromRoute] int id) + public async Task StopAsync([FromRoute] int id) { var server = ServerService.GetById(id); @@ -46,7 +46,7 @@ public class PowerController : Controller } [HttpPost("kill")] - public async Task Kill([FromRoute] int id) + public async Task KillAsync([FromRoute] int id) { var server = ServerService.GetById(id); @@ -61,7 +61,7 @@ public class PowerController : Controller } [HttpPost("install")] - public async Task Install([FromRoute] int id) + public async Task InstallAsync([FromRoute] int id) { var server = ServerService.GetById(id); diff --git a/MoonlightServers.Daemon/Http/Controllers/Servers/ServersController.cs b/MoonlightServers.Daemon/Http/Controllers/Servers/ServersController.cs index da794ab..1c09495 100644 --- a/MoonlightServers.Daemon/Http/Controllers/Servers/ServersController.cs +++ b/MoonlightServers.Daemon/Http/Controllers/Servers/ServersController.cs @@ -3,7 +3,6 @@ using MoonlightServers.Daemon.Mappers; using MoonlightServers.Daemon.Services; using MoonlightServers.DaemonShared.DaemonSide.Http.Responses.Servers; using MoonlightServers.DaemonShared.Enums; -using MoonlightServers.DaemonShared.PanelSide.Http.Responses; namespace MoonlightServers.Daemon.Http.Controllers.Servers; @@ -21,14 +20,14 @@ public class ServersController : Controller } [HttpPost("sync")] - public async Task Sync([FromRoute] int id) + public async Task SyncAsync([FromRoute] int id) { - await ServerService.InitializeById(id); + await ServerService.InitializeByIdAsync(id); return NoContent(); } [HttpGet("status")] - public async Task> Status([FromRoute] int id) + public async Task> StatusAsync([FromRoute] int id) { var server = ServerService.GetById(id); @@ -42,7 +41,7 @@ public class ServersController : Controller } [HttpGet("logs")] - public async Task> Logs([FromRoute] int id) + public async Task> LogsAsync([FromRoute] int id) { var server = ServerService.GetById(id); @@ -58,7 +57,7 @@ public class ServersController : Controller } [HttpGet("stats")] - public async Task GetStats([FromRoute] int id) + public async Task GetStatsAsync([FromRoute] int id) { return new ServerStatsResponse() { diff --git a/MoonlightServers.Daemon/Http/Controllers/Statistics/StatisticsController.cs b/MoonlightServers.Daemon/Http/Controllers/Statistics/StatisticsController.cs index f84a20e..ec032ac 100644 --- a/MoonlightServers.Daemon/Http/Controllers/Statistics/StatisticsController.cs +++ b/MoonlightServers.Daemon/Http/Controllers/Statistics/StatisticsController.cs @@ -18,17 +18,17 @@ public class StatisticsController : Controller } [HttpGet] - public async Task Get() + public async Task GetAsync() { var response = new StatisticsResponse(); - var cpuUsage = await HostSystemHelper.GetCpuUsage(); + var cpuUsage = await HostSystemHelper.GetCpuUsageAsync(); response.Cpu.Model = cpuUsage.Model; response.Cpu.Usage = cpuUsage.OverallUsage; response.Cpu.UsagePerCore = cpuUsage.PerCoreUsage; - var memoryUsage = await HostSystemHelper.GetMemoryUsage(); + var memoryUsage = await HostSystemHelper.GetMemoryUsageAsync(); response.Memory.Available = memoryUsage.Available; response.Memory.Cached = memoryUsage.Cached; @@ -37,7 +37,7 @@ public class StatisticsController : Controller response.Memory.SwapTotal = memoryUsage.SwapTotal; response.Memory.SwapFree = memoryUsage.SwapFree; - var diskDetails = await HostSystemHelper.GetDiskUsages(); + var diskDetails = await HostSystemHelper.GetDiskUsagesAsync(); response.Disks = diskDetails.Select(x => new StatisticsResponse.DiskData() { diff --git a/MoonlightServers.Daemon/Http/Controllers/Statistics/StatisticsDockerController.cs b/MoonlightServers.Daemon/Http/Controllers/Statistics/StatisticsDockerController.cs index 93b2fa4..38ce37e 100644 --- a/MoonlightServers.Daemon/Http/Controllers/Statistics/StatisticsDockerController.cs +++ b/MoonlightServers.Daemon/Http/Controllers/Statistics/StatisticsDockerController.cs @@ -20,13 +20,13 @@ public class StatisticsDockerController : Controller } [HttpGet] - public async Task Get() + public async Task GetAsync() { - var usage = await DockerInfoService.GetDataUsage(); + var usage = await DockerInfoService.GetDataUsageAsync(); return new StatisticsDockerResponse { - Version = await DockerInfoService.GetDockerVersion(), + Version = await DockerInfoService.GetDockerVersionAsync(), ContainersReclaimable = usage.Containers.Reclaimable, ContainersUsed = usage.Containers.Used, BuildCacheReclaimable = usage.BuildCache.Reclaimable, diff --git a/MoonlightServers.Daemon/Http/Controllers/Sys/SystemStatusController.cs b/MoonlightServers.Daemon/Http/Controllers/Sys/SystemStatusController.cs index 8f4208a..a046e0d 100644 --- a/MoonlightServers.Daemon/Http/Controllers/Sys/SystemStatusController.cs +++ b/MoonlightServers.Daemon/Http/Controllers/Sys/SystemStatusController.cs @@ -18,7 +18,7 @@ public class SystemStatusController : Controller RemoteService = remoteService; } - public async Task Get() + public async Task GetAsync() { SystemStatusResponse response; @@ -27,7 +27,7 @@ public class SystemStatusController : Controller try { - await RemoteService.GetStatus(); + await RemoteService.GetStatusAsync(); sw.Stop(); diff --git a/MoonlightServers.Daemon/Mappers/ServerConfigurationMapper.cs b/MoonlightServers.Daemon/Mappers/ServerConfigurationMapper.cs index 78c2d03..92750eb 100644 --- a/MoonlightServers.Daemon/Mappers/ServerConfigurationMapper.cs +++ b/MoonlightServers.Daemon/Mappers/ServerConfigurationMapper.cs @@ -30,8 +30,6 @@ public class ServerConfigurationMapper Variables = response.Variables, OnlineDetection = response.OnlineDetection, DockerImage = response.DockerImage, - UseVirtualDisk = response.UseVirtualDisk, - Bandwidth = response.Bandwidth, Cpu = response.Cpu, Disk = response.Disk, Memory = response.Memory, diff --git a/MoonlightServers.Daemon/Models/Cache/ServerConfiguration.cs b/MoonlightServers.Daemon/Models/Cache/ServerConfiguration.cs index 2215286..5111fac 100644 --- a/MoonlightServers.Daemon/Models/Cache/ServerConfiguration.cs +++ b/MoonlightServers.Daemon/Models/Cache/ServerConfiguration.cs @@ -8,8 +8,6 @@ public class ServerConfiguration public int Cpu { get; set; } public int Memory { get; set; } public int Disk { get; set; } - public int Bandwidth { get; set; } - public bool UseVirtualDisk { get; set; } // Start, Stop & Status public string StartupCommand { get; set; } diff --git a/MoonlightServers.Daemon/Models/ServerConsole.cs b/MoonlightServers.Daemon/Models/ServerConsole.cs index ec7f4d4..08d517c 100644 --- a/MoonlightServers.Daemon/Models/ServerConsole.cs +++ b/MoonlightServers.Daemon/Models/ServerConsole.cs @@ -14,7 +14,7 @@ public class ServerConsole MaxMessagesInCache = maxMessagesInCache; } - public async Task WriteToOutput(string content) + public async Task WriteToOutputAsync(string content) { lock (MessageCache) { @@ -32,7 +32,7 @@ public class ServerConsole } } - public async Task WriteToInput(string content) + public async Task WriteToInputAsync(string content) { if (OnInput != null) await OnInput.Invoke(content); diff --git a/MoonlightServers.Daemon/MoonlightServers.Daemon.csproj b/MoonlightServers.Daemon/MoonlightServers.Daemon.csproj index 40f85be..d25877a 100644 --- a/MoonlightServers.Daemon/MoonlightServers.Daemon.csproj +++ b/MoonlightServers.Daemon/MoonlightServers.Daemon.csproj @@ -8,9 +8,10 @@ + - - + + diff --git a/MoonlightServers.Daemon/Program.cs b/MoonlightServers.Daemon/Program.cs index ea1b72f..c6732cf 100644 --- a/MoonlightServers.Daemon/Program.cs +++ b/MoonlightServers.Daemon/Program.cs @@ -2,4 +2,4 @@ using MoonlightServers.Daemon; var startup = new Startup(); -await startup.Run(args); \ No newline at end of file +await startup.RunAsync(args); \ No newline at end of file diff --git a/MoonlightServers.Daemon/ServerSystem/Docker/DockerConsole.cs b/MoonlightServers.Daemon/ServerSystem/Docker/DockerConsole.cs index 39acf5a..2888361 100644 --- a/MoonlightServers.Daemon/ServerSystem/Docker/DockerConsole.cs +++ b/MoonlightServers.Daemon/ServerSystem/Docker/DockerConsole.cs @@ -57,17 +57,17 @@ public class DockerConsole : IConsole { var containerName = string.Format(DockerConstants.RuntimeNameTemplate, Context.Configuration.Id); - await AttachToContainer(containerName); + await AttachToContainerAsync(containerName); } public async Task AttachInstallationAsync() { var containerName = string.Format(DockerConstants.InstallationNameTemplate, Context.Configuration.Id); - await AttachToContainer(containerName); + await AttachToContainerAsync(containerName); } - private async Task AttachToContainer(string containerName) + private async Task AttachToContainerAsync(string containerName) { var cts = new CancellationTokenSource(); @@ -171,17 +171,17 @@ public class DockerConsole : IConsole { var containerName = string.Format(DockerConstants.RuntimeNameTemplate, Context.Configuration.Id); - await FetchFromContainer(containerName); + await FetchFromContainerAsync(containerName); } public async Task FetchInstallationAsync() { var containerName = string.Format(DockerConstants.InstallationNameTemplate, Context.Configuration.Id); - await FetchFromContainer(containerName); + await FetchFromContainerAsync(containerName); } - private async Task FetchFromContainer(string containerName) + private async Task FetchFromContainerAsync(string containerName) { var logStream = await DockerClient.Containers.GetContainerLogsAsync(containerName, true, new() { diff --git a/MoonlightServers.Daemon/ServerSystem/Docker/DockerInstallation.cs b/MoonlightServers.Daemon/ServerSystem/Docker/DockerInstallation.cs index ac6bb18..2a9b89d 100644 --- a/MoonlightServers.Daemon/ServerSystem/Docker/DockerInstallation.cs +++ b/MoonlightServers.Daemon/ServerSystem/Docker/DockerInstallation.cs @@ -104,7 +104,7 @@ public class DockerInstallation : IInstallation // Docker image await Reporter.StatusAsync("Downloading docker image"); - await ImageService.Download(data.DockerImage, async status => { await Reporter.StatusAsync(status); }); + await ImageService.DownloadAsync(data.DockerImage, async status => { await Reporter.StatusAsync(status); }); await Reporter.StatusAsync("Downloaded docker image"); @@ -159,7 +159,7 @@ public class DockerInstallation : IInstallation } } - public async Task SubscribeExited(Func callback) + public async Task SubscribeExitedAsync(Func callback) => await ExitEventSource.SubscribeAsync(callback); public async Task RestoreAsync() diff --git a/MoonlightServers.Daemon/ServerSystem/Docker/DockerRuntime.cs b/MoonlightServers.Daemon/ServerSystem/Docker/DockerRuntime.cs index 8fd771e..aabc565 100644 --- a/MoonlightServers.Daemon/ServerSystem/Docker/DockerRuntime.cs +++ b/MoonlightServers.Daemon/ServerSystem/Docker/DockerRuntime.cs @@ -96,7 +96,7 @@ public class DockerRuntime : IRuntime // Docker image await Reporter.StatusAsync("Downloading docker image"); - await ImageService.Download( + await ImageService.DownloadAsync( Context.Configuration.DockerImage, async status => { await Reporter.StatusAsync(status); } ); @@ -152,7 +152,7 @@ public class DockerRuntime : IRuntime } } - public async Task SubscribeExited(Func callback) + public async Task SubscribeExitedAsync(Func callback) => await ExitEventSource.SubscribeAsync(callback); public async Task RestoreAsync() diff --git a/MoonlightServers.Daemon/ServerSystem/Handlers/InstallationHandler.cs b/MoonlightServers.Daemon/ServerSystem/Handlers/InstallationHandler.cs index 8c38b8d..8f22f09 100644 --- a/MoonlightServers.Daemon/ServerSystem/Handlers/InstallationHandler.cs +++ b/MoonlightServers.Daemon/ServerSystem/Handlers/InstallationHandler.cs @@ -80,7 +80,7 @@ public class InstallationHandler : IServerStateHandler await Server.Installation.CreateAsync(runtimePath, installationPath, installData); if (ExitSubscription == null) - ExitSubscription = await Server.Installation.SubscribeExited(OnInstallationExited); + ExitSubscription = await Server.Installation.SubscribeExitedAsync(OnInstallationExited); // 6. Attach console diff --git a/MoonlightServers.Daemon/ServerSystem/Handlers/StartupHandler.cs b/MoonlightServers.Daemon/ServerSystem/Handlers/StartupHandler.cs index 7e151ad..c21e6d7 100644 --- a/MoonlightServers.Daemon/ServerSystem/Handlers/StartupHandler.cs +++ b/MoonlightServers.Daemon/ServerSystem/Handlers/StartupHandler.cs @@ -58,7 +58,7 @@ public class StartupHandler : IServerStateHandler await Server.Runtime.CreateAsync(hostPath); if (ExitSubscription == null) - ExitSubscription = await Server.Runtime.SubscribeExited(OnRuntimeExited); + ExitSubscription = await Server.Runtime.SubscribeExitedAsync(OnRuntimeExited); // 6. Attach console diff --git a/MoonlightServers.Daemon/ServerSystem/Interfaces/IInstallation.cs b/MoonlightServers.Daemon/ServerSystem/Interfaces/IInstallation.cs index 27236dc..c356f31 100644 --- a/MoonlightServers.Daemon/ServerSystem/Interfaces/IInstallation.cs +++ b/MoonlightServers.Daemon/ServerSystem/Interfaces/IInstallation.cs @@ -42,7 +42,7 @@ public interface IInstallation : IServerComponent /// /// Callback to invoke whenever the installation exists /// Subscription disposable to unsubscribe from the event - public Task SubscribeExited(Func callback); + public Task SubscribeExitedAsync(Func callback); /// /// Connects an existing installation to this abstraction in order to restore it. diff --git a/MoonlightServers.Daemon/ServerSystem/Interfaces/IRuntime.cs b/MoonlightServers.Daemon/ServerSystem/Interfaces/IRuntime.cs index d6a5f7a..d7e9490 100644 --- a/MoonlightServers.Daemon/ServerSystem/Interfaces/IRuntime.cs +++ b/MoonlightServers.Daemon/ServerSystem/Interfaces/IRuntime.cs @@ -44,7 +44,7 @@ public interface IRuntime : IServerComponent /// /// Callback gets invoked whenever the runtime exites /// Subscription disposable to unsubscribe from the event - public Task SubscribeExited(Func callback); + public Task SubscribeExitedAsync(Func callback); /// /// Connects an existing runtime to this abstraction in order to restore it. diff --git a/MoonlightServers.Daemon/ServerSystem/Models/ServerContext.cs b/MoonlightServers.Daemon/ServerSystem/Models/ServerContext.cs index 188c8ac..3a63609 100644 --- a/MoonlightServers.Daemon/ServerSystem/Models/ServerContext.cs +++ b/MoonlightServers.Daemon/ServerSystem/Models/ServerContext.cs @@ -1,5 +1,4 @@ using MoonlightServers.Daemon.Models.Cache; -using MoonlightServers.Daemon.ServerSystem.Interfaces; namespace MoonlightServers.Daemon.ServerSystem.Models; diff --git a/MoonlightServers.Daemon/ServerSystem/Server.cs b/MoonlightServers.Daemon/ServerSystem/Server.cs index 8b7848d..c0664da 100644 --- a/MoonlightServers.Daemon/ServerSystem/Server.cs +++ b/MoonlightServers.Daemon/ServerSystem/Server.cs @@ -1,4 +1,3 @@ -using System.Collections; using MoonlightServers.Daemon.ServerSystem.Enums; using MoonlightServers.Daemon.ServerSystem.Interfaces; using MoonlightServers.Daemon.ServerSystem.Models; diff --git a/MoonlightServers.Daemon/Services/DockerEventService.cs b/MoonlightServers.Daemon/Services/DockerEventService.cs index 1b794dc..ac881af 100644 --- a/MoonlightServers.Daemon/Services/DockerEventService.cs +++ b/MoonlightServers.Daemon/Services/DockerEventService.cs @@ -1,11 +1,6 @@ -using System.Reactive.Concurrency; -using System.Reactive.Linq; -using System.Reactive.Subjects; using Docker.DotNet; using Docker.DotNet.Models; using MoonCore.Events; -using MoonCore.Observability; -using MoonlightServers.Daemon.Helpers; namespace MoonlightServers.Daemon.Services; diff --git a/MoonlightServers.Daemon/Services/DockerImageService.cs b/MoonlightServers.Daemon/Services/DockerImageService.cs index 0c6d6c6..4fcb6b9 100644 --- a/MoonlightServers.Daemon/Services/DockerImageService.cs +++ b/MoonlightServers.Daemon/Services/DockerImageService.cs @@ -25,7 +25,7 @@ public class DockerImageService Logger = logger; } - public async Task Download(string name, Action? onProgressUpdated = null) + public async Task DownloadAsync(string name, Action? onProgressUpdated = null) { // If there is already a download for this image occuring, we want to wait for this to complete instead // of calling docker to download it again diff --git a/MoonlightServers.Daemon/Services/DockerInfoService.cs b/MoonlightServers.Daemon/Services/DockerInfoService.cs index 3a49639..c009f5b 100644 --- a/MoonlightServers.Daemon/Services/DockerInfoService.cs +++ b/MoonlightServers.Daemon/Services/DockerInfoService.cs @@ -17,16 +17,16 @@ public class DockerInfoService UnsafeDockerClient = unsafeDockerClient; } - public async Task GetDockerVersion() + public async Task GetDockerVersionAsync() { var version = await DockerClient.System.GetVersionAsync(); return $"{version.Version} commit {version.GitCommit} ({version.APIVersion})"; } - public async Task GetDataUsage() + public async Task GetDataUsageAsync() { - var response = await UnsafeDockerClient.GetDataUsage(); + var response = await UnsafeDockerClient.GetDataUsageAsync(); var report = new UsageDataReport() { diff --git a/MoonlightServers.Daemon/Services/RemoteService.cs b/MoonlightServers.Daemon/Services/RemoteService.cs index da6a3cb..69282dc 100644 --- a/MoonlightServers.Daemon/Services/RemoteService.cs +++ b/MoonlightServers.Daemon/Services/RemoteService.cs @@ -1,6 +1,3 @@ -using System.IdentityModel.Tokens.Jwt; -using System.Text; -using Microsoft.IdentityModel.Tokens; using MoonCore.Attributes; using MoonCore.Helpers; using MoonCore.Models; @@ -19,26 +16,26 @@ public class RemoteService ApiClient = CreateHttpClient(configuration); } - public async Task GetStatus() + public async Task GetStatusAsync() { await ApiClient.Get("api/remote/servers/node/trip"); } - public async Task> GetServers(int page, int perPage) + public async Task> GetServersAsync(int startIndex, int count) { - return await ApiClient.GetJson>( - $"api/remote/servers?page={page}&pageSize={perPage}" + return await ApiClient.GetJson>( + $"api/remote/servers?startIndex={startIndex}&count={count}" ); } - public async Task GetServer(int serverId) + public async Task GetServerAsync(int serverId) { return await ApiClient.GetJson( $"api/remote/servers/{serverId}" ); } - public async Task GetServerInstallation(int serverId) + public async Task GetServerInstallationAsync(int serverId) { return await ApiClient.GetJson( $"api/remote/servers/{serverId}/install" diff --git a/MoonlightServers.Daemon/Services/ServerService.cs b/MoonlightServers.Daemon/Services/ServerService.cs index 985210b..d3fe831 100644 --- a/MoonlightServers.Daemon/Services/ServerService.cs +++ b/MoonlightServers.Daemon/Services/ServerService.cs @@ -1,5 +1,4 @@ using System.Collections.Concurrent; -using MoonCore.Helpers; using MoonCore.Models; using MoonlightServers.Daemon.Mappers; using MoonlightServers.Daemon.Models.Cache; @@ -32,7 +31,7 @@ public class ServerService : IHostedLifecycleService public Server? GetById(int id) => Servers.GetValueOrDefault(id); - public async Task Initialize(ServerConfiguration configuration) + public async Task InitializeAsync(ServerConfiguration configuration) { var existingServer = Servers.GetValueOrDefault(configuration.Id); @@ -50,20 +49,20 @@ public class ServerService : IHostedLifecycleService } } - public async Task InitializeById(int id) + public async Task InitializeByIdAsync(int id) { - var serverData = await RemoteService.GetServer(id); + var serverData = await RemoteService.GetServerAsync(id); var config = ConfigurationMapper.FromServerDataResponse(serverData); - await Initialize(config); + await InitializeAsync(config); } - private async Task InitializeAll() + private async Task InitializeAllAsync() { Logger.LogDebug("Initialing servers from panel"); - var servers = await PagedData.All(async (page, pageSize) => - await RemoteService.GetServers(page, pageSize) + var servers = await CountedData.LoadAllAsync(async (startIndex, count) => + await RemoteService.GetServersAsync(startIndex, count) ); foreach (var serverData in servers) @@ -72,7 +71,7 @@ public class ServerService : IHostedLifecycleService { var config = ConfigurationMapper.FromServerDataResponse(serverData); - await Initialize(config); + await InitializeAsync(config); } catch (Exception e) { @@ -91,7 +90,7 @@ public class ServerService : IHostedLifecycleService public async Task StartedAsync(CancellationToken cancellationToken) { - await InitializeAll(); + await InitializeAllAsync(); } public Task StartingAsync(CancellationToken cancellationToken) diff --git a/MoonlightServers.Daemon/Startup.cs b/MoonlightServers.Daemon/Startup.cs index b631e04..8507ebb 100644 --- a/MoonlightServers.Daemon/Startup.cs +++ b/MoonlightServers.Daemon/Startup.cs @@ -14,11 +14,7 @@ using MoonlightServers.Daemon.Http.Hubs; using MoonlightServers.Daemon.Mappers; using MoonlightServers.Daemon.Models.Cache; using MoonlightServers.Daemon.ServerSystem; -using MoonlightServers.Daemon.ServerSystem.Docker; using MoonlightServers.Daemon.ServerSystem.Enums; -using MoonlightServers.Daemon.ServerSystem.FileSystems; -using MoonlightServers.Daemon.ServerSystem.Handlers; -using MoonlightServers.Daemon.ServerSystem.Implementations; using MoonlightServers.Daemon.ServerSystem.Models; using MoonlightServers.Daemon.Services; @@ -40,35 +36,35 @@ public class Startup private WebApplication WebApplication; private WebApplicationBuilder WebApplicationBuilder; - public async Task Run(string[] args) + public async Task RunAsync(string[] args) { Args = args; - await SetupStorage(); - await SetupAppConfiguration(); - await SetupLogging(); + await SetupStorageAsync(); + await SetupAppConfigurationAsync(); + await SetupLoggingAsync(); - await CreateWebApplicationBuilder(); + await CreateWebApplicationBuilderAsync(); - await ConfigureKestrel(); - await RegisterAppConfiguration(); - await RegisterLogging(); - await RegisterBase(); - await RegisterAuth(); - await RegisterDocker(); - await RegisterServers(); - await RegisterSignalR(); - await RegisterCors(); + await ConfigureKestrelAsync(); + await RegisterAppConfigurationAsync(); + await RegisterLoggingAsync(); + await RegisterBaseAsync(); + await RegisterAuthAsync(); + await RegisterDockerAsync(); + await RegisterServersAsync(); + await RegisterSignalRAsync(); + await RegisterCorsAsync(); - await BuildWebApplication(); + await BuildWebApplicationAsync(); - await UseBase(); - await UseCors(); - await UseAuth(); - await UseBaseMiddleware(); + await UseBaseAsync(); + await UseCorsAsync(); + await UseAuthAsync(); + await UseBaseMiddlewareAsync(); - await MapBase(); - await MapHubs(); + await MapBaseAsync(); + await MapHubsAsync(); Task.Run(async () => { @@ -93,8 +89,6 @@ public class Startup "java -Xms128M -Xmx{{SERVER_MEMORY}}M -Dterminal.jline=false -Dterminal.ansi=true -jar {{SERVER_JARFILE}}", DockerImage = "ghcr.io/nexocrew-hq/moonlightdockerimages:java21", StopCommand = "stop", - UseVirtualDisk = false, - Bandwidth = 0, Variables = new Dictionary() { { "SERVER_JARFILE", "server.jar" }, @@ -139,7 +133,7 @@ public class Startup await WebApplication.RunAsync(); } - private Task SetupStorage() + private Task SetupStorageAsync() { Directory.CreateDirectory("storage"); Directory.CreateDirectory(Path.Combine("storage", "logs")); @@ -149,7 +143,7 @@ public class Startup #region Base - private Task RegisterBase() + private Task RegisterBaseAsync() { WebApplicationBuilder.Services.AutoAddServices(); WebApplicationBuilder.Services.AddControllers(); @@ -159,7 +153,7 @@ public class Startup return Task.CompletedTask; } - private Task ConfigureKestrel() + private Task ConfigureKestrelAsync() { WebApplicationBuilder.WebHost.ConfigureKestrel(options => { @@ -170,7 +164,7 @@ public class Startup return Task.CompletedTask; } - private Task UseBase() + private Task UseBaseAsync() { WebApplication.UseRouting(); WebApplication.UseExceptionHandler(); @@ -178,12 +172,12 @@ public class Startup return Task.CompletedTask; } - private Task UseBaseMiddleware() + private Task UseBaseMiddlewareAsync() { return Task.CompletedTask; } - private Task MapBase() + private Task MapBaseAsync() { WebApplication.MapControllers(); @@ -194,7 +188,7 @@ public class Startup #region Docker - private Task RegisterDocker() + private Task RegisterDockerAsync() { var dockerClient = new DockerClientConfiguration( new Uri(Configuration.Docker.Uri) @@ -213,7 +207,7 @@ public class Startup #region Configurations - private async Task SetupAppConfiguration() + private async Task SetupAppConfigurationAsync() { var configurationBuilder = new ConfigurationBuilder(); @@ -235,7 +229,7 @@ public class Startup Configuration = configurationRoot.Get()!; } - private Task RegisterAppConfiguration() + private Task RegisterAppConfigurationAsync() { WebApplicationBuilder.Services.AddSingleton(Configuration); @@ -246,13 +240,13 @@ public class Startup #region Web Application - private Task CreateWebApplicationBuilder() + private Task CreateWebApplicationBuilderAsync() { WebApplicationBuilder = WebApplication.CreateBuilder(Args); return Task.CompletedTask; } - private Task BuildWebApplication() + private Task BuildWebApplicationAsync() { WebApplication = WebApplicationBuilder.Build(); return Task.CompletedTask; @@ -262,7 +256,7 @@ public class Startup #region Logging - private Task SetupLogging() + private Task SetupLoggingAsync() { LoggerFactory = new LoggerFactory(); LoggerFactory.AddAnsiConsole(); @@ -272,7 +266,7 @@ public class Startup return Task.CompletedTask; } - private async Task RegisterLogging() + private async Task RegisterLoggingAsync() { // Configure application logging WebApplicationBuilder.Logging.ClearProviders(); @@ -323,7 +317,7 @@ public class Startup #region Servers - private Task RegisterServers() + private Task RegisterServersAsync() { WebApplicationBuilder.Services.AddScoped(); WebApplicationBuilder.Services.AddSingleton(); @@ -335,7 +329,7 @@ public class Startup return Task.CompletedTask; } - private Task UseServers() + private Task UseServersAsync() { return Task.CompletedTask; } @@ -344,13 +338,13 @@ public class Startup #region Hubs - private Task RegisterSignalR() + private Task RegisterSignalRAsync() { WebApplicationBuilder.Services.AddSignalR(); return Task.CompletedTask; } - private Task MapHubs() + private Task MapHubsAsync() { WebApplication.MapHub("api/servers/ws", options => { @@ -365,7 +359,7 @@ public class Startup #region Cors - private Task RegisterCors() + private Task RegisterCorsAsync() { //TODO: IMPORTANT: CHANGE !!! WebApplicationBuilder.Services.AddCors(x => @@ -380,7 +374,7 @@ public class Startup return Task.CompletedTask; } - private Task UseCors() + private Task UseCorsAsync() { WebApplication.UseCors(); return Task.CompletedTask; @@ -390,7 +384,7 @@ public class Startup #region Authentication - private Task RegisterAuth() + private Task RegisterAuthAsync() { WebApplicationBuilder.Services .AddAuthentication("token") @@ -461,7 +455,7 @@ public class Startup return Task.CompletedTask; } - private Task UseAuth() + private Task UseAuthAsync() { WebApplication.UseAuthentication(); WebApplication.UseAuthorization(); diff --git a/MoonlightServers.DaemonShared/PanelSide/Http/Responses/ServerDataResponse.cs b/MoonlightServers.DaemonShared/PanelSide/Http/Responses/ServerDataResponse.cs index db7bae3..c18130d 100644 --- a/MoonlightServers.DaemonShared/PanelSide/Http/Responses/ServerDataResponse.cs +++ b/MoonlightServers.DaemonShared/PanelSide/Http/Responses/ServerDataResponse.cs @@ -14,9 +14,6 @@ public class ServerDataResponse public int Memory { get; set; } public int Disk { get; set; } - public bool UseVirtualDisk { get; set; } - public int Bandwidth { get; set; } - public AllocationDataResponse[] Allocations { get; set; } public Dictionary Variables { get; set; } } \ No newline at end of file diff --git a/MoonlightServers.Frontend.Runtime/MoonlightServers.Frontend.Runtime.csproj b/MoonlightServers.Frontend.Runtime/MoonlightServers.Frontend.Runtime.csproj index 00bc28e..3318612 100644 --- a/MoonlightServers.Frontend.Runtime/MoonlightServers.Frontend.Runtime.csproj +++ b/MoonlightServers.Frontend.Runtime/MoonlightServers.Frontend.Runtime.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/MoonlightServers.Frontend.Runtime/Program.cs b/MoonlightServers.Frontend.Runtime/Program.cs index 0f6664c..ee4706f 100644 --- a/MoonlightServers.Frontend.Runtime/Program.cs +++ b/MoonlightServers.Frontend.Runtime/Program.cs @@ -7,14 +7,14 @@ pluginLoader.Initialize(); var startup = new Startup(); -await startup.Initialize(pluginLoader.Instances); +await startup.InitializeAsync(pluginLoader.Instances); var wasmHostBuilder = WebAssemblyHostBuilder.CreateDefault(args); -await startup.AddMoonlight(wasmHostBuilder); +await startup.AddMoonlightAsync(wasmHostBuilder); var wasmApp = wasmHostBuilder.Build(); -await startup.AddMoonlight(wasmApp); +await startup.AddMoonlightAsync(wasmApp); await wasmApp.RunAsync(); \ No newline at end of file diff --git a/MoonlightServers.Frontend.Runtime/Styles/extract-classes.js b/MoonlightServers.Frontend.Runtime/Styles/extract-classes.js index 2bae324..b5d5c2c 100644 --- a/MoonlightServers.Frontend.Runtime/Styles/extract-classes.js +++ b/MoonlightServers.Frontend.Runtime/Styles/extract-classes.js @@ -21,8 +21,8 @@ module.exports = (opts = {}) => { fs.mkdirSync("../../MoonlightServers.Frontend/Styles/mappings"); } - fs.writeFileSync('../../MoonlightServers.Frontend/mappings/classes.map', classArray.join('\n')); - console.log(`✅ Extracted ${classArray.length} Tailwind classes to tailwind-classes.txt`); + fs.writeFileSync('../../MoonlightServers.Frontend/Styles/mappings/classes.map', classArray.join('\n')); + console.log(`Extracted ${classArray.length} Tailwind classes`); } }; }; diff --git a/MoonlightServers.Frontend.Runtime/Styles/styles.css b/MoonlightServers.Frontend.Runtime/Styles/styles.css index e941b47..13cb719 100644 --- a/MoonlightServers.Frontend.Runtime/Styles/styles.css +++ b/MoonlightServers.Frontend.Runtime/Styles/styles.css @@ -100,18 +100,38 @@ .select { @apply !border-base-content/20 border-2 ring-0! outline-0! focus:border-primary! focus-within:border-primary! bg-base-200/50; } - + .table { :where(th, td) { @apply py-1.5; } } - + .dropdown-item { @apply px-2.5 py-1.5 text-sm; } - + .dropdown-menu { @apply bg-base-150; } + + .advance-select-menu { + @apply !border-base-content/20 border-2 ring-0! outline-0! bg-base-200/50 !px-0; + } + + .advance-select-option { + @apply !rounded-none hover:!bg-primary; + } + + .advance-select-option.selected { + @apply !bg-primary !text-primary-content; + } + + .advance-select-toggle { + @apply !border-base-content/20 border-2 ring-0! outline-0! focus:border-primary! focus-within:border-primary! bg-base-200/50; + } + + .table thead { + @apply !normal-case; + } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/Helpers/ServerFsAccess.cs b/MoonlightServers.Frontend/Helpers/ServerFsAccess.cs index 3cbe3d6..349a39c 100644 --- a/MoonlightServers.Frontend/Helpers/ServerFsAccess.cs +++ b/MoonlightServers.Frontend/Helpers/ServerFsAccess.cs @@ -15,15 +15,15 @@ public class ServerFsAccess : IFsAccess FileSystemService = fileSystemService; } - public Task CreateFile(string path) - => FileSystemService.Touch(Id, path); + public Task CreateFileAsync(string path) + => FileSystemService.TouchAsync(Id, path); - public Task CreateDirectory(string path) - => FileSystemService.Mkdir(Id, path); + public Task CreateDirectoryAsync(string path) + => FileSystemService.MkdirAsync(Id, path); - public async Task List(string path) + public async Task ListAsync(string path) { - var entries = await FileSystemService.List(Id, path); + var entries = await FileSystemService.ListAsync(Id, path); return entries.Select(x => new FsEntry() { @@ -35,28 +35,28 @@ public class ServerFsAccess : IFsAccess }).ToArray(); } - public Task Move(string oldPath, string newPath) - => FileSystemService.Move(Id, oldPath, newPath); + public Task MoveAsync(string oldPath, string newPath) + => FileSystemService.MoveAsync(Id, oldPath, newPath); - public Task Read(string path, Func onHandleData) + public Task ReadAsync(string path, Func onHandleData) { throw new NotImplementedException(); } - public Task Write(string path, Stream dataStream) + public Task WriteAsync(string path, Stream dataStream) { throw new NotImplementedException(); } - public Task Delete(string path) - => FileSystemService.Delete(Id, path); + public Task DeleteAsync(string path) + => FileSystemService.DeleteAsync(Id, path); - public Task UploadChunk(string path, int chunkId, long chunkSize, long totalSize, byte[] data) + public Task UploadChunkAsync(string path, int chunkId, long chunkSize, long totalSize, byte[] data) { throw new NotImplementedException(); } - public Task DownloadChunk(string path, int chunkId, long chunkSize) + public Task DownloadChunkAsync(string path, int chunkId, long chunkSize) { throw new NotImplementedException(); } diff --git a/MoonlightServers.Frontend/Implementations/DefaultPermissionProvider.cs b/MoonlightServers.Frontend/Implementations/DefaultPermissionProvider.cs index 0942ade..8d6b2ad 100644 --- a/MoonlightServers.Frontend/Implementations/DefaultPermissionProvider.cs +++ b/MoonlightServers.Frontend/Implementations/DefaultPermissionProvider.cs @@ -7,7 +7,7 @@ namespace MoonlightServers.Frontend.Implementations; public class DefaultPermissionProvider : IServerPermissionProvider { - public Task GetPermissions(ServerDetailResponse server) + public Task GetPermissionsAsync(ServerDetailResponse server) { ServerPermission[] permissions = [ new() diff --git a/MoonlightServers.Frontend/Implementations/DefaultServerTabProvider.cs b/MoonlightServers.Frontend/Implementations/DefaultServerTabProvider.cs index 5b9dca8..922d9a1 100644 --- a/MoonlightServers.Frontend/Implementations/DefaultServerTabProvider.cs +++ b/MoonlightServers.Frontend/Implementations/DefaultServerTabProvider.cs @@ -9,7 +9,7 @@ namespace MoonlightServers.Frontend.Implementations; public class DefaultServerTabProvider : IServerTabProvider { - public Task GetTabs(ServerDetailResponse server) + public Task GetTabsAsync(ServerDetailResponse server) { ServerTab[] tabs = [ diff --git a/MoonlightServers.Frontend/Interfaces/IServerPermissionProvider.cs b/MoonlightServers.Frontend/Interfaces/IServerPermissionProvider.cs index 6832ad6..01d3988 100644 --- a/MoonlightServers.Frontend/Interfaces/IServerPermissionProvider.cs +++ b/MoonlightServers.Frontend/Interfaces/IServerPermissionProvider.cs @@ -5,5 +5,5 @@ namespace MoonlightServers.Frontend.Interfaces; public interface IServerPermissionProvider { - public Task GetPermissions(ServerDetailResponse server); + public Task GetPermissionsAsync(ServerDetailResponse server); } \ No newline at end of file diff --git a/MoonlightServers.Frontend/Interfaces/IServerTabProvider.cs b/MoonlightServers.Frontend/Interfaces/IServerTabProvider.cs index 09aacd9..a359ae1 100644 --- a/MoonlightServers.Frontend/Interfaces/IServerTabProvider.cs +++ b/MoonlightServers.Frontend/Interfaces/IServerTabProvider.cs @@ -5,5 +5,5 @@ namespace MoonlightServers.Frontend.Interfaces; public interface IServerTabProvider { - public Task GetTabs(ServerDetailResponse server); + public Task GetTabsAsync(ServerDetailResponse server); } \ No newline at end of file diff --git a/MoonlightServers.Frontend/Models/ServerTab.cs b/MoonlightServers.Frontend/Models/ServerTab.cs index 954b39c..0f45e85 100644 --- a/MoonlightServers.Frontend/Models/ServerTab.cs +++ b/MoonlightServers.Frontend/Models/ServerTab.cs @@ -1,6 +1,5 @@ using MoonlightServers.Frontend.UI.Components.Servers.ServerTabs; using MoonlightServers.Shared.Enums; -using MoonlightServers.Shared.Models; namespace MoonlightServers.Frontend.Models; diff --git a/MoonlightServers.Frontend/MoonlightServers.Frontend.csproj b/MoonlightServers.Frontend/MoonlightServers.Frontend.csproj index cd7b719..2919aa2 100644 --- a/MoonlightServers.Frontend/MoonlightServers.Frontend.csproj +++ b/MoonlightServers.Frontend/MoonlightServers.Frontend.csproj @@ -15,7 +15,7 @@ - + @@ -31,7 +31,8 @@ - + + diff --git a/MoonlightServers.Frontend/MoonlightServers.Frontend.targets b/MoonlightServers.Frontend/MoonlightServers.Frontend.targets new file mode 100644 index 0000000..77321fd --- /dev/null +++ b/MoonlightServers.Frontend/MoonlightServers.Frontend.targets @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/MoonlightServers.Frontend/Services/NodeService.cs b/MoonlightServers.Frontend/Services/NodeService.cs index 3bdd364..ed1a2eb 100644 --- a/MoonlightServers.Frontend/Services/NodeService.cs +++ b/MoonlightServers.Frontend/Services/NodeService.cs @@ -15,19 +15,19 @@ public class NodeService HttpApiClient = httpApiClient; } - public async Task GetSystemStatus(int nodeId) + public async Task GetSystemStatusAsync(int nodeId) { return await HttpApiClient.GetJson($"api/admin/servers/nodes/{nodeId}/system/status"); } - public async Task GetStatistics(int nodeId) + public async Task GetStatisticsAsync(int nodeId) { return await HttpApiClient.GetJson( $"api/admin/servers/nodes/{nodeId}/statistics" ); } - public async Task GetDockerStatistics(int nodeId) + public async Task GetDockerStatisticsAsync(int nodeId) { return await HttpApiClient.GetJson( $"api/admin/servers/nodes/{nodeId}/statistics/docker" diff --git a/MoonlightServers.Frontend/Services/ServerFileSystemService.cs b/MoonlightServers.Frontend/Services/ServerFileSystemService.cs index dc0cbcc..17a13e7 100644 --- a/MoonlightServers.Frontend/Services/ServerFileSystemService.cs +++ b/MoonlightServers.Frontend/Services/ServerFileSystemService.cs @@ -1,4 +1,3 @@ -using System.Net; using MoonCore.Attributes; using MoonCore.Helpers; using MoonlightServers.Shared.Http.Requests.Client.Servers.Files; @@ -16,56 +15,56 @@ public class ServerFileSystemService ApiClient = apiClient; } - public async Task List(int serverId, string path) + public async Task ListAsync(int serverId, string path) { return await ApiClient.GetJson( $"api/client/servers/{serverId}/files/list?path={path}" ); } - public async Task Move(int serverId, string oldPath, string newPath) + public async Task MoveAsync(int serverId, string oldPath, string newPath) { await ApiClient.Post( $"api/client/servers/{serverId}/files/move?oldPath={oldPath}&newPath={newPath}" ); } - public async Task Delete(int serverId, string path) + public async Task DeleteAsync(int serverId, string path) { await ApiClient.Delete( $"api/client/servers/{serverId}/files/delete?path={path}" ); } - public async Task Mkdir(int serverId, string path) + public async Task MkdirAsync(int serverId, string path) { await ApiClient.Post( $"api/client/servers/{serverId}/files/mkdir?path={path}" ); } - public async Task Touch(int serverId, string path) + public async Task TouchAsync(int serverId, string path) { await ApiClient.Post( $"api/client/servers/{serverId}/files/touch?path={path}" ); } - public async Task Upload(int serverId) + public async Task UploadAsync(int serverId) { return await ApiClient.GetJson( $"api/client/servers/{serverId}/files/upload" ); } - public async Task Download(int serverId, string path) + public async Task DownloadAsync(int serverId, string path) { return await ApiClient.GetJson( $"api/client/servers/{serverId}/files/download?path={path}" ); } - public async Task Compress(int serverId, string type, string[] items, string destination) + public async Task CompressAsync(int serverId, string type, string[] items, string destination) { await ApiClient.Post( $"api/client/servers/{serverId}/files/compress", @@ -78,7 +77,7 @@ public class ServerFileSystemService ); } - public async Task Decompress(int serverId, string type, string path, string destination) + public async Task DecompressAsync(int serverId, string type, string path, string destination) { await ApiClient.Post( $"api/client/servers/{serverId}/files/decompress", diff --git a/MoonlightServers.Frontend/Services/ServerService.cs b/MoonlightServers.Frontend/Services/ServerService.cs index ae07885..fa92dfd 100644 --- a/MoonlightServers.Frontend/Services/ServerService.cs +++ b/MoonlightServers.Frontend/Services/ServerService.cs @@ -18,49 +18,49 @@ public class ServerService HttpApiClient = httpApiClient; } - public async Task> GetServers(int page, int perPage) + public async Task> GetServersAsync(int startIndex, int count) { - return await HttpApiClient.GetJson>( - $"api/client/servers?page={page}&pageSize={perPage}" + return await HttpApiClient.GetJson>( + $"api/client/servers?startIndex={startIndex}&count={count}" ); } - public async Task> GetSharedServers(int page, int perPage) + public async Task> GetSharedServersAsync(int startIndex, int count) { - return await HttpApiClient.GetJson>( - $"api/client/servers/shared?page={page}&pageSize={perPage}" + return await HttpApiClient.GetJson>( + $"api/client/servers/shared?startIndex={startIndex}&count={count}" ); } - public async Task GetServer(int serverId) + public async Task GetServerAsync(int serverId) { return await HttpApiClient.GetJson( $"api/client/servers/{serverId}" ); } - public async Task GetStatus(int serverId) + public async Task GetStatusAsync(int serverId) { return await HttpApiClient.GetJson( $"api/client/servers/{serverId}/status" ); } - public async Task GetLogs(int serverId) + public async Task GetLogsAsync(int serverId) { return await HttpApiClient.GetJson( $"api/client/servers/{serverId}/logs" ); } - public async Task GetStats(int serverId) + public async Task GetStatsAsync(int serverId) { return await HttpApiClient.GetJson( $"api/client/servers/{serverId}/stats" ); } - public async Task RunCommand(int serverId, string command) + public async Task RunCommandAsync(int serverId, string command) { await HttpApiClient.Post( $"api/client/servers/{serverId}/command", @@ -71,14 +71,14 @@ public class ServerService ); } - public async Task GetWebSocket(int serverId) + public async Task GetWebSocketAsync(int serverId) { return await HttpApiClient.GetJson( $"api/client/servers/{serverId}/ws" ); } - public async Task Install(int serverId) + public async Task InstallAsync(int serverId) { await HttpApiClient.Post( $"api/client/servers/{serverId}/install" @@ -87,21 +87,21 @@ public class ServerService #region Power actions - public async Task Start(int serverId) + public async Task StartAsync(int serverId) { await HttpApiClient.Post( $"api/client/servers/{serverId}/start" ); } - public async Task Stop(int serverId) + public async Task StopAsync(int serverId) { await HttpApiClient.Post( $"api/client/servers/{serverId}/stop" ); } - public async Task Kill(int serverId) + public async Task KillAsync(int serverId) { await HttpApiClient.Post( $"api/client/servers/{serverId}/kill" @@ -112,14 +112,14 @@ public class ServerService #region Variables - public async Task> GetVariables(int serverId, int page, int pageSize) + public async Task> GetVariablesAsync(int serverId, int startIndex, int count) { - return await HttpApiClient.GetJson>( - $"api/client/servers/{serverId}/variables?page={page}&pageSize={pageSize}" + return await HttpApiClient.GetJson>( + $"api/client/servers/{serverId}/variables?startIndex={startIndex}&count={count}" ); } - public async Task UpdateVariables(int serverId, UpdateServerVariableRangeRequest request) + public async Task UpdateVariablesAsync(int serverId, UpdateServerVariableRangeRequest request) { await HttpApiClient.Patch( $"api/client/servers/{serverId}/variables", @@ -127,7 +127,7 @@ public class ServerService ); } - public async Task UpdateVariable(int serverId, UpdateServerVariableRequest request) + public async Task UpdateVariableAsync(int serverId, UpdateServerVariableRequest request) { await HttpApiClient.Put( $"api/client/servers/{serverId}/variables", diff --git a/MoonlightServers.Frontend/Services/ServerShareService.cs b/MoonlightServers.Frontend/Services/ServerShareService.cs index 2e4a0ea..f17a13c 100644 --- a/MoonlightServers.Frontend/Services/ServerShareService.cs +++ b/MoonlightServers.Frontend/Services/ServerShareService.cs @@ -16,19 +16,19 @@ public class ServerShareService ApiClient = apiClient; } - public async Task> Get(int id, int page, int pageSize) - => await ApiClient.GetJson>( - $"api/client/servers/{id}/shares?page={page}&pageSize={pageSize}"); + public async Task> GetAsync(int id, int startIndex, int count) + => await ApiClient.GetJson>( + $"api/client/servers/{id}/shares?startIndex={startIndex}&count={count}"); - public async Task Get(int id, int shareId) + public async Task GetAsync(int id, int shareId) => await ApiClient.GetJson($"api/client/servers/{id}/shares/{shareId}"); - public async Task Create(int id, CreateShareRequest request) + public async Task CreateAsync(int id, CreateShareRequest request) => await ApiClient.PostJson($"api/client/servers/{id}/shares", request); - public async Task Update(int id, int shareId, UpdateShareRequest request) + public async Task UpdateAsync(int id, int shareId, UpdateShareRequest request) => await ApiClient.PatchJson($"api/client/servers/{id}/shares/{shareId}", request); - public async Task Delete(int id, int shareId) + public async Task DeleteAsync(int id, int shareId) => await ApiClient.Delete($"api/client/servers/{id}/shares/{shareId}"); } \ No newline at end of file diff --git a/MoonlightServers.Frontend/Startup/PluginStartup.cs b/MoonlightServers.Frontend/Startup/PluginStartup.cs index 35065b7..f18144b 100644 --- a/MoonlightServers.Frontend/Startup/PluginStartup.cs +++ b/MoonlightServers.Frontend/Startup/PluginStartup.cs @@ -10,7 +10,7 @@ namespace MoonlightServers.Frontend.Startup; public class PluginStartup : IPluginStartup { - public Task BuildApplication(IServiceProvider serviceProvider, WebAssemblyHostBuilder builder) + public Task BuildApplicationAsync(IServiceProvider serviceProvider, WebAssemblyHostBuilder builder) { builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -21,7 +21,7 @@ public class PluginStartup : IPluginStartup return Task.CompletedTask; } - public Task ConfigureApplication(IServiceProvider serviceProvider, WebAssemblyHost app) + public Task ConfigureApplicationAsync(IServiceProvider serviceProvider, WebAssemblyHost app) { return Task.CompletedTask; } diff --git a/MoonlightServers.Frontend/Styles/Moonlight.Client/classes.map b/MoonlightServers.Frontend/Styles/Moonlight.Client/classes.map index a6584dd..599f38f 100755 --- a/MoonlightServers.Frontend/Styles/Moonlight.Client/classes.map +++ b/MoonlightServers.Frontend/Styles/Moonlight.Client/classes.map @@ -9,7 +9,9 @@ !me-1.5 !ms-auto !px-2.5 +!py-0.5 !rounded-full +!rounded-xs !text-sm !w-2.5 *:[grid-area:1/1] @@ -19,13 +21,17 @@ -ml-4 -translate-x-full -translate-y-1/2 +[animation-duration:0.8s] +[animation-timing-function:ease] absolute accordion accordion-bordered accordion-toggle active active-tab:bg-primary +active-tab:hover:text-primary-content active-tab:text-base-content +active-tab:text-primary-content advance-select-menu advance-select-option advance-select-tag @@ -39,6 +45,7 @@ align-bottom align-middle animate-bounce animate-ping +animate-spin aria-[current='page']:text-bg-soft-primary avatar avatar-away-bottom @@ -62,6 +69,7 @@ bg-background/60 bg-base-100 bg-base-150 bg-base-200 +bg-base-200! bg-base-200/50 bg-base-300 bg-base-300/45 @@ -85,9 +93,14 @@ block blur border border-0 +border-1 border-2 +border-3 border-accent border-b +border-b-2 +border-b-base-content/20 +border-b-primary border-base-content border-base-content/20 border-base-content/25 @@ -96,15 +109,26 @@ border-base-content/5 border-base-content/60 border-base-content/70 border-dashed +border-dotted border-e-2 +border-error/30 +border-info/30 border-l-4 +border-l-transparent border-primary +border-r-transparent +border-solid border-success +border-success/30 border-t border-t-2 +border-t-transparent border-transparent +border-warning/30 bottom-0 bottom-full +breadcrumbs +breadcrumbs-separator break-words btn btn-accent @@ -164,8 +188,10 @@ diff disabled divide-base-150/60 divide-y +divider drop-shadow dropdown +dropdown-active dropdown-disabled dropdown-item dropdown-menu @@ -179,7 +205,9 @@ ease-linear end-3 error-message file-upload-complete:progress-success +fill-base-content fill-black +fill-gray-200 filter filter-reset fixed @@ -210,6 +238,8 @@ font-inter font-medium font-normal font-semibold +footer +footer-center from-violet-400 gap-0.5 gap-1 @@ -226,6 +256,7 @@ gap-x-6 gap-y-1 gap-y-1.5 gap-y-2 +gap-y-2.5 gap-y-3 gap-y-8 grid @@ -233,10 +264,12 @@ grid-cols-1 grid-cols-12 grid-cols-2 grid-cols-3 +grid-cols-4 grid-flow-col grow grow-0 h-0 +h-10 h-12 h-14 h-2 @@ -253,11 +286,14 @@ hidden hover:bg-indigo-500 hover:bg-primary/5 hover:bg-transparent +hover:cursor-pointer hover:text-base-content hover:text-base-content/60 hover:text-indigo-500 hover:text-primary image-full +indicator +indicator-item inline inline-block inline-flex @@ -294,6 +330,7 @@ leading-3.5 leading-6 leading-9 leading-[1.1] +leading-none left-0 lg:bg-base-100/20 lg:flex @@ -320,6 +357,7 @@ link-hover link-primary list-disc list-inside +list-none loading loading-lg loading-sm @@ -332,7 +370,11 @@ mask max-h-52 max-lg:flex-col max-lg:hidden +max-md:flex-wrap +max-md:justify-center +max-sm:hidden max-w-7xl +max-w-8 max-w-80 max-w-full max-w-lg @@ -376,6 +418,7 @@ min-w-28 min-w-48 min-w-60 min-w-[100px] +min-w-full min-w-sm mix-blend-exclusion ml-3 @@ -387,10 +430,13 @@ modal-middle modal-title mr-2 mr-4 +ms-0.5 ms-1 +ms-1.5 ms-2 ms-2.5 ms-3 +ms-auto mt-1 mt-1.5 mt-10 @@ -398,6 +444,7 @@ mt-12 mt-2 mt-2.5 mt-3 +mt-3.5 mt-4 mt-5 mt-6 @@ -407,9 +454,12 @@ mx-auto my-2.5 my-3 my-5 +my-8 my-auto +object-cover opacity-0 opacity-100 +opacity-75 open origin-top-left outline @@ -430,6 +480,7 @@ p-4 p-5 p-6 p-8 +pb-1 pe-1.5 pin-input pin-input-underline @@ -444,6 +495,7 @@ progress-primary pt-0 pt-0.5 pt-1.5 +pt-2 pt-3 px-1.5 px-2 @@ -459,10 +511,12 @@ py-12 py-2 py-2.5 py-6 +radial-progress radio range relative resize +ring ring-0 ring-1 ring-gray-700 @@ -543,10 +597,12 @@ sm:text-sm/5 sm:w-1/2 sm:w-full space-x-1 +space-x-2.5 space-y-1 space-y-4 space-y-6 sr-only +stack stat stat-actions stat-desc @@ -602,6 +658,7 @@ text-left text-lg text-primary text-primary-content +text-right text-slate-100 text-sm text-sm/5 @@ -645,6 +702,7 @@ via-sky-400 w-0 w-0.5 w-12 +w-13 w-32 w-4 w-56 diff --git a/MoonlightServers.Frontend/Styles/mappings/classes.map b/MoonlightServers.Frontend/Styles/mappings/classes.map new file mode 100644 index 0000000..a34e84c --- /dev/null +++ b/MoonlightServers.Frontend/Styles/mappings/classes.map @@ -0,0 +1,790 @@ +!bg-base-100 +!border-base-content/40 +!border-none +!flex +!font-medium +!font-semibold +!h-2.5 +!justify-between +!me-1.5 +!ms-auto +!px-2.5 +!py-0.5 +!rounded-full +!rounded-xs +!text-sm +!w-2.5 +*:[grid-area:1/1] +*:first:rounded-tl-lg +*:last:rounded-tr-lg +-left-4 +-mb-3 +-ml-4 +-translate-x-full +-translate-y-1/2 +2xl:col-span-1 +2xl:col-span-2 +2xl:col-span-3 +2xl:flex +[animation-duration:0.8s] +[animation-timing-function:ease] +absolute +accordion +accordion-bordered +accordion-toggle +active +active-tab:bg-primary +active-tab:hover:text-primary-content +active-tab:text-base-content +active-tab:text-primary-content +advance-select-menu +advance-select-option +advance-select-tag +advance-select-toggle +alert +alert-error +alert-outline +alert-primary +alert-soft +align-bottom +align-middle +animate-bounce +animate-ping +animate-spin +aria-[current='page']:text-bg-soft-primary +avatar +avatar-away-bottom +avatar-away-top +avatar-busy-bottom +avatar-busy-top +avatar-offline-bottom +avatar-offline-top +avatar-online-bottom +avatar-online-top +avatar-placeholder +badge +badge-error +badge-info +badge-outline +badge-primary +badge-soft +badge-success +bg-background +bg-background/60 +bg-base-100 +bg-base-150 +bg-base-200 +bg-base-200! +bg-base-200/50 +bg-base-200/75 +bg-base-300 +bg-base-300/45 +bg-base-300/50 +bg-base-300/60 +bg-base-content/10 +bg-black +bg-clip-text +bg-error +bg-gradient-to-r +bg-gray-800 +bg-gray-900 +bg-indigo-600 +bg-info +bg-primary +bg-primary/5 +bg-red-500 +bg-success +bg-transparent +bg-warning +bg-white/5 +block +blur +border +border-0 +border-1 +border-2 +border-3 +border-accent +border-b +border-b-2 +border-b-base-content/20 +border-b-primary +border-base-content +border-base-content/10 +border-base-content/20 +border-base-content/25 +border-base-content/40 +border-base-content/5 +border-base-content/60 +border-base-content/70 +border-base-content/80 +border-dashed +border-dotted +border-e-2 +border-error +border-error/30 +border-gray-600 +border-info/30 +border-l-4 +border-l-8 +border-l-transparent +border-primary +border-r-transparent +border-solid +border-success +border-success/30 +border-t +border-t-2 +border-t-transparent +border-transparent +border-warning +border-warning/30 +bottom-0 +bottom-full +breadcrumbs +breadcrumbs-separator +break-words +btn +btn-accent +btn-active +btn-block +btn-circle +btn-disabled +btn-error +btn-gradient +btn-info +btn-lg +btn-outline +btn-primary +btn-secondary +btn-sm +btn-soft +btn-square +btn-success +btn-text +btn-warning +card +card-alert +card-body +card-border +card-footer +card-header +card-sm +card-title +carousel +carousel-body +carousel-next +carousel-prev +carousel-slide +chat +chat-avatar +chat-bubble +chat-footer +chat-header +chat-receiver +chat-sender +checkbox +checkbox-primary +checkbox-xs +col-span-1 +col-span-12 +col-span-2 +col-span-6 +collapse +combo-box-selected:block +combo-box-selected:dropdown-active +complete +container +contents +cursor-default +cursor-not-allowed +cursor-pointer +custom-option +diff +disabled +divide-base-150/60 +divide-y +divider +drop-shadow +dropdown +dropdown-active +dropdown-disabled +dropdown-item +dropdown-menu +dropdown-open:opacity-100 +dropdown-open:rotate-180 +dropdown-toggle +duration-300 +duration-500 +ease-in-out +ease-linear +end-3 +error-message +file-upload-complete:progress-success +fill-base-content +fill-black +fill-gray-200 +filter +filter-reset +fixed +flex +flex-1 +flex-col +flex-grow +flex-nowrap +flex-row +flex-shrink-0 +flex-wrap +focus-visible:outline +focus-visible:outline-2 +focus-visible:outline-indigo-600 +focus-visible:outline-none +focus-visible:outline-offset-2 +focus-within:border-primary +focus:border-primary +focus:outline-1 +focus:outline-none +focus:outline-primary +focus:ring-0 +focus:ring-2 +focus:ring-indigo-600 +focus:ring-inset +font-bold +font-inter +font-medium +font-normal +font-semibold +footer +footer-center +from-base-100 +from-base-100/20 +from-error/20 +from-gray-600/20 +from-primary/20 +from-success/20 +from-violet-400 +from-warning/20 +gap-0.5 +gap-1 +gap-1.5 +gap-2 +gap-3 +gap-4 +gap-5 +gap-6 +gap-x-1 +gap-x-1.5 +gap-x-2 +gap-x-3 +gap-x-5 +gap-x-6 +gap-y-1 +gap-y-1.5 +gap-y-2 +gap-y-2.5 +gap-y-3 +gap-y-4 +gap-y-5 +gap-y-8 +grid +grid-cols-1 +grid-cols-12 +grid-cols-2 +grid-cols-3 +grid-cols-4 +grid-cols-6 +grid-flow-col +grow +grow-0 +h-0 +h-10 +h-12 +h-14 +h-2 +h-3 +h-32 +h-44 +h-6 +h-64 +h-8 +h-[90vh] +h-auto +h-full +h-screen +helper-text +hidden +hover:bg-indigo-500 +hover:bg-primary/20 +hover:bg-primary/5 +hover:bg-transparent +hover:cursor-pointer +hover:text-base-content +hover:text-base-content/60 +hover:text-indigo-500 +hover:text-primary +image-full +indicator +indicator-item +inline +inline-block +inline-flex +inline-grid +input +input-floating +input-floating-label +input-lg +input-md +input-sm +input-xl +input-xs +inset-0 +inset-y-0 +inset-y-2 +invisible +is-invalid +is-valid +isolate +italic +items-center +items-end +items-start +join +join-item +justify-between +justify-center +justify-end +justify-start +justify-stretch +label-text +leading-3 +leading-3.5 +leading-6 +leading-7 +leading-9 +leading-[1.1] +leading-none +left-0 +lg:bg-base-100/20 +lg:flex +lg:gap-y-0 +lg:grid-cols-2 +lg:grid-cols-3 +lg:hidden +lg:justify-end +lg:justify-start +lg:mb-0 +lg:min-w-0 +lg:p-10 +lg:p-8 +lg:pb-5 +lg:pl-64 +lg:pr-3.5 +lg:pt-5 +lg:px-8 +lg:ring-1 +lg:ring-base-content/10 +lg:rounded-lg +lg:shadow-xs +link +link-animated +link-hover +link-primary +list-disc +list-inside +list-none +loading +loading-lg +loading-sm +loading-spinner +loading-xl +loading-xs +lowercase +m-10 +mask +max-h-52 +max-lg:flex-col +max-lg:hidden +max-md:flex-wrap +max-md:justify-center +max-sm:hidden +max-w-2xl +max-w-7xl +max-w-8 +max-w-80 +max-w-full +max-w-lg +max-w-md +max-w-none +max-w-sm +max-w-xl +mb-0.5 +mb-1 +mb-1.5 +mb-2 +mb-2.5 +mb-3 +mb-4 +mb-5 +mb-8 +md:col-span-1 +md:col-span-2 +md:col-span-6 +md:flex +md:gap-x-5 +md:grid-cols-2 +md:grid-cols-3 +md:min-w-md +md:table-cell +md:text-3xl +me-0.5 +me-1 +me-1.5 +me-2 +me-2.5 +me-3 +me-4 +me-5 +menu +menu-active +menu-disabled +menu-dropdown +menu-dropdown-show +menu-focus +menu-horizontal +menu-title +min-h-0 +min-h-full +min-h-screen +min-h-svh +min-w-0 +min-w-28 +min-w-48 +min-w-60 +min-w-[100px] +min-w-full +min-w-sm +mix-blend-exclusion +ml-3 +ml-4 +modal +modal-content +modal-dialog +modal-middle +modal-title +mr-2 +mr-3 +mr-4 +ms-0.5 +ms-1 +ms-1.5 +ms-2 +ms-2.5 +ms-3 +ms-5 +ms-auto +mt-1 +mt-1.5 +mt-10 +mt-12 +mt-2 +mt-2.5 +mt-3 +mt-3.5 +mt-4 +mt-5 +mt-6 +mt-8 +mt-auto +mx-1 +mx-auto +my-2.5 +my-3 +my-5 +my-8 +my-auto +object-cover +opacity-0 +opacity-100 +opacity-75 +open +origin-top-left +outline +outline-0 +overflow-hidden +overflow-x-auto +overflow-x-hidden +overflow-y-auto +overlay-open:duration-50 +overlay-open:opacity-100 +p-0.5 +p-1 +p-1.5 +p-2 +p-2.5 +p-3 +p-4 +p-5 +p-6 +p-8 +pb-1 +pe-1.5 +pin-input +pin-input-underline +placeholder-base-content/50 +placeholder-base-content/60 +placeholder:text-gray-600 +pointer-events-auto +pointer-events-none +progress +progress-bar +progress-indeterminate +progress-primary +pt-0 +pt-0.5 +pt-1.5 +pt-2 +pt-3 +pt-6 +px-1.5 +px-2 +px-2.5 +px-3 +px-4 +px-5 +px-6 +py-0.5 +py-1 +py-1.5 +py-10 +py-12 +py-2 +py-2.5 +py-3 +py-3.5 +py-6 +radial-progress +radio +range +relative +resize +right-4 +ring +ring-0 +ring-1 +ring-gray-700 +ring-inset +ring-white/10 +rounded-box +rounded-field +rounded-full +rounded-l-none +rounded-lg +rounded-md +rounded-none +rounded-r-none +rounded-t-lg +rounded-xl +row-active +row-hover +rtl:!mr-0 +select +select-disabled:opacity-40 +select-disabled:pointer-events-none +select-floating +select-floating-label +select-lg +select-md +select-sm +select-xl +select-xs +selected +selected:select-active +shadow +shadow-base-300/20 +shadow-lg +shadow-md +shadow-sm +shadow-xs +shrink-0 +size-10 +size-12 +size-4 +size-5 +size-7 +size-8 +skeleton +skeleton-animated +sm:auto-cols-max +sm:col-span-2 +sm:col-span-3 +sm:col-span-4 +sm:col-span-6 +sm:flex +sm:flex-nowrap +sm:gap-y-0 +sm:grid-cols-2 +sm:grid-cols-3 +sm:grid-cols-6 +sm:items-center +sm:items-end +sm:justify-between +sm:justify-end +sm:leading-6 +sm:max-w-2xl +sm:max-w-3xl +sm:max-w-4xl +sm:max-w-5xl +sm:max-w-6xl +sm:max-w-7xl +sm:max-w-[480px] +sm:max-w-lg +sm:max-w-md +sm:max-w-xl +sm:mb-0 +sm:min-w-md +sm:mr-3 +sm:mt-5 +sm:mt-6 +sm:mx-auto +sm:p-6 +sm:px-12 +sm:px-6 +sm:py-2 +sm:rounded-lg +sm:text-sm +sm:text-sm/5 +sm:w-1/2 +sm:w-full +space-x-1 +space-x-2 +space-x-2.5 +space-y-1 +space-y-4 +space-y-6 +sr-only +stack +stat +stat-actions +stat-desc +stat-figure +stat-title +stat-value +static +stats +stats-border +status +status-error +status-primary +status-secondary +status-success +status-warning +status-xl +sticky +success-message +switch +switch-primary +tab +tab-active +tab-content +table +table-pin-cols +table-pin-rows +tabs +tabs-bordered +tabs-lg +tabs-lifted +tabs-md +tabs-sm +tabs-vertical +tabs-xl +tabs-xs +text-2xl +text-3xl +text-4xl +text-accent +text-base +text-base-content +text-base-content/40 +text-base-content/50 +text-base-content/60 +text-base-content/70 +text-base-content/80 +text-base-content/90 +text-base/6 +text-center +text-error +text-error-content +text-gray-100 +text-gray-400 +text-gray-500 +text-gray-700 +text-indigo-600 +text-info +text-info-content +text-left +text-lg +text-primary +text-primary-content +text-right +text-slate-100 +text-sm +text-sm/5 +text-success +text-success-content +text-transparent +text-warning +text-warning-content +text-white +text-xl +text-xl! +text-xs +text-xs/5 +textarea +textarea-floating +textarea-floating-label +textarea-lg +textarea-md +textarea-sm +textarea-xl +textarea-xs +theme-controller +to-25% +to-base-100/75 +to-purple-400 +tooltip +tooltip-content +top-0 +top-1/2 +top-4 +top-full +tracking-tight +tracking-wide +transform +transition +transition-all +transition-opacity +translate-x-0 +truncate +underline +uppercase +validate +via-sky-400 +w-0 +w-0.5 +w-12 +w-13 +w-32 +w-4 +w-56 +w-64 +w-8 +w-auto +w-fit +w-full +whitespace-nowrap +xl:grid-cols-3 +xl:grid-cols-4 +z-1 +z-10 +z-40 +z-50 \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Forms/Switch.razor b/MoonlightServers.Frontend/UI/Components/Forms/Switch.razor index d95afef..ed51a23 100644 --- a/MoonlightServers.Frontend/UI/Components/Forms/Switch.razor +++ b/MoonlightServers.Frontend/UI/Components/Forms/Switch.razor @@ -1,5 +1,4 @@ @using System.Diagnostics.CodeAnalysis -@using Microsoft.AspNetCore.Components @* TODO: Extract to mooncore? *@ diff --git a/MoonlightServers.Frontend/UI/Components/FullScreenModal.razor b/MoonlightServers.Frontend/UI/Components/FullScreenModal.razor index da75e29..d782b07 100644 --- a/MoonlightServers.Frontend/UI/Components/FullScreenModal.razor +++ b/MoonlightServers.Frontend/UI/Components/FullScreenModal.razor @@ -1,4 +1,3 @@ -@using System.Text.Json.Serialization @using Microsoft.Extensions.Logging @using XtermBlazor @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal @@ -15,11 +14,11 @@ Addons="Parent.Addons" Options="Parent.Options" Class="h-full w-full" - OnFirstRender="HandleFirstRender"/> + OnFirstRender="HandleFirstRenderAsync"/> }
-
@@ -50,13 +49,13 @@ } // Subscribe to parent events - Parent.OnWrite += HandleWrite; + Parent.OnWrite += HandleWriteAsync; IsInitialized = true; await InvokeAsync(StateHasChanged); } - private async Task HandleFirstRender() + private async Task HandleFirstRenderAsync() { IsReadyToWrite = true; @@ -73,7 +72,7 @@ await Terminal.Write(outputToWrite); } - private async Task HandleWrite(string content) + private async Task HandleWriteAsync(string content) { if (!IsReadyToWrite) return; @@ -83,7 +82,7 @@ public async ValueTask DisposeAsync() { - Parent.OnWrite -= HandleWrite; + Parent.OnWrite -= HandleWriteAsync; await Terminal.DisposeAsync(); } } diff --git a/MoonlightServers.Frontend/UI/Components/Nodes/Modals/CreateAllocationModal.razor b/MoonlightServers.Frontend/UI/Components/Nodes/Modals/CreateAllocationModal.razor index 97255d4..dbbe69a 100644 --- a/MoonlightServers.Frontend/UI/Components/Nodes/Modals/CreateAllocationModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Nodes/Modals/CreateAllocationModal.razor @@ -3,25 +3,38 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Add a new allocation

- - -
-
- - +
+
+
+
+ +
- -
- - +
+

Add a new allocation

+

Add a new allocation to the selected node

- - -
- Cancel - Create +
+ +
+ + +
+
+ + +
+
+
+
+ + + Create + +
@code @@ -42,8 +55,8 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); } diff --git a/MoonlightServers.Frontend/UI/Components/Nodes/Modals/CreateMultipleAllocationModal.razor b/MoonlightServers.Frontend/UI/Components/Nodes/Modals/CreateMultipleAllocationModal.razor index 40c7293..1a06e51 100644 --- a/MoonlightServers.Frontend/UI/Components/Nodes/Modals/CreateMultipleAllocationModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Nodes/Modals/CreateMultipleAllocationModal.razor @@ -3,30 +3,42 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Add a range of new allocations

- - -
-
- - +
+
+
+
+ +
- -
- - -
- -
- - +
+

Add multiple allocations

+

Add a range of new allocations to the selected node

- - -
- Cancel - Create +
+ +
+ + +
+
+ + +
+
+ + +
+
+
+
+ + + Create + +
@code @@ -49,8 +61,8 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Nodes/Modals/UpdateAllocationModal.razor b/MoonlightServers.Frontend/UI/Components/Nodes/Modals/UpdateAllocationModal.razor index a2a6779..1433b81 100644 --- a/MoonlightServers.Frontend/UI/Components/Nodes/Modals/UpdateAllocationModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Nodes/Modals/UpdateAllocationModal.razor @@ -4,25 +4,38 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Update allocation

- - -
-
- - +
+
+
+
+ +
- -
- - +
+

Update allocation

+

Update an existing allocation

- - -
- Cancel - Update +
+ +
+ + +
+
+ + +
+
+
+
+ + + Update + +
@code @@ -45,8 +58,8 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Advanced.razor b/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Advanced.razor index 5a4ae26..a2241ff 100644 --- a/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Advanced.razor +++ b/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Advanced.razor @@ -2,26 +2,7 @@ @using MoonlightServers.Shared.Http.Requests.Admin.Nodes
-
- -
-
- -
-
-
-
- -
-
- -
-
-
+
@code diff --git a/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Allocations.razor b/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Allocations.razor index 0e44a57..6d549ee 100644 --- a/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Allocations.razor +++ b/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Allocations.razor @@ -1,5 +1,6 @@ @using MoonCore.Blazor.FlyonUi.Alerts -@using MoonCore.Blazor.FlyonUi.DataTables +@using MoonCore.Blazor.FlyonUi.Grid +@using MoonCore.Blazor.FlyonUi.Grid.Columns @using MoonCore.Blazor.FlyonUi.Modals @using MoonCore.Blazor.FlyonUi.Toasts @using MoonlightServers.Shared.Http.Responses.Admin.Nodes @@ -22,38 +23,38 @@
- - - + + +
- - - - - - - - - - - - - + + + + + + + + +
@@ -61,84 +62,94 @@ { [Parameter] public NodeResponse Node { get; set; } - private DataTable Table; - - private async Task> LoadData(PaginationOptions options) + private DataGrid Grid; + + private async Task> ItemsProviderAsync( + DataGridItemRequest request + ) { - return await ApiClient.GetJson>( - $"api/admin/servers/nodes/{Node.Id}/allocations?page={options.Page}&pageSize={options.PerPage}" + var query = $"?startIndex={request.StartIndex}&count={request.Count}"; + + var countedData = await ApiClient.GetJson>( + $"api/admin/servers/nodes/{Node.Id}/allocations{query}" ); + + return new() + { + TotalCount = countedData.TotalCount, + Items = countedData.Items + }; } - private async Task AddAllocationRange() + private async Task AddAllocationRangeAsync() { Func onSubmit = async request => { await ApiClient.Post($"api/admin/servers/nodes/{Node.Id}/allocations/range", request); - await ToastService.Success("Successfully created allocations"); - await Table.Refresh(); + await ToastService.SuccessAsync("Successfully created allocations"); + await Grid.RefreshAsync(); }; - await ModalService.Launch(parameters => { parameters.Add("OnSubmit", onSubmit); }); + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); }); } - private async Task AddAllocation() + private async Task AddAllocationAsync() { Func onSubmit = async request => { await ApiClient.Post($"api/admin/servers/nodes/{Node.Id}/allocations", request); - await ToastService.Success("Successfully created allocation"); - await Table.Refresh(); + await ToastService.SuccessAsync("Successfully created allocation"); + await Grid.RefreshAsync(); }; - await ModalService.Launch(parameters => { parameters.Add("OnSubmit", onSubmit); }); + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); }); } - private async Task UpdateAllocation(NodeAllocationResponse allocation) + private async Task UpdateAllocationAsync(NodeAllocationResponse allocation) { Func onSubmit = async request => { await ApiClient.Patch($"api/admin/servers/nodes/{Node.Id}/allocations/{allocation.Id}", request); - await ToastService.Success("Successfully updated allocation"); - await Table.Refresh(); + await ToastService.SuccessAsync("Successfully updated allocation"); + await Grid.RefreshAsync(); }; - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); parameters.Add("Allocation", allocation); }); } - private async Task DeleteAllocation(NodeAllocationResponse allocation) + private async Task DeleteAllocationAsync(NodeAllocationResponse allocation) { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Delete allocation", "Do you really want to delete the selected allocation? This cannot be undone", async () => { await ApiClient.Delete($"api/admin/servers/nodes/{Node.Id}/allocations/{allocation.Id}"); - await ToastService.Success("Successfully deleted allocation"); - await Table.Refresh(); + await ToastService.SuccessAsync("Successfully deleted allocation"); + await Grid.RefreshAsync(); } ); } - private async Task DeleteAllAllocations() + private async Task DeleteAllAllocationsAsync() { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Delete all allocations", "Do you really want to delete all allocations? This cannot be undone", async () => { await ApiClient.Delete($"api/admin/servers/nodes/{Node.Id}/allocations/all"); - await ToastService.Success("Successfully deleted allocations"); - await Table.Refresh(); + await ToastService.SuccessAsync("Successfully deleted allocations"); + await Grid.RefreshAsync(); } ); } diff --git a/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Overview.razor b/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Overview.razor index 2dd9029..1d82c75 100644 --- a/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Overview.razor +++ b/MoonlightServers.Frontend/UI/Components/Nodes/UpdatePartials/Overview.razor @@ -12,7 +12,7 @@ @implements IDisposable - +
Overview @@ -176,27 +176,27 @@ private Timer? UpdateTimer; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { - Statistics = await NodeService.GetStatistics(Node.Id); - DockerStatistics = await NodeService.GetDockerStatistics(Node.Id); + Statistics = await NodeService.GetStatisticsAsync(Node.Id); + DockerStatistics = await NodeService.GetDockerStatisticsAsync(Node.Id); - UpdateTimer = new Timer(HandleUpdate, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3)); + UpdateTimer = new Timer(HandleUpdateAsync, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3)); } - private async void HandleUpdate(object? _) + private async void HandleUpdateAsync(object? _) { try { - Statistics = await NodeService.GetStatistics(Node.Id); - DockerStatistics = await NodeService.GetDockerStatistics(Node.Id); + Statistics = await NodeService.GetStatisticsAsync(Node.Id); + DockerStatistics = await NodeService.GetDockerStatisticsAsync(Node.Id); await InvokeAsync(StateHasChanged); } catch (Exception e) { Logger.LogWarning("An error occured while fetching status update: {e}", e); - await ToastService.Error("Unable to fetch status update", e.Message); + await ToastService.ErrorAsync("Unable to fetch status update", e.Message); } } diff --git a/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Advanced.razor b/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Advanced.razor index 6e5dd40..61872ca 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Advanced.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Advanced.razor @@ -1,27 +1,7 @@ @using MoonlightServers.Shared.Http.Requests.Admin.Servers -@using MoonCore.Blazor.FlyonUi.Components
-
- -
-
- - - -
-
-
- -
- -
- -
-
+
@code diff --git a/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Allocations.razor b/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Allocations.razor index 75dedec..cb276ea 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Allocations.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Allocations.razor @@ -4,7 +4,6 @@ @using MoonlightServers.Shared.Http.Responses.Admin.NodeAllocations @using MoonCore.Blazor.FlyonUi.Forms @using MoonlightServers.Frontend.UI.Views.Admin.All -@using MoonlightServers.Shared.Http.Responses.Admin.Nodes @inject HttpApiClient ApiClient @@ -16,7 +15,7 @@ DisplayField="@(x => $"{x.IpAddress}:{x.Port}")" SearchField="@(x => $"{x.IpAddress}:{x.Port}")" Value="Parent.Allocations" - ItemSource="ItemSource"> + ItemSource="ItemSourceAsync">
@@ -27,16 +26,16 @@ [Parameter] public CreateServerRequest Request { get; set; } [Parameter] public Create Parent { get; set; } - private async Task ItemSource() + private async Task ItemSourceAsync() { // Handle unselected node // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract if (Parent.Node == null) return []; - var items = await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/servers/nodes/{Parent.Node.Id}/allocations/free?page={page}&pageSize={pageSize}" + var items = await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/servers/nodes/{Parent.Node.Id}/allocations/free?startIndex={startIndex}&count={count}" ) ); diff --git a/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/General.razor b/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/General.razor index 5329c3c..fd0121f 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/General.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/General.razor @@ -23,7 +23,7 @@
@@ -35,7 +35,7 @@
@@ -47,7 +47,7 @@
@@ -91,29 +91,29 @@ [Parameter] public CreateServerRequest Request { get; set; } [Parameter] public Create Parent { get; set; } - private async Task LoadStars() + private async Task LoadStarsAsync() { - return await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/servers/stars?page={page}&pageSize={pageSize}" + return await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/servers/stars?startIndex={startIndex}&count={count}" ) ); } - private async Task LoadNodes() + private async Task LoadNodesAsync() { - return await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/servers/nodes?page={page}&pageSize={pageSize}" + return await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/servers/nodes?startIndex={startIndex}&count={count}" ) ); } - private async Task LoadUsers() + private async Task LoadUsersAsync() { - return await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/users?page={page}&pageSize={pageSize}" + return await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/users?startIndex={startIndex}&count={count}" ) ); } diff --git a/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Variables.razor b/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Variables.razor index 0d88743..ae34c01 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Variables.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/CreatePartials/Variables.razor @@ -4,12 +4,11 @@ @using MoonCore.Models @using MoonlightServers.Frontend.UI.Views.Admin.All @using MoonlightServers.Shared.Http.Requests.Admin.ServerVariables -@using MoonlightServers.Shared.Http.Responses.Admin.Stars @using MoonlightServers.Shared.Http.Responses.Admin.StarVariables @inject HttpApiClient ApiClient - +
@foreach (var variable in StarVariables) { @@ -28,7 +27,7 @@ class="input placeholder-base-content/50 w-full" value="@value" placeholder="@variable.DefaultValue" - @onchange="@(args => UpdateValue(variable, args))"/> + @onchange="@(args => UpdateValueAsync(variable, args))"/>

@variable.Description @@ -45,7 +44,7 @@ private StarVariableResponse[] StarVariables; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { if (Parent.Star == null) { @@ -53,14 +52,14 @@ return; } - StarVariables = await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/servers/stars/{Parent.Star.Id}/variables?page={page}&pageSize={pageSize}" + StarVariables = await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/servers/stars/{Parent.Star.Id}/variables?startIndex={startIndex}&count={count}" ) ); } - private async Task UpdateValue(StarVariableResponse starVariable, ChangeEventArgs args) + private async Task UpdateValueAsync(StarVariableResponse starVariable, ChangeEventArgs args) { var value = args.Value?.ToString() ?? ""; diff --git a/MoonlightServers.Frontend/UI/Components/Servers/CreateShareModal.razor b/MoonlightServers.Frontend/UI/Components/Servers/CreateShareModal.razor index 839abe5..be3051e 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/CreateShareModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/CreateShareModal.razor @@ -5,21 +5,37 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

- Create a new share -
- - -
- - +
+
+
+
+ +
+
+
+

Create a new share

+

Grant access to this server to other users

+
+
+
+ +
+ + +
+
+ +
+
+
+
+ + + Create +
- - - -
- Cancel - Create
@code @@ -33,16 +49,6 @@ private Dictionary Permissions = new(); - private string[] Names = - [ - "console", - "power", - "shares", - "files", - "variables", - "settings" - ]; - protected override void OnInitialized() { Request = new() @@ -51,20 +57,20 @@ }; } - private async Task Set(string name, ServerPermissionLevel level) + private async Task SetAsync(string name, ServerPermissionLevel level) { Permissions[name] = level; await InvokeAsync(StateHasChanged); } - private async Task Submit() - => await HandleForm.Submit(); + private async Task SubmitAsync() + => await HandleForm.SubmitAsync(); private async Task OnValidSubmit() { Request.Permissions = Permissions; await OnSubmit.Invoke(Request); - await Hide(); + await HideAsync(); } } diff --git a/MoonlightServers.Frontend/UI/Components/Servers/PermissionEditor.razor b/MoonlightServers.Frontend/UI/Components/Servers/PermissionEditor.razor index 405a40d..286d665 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/PermissionEditor.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/PermissionEditor.razor @@ -6,7 +6,7 @@ @inject IEnumerable PermissionProviders - +
@foreach (var permission in AvailablePermissions) { @@ -30,7 +30,7 @@ } else { - } @@ -43,7 +43,7 @@ } else { - } @@ -56,7 +56,7 @@ } else { - } @@ -73,21 +73,21 @@ private ServerPermission[] AvailablePermissions; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { var permissions = new List(); foreach (var provider in PermissionProviders) { permissions.AddRange( - await provider.GetPermissions(Server) + await provider.GetPermissionsAsync(Server) ); } AvailablePermissions = permissions.ToArray(); } - private async Task Set(string name, ServerPermissionLevel level) + private async Task SetAsync(string name, ServerPermissionLevel level) { PermissionLevels[name] = level; await InvokeAsync(StateHasChanged); diff --git a/MoonlightServers.Frontend/UI/Components/Servers/ServerCard.razor b/MoonlightServers.Frontend/UI/Components/Servers/ServerCard.razor index 587d978..71d5c52 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/ServerCard.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/ServerCard.razor @@ -174,8 +174,8 @@ try { - Status = await ServerService.GetStatus(Server.Id); - Stats = await ServerService.GetStats(Server.Id); + Status = await ServerService.GetStatusAsync(Server.Id); + Stats = await ServerService.GetStatsAsync(Server.Id); } catch (Exception e) { diff --git a/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/ConsoleTab.razor b/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/ConsoleTab.razor index d88e8ba..cd59b71 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/ConsoleTab.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/ConsoleTab.razor @@ -23,7 +23,7 @@ HubConnection.On("ConsoleOutput", async content => { if (XtermConsole != null) - await XtermConsole.Write(content); + await XtermConsole.WriteAsync(content); }); return Task.CompletedTask; @@ -31,9 +31,9 @@ private async Task OnAfterConsoleInitialized() { - await XtermConsole!.Write(InitialConsoleMessage); + await XtermConsole!.WriteAsync(InitialConsoleMessage); } private async Task OnCommand(string command) - => await ServerService.RunCommand(Server.Id, command + "\n"); + => await ServerService.RunCommandAsync(Server.Id, command + "\n"); } diff --git a/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/SettingsTab.razor b/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/SettingsTab.razor index 65ebf9e..8cacfc8 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/SettingsTab.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/SettingsTab.razor @@ -19,7 +19,7 @@ } else { - + Reinstall @@ -29,12 +29,12 @@ @code { - private async Task Reinstall(WButton _) + private async Task ReinstallAsync(WButton _) { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Server installation", "Do you really want to reinstall the server? This can potentially lead to loss of data", - () => ServerService.Install(Server.Id) + () => ServerService.InstallAsync(Server.Id) ); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/SharesTab.razor b/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/SharesTab.razor index 88dc272..08f995b 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/SharesTab.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/SharesTab.razor @@ -16,13 +16,13 @@
-
- + @if (Shares.Length == 0) { @@ -40,11 +40,11 @@ @share.Username
- + Edit - + Delete @@ -63,60 +63,60 @@ private LazyLoader LazyLoader; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { - Shares = await PagedData.All(async (page, pageSize) - => await ShareService.Get(Server.Id, page, pageSize) + Shares = await CountedData.LoadAllAsync(async (startIndex, count) + => await ShareService.GetAsync(Server.Id, startIndex, count) ); } - private async Task OpenCreateModal() + private async Task OpenCreateModalAsync() { - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters["Username"] = UsernameInput; parameters["Server"] = Server; - parameters["OnSubmit"] = SubmitCreate; + parameters["OnSubmit"] = SubmitCreateAsync; }, size: "max-w-2xl"); } - private async Task SubmitCreate(CreateShareRequest request) + private async Task SubmitCreateAsync(CreateShareRequest request) { - await ShareService.Create(Server.Id, request); + await ShareService.CreateAsync(Server.Id, request); - await ToastService.Success("Share successfully created"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Share successfully created"); + await LazyLoader.ReloadAsync(); } - private async Task OpenUpdateModal(ServerShareResponse share) + private async Task OpenUpdateModalAsync(ServerShareResponse share) { - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters["Share"] = share; parameters["Server"] = Server; - parameters["OnSubmit"] = (UpdateShareRequest request) => SubmitUpdate(share.Id, request); + parameters["OnSubmit"] = (UpdateShareRequest request) => SubmitUpdateAsync(share.Id, request); }, size: "max-w-2xl"); } - private async Task SubmitUpdate(int shareId, UpdateShareRequest request) + private async Task SubmitUpdateAsync(int shareId, UpdateShareRequest request) { - await ShareService.Update(Server.Id, shareId, request); + await ShareService.UpdateAsync(Server.Id, shareId, request); - await ToastService.Success("Share successfully updated"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Share successfully updated"); + await LazyLoader.ReloadAsync(); } - private async Task Delete(ServerShareResponse share) + private async Task DeleteAsync(ServerShareResponse share) { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Share deletion", $"Do you really want to delete the share for the user '{share.Username}'? This cannot be undone", async () => { - await ShareService.Delete(Server.Id, share.Id); + await ShareService.DeleteAsync(Server.Id, share.Id); - await ToastService.Success("Successfully deleted share"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Successfully deleted share"); + await LazyLoader.ReloadAsync(); } ); } diff --git a/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/VariablesTab.razor b/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/VariablesTab.razor index 842191b..06f0232 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/VariablesTab.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/ServerTabs/VariablesTab.razor @@ -9,7 +9,7 @@ @inject ServerService ServerService @inject ToastService ToastService - +
@foreach (var variable in Variables) { @@ -24,7 +24,7 @@ @variable.Description

- @@ -40,26 +40,26 @@ private ServerVariableDetailResponse[] Variables; private LazyLoader LazyLoader; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { - Variables = await PagedData.All(async (page, pageSize) - => await ServerService.GetVariables(Server.Id, page, pageSize) + Variables = await CountedData.LoadAllAsync(async (startIndex, count) + => await ServerService.GetVariablesAsync(Server.Id, startIndex, count) ); } - private async Task UpdateVariable(ServerVariableDetailResponse variable, ChangeEventArgs args) + private async Task UpdateVariableAsync(ServerVariableDetailResponse variable, ChangeEventArgs args) { var value = args.Value?.ToString() ?? ""; - await ServerService.UpdateVariable(Server.Id, new() + await ServerService.UpdateVariableAsync(Server.Id, new() { Key = variable.Key, Value = value }); // Fetch the current data to make sure the user sees the latest data - await LazyLoader.Reload(); + await LazyLoader.ReloadAsync(); - await ToastService.Success("Successfully updated variable"); + await ToastService.SuccessAsync("Successfully updated variable"); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Advanced.razor b/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Advanced.razor index 937d67f..9b5b879 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Advanced.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Advanced.razor @@ -1,12 +1,6 @@ @using MoonlightServers.Shared.Http.Requests.Admin.Servers
-
- -
- -
-
@code diff --git a/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Allocations.razor b/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Allocations.razor index 4100af5..0ac3e92 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Allocations.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Allocations.razor @@ -16,7 +16,7 @@ Value="Parent.Allocations" DisplayField="@(x => $"{x.IpAddress}:{x.Port}")" SearchField="@(x => $"{x.IpAddress}:{x.Port}")" - ItemSource="Loader"> + ItemSource="LoaderAsync">
@@ -28,11 +28,11 @@ [Parameter] public ServerResponse Server { get; set; } [Parameter] public Update Parent { get; set; } - private async Task Loader() + private async Task LoaderAsync() { - return await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/servers/nodes/{Server.NodeId}/allocations/free?page={page}&pageSize={pageSize}&serverId={Server.Id}" + return await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/servers/nodes/{Server.NodeId}/allocations/free?startIndex={startIndex}&count={count}&serverId={Server.Id}" ) ); } diff --git a/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/General.razor b/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/General.razor index 8085cd2..85393ee 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/General.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/General.razor @@ -22,7 +22,7 @@ DisplayField="@(x => x.Username)" SearchField="@(x => x.Username)" @bind-Value="Parent.Owner" - ItemSource="Loader"> + ItemSource="LoaderAsync">
@@ -64,11 +64,11 @@ [Parameter] public UpdateServerRequest Request { get; set; } [Parameter] public Update Parent { get; set; } - private async Task Loader() + private async Task LoaderAsync() { - return await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/users?page={page}&pageSize={pageSize}" + return await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/users?startIndex={startIndex}&count={count}" ) ); } diff --git a/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Variables.razor b/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Variables.razor index 4b18578..6f45404 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Variables.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/UpdatePartials/Variables.razor @@ -9,7 +9,7 @@ @inject HttpApiClient ApiClient - +
@foreach (var variable in ServerVariables) { @@ -30,7 +30,7 @@
+ @onchange="@(args => UpdateValueAsync(variable, args))"/>

@starVariable.Description @@ -48,22 +48,22 @@ private StarVariableResponse[] StarVariables; private ServerVariableResponse[] ServerVariables; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { - StarVariables = await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/servers/stars/{Server.StarId}/variables?page={page}&pageSize={pageSize}" + StarVariables = await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/servers/stars/{Server.StarId}/variables?startIndex={startIndex}&count={count}" ) ); - ServerVariables = await PagedData.All(async (page, pageSize) => - await ApiClient.GetJson>( - $"api/admin/servers/{Server.Id}/variables?page={page}&pageSize={pageSize}" + ServerVariables = await CountedData.LoadAllAsync(async (startIndex, count) => + await ApiClient.GetJson>( + $"api/admin/servers/{Server.Id}/variables?startIndex={startIndex}&count={count}" ) ); } - private async Task UpdateValue(ServerVariableResponse serverVariable, ChangeEventArgs args) + private async Task UpdateValueAsync(ServerVariableResponse serverVariable, ChangeEventArgs args) { var value = args.Value?.ToString() ?? ""; diff --git a/MoonlightServers.Frontend/UI/Components/Servers/UpdateShareModal.razor b/MoonlightServers.Frontend/UI/Components/Servers/UpdateShareModal.razor index a080f7d..baeecd2 100644 --- a/MoonlightServers.Frontend/UI/Components/Servers/UpdateShareModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Servers/UpdateShareModal.razor @@ -3,21 +3,34 @@ @using MoonlightServers.Shared.Http.Requests.Client.Servers.Shares @using MoonlightServers.Shared.Http.Responses.Client.Servers @using MoonlightServers.Shared.Http.Responses.Client.Servers.Shares -@using MoonlightServers.Shared.Models @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

- Update share for @Share.Username -
- - - - - -
- Cancel - Update +
+
+
+
+ +
+
+
+

Update share for @Share.Username

+

Grant access to this server to other users

+
+
+
+ + + +
+
+ + + Create + +
@code @@ -31,16 +44,6 @@ private Dictionary Permissions = new(); - private string[] Names = - [ - "console", - "power", - "shares", - "files", - "variables", - "settings" - ]; - protected override void OnInitialized() { Request = new(); @@ -48,20 +51,20 @@ Permissions = Share.Permissions; } - private async Task Set(string name, ServerPermissionLevel level) + private async Task SetAsync(string name, ServerPermissionLevel level) { Permissions[name] = level; await InvokeAsync(StateHasChanged); } - private async Task Submit() - => await HandleForm.Submit(); + private async Task SubmitAsync() + => await HandleForm.SubmitAsync(); private async Task OnValidSubmit() { Request.Permissions = Permissions; await OnSubmit.Invoke(Request); - await Hide(); + await HideAsync(); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateDockerImageModal.razor b/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateDockerImageModal.razor index 8ad225e..0b583fe 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateDockerImageModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateDockerImageModal.razor @@ -4,30 +4,42 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Add a new variable

- - -
-
- - +
+
+
+
+ +
- -
- - -
- -
- - +
+

Add a new docker image

+

Add a new docker image to the star

- - -
- Cancel - Create +
+ +
+ + +
+
+ + +
+
+ + +
+
+
+
+ + + Create + +
@code @@ -49,8 +61,8 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateParseConfigModal.razor b/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateParseConfigModal.razor index d8b1d75..55dcd63 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateParseConfigModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateParseConfigModal.razor @@ -4,47 +4,57 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Add a new parse configuration

- - -
-
- - +
+
+
+
+ +
- -
- - +
+

Add a parse configuration

+

Add a new parse configuration to the star

- -
- -
- - @foreach (var entry in Form.Entries) - { -
-
+
+
+ +
+ + +
+
+ + +
+
+ +
+ + @foreach (var entry in Form.Entries) + { +
-
-
- } + } + +
+
+ + + Create +
- - -
- Cancel - Create
@code @@ -57,20 +67,20 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); - private async Task AddEntry() + private async Task AddEntryAsync() { Form.Entries.Add(new()); await InvokeAsync(StateHasChanged); } - private async Task RemoveEntry(ParseConfiguration.ParseConfigurationEntry entry) + private async Task RemoveEntryAsync(ParseConfiguration.ParseConfigurationEntry entry) { Form.Entries.Remove(entry); await InvokeAsync(StateHasChanged); } -} +} \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateVariableModal.razor b/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateVariableModal.razor index 0dc504d..132f0a0 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateVariableModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/Modals/CreateVariableModal.razor @@ -5,60 +5,76 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Add a new variable

- - -
-
- - +
+
+
+
+ +
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - +
+

Add a new variable

+

Add a new variable to the star

- +
+ +
+
+ + +
-
- Cancel - Create +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+
+ + + Create + +
@code @@ -71,8 +87,8 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); } diff --git a/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateDockerImageModal.razor b/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateDockerImageModal.razor index 3b91fb4..a17e8f7 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateDockerImageModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateDockerImageModal.razor @@ -5,30 +5,42 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Update variable

- - -
-
- - +
+
+
+
+ +
- -
- - -
- -
- - +
+

Update docker image

+

Update docker image properties

- - -
- Cancel - Update +
+ +
+ + +
+
+ + +
+
+ + +
+
+
+
+ + + Update + +
@code @@ -52,8 +64,8 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateParseConfigModal.razor b/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateParseConfigModal.razor index 51b3805..f70e71c 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateParseConfigModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateParseConfigModal.razor @@ -4,46 +4,57 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Update parse configuration

- - -
-
- - +
+
+
+
+ +
- -
- - +
+

Update parse configuration

+

Update parse configuration properties

- -
- -
- - @foreach (var entry in Form.Entries) - { -
-
+
+
+ +
+ + +
+
+ + +
+
+ +
+ + @foreach (var entry in Form.Entries) + { +
-
-
- } + } + +
+
+ + + Update +
- - -
- Save changes
@code @@ -63,18 +74,18 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); - private async Task AddEntry() + private async Task AddEntryAsync() { Form.Entries.Add(new()); await InvokeAsync(StateHasChanged); } - private async Task RemoveEntry(ParseConfiguration.ParseConfigurationEntry entry) + private async Task RemoveEntryAsync(ParseConfiguration.ParseConfigurationEntry entry) { Form.Entries.Remove(entry); await InvokeAsync(StateHasChanged); diff --git a/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateVariableModal.razor b/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateVariableModal.razor index 045ef98..56ac0a2 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateVariableModal.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/Modals/UpdateVariableModal.razor @@ -6,60 +6,76 @@ @inherits MoonCore.Blazor.FlyonUi.Modals.Components.BaseModal -

Update variable

- - -
-
- - +
+
+
+
+ +
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - +
+

Update variable

+

Update variable properties

- +
+ +
+
+ + +
-
- Cancel - Update +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+
+ + + Update + +
@code @@ -88,8 +104,8 @@ private async Task OnValidSubmit() { await OnSubmit.Invoke(Form); - await Hide(); + await HideAsync(); } - private Task Submit() => HandleForm.Submit(); + private Task SubmitAsync() => HandleForm.SubmitAsync(); } diff --git a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/DockerImage.razor b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/DockerImage.razor index 5581225..a617630 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/DockerImage.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/DockerImage.razor @@ -14,9 +14,9 @@ @inject ToastService ToastService @inject AlertService AlertService - +
- +
@@ -30,11 +30,11 @@
- -
@@ -51,59 +51,61 @@ private StarDockerImageResponse[] DockerImages; private LazyLoader LazyLoader; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { - var pagedVariables = await ApiClient.GetJson>( - $"api/admin/servers/stars/{Star.Id}/dockerImages?page=0&pageSize=50" + var pagedVariables = await ApiClient.GetJson>( + $"api/admin/servers/stars/{Star.Id}/dockerImages?startIndex=0&count=100" ); + // TODO: Improve paged stuff + DockerImages = pagedVariables.Items; } - private async Task AddDockerImage() + private async Task AddDockerImageAsync() { Func onSubmit = async request => { await ApiClient.Post($"api/admin/servers/stars/{Star.Id}/dockerImages", request); - await ToastService.Success("Successfully created docker image"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Successfully created docker image"); + await LazyLoader.ReloadAsync(); }; - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); }); } - private async Task UpdateDockerImage(StarDockerImageResponse dockerImage) + private async Task UpdateDockerImageAsync(StarDockerImageResponse dockerImage) { Func onSubmit = async request => { await ApiClient.Patch($"api/admin/servers/stars/{Star.Id}/dockerImages/{dockerImage.Id}", request); - await ToastService.Success("Successfully updated docker image"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Successfully updated docker image"); + await LazyLoader.ReloadAsync(); }; - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); parameters.Add("DockerImage", dockerImage); }); } - private async Task DeleteDockerImage(StarDockerImageResponse dockerImage) + private async Task DeleteDockerImageAsync(StarDockerImageResponse dockerImage) { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Delete docker image", "Do you really want to delete the selected docker image? This cannot be undone", async () => { await ApiClient.Delete($"api/admin/servers/stars/{Star.Id}/dockerImages/{dockerImage.Id}"); - await ToastService.Success("Successfully deleted docker image"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Successfully deleted docker image"); + await LazyLoader.ReloadAsync(); } ); } diff --git a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Installation.razor b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Installation.razor index 0ddc3a2..ee23d2f 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Installation.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Installation.razor @@ -37,6 +37,6 @@ private async Task OnFocusOut() { - Request.InstallScript = await CodeEditor.GetValue(); + Request.InstallScript = await CodeEditor.GetValueAsync(); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Misc.razor b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Misc.razor index 924650b..495598e 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Misc.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Misc.razor @@ -8,7 +8,7 @@ @inject HttpApiClient ApiClient - +
@@ -53,11 +53,13 @@ private List DockerImages; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { - var pagedVariables = await ApiClient.GetJson>( - $"api/admin/servers/stars/{Star.Id}/dockerImages?page=0&pageSize=50" + var pagedVariables = await ApiClient.GetJson>( + $"api/admin/servers/stars/{Star.Id}/dockerImages?startIndex=0&count=100" ); + + // TODO: Fix this DockerImages = pagedVariables .Items diff --git a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/ParseConfig.razor b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/ParseConfig.razor index f7a1243..0180506 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/ParseConfig.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/ParseConfig.razor @@ -13,7 +13,7 @@ @inject ToastService ToastService
- +
@if (HasParseError) @@ -33,11 +33,11 @@ else
- -
@@ -60,7 +60,7 @@ else return Task.CompletedTask; } - private async Task AddConfig() + private async Task AddConfigAsync() { Func onSubmit = async configuration => { @@ -68,35 +68,35 @@ else SaveChanges(); await InvokeAsync(StateHasChanged); - await ToastService.Success("Successfully created parse configuration"); + await ToastService.SuccessAsync("Successfully created parse configuration"); }; - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); }, "max-w-xl"); } - private async Task UpdateConfig(ParseConfiguration configuration) + private async Task UpdateConfigAsync(ParseConfiguration configuration) { Func onSubmit = async _ => { SaveChanges(); await InvokeAsync(StateHasChanged); - await ToastService.Success("Successfully updated parse configuration"); + await ToastService.SuccessAsync("Successfully updated parse configuration"); }; - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); parameters.Add("Configuration", configuration); }, "max-w-xl"); } - private async Task DeleteConfig(ParseConfiguration configuration) + private async Task DeleteConfigAsync(ParseConfiguration configuration) { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Parse configuration deletion", "Do you really want to delete the selected parse configuration", async () => @@ -105,7 +105,7 @@ else SaveChanges(); await InvokeAsync(StateHasChanged); - await ToastService.Success("Successfully deleted parse configuration"); + await ToastService.SuccessAsync("Successfully deleted parse configuration"); } ); } diff --git a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Variables.razor b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Variables.razor index 41619a0..383898b 100644 --- a/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Variables.razor +++ b/MoonlightServers.Frontend/UI/Components/Stars/UpdatePartials/Variables.razor @@ -15,10 +15,10 @@ @inject ToastService ToastService
- +
- +
@foreach (var variable in CurrentVariables) { @@ -30,11 +30,11 @@
- -
@@ -51,59 +51,59 @@ private StarVariableResponse[] CurrentVariables; private LazyLoader LazyLoader; - private async Task Load(LazyLoader arg) + private async Task LoadAsync(LazyLoader arg) { - var pagedVariables = await ApiClient.GetJson>( - $"api/admin/servers/stars/{Star.Id}/variables?page=0&pageSize=50" + var pagedVariables = await ApiClient.GetJson>( + $"api/admin/servers/stars/{Star.Id}/variables?startIndex=0&count=100" ); CurrentVariables = pagedVariables.Items; } - private async Task AddVariable() + private async Task AddVariableAsync() { Func onSubmit = async request => { await ApiClient.Post($"api/admin/servers/stars/{Star.Id}/variables", request); - await ToastService.Success("Successfully created variable"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Successfully created variable"); + await LazyLoader.ReloadAsync(); }; - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); }, "max-w-xl"); } - private async Task UpdateVariable(StarVariableResponse variable) + private async Task UpdateVariableAsync(StarVariableResponse variable) { Func onSubmit = async request => { await ApiClient.Patch($"api/admin/servers/stars/{Star.Id}/variables/{variable.Id}", request); - await ToastService.Success("Successfully updated variable"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Successfully updated variable"); + await LazyLoader.ReloadAsync(); }; - await ModalService.Launch(parameters => + await ModalService.LaunchAsync(parameters => { parameters.Add("OnSubmit", onSubmit); parameters.Add("Variable", variable); }, "max-w-xl"); } - private async Task DeleteVariable(StarVariableResponse variable) + private async Task DeleteVariableAsync(StarVariableResponse variable) { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Delete variable", "Do you really want to delete the selected variable? This cannot be undone", async () => { await ApiClient.Delete($"api/admin/servers/stars/{Star.Id}/variables/{variable.Id}"); - await ToastService.Success("Successfully deleted variable"); - await LazyLoader.Reload(); + await ToastService.SuccessAsync("Successfully deleted variable"); + await LazyLoader.ReloadAsync(); } ); } diff --git a/MoonlightServers.Frontend/UI/Components/XtermConsole.razor b/MoonlightServers.Frontend/UI/Components/XtermConsole.razor index 0853d3b..2b9a124 100644 --- a/MoonlightServers.Frontend/UI/Components/XtermConsole.razor +++ b/MoonlightServers.Frontend/UI/Components/XtermConsole.razor @@ -1,4 +1,3 @@ -@using System.Collections.Concurrent @using Microsoft.Extensions.Logging @using MoonCore.Blazor.FlyonUi.Modals @using MoonCore.Helpers @@ -18,12 +17,12 @@ Addons="Addons" Options="Options" Class="h-full w-full" - OnFirstRender="HandleFirstRender"/> + OnFirstRender="HandleFirstRenderAsync"/> }
- - + +
@@ -32,18 +31,18 @@
@if (IsPaused) { - } else { - } -
@@ -110,7 +109,7 @@ await OnAfterInitialized.Invoke(); } - private async Task HandleFirstRender() + private async Task HandleFirstRenderAsync() { try { @@ -133,17 +132,17 @@ await OnFirstRender.Invoke(); } - public async Task Write(string content) + public async Task WriteAsync(string content) { // We cache messages here as there is the chance that the console isn't ready for input while receiving write tasks if (IsReadyToWrite && !IsPaused) - await HandleWrite(content); + await HandleWriteAsync(content); else WriteQueue.Add(content); } - private async Task HandleWrite(string content) + private async Task HandleWriteAsync(string content) { // Update output cache and prune it if required if (OutputCache.Count > MaxOutputCacheSize) @@ -162,12 +161,12 @@ await Terminal.Write(content); } - private async Task OpenFullscreen() + private async Task OpenFullscreenAsync() { - await ModalService.Launch(parameters => { parameters["Parent"] = this; }, size: "max-w-none"); + await ModalService.LaunchAsync(parameters => { parameters["Parent"] = this; }, size: "max-w-none"); } - private async Task TogglePause() + private async Task TogglePauseAsync() { IsPaused = !IsPaused; await InvokeAsync(StateHasChanged); @@ -178,10 +177,10 @@ var queueContent = string.Concat(WriteQueue); WriteQueue.Clear(); - await HandleWrite(queueContent); + await HandleWriteAsync(queueContent); } - private async Task SubmitCommand() + private async Task SubmitCommandAsync() { CommandHistory.Add(CommandInput); @@ -194,12 +193,12 @@ await InvokeAsync(StateHasChanged); } - private async Task HandleKey(KeyboardEventArgs keyboard) + private async Task HandleKeyAsync(KeyboardEventArgs keyboard) { switch (keyboard.Code) { case "Enter": - await SubmitCommand(); + await SubmitCommandAsync(); break; case "ArrowUp" or "ArrowDown": diff --git a/MoonlightServers.Frontend/UI/Views/Admin/All/Create.razor b/MoonlightServers.Frontend/UI/Views/Admin/All/Create.razor index 224419a..9be37f7 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/All/Create.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/All/Create.razor @@ -21,7 +21,7 @@ Back - + Create @@ -73,7 +73,7 @@ await ApiClient.Post("api/admin/servers", Request); - await ToastService.Success("Successfully created Server"); + await ToastService.SuccessAsync("Successfully created Server"); Navigation.NavigateTo("/admin/servers/all"); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Admin/All/Index.razor b/MoonlightServers.Frontend/UI/Views/Admin/All/Index.razor index 1bc51d2..98933d8 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/All/Index.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/All/Index.razor @@ -1,7 +1,6 @@ @page "/admin/servers/all" @using MoonCore.Blazor.FlyonUi.Alerts -@using MoonCore.Blazor.FlyonUi.DataTables @using MoonCore.Blazor.FlyonUi.Toasts @using MoonCore.Helpers @using MoonCore.Models @@ -9,6 +8,9 @@ @using MoonlightServers.Shared.Http.Responses.Admin.Servers @using MoonlightServers.Shared.Http.Responses.Admin.Stars @using MoonCore.Blazor.FlyonUi.Components +@using MoonCore.Blazor.FlyonUi.Grid +@using MoonCore.Blazor.FlyonUi.Grid.Columns +@using Moonlight.Shared.Http.Responses.Admin.Users @inject HttpApiClient ApiClient @inject AlertService AlertService @@ -28,98 +30,136 @@
- - - - - - - - - @context.Name + + + + + + @context.Name + + + + + + @{ + var owner = Users.GetValueOrDefault(context.OwnerId); + } + + + @(owner?.Username ?? "N/A") + + + + + + @{ + var node = Nodes.GetValueOrDefault(context.NodeId); + } + + + @(node?.Name ?? "N/A") + + + + + + @{ + var star = Stars.GetValueOrDefault(context.StarId); + } + + + @(star?.Name ?? "N/A") + + + + + +
+ + - - - - - @{ - var node = Nodes.FirstOrDefault(x => x.Id == context.NodeId); - } - - @(node?.Name ?? "N/A") - - - - - - @{ - var star = Stars.FirstOrDefault(x => x.Id == context.StarId); - } - - - @(star?.Name ?? "N/A") - - - - - -
- - - - - - - -
-
-
- - + + + +
+ +
+ @code { - private DataTable Table; - - private List Stars = new(); - private List Nodes = new(); + private DataGrid Grid; - private async Task> LoadData(PaginationOptions options) + private Dictionary Stars = new(); + private Dictionary Nodes = new(); + private Dictionary Users = new(); + + private async Task> ItemsProviderAsync( + DataGridItemRequest request + ) { - // Clear potential previous data - var data = await ApiClient.GetJson>($"api/admin/servers?page={options.Page}&pageSize={options.PerPage}"); + var query = $"?startIndex={request.StartIndex}&count={request.Count}"; - foreach (var item in data.Items) + var countedData = await ApiClient.GetJson>($"api/admin/servers{query}"); + + // Fetch relations + + var nodesToFetch = countedData.Items + .Where(x => !Nodes.ContainsKey(x.Id)) + .Select(x => x.Id) + .Distinct(); + + foreach (var id in nodesToFetch) { - if (Nodes.All(x => x.Id != item.NodeId)) - { - var node = await ApiClient.GetJson($"api/admin/servers/nodes/{item.NodeId}"); - Nodes.Add(node); - } - - if (Stars.All(x => x.Id != item.StarId)) - { - var star = await ApiClient.GetJson($"api/admin/servers/stars/{item.StarId}"); - Stars.Add(star); - } + var node = await ApiClient.GetJson($"api/admin/servers/nodes/{id}"); + Nodes[node.Id] = node; } - return data; + var starsToFetch = countedData.Items + .Where(x => !Stars.ContainsKey(x.Id)) + .Select(x => x.Id) + .Distinct(); + + foreach (var id in starsToFetch) + { + var star = await ApiClient.GetJson($"api/admin/servers/stars/{id}"); + Stars[star.Id] = star; + } + + var usersToFetch = countedData.Items + .Where(x => !Users.ContainsKey(x.Id)) + .Select(x => x.Id) + .Distinct(); + + foreach (var id in usersToFetch) + { + var user = await ApiClient.GetJson($"api/admin/users/{id}"); + Users[user.Id] = user; + } + + return new() + { + Items = countedData.Items, + TotalCount = countedData.TotalCount + }; } - - private async Task Delete(ServerResponse response) + + private async Task DeleteAsync(ServerResponse response) { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Server deletion", $"Do you really want to delete the server '{response.Name}'", async () => { await ApiClient.Delete($"api/admin/servers/{response.Id}"); - await ToastService.Success("Successfully deleted server"); + await ToastService.SuccessAsync("Successfully deleted server"); - await Table.Refresh(); + await Grid.RefreshAsync(); } ); } diff --git a/MoonlightServers.Frontend/UI/Views/Admin/All/Update.razor b/MoonlightServers.Frontend/UI/Views/Admin/All/Update.razor index 89f01e3..7dc0297 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/All/Update.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/All/Update.razor @@ -15,13 +15,13 @@ @attribute [Authorize(Policy = "permissions:admin.servers.update")] - + Back - + Update @@ -58,7 +58,7 @@ public List Allocations = new(); public UserResponse Owner; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { Server = await ApiClient.GetJson($"api/admin/servers/{Id}"); @@ -67,7 +67,6 @@ Name = Server.Name, AllocationIds = Server.AllocationIds, OwnerId = Server.OwnerId, - Bandwidth = Server.Bandwidth, Cpu = Server.Cpu, Disk = Server.Disk, DockerImageIndex = Server.DockerImageIndex, @@ -96,7 +95,7 @@ await ApiClient.Patch($"api/admin/servers/{Id}", Request); - await ToastService.Success("Successfully updated server"); + await ToastService.SuccessAsync("Successfully updated server"); Navigation.NavigateTo("/admin/servers/all"); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Create.razor b/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Create.razor index 57c0747..86ef049 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Create.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Create.razor @@ -16,7 +16,7 @@ Back - + Create @@ -71,7 +71,7 @@ TODO: EnableTransparentMode, EnableDynamicFirewall { await ApiClient.Post("api/admin/servers/nodes", Request); - await ToastService.Success("Successfully created node"); + await ToastService.SuccessAsync("Successfully created node"); Navigation.NavigateTo("/admin/servers/nodes"); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Index.razor b/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Index.razor index 4552719..84de7f0 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Index.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Index.razor @@ -2,7 +2,6 @@ @using Microsoft.Extensions.Logging @using MoonCore.Blazor.FlyonUi.Alerts -@using MoonCore.Blazor.FlyonUi.DataTables @using MoonCore.Blazor.FlyonUi.Toasts @using MoonCore.Helpers @using MoonCore.Models @@ -11,6 +10,8 @@ @using MoonlightServers.Shared.Http.Responses.Admin.Nodes.Statistics @using MoonlightServers.Shared.Http.Responses.Admin.Nodes.Sys @using MoonCore.Blazor.FlyonUi.Components +@using MoonCore.Blazor.FlyonUi.Grid +@using MoonCore.Blazor.FlyonUi.Grid.Columns @inject HttpApiClient ApiClient @inject NodeService NodeService @@ -32,153 +33,151 @@
- - - + + + + + + @context.Name + + + + + + + @{ + var isFetched = StatusResponses.TryGetValue(context.Id, out var data); + } - - - - - @context.Name - - - - - - - @{ - var isFetched = StatusResponses.TryGetValue(context.Id, out var data); - } - - @if (isFetched) + @if (isFetched) + { + if (data == null) { - if (data == null) +
+ + + API Error + +
+ } + else + { + if (data.RoundtripSuccess) + { +
+ + Online (@(data.Version)) +
+ } + else {
- - API Error + + Error -
- } - else - { - if (data.RoundtripSuccess) - { -
- - Online (@(data.Version)) -
- } - else - { -
- - - Error - - Details -
- } - } - } - else - { -
- - Loading -
- } -
-
- - - @{ - var isFetched = Statistics.TryGetValue(context.Id, out var data); - } - - @if (isFetched) - { - if (data == null) - { -
- - - API Error - -
- } - else - { -
-
- - @(Math.Round(data.Cpu.Usage))% -
- -
- - - @(Math.Round((data.Memory.Total - data.Memory.Free - data.Memory.Cached) / (double)data.Memory.Total * 100))% - -
+ Details
} } - else - { -
- - Loading -
- } -
-
- - -
- - - - - - - + } + else + { +
+ + Loading
- - - - + } + + + + + @{ + var isFetched = Statistics.TryGetValue(context.Id, out var data); + } + + @if (isFetched) + { + if (data == null) + { +
+ + + API Error + +
+ } + else + { +
+
+ + @(Math.Round(data.Cpu.Usage))% +
+ +
+ + + @(Math.Round((data.Memory.Total - data.Memory.Free - data.Memory.Cached) / (double)data.Memory.Total * 100))% + +
+
+ } + } + else + { +
+ + Loading +
+ } + +
+ + +
+ + + + + + + +
+ +
+ @code { - private DataTable Table; + private DataGrid Grid; private Dictionary StatusResponses = new(); private Dictionary Statistics = new(); - - private async Task> LoadData(PaginationOptions options) + + private async Task> ItemsProviderAsync( + DataGridItemRequest request + ) { + var query = $"?startIndex={request.StartIndex}&count={request.Count}"; + + var countedData = await ApiClient.GetJson>($"api/admin/servers/nodes{query}"); + Statistics.Clear(); StatusResponses.Clear(); - - var result = await ApiClient.GetJson>( - $"api/admin/servers/nodes?page={options.Page}&pageSize={options.PerPage}" - ); - + Task.Run(async () => { - foreach (var item in result.Items) + foreach (var item in countedData.Items) { try { - Statistics[item.Id] = await NodeService.GetStatistics(item.Id); + Statistics[item.Id] = await NodeService.GetStatisticsAsync(item.Id); } catch (Exception e) { @@ -192,10 +191,10 @@ } await InvokeAsync(StateHasChanged); - + try { - StatusResponses[item.Id] = await NodeService.GetSystemStatus(item.Id); + StatusResponses[item.Id] = await NodeService.GetSystemStatusAsync(item.Id); } catch (Exception e) { @@ -207,30 +206,34 @@ StatusResponses[item.Id] = null; } - + await InvokeAsync(StateHasChanged); } }); - - return result; + + return new() + { + Items = countedData.Items, + TotalCount = countedData.TotalCount + }; } - private async Task Delete(NodeResponse response) + private async Task DeleteAsync(NodeResponse response) { - await AlertService.ConfirmDanger( + await AlertService.ConfirmDangerAsync( "Node deletion", $"Do you really want to delete the node '{response.Name}'", async () => { await ApiClient.Delete($"api/admin/servers/nodes/{response.Id}"); - await ToastService.Success("Successfully deleted node"); + await ToastService.SuccessAsync("Successfully deleted node"); - await Table.Refresh(); + await Grid.RefreshAsync(); } ); } - private async Task ShowErrorDetails(int id) + private async Task ShowErrorDetailsAsync(int id) { var data = StatusResponses.GetValueOrDefault(id); @@ -241,6 +244,6 @@ (data.RoundtripRemoteFailure ? "(Failed at node)" : "(Failed at api server)") + $" {data.RoundtripError}"; - await AlertService.Error("Node error details", message); + await AlertService.ErrorAsync("Node error details", message); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Update.razor b/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Update.razor index df521f3..73307c9 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Update.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/Nodes/Update.razor @@ -13,13 +13,13 @@ @attribute [Authorize(Policy = "permissions:admin.servers.nodes.update")] - + Back - + Update @@ -58,15 +58,13 @@ private UpdateNodeRequest Request; private NodeResponse Node; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { Node = await ApiClient.GetJson($"api/admin/servers/nodes/{Id}"); Request = new UpdateNodeRequest() { Name = Node.Name, - EnableDynamicFirewall = Node.EnableDynamicFirewall, - EnableTransparentMode = Node.EnableTransparentMode, Fqdn = Node.Fqdn, FtpPort = Node.FtpPort, HttpPort = Node.HttpPort @@ -77,7 +75,7 @@ { await ApiClient.Patch($"api/admin/servers/nodes/{Id}", Request); - await ToastService.Success("Successfully updated Node"); + await ToastService.SuccessAsync("Successfully updated Node"); Navigation.NavigateTo("/admin/servers/nodes"); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Admin/Stars/Create.razor b/MoonlightServers.Frontend/UI/Views/Admin/Stars/Create.razor index 3653c4c..b0905ad 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/Stars/Create.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/Stars/Create.razor @@ -17,7 +17,7 @@ Back - + Create @@ -61,7 +61,7 @@ { await ApiClient.Post("api/admin/servers/stars", Request); - await ToastService.Success("Successfully created star"); + await ToastService.SuccessAsync("Successfully created star"); Navigation.NavigateTo("/admin/servers/stars"); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Admin/Stars/Index.razor b/MoonlightServers.Frontend/UI/Views/Admin/Stars/Index.razor index 005a7e1..aa35fcd 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/Stars/Index.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/Stars/Index.razor @@ -1,7 +1,6 @@ @page "/admin/servers/stars" @using MoonCore.Blazor.FlyonUi.Alerts -@using MoonCore.Blazor.FlyonUi.DataTables @using MoonCore.Blazor.FlyonUi.Helpers @using MoonCore.Blazor.FlyonUi.Toasts @using MoonCore.Helpers @@ -9,6 +8,8 @@ @using MoonlightServers.Shared.Http.Responses.Admin.Stars @using MoonCore.Exceptions @using MoonCore.Blazor.FlyonUi.Components +@using MoonCore.Blazor.FlyonUi.Grid +@using MoonCore.Blazor.FlyonUi.Grid.Columns @inject HttpApiClient ApiClient @inject DownloadService DownloadService @@ -35,88 +36,99 @@
- - - - - - - - - @context.Name + + + + + + @context.Name + + +
+ + + + +
+ @if (!string.IsNullOrEmpty(context.DonateUrl)) + { + + + Donate + + } + + @if (!string.IsNullOrEmpty(context.UpdateUrl)) + { + + + Update + + } + + + + Export - - - - - - -
- @if (!string.IsNullOrEmpty(context.DonateUrl)) - { - - - Donate - - } - @if (!string.IsNullOrEmpty(context.UpdateUrl)) - { - - - Update - - } + + + - - - Export - - - - - - - - - -
-
-
- - + + + +
+ +
+
@code { - private DataTable Table; + private DataGrid Grid; - private async Task> LoadData(PaginationOptions options) - => await ApiClient.GetJson>($"api/admin/servers/stars?page={options.Page}&pageSize={options.PerPage}"); - - private async Task Delete(StarResponse response) + private async Task> ItemsProviderAsync( + DataGridItemRequest request + ) { - await AlertService.ConfirmDanger( + var query = $"?startIndex={request.StartIndex}&count={request.Count}"; + + var countedData = await ApiClient.GetJson>($"api/admin/servers/stars{query}"); + + return new() + { + TotalCount = countedData.TotalCount, + Items = countedData.Items + }; + } + + private async Task DeleteAsync(StarResponse response) + { + await AlertService.ConfirmDangerAsync( "Star deletion", $"Do you really want to delete the star '{response.Name}'", async () => { await ApiClient.Delete($"api/admin/servers/stars/{response.Id}"); - await ToastService.Success("Successfully deleted star"); + await ToastService.SuccessAsync("Successfully deleted star"); - await Table.Refresh(); + await Grid.RefreshAsync(); } ); } - private async Task Export(StarResponse star) + private async Task ExportAsync(StarResponse star) { var json = await ApiClient.GetString($"api/admin/servers/stars/{star.Id}/export"); var formattedFileName = star.Name.Replace(" ", "_") + ".json"; - await DownloadService.Download(formattedFileName, json); - await ToastService.Success($"Successfully exported '{star.Name}'"); + await DownloadService.DownloadAsync(formattedFileName, json); + await ToastService.SuccessAsync($"Successfully exported '{star.Name}'"); } private async Task OnImportFiles(InputFileChangeEventArgs eventArgs) @@ -137,7 +149,7 @@ { if (!file.Name.EndsWith(".json")) { - await ToastService.Error($"Failed to import '{file.Name}': Only json files are supported"); + await ToastService.ErrorAsync($"Failed to import '{file.Name}': Only json files are supported"); continue; } @@ -147,14 +159,14 @@ var star = await ApiClient.PostJson("api/admin/servers/stars/import", content); - await ToastService.Success($"Successfully imported '{star.Name}'"); + await ToastService.SuccessAsync($"Successfully imported '{star.Name}'"); } catch (HttpApiException e) { - await ToastService.Error($"Failed to import '{file.Name}': {e.Title}"); + await ToastService.ErrorAsync($"Failed to import '{file.Name}': {e.Title}"); } } - await Table.Refresh(); + await Grid.RefreshAsync(); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Admin/Stars/Update.razor b/MoonlightServers.Frontend/UI/Views/Admin/Stars/Update.razor index 6dba3db..44f2ab4 100644 --- a/MoonlightServers.Frontend/UI/Views/Admin/Stars/Update.razor +++ b/MoonlightServers.Frontend/UI/Views/Admin/Stars/Update.razor @@ -13,13 +13,13 @@ @attribute [Authorize(Policy = "permissions:admin.servers.stars.update")] - + Back - + Update @@ -70,7 +70,7 @@ private UpdateStarRequest Request; private StarResponse Detail; - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { Detail = await ApiClient.GetJson($"api/admin/servers/stars/{Id}"); Request = new() @@ -97,7 +97,7 @@ { await ApiClient.Patch($"api/admin/servers/stars/{Id}", Request); - await ToastService.Success("Successfully updated Star"); + await ToastService.SuccessAsync("Successfully updated Star"); Navigation.NavigateTo("/admin/servers/stars"); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Client/Index.razor b/MoonlightServers.Frontend/UI/Views/Client/Index.razor index ddee1a4..0ac125a 100644 --- a/MoonlightServers.Frontend/UI/Views/Client/Index.razor +++ b/MoonlightServers.Frontend/UI/Views/Client/Index.razor @@ -10,7 +10,7 @@ - + @if (OwnServers.Length == 0) { @@ -47,7 +47,7 @@ - + @if (SharedServers.Length == 0) { @@ -72,17 +72,17 @@ private ServerDetailResponse[] OwnServers; private ServerDetailResponse[] SharedServers; - private async Task LoadOwnServers(LazyLoader lazyLoader) + private async Task LoadOwnServersAsync(LazyLoader lazyLoader) { - OwnServers = await PagedData.All(async (page, pageSize) => - await ServerService.GetServers(page, pageSize) + OwnServers = await CountedData.LoadAllAsync(async (startIndex, count) => + await ServerService.GetServersAsync(startIndex, count) ); } - private async Task LoadSharedServers(LazyLoader lazyLoader) + private async Task LoadSharedServersAsync(LazyLoader lazyLoader) { - SharedServers = await PagedData.All(async (page, pageSize) => - await ServerService.GetSharedServers(page, pageSize) + SharedServers = await CountedData.LoadAllAsync(async (startIndex, count) => + await ServerService.GetSharedServersAsync(startIndex, count) ); } } \ No newline at end of file diff --git a/MoonlightServers.Frontend/UI/Views/Client/Manage.razor b/MoonlightServers.Frontend/UI/Views/Client/Manage.razor index 6679cb1..3039f75 100644 --- a/MoonlightServers.Frontend/UI/Views/Client/Manage.razor +++ b/MoonlightServers.Frontend/UI/Views/Client/Manage.razor @@ -17,7 +17,7 @@ @implements IAsyncDisposable - + @if (NotFound) { @@ -69,7 +69,7 @@ { @if (State == ServerState.Offline) { - + Start @@ -101,14 +101,14 @@ { if (State == ServerState.Stopping) { - + Kill } else { - + Stop @@ -153,7 +153,7 @@ data-tab="na" role="tab" @onclick:preventDefault - @onclick="() => SwitchTab(tab)"> + @onclick="() => SwitchTabAsync(tab)"> @tab.Name } @@ -201,18 +201,18 @@ public ConcurrentList CommandHistory = new(); - private async Task Load(LazyLoader _) + private async Task LoadAsync(LazyLoader _) { try { // Load meta data - Server = await ServerService.GetServer(ServerId); + Server = await ServerService.GetServerAsync(ServerId); // Load server tabs var tmpTabs = new List(); foreach (var serverTabProvider in TabProviders) - tmpTabs.AddRange(await serverTabProvider.GetTabs(Server)); + tmpTabs.AddRange(await serverTabProvider.GetTabsAsync(Server)); // If we are accessing a shared server, we need to handle permissions if (Server.Share != null) @@ -245,7 +245,7 @@ CurrentTab = Tabs.FirstOrDefault(); // Load initial status for first render - var status = await ServerService.GetStatus(ServerId); + var status = await ServerService.GetStatusAsync(ServerId); State = status.State; @@ -253,7 +253,7 @@ return; // Exit early if we don't have permissions to load the console // Load initial messages - var initialLogs = await ServerService.GetLogs(ServerId); + var initialLogs = await ServerService.GetLogsAsync(ServerId); InitialConsoleMessage = ""; @@ -261,7 +261,7 @@ InitialConsoleMessage += message; // Load websocket meta - var websocketDetails = await ServerService.GetWebSocket(ServerId); + var websocketDetails = await ServerService.GetWebSocketAsync(ServerId); // Build signal r HubConnection = new HubConnectionBuilder() @@ -269,7 +269,7 @@ { options.AccessTokenProvider = async () => { - var details = await ServerService.GetWebSocket(ServerId); + var details = await ServerService.GetWebSocketAsync(ServerId); return details.AccessToken; }; }) @@ -317,7 +317,7 @@ return acquiredLevel >= level; } - private async Task SwitchTab(ServerTab tab) + private async Task SwitchTabAsync(ServerTab tab) { CurrentTab = tab; Navigation.NavigateTo($"/servers/{ServerId}/{tab.Path}"); @@ -325,14 +325,14 @@ await InvokeAsync(StateHasChanged); } - private async Task Start() - => await ServerService.Start(ServerId); + private async Task StartAsync() + => await ServerService.StartAsync(ServerId); - private async Task Stop() - => await ServerService.Stop(ServerId); + private async Task StopAsync() + => await ServerService.StopAsync(ServerId); - private async Task Kill() - => await ServerService.Kill(ServerId); + private async Task KillAsync() + => await ServerService.KillAsync(ServerId); public async ValueTask DisposeAsync() { diff --git a/MoonlightServers.Shared/Http/Requests/Admin/Nodes/CreateNodeRequest.cs b/MoonlightServers.Shared/Http/Requests/Admin/Nodes/CreateNodeRequest.cs index ed5fad1..1ffb218 100644 --- a/MoonlightServers.Shared/Http/Requests/Admin/Nodes/CreateNodeRequest.cs +++ b/MoonlightServers.Shared/Http/Requests/Admin/Nodes/CreateNodeRequest.cs @@ -17,7 +17,4 @@ public class CreateNodeRequest [Required(ErrorMessage = "You need to provide a ftp port")] [Range(1, 65535, ErrorMessage = "You need to provide a valid ftp port")] public int FtpPort { get; set; } = 2021; - - public bool EnableTransparentMode { get; set; } - public bool EnableDynamicFirewall { get; set; } } \ No newline at end of file diff --git a/MoonlightServers.Shared/Http/Requests/Admin/Nodes/UpdateNodeRequest.cs b/MoonlightServers.Shared/Http/Requests/Admin/Nodes/UpdateNodeRequest.cs index 027d0fc..fc2ac49 100644 --- a/MoonlightServers.Shared/Http/Requests/Admin/Nodes/UpdateNodeRequest.cs +++ b/MoonlightServers.Shared/Http/Requests/Admin/Nodes/UpdateNodeRequest.cs @@ -17,7 +17,4 @@ public class UpdateNodeRequest [Required(ErrorMessage = "You need to provide a ftp port")] [Range(1, 65535, ErrorMessage = "You need to provide a valid ftp port")] public int FtpPort { get; set; } - - public bool EnableTransparentMode { get; set; } - public bool EnableDynamicFirewall { get; set; } } \ No newline at end of file diff --git a/MoonlightServers.Shared/Http/Requests/Admin/Servers/CreateServerRequest.cs b/MoonlightServers.Shared/Http/Requests/Admin/Servers/CreateServerRequest.cs index 272722a..a053fa5 100644 --- a/MoonlightServers.Shared/Http/Requests/Admin/Servers/CreateServerRequest.cs +++ b/MoonlightServers.Shared/Http/Requests/Admin/Servers/CreateServerRequest.cs @@ -18,11 +18,6 @@ public class CreateServerRequest [Range(1, int.MaxValue, ErrorMessage = "You need to provide a valid disk amount")] public int Disk { get; set; } - public bool UseVirtualDisk { get; set; } - - [Range(0, int.MaxValue, ErrorMessage = "You need to provide a valid bandwidth amount")] - public int Bandwidth { get; set; } - public string? StartupOverride { get; set; } public int DockerImageIndex { get; set; } = -1; diff --git a/MoonlightServers.Shared/Http/Requests/Admin/Servers/UpdateServerRequest.cs b/MoonlightServers.Shared/Http/Requests/Admin/Servers/UpdateServerRequest.cs index 5007b15..d3420c1 100644 --- a/MoonlightServers.Shared/Http/Requests/Admin/Servers/UpdateServerRequest.cs +++ b/MoonlightServers.Shared/Http/Requests/Admin/Servers/UpdateServerRequest.cs @@ -17,9 +17,6 @@ public class UpdateServerRequest [Range(1, int.MaxValue, ErrorMessage = "You need to provide a valid disk amount")] public int Disk { get; set; } - - [Range(0, int.MaxValue, ErrorMessage = "You need to provide a valid bandwidth amount")] - public int Bandwidth { get; set; } public string? StartupOverride { get; set; } diff --git a/MoonlightServers.Shared/Http/Requests/Admin/Stars/CreateStarRequest.cs b/MoonlightServers.Shared/Http/Requests/Admin/Stars/CreateStarRequest.cs index f2ad829..1e45595 100644 --- a/MoonlightServers.Shared/Http/Requests/Admin/Stars/CreateStarRequest.cs +++ b/MoonlightServers.Shared/Http/Requests/Admin/Stars/CreateStarRequest.cs @@ -1,5 +1,4 @@ using System.ComponentModel.DataAnnotations; -using MoonlightServers.Shared.Http.Requests.Admin.StarVariables; namespace MoonlightServers.Shared.Http.Requests.Admin.Stars; diff --git a/MoonlightServers.Shared/Http/Requests/Client/Servers/Shares/CreateShareRequest.cs b/MoonlightServers.Shared/Http/Requests/Client/Servers/Shares/CreateShareRequest.cs index 8ab8e39..cd277b2 100644 --- a/MoonlightServers.Shared/Http/Requests/Client/Servers/Shares/CreateShareRequest.cs +++ b/MoonlightServers.Shared/Http/Requests/Client/Servers/Shares/CreateShareRequest.cs @@ -1,6 +1,5 @@ using System.ComponentModel.DataAnnotations; using MoonlightServers.Shared.Enums; -using MoonlightServers.Shared.Models; namespace MoonlightServers.Shared.Http.Requests.Client.Servers.Shares; diff --git a/MoonlightServers.Shared/Http/Responses/Admin/Stars/StarResponse.cs b/MoonlightServers.Shared/Http/Responses/Admin/Stars/StarResponse.cs index 7d4fa27..ca6b0bb 100644 --- a/MoonlightServers.Shared/Http/Responses/Admin/Stars/StarResponse.cs +++ b/MoonlightServers.Shared/Http/Responses/Admin/Stars/StarResponse.cs @@ -1,6 +1,3 @@ -using MoonlightServers.Shared.Http.Responses.Admin.StarDockerImages; -using MoonlightServers.Shared.Http.Responses.Admin.StarVariables; - namespace MoonlightServers.Shared.Http.Responses.Admin.Stars; public class StarResponse diff --git a/MoonlightServers.Shared/Http/Responses/Client/Servers/ServerDetailResponse.cs b/MoonlightServers.Shared/Http/Responses/Client/Servers/ServerDetailResponse.cs index 0cb4e47..ee5516d 100644 --- a/MoonlightServers.Shared/Http/Responses/Client/Servers/ServerDetailResponse.cs +++ b/MoonlightServers.Shared/Http/Responses/Client/Servers/ServerDetailResponse.cs @@ -1,6 +1,5 @@ using MoonlightServers.Shared.Enums; using MoonlightServers.Shared.Http.Responses.Client.Servers.Allocations; -using MoonlightServers.Shared.Models; namespace MoonlightServers.Shared.Http.Responses.Client.Servers; diff --git a/MoonlightServers.Shared/Http/Responses/Client/Servers/Shares/ServerShareResponse.cs b/MoonlightServers.Shared/Http/Responses/Client/Servers/Shares/ServerShareResponse.cs index 3837f0d..aa96d34 100644 --- a/MoonlightServers.Shared/Http/Responses/Client/Servers/Shares/ServerShareResponse.cs +++ b/MoonlightServers.Shared/Http/Responses/Client/Servers/Shares/ServerShareResponse.cs @@ -1,5 +1,4 @@ using MoonlightServers.Shared.Enums; -using MoonlightServers.Shared.Models; namespace MoonlightServers.Shared.Http.Responses.Client.Servers.Shares;