14 Commits
v1b6 ... v1b7

Author SHA1 Message Date
Marcel Baumgartner
c2cb10f069 Merge pull request #173 from Moonlight-Panel/CleanupHotfix
Fixed cleanup calculation errors
2023-06-17 00:30:16 +02:00
Marcel Baumgartner
cc06d1eb0b Fixed cleanup calculation errors 2023-06-17 00:29:47 +02:00
Marcel Baumgartner
916ff71022 Merge pull request #172 from Moonlight-Panel/FixConsoleIssues
Fixed xterm console issues
2023-06-16 22:57:04 +02:00
Marcel Baumgartner
9e80342e26 Fixed xterm console issues 2023-06-16 22:56:33 +02:00
Marcel Baumgartner
0fb97683bf Merge pull request #171 from Moonlight-Panel/DisableServerDelete
Disabled server delete
2023-06-16 20:30:00 +02:00
Marcel Baumgartner
32415bad54 Merge pull request #170 from Moonlight-Panel/AddModrinthSupport
Add modrinth support
2023-06-16 20:29:45 +02:00
Marcel Baumgartner
d2b0bcc4a3 Disabled server delete 2023-06-16 20:29:23 +02:00
Daniel Balk
2f4f4193d3 Merge pull request #169 from Moonlight-Panel/NotificationDebuggingUi
added simple debugging page
2023-06-16 20:25:39 +02:00
Daniel Balk
7279f05a16 added simple debugging page 2023-06-16 20:24:32 +02:00
Marcel Baumgartner
3962723acb Implemented plugin installer 2023-06-16 20:24:03 +02:00
Marcel Baumgartner
125e72fa58 Switched to new routing for the server manage page 2023-06-16 17:43:48 +02:00
Marcel Baumgartner
880cce060f Added missing server installing db change 2023-06-16 17:33:47 +02:00
Marcel Baumgartner
0e04942111 Merge pull request #168 from Moonlight-Panel/AddServerArchive
Added archive system. Added ml debug menu and related stuff
2023-06-16 17:21:05 +02:00
Marcel Baumgartner
46a88d4638 Added archive system. Added ml debug menu and related stuff 2023-06-16 16:58:58 +02:00
65 changed files with 2603 additions and 210 deletions

View File

@@ -0,0 +1,59 @@
using Logging.Net;
using Newtonsoft.Json;
using RestSharp;
namespace Moonlight.App.ApiClients.Modrinth;
public class ModrinthApiHelper
{
private readonly RestClient Client;
public ModrinthApiHelper()
{
Client = new();
Client.AddDefaultParameter(
new HeaderParameter("User-Agent", "Moonlight-Panel/Moonlight (admin@endelon-hosting.de)")
);
}
public async Task<T> Get<T>(string resource)
{
var request = CreateRequest(resource);
request.Method = Method.Get;
var response = await Client.ExecuteAsync(request);
if (!response.IsSuccessful)
{
if (response.StatusCode != 0)
{
throw new ModrinthException(
$"An error occured: ({response.StatusCode}) {response.Content}",
(int)response.StatusCode
);
}
else
{
throw new Exception($"An internal error occured: {response.ErrorMessage}");
}
}
return JsonConvert.DeserializeObject<T>(response.Content!)!;
}
private RestRequest CreateRequest(string resource)
{
var url = "https://api.modrinth.com/v2/" + resource;
var request = new RestRequest(url)
{
Timeout = 60 * 15
};
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
return request;
}
}

View File

@@ -0,0 +1,19 @@
namespace Moonlight.App.ApiClients.Modrinth;
public class ModrinthException : Exception
{
public int StatusCode { get; set; }
public ModrinthException()
{
}
public ModrinthException(string message, int statusCode) : base(message)
{
StatusCode = statusCode;
}
public ModrinthException(string message, Exception inner) : base(message, inner)
{
}
}

View File

@@ -0,0 +1,14 @@
using Newtonsoft.Json;
namespace Moonlight.App.ApiClients.Modrinth.Resources;
public class Pagination
{
[JsonProperty("hits")] public Project[] Hits { get; set; }
[JsonProperty("offset")] public long Offset { get; set; }
[JsonProperty("limit")] public long Limit { get; set; }
[JsonProperty("total_hits")] public long TotalHits { get; set; }
}

View File

@@ -0,0 +1,48 @@
using Newtonsoft.Json;
namespace Moonlight.App.ApiClients.Modrinth.Resources;
public class Project
{
[JsonProperty("project_id")] public string ProjectId { get; set; }
[JsonProperty("project_type")] public string ProjectType { get; set; }
[JsonProperty("slug")] public string Slug { get; set; }
[JsonProperty("author")] public string Author { get; set; }
[JsonProperty("title")] public string Title { get; set; }
[JsonProperty("description")] public string Description { get; set; }
[JsonProperty("categories")] public string[] Categories { get; set; }
[JsonProperty("display_categories")] public string[] DisplayCategories { get; set; }
[JsonProperty("versions")] public string[] Versions { get; set; }
[JsonProperty("downloads")] public long Downloads { get; set; }
[JsonProperty("follows")] public long Follows { get; set; }
[JsonProperty("icon_url")] public string IconUrl { get; set; }
[JsonProperty("date_created")] public DateTimeOffset DateCreated { get; set; }
[JsonProperty("date_modified")] public DateTimeOffset DateModified { get; set; }
[JsonProperty("latest_version")] public string LatestVersion { get; set; }
[JsonProperty("license")] public string License { get; set; }
[JsonProperty("client_side")] public string ClientSide { get; set; }
[JsonProperty("server_side")] public string ServerSide { get; set; }
[JsonProperty("gallery")] public Uri[] Gallery { get; set; }
[JsonProperty("featured_gallery")] public Uri FeaturedGallery { get; set; }
[JsonProperty("color")] public long? Color { get; set; }
}

View File

@@ -0,0 +1,57 @@
using Newtonsoft.Json;
namespace Moonlight.App.ApiClients.Modrinth.Resources;
public class Version
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("version_number")]
public string VersionNumber { get; set; }
[JsonProperty("changelog")]
public string Changelog { get; set; }
[JsonProperty("dependencies")]
public object[] Dependencies { get; set; }
[JsonProperty("game_versions")]
public object[] GameVersions { get; set; }
[JsonProperty("version_type")]
public string VersionType { get; set; }
[JsonProperty("loaders")]
public object[] Loaders { get; set; }
[JsonProperty("featured")]
public bool Featured { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("requested_status")]
public string RequestedStatus { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("project_id")]
public string ProjectId { get; set; }
[JsonProperty("author_id")]
public string AuthorId { get; set; }
[JsonProperty("date_published")]
public DateTime DatePublished { get; set; }
[JsonProperty("downloads")]
public long Downloads { get; set; }
[JsonProperty("changelog_url")]
public object ChangelogUrl { get; set; }
[JsonProperty("files")]
public VersionFile[] Files { get; set; }
}

View File

@@ -0,0 +1,21 @@
using Newtonsoft.Json;
namespace Moonlight.App.ApiClients.Modrinth.Resources;
public class VersionFile
{
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("filename")]
public string Filename { get; set; }
[JsonProperty("primary")]
public bool Primary { get; set; }
[JsonProperty("size")]
public long Size { get; set; }
[JsonProperty("file_type")]
public string FileType { get; set; }
}

View File

@@ -13,6 +13,8 @@ public class Server
public string OverrideStartup { get; set; } = "";
public bool Installing { get; set; } = false;
public bool Suspended { get; set; } = false;
public bool IsArchived { get; set; } = false;
public ServerBackup? Archive { get; set; } = null;
public List<ServerVariable> Variables { get; set; } = new();
public List<ServerBackup> Backups { get; set; } = new();

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Moonlight.App.Database.Migrations
{
/// <inheritdoc />
public partial class AddedServerAchive : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "ArchiveId",
table: "Servers",
type: "int",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsArchived",
table: "Servers",
type: "tinyint(1)",
nullable: false,
defaultValue: false);
migrationBuilder.CreateIndex(
name: "IX_Servers_ArchiveId",
table: "Servers",
column: "ArchiveId");
migrationBuilder.AddForeignKey(
name: "FK_Servers_ServerBackups_ArchiveId",
table: "Servers",
column: "ArchiveId",
principalTable: "ServerBackups",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Servers_ServerBackups_ArchiveId",
table: "Servers");
migrationBuilder.DropIndex(
name: "IX_Servers_ArchiveId",
table: "Servers");
migrationBuilder.DropColumn(
name: "ArchiveId",
table: "Servers");
migrationBuilder.DropColumn(
name: "IsArchived",
table: "Servers");
}
}
}

View File

@@ -496,6 +496,9 @@ namespace Moonlight.App.Database.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("ArchiveId")
.HasColumnType("int");
b.Property<int>("Cpu")
.HasColumnType("int");
@@ -511,6 +514,9 @@ namespace Moonlight.App.Database.Migrations
b.Property<bool>("Installing")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsArchived")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsCleanupException")
.HasColumnType("tinyint(1)");
@@ -542,6 +548,8 @@ namespace Moonlight.App.Database.Migrations
b.HasKey("Id");
b.HasIndex("ArchiveId");
b.HasIndex("ImageId");
b.HasIndex("MainAllocationId");
@@ -935,6 +943,10 @@ namespace Moonlight.App.Database.Migrations
modelBuilder.Entity("Moonlight.App.Database.Entities.Server", b =>
{
b.HasOne("Moonlight.App.Database.Entities.ServerBackup", "Archive")
.WithMany()
.HasForeignKey("ArchiveId");
b.HasOne("Moonlight.App.Database.Entities.Image", "Image")
.WithMany()
.HasForeignKey("ImageId")
@@ -957,6 +969,8 @@ namespace Moonlight.App.Database.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Archive");
b.Navigation("Image");
b.Navigation("MainAllocation");

View File

@@ -112,4 +112,22 @@ public class EventSystem
return Task.CompletedTask;
}
public Task<T> WaitForEvent<T>(string id, object handle, Func<T, bool> filter)
{
var taskCompletionSource = new TaskCompletionSource<T>();
Func<T, Task> action = async data =>
{
if (filter.Invoke(data))
{
taskCompletionSource.SetResult(data);
await Off(id, handle);
}
};
On<T>(id, handle, action);
return taskCompletionSource.Task;
}
}

View File

@@ -89,10 +89,6 @@ public class WingsConsole : IDisposable
{
await Work();
}
catch (JsonReaderException)
{
// ignore
}
catch (Exception e)
{
Logger.Warn("Error connecting to wings console");
@@ -247,6 +243,7 @@ public class WingsConsole : IDisposable
break;
}
}
catch(JsonReaderException){}
catch (Exception e)
{
if (!Disconnecting)

View File

@@ -0,0 +1,8 @@
namespace Moonlight.App.Models.Forms;
public class ServerImageDataModel
{
public string OverrideStartup { get; set; }
public int DockerImageIndex { get; set; }
}

View File

@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
using Moonlight.App.Database.Entities;
namespace Moonlight.App.Models.Forms;
public class ServerOverviewDataModel
{
[Required(ErrorMessage = "You need to enter a name")]
[MaxLength(32, ErrorMessage = "The name cannot be longer that 32 characters")]
public string Name { get; set; }
[Required(ErrorMessage = "You need to specify a owner")]
public User Owner { get; set; }
}

View File

@@ -0,0 +1,15 @@
using System.ComponentModel.DataAnnotations;
namespace Moonlight.App.Models.Forms;
public class ServerResourcesDataModel
{
[Required(ErrorMessage = "You need to specify the cpu cores")]
public int Cpu { get; set; }
[Required(ErrorMessage = "You need to specify the memory")]
public long Memory { get; set; }
[Required(ErrorMessage = "You need to specify the disk")]
public long Disk { get; set; }
}

View File

@@ -0,0 +1,83 @@
using Moonlight.App.ApiClients.Modrinth;
using Moonlight.App.ApiClients.Modrinth.Resources;
using Moonlight.App.Exceptions;
using FileAccess = Moonlight.App.Helpers.Files.FileAccess;
using Version = Moonlight.App.ApiClients.Modrinth.Resources.Version;
namespace Moonlight.App.Services.Addon;
public class ServerAddonPluginService
{
private readonly ModrinthApiHelper ModrinthApiHelper;
private readonly ServerService ServerService;
public ServerAddonPluginService(ModrinthApiHelper modrinthApiHelper)
{
ModrinthApiHelper = modrinthApiHelper;
}
public async Task<Project[]> GetPluginsForVersion(string version, string search = "")
{
string resource;
var filter =
"[[\"categories:\'bukkit\'\",\"categories:\'paper\'\",\"categories:\'spigot\'\"],[\"versions:" + version + "\"],[\"project_type:mod\"]]";
if (string.IsNullOrEmpty(search))
resource = "search?limit=21&index=relevance&facets=" + filter;
else
resource = $"search?query={search}&limit=21&index=relevance&facets=" + filter;
var result = await ModrinthApiHelper.Get<Pagination>(resource);
return result.Hits;
}
public async Task InstallPlugin(FileAccess fileAccess, string version, Project project, Action<string>? onStateUpdated = null)
{
// Resolve plugin download
onStateUpdated?.Invoke($"Resolving {project.Slug}");
var filter = "game_versions=[\"" + version + "\"]&loaders=[\"bukkit\", \"paper\", \"spigot\"]";
var versions = await ModrinthApiHelper.Get<Version[]>(
$"project/{project.Slug}/version?" + filter);
if (!versions.Any())
throw new DisplayException("No plugin download for your minecraft version found");
var installVersion = versions.OrderByDescending(x => x.DatePublished).First();
var fileToInstall = installVersion.Files.First();
// Download plugin in a stream cached mode
var httpClient = new HttpClient();
var stream = await httpClient.GetStreamAsync(fileToInstall.Url);
var dataStream = new MemoryStream(1024 * 1024 * 40);
await stream.CopyToAsync(dataStream);
stream.Close();
dataStream.Position = 0;
// Install plugin
await fileAccess.SetDir("/");
try
{
await fileAccess.MkDir("plugins");
}
catch (Exception)
{
// Ignored
}
await fileAccess.SetDir("plugins");
onStateUpdated?.Invoke($"Installing {project.Slug}");
await fileAccess.Upload(fileToInstall.Filename, dataStream);
await dataStream.DisposeAsync();
//TODO: At some point of time, create a dependency resolver
}
}

View File

@@ -46,11 +46,13 @@ public class CleanupService
var config = ConfigService.GetSection("Moonlight").GetSection("Cleanup");
if (!config.GetValue<bool>("Enable") || ConfigService.DebugMode)
/*
* if (!config.GetValue<bool>("Enable") || ConfigService.DebugMode)
{
Logger.Info("Disabling cleanup service");
return;
}
*/
Timer = new(TimeSpan.FromMinutes(config.GetValue<int>("Wait")));
@@ -85,7 +87,30 @@ public class CleanupService
var cpuMetrics = await nodeService.GetCpuMetrics(node);
var memoryMetrics = await nodeService.GetMemoryMetrics(node);
if (cpuMetrics.CpuUsage > maxCpu || (Formatter.BytesToGb(memoryMetrics.Total) - (Formatter.BytesToGb(memoryMetrics.Used))) < minMemory)
bool executeCleanup;
if (cpuMetrics.CpuUsage > maxCpu)
{
Logger.Debug($"{node.Name}: CPU Usage is too high");
Logger.Debug($"Usage: {cpuMetrics.CpuUsage}");
Logger.Debug($"Max CPU: {maxCpu}");
executeCleanup = true;
}
else if (Formatter.BytesToGb(memoryMetrics.Total) - Formatter.BytesToGb(memoryMetrics.Used) <
minMemory / 1024D)
{
Logger.Debug($"{node.Name}: Memory Usage is too high");
Logger.Debug($"Memory (Total): {Formatter.BytesToGb(memoryMetrics.Total)}");
Logger.Debug($"Memory (Used): {Formatter.BytesToGb(memoryMetrics.Used)}");
Logger.Debug(
$"Memory (Free): {Formatter.BytesToGb(memoryMetrics.Total) - Formatter.BytesToGb(memoryMetrics.Used)}");
Logger.Debug($"Min Memory: {minMemory}");
executeCleanup = true;
}
else
executeCleanup = false;
if (executeCleanup)
{
var dockerMetrics = await nodeService.GetDockerMetrics(node);
@@ -140,6 +165,7 @@ public class CleanupService
if (players == 0)
{
Logger.Debug($"Restarted {server.Name} ({server.Uuid}) on node {node.Name}");
await serverService.SetPowerState(server, PowerSignal.Restart);
ServersCleaned++;
@@ -165,10 +191,12 @@ public class CleanupService
if (handleJ2S)
{
Logger.Debug($"Restarted (cleanup) {server.Name} ({server.Uuid}) on node {node.Name}");
await serverService.SetPowerState(server, PowerSignal.Restart);
}
else
{
Logger.Debug($"Stopped {server.Name} ({server.Uuid}) on node {node.Name}");
await serverService.SetPowerState(server, PowerSignal.Stop);
}

View File

@@ -72,7 +72,7 @@ public class NodeService
{
try
{
await GetSystemMetrics(node);
await GetStatus(node);
return true;
}

View File

@@ -36,6 +36,11 @@ public class NotificationServerService
private List<NotificationClientService> connectedClients = new();
public List<NotificationClientService> GetConnectedClients()
{
return connectedClients.ToList();
}
public List<NotificationClientService> GetConnectedClients(User user)
{
return connectedClients.Where(x => x.User == user).ToList();

View File

@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Logging.Net;
using Microsoft.EntityFrameworkCore;
using Moonlight.App.ApiClients.Wings;
using Moonlight.App.ApiClients.Wings.Requests;
using Moonlight.App.ApiClients.Wings.Resources;
@@ -369,6 +370,9 @@ public class ServerService
await WingsApiHelper.Post(server.Node, $"api/servers/{server.Uuid}/reinstall", null);
server.Installing = true;
ServerRepository.Update(server);
await AuditLogService.Log(AuditLogType.ReinstallServer, x => { x.Add<Server>(server.Uuid); });
}
@@ -404,6 +408,8 @@ public class ServerService
public async Task Delete(Server s)
{
throw new DisplayException("Deleting servers is currently disabled");
var backups = await GetBackups(s);
foreach (var backup in backups)
@@ -446,4 +452,65 @@ public class ServerService
return await NodeService.IsHostUp(server.Node);
}
public async Task ArchiveServer(Server server)
{
if (server.IsArchived)
throw new DisplayException("Unable to archive an already archived server");
// Archive server
var backup = await CreateBackup(server);
server.IsArchived = true;
server.Archive = backup;
ServerRepository.Update(server);
await Event.WaitForEvent<ServerBackup>("wings.backups.create", this, x => backup.Id == x.Id);
// Reset server
var access = await CreateFileAccess(server, null!);
var files = await access.Ls();
foreach (var file in files)
{
try
{
await access.Delete(file);
}
catch (Exception)
{
// ignored
}
}
await Event.Emit($"server.{server.Uuid}.archiveStatusChanged", server);
}
public async Task UnArchiveServer(Server s)
{
if (!s.IsArchived)
throw new DisplayException("Unable to unarchive a server which is not archived");
var server = ServerRepository
.Get()
.Include(x => x.Archive)
.First(x => x.Id == s.Id);
if (server.Archive == null)
throw new DisplayException("Archive from server not found");
if (!server.Archive.Created)
throw new DisplayException("Creating the server archive is in progress");
await RestoreBackup(server, server.Archive);
await Event.WaitForEvent<ServerBackup>("wings.backups.restore", this,
x => x.Id == server.Archive.Id);
server.IsArchived = false;
ServerRepository.Update(server);
await Event.Emit($"server.{server.Uuid}.archiveStatusChanged", server);
}
}

View File

@@ -48,7 +48,7 @@
<PackageReference Include="RestSharp" Version="109.0.0-preview.1" />
<PackageReference Include="SSH.NET" Version="2020.0.2" />
<PackageReference Include="UAParser" Version="3.1.47" />
<PackageReference Include="XtermBlazor" Version="1.6.1" />
<PackageReference Include="XtermBlazor" Version="1.8.1" />
</ItemGroup>
<ItemGroup>
@@ -79,4 +79,22 @@
<Folder Include="storage\resources\public\background\" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="Shared\Views\Server\Settings\DotnetFileSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\DotnetVersionSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\FabricVersionSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\ForgeVersionSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\JavaFileSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\JavaRuntimeVersionSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\JavascriptFileSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\JavascriptVersionSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\Join2StartSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\PaperVersionSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\PythonFileSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\PythonVersionSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\ServerDeleteSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\ServerRenameSetting.razor" />
<AdditionalFiles Include="Shared\Views\Server\Settings\ServerResetSetting.razor" />
</ItemGroup>
</Project>

View File

@@ -105,9 +105,7 @@
<script src="https://www.google.com/recaptcha/api.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.5.0/lib/xterm-addon-fit.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xterm-addon-search@0.8.2/lib/xterm-addon-search.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xterm-addon-web-links@0.5.0/lib/xterm-addon-web-links.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.7.0/lib/xterm-addon-fit.min.js"></script>
<script src="/_content/BlazorMonaco/lib/monaco-editor/min/vs/loader.js"></script>
<script>require.config({ paths: { 'vs': '/_content/BlazorMonaco/lib/monaco-editor/min/vs' } });</script>

View File

@@ -5,6 +5,7 @@ using HealthChecks.UI.Client;
using Logging.Net;
using Moonlight.App.ApiClients.CloudPanel;
using Moonlight.App.ApiClients.Daemon;
using Moonlight.App.ApiClients.Modrinth;
using Moonlight.App.ApiClients.Paper;
using Moonlight.App.ApiClients.Wings;
using Moonlight.App.Database;
@@ -18,6 +19,7 @@ using Moonlight.App.Repositories.Domains;
using Moonlight.App.Repositories.LogEntries;
using Moonlight.App.Repositories.Servers;
using Moonlight.App.Services;
using Moonlight.App.Services.Addon;
using Moonlight.App.Services.Background;
using Moonlight.App.Services.DiscordBot;
using Moonlight.App.Services.Files;
@@ -132,6 +134,7 @@ namespace Moonlight
builder.Services.AddScoped<IpBanService>();
builder.Services.AddSingleton<OAuth2Service>();
builder.Services.AddScoped<DynamicBackgroundService>();
builder.Services.AddScoped<ServerAddonPluginService>();
builder.Services.AddScoped<SubscriptionService>();
builder.Services.AddScoped<SubscriptionAdminService>();
@@ -159,6 +162,7 @@ namespace Moonlight
builder.Services.AddSingleton<HostSystemHelper>();
builder.Services.AddScoped<DaemonApiHelper>();
builder.Services.AddScoped<CloudPanelApiHelper>();
builder.Services.AddScoped<ModrinthApiHelper>();
// Background services
builder.Services.AddSingleton<DiscordBotService>();

View File

@@ -3,10 +3,13 @@
@using Moonlight.App.Services
@using Logging.Net
@using Moonlight.App.ApiClients.CloudPanel
@using Moonlight.App.ApiClients.Daemon
@using Moonlight.App.ApiClients.Modrinth
@using Moonlight.App.ApiClients.Wings
@inherits ErrorBoundaryBase
@inject AlertService AlertService
@inject ConfigService ConfigService
@inject SmartTranslateService SmartTranslateService
@if (Crashed)
@@ -37,12 +40,14 @@ else
protected override async Task OnErrorAsync(Exception exception)
{
Logger.Warn(exception);
if (ConfigService.DebugMode)
{
Logger.Warn(exception);
}
if (exception is DisplayException displayException)
{
await AlertService.Error(
SmartTranslateService.Translate("Error"),
SmartTranslateService.Translate(displayException.Message)
);
}
@@ -56,7 +61,7 @@ else
else if (exception is WingsException wingsException)
{
await AlertService.Error(
SmartTranslateService.Translate("Error from daemon"),
SmartTranslateService.Translate("Error from wings"),
wingsException.Message
);
@@ -64,6 +69,22 @@ else
Logger.Warn($"Wings exception status code: {wingsException.StatusCode}");
}
else if (exception is DaemonException daemonException)
{
await AlertService.Error(
SmartTranslateService.Translate("Error from daemon"),
daemonException.Message
);
Logger.Warn($"Wings exception status code: {daemonException.StatusCode}");
}
else if (exception is ModrinthException modrinthException)
{
await AlertService.Error(
SmartTranslateService.Translate("Error from modrinth"),
modrinthException.Message
);
}
else if (exception is CloudPanelException cloudPanelException)
{
await AlertService.Error(
@@ -77,6 +98,7 @@ else
}
else
{
Logger.Warn(exception);
Crashed = true;
await InvokeAsync(StateHasChanged);
}

View File

@@ -0,0 +1,51 @@
@using Moonlight.App.Database.Entities
<div class="card mb-5 mb-xl-10">
<div class="card-body pt-0 pb-0">
<ul class="nav nav-stretch nav-line-tabs nav-line-tabs-2x border-transparent fs-5 fw-bold">
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 0 ? "active" : "")" href="/admin/servers/view/@(Server.Id)">
<TL>Overview</TL>
</a>
</li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 1 ? "active" : "")" href="/admin/servers/view/@(Server.Id)/image">
<TL>Image</TL>
</a>
</li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 2 ? "active" : "")" href="/admin/servers/view/@(Server.Id)/resources">
<TL>Resources</TL>
</a>
</li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 3 ? "active" : "")" href="/admin/servers/view/@(Server.Id)/allocations">
<TL>Allocations</TL>
</a>
</li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 4 ? "active" : "")" href="/admin/servers/view/@(Server.Id)/archive">
<TL>Archive</TL>
</a>
</li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 5 ? "active" : "")" href="/admin/servers/view/@(Server.Id)/debug">
<TL>Debug</TL>
</a>
</li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 6 ? "active" : "")" href="/admin/servers/view/@(Server.Id)/delete">
<TL>Delete</TL>
</a>
</li>
</ul>
</div>
</div>
@code
{
[Parameter]
public int Index { get; set; }
[Parameter]
public Server Server { get; set; }
}

View File

@@ -0,0 +1,20 @@
@{
var route = "/" + (Router.Route ?? "");
}
@if (route == Path)
{
@ChildContent
}
@code
{
[CascadingParameter]
public SmartRouter Router { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public string Path { get; set; }
}

View File

@@ -0,0 +1,12 @@
<CascadingValue TValue="SmartRouter" Value="@this">
@ChildContent
</CascadingValue>
@code
{
[Parameter]
public string? Route { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
}

View File

@@ -1,10 +0,0 @@
<div class="alert alert-primary d-flex rounded p-6">
<div class="d-flex flex-stack flex-grow-1 flex-wrap flex-md-nowrap">
<div class="mb-3 mb-md-0 fw-semibold">
<h4 class="text-gray-900 fw-bold"><TL>Addons</TL></h4>
<div class="fs-6 text-gray-700 pe-7">
<TL>This feature is currently not available</TL>
</div>
</div>
</div>
</div>

View File

@@ -5,7 +5,7 @@
<Xterm
@ref="Xterm"
Options="TerminalOptions"
AddonIds="@(new[] { "xterm-addon-fit", "xterm-addon-search", "xterm-addon-web-links" })"
AddonIds="@(new[] { "xterm-addon-fit" })"
OnFirstRender="OnFirstRender">
</Xterm>
@@ -48,6 +48,18 @@
{
await Xterm.InvokeAddonFunctionVoidAsync("xterm-addon-fit", "fit");
RunOnFirstRender.Invoke();
await Task.Run(async () =>
{
try
{
await Task.Delay(1000);
await Xterm.InvokeAddonFunctionVoidAsync("xterm-addon-fit", "fit");
await Task.Delay(1000);
await Xterm.InvokeAddonFunctionVoidAsync("xterm-addon-fit", "fit");
}
catch (Exception){}
});
}
catch (Exception)
{

View File

@@ -22,138 +22,134 @@
@inject IpBanService IpBanService
@inject DynamicBackgroundService DynamicBackgroundService
<GlobalErrorBoundary>
@{
var uri = new Uri(NavigationManager.Uri);
var pathParts = uri.LocalPath.Split("/").Reverse();
@{
var uri = new Uri(NavigationManager.Uri);
var pathParts = uri.LocalPath.Split("/").Reverse();
var title = "";
var title = "";
foreach (var pathPart in pathParts)
foreach (var pathPart in pathParts)
{
if (!string.IsNullOrEmpty(pathPart))
{
if (!string.IsNullOrEmpty(pathPart))
{
if (pathPart == pathParts.Last())
title += $"{pathPart.FirstCharToUpper()} ";
else
title += $"{pathPart.FirstCharToUpper()} - ";
}
if (pathPart == pathParts.Last())
title += $"{pathPart.FirstCharToUpper()} ";
else
title += $"{pathPart.FirstCharToUpper()} - ";
}
}
}
<CascadingValue Value="User">
<PageTitle>@(string.IsNullOrEmpty(title) ? "Dashboard - " : title)Moonlight</PageTitle>
<CascadingValue Value="User">
<PageTitle>@(string.IsNullOrEmpty(title) ? "Dashboard - " : title)Moonlight</PageTitle>
<div class="d-flex flex-column flex-root app-root" id="kt_app_root">
<div class="app-page flex-column flex-column-fluid" id="kt_app_page">
<canvas id="snow" class="snow-canvas"></canvas>
<div class="d-flex flex-column flex-root app-root" id="kt_app_root">
<div class="app-page flex-column flex-column-fluid" id="kt_app_page">
<canvas id="snow" class="snow-canvas"></canvas>
@{
//TODO: Add a way to disable the snow
}
@{
//TODO: Add a way to disable the snow
}
<PageHeader></PageHeader>
<div class="app-wrapper flex-column flex-row-fluid" id="kt_app_wrapper">
<Sidebar></Sidebar>
<div class="app-main flex-column flex-row-fluid" id="kt_app_main">
<div class="d-flex flex-column flex-column-fluid">
<div id="kt_app_content" class="app-content flex-column-fluid" style="background-position: center; background-size: cover; background-repeat: no-repeat; background-attachment: fixed; background-image: url('@(DynamicBackgroundService.BackgroundImageUrl)')">
<div id="kt_app_content_container" class="app-container container-fluid">
<div class="mt-10">
<SoftErrorBoundary>
@if (!IsIpBanned)
<PageHeader></PageHeader>
<div class="app-wrapper flex-column flex-row-fluid" id="kt_app_wrapper">
<Sidebar></Sidebar>
<div class="app-main flex-column flex-row-fluid" id="kt_app_main">
<div class="d-flex flex-column flex-column-fluid">
<div id="kt_app_content" class="app-content flex-column-fluid" style="background-position: center; background-size: cover; background-repeat: no-repeat; background-attachment: fixed; background-image: url('@(DynamicBackgroundService.BackgroundImageUrl)')">
<div id="kt_app_content_container" class="app-container container-fluid">
<div class="mt-10">
@if (!IsIpBanned)
{
if (UserProcessed)
{
if (uri.LocalPath != "/login" &&
uri.LocalPath != "/passwordreset" &&
uri.LocalPath != "/register")
{
if (UserProcessed)
if (User == null)
{
if (uri.LocalPath != "/login" &&
uri.LocalPath != "/passwordreset" &&
uri.LocalPath != "/register")
{
if (User == null)
{
<Login></Login>
}
else
{
if (User.Status == UserStatus.Banned)
{
<BannedAlert></BannedAlert>
}
else if (User.Status == UserStatus.Disabled)
{
<DisabledAlert></DisabledAlert>
}
else if (User.Status == UserStatus.PasswordPending)
{
<PasswordChangeView></PasswordChangeView>
}
else if (User.Status == UserStatus.DataPending)
{
<UserDataSetView></UserDataSetView>
}
else
{
@Body
<RatingPopup/>
}
}
}
else
{
if (uri.LocalPath == "/login")
{
<Login></Login>
}
else if (uri.LocalPath == "/register")
{
<Register></Register>
}
else if (uri.LocalPath == "/passwordreset")
{
<PasswordReset></PasswordReset>
}
}
<Login></Login>
}
else
{
<div class="modal d-block">
<div class="modal-dialog modal-dialog-centered mw-900px">
<div class="modal-content">
<div class="pt-2 modal-body py-lg-10 px-lg-10">
<h2>@(SmartTranslateService.Translate("Authenticating"))...</h2>
<p class="mt-3 fw-normal fs-6">@(SmartTranslateService.Translate("Verifying token, loading user data"))</p>
</div>
</div>
</div>
</div>
if (User.Status == UserStatus.Banned)
{
<BannedAlert></BannedAlert>
}
else if (User.Status == UserStatus.Disabled)
{
<DisabledAlert></DisabledAlert>
}
else if (User.Status == UserStatus.PasswordPending)
{
<PasswordChangeView></PasswordChangeView>
}
else if (User.Status == UserStatus.DataPending)
{
<UserDataSetView></UserDataSetView>
}
else
{
@Body
<RatingPopup/>
}
}
}
else
{
<div class="modal d-block">
<div class="modal-dialog modal-dialog-centered mw-900px">
<div class="modal-content">
<div class="pt-2 modal-body py-lg-10 px-lg-10">
<h2>@(SmartTranslateService.Translate("Your ip has been banned"))</h2>
<p class="mt-3 fw-normal fs-6">@(SmartTranslateService.Translate("Your ip address has been banned by an admin"))</p>
</div>
if (uri.LocalPath == "/login")
{
<Login></Login>
}
else if (uri.LocalPath == "/register")
{
<Register></Register>
}
else if (uri.LocalPath == "/passwordreset")
{
<PasswordReset></PasswordReset>
}
}
}
else
{
<div class="modal d-block">
<div class="modal-dialog modal-dialog-centered mw-900px">
<div class="modal-content">
<div class="pt-2 modal-body py-lg-10 px-lg-10">
<h2>@(SmartTranslateService.Translate("Authenticating"))...</h2>
<p class="mt-3 fw-normal fs-6">@(SmartTranslateService.Translate("Verifying token, loading user data"))</p>
</div>
</div>
</div>
}
</SoftErrorBoundary>
</div>
</div>
}
}
else
{
<div class="modal d-block">
<div class="modal-dialog modal-dialog-centered mw-900px">
<div class="modal-content">
<div class="pt-2 modal-body py-lg-10 px-lg-10">
<h2>@(SmartTranslateService.Translate("Your ip has been banned"))</h2>
<p class="mt-3 fw-normal fs-6">@(SmartTranslateService.Translate("Your ip address has been banned by an admin"))</p>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
<Footer></Footer>
</div>
<Footer></Footer>
</div>
</div>
</div>
</CascadingValue>
</GlobalErrorBoundary>
</div>
</CascadingValue>
@code
{
@@ -190,16 +186,13 @@
{
try
{
DynamicBackgroundService.OnBackgroundImageChanged += async (_, _) =>
{
await InvokeAsync(StateHasChanged);
};
DynamicBackgroundService.OnBackgroundImageChanged += async (_, _) => { await InvokeAsync(StateHasChanged); };
IsIpBanned = await IpBanService.IsBanned();
if(IsIpBanned)
if (IsIpBanned)
await InvokeAsync(StateHasChanged);
await Event.On<Object>("ipBan.update", this, async _ =>
{
IsIpBanned = await IpBanService.IsBanned();

View File

@@ -0,0 +1,33 @@
@page "/admin/notifications/debugging"
@using Moonlight.App.Services.Notifications
@inject NotificationServerService NotificationServerService
<OnlyAdmin>
<LazyLoader Load="Load">
<h1>Notification Debugging</h1>
@foreach (var client in Clients)
{
<hr/>
<div>
<p>Id: @client.NotificationClient.Id User: @client.User.Email</p>
<button @onclick="async () => await SendSampleNotification(client)"></button>
</div>
}
</LazyLoader>
</OnlyAdmin>
@code {
private List<NotificationClientService> Clients;
private async Task Load(LazyLoader loader)
{
Clients = NotificationServerService.GetConnectedClients();
}
private async Task SendSampleNotification(NotificationClientService client)
{
await client.SendAction(@"{""action"": ""notify"",""notification"":{""id"":999,""channel"":""Sample Channel"",""content"":""This is a sample Notification"",""title"":""Sample Notification""}}");
}
}

View File

@@ -1,4 +1,4 @@
@page "/admin/servers/edit/{id:int}"
@page "/admin/servers/editx/{id:int}"
@using Moonlight.App.Services
@using Moonlight.App.Repositories.Servers

View File

@@ -44,7 +44,7 @@
</Column>
<Column TableItem="Server" Title="" Field="@(x => x.Id)" Sortable="false" Filterable="false">
<Template>
<a href="/admin/servers/edit/@(context.Id)">
<a href="/admin/servers/view/@(context.Id)">
@(SmartTranslateService.Translate("Manage"))
</a>
</Template>

View File

@@ -0,0 +1,68 @@
@using Moonlight.App.Database.Entities
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@inject ServerService ServerService
@inject SmartTranslateService SmartTranslateService
@inject AlertService AlertService
<div class="card">
<div class="card-body">
@if (Server.IsArchived)
{
<span class="fs-5 text-warning"><TL>Server is currently archived</TL></span>
}
else
{
<span class="fs-5"><TL>Server is currently not archived</TL></span>
}
</div>
<div class="card-footer">
<div class="text-end">
@if (Server.IsArchived)
{
<WButton Text="@(SmartTranslateService.Translate("Unarchive"))"
WorkingText="@(SmartTranslateService.Translate("Unarchiving"))"
CssClasses="btn-success"
OnClick="UnArchiveServer">
</WButton>
}
else
{
<WButton Text="@(SmartTranslateService.Translate("Archive"))"
WorkingText="@(SmartTranslateService.Translate("Archiving"))"
CssClasses="btn-danger"
OnClick="ArchiveServer">
</WButton>
}
</div>
</div>
</div>
@code
{
[CascadingParameter]
public Server Server { get; set; }
private async Task ArchiveServer()
{
await ServerService.ArchiveServer(Server);
await InvokeAsync(StateHasChanged);
await AlertService.Success(
SmartTranslateService.Translate("Successfully archived the server")
);
}
private async Task UnArchiveServer()
{
await ServerService.UnArchiveServer(Server);
await InvokeAsync(StateHasChanged);
await AlertService.Success(
SmartTranslateService.Translate("Successfully unarchived the server")
);
}
}

View File

@@ -0,0 +1,31 @@
@using Moonlight.App.Database.Entities
@using Moonlight.App.Services
@inject ServerService ServerService
@inject SmartTranslateService SmartTranslateService
<div class="card">
<div class="card-header">
<span class="card-title">
<TL>Reinstall</TL>
</span>
</div>
<div class="card-footer">
<WButton Text="@(SmartTranslateService.Translate("Reinstall"))"
WorkingText="@(SmartTranslateService.Translate("Reinstalling"))"
CssClasses="btn-warning"
OnClick="Reinstall">
</WButton>
</div>
</div>
@code
{
[CascadingParameter]
public Server Server { get; set; }
private async Task Reinstall()
{
await ServerService.Reinstall(Server!);
}
}

View File

@@ -0,0 +1,111 @@
@using Moonlight.App.Database.Entities
@using Moonlight.App.Repositories
@using Microsoft.EntityFrameworkCore
@using Moonlight.App.Models.Forms
@using Mappy.Net
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@inject Repository<Moonlight.App.Database.Entities.Image> ImageRepository
@inject Repository<Server> ServerRepository
@inject SmartTranslateService SmartTranslateService
@inject ToastService ToastService
<LazyLoader Load="Load">
<SmartForm Model="Model" OnValidSubmit="OnValidSubmit">
<div class="card">
<div class="card-body p-10">
<label class="form-label">
<TL>Override startup command</TL>
</label>
<div class="input-group mb-5">
<span class="input-group-text">
<i class="bx bx-terminal"></i>
</span>
<InputText @bind-Value="Model.OverrideStartup" type="text" class="form-control" placeholder="@(Server.Image.Startup)"></InputText>
</div>
<label class="form-label">
<TL>Docker image</TL>
</label>
<select @bind="Model.DockerImageIndex" class="form-select">
@foreach (var image in DockerImages)
{
<option value="@(DockerImages.IndexOf(image))">@(image.Name)</option>
}
</select>
</div>
<div class="card-body">
@foreach (var vars in Server.Variables.Chunk(4))
{
<div class="row mb-3">
@foreach (var variable in vars)
{
<div class="col">
<div class="card card-body">
<label class="form-label">
<TL>Name</TL>
</label>
<div class="input-group mb-5">
<input @bind="variable.Key" type="text" class="form-control disabled" disabled="">
</div>
<label class="form-label">
<TL>Value</TL>
</label>
<div class="input-group mb-5">
<input @bind="variable.Value" type="text" class="form-control">
</div>
</div>
</div>
}
</div>
}
</div>
<div class="card-footer">
<div class="text-end">
<button type="submit" class="btn btn-success">
<TL>Save changes</TL>
</button>
</div>
</div>
</div>
</SmartForm>
</LazyLoader>
@code
{
[CascadingParameter]
public Server Server { get; set; }
private List<DockerImage> DockerImages;
private List<Moonlight.App.Database.Entities.Image> Images;
private ServerImageDataModel Model;
private Task Load(LazyLoader arg)
{
Images = ImageRepository
.Get()
.Include(x => x.Variables)
.Include(x => x.DockerImages)
.ToList();
DockerImages = Images
.First(x => x.Id == Server.Image.Id).DockerImages
.ToList();
Model = Mapper.Map<ServerImageDataModel>(Server);
return Task.CompletedTask;
}
private async Task OnValidSubmit()
{
Server = Mapper.Map(Server, Model);
ServerRepository.Update(Server);
await ToastService.Success(
SmartTranslateService.Translate("Successfully saved changes")
);
}
}

View File

@@ -0,0 +1,79 @@
@page "/admin/servers/view/{Id:int}/{Route?}"
@using Moonlight.App.Repositories
@using Moonlight.App.Database.Entities
@using Microsoft.EntityFrameworkCore
@using Moonlight.Shared.Components.Navigations
@inject Repository<Server> ServerRepository
<OnlyAdmin>
<LazyLoader @ref="LazyLoader" Load="Load">
@if (Server == null)
{
<div class="alert alert-danger">
<TL>No server with this id found</TL>
</div>
}
else
{
<CascadingValue TValue="Server" Value="Server">
<SmartRouter Route="@Route">
<Route Path="/">
<AdminServersViewNavigation Index="0" Server="Server"/>
<Overview/>
</Route>
<Route Path="/image">
<AdminServersViewNavigation Index="1" Server="Server"/>
<Image/>
</Route>
<Route Path="/resources">
<AdminServersViewNavigation Index="2" Server="Server"/>
<Resources/>
</Route>
<Route Path="/allocations">
<AdminServersViewNavigation Index="3" Server="Server"/>
</Route>
<Route Path="/archive">
<AdminServersViewNavigation Index="4" Server="Server"/>
<Archive/>
</Route>
<Route Path="/debug">
<AdminServersViewNavigation Index="5" Server="Server"/>
<Debug/>
</Route>
<Route Path="/delete">
<AdminServersViewNavigation Index="6" Server="Server"/>
</Route>
</SmartRouter>
</CascadingValue>
}
</LazyLoader>
</OnlyAdmin>
@code
{
[Parameter]
public string? Route { get; set; }
[Parameter]
public int Id { get; set; }
private LazyLoader LazyLoader;
private Server? Server;
private Task Load(LazyLoader arg)
{
Server = ServerRepository
.Get()
.Include(x => x.Image)
.Include(x => x.Owner)
.Include(x => x.Archive)
.Include(x => x.Allocations)
.Include(x => x.MainAllocation)
.Include(x => x.Variables)
.FirstOrDefault(x => x.Id == Id);
return Task.CompletedTask;
}
}

View File

@@ -0,0 +1,91 @@
@using Moonlight.App.Repositories
@using Moonlight.App.Database.Entities
@using Moonlight.App.Models.Forms
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@using Mappy.Net
@inject Repository<User> UserRepository
@inject Repository<Server> ServerRepository
@inject ToastService ToastService
@inject SmartTranslateService SmartTranslateService
<LazyLoader Load="Load">
<SmartForm Model="Model" OnValidSubmit="OnValidSubmit">
<div class="card">
<div class="card-body p-10">
<label class="form-label">
<TL>Identifier</TL>
</label>
<div class="input-group mb-5">
<span class="input-group-text">
<i class="bx bx-id-card"></i>
</span>
<input type="number" class="form-control disabled" disabled="" value="@(Server.Id)">
</div>
<label class="form-label">
<TL>UuidIdentifier</TL>
</label>
<div class="input-group mb-5">
<span class="input-group-text">
<i class="bx bx-id-card"></i>
</span>
<input type="text" class="form-control disabled" disabled="" value="@(Server.Uuid)">
</div>
<label class="form-label">
<TL>Server name</TL>
</label>
<div class="input-group mb-5">
<span class="input-group-text">
<i class="bx bx-purchase-tag-alt"></i>
</span>
<InputText @bind-Value="Model.Name" type="text" class="form-control" placeholder="@(SmartTranslateService.Translate("Server name"))"></InputText>
</div>
<label class="form-label">
<TL>Owner</TL>
</label>
<div class="input-group mb-5">
<SmartDropdown T="User"
@bind-Value="Model.Owner"
Items="Users"
DisplayFunc="@(x => x.Email)"
SearchProp="@(x => x.Email)">
</SmartDropdown>
</div>
</div>
<div class="card-footer">
<div class="text-end">
<button type="submit" class="btn btn-success"><TL>Save changes</TL></button>
</div>
</div>
</div>
</SmartForm>
</LazyLoader>
@code
{
[CascadingParameter]
public Server Server { get; set; }
private ServerOverviewDataModel Model;
private User[] Users;
private Task Load(LazyLoader arg)
{
Users = UserRepository.Get().ToArray();
Model = Mapper.Map<ServerOverviewDataModel>(Server);
return Task.CompletedTask;
}
private async Task OnValidSubmit()
{
Server = Mapper.Map(Server, Model);
ServerRepository.Update(Server);
await ToastService.Success(
SmartTranslateService.Translate("Successfully saved changes")
);
}
}

View File

@@ -0,0 +1,88 @@
@using Moonlight.App.Database.Entities
@using Moonlight.App.Models.Forms
@using Moonlight.App.Repositories
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@using Mappy.Net
@inject Repository<Server> ServerRepository
@inject SmartTranslateService SmartTranslateService
@inject ToastService ToastService
<LazyLoader Load="Load">
<SmartForm Model="Model" OnValidSubmit="OnValidSubmit">
<div class="card">
<div class="card-body p-10">
<label class="form-label">
<TL>Cpu cores</TL>
</label>
<div class="input-group mb-5">
<span class="input-group-text">
<i class="bx bx-chip"></i>
</span>
<InputNumber @bind-Value="Model.Cpu" type="number" class="form-control"></InputNumber>
<span class="input-group-text">
<TL>CPU Cores (100% = 1 Core)</TL>
</span>
</div>
<label class="form-label">
<TL>Memory</TL>
</label>
<div class="input-group mb-5">
<span class="input-group-text">
<i class="bx bx-microchip"></i>
</span>
<InputNumber @bind-Value="Model.Memory" type="number" class="form-control"></InputNumber>
<span class="input-group-text">
MB
</span>
</div>
<label class="form-label">
<TL>Disk</TL>
</label>
<div class="input-group mb-5">
<span class="input-group-text">
<i class="bx bx-hdd"></i>
</span>
<InputNumber @bind-Value="Model.Disk" type="number" class="form-control"></InputNumber>
<span class="input-group-text">
MB
</span>
</div>
</div>
<div class="card-footer">
<div class="text-end">
<button type="submit" class="btn btn-success">
<TL>Save changes</TL>
</button>
</div>
</div>
</div>
</SmartForm>
</LazyLoader>
@code
{
[CascadingParameter]
public Server Server { get; set; }
private ServerResourcesDataModel Model;
private Task Load(LazyLoader arg)
{
Model = Mapper.Map<ServerResourcesDataModel>(Server);
return Task.CompletedTask;
}
private async Task OnValidSubmit()
{
Server = Mapper.Map(Server, Model);
ServerRepository.Update(Server);
await ToastService.Success(
SmartTranslateService.Translate("Successfully saved changes")
);
}
}

View File

@@ -5,14 +5,12 @@
@using Logging.Net
@using Moonlight.App.Database.Entities
@using Moonlight.App.Events
@using Moonlight.App.Helpers
@using Moonlight.App.Helpers.Wings
@using Moonlight.App.Helpers.Wings.Enums
@using Moonlight.App.Repositories
@using Moonlight.App.Services
@using Moonlight.App.Services.Sessions
@using Moonlight.Shared.Components.Xterm
@using Moonlight.Shared.Components.ServerControl
@using Newtonsoft.Json
@inject ImageRepository ImageRepository
@@ -22,6 +20,7 @@
@inject ServerService ServerService
@inject NavigationManager NavigationManager
@inject DynamicBackgroundService DynamicBackgroundService
@inject SmartTranslateService SmartTranslateService
@implements IDisposable
@@ -78,66 +77,65 @@
</div>
</div>
}
else if (CurrentServer.IsArchived)
{
<div class="d-flex justify-content-center flex-center">
<div class="card">
<img src="/assets/media/svg/archive.svg" class="card-img-top w-50 mx-auto pt-5" alt="Not found image"/>
<div class="card-body text-center">
<h1 class="card-title">
<TL>Server is currently archived</TL>
</h1>
<p class="card-text fs-4">
<TL>This server is archived. The data of this server is stored as a backup. To restore click the unarchive button an be patient</TL>
</p>
<WButton Text="@(SmartTranslateService.Translate("Unarchive"))"
WorkingText="@(SmartTranslateService.Translate("Please wait"))"
CssClasses="btn-primary"
OnClick="UnArchive">
</WButton>
</div>
</div>
</div>
}
else
{
<CascadingValue Value="Console">
<CascadingValue Value="CurrentServer">
<CascadingValue Value="Tags">
<CascadingValue Value="Node">
<CascadingValue Value="Image">
<CascadingValue Value="NodeAllocation">
@{
var index = 0;
switch (Route)
{
case "files":
index = 1;
break;
case "backups":
index = 2;
break;
case "network":
index = 3;
break;
case "addons":
index = 4;
break;
case "settings":
index = 5;
break;
default:
index = 0;
break;
}
}
<ServerNavigation Index="index">
@switch (Route)
{
case "files":
<ServerFiles></ServerFiles>
break;
case "backups":
<ServerBackups></ServerBackups>
break;
case "network":
<ServerNetwork></ServerNetwork>
break;
case "addons":
<ServerAddons></ServerAddons>
break;
case "settings":
<ServerSettings></ServerSettings>
break;
default:
<ServerConsole></ServerConsole>
break;
}
</ServerNavigation>
</CascadingValue>
</CascadingValue>
</CascadingValue>
<SmartRouter Route="@Route">
<Route Path="/">
<ServerNavigation Index="0">
<ServerConsole/>
</ServerNavigation>
</Route>
<Route Path="/files">
<ServerNavigation Index="1">
<ServerFiles/>
</ServerNavigation>
</Route>
<Route Path="/backups">
<ServerNavigation Index="2">
<ServerBackups/>
</ServerNavigation>
</Route>
<Route Path="/network">
<ServerNavigation Index="3">
<ServerNetwork/>
</ServerNavigation>
</Route>
<Route Path="/addons">
<ServerNavigation Index="4">
<ServerAddons/>
</ServerNavigation>
</Route>
<Route Path="/settings">
<ServerNavigation Index="5">
<ServerSettings/>
</ServerNavigation>
</Route>
</SmartRouter>
</CascadingValue>
</CascadingValue>
</CascadingValue>
@@ -236,7 +234,7 @@
}
catch (Exception)
{
// ignored
// ignored
}
if (CurrentServer != null)
@@ -260,8 +258,8 @@
.Include(x => x.Variables)
.First(x => x.Id == CurrentServer.Image.Id);
// Live variable migration
// Live variable migration
foreach (var variable in image.Variables)
{
if (!CurrentServer.Variables.Any(x => x.Key == variable.Key))
@@ -271,13 +269,13 @@
Key = variable.Key,
Value = variable.DefaultValue
});
ServerRepository.Update(CurrentServer);
}
}
// Tags
// Tags
await lazyLoader.SetText("Requesting tags");
Tags = JsonConvert.DeserializeObject<string[]>(image.TagsJson) ?? Array.Empty<string>();
@@ -294,6 +292,13 @@
return Task.CompletedTask;
});
await Event.On<Server>($"server.{CurrentServer.Uuid}.archiveStatusChanged", this, server =>
{
NavigationManager.NavigateTo(NavigationManager.Uri, true);
return Task.CompletedTask;
});
if (string.IsNullOrEmpty(Image.BackgroundImageUrl))
await DynamicBackgroundService.Reset();
else
@@ -305,7 +310,7 @@
Logger.Debug("Server is null");
}
}
private async Task ReconnectConsole()
{
await Console!.Disconnect();
@@ -317,6 +322,7 @@
if (CurrentServer != null)
{
await Event.Off($"server.{CurrentServer.Uuid}.installComplete", this);
await Event.Off($"server.{CurrentServer.Uuid}.archiveStatusChanged", this);
}
if (Console != null)
@@ -324,4 +330,9 @@
Console.Dispose();
}
}
private async Task UnArchive()
{
await ServerService.UnArchiveServer(CurrentServer!);
}
}

View File

@@ -0,0 +1,158 @@
@using Moonlight.App.Database.Entities
@using Moonlight.App.Services
@using Moonlight.App.Services.Addon
@using Moonlight.App.ApiClients.Modrinth.Resources
@using Logging.Net
@using Moonlight.App.Services.Interop
@inject ServerAddonPluginService AddonPluginService
@inject SmartTranslateService SmartTranslateService
@inject ServerService ServerService
@inject ToastService ToastService
@if (Tags.Contains("addon-plugins"))
{
<div class="card">
<div class="card-header">
<span class="card-title">
<TL>Plugins</TL>
</span>
<div class="card-toolbar">
<div class="input-group">
<i class="bx bx-sm bx-search input-group-text"></i>
<input class="form-control"
placeholder="@(SmartTranslateService.Translate("Search for plugins"))"
@bind="PluginsSearch"/>
<WButton Text="@(SmartTranslateService.Translate("Search"))"
WorkingText="@(SmartTranslateService.Translate("Searching"))"
CssClasses="btn-primary"
OnClick="SearchPlugins">
</WButton>
</div>
</div>
</div>
<div class="card-body">
<LazyLoader @ref="PluginsLazyLoader" Load="LoadPlugins">
@foreach (var pluginsPart in Plugins.Chunk(3))
{
<div class="row">
@foreach (var plugin in pluginsPart)
{
<div class="col">
<div class="card p-2 card-bordered border-active">
<div class="d-flex justify-content-center">
<img height="100" width="100" src="@(plugin.IconUrl)" alt="@(plugin.Title)"/>
</div>
<div class="card-body">
<span class="card-title">@(plugin.Title)</span>
<p class="card-text">
@(plugin.Description)
</p>
<WButton Text="@(SmartTranslateService.Translate("Install"))"
WorkingText="@(SmartTranslateService.Translate("Installing"))"
CssClasses="btn-primary"
OnClick="() => InstallPlugin(plugin)">
</WButton>
</div>
</div>
</div>
}
</div>
}
</LazyLoader>
</div>
</div>
}
else
{
<div class="alert alert-primary d-flex rounded p-6">
<div class="d-flex flex-stack flex-grow-1 flex-wrap flex-md-nowrap">
<div class="mb-3 mb-md-0 fw-semibold">
<h4 class="text-gray-900 fw-bold">
<TL>Addons</TL>
</h4>
<div class="fs-6 text-gray-700 pe-7">
<TL>This feature is not available for</TL>&nbsp;<b>@(CurrentServer.Image.Name)</b>
</div>
</div>
</div>
</div>
}
@code
{
[CascadingParameter]
public Server CurrentServer { get; set; }
[CascadingParameter]
public string[] Tags { get; set; }
private string PluginsSearch = "";
private Project[] Plugins = Array.Empty<Project>();
private LazyLoader PluginsLazyLoader;
private bool IsPluginInstalling = false;
private async Task LoadPlugins(LazyLoader lazyLoader)
{
await lazyLoader.SetText(SmartTranslateService.Translate("Searching"));
var version = CurrentServer.Variables.First(x => x.Key == "MINECRAFT_VERSION").Value;
if (string.IsNullOrEmpty(version) || version == "latest")
version = "1.20.1"; // This should NOT be called at any time if all the images have the correct tags
Plugins = await AddonPluginService.GetPluginsForVersion(version, PluginsSearch);
}
private async Task SearchPlugins()
{
await PluginsLazyLoader.Reload();
}
private async Task InstallPlugin(Project project)
{
if (IsPluginInstalling)
{
await ToastService.Error(
SmartTranslateService.Translate("Please wait until the other plugin is installed"));
return;
}
IsPluginInstalling = true;
try
{
var fileAccess = await ServerService.CreateFileAccess(CurrentServer, null!);
var version = CurrentServer.Variables.First(x => x.Key == "MINECRAFT_VERSION").Value;
if (string.IsNullOrEmpty(version) || version == "latest")
version = "1.20.1"; // This should NOT be called at any time if all the images have the correct tags
await ToastService.CreateProcessToast("pluginDownload", "Preparing");
await AddonPluginService.InstallPlugin(fileAccess, version, project, delegate(string s)
{
Task.Run(async () =>
{
await ToastService.UpdateProcessToast("pluginDownload", s);
});
});
await ToastService.Success(
SmartTranslateService.Translate("Successfully installed " + project.Slug)
);
}
catch (Exception e)
{
Logger.Info(e.Message);
throw;
}
finally
{
IsPluginInstalling = false;
await ToastService.RemoveProcessToast("pluginDownload");
}
}
}

View File

@@ -57,7 +57,7 @@
<span class="ms-1 text-muted">
@if (User.Admin)
{
<a href="/admin/servers/edit/@(CurrentServer.Id)">@(CurrentServer.Id)</a>
<a href="/admin/servers/view/@(CurrentServer.Id)">@(CurrentServer.Id)</a>
}
else
{

View File

@@ -1,5 +1,5 @@
@using Moonlight.App.Database.Entities
@using Moonlight.Shared.Components.ServerControl.Settings
@using Moonlight.Shared.Views.Server.Settings
@using Microsoft.AspNetCore.Components.Rendering
<LazyLoader Load="Load">

View File

@@ -11,4 +11,5 @@
@using Moonlight.Shared.Components.StateLogic
@using Moonlight.Shared.Components.Alerts
@using Moonlight.Shared.Components.Forms
@using Moonlight.Shared.Components.Partials
@using Moonlight.Shared.Components.Partials
@using Moonlight.Shared.Components.Router

View File

@@ -302,8 +302,8 @@
console.log("Registering xterm addons");
window.XtermBlazor.registerAddon("xterm-addon-fit", new window.FitAddon.FitAddon());
window.XtermBlazor.registerAddon("xterm-addon-search", new window.SearchAddon.SearchAddon());
window.XtermBlazor.registerAddon("xterm-addon-web-links", new window.WebLinksAddon.WebLinksAddon());
//window.XtermBlazor.registerAddon("xterm-addon-search", new window.SearchAddon.SearchAddon());
//window.XtermBlazor.registerAddon("xterm-addon-web-links", new window.WebLinksAddon.WebLinksAddon());
},
loadMonaco: function ()
{

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.3 KiB