Merge pull request #170 from Moonlight-Panel/AddModrinthSupport

Add modrinth support
This commit is contained in:
Marcel Baumgartner
2023-06-16 20:29:45 +02:00
committed by GitHub
35 changed files with 542 additions and 71 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

@@ -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

@@ -370,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); });
}

View File

@@ -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

@@ -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)
@@ -36,13 +39,15 @@ else
private bool Crashed = false;
protected override async Task OnErrorAsync(Exception 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

@@ -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,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
@@ -106,61 +104,38 @@
<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;
}
<SmartRouter Route="@Route">
<Route Path="/">
<ServerNavigation Index="0">
<ServerConsole/>
</ServerNavigation>
</CascadingValue>
</CascadingValue>
</CascadingValue>
</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>

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

@@ -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">