commit 7120c81089422107a5f009753e1b8a3cda3c06a4 Author: tbS Date: Fri Aug 1 23:28:27 2025 +0200 Initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/.idea/.idea.Valheim Dashboard/.idea/.gitignore b/.idea/.idea.Valheim Dashboard/.idea/.gitignore new file mode 100644 index 0000000..a26c168 --- /dev/null +++ b/.idea/.idea.Valheim Dashboard/.idea/.gitignore @@ -0,0 +1,13 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/modules.xml +/.idea.Valheim Dashboard.iml +/contentModel.xml +/projectSettingsUpdater.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/.idea.Valheim Dashboard/.idea/avalonia.xml b/.idea/.idea.Valheim Dashboard/.idea/avalonia.xml new file mode 100644 index 0000000..e435154 --- /dev/null +++ b/.idea/.idea.Valheim Dashboard/.idea/avalonia.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/.idea/.idea.Valheim Dashboard/.idea/indexLayout.xml b/.idea/.idea.Valheim Dashboard/.idea/indexLayout.xml new file mode 100644 index 0000000..7b08163 --- /dev/null +++ b/.idea/.idea.Valheim Dashboard/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.Valheim Dashboard/.idea/vcs.xml b/.idea/.idea.Valheim Dashboard/.idea/vcs.xml new file mode 100644 index 0000000..d843f34 --- /dev/null +++ b/.idea/.idea.Valheim Dashboard/.idea/vcs.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Valheim Dashboard.sln b/Valheim Dashboard.sln new file mode 100644 index 0000000..313b451 --- /dev/null +++ b/Valheim Dashboard.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Valheim Dashboard", "Valheim Dashboard\Valheim Dashboard.csproj", "{BDB3822A-2776-4E4A-8A1A-14BD902A66EE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BDB3822A-2776-4E4A-8A1A-14BD902A66EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BDB3822A-2776-4E4A-8A1A-14BD902A66EE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BDB3822A-2776-4E4A-8A1A-14BD902A66EE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BDB3822A-2776-4E4A-8A1A-14BD902A66EE}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/Valheim Dashboard/Animationen.cs b/Valheim Dashboard/Animationen.cs new file mode 100644 index 0000000..94989dd --- /dev/null +++ b/Valheim Dashboard/Animationen.cs @@ -0,0 +1,103 @@ +using System; +using Avalonia.Animation; +using Avalonia.Controls; +using Avalonia.Media; +using Avalonia.Styling; +using System; +using System.Globalization; +using Avalonia; +using Avalonia.Animation; +using Avalonia.Controls; +using Avalonia.Data.Converters; +using Avalonia.Interactivity; +using Avalonia.Markup.Xaml; +using static Avalonia.Visual; +using Avalonia.Styling; +using ReactiveUI; + +namespace Valheim_Dashboard; + +public class Animationen +{ + + public static void RunSlideAnimation(double offset,Animatable ziel) + { + var animation = new Animation + { + Duration = TimeSpan.FromSeconds(0.5), + FillMode = FillMode.Forward, + Children = + { + new KeyFrame + { + Cue = new Cue(0.0), + Setters = + { + new Setter(TranslateTransform.YProperty, 0.0) // Startposition + } + }, + new KeyFrame + { + Cue = new Cue(1.0), + Setters = + { + new Setter(TranslateTransform.YProperty, offset) // Endposition + }, + + } + } + }; + + + animation.RunAsync(ziel); + + } + + + public static void FadeOutAnimation(Control control, double durationSeconds = 0.5) + { + + var fadeOutAnimation = new Animation + { + Duration = TimeSpan.FromSeconds(durationSeconds), + FillMode = FillMode.Forward, + Children = + { + new KeyFrame + { + Cue = new Cue(0.0), + Setters = { new Setter(OpacityProperty, 1.0) } + }, + new KeyFrame + { + Cue = new Cue(1.0), + Setters = { new Setter(OpacityProperty, 0.0) } + } + } + }; + + fadeOutAnimation.RunAsync(control); + + } +} + +public class DoubleOffsetConverter : IValueConverter +{ + public static readonly DoubleOffsetConverter Instance = new DoubleOffsetConverter(); + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is double doubleValue && parameter is string stringParameter && double.TryParse(stringParameter, out double offset)) + { + return doubleValue + offset; + } + return value; + } + + + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/Valheim Dashboard/App.axaml b/Valheim Dashboard/App.axaml new file mode 100644 index 0000000..903513b --- /dev/null +++ b/Valheim Dashboard/App.axaml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Valheim Dashboard/App.axaml.cs b/Valheim Dashboard/App.axaml.cs new file mode 100644 index 0000000..161d9ef --- /dev/null +++ b/Valheim Dashboard/App.axaml.cs @@ -0,0 +1,31 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using Valheim_Dashboard.ViewModels; +using Valheim_Dashboard.Views; + +namespace Valheim_Dashboard; + +public partial class App : Application +{ + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + // ViewModelLocator im Ressourcenverzeichnis registrieren + Resources.Add("Locator", new ViewModelLocator()); + + desktop.MainWindow = new MainWindow + { + DataContext = (Resources["Locator"] as ViewModelLocator)?.MainWindowViewModel, + }; + } + + base.OnFrameworkInitializationCompleted(); + } +} diff --git a/Valheim Dashboard/Assets/avalonia-logo.ico b/Valheim Dashboard/Assets/avalonia-logo.ico new file mode 100644 index 0000000..da8d49f Binary files /dev/null and b/Valheim Dashboard/Assets/avalonia-logo.ico differ diff --git a/Valheim Dashboard/AtomTable.cs b/Valheim Dashboard/AtomTable.cs new file mode 100644 index 0000000..1b5e5b0 --- /dev/null +++ b/Valheim Dashboard/AtomTable.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; + +namespace Valheim_Dashboard; + +public class AtomTable +{ + private static readonly Dictionary AtomDictionary = new(); + private static ushort CurrentAtomValue = 1; // Startwert für Atoms + + public static ushort AddAtom(string atomString) + { + lock (AtomDictionary) + { + if (AtomDictionary.ContainsKey(atomString)) + { + return AtomDictionary[atomString]; + } + + ushort newAtom = CurrentAtomValue++; + AtomDictionary[atomString] = newAtom; + return newAtom; + } + } + + public static ushort FindAtom(string atomString) + { + lock (AtomDictionary) + { + if (AtomDictionary.TryGetValue(atomString, out ushort atom)) + { + return atom; + } + + // Rückgabe 0 wie bei `GlobalFindAtom` in Windows, wenn nicht gefunden + return 0; + } + } +} \ No newline at end of file diff --git a/Valheim Dashboard/FtpClient.cs b/Valheim Dashboard/FtpClient.cs new file mode 100644 index 0000000..63acf47 --- /dev/null +++ b/Valheim Dashboard/FtpClient.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Reactive; +using System.Threading.Tasks; +using ReactiveUI; +using Valheim_Dashboard.ViewModels; + +namespace Valheim_Dashboard +{ + + public class FtpItem + { + public string Name { get; set; } + public bool IsDirectory { get; set; } + } + public class FtpClient + { + private readonly string _ftpServer; + private readonly string _username; + private readonly string _password; + + public FtpClient(string ftpServer, string username, string password) + { + _ftpServer = ftpServer.EndsWith("/") ? ftpServer : ftpServer + "/"; + _username = username; + _password = password; + FolderClickedCommand = ViewModel.FolderClickedCommand; + } + private FtpViewModel ViewModel; + + + + + public ReactiveCommand FolderClickedCommand { get; private set; } + + /// + /// Listet die Inhalte eines Ordners (Dateien und Unterordner) auf (Async-Version). + /// + + + public async Task> ListDirectoryDetailsAsync(string path = "") + { + var request = CreateFtpWebRequest(path, WebRequestMethods.Ftp.ListDirectoryDetails); + + using var response = (FtpWebResponse)await request.GetResponseAsync(); + using var reader = new StreamReader(response.GetResponseStream()); + + var result = new List(); + string line; + while ((line = await reader.ReadLineAsync()) != null) + { + // Beispiel: In Unix-Listings beginnt eine Zeile mit "d", wenn es ein Verzeichnis ist. + bool isDirectory = line.StartsWith("d"); + + // Der Dateiname befindet sich üblicherweise am Ende der Zeile. + // Dies kann je nach FTP-Server variieren. + string[] tokens = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + string fileName = tokens[tokens.Length - 1]; + + result.Add(new FtpItem { Name = fileName, IsDirectory = isDirectory }); + } + + return result; + } + + + /// + /// Erstellt einen Ordner auf dem FTP-Server (Async). + /// + public async Task CreateDirectoryAsync(string path) + { + var request = CreateFtpWebRequest(path, WebRequestMethods.Ftp.MakeDirectory); + using var response = (FtpWebResponse)await request.GetResponseAsync(); + } + + /// + /// Lädt eine Datei vom FTP-Server herunter (Async). + /// + public async Task DownloadFileAsync(string remoteFilePath, string localFilePath) + { + var request = CreateFtpWebRequest(remoteFilePath, WebRequestMethods.Ftp.DownloadFile); + + using var response = (FtpWebResponse)await request.GetResponseAsync(); + using var responseStream = response.GetResponseStream(); + using var fileStream = new FileStream(localFilePath, FileMode.Create); + + await responseStream.CopyToAsync(fileStream); + } + + /// + /// Lädt eine Datei auf den FTP-Server hoch (Async). + /// + public async Task UploadFileAsync(string localFilePath, string remoteFilePath) + { + var request = CreateFtpWebRequest(remoteFilePath, WebRequestMethods.Ftp.UploadFile); + request.ContentLength = new FileInfo(localFilePath).Length; + + using var requestStream = await request.GetRequestStreamAsync(); + using var fileStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read); + + await fileStream.CopyToAsync(requestStream); + } + + /// + /// Löscht eine Datei vom FTP-Server (Async). + /// + public async Task DeleteFileAsync(string remoteFilePath) + { + var request = CreateFtpWebRequest(remoteFilePath, WebRequestMethods.Ftp.DeleteFile); + using var response = (FtpWebResponse)await request.GetResponseAsync(); + } + + /// + /// Löscht einen Ordner vom FTP-Server (Async). + /// + public async Task DeleteDirectoryAsync(string remoteDirectoryPath) + { + var request = CreateFtpWebRequest(remoteDirectoryPath, WebRequestMethods.Ftp.RemoveDirectory); + using var response = (FtpWebResponse)await request.GetResponseAsync(); + } + + /// + /// Hilfsmethode zum Erstellen eines FtpWebRequest. + /// + private FtpWebRequest CreateFtpWebRequest(string path, string method) + { + var uri = new Uri(_ftpServer + path); + var request = (FtpWebRequest)WebRequest.Create(uri); + request.Method = method; + request.Credentials = new NetworkCredential(_username, _password); + request.UseBinary = true; + request.UsePassive = true; + request.KeepAlive = false; + return request; + } + + public async Task> OpenFolderAsync(string folderPath) + { + return await ListDirectoryDetailsAsync(folderPath); + } + + } +} diff --git a/Valheim Dashboard/HWID.cs b/Valheim Dashboard/HWID.cs new file mode 100644 index 0000000..9b97611 --- /dev/null +++ b/Valheim Dashboard/HWID.cs @@ -0,0 +1,70 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Win32; +using System.Runtime.InteropServices; + +class HWID +{ + public static string GetHWID() + { + string rawData = ""; + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + rawData = GetWindowsHWID(); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + rawData = GetLinuxHWID(); + } + else + { + throw new PlatformNotSupportedException("Unsupported OS"); + } + + return ComputeHash(rawData); + } + + private static string GetWindowsHWID() + { + string machineGuid = GetRegistryValue(@"SOFTWARE\Microsoft\Cryptography", "MachineGuid"); + string uuid = GetRegistryValue(@"SYSTEM\CurrentControlSet\Control\IDConfigDB\Hardware Profiles\0001", "HwProfileGuid"); + + return $"{machineGuid}-{uuid}"; + } + + private static string GetRegistryValue(string path, string key) + { + try + { + using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(path)) + { + return regKey?.GetValue(key)?.ToString(); + } + } + catch { return null; } + } + + private static string GetLinuxHWID() + { + return ReadFile("/etc/machine-id") ?? ReadFile("/var/lib/dbus/machine-id"); + } + + private static string ReadFile(string path) + { + try { return File.ReadAllText(path).Trim(); } + catch { return null; } + } + + private static string ComputeHash(string input) + { + using (SHA256 sha256 = SHA256.Create()) + { + byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(input)); + return BitConverter.ToString(hash).Replace("-", "").ToLower(); + } + } +} + diff --git a/Valheim Dashboard/KeyAuth.cs b/Valheim Dashboard/KeyAuth.cs new file mode 100644 index 0000000..6898f36 --- /dev/null +++ b/Valheim Dashboard/KeyAuth.cs @@ -0,0 +1,1206 @@ +using System; +using System.Security.Cryptography; +using System.Collections.Specialized; +using System.Text; +using System.Net; +using System.IO; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using System.Diagnostics; +using System.Security.Principal; +using System.Collections.Generic; +using System.Security.Cryptography.X509Certificates; +using System.Net.Security; +using System.Threading; +using System.Runtime.CompilerServices; +using System.Text.Json; + +namespace KeyAuth +{ + public class api + { + public string name, ownerid, secret, version, path; + public static long responseTime; + /// + /// Set up your application credentials in order to use keyauth + /// + /// Application Name + /// Your OwnerID, found in your account settings. + /// Application Secret + /// Application Version, if version doesnt match it will open the download link you set up in your application settings and close the app, if empty the app will close + public api(string name, string ownerid, string secret, string version, string path = null) + { + if (ownerid.Length != 10 || secret.Length != 64) + { + Process.Start("https://youtube.com/watch?v=RfDTdiBq4_o"); + Process.Start("https://keyauth.cc/app/"); + Thread.Sleep(2000); + error("Application not setup correctly. Please watch the YouTube video for setup."); + Environment.Exit(0); + } + + this.name = name; + + this.ownerid = ownerid; + + this.secret = secret; + + this.version = version; + + this.path = path; + } + + #region structures + [DataContract] + private class response_structure + { + [DataMember] + public bool success { get; set; } + + [DataMember] + public bool newSession { get; set; } + + [DataMember] + public string sessionid { get; set; } + + [DataMember] + public string contents { get; set; } + + [DataMember] + public string response { get; set; } + + [DataMember] + public string message { get; set; } + + [DataMember] + public string download { get; set; } + + [DataMember(IsRequired = false, EmitDefaultValue = false)] + public user_data_structure info { get; set; } + + [DataMember(IsRequired = false, EmitDefaultValue = false)] + public app_data_structure appinfo { get; set; } + + [DataMember] + public List messages { get; set; } + + [DataMember] + public List users { get; set; } + } + + public class msg + { + public string message { get; set; } + public string author { get; set; } + public string timestamp { get; set; } + } + + public class users + { + public string credential { get; set; } + } + + [DataContract] + private class user_data_structure + { + [DataMember] + public string username { get; set; } + + [DataMember] + public string ip { get; set; } + [DataMember] + public string hwid { get; set; } + [DataMember] + public string createdate { get; set; } + [DataMember] + public string lastlogin { get; set; } + [DataMember] + public List subscriptions { get; set; } // array of subscriptions (basically multiple user ranks for user with individual expiry dates + } + + [DataContract] + private class app_data_structure + { + [DataMember] + public string numUsers { get; set; } + [DataMember] + public string numOnlineUsers { get; set; } + [DataMember] + public string numKeys { get; set; } + [DataMember] + public string version { get; set; } + [DataMember] + public string customerPanelLink { get; set; } + [DataMember] + public string downloadLink { get; set; } + } + #endregion + private static string sessionid, enckey; + bool initialized; + /// + /// Initializes the connection with keyauth in order to use any of the functions + /// + public void init() + { + string sentKey = encryption.iv_key(); + enckey = sentKey + "-" + secret; + var values_to_upload = new NameValueCollection + { + ["type"] = "init", + ["ver"] = version, + ["hash"] = checksum(Process.GetCurrentProcess().MainModule.FileName), + ["enckey"] = sentKey, + ["name"] = name, + ["ownerid"] = ownerid + }; + + if (!string.IsNullOrEmpty(path)) + { + values_to_upload.Add("token", File.ReadAllText(path)); + values_to_upload.Add("thash", TokenHash(path)); + } + + var response = req(values_to_upload); + + if (response == "KeyAuth_Invalid") + { + error("Application not found"); + Environment.Exit(0); + } + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + { + if (json.newSession) + { + Thread.Sleep(100); + } + sessionid = json.sessionid; + initialized = true; + } + else if (json.message == "invalidver") + { + app_data.downloadLink = json.download; + } + + } + + public static string TokenHash(string tokenPath) + { + using (var sha256 = SHA256.Create()) + { + using (var s = File.OpenRead(tokenPath)) + { + byte[] bytes = sha256.ComputeHash(s); + return BitConverter.ToString(bytes).Replace("-", string.Empty); + } + } + } + + /// + /// Checks if Keyauth is been Initalized + /// + public void CheckInit() + { + if (!initialized) + { + error("You must run the function KeyAuthApp.init(); first"); + Environment.Exit(0); + } + } + + /// + /// Converts Unix time to Days,Months,Hours + /// + /// Subscription Number + /// You can choose between Days,Hours,Months + public string expirydaysleft(string Type, int subscription) + { + CheckInit(); + + System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Local); + dtDateTime = dtDateTime.AddSeconds(long.Parse(user_data.subscriptions[subscription].expiry)).ToLocalTime(); + TimeSpan difference = dtDateTime - DateTime.Now; + switch (Type.ToLower()) + { + case "months": + return Convert.ToString(difference.Days / 30); + case "days": + return Convert.ToString(difference.Days); + case "hours": + return Convert.ToString(difference.Hours); + } + return null; + + } + + /// + /// Registers the user using a license and gives the user a subscription that matches their license level + /// + /// Username + /// Password + /// License key + public void register(string username, string pass, string key, string email = "") + { + CheckInit(); + + string hwid = HWID.GetHWID(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "register", + ["username"] = username, + ["pass"] = pass, + ["key"] = key, + ["email"] = email, + ["hwid"] = hwid, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + load_user_data(json.info); + } + /// + /// Allow users to enter their account information and recieve an email to reset their password. + /// + /// Username + /// Email address + public void forgot(string username, string email) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "forgot", + ["username"] = username, + ["email"] = email, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + } + /// + /// Authenticates the user using their username and password + /// + /// Username + /// Password + public void login(string username, string pass) + { + CheckInit(); + + string hwid = HWID.GetHWID(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "login", + ["username"] = username, + ["pass"] = pass, + ["hwid"] = hwid, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + load_user_data(json.info); + } + + public void logout() + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "logout", + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + } + + public void web_login() + { + CheckInit(); + + string hwid = HWID.GetHWID(); + + string datastore, datastore2, outputten; + + start: + + HttpListener listener = new HttpListener(); + + outputten = "handshake"; + outputten = "http://localhost:1337/" + outputten + "/"; + + listener.Prefixes.Add(outputten); + + listener.Start(); + + HttpListenerContext context = listener.GetContext(); + HttpListenerRequest request = context.Request; + HttpListenerResponse responsepp = context.Response; + + responsepp.AddHeader("Access-Control-Allow-Methods", "GET, POST"); + responsepp.AddHeader("Access-Control-Allow-Origin", "*"); + responsepp.AddHeader("Via", "hugzho's big brain"); + responsepp.AddHeader("Location", "your kernel ;)"); + responsepp.AddHeader("Retry-After", "never lmao"); + responsepp.Headers.Add("Server", "\r\n\r\n"); + + if (request.HttpMethod == "OPTIONS") + { + responsepp.StatusCode = (int)HttpStatusCode.OK; + Thread.Sleep(1); // without this, the response doesn't return to the website, and the web buttons can't be shown + listener.Stop(); + goto start; + } + + listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate; + listener.UnsafeConnectionNtlmAuthentication = true; + listener.IgnoreWriteExceptions = true; + + string data = request.RawUrl; + + datastore2 = data.Replace("/handshake?user=", ""); + datastore2 = datastore2.Replace("&token=", " "); + + datastore = datastore2; + + string user = datastore.Split()[0]; + string token = datastore.Split(' ')[1]; + + var values_to_upload = new NameValueCollection + { + ["type"] = "login", + ["username"] = user, + ["token"] = token, + ["hwid"] = hwid, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + + bool success = true; + + if (json.success) + { + load_user_data(json.info); + + responsepp.StatusCode = 420; + responsepp.StatusDescription = "SHEESH"; + } + else + { + Console.WriteLine(json.message); + responsepp.StatusCode = (int)HttpStatusCode.OK; + responsepp.StatusDescription = json.message; + success = false; + } + + byte[] buffer = Encoding.UTF8.GetBytes("Whats up?"); + + responsepp.ContentLength64 = buffer.Length; + Stream output = responsepp.OutputStream; + output.Write(buffer, 0, buffer.Length); + Thread.Sleep(1); // without this, the response doesn't return to the website, and the web buttons can't be shown + listener.Stop(); + + if (!success) + Environment.Exit(0); + + } + + /// + /// Use Buttons from KeyAuth Customer Panel + /// + /// Button Name + + public void button(string button) + { + CheckInit(); + + HttpListener listener = new HttpListener(); + + string output; + + output = button; + output = "http://localhost:1337/" + output + "/"; + + listener.Prefixes.Add(output); + + listener.Start(); + + HttpListenerContext context = listener.GetContext(); + HttpListenerRequest request = context.Request; + HttpListenerResponse responsepp = context.Response; + + responsepp.AddHeader("Access-Control-Allow-Methods", "GET, POST"); + responsepp.AddHeader("Access-Control-Allow-Origin", "*"); + responsepp.AddHeader("Via", "hugzho's big brain"); + responsepp.AddHeader("Location", "your kernel ;)"); + responsepp.AddHeader("Retry-After", "never lmao"); + responsepp.Headers.Add("Server", "\r\n\r\n"); + + responsepp.StatusCode = 420; + responsepp.StatusDescription = "SHEESH"; + + listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate; + listener.UnsafeConnectionNtlmAuthentication = true; + listener.IgnoreWriteExceptions = true; + + listener.Stop(); + } + + /// + /// Gives the user a subscription that has the same level as the key + /// + /// Username of the user thats going to get upgraded + /// License with the same level as the subscription you want to give the user + public void upgrade(string username, string key) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "upgrade", + ["username"] = username, + ["key"] = key, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + json.success = false; + load_response_struct(json); + } + + /// + /// Authenticate without using usernames and passwords + /// + /// Licence used to login with + public void license(string key) + { + CheckInit(); + + string hwid = HWID.GetHWID(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "license", + ["key"] = key, + ["hwid"] = hwid, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + load_user_data(json.info); + } + /// + /// Checks if the current session is validated or not + /// + public void check() + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "check", + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + } + /// + /// Change the data of an existing user variable, *User must be logged in* + /// + /// User variable name + /// The content of the variable + public void setvar(string var, string data) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "setvar", + ["var"] = var, + ["data"] = data, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + } + /// + /// Gets the an existing user variable + /// + /// User Variable Name + /// The content of the user variable + public string getvar(string var) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "getvar", + ["var"] = var, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + return json.response; + return null; + } + /// + /// Bans the current logged in user + /// + public void ban(string reason = null) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "ban", + ["reason"] = reason, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + } + /// + /// Gets an existing global variable + /// + /// Variable ID + /// The content of the variable + public string var(string varid) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "var", + ["varid"] = varid, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + return json.message; + return null; + } + /// + /// Fetch usernames of online users + /// + /// ArrayList of usernames + public List fetchOnline() + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "fetchOnline", + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + + if (json.success) + return json.users; + return null; + } + /// + /// Fetch app statistic counts + /// + public void fetchStats() + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "fetchStats", + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + + if (json.success) + load_app_data(json.appinfo); + } + /// + /// Gets the last 50 sent messages of that channel + /// + /// The channel name + /// the last 50 sent messages of that channel + public List chatget(string channelname) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "chatget", + ["channel"] = channelname, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + { + return json.messages; + } + return null; + } + /// + /// Sends a message to the given channel name + /// + /// Message + /// Channel Name + /// If the message was sent successfully, it returns true if not false + public bool chatsend(string msg, string channelname) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "chatsend", + ["message"] = msg, + ["channel"] = channelname, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + return true; + return false; + } + /// + /// Checks if the current ip address/hwid is blacklisted + /// + /// If found blacklisted returns true if not false + public bool checkblack() + { + CheckInit(); + string hwid = HWID.GetHWID(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "checkblacklist", + ["hwid"] = hwid, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + return true; + return false; + } + /// + /// Sends a request to a webhook that you've added in the dashboard in a safe way without it being showed for example a http debugger + /// + /// Webhook ID + /// Parameters + /// Body of the request, empty by default + /// Content type, empty by default + /// the webhook's response + public string webhook(string webid, string param, string body = "", string conttype = "") + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "webhook", + ["webid"] = webid, + ["params"] = param, + ["body"] = body, + ["conttype"] = conttype, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + return json.response; + return null; + } + /// + /// KeyAuth acts as proxy and downlods the file in a secure way + /// + /// File ID + /// The bytes of the download file + public byte[] download(string fileid) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + + ["type"] = "file", + ["fileid"] = fileid, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + if (json.success) + return encryption.str_to_byte_arr(json.contents); + return null; + } + /// + /// Logs the IP address,PC Name with a message, if a discord webhook is set up in the app settings, the log will get sent there and the dashboard if not set up it will only be in the dashboard + /// + /// Message + public void log(string message) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "log", + ["pcuser"] = Environment.UserName, + ["message"] = message, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + req(values_to_upload); + } + /// + /// Change the username of a user, *User must be logged in* + /// + /// New username. + public void changeUsername(string username) + { + CheckInit(); + + var values_to_upload = new NameValueCollection + { + ["type"] = "changeUsername", + ["newUsername"] = username, + ["sessionid"] = sessionid, + ["name"] = name, + ["ownerid"] = ownerid + }; + + var response = req(values_to_upload); + + var json = response_decoder.string_to_generic(response); + load_response_struct(json); + } + + public static string checksum(string filename) + { + string result; + using (MD5 md = MD5.Create()) + { + using (FileStream fileStream = File.OpenRead(filename)) + { + byte[] value = md.ComputeHash(fileStream); + result = BitConverter.ToString(value).Replace("-", "").ToLowerInvariant(); + } + } + return result; + } + + public static void LogEvent(string content) + { + string logFilePath = "KeyAuth_Logs.txt"; + + try + { + var jsonObject = JsonSerializer.Deserialize>(content); + if (jsonObject != null) + { + string[] redactFields = { "sessionid", "ownerid", "secret", "version" }; + foreach (var field in redactFields) + { + if (jsonObject.ContainsKey(field)) + { + jsonObject[field] = "REDACTED"; + } + } + content = JsonSerializer.Serialize(jsonObject); + } + + File.AppendAllText(logFilePath, $"[{DateTime.Now}] {content}\n"); + } + catch (Exception ex) + { + Console.WriteLine($"Error logging data: {ex.Message}"); + } + } + + private static void RedactField(Dictionary jsonObject, string fieldName) + { + if (jsonObject.ContainsKey(fieldName)) + { + jsonObject[fieldName] = "REDACTED"; + } + } + + + public static void error(string message) + { + string folder = @"Logs", file = Path.Combine(folder, "ErrorLogs.txt"); + + if (!Directory.Exists(folder)) + { + Directory.CreateDirectory(folder); + } + + if (!File.Exists(file)) + { + using (FileStream stream = File.Create(file)) + { + File.AppendAllText(file, DateTime.Now + " > This is the start of your error logs file"); + } + } + + File.AppendAllText(file, DateTime.Now + $" > {message}" + Environment.NewLine); + + Process.Start(new ProcessStartInfo("cmd.exe", $"/c start cmd /C \"color b && title Error && echo {message} && timeout /t 5\"") + { + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }); + Environment.Exit(0); + } + + private static string req(NameValueCollection post_data) + { + try + { + using (WebClient client = new WebClient()) + { + client.Proxy = null; + + ServicePointManager.ServerCertificateValidationCallback += assertSSL; + + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); + + var raw_response = client.UploadValues("https://lizenz.tbs-server.de/api/1.2/", post_data); + + stopwatch.Stop(); + responseTime = stopwatch.ElapsedMilliseconds; + + ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; + + sigCheck(Encoding.UTF8.GetString(raw_response), client.ResponseHeaders["signature"], post_data.Get(0)); + + LogEvent(Encoding.Default.GetString(raw_response) + "\n"); + + return Encoding.Default.GetString(raw_response); + } + } + catch (WebException webex) + { + var response = (HttpWebResponse)webex.Response; + switch (response.StatusCode) + { + case (HttpStatusCode)429: // client hit our rate limit + error("You're connecting too fast to loader, slow down."); + LogEvent("You're connecting too fast to loader, slow down."); + Environment.Exit(0); + return ""; + default: // site won't resolve. you should use keyauth.uk domain since it's not blocked by any ISPs + error("Connection failure. Please try again, or contact us for help."); + LogEvent("Connection failure. Please try again, or contact us for help."); + Environment.Exit(0); + return ""; + } + } + } + + private static bool assertSSL(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + if ((!certificate.Issuer.Contains("Google Trust Services") && !certificate.Issuer.Contains("Let's Encrypt")) || sslPolicyErrors != SslPolicyErrors.None) + { + error("SSL assertion fail, make sure you're not debugging Network. Disable internet firewall on router if possible. & echo: & echo If not, ask the developer of the program to use custom domains to fix this."); + LogEvent("SSL assertion fail, make sure you're not debugging Network. Disable internet firewall on router if possible. If not, ask the developer of the program to use custom domains to fix this."); + return false; + } + return true; + } + + private static void sigCheck(string resp, string signature, string type) + { + if (type == "log" || type == "file") // log doesn't return a response. + { + return; + } + + try + { + string clientComputed = encryption.HashHMAC((type == "init") ? enckey.Substring(17, 64) : enckey, resp); + if (!encryption.CheckStringsFixedTime(clientComputed, signature)) + { + error("Signature checksum failed. Request was tampered with or session ended most likely. & echo: & echo Response: " + resp); + LogEvent(resp + "\n"); + Environment.Exit(0); + } + } + catch + { + error("Signature checksum failed. Request was tampered with or session ended most likely. & echo: & echo Response: " + resp); + LogEvent(resp + "\n"); + Environment.Exit(0); + } + } + + #region app_data + public app_data_class app_data = new app_data_class(); + + public class app_data_class + { + public string numUsers { get; set; } + public string numOnlineUsers { get; set; } + public string numKeys { get; set; } + public string version { get; set; } + public string customerPanelLink { get; set; } + public string downloadLink { get; set; } + } + + private void load_app_data(app_data_structure data) + { + app_data.numUsers = data.numUsers; + app_data.numOnlineUsers = data.numOnlineUsers; + app_data.numKeys = data.numKeys; + app_data.version = data.version; + app_data.customerPanelLink = data.customerPanelLink; + } + #endregion + + #region user_data + public user_data_class user_data = new user_data_class(); + + public class user_data_class + { + public string username { get; set; } + public string ip { get; set; } + public string hwid { get; set; } + public string createdate { get; set; } + public string lastlogin { get; set; } + public List subscriptions { get; set; } // array of subscriptions (basically multiple user ranks for user with individual expiry dates + } + public class Data + { + public string subscription { get; set; } + public string expiry { get; set; } + public string timeleft { get; set; } + } + + private void load_user_data(user_data_structure data) + { + user_data.username = data.username; + user_data.ip = data.ip; + user_data.hwid = data.hwid; + user_data.createdate = data.createdate; + user_data.lastlogin = data.lastlogin; + user_data.subscriptions = data.subscriptions; // array of subscriptions (basically multiple user ranks for user with individual expiry dates + } + #endregion + + #region response_struct + public response_class response = new response_class(); + + public class response_class + { + public bool success { get; set; } + public string message { get; set; } + } + + private void load_response_struct(response_structure data) + { + response.success = data.success; + response.message = data.message; + } + #endregion + + private json_wrapper response_decoder = new json_wrapper(new response_structure()); + } + + public static class encryption + { + public static string HashHMAC(string enckey, string resp) + { + byte[] key = Encoding.UTF8.GetBytes(enckey); + byte[] message = Encoding.UTF8.GetBytes(resp); + var hash = new HMACSHA256(key); + return byte_arr_to_str(hash.ComputeHash(message)); + } + + public static string byte_arr_to_str(byte[] ba) + { + StringBuilder hex = new StringBuilder(ba.Length * 2); + foreach (byte b in ba) + hex.AppendFormat("{0:x2}", b); + return hex.ToString(); + } + + public static byte[] str_to_byte_arr(string hex) + { + try + { + int NumberChars = hex.Length; + byte[] bytes = new byte[NumberChars / 2]; + for (int i = 0; i < NumberChars; i += 2) + bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); + return bytes; + } + catch + { + api.error("The session has ended, open program again."); + Environment.Exit(0); + return null; + } + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public static bool CheckStringsFixedTime(string str1, string str2) + { + if (str1.Length != str2.Length) + { + return false; + } + var result = 0; + for (var i = 0; i < str1.Length; i++) + { + result |= str1[i] ^ str2[i]; + } + return result == 0; + } + + public static string iv_key() => + Guid.NewGuid().ToString().Substring(0, 16); + } + + public class json_wrapper + { + public static bool is_serializable(Type to_check) => + to_check.IsSerializable || to_check.IsDefined(typeof(DataContractAttribute), true); + + public json_wrapper(object obj_to_work_with) + { + current_object = obj_to_work_with; + + var object_type = current_object.GetType(); + + serializer = new DataContractJsonSerializer(object_type); + + if (!is_serializable(object_type)) + throw new Exception($"the object {current_object} isn't a serializable"); + } + + public object string_to_object(string json) + { + var buffer = Encoding.Default.GetBytes(json); + + //SerializationException = session expired + + using (var mem_stream = new MemoryStream(buffer)) + return serializer.ReadObject(mem_stream); + } + + public T string_to_generic(string json) => + (T)string_to_object(json); + + private DataContractJsonSerializer serializer; + + private object current_object; + } +} \ No newline at end of file diff --git a/Valheim Dashboard/Language.cs b/Valheim Dashboard/Language.cs new file mode 100644 index 0000000..a48cba3 --- /dev/null +++ b/Valheim Dashboard/Language.cs @@ -0,0 +1,15 @@ +using System.Globalization; +using System.Resources; + +namespace Valheim_Dashboard; + +public class Language +{ + private static readonly ResourceManager ResourceManager = new ResourceManager("Valheim_Dashboard.Languages.Resources", typeof(Language).Assembly); + + public static string GetString(string key) + { + return ResourceManager.GetString(key, CultureInfo.CurrentUICulture) ?? $"[{key}]"; + } + +} \ No newline at end of file diff --git a/Valheim Dashboard/Languages/Resources.Designer.cs b/Valheim Dashboard/Languages/Resources.Designer.cs new file mode 100644 index 0000000..fea3af0 --- /dev/null +++ b/Valheim Dashboard/Languages/Resources.Designer.cs @@ -0,0 +1,125 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Valheim_Dashboard.Languages { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Valheim_Dashboard.Languages.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Für die Synchronisierung steht das Plugin oder FTP zur verfügung.. + /// + internal static string Server_Schritt_1 { + get { + return ResourceManager.GetString("Server_Schritt_1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Für das Plugin trage hier deine Server IP und Port ein. Standart mäßig läuft es auf dem standart Valheim Port: 2456. Achte darauf das der Port offen ist. Also am besten den selben wie der Server :). + /// + internal static string Server_Schritt_2 { + get { + return ResourceManager.GetString("Server_Schritt_2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Anschließen kannst du die Verbindung prüfen! Bedenke das der Server mit dem Plugin bereits online sein muss. Es wird wie jedes andere Plugin / Mod bei BepInEx installiert.. + /// + internal static string Server_Schritt_3 { + get { + return ResourceManager.GetString("Server_Schritt_3", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to FTP geht auch! Dazu musst du nur IP, Port, Benutzername, Passwort eintragen. Die daten siehst du in deinem Server Panel vom Hoster.. + /// + internal static string Server_Schritt_4 { + get { + return ResourceManager.GetString("Server_Schritt_4", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Anschließend klicke auf Verbindung Prüfen. . + /// + internal static string Server_Schritt_5 { + get { + return ResourceManager.GetString("Server_Schritt_5", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Nun musst du nur den BepInEx ordner auswählen.. + /// + internal static string Server_Schritt_6 { + get { + return ResourceManager.GetString("Server_Schritt_6", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Willkommen !. + /// + internal static string Willkommen { + get { + return ResourceManager.GetString("Willkommen", resourceCulture); + } + } + } +} diff --git a/Valheim Dashboard/Languages/Resources.resx b/Valheim Dashboard/Languages/Resources.resx new file mode 100644 index 0000000..2b0dac3 --- /dev/null +++ b/Valheim Dashboard/Languages/Resources.resx @@ -0,0 +1,42 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Willkommen ! + + + Für die Synchronisierung steht das Plugin oder FTP zur verfügung. + + + Für das Plugin trage hier deine Server IP und Port ein. Standart mäßig läuft es auf dem standart Valheim Port: 2456. Achte darauf das der Port offen ist. Also am besten den selben wie der Server :) + + + Anschließen kannst du die Verbindung prüfen! Bedenke das der Server mit dem Plugin bereits online sein muss. Es wird wie jedes andere Plugin / Mod bei BepInEx installiert. + + + FTP geht auch! Dazu musst du nur IP, Port, Benutzername, Passwort eintragen. Die daten siehst du in deinem Server Panel vom Hoster. + + + Anschließend klicke auf Verbindung Prüfen. + + + Nun musst du nur den BepInEx ordner auswählen. + + \ No newline at end of file diff --git a/Valheim Dashboard/Program.cs b/Valheim Dashboard/Program.cs new file mode 100644 index 0000000..38458fb --- /dev/null +++ b/Valheim Dashboard/Program.cs @@ -0,0 +1,36 @@ +using Avalonia; +using Avalonia.ReactiveUI; +using System; +using System.IO; + +namespace Valheim_Dashboard; + +sealed class Program +{ + // Initialization code. Don't use any Avalonia, third-party APIs or any + // SynchronizationContext-reliant code before AppMain is called: things aren't initialized + // yet and stuff might break. + [STAThread] + public static void Main(string[] args) + { + // Logs in eine Datei schreiben + var logFilePath = "logs.txt"; + var writer = new StreamWriter(logFilePath); + writer.AutoFlush = true; + //Console.SetOut(writer); + + Console.WriteLine("Die Anwendung wird gestartet..."); + + BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); + } + + + // Avalonia configuration, don't remove; also used by visual designer. + public static AppBuilder BuildAvaloniaApp() + => AppBuilder.Configure() + .UsePlatformDetect() + .WithInterFont() + .LogToTrace() + .UseReactiveUI(); +} \ No newline at end of file diff --git a/Valheim Dashboard/Settings.cs b/Valheim Dashboard/Settings.cs new file mode 100644 index 0000000..d830ee0 --- /dev/null +++ b/Valheim Dashboard/Settings.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text.Json; +using System.Xml; +using System.Xml.Serialization; + +namespace Valheim_Dashboard; + +public class Settings +{ + private static readonly string AppName = "ValheimDashboard"; + private static readonly string SettingsFileName = "settings.json"; + private static readonly string ConfigPath = CreatePath(); + + public static string CreatePath() + { + string basePath; + + if (OperatingSystem.IsWindows()) + { + basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // %AppData% + } + else // Linux + { + basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".config"); + } + + // Anwendungspfad erstellen + string appPath = Path.Combine(basePath, AppName); + Directory.CreateDirectory(appPath); // Pfad erstellen, falls er nicht existiert + return appPath; + } + + public static string SettingsPath() + { + return Path.Combine(ConfigPath, SettingsFileName); + } + + public static void SettingsSave(string name, string value) + { + // Vorhandenes JSON lesen (falls existent) + Dictionary settings; + if (File.Exists(SettingsPath())) + { + string existingJson = File.ReadAllText(SettingsPath()); + settings = JsonSerializer.Deserialize>(existingJson) ?? new Dictionary(); + } + else + { + settings = new Dictionary(); + } + + // Neuen Schlüssel-Wert hinzufügen/überschreiben + settings[name] = value; + + // Änderungen speichern + string json = JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(SettingsPath(), json); + } + + public static string? SettingsLoad(string name, bool force_reload = false) + { + string filePath = SettingsPath(); + if (File.Exists(filePath)) + { + string json = File.ReadAllText(filePath); + + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + + if (root.TryGetProperty(name, out JsonElement nameProperty)) + { + return nameProperty.GetString(); + } + else + { + return null; + } + } + return null; + } + + +} \ No newline at end of file diff --git a/Valheim Dashboard/TutorialManager.cs b/Valheim Dashboard/TutorialManager.cs new file mode 100644 index 0000000..8c9ba84 --- /dev/null +++ b/Valheim Dashboard/TutorialManager.cs @@ -0,0 +1,284 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Media; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Avalonia.Input; +using Avalonia.Interactivity; + +namespace Valheim_Dashboard +{ + public class TutorialManager + { + private readonly Window _mainWindow; + + public TutorialManager(Window mainWindow) + { + _mainWindow = mainWindow ?? throw new ArgumentNullException(nameof(mainWindow)); + } + + + public void HighlightControl(Control target, bool highlight) + { + if (target == null) return; + + if (highlight) + { + if (target is Button button) + { + button.BorderBrush = Brushes.Gold; + button.BorderThickness = new Thickness(2); + } + + // Weitere visuelle Anpassungen hier + } + else + { + if (target is Button button) + { + button.BorderBrush = Brushes.Transparent; + button.BorderThickness = new Thickness(0); + } + + } + } + + + // Highlight ein Element mit einem animierten Rahmen + public void HighlightElement(Control element, Brush borderBrush, double thickness = 3) + { + + if (element is Button button) + { + button.BorderBrush = borderBrush; + button.BorderThickness = new Thickness(thickness); + } + + if (element is TextBox textBox) + { + textBox.BorderBrush = borderBrush; + textBox.BorderThickness = new Thickness(thickness); + } + + if (element is Expander expander) + { + + + Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() => + { + var overlayLayer = _mainWindow.FindControl("OverlayLayer"); + if (overlayLayer == null) + { + Console.WriteLine("Overlay-Layer (Canvas) nicht gefunden."); + return; + } + + + // Ziel-Element Position berechnen + var targetPosition = expander.TranslatePoint(new Point(0, 0), overlayLayer); + if (targetPosition.HasValue) + { + var highlightBorder = new Border + { + BorderBrush = borderBrush, + BorderThickness = new Thickness(thickness), + Background = Brushes.Transparent, + Width = expander.Bounds.Width + thickness * 2, + Height = expander.Bounds.Height + thickness * 2 + }; + + overlayLayer.Children.Add(highlightBorder); + Canvas.SetLeft(highlightBorder, targetPosition.Value.X - thickness); + Canvas.SetTop(highlightBorder, targetPosition.Value.Y - thickness); + } + else + { + Console.WriteLine("Konnte die Position der Zielkontrolle nicht berechnen."); + } + }); + } + } + + public async Task SmoothScrollToControl(ScrollViewer scrollViewer, Control target, int duration = 300) + { + + var targetPosition = target.TranslatePoint(new Point(0, 0), scrollViewer); + + double startOffset = scrollViewer.Offset.Y; + double delta = targetPosition.Value.Y - startOffset; + + int frames = duration / 16; // 16ms pro Frame + for (int i = 0; i <= frames; i++) + { + double progress = (double)i / frames; + double easedProgress = EasingFunction(progress); // Optional: Easing-Funktion + scrollViewer.Offset = new Vector(scrollViewer.Offset.X, startOffset + (delta * easedProgress)); + await Task.Delay(16); + } + } + + private double EasingFunction(double t) + { + return t * t * (3 - 2 * t); // Standard Smoothing (EaseInOut) + } + + + // Öffnen eines Expanders + public void OpenExpander(Expander expander) + { + if (expander != null) + { + expander.IsExpanded = true; + } + } + + public void CloseExpander(Expander expander) + { + if (expander != null) + { + expander.IsExpanded = false; + } + } + + // Schreibe Text in ein Textfeld (z. B. TextBox) + public void WriteText(TextBox textBox, string text) + { + if (textBox != null) + { + textBox.Text = text; + } + } + + // Simuliere einen Button-Klick + public void ClickButton(Button button) + { + if (button != null) + { + button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); // Simuliere Klick + } + } + + public enum SpeechBubblePosition + { + Top, + Bottom, + Left, + Right + } + + + + + // Zeige eine Sprechblase mit einem Weiter-Button + public void ShowSpeechBubble(Control target, SpeechBubblePosition position, string text, Action onNext = null) +{ + Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() => + { + var overlayLayer = _mainWindow.FindControl("OverlayLayer"); + if (overlayLayer == null) + { + Console.WriteLine("Overlay-Layer (Canvas) nicht gefunden."); + return; + } + + var speechBubble = new Border + { + Background = Brushes.DarkGray, + BorderBrush = Brushes.Black, + BorderThickness = new Thickness(2), + CornerRadius = new CornerRadius(8), + Width = 250, + Padding = new Thickness(10), + Child = new StackPanel + { + Children = + { + new TextBlock + { + Text = text, + Foreground = Brushes.White, + TextWrapping = TextWrapping.Wrap, + Margin = new Thickness(0, 0, 0, 10) + }, + new Button + { + IsHitTestVisible = true, + Content = "Weiter", + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + Command = ReactiveUI.ReactiveCommand.Create(() => + { + overlayLayer.Children.Clear(); + onNext?.Invoke(); + }) + } + } + } + }; + + // Positionierung relativ zum Ziel + + var targetPosition = target.TranslatePoint(new Point(0, 0), overlayLayer); + if (targetPosition.HasValue) + { + overlayLayer.Children.Add(speechBubble); + + // Bildschirm- oder Overlay-Größen abrufen + var overlayBounds = overlayLayer.Bounds; + + double finalX = targetPosition.Value.X; + double finalY = targetPosition.Value.Y; + + // Manuelle Layout-Berechnung + speechBubble.Measure(Size.Infinity); // Grenze für unendliche Größe setzen + speechBubble.Arrange(new Rect(0, 0, speechBubble.DesiredSize.Width, speechBubble.DesiredSize.Height)); + + // Nach Layout-Berechnung gewünschte Maße abrufen + double speechBubbleWidth = speechBubble.Bounds.Width > 0 ? speechBubble.Bounds.Width : speechBubble.DesiredSize.Width; + double speechBubbleHeight = speechBubble.Bounds.Height > 0 ? speechBubble.Bounds.Height : speechBubble.DesiredSize.Height; + + + // Position basierend auf dem Parameter "position" berechnen + switch (position) + { + case SpeechBubblePosition.Top: + finalX = targetPosition.Value.X + (target.Bounds.Width / 2) - (speechBubbleWidth / 2); + finalY = targetPosition.Value.Y - speechBubbleHeight - 10; + break; + + case SpeechBubblePosition.Bottom: + finalX = targetPosition.Value.X + (target.Bounds.Width / 2) - (speechBubbleWidth / 2); + finalY = targetPosition.Value.Y + target.Bounds.Height + 10; + break; + + case SpeechBubblePosition.Left: + finalX = targetPosition.Value.X - speechBubbleWidth - 10; + finalY = targetPosition.Value.Y; + break; + + case SpeechBubblePosition.Right: + finalX = targetPosition.Value.X + target.Bounds.Width + 10; + finalY = targetPosition.Value.Y; + break; + } + + // Dynamisch prüfen, ob das Popup im Sichtbereich ist + if (finalX < 0) finalX = 0; // Zu weit links + if (finalX + speechBubble.Width > overlayBounds.Width) finalX = overlayBounds.Width - speechBubble.Width; // Zu weit rechts + if (finalY < 0) finalY = 0; // Zu weit oben + if (finalY + speechBubble.Height > overlayBounds.Height) finalY = overlayBounds.Height - speechBubble.Height; // Zu weit unten + + // Position setzen + Canvas.SetLeft(speechBubble, finalX); + Canvas.SetTop(speechBubble, finalY); + } + else + { + Console.WriteLine("Konnte die Position der Zielkontrolle nicht berechnen."); + } + }); +} + + } +} \ No newline at end of file diff --git a/Valheim Dashboard/Valheim Dashboard.csproj b/Valheim Dashboard/Valheim Dashboard.csproj new file mode 100644 index 0000000..5971f8f --- /dev/null +++ b/Valheim Dashboard/Valheim Dashboard.csproj @@ -0,0 +1,43 @@ + + + WinExe + net8.0 + enable + true + app.manifest + true + + + + + + + + + + + + + + + None + All + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + True + True + Resources.resx + + + diff --git a/Valheim Dashboard/ViewLocator.cs b/Valheim Dashboard/ViewLocator.cs new file mode 100644 index 0000000..6db06f6 --- /dev/null +++ b/Valheim Dashboard/ViewLocator.cs @@ -0,0 +1,33 @@ +using System; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using Valheim_Dashboard.ViewModels; + +namespace Valheim_Dashboard; + +public class ViewLocator : IDataTemplate +{ + public Control? Build(object? param) + { + if (param is null) + return null; + + var viewModelType = param.GetType(); + var name = viewModelType.FullName!.Replace("ViewModel", "View", StringComparison.Ordinal); + + // Verwenden Sie die Assembly des ViewModels, um die View zu finden + var viewType = viewModelType.Assembly.GetType(name); + + + if (viewType != null) + { + return (Control)Activator.CreateInstance(viewType)!; + } + + return new TextBlock { Text = "Not Found: " + name }; + } + public bool Match(object? data) + { + return data is ViewModelBase; + } +} \ No newline at end of file diff --git a/Valheim Dashboard/ViewModels/DashboardViewModel.cs b/Valheim Dashboard/ViewModels/DashboardViewModel.cs new file mode 100644 index 0000000..f7f2c5b --- /dev/null +++ b/Valheim Dashboard/ViewModels/DashboardViewModel.cs @@ -0,0 +1,6 @@ +namespace Valheim_Dashboard.ViewModels; + +public class DashboardViewModel : ViewModelBase +{ + +} \ No newline at end of file diff --git a/Valheim Dashboard/ViewModels/ErsterStartViewModel.cs b/Valheim Dashboard/ViewModels/ErsterStartViewModel.cs new file mode 100644 index 0000000..434c57e --- /dev/null +++ b/Valheim Dashboard/ViewModels/ErsterStartViewModel.cs @@ -0,0 +1,28 @@ +using Avalonia; +using ReactiveUI; + +namespace Valheim_Dashboard.ViewModels; + +public class ErsterStartViewModel : ViewModelBase +{ + private bool _startAnimation; + public bool StartAnimation + { + get => _startAnimation; + set => this.RaiseAndSetIfChanged(ref _startAnimation, value); + } + + + private Point _animationTargetPosition; + public Point AnimationTargetPosition + { + get => _animationTargetPosition; + set => this.RaiseAndSetIfChanged(ref _animationTargetPosition, value); + } + + public ErsterStartViewModel() + { + StartAnimation = true; // Property auf true setzen + } + +} \ No newline at end of file diff --git a/Valheim Dashboard/ViewModels/FTPViewModel.cs b/Valheim Dashboard/ViewModels/FTPViewModel.cs new file mode 100644 index 0000000..aad6d1c --- /dev/null +++ b/Valheim Dashboard/ViewModels/FTPViewModel.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reactive; +using System.Threading.Tasks; +using ReactiveUI; + +namespace Valheim_Dashboard.ViewModels +{ + public class FtpViewModel : ViewModelBase + { + public static FtpClient _ftpClient; + + // Speichert den aktuellen FTP-Pfad + private string _currentPath = "/"; + + public string CurrentPath + { + get => _currentPath; + set => this.RaiseAndSetIfChanged(ref _currentPath, value); + } + + + + // ObservableCollection, die jetzt FtpItem-Objekte enthält + public ObservableCollection Files { get; } = new(); + + // Liste für FTP-Dateien und Ordner + // public ObservableCollection Files { get; } = new(); + + // Befehl zum Laden des Verzeichnisses + public ReactiveCommand LoadFtpCommand { get; } + + // Command, der ausgeführt wird, wenn ein Ordner geklickt wird + public ReactiveCommand FolderClickedCommand { get; } + + + public FtpViewModel() + { + + + // Befehl für das Neuladen des Verzeichnisses + LoadFtpCommand = ReactiveCommand.CreateFromTask(LoadFtpDirectory); + + // Command, der beim Klick auf einen Ordner ausgeführt wird + // FolderClickedCommand = ReactiveCommand.Create(OnFolderClicked); + FolderClickedCommand = ReactiveCommand.Create(item => + { + // Logik für den Klick auf das Folder-Item + Console.WriteLine($"Folder {item.Name} clicked!"); + }); + + // Beim Erstellen direkt FTP-Verzeichnis laden + LoadFtpCommand.Execute().Subscribe(); + Files.Add(new FtpItem { Name = "TestFile.txt", IsDirectory = false }); + + } + + private async Task LoadFtpDirectory() + { + try + { + // Verwende die neue Methode, um detaillierte Informationen zu erhalten + var items = await _ftpClient.ListDirectoryDetailsAsync(CurrentPath); + + // Sortiere: Ordner zuerst, dann Dateien, jeweils alphabetisch + var sortedItems = items + .OrderBy(item => item.IsDirectory ? 0 : 1) + .ThenBy(item => item.Name, StringComparer.OrdinalIgnoreCase) + .ToList(); + + // Hier gehen wir davon aus, dass du z. B. eine ObservableCollection vom Typ string hast. + // Du kannst aber auch deine ObservableCollection umstellen, sodass du FtpItem-Objekte speicherst. + Files.Clear(); + foreach (var item in sortedItems) + { + Console.WriteLine($"Item geladen: {item.Name}"); + // Je nach Bedarf kannst du hier den Namen oder auch weitere Infos anzeigen. + Files.Add(item); + } + } + catch (Exception ex) + { + Console.WriteLine($"Fehler beim Laden des FTP-Verzeichnisses: {ex.Message}"); + } + } + + private void OnFolderClicked(FtpItem item) + { + Console.WriteLine("OrdnerKlick"); + if (item.IsDirectory) + { + // Beispiel: Den aktuellen Pfad serweitern und das neue Verzeichnis laden + // Je nach Bedarf kannst du hier auch Navigation oder andere Logik einbauen + CurrentPath = System.IO.Path.Combine(CurrentPath, item.Name); + // Neues Verzeichnis laden + LoadFtpCommand.Execute().Subscribe(); + } + } + + } +} \ No newline at end of file diff --git a/Valheim Dashboard/ViewModels/LizenzViewModel.cs b/Valheim Dashboard/ViewModels/LizenzViewModel.cs new file mode 100644 index 0000000..e4fd47c --- /dev/null +++ b/Valheim Dashboard/ViewModels/LizenzViewModel.cs @@ -0,0 +1,29 @@ +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Valheim_Dashboard.ViewModels; + +public class LizenzViewModel : ViewModelBase +{ + + public string LizenzKey { get; set; } + + private string _verifizierungsAntwort; + public string VerifizierungsAntwort + { + get => _verifizierungsAntwort; + set + { + if (_verifizierungsAntwort != value) + { + _verifizierungsAntwort = value; + OnPropertyChanged(); + } + } + } + + public event PropertyChangedEventHandler? PropertyChanged; + protected void OnPropertyChanged([CallerMemberName] string? name = null) + => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); + +} \ No newline at end of file diff --git a/Valheim Dashboard/ViewModels/MainWindowViewModel.cs b/Valheim Dashboard/ViewModels/MainWindowViewModel.cs new file mode 100644 index 0000000..b3a9fdc --- /dev/null +++ b/Valheim Dashboard/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,84 @@ +using ReactiveUI; +using Valheim_Dashboard.ViewModels; +using Valheim_Dashboard.Views; + +namespace Valheim_Dashboard.ViewModels +{ + public class MainWindowViewModel : ViewModelBase + { + private readonly ViewModelLocator _locator; + private ViewModelBase _currentViewModel; + private LizenzView _lizenzView; + + + public MainWindowViewModel(ViewModelLocator locator) + { + _locator = locator; + + // Initialer ViewModel über Locator setzen + if (Settings.SettingsLoad("LizenzKey") != null) { + + + + // Lizenzkey aus den Einstellungen laden + string lizenzKey = Settings.SettingsLoad("LizenzKey"); + var lizenzViewModel = _locator.LizenzViewModel; + lizenzViewModel.LizenzKey = lizenzKey; // Lizenzkey übergeben + _currentViewModel = lizenzViewModel; + + + } + else + { + _currentViewModel = _locator.ErsterStartViewModel; + } + + } + + + public ViewModelBase CurrentViewModel + { + get => _currentViewModel; + set => this.RaiseAndSetIfChanged(ref _currentViewModel, value); + } + + public void SwitchToErsterStart() + { + CurrentViewModel = _locator.ErsterStartViewModel; + + } + + + public void SwitchToLizenzView() + { + + CurrentViewModel = _locator.LizenzViewModel; + } + + public void SwitchToServerSettings() + { + + CurrentViewModel = _locator.ServerSettingsViewModel; + } + + public void SwitchToDashboard() + { + CurrentViewModel = _locator.DashboardViewModel; + } + + + + + public void SwitchToFTP(FtpClient ftpClient) + { + // var ftpViewModel = new FtpViewModel(ftpClient); + // var ftpView = new FTPView(ftpViewModel); + CurrentViewModel = _locator.FtpViewModel; + + } + + + + + } +} \ No newline at end of file diff --git a/Valheim Dashboard/ViewModels/ServerSettingsViewModel.cs b/Valheim Dashboard/ViewModels/ServerSettingsViewModel.cs new file mode 100644 index 0000000..ba255ce --- /dev/null +++ b/Valheim Dashboard/ViewModels/ServerSettingsViewModel.cs @@ -0,0 +1,76 @@ +using System; +using System.ComponentModel; +using System.Reactive; +using System.Reactive.Linq; +using System.Runtime.CompilerServices; +using System.Windows.Input; +using Avalonia.Controls; +using Avalonia.Media; +using ReactiveUI; +using Valheim_Dashboard.Views; + +namespace Valheim_Dashboard.ViewModels; + +public class ServerSettingsViewModel : ViewModelBase +{ + + // Eigenschaften für Plugin + private string? _pluginIp; + + public string? PluginIp + { + get => _pluginIp; + set => this.RaiseAndSetIfChanged(ref _pluginIp, value); + } + + private string? _pluginPort; + + public string? PluginPort + { + get => _pluginPort; + set => this.RaiseAndSetIfChanged(ref _pluginPort, value); + } + + // Eigenschaften für FTP + private string? _ftpIp; + + public string? FtpIp + { + get => _ftpIp; + set => this.RaiseAndSetIfChanged(ref _ftpIp, value); + } + + private string? _ftpPort; + + public string? FtpPort + { + get => _ftpPort; + set => this.RaiseAndSetIfChanged(ref _ftpPort, value); + } + + private string? _ftpUsername; + + public string? FtpUsername + { + get => _ftpUsername; + set => this.RaiseAndSetIfChanged(ref _ftpUsername, value); + } + + private string? _ftpPassword; + + public string? FtpPassword + { + get => _ftpPassword; + set => this.RaiseAndSetIfChanged(ref _ftpPassword, value); + } + + private readonly TutorialManager _tutorialManager; + private Window? _window; + public ServerSettingsViewModel() + { + } + + + + +} \ No newline at end of file diff --git a/Valheim Dashboard/ViewModels/ViewModelBase.cs b/Valheim Dashboard/ViewModels/ViewModelBase.cs new file mode 100644 index 0000000..ebe013c --- /dev/null +++ b/Valheim Dashboard/ViewModels/ViewModelBase.cs @@ -0,0 +1,7 @@ +using ReactiveUI; + +namespace Valheim_Dashboard.ViewModels; + +public class ViewModelBase : ReactiveObject +{ +} \ No newline at end of file diff --git a/Valheim Dashboard/ViewModels/ViewModelLocator.cs b/Valheim Dashboard/ViewModels/ViewModelLocator.cs new file mode 100644 index 0000000..87757dc --- /dev/null +++ b/Valheim Dashboard/ViewModels/ViewModelLocator.cs @@ -0,0 +1,16 @@ +using Valheim_Dashboard.ViewModels; + +namespace Valheim_Dashboard +{ + public class ViewModelLocator + { + public MainWindowViewModel MainWindowViewModel => new MainWindowViewModel(this); + public ErsterStartViewModel ErsterStartViewModel => new ErsterStartViewModel(); + public LizenzViewModel LizenzViewModel => new LizenzViewModel(); // Hinzugefügt + public ServerSettingsViewModel ServerSettingsViewModel => new ServerSettingsViewModel(); // Hinzugefügt + public DashboardViewModel DashboardViewModel => new DashboardViewModel(); // Hinzugefügt + public FtpViewModel FtpViewModel => new FtpViewModel(); // Hinzugefügt + + public ViewModelLocator() { } + } +} \ No newline at end of file diff --git a/Valheim Dashboard/Views/DashboardView.axaml b/Valheim Dashboard/Views/DashboardView.axaml new file mode 100644 index 0000000..99a39f6 --- /dev/null +++ b/Valheim Dashboard/Views/DashboardView.axaml @@ -0,0 +1,8 @@ + + Fashboard + diff --git a/Valheim Dashboard/Views/DashboardView.axaml.cs b/Valheim Dashboard/Views/DashboardView.axaml.cs new file mode 100644 index 0000000..ab2040f --- /dev/null +++ b/Valheim Dashboard/Views/DashboardView.axaml.cs @@ -0,0 +1,13 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Markup.Xaml; + +namespace Valheim_Dashboard.Views; + +public partial class DashboardView : UserControl +{ + public DashboardView() + { + InitializeComponent(); + } +} \ No newline at end of file diff --git a/Valheim Dashboard/Views/ErsterStartView.axaml b/Valheim Dashboard/Views/ErsterStartView.axaml new file mode 100644 index 0000000..5109dd6 --- /dev/null +++ b/Valheim Dashboard/Views/ErsterStartView.axaml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Valheim Dashboard/Views/ErsterStartView.axaml.cs b/Valheim Dashboard/Views/ErsterStartView.axaml.cs new file mode 100644 index 0000000..c0faaa2 --- /dev/null +++ b/Valheim Dashboard/Views/ErsterStartView.axaml.cs @@ -0,0 +1,122 @@ +using System; +using System.Reactive.Linq; +using Avalonia.Animation; +using Avalonia.Controls; +using Avalonia.Interactivity; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using Avalonia.ReactiveUI; +using Avalonia.Styling; +using ReactiveUI; +using Valheim_Dashboard.ViewModels; +using static Valheim_Dashboard.Animationen; +using Valheim_Dashboard.Views; + +namespace Valheim_Dashboard.Views +{ + public partial class ErsterStartView : ReactiveUserControl + { + + + + public ErsterStartView() + { + InitializeComponent(); + + this.WhenActivated(disposables => + { + Console.WriteLine("erster start view"); + // Animation starten, wenn ViewModel-Property sich ändert + this.WhenAnyValue(x => x.ViewModel.StartAnimation) + .Where(startAnimation => startAnimation) + .Subscribe(_ => StartAnimation()); + + this.WhenAnyValue(x => x.ViewModel.AnimationTargetPosition) + .Subscribe(pos => + { + if(HinweisTextBlock != null && WeiterButton != null) { + double offsetX = pos.X - WeiterButton.Bounds.X - 200; + double offsetY = pos.Y - WeiterButton.Bounds.Y - 150; + HinweisTextBlock.RenderTransform = new TranslateTransform(offsetX, offsetY); + } + }); + }); + } + + + private void StartAnimation() + { + + var hinweisTextBlock = this.FindControl("HinweisTextBlock"); + var weiterButton = this.FindControl + + + + + + diff --git a/Valheim Dashboard/Views/FTPView.axaml.cs b/Valheim Dashboard/Views/FTPView.axaml.cs new file mode 100644 index 0000000..d04c712 --- /dev/null +++ b/Valheim Dashboard/Views/FTPView.axaml.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Reactive; +using System.Reactive.Disposables; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Markup.Xaml; +using Avalonia.ReactiveUI; +using KeyAuth; +using ReactiveUI; +using Valheim_Dashboard.ViewModels; + +namespace Valheim_Dashboard.Views; + +public partial class FtpView : ReactiveUserControl +{ + public FtpView() + { + + InitializeComponent(); + + + // Aktivierungslogik für Bindings + this.WhenActivated(disposables => + { + // Binde den aktuellen Pfad an die TextBox + this.OneWayBind(ViewModel, vm => vm.CurrentPath, v => v.CurrentPathTextBox_.Text) + .DisposeWith(disposables); + + // Konvertiere die ObservableCollection zu IEnumerable + this.OneWayBind(ViewModel, vm => vm.Files, v => v.FtpFileList_.ItemsSource) + .DisposeWith(disposables); + + + }); + + + + + } + + + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); + } + + private TextBox CurrentPathTextBox_ => this.FindControl("CurrentPathTextBox"); + private ListBox FtpFileList_ => this.FindControl("FtpFileList"); +} \ No newline at end of file diff --git a/Valheim Dashboard/Views/LizenzView.axaml b/Valheim Dashboard/Views/LizenzView.axaml new file mode 100644 index 0000000..8479190 --- /dev/null +++ b/Valheim Dashboard/Views/LizenzView.axaml @@ -0,0 +1,151 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/Valheim Dashboard/Views/LizenzView.axaml.cs b/Valheim Dashboard/Views/LizenzView.axaml.cs new file mode 100644 index 0000000..cd7df38 --- /dev/null +++ b/Valheim Dashboard/Views/LizenzView.axaml.cs @@ -0,0 +1,144 @@ +using System; +using System.Threading.Tasks; +using Avalonia.Controls; +using Avalonia.Interactivity; +using KeyAuth; +using Valheim_Dashboard.ViewModels; + +namespace Valheim_Dashboard.Views; + +public partial class LizenzView : UserControl +{ + public LizenzView() + { + InitializeComponent(); + + LizenzKeyTextBox.GotFocus += (sender, e) => + { + if (LizenzKeyTextBox.Text == "Lizenzkey eingeben") + { + LizenzKeyTextBox.Text = ""; + verifizieren_button.IsEnabled = true; + }else if (LizenzKeyTextBox.Text != "Lizenzkey eingeben" || LizenzKeyTextBox.Text != "") + { + verifizieren_button.IsEnabled = true; + + verbindung_lizenz_server.IsVisible = false; + verbindung_erfolgreich_lizenz_server.IsVisible = false; + verbindung_fehler_lizenz_server.IsVisible = false; + lizenz_prüfung.IsVisible = false; + lizenz_fehler.IsVisible = false; + lizenz_erfolgreich.IsVisible = false; + + } + }; + } + + public void SetAndCheckLizenz(string lizenzKey) + { + LizenzKeyTextBox.Text = lizenzKey; + VerifyKey(); + } + + private void Verifizieren_button_OnClick(object? sender, RoutedEventArgs e) + { + + + if (LizenzKeyTextBox.Text != "") + { + //Animationen.RunSlideAnimation(-60, ueberschrift); + //Animationen.RunSlideAnimation(-120, LizenzKeyTextBox); + //Animationen.FadeOutAnimation(verifizieren_button, 0.3D); + verifizieren_button.IsEnabled = false; + + + + //Animationen.RunSlideAnimation(-100, StatusTextBlock); + VerifyKey(); + } + } + + public async void VerifyKey() + { + + try + { + verbindung_lizenz_server.IsVisible = true; + await Task.Run(KeyAuthApp.init); + + if (!KeyAuthApp.response.success) + { + verbindung_fehler_lizenz_server.IsVisible = true; + } + else + { + verbindung_erfolgreich_lizenz_server.IsVisible = true; + } + + string key = LizenzKeyTextBox.Text; + + lizenz_prüfung.IsVisible = true; + + await Task.Run(() => + { + KeyAuthApp.license(key); + return 0; + }); + + + + if (!KeyAuthApp.response.success) + { + lizenz_fehler.IsVisible = true; + Console.WriteLine(KeyAuthApp.response.message); + + } + else + { + Settings.SettingsSave("LizenzKey", LizenzKeyTextBox.Text); + lizenz_erfolgreich.IsVisible = true; + weiter.IsVisible = true; + } + }catch (Exception ex) + { + Console.WriteLine("error" + ex); + } + } + + + public static api KeyAuthApp = new api( + name: "Valheim Dashboard", // App name - VaultCord.com FREE Discord backup bot for members & your entire server saved from terms and nukes! + ownerid: "sS0sZlXiY5", // Account ID + secret: "6e83db8b463d0a3822b002f8d06dbe51d07c8f0481bda05038291eac5d74eb0f", + version: "1.0" // Application version. Used for automatic downloads see video here https://www.youtube.com/watch?v=kW195PLCBKs + //path: @"Your_Path_Here" // (OPTIONAL) see tutorial here https://www.youtube.com/watch?v=I9rxt821gMk&t=1s + ); + + + public static string[] lizenz_name; + + private void Weiter_Click(object sender, RoutedEventArgs e) + { + + Console.WriteLine("weiter geklickt"); + if (this.Parent.Parent.Parent is MainWindow mainWindow) + { + if(mainWindow.DataContext is MainWindowViewModel mainWindowViewModel) + { + lizenz_name = LizenzKeyTextBox.Text.Split('-'); + + + if (lizenz_name[2] == "A") + { + mainWindowViewModel.SwitchToServerSettings(); + } + else + { + Console.WriteLine(KeyAuthApp.var(lizenz_name[1])); + mainWindowViewModel.SwitchToDashboard(); + } + + } + } + } +} \ No newline at end of file diff --git a/Valheim Dashboard/Views/MainWindow.axaml b/Valheim Dashboard/Views/MainWindow.axaml new file mode 100644 index 0000000..ac12ba1 --- /dev/null +++ b/Valheim Dashboard/Views/MainWindow.axaml @@ -0,0 +1,22 @@ + + + + + + + + + + + + diff --git a/Valheim Dashboard/Views/MainWindow.axaml.cs b/Valheim Dashboard/Views/MainWindow.axaml.cs new file mode 100644 index 0000000..ddaa275 --- /dev/null +++ b/Valheim Dashboard/Views/MainWindow.axaml.cs @@ -0,0 +1,11 @@ +using Avalonia.Controls; + +namespace Valheim_Dashboard.Views; + +public partial class MainWindow : Window +{ + public MainWindow() + { + InitializeComponent(); + } +} \ No newline at end of file diff --git a/Valheim Dashboard/Views/ServerSettingsView.axaml b/Valheim Dashboard/Views/ServerSettingsView.axaml new file mode 100644 index 0000000..5166e38 --- /dev/null +++ b/Valheim Dashboard/Views/ServerSettingsView.axaml @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Valheim Dashboard/Views/ServerSettingsView.axaml.cs b/Valheim Dashboard/Views/ServerSettingsView.axaml.cs new file mode 100644 index 0000000..de44c98 --- /dev/null +++ b/Valheim Dashboard/Views/ServerSettingsView.axaml.cs @@ -0,0 +1,249 @@ +using System; +using System.Diagnostics; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Interactivity; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using Tmds.DBus.Protocol; +using Valheim_Dashboard.ViewModels; + +namespace Valheim_Dashboard.Views; + +public partial class ServerSettingsView : UserControl +{ + + + private TutorialManager _tutorialManager; + + public ServerSettingsView() + { + InitializeComponent(); + + this.Initialized += (sender, e) => + { + var window = this.VisualRoot as Window; + + if (window == null) + throw new InvalidOperationException("Das übergeordnete Element ist kein Fenster."); + + // TutorialManager direkt im Code-Behind initialisieren + _tutorialManager = new TutorialManager(window); + + // Beispiel: Ein Tutorial starten + // StartTutorial(); + }; + } + + public void StartTutorial() + { + var pluginExpander = Plugin; + var pluginIpTextBox = plugin_ip; + var pluginPortTextBox = plugin_port; + var pluginUeberpruefen = plugin_prüfen; + var ftpExpander = FTP; + var ftpIpTextBox = ftp_ip; + var ftpPortTextBox = ftp_port; + var ftpBenutzernameTextBox = ftp_benutzername; + var ftpPasswortTextBox = ftp_passwort; + var ftpUeberpruefen = ftp_prüfen; + + // Schritt 1: Sprechblase anzeigen: Öffnen des Plugin-Expanders oder FTP-Expanders + _tutorialManager.HighlightElement(pluginExpander, new SolidColorBrush(Colors.Yellow)); + _tutorialManager.HighlightElement(ftpExpander, new SolidColorBrush(Colors.Yellow)); + _tutorialManager.ShowSpeechBubble(pluginExpander, TutorialManager.SpeechBubblePosition.Top, Language.GetString("Server_Schritt_1"), () => + { + // Schritt 2: Plugin-Expander öffnen und Sprechblase ändern + _tutorialManager.OpenExpander(pluginExpander); + _tutorialManager.HighlightElement(pluginExpander, new SolidColorBrush(Colors.Transparent)); + _tutorialManager.HighlightElement(ftpExpander, new SolidColorBrush(Colors.Transparent)); + // Beide Felder hervorheben + _tutorialManager.HighlightElement(pluginIpTextBox, new SolidColorBrush(Colors.LightBlue)); + _tutorialManager.HighlightElement(pluginPortTextBox, new SolidColorBrush(Colors.LightBlue)); + + _tutorialManager.ShowSpeechBubble(pluginExpander, TutorialManager.SpeechBubblePosition.Right,Language.GetString("Server_Schritt_2"), () => + { + // Schritt 3: Beispielwerte in IP- und Port-Felder eintragen + pluginIpTextBox.Text = "127.0.0.1"; + pluginPortTextBox.Text = "2456"; + _tutorialManager.HighlightElement(pluginUeberpruefen, new SolidColorBrush(Colors.LightBlue)); + + + + // Nächste Sprechblase: Warten auf Weiter! + _tutorialManager.ShowSpeechBubble(pluginExpander, TutorialManager.SpeechBubblePosition.Right,Language.GetString("Server_Schritt_3"), () => + { + // Schritt 4: Nächste Aktion einleiten (falls notwendig) + _tutorialManager.ClickButton(pluginUeberpruefen); + Task.Delay(2000); + pluginUeberpruefen.Background = new SolidColorBrush(Colors.Green); + pluginUeberpruefen.Content = "Erfolgreich Verbunden!"; + + _tutorialManager.ShowSpeechBubble(ftpExpander, TutorialManager.SpeechBubblePosition.Left, + Language.GetString("Server_Schritt_4"), + () => + { + _tutorialManager.CloseExpander(pluginExpander); + _tutorialManager.HighlightElement(pluginIpTextBox, new SolidColorBrush(Colors.Transparent)); + _tutorialManager.HighlightElement(pluginPortTextBox, new SolidColorBrush(Colors.Transparent)); + _tutorialManager.HighlightElement(pluginUeberpruefen, new SolidColorBrush(Colors.Transparent)); + pluginIpTextBox.Text = ""; + pluginPortTextBox.Text = ""; + pluginUeberpruefen.Background = new SolidColorBrush(Colors.Gray); + pluginUeberpruefen.Content = "Verbindung Prüfen"; + _tutorialManager.OpenExpander(ftpExpander); + _tutorialManager.HighlightElement(ftpIpTextBox, new SolidColorBrush(Colors.LightBlue)); + _tutorialManager.HighlightElement(ftpPortTextBox, new SolidColorBrush(Colors.LightBlue)); + _tutorialManager.HighlightElement(ftpBenutzernameTextBox, new SolidColorBrush(Colors.LightBlue)); + _tutorialManager.HighlightElement(ftpPasswortTextBox, new SolidColorBrush(Colors.LightBlue)); + + _tutorialManager.ShowSpeechBubble(ftpExpander, TutorialManager.SpeechBubblePosition.Left, + Language.GetString("Server_Schritt_5"), + async () => + { + + _tutorialManager.WriteText(ftpIpTextBox, "127.0.0.1"); + _tutorialManager.WriteText(ftpPortTextBox, "21"); + _tutorialManager.WriteText(ftpBenutzernameTextBox, "ftpUser"); + _tutorialManager.WriteText(ftpPasswortTextBox, "123456789"); + + await _tutorialManager.SmoothScrollToControl(ftp_scroll, ftpUeberpruefen); + Task.Delay(2000); + + _tutorialManager.ClickButton(ftpUeberpruefen); + ftpUeberpruefen.Background = new SolidColorBrush(Colors.Green); + ftpUeberpruefen.Content = "Verbindung Erfolgreich"; + + _tutorialManager.ShowSpeechBubble(ftpExpander, + TutorialManager.SpeechBubblePosition.Left, + Language.GetString("Server_Schritt_6"), + () => + { + + + + }); + + }); + + }); + }); + }); + }); + } + private void Weiter_OnClick(object? sender, RoutedEventArgs e) + { + if (this.Parent.Parent.Parent is MainWindow mainWindow) { + if (mainWindow.DataContext is MainWindowViewModel mainWindowViewModel) + { + + mainWindowViewModel.SwitchToFTP(ftpClient); + + } + } + } + + public class DataPluginJson + { + public string ModVersion { get; set; } + public string PluginVersion { get; set; } + public string HashPlugins { get; set; } + public string HashConfig { get; set; } + public string HashClientSide { get; set; } + public string OldConfigFiles { get; set; } + public string OldConfigFolder { get; set; } + public string OldConfigFolderFiles { get; set; } + public string OldPluginFiles { get; set; } + public string OldPluginFolder { get; set; } + public string OldPluginFolderFiles { get; set; } + public string ConfigFilestoDelete { get; set; } + public string ConfigFoldertoDelete { get; set; } + public string ConfigFolderFilestoDelete { get; set; } + public string PluginFilestoDelete { get; set; } + public string PluginFoldertoDelete { get; set; } + public string PluginFolderFilestoDelete { get; set; } + public string OldClientSideConfigFiles { get; set; } + public string OldClientSideConfigFolder { get; set; } + public string OldClientSideConfigFolderFiles { get; set; } + public string OldClientSidePluginFiles { get; set; } + public string OldClientSidePluginFolder { get; set; } + public string OldClientSidePluginFolderFiles { get; set; } + public string ClientSideConfigFilestoDelete { get; set; } + public string ClientSideConfigFoldertoDelete { get; set; } + public string ClientSideConfigFolderFilestoDelete { get; set; } + public string ClientSidePluginFilestoDelete { get; set; } + public string ClientSidePluginFoldertoDelete { get; set; } + public string ClientSidePluginFolderFilestoDelete { get; set; } + } + + + private async void Plugin_prüfen_OnClick(object? sender, RoutedEventArgs e) + { + + HttpClient PluginClient = new HttpClient(); + + try + { + var response = await PluginClient.GetAsync("http://amp.tbs-server.de:2456"); + if (response.IsSuccessStatusCode) + { + var data = await response.Content.ReadFromJsonAsync(); + plugin_prüfen.Background = new SolidColorBrush(Colors.Green); + plugin_prüfen.Content = "Verbindung Erfolgreich"; + Debug.WriteLine(data.ModVersion); + }else + { + plugin_prüfen.Background = new SolidColorBrush(Colors.Red); + plugin_prüfen.Content = "Verbindung Fehlgeschlagen"; + } + + } + catch (Exception ex) + { + + plugin_prüfen.Background = new SolidColorBrush(Colors.Red); + plugin_prüfen.Content = "Verbindung Fehlgeschlagen"; + + } + + + } + + private FtpClient ftpClient; + private async void Ftp_prüfen_OnClick(object? sender, RoutedEventArgs e) + { + try + {Console.WriteLine(ftp_ip.Text + ftp_port.Text + ftp_benutzername.Text + ftp_passwort.Text); + + //ftpClient = new FtpClient("ftp://"+ ftp_ip.Text + ":" +ftp_port.Text, ftp_benutzername.Text, ftp_passwort.Text); + FtpViewModel._ftpClient = new FtpClient("ftp://192.168.178.34:21", "tbs_ftp", "JLI_._nTH-DyG53Se9"); + var files = await ftpClient.ListDirectoryDetailsAsync(); + + if (files != null && files.Count > 0) + { + var name = "tbs"; + ftp_prüfen.Background = new SolidColorBrush(Colors.Green); + ftp_prüfen.Content = "Verbindung Erfolgreich1"; + Console.WriteLine(files); + LizenzView.KeyAuthApp.webhook("aHtrWbrxrZ", "&name="+ LizenzView.lizenz_name[1] +"&data=testabc", ""); + Console.WriteLine(LizenzView.KeyAuthApp.response.message); + + } + else + { + ftp_prüfen.Background = new SolidColorBrush(Colors.Green); + ftp_prüfen.Content = "Verbindung Erfolgreich2"; + } + } + catch (Exception ex) + { + Console.WriteLine($"Fehler beim Verbinden: {ex.Message}"); + } + + } +} \ No newline at end of file diff --git a/Valheim Dashboard/app.manifest b/Valheim Dashboard/app.manifest new file mode 100644 index 0000000..4eda616 --- /dev/null +++ b/Valheim Dashboard/app.manifest @@ -0,0 +1,18 @@ + + + + + + + + + + + + + +