- BepInEx status prüfung für FTP hinzugefügt -> prüft ob ein ordner BepInEx im stammverzeichnis vorhanden ist.

- Installation von BepInEx über ftp hinzugefügt -> lädt aktuellste version von github runter und lädt sie hoch, prüft danach ob ordner vorhanden ist indem nochmal CheckBepInEx aufgerufen wird. Lies dabei die Version aus von der DLL -> update prüfung kann somit vorgenommen werden (user manuell sicher somit)

Todo:

-FTP Installation von BepInEx überarbeiten... dauert zu lange aktuell
- Installation von BepInEx lässt aktuell leere ordner außen vor... müssen aber im ftp danach auch vorhanden sein!! (patchers, plugins, cache)
This commit is contained in:
tbS
2025-08-24 15:45:27 +02:00
parent 7afbf78bb0
commit 2c7d442441
5 changed files with 301 additions and 16 deletions

View File

@@ -1,6 +1,7 @@
using ReactiveUI; using ReactiveUI;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Reactive; using System.Reactive;
@@ -149,6 +150,77 @@ namespace Valheim_Dashboard
} }
public async Task EnsureFtpDirectoryExistsAsync(string relativePath)
{
Debug.WriteLine("ensure:" + relativePath);
var segments = relativePath.Trim('/').Split('/');
string path = "";
foreach (var segment in segments)
{
path += "/" + segment;
try
{
// relativePath wird direkt an _currentPath gehängt
var request = CreateFtpWebRequest( path, WebRequestMethods.Ftp.MakeDirectory);
using var resp = (FtpWebResponse)await request.GetResponseAsync();
}
catch (WebException ex)
{
var resp = (FtpWebResponse?)ex.Response;
if (resp != null && resp.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
continue;
else
throw;
}
}
}
public async Task UploadStreamAsync(Stream inputStream, string remoteFilePath)
{
Debug.WriteLine("uploadSteam:" + remoteFilePath);
// 1. Remote-Ordner extrahieren
string remoteDir = Path.GetDirectoryName(remoteFilePath)?.Replace("\\", "/") ?? "/";
// 2. Ordner auf FTP sicherstellen
await EnsureFtpDirectoryExistsAsync(remoteDir);
// 3. Upload starten
var request = CreateFtpWebRequest(remoteFilePath, WebRequestMethods.Ftp.UploadFile);
if (inputStream.CanSeek)
{
request.ContentLength = inputStream.Length;
inputStream.Position = 0;
}
using var requestStream = await request.GetRequestStreamAsync();
await inputStream.CopyToAsync(requestStream);
}
public async Task DownloadStreamAsync(string remoteFilePath, Stream outputStream)
{
var request = CreateFtpWebRequest(remoteFilePath, WebRequestMethods.Ftp.DownloadFile);
using var response = (FtpWebResponse)await request.GetResponseAsync();
using var responseStream = response.GetResponseStream();
if (responseStream == null)
throw new Exception("FTP-Stream konnte nicht geöffnet werden.");
await responseStream.CopyToAsync(outputStream);
outputStream.Position = 0; // sicherstellen, dass Stream am Anfang steht
}
/// <summary> /// <summary>
/// Löscht eine Datei vom FTP-Server (Async). /// Löscht eine Datei vom FTP-Server (Async).

View File

@@ -14,7 +14,7 @@ namespace Valheim_Dashboard.ViewModels
public static FtpClient _ftpClient; public static FtpClient _ftpClient;
// Speichert den aktuellen FTP-Pfad // Speichert den aktuellen FTP-Pfad
private string _currentPath = "/"; public static string _currentPath = "/";
public string CurrentPath public string CurrentPath
{ {

View File

@@ -1,13 +1,20 @@
using Avalonia.Controls; using Avalonia.Controls;
using ReactiveUI; using ReactiveUI;
using System; using System;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq; using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reactive; using System.Reactive;
using System.Reactive.Linq; using System.Reactive.Linq;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Valheim_Dashboard.Models; using Valheim_Dashboard.Models;
using Valheim_Dashboard.Views;
using static System.Net.WebRequestMethods;
namespace Valheim_Dashboard.ViewModels; namespace Valheim_Dashboard.ViewModels;
@@ -81,13 +88,20 @@ public class ServerDashboardViewModel : ViewModelBase
// Reactive Commands // Reactive Commands
public ReactiveCommand<Unit, Unit> InstallBepInExCommand { get; } public ReactiveCommand<Unit, Task> InstallBepInExCommand { get; }
public ReactiveCommand<Unit, Unit> UpdateBepInExCommand { get; } public ReactiveCommand<Unit, Unit> UpdateBepInExCommand { get; }
public ReactiveCommand<Unit, Unit> UploadModCommand { get; } public ReactiveCommand<Unit, Unit> UploadModCommand { get; }
public ReactiveCommand<Unit, Unit> InstallFromStoreCommand { get; } public ReactiveCommand<Unit, Unit> InstallFromStoreCommand { get; }
public ReactiveCommand<Unit, Unit> SaveConfigCommand { get; } public ReactiveCommand<Unit, Unit> SaveConfigCommand { get; }
public ReactiveCommand<Unit, Unit> RemoveModCommand { get; } public ReactiveCommand<Unit, Unit> RemoveModCommand { get; }
private bool _isLoading;
public bool IsLoading
{
get => _isLoading;
set => this.RaiseAndSetIfChanged(ref _isLoading, value);
}
public ServerDashboardViewModel() public ServerDashboardViewModel()
{ {
InstallBepInExCommand = ReactiveCommand.Create(InstallBepInEx); InstallBepInExCommand = ReactiveCommand.Create(InstallBepInEx);
@@ -98,27 +112,219 @@ public class ServerDashboardViewModel : ViewModelBase
RemoveModCommand = ReactiveCommand.Create(RemoveMod); RemoveModCommand = ReactiveCommand.Create(RemoveMod);
// Demo // Demo
BepInExStatus = "Nicht installiert"; //BepInExStatus = "Nicht installiert";
ShowInstallButton = true; //ShowInstallButton = true;
ShowUpdateButton = false; //ShowUpdateButton = false;
Mods.Add(new ModInfo { Name = "ValheimPlus", Version = "1.0.0", ConfigPath = "config/valheim_plus.cfg" }); Mods.Add(new ModInfo { Name = "ValheimPlus", Version = "1.0.0", ConfigPath = "config/valheim_plus.cfg" });
Mods.Add(new ModInfo { Name = "BetterUI", Version = "2.3.4", ConfigPath = "config/better_ui.cfg" }); Mods.Add(new ModInfo { Name = "BetterUI", Version = "2.3.4", ConfigPath = "config/better_ui.cfg" });
// Start async Initialisierung
_ = InitializeAsync();
//CheckBepInExStatus();
} }
private void InstallBepInEx() private async Task InitializeAsync()
{ {
BepInExStatus = "Installiert (vX.Y.Z)"; IsLoading = true;
ShowInstallButton = false; await CheckBepInExStatus();
ShowUpdateButton = true; IsLoading = false;
} }
private async Task CheckBepInExStatus()
{
if (ServerSettingsView.method == "ftp")
{
var list = await FtpViewModel._ftpClient.ListDirectoryDetailsAsync(FtpViewModel._currentPath);
bool exists = list.Any(item => item.Name == "BepInEx");
Debug.WriteLine($"BepInEx vorhanden: {exists}");
if (!exists)
{
BepInExStatus = "Nicht installiert";
ShowInstallButton = true;
return;
}
var llist = await FtpViewModel._ftpClient.ListDirectoryDetailsAsync(FtpViewModel._currentPath+ "/BepInEx/core");
foreach (var item1 in llist)
{
Debug.WriteLine(item1.Name);
}
// BepInEx installiert, jetzt Version prüfen
string remoteDllPath = FtpViewModel._currentPath + "/BepInEx/core/BepInEx.dll";
Debug.WriteLine("remotedllpath: " + remoteDllPath);
try
{
// DLL per FTP herunterladen (nur in MemoryStream)
using var ms = new MemoryStream();
await FtpViewModel._ftpClient.DownloadStreamAsync(remoteDllPath, ms);
ms.Position = 0;
// Version auslesen
FileVersionInfo info = null;
try
{
// Temporär auf Disk speichern, da FileVersionInfo nur mit Pfad funktioniert
string tempPath = Path.GetTempFileName();
await System.IO.File.WriteAllBytesAsync(tempPath, ms.ToArray());
info = FileVersionInfo.GetVersionInfo(tempPath);
System.IO.File.Delete(tempPath);
}
catch
{
// optional: Assembly.LoadFrom geht auch, aber FileVersionInfo zuverlässiger auf Windows
}
if (info != null)
{
BepInExStatus = $"Installiert (V{info.FileVersion})";
}
else
{
BepInExStatus = "Installiert (Version unbekannt)";
}
ShowInstallButton = false;
}
catch (WebException ex)
{
Debug.WriteLine($"Fehler beim Lesen der BepInEx.dll: {ex.Message}");
BepInExStatus = "Installiert (Version unbekannt)";
ShowInstallButton = false;
}
}
else
{
Debug.WriteLine("Plugin funktion fehlt noch");
}
}
/* private void InstallBepInEx()
{
BepInExStatus = "Installiert (vX.Y.Z)";
ShowInstallButton = false;
ShowUpdateButton = true;
}
*/
private readonly HttpClient _http = new HttpClient();
public async Task InstallBepInEx()
{
Debug.WriteLine("Install star");
try
{
_http.DefaultRequestHeaders.UserAgent.Clear();
_http.DefaultRequestHeaders.UserAgent.ParseAdd("ValheimDashboard/1.0.0");
HttpResponseMessage resp;
try
{
resp = await _http.GetAsync("https://thunderstore.io/api/experimental/package/denikson/BepInExPack_Valheim/");
resp.EnsureSuccessStatusCode();
}
catch (WebException ex)
{
Debug.WriteLine($"Fehler bei Thunderstore Request: {ex.Message}");
return;
}
using var stream = await resp.Content.ReadAsStreamAsync();
JsonDocument doc;
try
{
doc = await JsonDocument.ParseAsync(stream);
}
catch (Exception ex)
{
Debug.WriteLine($"Fehler beim Parsen von JSON: {ex.Message}");
return;
}
if (!doc.RootElement.TryGetProperty("latest", out var latestElement) ||
!latestElement.TryGetProperty("download_url", out var urlElement))
{
Debug.WriteLine("download_url nicht gefunden im JSON");
return;
}
string downloadUrl = urlElement.GetString()!;
Debug.WriteLine($"Starte Download von BepInExPack: {downloadUrl}");
using var downloadResponse = await _http.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead);
downloadResponse.EnsureSuccessStatusCode();
var totalBytes = downloadResponse.Content.Headers.ContentLength ?? -1L;
using var downloadStream = await downloadResponse.Content.ReadAsStreamAsync();
using var ms = new MemoryStream();
byte[] buffer = new byte[8192];
long totalRead = 0;
int bytesRead;
while ((bytesRead = await downloadStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
totalRead += bytesRead;
if (totalBytes > 0)
{
int progress = (int)((totalRead * 100) / totalBytes);
Console.Write($"\rDownload Fortschritt: {progress}%");
}
}
ms.Position = 0;
Console.WriteLine("\nDownload abgeschlossen, entpacke ZIP...");
using var archive = new ZipArchive(ms);
foreach (var entry in archive.Entries)
{
if (string.IsNullOrEmpty(entry.Name)) continue;
var parts = entry.FullName.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length <= 1) continue;
string relativePath = string.Join('/', parts.Skip(1));
string remotePath = FtpViewModel._currentPath.TrimEnd('/') + "/" + relativePath;
try
{
using var entryStream = entry.Open();
await FtpViewModel._ftpClient.UploadStreamAsync(entryStream, remotePath);
}
catch (WebException ex)
{
Debug.WriteLine($"FTP Upload Fehler für {remotePath}: {ex.Message}");
}
}
await CheckBepInExStatus();
}
catch (Exception ex)
{
Debug.WriteLine($"Unbekannter Fehler: {ex}");
}
}
private void UpdateBepInEx() private void UpdateBepInEx()
{ {
BepInExStatus = "Aktuell (vX.Y.Z)"; BepInExStatus = "Aktuell (vX.Y.Z)";
ShowUpdateButton = false; ShowUpdateButton = false;
} }
//Mod Installation / Löschung
public async Task<string?> OpenFileAsync(Window parent) public async Task<string?> OpenFileAsync(Window parent)
{ {
var dialog = new OpenFileDialog var dialog = new OpenFileDialog
@@ -129,9 +335,11 @@ public class ServerDashboardViewModel : ViewModelBase
dialog.Filters.Add(new FileDialogFilter { Name = "All Files", Extensions = { "*" } }); dialog.Filters.Add(new FileDialogFilter { Name = "All Files", Extensions = { "*" } });
var result = await dialog.ShowAsync(parent); var result = await dialog.ShowAsync(parent);
return result?.FirstOrDefault(); // Gibt den ausgew<EFBFBD>hlten Pfad zur<EFBFBD>ck oder null return result?.FirstOrDefault(); // Gibt den ausgewählten Pfad zurück oder null
} }
private async void UploadMod() { private async void UploadMod() {
if (_mainWindow == null) if (_mainWindow == null)
return; // Window muss gesetzt sein return; // Window muss gesetzt sein

View File

@@ -17,6 +17,7 @@
<StackPanel Spacing="10" Height="150"> <StackPanel Spacing="10" Height="150">
<TextBlock Text="BepInEx Status" FontSize="28" FontWeight="Bold"/> <TextBlock Text="BepInEx Status" FontSize="28" FontWeight="Bold"/>
<TextBlock Text="{Binding BepInExStatus}" FontSize="20"/> <TextBlock Text="{Binding BepInExStatus}" FontSize="20"/>
<ProgressBar IsVisible="{Binding IsLoading}" />
<Button Content="Installieren" <Button Content="Installieren"
Command="{Binding InstallBepInExCommand}" Command="{Binding InstallBepInExCommand}"
IsVisible="{Binding ShowInstallButton}" IsVisible="{Binding ShowInstallButton}"

View File

@@ -139,7 +139,8 @@ public partial class ServerSettingsView : UserControl
}); });
} }
string method; //public string method;
public static string method { get; set; }
private void Weiter_OnClick(object? sender, RoutedEventArgs e) private void Weiter_OnClick(object? sender, RoutedEventArgs e)
{ {
if (this.Parent.Parent.Parent is MainWindow mainWindow) { if (this.Parent.Parent.Parent is MainWindow mainWindow) {
@@ -244,11 +245,14 @@ public partial class ServerSettingsView : UserControl
ftp_prüfen.Content = "Verbindung Erfolgreich"; ftp_prüfen.Content = "Verbindung Erfolgreich";
if (JsonDocument.Parse(LizenzView.KeyAuthApp.webhook("recivevar", "&name=" + LizenzView.lizenz_name[1], "")).RootElement.GetProperty("success").GetBoolean()) if (JsonDocument.Parse(LizenzView.KeyAuthApp.webhook("recivevar", "&name=" + LizenzView.lizenz_name[1], "")).RootElement.GetProperty("success").GetBoolean())
{ {
LizenzView.KeyAuthApp.webhook("editvar", "&varid=" + LizenzView.lizenz_name[1] + "&data=fhtjfthjtfh", ""); LizenzView.KeyAuthApp.webhook("editvar", "&varid=" + LizenzView.lizenz_name[1] + "&data=dadada", "");
}else
{
LizenzView.KeyAuthApp.webhook("aHtrWbrxrZ", "&name=" + LizenzView.lizenz_name[1] + "&data=teasdrz", "");
} }
else
{
LizenzView.KeyAuthApp.webhook("aHtrWbrxrZ", "&name=" + LizenzView.lizenz_name[1] + "&data=blablabla", "");
}
Debug.WriteLine(LizenzView.KeyAuthApp.response.message);
weiter.IsEnabled = true; weiter.IsEnabled = true;
method = "ftp"; method = "ftp";