mirror of
https://github.com/chylex/Minecraft-Phantom-Panel.git
synced 2024-11-22 08:42:44 +01:00
57 lines
2.1 KiB
C#
57 lines
2.1 KiB
C#
using System.Text.RegularExpressions;
|
|
using Phantom.Common.Logging;
|
|
using Serilog;
|
|
|
|
namespace Phantom.Agent.Minecraft.Server;
|
|
|
|
public sealed class MinecraftServerExecutables {
|
|
private static readonly ILogger Logger = PhantomLogger.Create<MinecraftServerExecutables>();
|
|
|
|
private static readonly Regex VersionFolderSanitizeRegex = new (@"[^a-zA-Z0-9_\-\.]", RegexOptions.Compiled);
|
|
|
|
private readonly string basePath;
|
|
private readonly Dictionary<string, MinecraftServerExecutableDownloader> runningDownloadersByVersion = new ();
|
|
|
|
public MinecraftServerExecutables(string basePath) {
|
|
this.basePath = basePath;
|
|
}
|
|
|
|
internal async Task<string?> DownloadAndGetPath(string version, EventHandler<DownloadProgressEventArgs> progressEventHandler, CancellationToken cancellationToken) {
|
|
string serverExecutableFolderPath = Path.Combine(basePath, VersionFolderSanitizeRegex.Replace(version, "_"));
|
|
string serverExecutableFilePath = Path.Combine(serverExecutableFolderPath, "server.jar");
|
|
|
|
if (File.Exists(serverExecutableFilePath)) {
|
|
return serverExecutableFilePath;
|
|
}
|
|
|
|
try {
|
|
Directory.CreateDirectory(serverExecutableFolderPath);
|
|
} catch (Exception e) {
|
|
Logger.Error(e, "Unable to create folder for server executable: {ServerExecutableFolderPath}", serverExecutableFolderPath);
|
|
return null;
|
|
}
|
|
|
|
MinecraftServerExecutableDownloader? downloader;
|
|
MinecraftServerExecutableDownloadListener listener = new (progressEventHandler, cancellationToken);
|
|
|
|
lock (this) {
|
|
if (runningDownloadersByVersion.TryGetValue(version, out downloader)) {
|
|
Logger.Information("A download for server version {Version} is already running, waiting for it to finish...", version);
|
|
downloader.Register(listener);
|
|
}
|
|
else {
|
|
downloader = new MinecraftServerExecutableDownloader(version, serverExecutableFilePath, listener);
|
|
downloader.Completed += (_, _) => {
|
|
lock (this) {
|
|
runningDownloadersByVersion.Remove(version);
|
|
}
|
|
};
|
|
|
|
runningDownloadersByVersion[version] = downloader;
|
|
}
|
|
}
|
|
|
|
return await downloader.Task.WaitAsync(cancellationToken);
|
|
}
|
|
}
|