using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Media; using AvaloniaEdit.Document; using ReactiveUI; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; 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; using Valheim_Dashboard.Views; using static System.Net.WebRequestMethods; namespace Valheim_Dashboard.ViewModels; public class ServerDashboardViewModel : ViewModelBase { // BepInEx Status private string _bepInExStatus; public string BepInExStatus { get => _bepInExStatus; set => this.RaiseAndSetIfChanged(ref _bepInExStatus, value); } private bool _showInstallButton; public bool ShowInstallButton { get => _showInstallButton; set => this.RaiseAndSetIfChanged(ref _showInstallButton, value); } private bool _showUpdateButton; public bool ShowUpdateButton { get => _showUpdateButton; set => this.RaiseAndSetIfChanged(ref _showUpdateButton, value); } public ObservableCollection Mods { get; } = new(); private ModInfo? _selectedMod; public ModInfo? SelectedMod { get => _selectedMod; set { this.RaiseAndSetIfChanged(ref _selectedMod, value); if (value == null) { SelectedModConfig = string.Empty; } else if (string.IsNullOrEmpty(value.ConfigPath)) { // Keine Config zugeordnet → Hinweistext SelectedModConfig = "Keine Config gefunden, Server bereits neugestartet?"; } else { // Config laden _ = LoadSelectedModConfigFromFtp(); ; } } } private async Task LoadSelectedModConfigFromFtp() { if (SelectedMod == null) { SelectedModConfig = string.Empty; return; } try { SelectedModConfig = await FtpViewModel._ftpClient.DownloadTextAsync(SelectedMod.ConfigPath); } catch (Exception ex) { SelectedModConfig = $"Fehler beim Laden: {ex.Message}"; } } public TextDocument ConfigDocument { get; } = new TextDocument(); private string? _selectedModConfig; public string? SelectedModConfig { get => _selectedModConfig; 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) { _mainWindow = mainWindow; } // Reactive Commands public ReactiveCommand InstallBepInExCommand { get; } public ReactiveCommand UpdateBepInExCommand { get; } public ReactiveCommand UploadModCommand { get; } public ReactiveCommand InstallFromStoreCommand { get; } public ReactiveCommand SaveConfigCommand { get; } public ReactiveCommand RemoveModCommand { get; } public ReactiveCommand UpdateModCommand { get; } private bool _isLoading; public bool IsLoading { get => _isLoading; set => this.RaiseAndSetIfChanged(ref _isLoading, value); } private readonly MainWindowViewModel _main; public ServerDashboardViewModel(MainWindowViewModel main) { _main = main; InstallBepInExCommand = ReactiveCommand.Create(InstallBepInEx); UpdateBepInExCommand = ReactiveCommand.Create(UpdateBepInEx); UploadModCommand = ReactiveCommand.CreateFromTask(UploadMod); //InstallFromStoreCommand = ReactiveCommand.Create(InstallFromStore); InstallFromStoreCommand = ReactiveCommand.Create(() => { Debug.WriteLine("InstallFromStoreCommand"); _main.SwitchToStore(); }); SaveConfigCommand = ReactiveCommand.Create(SaveConfig); RemoveModCommand = ReactiveCommand.Create(RemoveMod); UpdateModCommand = ReactiveCommand.Create(UpdateMod); // SelectedModConfig Sync mit ConfigDocument text (: ConfigDocument = new TextDocument(); ConfigDocument.TextChanged += (s, e) => { if (SelectedModConfig != ConfigDocument.Text) SelectedModConfig = ConfigDocument.Text; }; //SelectedMod.Name = "Bitte Mod Auswählen"; // 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" }); // Start async Initialisierung // _ = InitializeAsync(); //CheckBepInExStatus(); } public void Init() { // Start async Initialisierung _ = InitializeAsync(); ConfigDocument.Text = "Bitte Mod Auswählen"; } private async Task InitializeAsync() { IsLoading = true; await CheckBepInExStatus(); IsLoading = false; await LoadModsFromServer(); } 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; BepInExStatusBrush = Brushes.Red; return; } // 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})"; BepInExStatusBrush = Brushes.Green; } else { BepInExStatus = "Installiert (Version unbekannt)"; BepInExStatusBrush = Brushes.Green; } 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 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); } private IBrush _bepInExStatusBrush = Brushes.Red; // default public IBrush BepInExStatusBrush { get => _bepInExStatusBrush; set => this.RaiseAndSetIfChanged(ref _bepInExStatusBrush, value); } public async Task InstallBepInEx() { 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"); // 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(); using var doc = await JsonDocument.ParseAsync(stream); if (!doc.RootElement.TryGetProperty("latest", out var latest) || !latest.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}"); // --- 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[64 * 1024]; // größerer Buffer = schneller 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 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; 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(StringComparer.Ordinal); var allFiles = new List(); foreach (var entry in archive.Entries) { var parts = entry.FullName.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); 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 { using var entryStream = entry.Open(); await FtpViewModel._ftpClient.UploadStreamAsync(entryStream, remotePath); } catch (WebException ex) { 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 private bool _isModsLoading; public bool IsModsLoading { get => _isModsLoading; set => this.RaiseAndSetIfChanged(ref _isModsLoading, value); } // 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 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 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() { IsModsLoading = true; 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 // cfgHit bleibt null } // 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}"); } finally { IsModsLoading = false; } } //Mod Installation / Löschung public async Task OpenFileAsync(Window parent) { var dialog = new OpenFileDialog { AllowMultiple = false, Filters = { new FileDialogFilter { Name = "Mod Files", Extensions = { "dll" } }, new FileDialogFilter { Name = "All Files", Extensions = { "*" } } } }; var result = await dialog.ShowAsync(parent); return result?.FirstOrDefault(); } public async Task UploadMod() { // Finde das aktive Fenster über das Visual Tree var topLevel = TopLevel.GetTopLevel(App.Current!.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime d ? d.MainWindow : null); if (topLevel is not Window parent) { Debug.WriteLine("Kein gültiges Window gefunden."); return; } var path = await OpenFileAsync(parent); if (string.IsNullOrEmpty(path)) return; var fileName = Path.GetFileName(path); var remotePath = FtpViewModel._currentPath.TrimEnd('/') + "/BepInEx/plugins/" + fileName; try { await FtpViewModel._ftpClient.UploadFileAsync(path, remotePath); Debug.WriteLine($"Upload erfolgreich: {remotePath}"); await LoadModsFromServer(); } catch (Exception ex) { Debug.WriteLine($"Fehler beim Upload: {ex.Message}"); } } private void InstallFromStore() { } private void SaveConfig() { Debug.WriteLine(SelectedMod.ConfigPath); FtpViewModel._ftpClient.UploadTextAsync(SelectedModConfig, SelectedMod.ConfigPath); } private async Task RemoveMod(ModInfo mod) { // Finde das aktive Fenster über das Visual Tree var topLevel = TopLevel.GetTopLevel(App.Current!.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime d ? d.MainWindow : null); if (topLevel is not Window parent) { Debug.WriteLine("Kein gültiges Window gefunden."); return; } var dialog = new ConfirmDialog(); dialog.SetMessage($"Möchtest du den Mod \"{mod.Name}\" wirklich löschen?"); bool confirmed = await dialog.ShowDialogAsync(parent); if (confirmed) { Mods.Remove(mod); if (ServerSettingsView.method == "ftp") { var remotePath = CombineFtp(FtpViewModel._currentPath, "BepInEx/plugins", mod.Name + ".dll"); try { await FtpViewModel._ftpClient.DeleteFileAsync(remotePath); Debug.WriteLine($"Mod {mod.Name} gelöscht."); } catch (Exception ex) { Debug.WriteLine($"Fehler beim Löschen der Mod {mod.Name}: {ex.Message}"); } try { await FtpViewModel._ftpClient.DeleteFileAsync(mod.ConfigPath); Debug.WriteLine($"Mod Config {mod.Name} gelöscht."); } catch (Exception ex) { Debug.WriteLine($"Fehler beim Löschen der Mod Config {mod.Name}: {ex.Message}"); } } else { Debug.WriteLine("Plugin funktion fehlt noch"); } } } private void UpdateMod(ModInfo mod) { Debug.WriteLine($"Update {mod.Name} von {mod.Version} → {mod.LatestVersion}"); } }