24 Commits
v1b6 ... v1b8

Author SHA1 Message Date
Marcel Baumgartner
432e441972 Change moonlight service to always fetch the changelog 2023-06-18 02:37:07 +02:00
Marcel Baumgartner
1dae5150bd Merge pull request #178 from Moonlight-Panel/RewriteNotificationSystem
Rewrite notification system
2023-06-18 02:32:33 +02:00
Marcel Baumgartner
72c6f636ee Rewritten notification system 2023-06-17 20:47:07 +02:00
Daniel Balk
e54d04277d Merge pull request #177 from Moonlight-Panel/ShowMoonlightAppInSessions
added check for moonlight app for getting the device
2023-06-17 17:52:41 +02:00
Daniel Balk
f559f08e8d added check for moonlight app for getting the device 2023-06-17 17:51:34 +02:00
Daniel Balk
2674fb3fa7 Update Debugging.razor 2023-06-17 14:10:24 +02:00
Marcel Baumgartner
d5d77ae7da Merge pull request #175 from Moonlight-Panel/AddMoonlightSideDnsCheckSsl
Added moonlight side dns check for ssl
2023-06-17 13:39:25 +02:00
Marcel Baumgartner
3ae905038c Added moonlight side dns check for ssl 2023-06-17 13:38:32 +02:00
Marcel Baumgartner
6707d722e0 Merge pull request #174 from Moonlight-Panel/SomeHotfixes
Fixed cleanup, error handling missing and missing gif
2023-06-17 13:00:12 +02:00
Marcel Baumgartner
bc9fecf6d9 Fixed cleanup, error handling missing and missing gif 2023-06-17 12:57:01 +02:00
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
75 changed files with 2839 additions and 297 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

@@ -5,6 +5,8 @@ namespace Moonlight.App.Exceptions;
[Serializable]
public class DisplayException : Exception
{
public bool DoNotTranslate { get; set; } = false;
//
// For guidelines regarding the creation of new exception types, see
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp
@@ -19,6 +21,11 @@ public class DisplayException : Exception
public DisplayException(string message) : base(message)
{
}
public DisplayException(string message, bool doNotTranslate) : base(message)
{
DoNotTranslate = doNotTranslate;
}
public DisplayException(string message, Exception inner) : base(message, inner)
{

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

@@ -1,7 +1,9 @@
using System.Net.WebSockets;
using System.Text;
using Logging.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Moonlight.App.Database.Entities;
using Moonlight.App.Database.Entities.Notification;
using Moonlight.App.Models.Notifications;
using Moonlight.App.Repositories;
@@ -12,135 +14,156 @@ using Newtonsoft.Json;
namespace Moonlight.App.Http.Controllers.Api.Moonlight.Notifications;
public class ListenController : ControllerBase
[ApiController]
[Route("api/moonlight/notification/listen")]
public class ListenController : Controller
{
internal WebSocket ws;
private bool active = true;
private bool isAuth = false;
private WebSocket WebSocket;
private NotificationClient Client;
private readonly IdentityService IdentityService;
private readonly NotificationRepository NotificationRepository;
private readonly OneTimeJwtService OneTimeJwtService;
private readonly NotificationClientService NotificationClientService;
private readonly NotificationServerService NotificationServerService;
private CancellationTokenSource CancellationTokenSource = new();
public ListenController(IdentityService identityService,
NotificationRepository notificationRepository,
OneTimeJwtService oneTimeJwtService,
NotificationClientService notificationClientService,
NotificationServerService notificationServerService)
private User? CurrentUser;
private readonly OneTimeJwtService OneTimeJwtService;
private readonly NotificationServerService NotificationServerService;
private readonly Repository<NotificationClient> NotificationClientRepository;
public ListenController(
OneTimeJwtService oneTimeJwtService,
NotificationServerService notificationServerService, Repository<NotificationClient> notificationClientRepository)
{
IdentityService = identityService;
NotificationRepository = notificationRepository;
OneTimeJwtService = oneTimeJwtService;
NotificationClientService = notificationClientService;
NotificationServerService = notificationServerService;
NotificationClientRepository = notificationClientRepository;
}
[Route("/api/moonlight/notifications/listen")]
public async Task Get()
public async Task<ActionResult> Get()
{
if (HttpContext.WebSockets.IsWebSocketRequest)
{
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
ws = webSocket;
await Echo();
WebSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
await ProcessWebsocket();
return new EmptyResult();
}
else
{
HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
return StatusCode(400);
}
}
private async Task Echo()
private async Task ProcessWebsocket()
{
while (active)
while (!CancellationTokenSource.Token.IsCancellationRequested && WebSocket.State == WebSocketState.Open)
{
byte[] bytes = new byte[1024 * 16];
var asg = new ArraySegment<byte>(bytes);
var res = await ws.ReceiveAsync(asg, CancellationToken.None);
var text = Encoding.UTF8.GetString(bytes).Trim('\0');
var obj = JsonConvert.DeserializeObject<BasicWSModel>(text);
if (!string.IsNullOrWhiteSpace(obj.Action))
try
{
await HandleRequest(text, obj.Action);
byte[] buffer = new byte[1024 * 16];
_ = await WebSocket.ReceiveAsync(buffer, CancellationTokenSource.Token);
var text = Encoding.UTF8.GetString(buffer).Trim('\0');
var basicWsModel = JsonConvert.DeserializeObject<BasicWSModel>(text) ?? new();
if (!string.IsNullOrWhiteSpace(basicWsModel.Action))
{
await HandleRequest(text, basicWsModel.Action);
}
if (WebSocket.State != WebSocketState.Open)
{
CancellationTokenSource.Cancel();
}
}
catch (WebSocketException e)
{
CancellationTokenSource.Cancel();
}
active = ws.State == WebSocketState.Open;
}
await NotificationServerService.UnRegisterClient(Client);
}
private async Task HandleRequest(string text, string action)
{
if (!isAuth && action == "login")
await Login(text);
else if (!isAuth)
await ws.SendAsync(Encoding.UTF8.GetBytes("{\"error\": \"Unauthorised\"}"), WebSocketMessageType.Text,
WebSocketMessageFlags.EndOfMessage, CancellationToken.None);
else switch (action)
if (CurrentUser == null && action != "login")
{
await Send("{\"error\": \"Unauthorised\"}");
}
switch (action)
{
case "login":
await Login(text);
break;
case "received":
await Received(text);
break;
case "read":
await Read(text);
break;
default:
break;
}
}
private async Task Send(string text)
{
await WebSocket.SendAsync(
Encoding.UTF8.GetBytes(text),
WebSocketMessageType.Text,
WebSocketMessageFlags.EndOfMessage, CancellationTokenSource.Token
);
}
private async Task Login(string json)
{
var jwt = JsonConvert.DeserializeObject<Login>(json).token;
var dict = await OneTimeJwtService.Validate(jwt);
var loginModel = JsonConvert.DeserializeObject<Login>(json) ?? new();
var dict = await OneTimeJwtService.Validate(loginModel.Token);
if (dict == null)
{
string error = "{\"status\":false}";
var bytes = Encoding.UTF8.GetBytes(error);
await ws.SendAsync(bytes, WebSocketMessageType.Text, WebSocketMessageFlags.EndOfMessage, CancellationToken.None);
await Send("{\"status\":false}");
return;
}
var _clientId = dict["clientId"];
var clientId = int.Parse(_clientId);
if (!int.TryParse(dict["clientId"], out int clientId))
{
await Send("{\"status\":false}");
return;
}
var client = NotificationRepository.GetClients().Include(x => x.User).First(x => x.Id == clientId);
Client = NotificationClientRepository
.Get()
.Include(x => x.User)
.First(x => x.Id == clientId);
Client = client;
await InitWebsocket();
string success = "{\"status\":true}";
var byt = Encoding.UTF8.GetBytes(success);
await ws.SendAsync(byt, WebSocketMessageType.Text, WebSocketMessageFlags.EndOfMessage, CancellationToken.None);
}
CurrentUser = Client.User;
private async Task InitWebsocket()
{
NotificationClientService.listenController = this;
NotificationClientService.WebsocketReady(Client);
await NotificationServerService.RegisterClient(WebSocket, Client);
isAuth = true;
await Send("{\"status\":true}");
}
private async Task Received(string json)
{
var id = JsonConvert.DeserializeObject<NotificationById>(json).notification;
var id = JsonConvert.DeserializeObject<NotificationById>(json).Notification;
//TODO: Implement ws notification received
}
private async Task Read(string json)
{
var id = JsonConvert.DeserializeObject<NotificationById>(json).notification;
var model = JsonConvert.DeserializeObject<NotificationById>(json) ?? new();
await NotificationServerService.SendAction(NotificationClientService.User,
JsonConvert.SerializeObject(new NotificationById() {Action = "hide", notification = id}));
await NotificationServerService.SendAction(
CurrentUser!,
JsonConvert.SerializeObject(
new NotificationById()
{
Action = "hide", Notification = model.Notification
}
)
);
}
}

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,19 @@
using System.Net.WebSockets;
using System.Text;
using Moonlight.App.Database.Entities.Notification;
namespace Moonlight.App.Models.Misc;
public class ActiveNotificationClient
{
public WebSocket WebSocket { get; set; }
public NotificationClient Client { get; set; }
public async Task SendAction(string action)
{
await WebSocket.SendAsync(
Encoding.UTF8.GetBytes(action),
WebSocketMessageType.Text,
WebSocketMessageFlags.EndOfMessage, CancellationToken.None);
}
}

View File

@@ -1,6 +1,8 @@
namespace Moonlight.App.Models.Notifications;
using Newtonsoft.Json;
namespace Moonlight.App.Models.Notifications;
public class Login : BasicWSModel
{
public string token { get; set; }
[JsonProperty("token")] public string Token { get; set; } = "";
}

View File

@@ -1,6 +1,9 @@
namespace Moonlight.App.Models.Notifications;
using Newtonsoft.Json;
namespace Moonlight.App.Models.Notifications;
public class NotificationById : BasicWSModel
{
public int notification { get; set; }
[JsonProperty("notification")]
public int Notification { 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

@@ -85,7 +85,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 +163,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 +189,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

@@ -33,9 +33,6 @@ public class MoonlightService
private async Task FetchChangeLog()
{
if(AppVersion == "unknown")
return;
if (ConfigService.DebugMode)
{
ChangeLog.Add(new[]

View File

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

View File

@@ -1,43 +0,0 @@
using System.Net.WebSockets;
using System.Text;
using Moonlight.App.Database.Entities;
using Moonlight.App.Database.Entities.Notification;
using Moonlight.App.Http.Controllers.Api.Moonlight.Notifications;
using Moonlight.App.Repositories;
using Moonlight.App.Services.Sessions;
namespace Moonlight.App.Services.Notifications;
public class NotificationClientService
{
private readonly NotificationRepository NotificationRepository;
private readonly NotificationServerService NotificationServerService;
internal ListenController listenController;
public NotificationClientService(NotificationRepository notificationRepository, NotificationServerService notificationServerService)
{
NotificationRepository = notificationRepository;
NotificationServerService = notificationServerService;
}
public User User => NotificationClient.User;
public NotificationClient NotificationClient { get; set; }
public async Task SendAction(string action)
{
await listenController.ws.SendAsync(Encoding.UTF8.GetBytes(action), WebSocketMessageType.Text,
WebSocketMessageFlags.EndOfMessage, CancellationToken.None);
}
public void WebsocketReady(NotificationClient client)
{
NotificationClient = client;
NotificationServerService.AddClient(this);
}
public void WebsocketClosed()
{
NotificationServerService.RemoveClient(this);
}
}

View File

@@ -1,79 +1,113 @@
using Microsoft.EntityFrameworkCore;
using System.Net.WebSockets;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Moonlight.App.Database.Entities;
using Moonlight.App.Database.Entities.Notification;
using Moonlight.App.Events;
using Moonlight.App.Models.Misc;
using Moonlight.App.Repositories;
namespace Moonlight.App.Services.Notifications;
public class NotificationServerService
{
private UserRepository UserRepository;
private NotificationRepository NotificationRepository;
private readonly List<ActiveNotificationClient> ActiveClients = new();
private readonly IServiceScopeFactory ServiceScopeFactory;
private IServiceScope ServiceScope;
public NotificationServerService(IServiceScopeFactory serviceScopeFactory)
private readonly EventSystem Event;
public NotificationServerService(IServiceScopeFactory serviceScopeFactory, EventSystem eventSystem)
{
ServiceScopeFactory = serviceScopeFactory;
Task.Run(Run);
}
private Task Run()
{
ServiceScope = ServiceScopeFactory.CreateScope();
UserRepository = ServiceScope
.ServiceProvider
.GetRequiredService<UserRepository>();
NotificationRepository = ServiceScope
.ServiceProvider
.GetRequiredService<NotificationRepository>();
return Task.CompletedTask;
Event = eventSystem;
}
private List<NotificationClientService> connectedClients = new();
public List<NotificationClientService> GetConnectedClients(User user)
public Task<ActiveNotificationClient[]> GetActiveClients()
{
return connectedClients.Where(x => x.User == user).ToList();
lock (ActiveClients)
{
return Task.FromResult(ActiveClients.ToArray());
}
}
public Task<ActiveNotificationClient[]> GetUserClients(User user)
{
lock (ActiveClients)
{
return Task.FromResult(
ActiveClients
.Where(x => x.Client.User.Id == user.Id)
.ToArray()
);
}
}
public async Task SendAction(User user, string action)
{
var clients = NotificationRepository.GetClients().Include(x => x.User).Where(x => x.User == user).ToList();
using var scope = ServiceScopeFactory.CreateScope();
var notificationClientRepository =
scope.ServiceProvider.GetRequiredService<Repository<NotificationClient>>();
var clients = notificationClientRepository
.Get()
.Include(x => x.User)
.Where(x => x.User == user)
.ToList();
foreach (var client in clients)
{
var notificationAction = new NotificationAction()
{
Action = action,
NotificationClient = client
};
var connected = connectedClients.Where(x => x.NotificationClient.Id == client.Id).ToList();
ActiveNotificationClient[] connectedUserClients;
if (connected.Count > 0)
lock (ActiveClients)
{
var clientService = connected[0];
await clientService.SendAction(action);
connectedUserClients = ActiveClients
.Where(x => x.Client.Id == user.Id)
.ToArray();
}
if (connectedUserClients.Length > 0)
{
await connectedUserClients[0].SendAction(action);
}
else
{
NotificationRepository.AddAction(notificationAction);
var notificationAction = new NotificationAction()
{
Action = action,
NotificationClient = client
};
var notificationActionsRepository =
scope.ServiceProvider.GetRequiredService<Repository<NotificationAction>>();
notificationActionsRepository.Add(notificationAction);
}
}
}
public void AddClient(NotificationClientService notificationClientService)
public async Task RegisterClient(WebSocket webSocket, NotificationClient notificationClient)
{
connectedClients.Add(notificationClientService);
var newClient = new ActiveNotificationClient()
{
WebSocket = webSocket,
Client = notificationClient
};
lock (ActiveClients)
{
ActiveClients.Add(newClient);
}
await Event.Emit("notifications.addClient", notificationClient);
}
public void RemoveClient(NotificationClientService notificationClientService)
public async Task UnRegisterClient(NotificationClient client)
{
connectedClients.Remove(notificationClientService);
lock (ActiveClients)
{
ActiveClients.RemoveAll(x => x.Client == client);
}
await Event.Emit("notifications.removeClient", client);
}
}

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

@@ -159,8 +159,17 @@ public class IdentityService
try
{
var userAgent = HttpContextAccessor.HttpContext.Request.Headers.UserAgent.ToString();
if (userAgent.Contains("Moonlight.App"))
{
var version = userAgent.Remove(0, "Moonlight.App/".Length).Split(' ').FirstOrDefault();
return "Moonlight App " + version;
}
var uaParser = Parser.GetDefault();
var info = uaParser.Parse(HttpContextAccessor.HttpContext.Request.Headers.UserAgent);
var info = uaParser.Parse(userAgent);
return $"{info.OS} - {info.Device}";
}

View File

@@ -1,4 +1,7 @@
using Microsoft.EntityFrameworkCore;
using System.Net;
using DnsClient;
using Logging.Net;
using Microsoft.EntityFrameworkCore;
using Moonlight.App.ApiClients.CloudPanel;
using Moonlight.App.ApiClients.CloudPanel.Requests;
using Moonlight.App.Database.Entities;
@@ -18,7 +21,8 @@ public class WebSpaceService
private readonly CloudPanelApiHelper CloudPanelApiHelper;
public WebSpaceService(Repository<CloudPanel> cloudPanelRepository, Repository<WebSpace> webSpaceRepository, CloudPanelApiHelper cloudPanelApiHelper, Repository<MySqlDatabase> databaseRepository)
public WebSpaceService(Repository<CloudPanel> cloudPanelRepository, Repository<WebSpace> webSpaceRepository,
CloudPanelApiHelper cloudPanelApiHelper, Repository<MySqlDatabase> databaseRepository)
{
CloudPanelRepository = cloudPanelRepository;
WebSpaceRepository = webSpaceRepository;
@@ -37,7 +41,7 @@ public class WebSpaceService
var ftpPassword = StringHelper.GenerateString(16);
var phpVersion = "8.1"; // TODO: Add config option or smth
var w = new WebSpace()
{
CloudPanel = cloudPanel,
@@ -83,9 +87,9 @@ public class WebSpaceService
{
await DeleteDatabase(webSpace, database);
}
await CloudPanelApiHelper.Delete(webSpace.CloudPanel, $"site/{webSpace.Domain}", null);
WebSpaceRepository.Delete(webSpace);
}
@@ -109,7 +113,7 @@ public class WebSpaceService
return false;
}
public async Task<bool> IsHostUp(WebSpace w)
{
var webSpace = EnsureData(w);
@@ -121,6 +125,52 @@ public class WebSpaceService
{
var webspace = EnsureData(w);
var dns = new LookupClient(new LookupClientOptions()
{
CacheFailedResults = false,
UseCache = false
});
var ipOfWebspaceQuery = await dns.QueryAsync(
webspace.Domain,
QueryType.A
);
var ipOfWebspaceWwwQuery = await dns.QueryAsync(
"www." + webspace.Domain,
QueryType.CNAME
);
var ipOfWebspace = ipOfWebspaceQuery.Answers.ARecords().FirstOrDefault();
var ipOfWebspaceWww = ipOfWebspaceWwwQuery.Answers.CnameRecords().FirstOrDefault();
if (ipOfWebspace == null)
throw new DisplayException($"Unable to find any a records for {webspace.Domain}", true);
if (ipOfWebspaceWww == null)
throw new DisplayException($"Unable to find any cname records for www.{webspace.Domain}", true);
var ipOfHostQuery = await dns.QueryAsync(
webspace.CloudPanel.Host,
QueryType.A
);
var ipOfHost = ipOfHostQuery.Answers.ARecords().FirstOrDefault();
if (ipOfHost == null)
throw new DisplayException("Unable to find a record of host system");
if (ipOfHost.Address.ToString() != ipOfWebspace.Address.ToString())
throw new DisplayException("The dns records of your webspace do not point to the host system");
Logger.Debug($"{ipOfWebspaceWww.CanonicalName.Value}");
if (ipOfWebspaceWww.CanonicalName.Value != webspace.CloudPanel.Host + ".")
throw new DisplayException(
$"The dns record www.{webspace.Domain} does not point to {webspace.CloudPanel.Host}", true);
await CloudPanelApiHelper.Post(webspace.CloudPanel, "letsencrypt/install/certificate", new InstallLetsEncrypt()
{
DomainName = webspace.Domain
@@ -158,7 +208,7 @@ public class WebSpaceService
DatabaseUserName = database.UserName,
DatabaseUserPassword = database.Password
});
webspace.Databases.Add(database);
WebSpaceRepository.Update(webspace);
}
@@ -166,7 +216,7 @@ public class WebSpaceService
public async Task DeleteDatabase(WebSpace w, MySqlDatabase database)
{
var webspace = EnsureData(w);
await CloudPanelApiHelper.Delete(webspace.CloudPanel, $"db/{database.UserName}", null);
webspace.Databases.Remove(database);
@@ -180,7 +230,8 @@ public class WebSpaceService
var webspace = EnsureData(w);
return Task.FromResult<FileAccess>(
new SftpFileAccess(webspace.CloudPanel.Host, webspace.UserName, webspace.Password, 22, true, $"/htdocs/{webspace.Domain}")
new SftpFileAccess(webspace.CloudPanel.Host, webspace.UserName, webspace.Password, 22, true,
$"/htdocs/{webspace.Domain}")
);
}
@@ -192,7 +243,7 @@ public class WebSpaceService
.Include(x => x.CloudPanel)
.Include(x => x.Owner)
.First(x => x.Id == webSpace.Id);
return webSpace;
}
}

View File

@@ -21,6 +21,7 @@
<PackageReference Include="CurrieTechnologies.Razor.SweetAlert2" Version="5.4.0" />
<PackageReference Include="Discord.Net" Version="3.10.0" />
<PackageReference Include="Discord.Net.Webhook" Version="3.10.0" />
<PackageReference Include="DnsClient" Version="1.7.0" />
<PackageReference Include="FluentFTP" Version="46.0.2" />
<PackageReference Include="GravatarSharp.Core" Version="1.0.1.2" />
<PackageReference Include="JWT" Version="10.0.2" />
@@ -48,7 +49,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 +80,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;
@@ -116,7 +118,6 @@ namespace Moonlight
builder.Services.AddScoped<OneTimeJwtService>();
builder.Services.AddSingleton<NotificationServerService>();
builder.Services.AddScoped<NotificationAdminService>();
builder.Services.AddScoped<NotificationClientService>();
builder.Services.AddScoped<ModalService>();
builder.Services.AddScoped<SmartDeployService>();
builder.Services.AddScoped<WebSpaceService>();
@@ -132,6 +133,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 +161,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,14 +40,25 @@ 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)
);
if (displayException.DoNotTranslate)
{
await AlertService.Error(
displayException.Message
);
}
else
{
await AlertService.Error(
SmartTranslateService.Translate(displayException.Message)
);
}
}
else if (exception is CloudflareException cloudflareException)
{
@@ -56,7 +70,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 +78,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 +107,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,25 +22,25 @@
@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()} - ";
}
}
}
<GlobalErrorBoundary>
<CascadingValue Value="User">
<PageTitle>@(string.IsNullOrEmpty(title) ? "Dashboard - " : title)Moonlight</PageTitle>
@@ -190,16 +190,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,74 @@
@page "/admin/notifications/debugging"
@using Moonlight.App.Services.Notifications
@using Moonlight.App.Models.Misc
@using Moonlight.App.Events
@using BlazorTable
@using Moonlight.App.Database.Entities.Notification
@using Moonlight.App.Services
@inject NotificationServerService NotificationServerService
@inject SmartTranslateService SmartTranslateService
@inject EventSystem Event
@implements IDisposable
<OnlyAdmin>
<LazyLoader Load="Load">
<div class="card card-body">
<Table TableItem="ActiveNotificationClient" Items="Clients" PageSize="25" TableClass="table table-row-bordered table-row-gray-100 align-middle gs-0 gy-3" TableHeadClass="fw-bold text-muted">
<Column TableItem="ActiveNotificationClient" Title="@(SmartTranslateService.Translate("Id"))" Field="@(x => x.Client.Id)" Sortable="false" Filterable="true"/>
<Column TableItem="ActiveNotificationClient" Title="@(SmartTranslateService.Translate("User"))" Field="@(x => x.Client.User.Email)" Sortable="false" Filterable="true"/>
<Column TableItem="ActiveNotificationClient" Title="" Field="@(x => x.Client.Id)" Sortable="false" Filterable="false">
<Template>
<WButton Text="@(SmartTranslateService.Translate("Send notification"))"
WorkingText="@(SmartTranslateService.Translate("Working"))"
CssClasses="btn-primary"
OnClick="() => SendSampleNotification(context)">
</WButton>
</Template>
</Column>
<Pager ShowPageNumber="true" ShowTotalCount="true"/>
</Table>
</div>
</LazyLoader>
</OnlyAdmin>
@code
{
private ActiveNotificationClient[] Clients;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await Event.On<NotificationClient>("notifications.addClient", this, async client =>
{
Clients = await NotificationServerService.GetActiveClients();
await InvokeAsync(StateHasChanged);
});
await Event.On<NotificationClient>("notifications.removeClient", this, async client =>
{
Clients = await NotificationServerService.GetActiveClients();
await InvokeAsync(StateHasChanged);
});
}
}
private async Task Load(LazyLoader loader)
{
Clients = await NotificationServerService.GetActiveClients();
}
private async Task SendSampleNotification(ActiveNotificationClient client)
{
await client.SendAction(@"{""action"": ""notify"",""notification"":{""id"":999,""channel"":""Sample Channel"",""content"":""This is a sample Notification"",""title"":""Sample Notification"",""url"":""server/9b724fe2-d882-49c9-8c34-3414c7e4a17e""}}");
}
public async void Dispose()
{
await Event.Off("notifications.addClient", this);
await Event.Off("notifications.removeClient", this);
}
}

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 ()
{

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.3 KiB