Files
valheim-mod-sync-desktop/Valheim Mod Sync Desktop/MainWindow.xaml.cs
2025-08-01 21:10:51 +02:00

555 lines
20 KiB
C#

using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Text.Json;
using System.IO;
using Application = System.Windows.Application;
using Valheim_Mod_Sync_Desktop.ViewModels;
using Valheim_Mod_Sync_Desktop.Views;
using IWshRuntimeLibrary;
using System.Linq;
using System.Threading.Tasks;
using Valheim_Mod_Sync_Desktop.Properties;
using System.Diagnostics;
using System.Configuration;
using System.Security.Cryptography;
using System.Threading;
using System.Windows.Media;
namespace Valheim_Mod_Sync_Desktop
{
public class LizenzReturn
{
public bool success { get; set; }
public LizenzDetail data { get; set; }
}
public class LizenzDetail
{
public int timesActivatedMax { get; set; }
public int remainingActivations { get; set; }
public int timesActivated { get; set; }
public string hwid { get; set; }
}
public class LizenzReturnDeactivate
{
public bool success { get; set; }
public LizenzDetailDeactivate data { get; set; }
}
public class LizenzDetailDeactivate
{
public int timesActivatedMax { get; set; }
public int remainingActivations { get; set; }
public int timesActivated { get; set; }
public string hwid { get; set; }
}
public partial class MainWindow : Window
{
public static string LizenzReturn { get; set; }
private MainViewModel viewModel;
private Ladescreen _splashScreen;
public MainWindow()
{
InitializeComponent();
viewModel = new MainViewModel();
DataContext = viewModel;
Loaded += Loadedfinish;
// Erstelle den Splashscreen und zeige ihn an
_splashScreen = new Ladescreen();
_splashScreen.Show();
_splashScreen.SetProgress(0);
// Starte den Hintergrundprozess
Task.Run(async () =>
{
// Führe die Aufgabe aus
await DoLongTaskAsync();
// Schließe den Splashscreen
Dispatcher.Invoke(() =>
{
this.Show();
_splashScreen.Close();
Debug.WriteLine("show");
});
});
}
private async Task DoLongTaskAsync()
{
await UpdateProgressAsync(10);
await UpdateProgressNameAsync("Prüfe Config");
Debug.WriteLine("10");
//Debug.WriteLine(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath);
//Übernehmem der alten Config beim ersten Start
if (Properties.Settings.Default.ErsterStart)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.ErsterStart = false;
Properties.Settings.Default.Save();
}
// Aktualisiere den Fortschritt
await UpdateProgressAsync(30);
await UpdateProgressNameAsync("Lade Config");
Debug.WriteLine("30");
//Read config
Application.Current.Dispatcher.Invoke(() =>
{
try
{
// Hier kommt Ihr Code rein
Theme.Text = Properties.Settings.Default.Theme;
Server.Text = Properties.Settings.Default.Server;
Sprache.Text = Properties.Settings.Default.Sprache;
Autostart.IsChecked = Properties.Settings.Default.Autostart;
StartmenueVerknuepfung.IsChecked = Properties.Settings.Default.Verknuepfung;
}
catch (InvalidOperationException ex)
{
Debug.WriteLine("Fehler: " + ex.Message);
}
});
// Aktualisiere den Fortschritt
await UpdateProgressAsync(50);
await UpdateProgressNameAsync("Prüfe Internetzugang");
Debug.WriteLine("50");
//prüfe verbindung
if (SyncControl.IsConnectionAvailable())
{
//prüfe lizenz
// Aktualisiere den Fortschritt
await UpdateProgressAsync(60);
await UpdateProgressNameAsync("Prüfe Lizenz");
Debug.WriteLine("60");
await Prüfung();
// Aktualisiere den Fortschritt
await UpdateProgressAsync(70);
await UpdateProgressNameAsync("Prüfe ob Server IP gesetzt");
Debug.WriteLine("70");
PrüfungServerIP();
// Aktualisiere den Fortschritt
await UpdateProgressAsync(80);
Debug.WriteLine("80");
}
else
{
Benachrichtigung modalWindow = new Benachrichtigung(false, false, false, false, false, false, true, false);
modalWindow.ShowDialog();
if (LizenzReturn == "false")
{
this.Close();
}
}
// Aktualisiere den Fortschritt
await UpdateProgressAsync(90);
await UpdateProgressNameAsync("Prüfe Einstellungen");
Debug.WriteLine("90");
//check autostart
SyncControl.CheckUpdateAutostart();
// Aktualisiere den Fortschritt
await UpdateProgressAsync(95);
await UpdateProgressNameAsync("Lade Anwendung");
Debug.WriteLine("95");
await UpdateProgressAsync(100);
await UpdateProgressNameAsync("Fertig");
Debug.WriteLine("100");
}
private async Task UpdateProgressAsync(int progress)
{
// Aktualisiere den Fortschritt
await Dispatcher.InvokeAsync(() =>
{
_splashScreen.SetProgress(progress);
});
// Warte eine kurze Zeit, damit die Fortschrittsleiste aktualisiert wird
await Task.Delay(100);
}
private async Task UpdateProgressNameAsync(string progressName)
{
// Aktualisiere den Fortschritt
await Dispatcher.InvokeAsync(() =>
{
_splashScreen.SetProgressName(progressName);
});
// Warte eine kurze Zeit, damit die Fortschrittsleiste aktualisiert wird
await Task.Delay(100);
}
//Wenn fertig geladen
private void Loadedfinish(object sender, RoutedEventArgs e)
{
if (Properties.Settings.Default.Server == "..." && admin || !Properties.Settings.Default.Server.Contains(":") && admin)
{
contentControl.Content = new SetupViewModel();
MenüGrid.Visibility = Visibility.Hidden;
}
if (!admin)
{
Server.IsEnabled = false;
}
}
//Prüfung
private async Task Prüfung()
{
if (Properties.Settings.Default.Lizenz == "")
{
Lizenz modalWindow = null;
await Application.Current.Dispatcher.InvokeAsync(() =>
{
modalWindow = new Lizenz();
modalWindow.ShowDialog();
});
if (LizenzReturn == "false")
{
Application.Current.Dispatcher.Invoke(() =>
{
// Schließen des Splashscreens
_splashScreen.Dispatcher.Invoke(() =>
{
_splashScreen.Close();
});
((MainWindow)Application.Current.MainWindow).Close();
});
}
}else
{
string html = string.Empty;
string url = @"https://tbs-server.de/wp-json/lmfwc/v2/licenses/validate/" + Properties.Settings.Default.Lizenz;
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1")
.GetBytes(Properties.Settings.Default.benutzername + ":" + Properties.Settings.Default.passwort));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
request.Headers.Add("Authorization", "Basic " + encoded);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
LizenzReturn lizenz_return = JsonSerializer.Deserialize<LizenzReturn>(html);
if (lizenz_return.data.hwid != Lizenz.HardwareID())
{
Lizenz modalWindow = new Lizenz();
modalWindow.ShowDialog();
if (LizenzReturn == "false")
{
this.Close();
}
}
}
}
public class LizenzIPReturn_
{
public string Admin { get; set; }
public string IP_Alt { get; set; }
public string IP { get; set; }
}
private bool admin;
//Prüfung ServerIP
private void PrüfungServerIP()
{
string html = string.Empty;
string url = @"https://tbs-server.de//wp-json/lmfwc/v2/vms/check_server_ip/" + Properties.Settings.Default.Lizenz;
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1")
.GetBytes(Properties.Settings.Default.benutzername + ":" + Properties.Settings.Default.passwort));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
request.Headers.Add("Authorization", "Basic " + encoded);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
LizenzIPReturn_ lizenzip_return_ = JsonSerializer.Deserialize<LizenzIPReturn_>(html);
admin = (lizenzip_return_.Admin == "true") ? true : false;
if (!lizenzip_return_.IP.Equals("0") | lizenzip_return_.IP.Contains(":"))
{
Properties.Settings.Default.Server = lizenzip_return_.IP;
Properties.Settings.Default.ModVersion = 0;
Properties.Settings.Default.Save();
Application.Current.Dispatcher.Invoke(() =>
{
Server.Text = lizenzip_return_.IP;
});
}
else
{
Properties.Settings.Default.Server = "...";
Properties.Settings.Default.ModVersion = 0;
Properties.Settings.Default.Save();
}
}
//Close Button
private void exitBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.Close();
}
//Minimize Button
private void miniBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
//Header Move
private void header_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
//Save Theme Change to Config
private void theme_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem typeItem = (ComboBoxItem)Theme.SelectedItem;
string value = typeItem.Content.ToString();
Properties.Settings.Default.Theme = value;
Properties.Settings.Default.Save();
var app = (App)Application.Current; app.ChangeTheme(new Uri("/Skins/" + value + ".xaml", UriKind.RelativeOrAbsolute));
}
//Save Sprache
private void Sprache_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem sprachItem = (ComboBoxItem)Sprache.SelectedItem;
string sprachvalue = sprachItem.Content.ToString();
Properties.Settings.Default.Sprache = sprachvalue;
Properties.Settings.Default.Save();
var app1 = (App)Application.Current;
app1.ChangeLanguage(new Uri("/Language/" + sprachvalue + ".xaml", UriKind.RelativeOrAbsolute));
}
//Save Server
private void Server_TextChanged(object sender, TextChangedEventArgs e)
{
if (Server.Text != Properties.Settings.Default.Server)
{
//Debug.WriteLine("change");
Properties.Settings.Default.ModVersion = 0;
Properties.Settings.Default.Server = Server.Text;
Properties.Settings.Default.Save();
}
}
//Save state Autostart
private void Autostart_Click(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Autostart = (bool)Autostart.IsChecked;
Properties.Settings.Default.Save();
}
//Kontakt Button
private void KontaktButton_Click(object sender, RoutedEventArgs e)
{
contentControl.Content = new Kontakt();
MenuToggleButton.Visibility = Visibility.Collapsed;
Back.Visibility = Visibility.Visible;
}
//Zurück Button
private void Back_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
contentControl.Content = new SyncControl();
Back.Visibility = Visibility.Collapsed;
MenuToggleButton.Visibility = Visibility.Visible;
}
//Verknüpfung Hinzufügen / Löschen
private void StartmenueVerknuepfung_Click(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Verknuepfung = (bool)StartmenueVerknuepfung.IsChecked;
Properties.Settings.Default.Save();
string pathToExe = Directory.GetCurrentDirectory() + "/" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";
string programs_path = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
string appStartMenuOrdner = "tbs-server.de";
string appStartMenuPath = Path.Combine(programs_path, appStartMenuOrdner, "Valheim Mod Sync");
string settingsLink = Path.Combine(appStartMenuPath, "Valheim Mod Sync.lnk");
if (StartmenueVerknuepfung.IsChecked == true)
{
if (!Directory.Exists(appStartMenuPath))
{
Directory.CreateDirectory(appStartMenuPath);
}
new WebClient().DownloadFile("https://vms.tbs-server.de/vms.ico", appStartMenuPath+"/vms.ico");
WshShell shellClass = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
shortcut.TargetPath = pathToExe;
shortcut.WorkingDirectory = Directory.GetCurrentDirectory();
shortcut.IconLocation = appStartMenuPath+"/vms.ico";
shortcut.Description = "Valheim Mod Sync";
shortcut.Save();
}else
{
if (Directory.Exists(appStartMenuPath))
{
System.IO.File.Delete(settingsLink);
System.IO.File.Delete(appStartMenuPath + "/vms.ico");
Directory.Delete(appStartMenuPath);
if (!Directory.EnumerateFileSystemEntries(Path.Combine(programs_path, appStartMenuOrdner)).Any())
{
Directory.Delete(Path.Combine(programs_path, appStartMenuOrdner));
}
}
}
}
private void Lizenz_Deaktivieren_Click(object sender, RoutedEventArgs e)
{
try
{
string html = string.Empty;
string url = @"https://tbs-server.de//wp-json/lmfwc/v2/licenses/deactivate/" + Properties.Settings.Default.Lizenz;
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1")
.GetBytes(Properties.Settings.Default.benutzername + ":" + Properties.Settings.Default.passwort));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
request.Headers.Add("Authorization", "Basic " + encoded);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
LizenzReturnDeactivate lizenz_return_deactivate = JsonSerializer.Deserialize<LizenzReturnDeactivate>(html);
if (lizenz_return_deactivate.data.timesActivated != lizenz_return_deactivate.data.timesActivatedMax && lizenz_return_deactivate.success == true)
{
Properties.Settings.Default.Lizenz = "";
Properties.Settings.Default.Save();
this.Close();
}
else
{
}
}
catch
{
//outputlizenz.Text = (string)Application.Current.FindResource("LizenzKeyFehler");
}
}
private void Sync_Menu_Click(object sender, RoutedEventArgs e)
{
contentControl.Content = new SyncControl();
MenüAktivBorder();
Sync_Menu.SetResourceReference(Button.BackgroundProperty, "BackgroundGrid");
}
private void Mods_View_Click(object sender, RoutedEventArgs e)
{
contentControl.Content = new FTP();
MenüAktivBorder();
Mods_View.SetResourceReference(Button.BackgroundProperty, "BackgroundGrid");
}
private void Lizenzen_View_Click(object sender, RoutedEventArgs e)
{
contentControl.Content = new Lizenzen();
MenüAktivBorder();
Mods_View.SetResourceReference(Button.BackgroundProperty, "BackgroundGrid");
}
private void Einstellungen_View_Click(object sender, RoutedEventArgs e)
{
contentControl.Content = new Kontakt();
MenüAktivBorder();
//Einstellungen_View.Background = Brushes.Red;
Einstellungen_View.SetResourceReference(Button.BackgroundProperty, "BackgroundGrid");
}
private void MenüAktivBorder()
{
foreach (var child in MenüGrid.Children)
{
if (child is Button button)
{
button.Background = Brushes.Transparent;
}
}
}
}
}