using Avalonia.Controls; using ReactiveUI; using System; 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.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); _ = LoadSelectedModConfigFromFtp(); // async fire-and-forget } } 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}"; } } private string _selectedModConfig; public string SelectedModConfig { get => _selectedModConfig; set => this.RaiseAndSetIfChanged(ref _selectedModConfig, value); } 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; } private bool _isLoading; public bool IsLoading { get => _isLoading; set => this.RaiseAndSetIfChanged(ref _isLoading, value); } public ServerDashboardViewModel() { InstallBepInExCommand = ReactiveCommand.Create(InstallBepInEx); UpdateBepInExCommand = ReactiveCommand.Create(UpdateBepInEx); UploadModCommand = ReactiveCommand.Create(UploadMod); InstallFromStoreCommand = ReactiveCommand.Create(InstallFromStore); SaveConfigCommand = ReactiveCommand.Create(SaveConfig); RemoveModCommand = ReactiveCommand.Create(RemoveMod); // 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(); } private async Task InitializeAsync() { IsLoading = true; await CheckBepInExStatus(); 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() { BepInExStatus = "Aktuell (vX.Y.Z)"; ShowUpdateButton = false; } //Mod Installation / Löschung public async Task OpenFileAsync(Window parent) { var dialog = new OpenFileDialog { AllowMultiple = false }; dialog.Filters.Add(new FileDialogFilter { Name = "Config Files", Extensions = { "cfg" } }); dialog.Filters.Add(new FileDialogFilter { Name = "All Files", Extensions = { "*" } }); var result = await dialog.ShowAsync(parent); return result?.FirstOrDefault(); // Gibt den ausgewählten Pfad zurück oder null } private async void UploadMod() { if (_mainWindow == null) return; // Window muss gesetzt sein var path = await OpenFileAsync(_mainWindow); FtpViewModel._ftpClient.UploadFileAsync("", ""); } private void InstallFromStore() { /* TODO */ } private void SaveConfig() { Debug.WriteLine(SelectedMod.ConfigPath); FtpViewModel._ftpClient.UploadTextAsync(SelectedModConfig, SelectedMod.ConfigPath); } private void RemoveMod() { if (SelectedMod != null) Mods.Remove(SelectedMod); } }