- BepInEx Installation schneller gemach

- BepInEx Installation Progress Bar hinzugefügt um fortschritt anzuzeigen
-BepInEx Leere ordner werden jetzt direkt mit erstellt, falls der user selber prüfen will oder so damit er sie sieht. Also 1zu1 die ZIP
-Mods werden jetzt vom ftp server gelesen mit version und config suche. Plugin funktion fehlt dafür nur
- Text Editor für Config von Simple zu wirklichen Editor mit highlights wie notepad++ geändert. funktioniert aber noch nicht
This commit is contained in:
tbS
2025-08-27 19:19:23 +02:00
parent 2c7d442441
commit cf6bd3765f
9 changed files with 497 additions and 60 deletions

View File

@@ -1,6 +1,8 @@
using Avalonia.Controls;
using AvaloniaEdit.Document;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
@@ -10,6 +12,8 @@ using System.Net;
using System.Net.Http;
using System.Reactive;
using System.Reactive.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Valheim_Dashboard.Models;
@@ -74,11 +78,19 @@ public class ServerDashboardViewModel : ViewModelBase
}
private string _selectedModConfig;
public string SelectedModConfig
public TextDocument ConfigDocument { get; } = new TextDocument();
private string? _selectedModConfig;
public string? SelectedModConfig
{
get => _selectedModConfig;
set => this.RaiseAndSetIfChanged(ref _selectedModConfig, value);
set
{
this.RaiseAndSetIfChanged(ref _selectedModConfig, value);
var text = value ?? string.Empty;
if (ConfigDocument.Text != text)
ConfigDocument.Text = text;
}
}
private Window _mainWindow;
public void SetMainWindow(Window mainWindow)
@@ -111,13 +123,18 @@ public class ServerDashboardViewModel : ViewModelBase
SaveConfigCommand = ReactiveCommand.Create(SaveConfig);
RemoveModCommand = ReactiveCommand.Create(RemoveMod);
// DEBUG: harter Testtext – MUSS im Editor erscheinen
ConfigDocument.Text = "[Berries]\n# test\nRaspberryCost = 5";
// Demo
//BepInExStatus = "Nicht installiert";
//ShowInstallButton = true;
//ShowUpdateButton = false;
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 = "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" });
// Start async Initialisierung
_ = InitializeAsync();
@@ -130,6 +147,7 @@ public class ServerDashboardViewModel : ViewModelBase
IsLoading = true;
await CheckBepInExStatus();
IsLoading = false;
await LoadModsFromServer();
}
private async Task CheckBepInExStatus()
@@ -147,12 +165,6 @@ public class ServerDashboardViewModel : ViewModelBase
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);
@@ -207,52 +219,51 @@ public class ServerDashboardViewModel : ViewModelBase
/* private void InstallBepInEx()
{
BepInExStatus = "Installiert (vX.Y.Z)";
ShowInstallButton = false;
ShowUpdateButton = true;
}
*/
private readonly HttpClient _http = new HttpClient();
private int _progressValue;
public int ProgressValue
{
get => _progressValue;
set => this.RaiseAndSetIfChanged(ref _progressValue, value);
}
private string _progressText;
public string ProgressText
{
get => _progressText;
set => this.RaiseAndSetIfChanged(ref _progressText, value);
}
private bool _isProgress;
public bool IsProgress
{
get => _isProgress;
set => this.RaiseAndSetIfChanged(ref _isProgress, value);
}
public async Task InstallBepInEx()
{
Debug.WriteLine("Install star");
Debug.WriteLine("Install start");
ShowInstallButton = false;
IsProgress = true;
ProgressValue = 0;
ProgressText = "Starte…";
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;
}
// 1) Thunderstore API
HttpResponseMessage resp = await _http.GetAsync("https://thunderstore.io/api/experimental/package/denikson/BepInExPack_Valheim/");
resp.EnsureSuccessStatusCode();
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;
}
using var doc = await JsonDocument.ParseAsync(stream);
if (!doc.RootElement.TryGetProperty("latest", out var latestElement) ||
!latestElement.TryGetProperty("download_url", out var urlElement))
if (!doc.RootElement.TryGetProperty("latest", out var latest) ||
!latest.TryGetProperty("download_url", out var urlElement))
{
Debug.WriteLine("download_url nicht gefunden im JSON");
return;
@@ -261,13 +272,16 @@ public class ServerDashboardViewModel : ViewModelBase
string downloadUrl = urlElement.GetString()!;
Debug.WriteLine($"Starte Download von BepInExPack: {downloadUrl}");
// --- Fortschritt: Download = 0..25 %
const int DL_START = 0, DL_END = 25, MKDIR_END = 40, UP_END = 100;
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];
byte[] buffer = new byte[64 * 1024]; // größerer Buffer = schneller
long totalRead = 0;
int bytesRead;
while ((bytesRead = await downloadStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
@@ -277,22 +291,85 @@ public class ServerDashboardViewModel : ViewModelBase
if (totalBytes > 0)
{
int progress = (int)((totalRead * 100) / totalBytes);
Console.Write($"\rDownload Fortschritt: {progress}%");
int dlPct = (int)((totalRead * 100) / totalBytes);
int uiPct = DL_START + (int)((dlPct / 100.0) * (DL_END - DL_START));
ProgressValue = uiPct;
ProgressText = $"Download: {dlPct}%";
}
}
ms.Position = 0;
Console.WriteLine("\nDownload abgeschlossen, entpacke ZIP...");
ProgressValue = DL_END;
ProgressText = "Download fertig. Entpacke…";
// 2) ZIP öffnen
using var archive = new ZipArchive(ms);
// 2a) Alle Ordner (inkl. leerer) sammeln -> erster Ordnerteil (BepInExPack_Valheim) wird weggeschnitten
var allFolders = new HashSet<string>(StringComparer.Ordinal);
var allFiles = new List<ZipArchiveEntry>();
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));
if (parts.Length <= 1) continue; // root-pack-ordner allein ignorieren
// relative Teile ohne Top-Level-Ordner
var relParts = parts.Skip(1).ToArray();
if (string.IsNullOrEmpty(entry.Name))
{
// Ein echter Verzeichniseintrag im ZIP (leer)
string folder = string.Join('/', relParts);
if (!string.IsNullOrWhiteSpace(folder))
allFolders.Add(folder);
}
else
{
// Datei -> über alle Zwischenordner iterieren
for (int i = 0; i < relParts.Length - 1; i++)
{
string folder = string.Join('/', relParts.Take(i + 1));
allFolders.Add(folder);
}
allFiles.Add(entry);
}
}
// --- Fortschritt: Ordner anlegen = 25..40 %
ProgressText = "Lege Ordner an…";
int foldersTotal = allFolders.Count;
int foldersDone = 0;
foreach (var folder in allFolders.OrderBy(s => s.Length)) // erst flache, dann tiefe Ordner
{
Debug.WriteLine("ordner: " + folder);
try
{
// relative Pfade an Ensure übergeben – deine CreateFtpWebRequest() hängt _currentPath selbst an
await FtpViewModel._ftpClient.EnsureFtpDirectoryExistsAsync(
FtpViewModel._currentPath.TrimEnd('/') + "/" + folder
);
}
catch (Exception ex)
{
Debug.WriteLine($"Ordner konnte nicht erstellt werden: {folder} - {ex.Message}");
// idempotent – wenn schon vorhanden, passts
}
foldersDone++;
int uiPct = DL_END + (int)(((foldersDone / (double)Math.Max(1, foldersTotal)) * (MKDIR_END - DL_END)));
ProgressValue = uiPct;
ProgressText = $"Ordner: {foldersDone}/{foldersTotal}";
}
// --- Fortschritt: Dateien hochladen = 40..100 %
ProgressText = "Lade Dateien hoch…";
int filesTotal = allFiles.Count;
int filesDone = 0;
foreach (var entry in allFiles)
{
var parts = entry.FullName.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
var relativePath = string.Join('/', parts.Skip(1)); // Top-Level-Ordner weg
string remotePath = FtpViewModel._currentPath.TrimEnd('/') + "/" + relativePath;
try
@@ -304,25 +381,243 @@ public class ServerDashboardViewModel : ViewModelBase
{
Debug.WriteLine($"FTP Upload Fehler für {remotePath}: {ex.Message}");
}
filesDone++;
int uiPct = MKDIR_END + (int)(((filesDone / (double)Math.Max(1, filesTotal)) * (UP_END - MKDIR_END)));
ProgressValue = uiPct;
ProgressText = $"Hochgeladen: {filesDone}/{filesTotal}";
}
ProgressValue = 100;
ProgressText = "Fertig ✅";
await CheckBepInExStatus();
}
catch (Exception ex)
{
Debug.WriteLine($"Unbekannter Fehler: {ex}");
ProgressText = "Fehler";
}
finally
{
IsProgress = false;
}
}
private void UpdateBepInEx()
{
BepInExStatus = "Aktuell (vX.Y.Z)";
ShowUpdateButton = false;
}
//Mod Liste holen
// Hilfsfunktionen
static string NormalizeKey(string s)
{
// nur Buchstaben/Ziffern, alles klein
var sb = new StringBuilder(s.Length);
foreach (var ch in s)
if (char.IsLetterOrDigit(ch))
sb.Append(char.ToLowerInvariant(ch));
return sb.ToString();
}
static string[] SplitBySeparators(string s)
{
// trennt per _,.,-,+, Leerzeichen und Slash/Backslash
return s.Split(new[] { '_', '.', '-', '+', ' ', '/', '\\' },
StringSplitOptions.RemoveEmptyEntries);
}
static string ExtractCoreModName(string dllNameNoExt)
{
var parts = SplitBySeparators(dllNameNoExt);
if (parts.Length == 0) return dllNameNoExt;
// häufig ist der letzte Part der eigentliche Modname
return parts[^1];
}
static IEnumerable<string> BuildCandidates(string dllNameNoExt)
{
var parts = SplitBySeparators(dllNameNoExt);
// 1) ganzer Name
yield return dllNameNoExt;
// 2) Core-Name (letzter Part)
if (parts.Length > 0)
yield return parts[^1];
// 3) Varianten mit Punkt/Unterstrich (für Fälle wie Advize_PlantEverything vs advize.PlantEverything)
if (parts.Length > 1)
{
yield return string.Join(".", parts);
yield return string.Join("_", parts);
}
}
static int LongestCommonSubsequenceLen(string a, string b)
{
// kleine, schnelle Heuristik als Fallback (O(n*m)), nur bei wenigen Kandidaten benutzt
var dp = new int[a.Length + 1, b.Length + 1];
for (int i = 1; i <= a.Length; i++)
for (int j = 1; j <= b.Length; j++)
dp[i, j] = a[i - 1] == b[j - 1] ? dp[i - 1, j - 1] + 1 : Math.Max(dp[i - 1, j], dp[i, j - 1]);
return dp[a.Length, b.Length];
}
private static string CombineFtp(params string[] parts)
{
return string.Join("/", parts.Where(p => !string.IsNullOrWhiteSpace(p))
.Select(p => p.Trim('/')));
}
private static bool LooksLikeDirectory(dynamic item) // FtpItem? Falls es IsDirectory gibt, nutzen wir das
{
try { return item.IsDirectory; } catch { /* fallback */ }
// Fallback-Heuristik: wenn kein Punkt im Namen, ist es sehr wahrscheinlich ein Ordner
var name = (string)item.Name;
return !name.Contains('.');
}
private async Task<string?> GetDllVersionFromFtpAsync(string remoteDllPath)
{
using var ms = new MemoryStream();
await FtpViewModel._ftpClient.DownloadStreamAsync(remoteDllPath, ms);
ms.Position = 0;
string? version = null;
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".dll");
try
{
await System.IO.File.WriteAllBytesAsync(tempPath, ms.ToArray());
var fvi = FileVersionInfo.GetVersionInfo(tempPath);
version = fvi.FileVersion ?? fvi.ProductVersion;
// Falls FileVersion leer ist, optional Assembly-Version probieren:
if (string.IsNullOrWhiteSpace(version))
{
try
{
var an = AssemblyName.GetAssemblyName(tempPath);
version = an.Version?.ToString();
}
catch { /* ignorieren */ }
}
}
finally
{
try { if (System.IO.File.Exists(tempPath)) System.IO.File.Delete(tempPath); } catch { /* ignore */ }
}
return version;
}
// Hauptmethode
public async Task LoadModsFromServer()
{
try
{
Mods.Clear();
if (ServerSettingsView.method == "ftp")
{
var basePath = FtpViewModel._currentPath.TrimEnd('/');
var pluginsDir = $"{basePath}/BepInEx/plugins";
var configDir = $"{basePath}/BepInEx/config";
var pluginList = await FtpViewModel._ftpClient.ListDirectoryDetailsAsync(pluginsDir);
var configList = await FtpViewModel._ftpClient.ListDirectoryDetailsAsync(configDir);
// Vorbereiten: normalisierte Config-Namen mapen
var cfgFiles = configList
.Where(c => c.Name.EndsWith(".cfg", StringComparison.OrdinalIgnoreCase))
.Select(c => new {
Name = c.Name,
NameNoExt = Path.GetFileNameWithoutExtension(c.Name),
Normalized = NormalizeKey(Path.GetFileNameWithoutExtension(c.Name))
})
.ToList();
foreach (var pl in pluginList)
{
if (!pl.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
continue;
string dllNoExt = Path.GetFileNameWithoutExtension(pl.Name);
// Kandidaten + normalisierte Kandidaten
var candidates = BuildCandidates(dllNoExt).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var normCandidates = candidates.Select(NormalizeKey).Distinct().ToList();
// 1) Bevorzugt: Core-Modname muss vorkommen
string core = ExtractCoreModName(dllNoExt);
string normCore = NormalizeKey(core);
// Match: irgendein normalisierter Kandidat kommt im normalisierten Config-Namen vor
var cfgHit = cfgFiles.FirstOrDefault(cf => cf.Normalized.Contains(normCore));
if (cfgHit == null)
{
// 2) sonst: irgendein Kandidat kommt vor
cfgHit = cfgFiles.FirstOrDefault(cf => normCandidates.Any(nc => cf.Normalized.Contains(nc)));
// 3) Fallback: „bester“ Fit über LCS
if (cfgHit == null)
{
cfgHit = cfgFiles
.Select(cf => new {
cf,
score = normCandidates.Max(nc => LongestCommonSubsequenceLen(cf.Normalized, nc))
})
.OrderByDescending(x => x.score)
.FirstOrDefault()?.cf;
}
}
// Version aus DLL ziehen
string dllRemote = $"{pluginsDir}/{pl.Name}";
string? version = null;
try
{
version = await GetDllVersionFromFtpAsync(dllRemote); // wie zuvor implementiert
}
catch (Exception ex)
{
Debug.WriteLine($"Version für {pl.Name} nicht lesbar: {ex.Message}");
}
// Config-Pfad setzen (siehe Punkt 2 unten für „absolute“ URI)
string? configRelPath = cfgHit != null ? $"{FtpViewModel._currentPath}/BepInEx/config/{cfgHit.Name}" : null;
Mods.Add(new ModInfo
{
Name = candidates.Last(), // z.B. „PlantEverything“ statt Autor.Mod
Version = string.IsNullOrWhiteSpace(version) ? "Unbekannt" : version,
ConfigPath = configRelPath // relativ (empfohlen)
});
}
}
else
{
Debug.WriteLine("Plugin funktion fehlt noch");
}
}
catch (Exception ex)
{
Debug.WriteLine($"LoadModsFromFtp Fehler: {ex}");
}
}
//Mod Installation / Löschung
public async Task<string?> OpenFileAsync(Window parent)