123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622 |
- using Avalonia.Controls.ApplicationLifetimes;
- using ReactiveUI;
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Diagnostics;
- using System.IO;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using VeloeMinecraftLauncher.Entity.LauncherProfiles;
- using VeloeMinecraftLauncher.Entity.VersionManifest;
- using VeloeMinecraftLauncher.MinecraftLauncher;
- using VeloeMinecraftLauncher.Views;
- using System;
- using System.Threading.Tasks;
- using System.Windows;
- using Microsoft.AspNetCore.SignalR.Client;
- using VeloeMinecraftLauncher.Entity.McStatus;
- using System.Timers;
- using System.ComponentModel;
- using System.Reflection;
- using Serilog;
- using Serilog.Events;
- using Serilog.Formatting;
- using Avalonia.Controls;
- using Avalonia.Threading;
- namespace VeloeMinecraftLauncher.ViewModels
- {
- public class MainWindowViewModel : ViewModelBase
- {
- public MainWindowViewModel()
- {
- //creating logger
- EventSink eventSink = new(null);
- eventSink.DataReceived += LogHandler;
- logger = new LoggerConfiguration()
- .MinimumLevel.Debug()
- .WriteTo.Sink(eventSink)
- .WriteTo.File("launcher.log", LogEventLevel.Debug, fileSizeLimitBytes: 100000000)// restricted... is Optional
- .CreateLogger();
- Settings.logger = logger;
- //loading settings
- logger.Debug("Loading settings.");
- Settings.LoadSettings();
- username = Settings.Username;
- //loading local verions
- logger.Debug("Loading local versions.");
- updateAvailable();
- //check launcher update
- logger.Debug("Checking launcher versions updates.");
- latestLauncherInfo = Downloader.DownloadAndDeserializeJsonData<LatestLauncherVersion>("https://files.veloe.link/launcher/update/versions.json");
- if (latestLauncherInfo is not null)
- {
- logger.Debug("Launcher version on server: {0}", latestLauncherInfo.latest);
- logger.Debug("Launcher version: {0}", Assembly.GetExecutingAssembly().GetName().Version);
- string[] version = latestLauncherInfo.latest.Split('.');
- var vat = Assembly.GetExecutingAssembly().GetName().Version;
- if (Int16.Parse(version[0]) > Assembly.GetExecutingAssembly().GetName().Version.Major ||
- Int16.Parse(version[1]) > Assembly.GetExecutingAssembly().GetName().Version.Minor ||
- Int16.Parse(version[2]) > Assembly.GetExecutingAssembly().GetName().Version.Build ||
- Int16.Parse(version[3]) > Assembly.GetExecutingAssembly().GetName().Version.Revision)
- {
- logger.Debug("Update available!");
- IsUpdateAvailable = true;
- }
- }
- logger.Debug("Connecting to WebSoket");
- //conection to my servers
- connection = new HubConnectionBuilder()
- .WithUrl("https://monitor.veloe.link/hubs/data")
- .WithAutomaticReconnect()
- .Build();
- Func<Exception, Task> reconnecting = ex => Task.Run(() => {
- logger.Warning("Reconnecting to WebCoket...");
- });
- Func<string, Task> reconnected = str => Task.Run(() => {
- logger.Warning("Reconnected to WebCoket.");
- connection.InvokeAsync("ConnectToGroup", "McTFC");
- connection.InvokeAsync("ConnectToGroup", "McVanilla");
- connection.InvokeAsync("ConnectToGroup", "McTech");
- });
- connection.Reconnecting += reconnecting;
- connection.Reconnected += reconnected;
- connection.On<string>("UpdateMcTFC", (message) =>
- {
- McStatus status = JsonSerializer.Deserialize<McStatus>(message);
- McTfcBlock = $"McTFC: Online {status.NumPlayers}/{status.MaxPlayers}";
- mcTfcTimer.Stop();
- mcTfcTimer.Start();
- //ConsoleText += message;
- });
- connection.On<string>("UpdateMcVanilla", (message) =>
- {
- McStatus status = JsonSerializer.Deserialize<McStatus>(message);
- McTfcBlock = $"McVanilla: Online {status.NumPlayers}/{status.MaxPlayers}";
- mcTechTimer.Stop();
- mcTechTimer.Start();
- //ConsoleText += message;
- });
- connection.On<string>("UpdateMcTech", (message) =>
- {
- McStatus status = JsonSerializer.Deserialize<McStatus>(message);
- McTfcBlock = $"McTech: Online {status.NumPlayers}/{status.MaxPlayers}";
- mcVanillaTimer.Stop();
- mcVanillaTimer.Start();
- //ConsoleText += message;
- });
- mcTfcTimer.Elapsed += OnTimedEventMcTfc;
- mcTfcTimer.Start();
- mcTechTimer.Elapsed += OnTimedEventMcTech;
- mcTechTimer.Start();
- mcVanillaTimer.Elapsed += OnTimedEventMcVanilla;
- mcVanillaTimer.Start();
- connection.StartAsync();
- connection.InvokeAsync("ConnectToGroup", "McTFC");
- connection.InvokeAsync("ConnectToGroup", "McVanilla");
- connection.InvokeAsync("ConnectToGroup", "McTech");
- consoleOutputTimer.Elapsed += UpdateConsoleOutput;
- consoleOutputTimer.AutoReset = false;
- }
- int i = 0;
- System.Timers.Timer mcTfcTimer = new System.Timers.Timer(30000);
- System.Timers.Timer mcTechTimer = new System.Timers.Timer(30000);
- System.Timers.Timer mcVanillaTimer = new System.Timers.Timer(30000);
- System.Timers.Timer consoleOutputTimer = new(250);
- private HubConnection connection;
- private string downloadButton = "Download versions";
- private string startButton = "Start Minecraft";
- private string username;
- private StringBuilder consoleText = new StringBuilder();
- private int downloadedIndex;
- private string argumentsBox;
- private bool isNoGameRunning = true;
- private bool isUpdateAvailable = false;
- private string settingsButton = "Settings";
- private string mcTfcBlock = "Wait for update...";
- private string mcTechBlock = "Wait for update...";
- private string mcVanillaBlock = "Wait for update...";
- ILogger logger;
- LatestLauncherVersion latestLauncherInfo;
- DownloadedVerion downloadedVersion;
- ObservableCollection<DownloadedVerion> downloadedVersions;
- public ObservableCollection<DownloadedVerion> DownloadedVersions {
- get => downloadedVersions;
- set
- {
- this.RaiseAndSetIfChanged(ref downloadedVersions, value);
- }
- }
- public DownloadedVerion DownloadedVerion
- {
- get => downloadedVersion;
- set
- {
- this.RaiseAndSetIfChanged(ref downloadedVersion, value);
- //Settings.lastChosenVersion = value.version;
- //logger.Debug("Version choosen: {0}",value.version);
- //logger.Debug("Version json: {0}", value.path);
- }
- }
- public int DownloadedIndex
- {
- get => downloadedIndex;
- set
- {
- this.RaiseAndSetIfChanged(ref downloadedIndex, value);
- if (value >= 0 && value < DownloadedVersions.Count)
- DownloadedVerion = DownloadedVersions[value];
- }
- }
- public string Greeting => "Welcome to Cringe Launcher!";
- public string DownloadButton {
- get => downloadButton;
- set
- {
- this.RaiseAndSetIfChanged(ref downloadButton, value);
- }
- }
- public string StartButton
- {
- get => startButton;
- set
- {
- this.RaiseAndSetIfChanged(ref startButton, value);
- }
- }
- public string Username
- {
- get => username;
- set => this.RaiseAndSetIfChanged(ref username, value);
- }
- public string ConsoleText
- {
- get
- {
- if (consoleText.Length < UInt16.MaxValue)
- return consoleText.ToString();
- else
- return consoleText.ToString(consoleText.Length - UInt16.MaxValue, UInt16.MaxValue);
- }
- set
- {
- consoleText.Clear();
- consoleText.Append(value);
- this.RaisePropertyChanged(nameof(ConsoleText));
- ConsoleTextCaretIndex = int.MaxValue;
- }
- }
- public string ArgumentsBox
- {
- get => argumentsBox;
- set
- {
- this.RaiseAndSetIfChanged(ref argumentsBox, value);
- }
- }
- public string SettingsButton
- {
- get => settingsButton;
- set
- {
- this.RaiseAndSetIfChanged(ref settingsButton, value);
- }
- }
- public bool IsNoGameRunning
- {
- get => isNoGameRunning;
- set
- {
- this.RaiseAndSetIfChanged(ref isNoGameRunning, value);
- }
- }
- public bool IsUpdateAvailable
- {
- get => isUpdateAvailable;
- set
- {
- this.RaiseAndSetIfChanged(ref isUpdateAvailable, value);
- }
- }
- public string McTfcBlock
- {
- get => mcTfcBlock;
- set
- {
- this.RaiseAndSetIfChanged(ref mcTfcBlock, value);
- }
- }
- public string McTechBlock
- {
- get => mcTechBlock;
- set
- {
- this.RaiseAndSetIfChanged(ref mcTechBlock, value);
- }
- }
- public string McVanillaBlock
- {
- get => mcVanillaBlock;
- set
- {
- this.RaiseAndSetIfChanged(ref mcVanillaBlock, value);
- }
- }
- public int ConsoleTextCaretIndex
- {
- get { return int.MaxValue; }
- set
- {
- this.RaisePropertyChanged(nameof(ConsoleTextCaretIndex));
- }
- }
- public void OnClickCommand()
- {
- var versionsDownloader = new VersionsDownloader { DataContext = new VersionsDownloaderViewModel() };
-
- if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- {
- //var versionsDownloaderTask =
- versionsDownloader.Closed += updateAvailable;
- versionsDownloader.ShowDialog(desktop.MainWindow);
- //versionsDownloaderTask.Wait();
-
- }
- }
- public void StartMinecraft()
- {
- logger.Debug("Starting minecraft.");
- if (DownloadedVerion is null)
- return;
- int version = 0;
- //var verionJsonFileStream = File.OpenRead(DownloadedVerion.path);
- using (StreamReader reader = new StreamReader(DownloadedVerion.path))
- {
- string json = reader.ReadToEnd();
- var versionJson = JsonSerializer.Deserialize<Entity.Version.Version>(json);
- string arguments = StartCommandBuilder.Build(versionJson, Username);
- if (!Settings.useCustomJava)
- {
- if (versionJson.javaVersion != null)
- {
- logger.Debug("Java version required: {0}", versionJson.javaVersion.majorVersion);
- version = versionJson.javaVersion.majorVersion;
- }
- else
- {
- if (versionJson.inheritsFrom != null)
- {
- using (StreamReader inheritsFromReader = new StreamReader(Settings.MinecraftForlderPath + "versions/" + versionJson.inheritsFrom + "/" + versionJson.inheritsFrom + ".json"))
- {
- string jsonInheritsFrom = inheritsFromReader.ReadToEnd();
- var inheritsFromJson = JsonSerializer.Deserialize<Entity.Version.Version>(jsonInheritsFrom);
- if (inheritsFromJson.javaVersion != null)
- {
- logger.Debug("Java version required: {0}", inheritsFromJson.javaVersion.majorVersion);
- version = inheritsFromJson.javaVersion.majorVersion;
- }
- }
- }
- }
- }
-
- ConsoleText += arguments;
- ArgumentsBox = arguments;
- }
- if (DownloadedVerion is null)
- return;
- string javaPath = Settings.JavaPath;
- if (!Settings.useCustomJava)
- javaPath = Settings.MinecraftForlderPath + "javaruntime/" + version + "/bin/java.exe";
- logger.Debug("Java version path: {0}", javaPath);
- logger.Debug("Minecraft arguments: {0}", ArgumentsBox);
- ProcessStartInfo proc;
- proc = new ProcessStartInfo
- {
- UseShellExecute = false,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- WindowStyle = ProcessWindowStyle.Hidden,
- CreateNoWindow = true,
- FileName = System.IO.Path.Combine(Settings.MinecraftForlderPath, javaPath),
- StandardErrorEncoding = Encoding.UTF8,
- WorkingDirectory = Settings.MinecraftForlderPath,
- Arguments = ArgumentsBox
- };
- Process minecraft = new Process();
- minecraft.StartInfo = proc;
- Task.Run(() =>
- {
- logger.Debug("Starting java process.");
-
- minecraft.OutputDataReceived += OutputHandler;
- minecraft.ErrorDataReceived += OutputHandler;
- //minecraft.Exited += ProcessExited; //dont work properly
- //* Start process and handlers
- //minecraft.WaitForExit();
- minecraft.Start();
- minecraft.BeginOutputReadLine();
- minecraft.BeginErrorReadLine();
- if (!Settings.gameLogToLauncher)
- {
- minecraft.OutputDataReceived -= OutputHandler;
- minecraft.CancelOutputRead();
- }
- return Task.CompletedTask;
- });
- logger.Debug("Updating Username in Settings");
- Settings.Username = username;
- Settings.lastChosenVersion = DownloadedVerion.version;
- Settings.SaveSettings();
- }
- void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
- {
- //Todo create multiple TextBlocks if char limit
- if (!consoleOutputTimer.Enabled)
- {
- consoleOutputTimer.Stop();
- consoleOutputTimer.Start();
- }
- consoleText.Append(outLine.Data + "\n");
- }
- void LogHandler(object sendingProcess, EventArgs args)
- {
- if (!consoleOutputTimer.Enabled)
- {
- consoleOutputTimer.Stop();
- consoleOutputTimer.Start();
- }
- consoleText.Append(((MyEventArgs)args).Data);
- }
- void UpdateConsoleOutput(Object source, ElapsedEventArgs e)
- {
- this.RaisePropertyChanged(nameof(ConsoleText));
- ScrollToEnd("ConsoleScroll");
- }
- void ScrollToEnd(string ScrollName)
- {
- if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- {
- Dispatcher.UIThread.InvokeAsync(() =>
- {
- var scroll = desktop.MainWindow.GetControl<ScrollViewer>("ConsoleScroll");
- scroll.ScrollToEnd();
- });
- }
- }
- //dont work properly
- void ProcessExited(object sendingProcess, EventArgs e)
- {
- IsNoGameRunning = true;
- ((Process)sendingProcess).Dispose();
- }
- public void updateAvailable()
- {
- if (DownloadedVersions is null)
- DownloadedVersions = new();
- DownloadedVersions.Clear();
- DirectoryInfo versions = new( Settings.MinecraftForlderPath + "versions");
- try
- {
- var dirs = versions.GetDirectories("*", SearchOption.TopDirectoryOnly);
- LauncherProfiles profiles = new LauncherProfiles();
- profiles.selectedProfile = "NotImplemented";
- foreach (var dir in dirs)
- {
- string checkedPath;
- if (File.Exists(checkedPath = dir.FullName + "\\" + dir.Name + ".json"))
- {
- DownloadedVersions.Add(new DownloadedVerion() { path = checkedPath, version = dir.Name });
- profiles.profiles.Add($"Version {dir.Name}", new Profile() { name = dir.Name, lastVersionId = dir.Name, launcherVisibilityOnGameClose = "keep the launcher open" });
- }
- }
- if (Settings.lastChosenVersion != null)
- {
- DownloadedIndex = 0;
- for (int i = 0; i < DownloadedVersions.Count; i++)
- {
- if (DownloadedVersions[i].version == Settings.lastChosenVersion)
- {
- DownloadedIndex = i;
- break;
- }
- }
-
- }
- if (!File.Exists(Settings.MinecraftForlderPath + "launcher_profiles.json"))
- {
- var file = File.Create(Settings.MinecraftForlderPath + "launcher_profiles.json");
- file.Close();
- file.Dispose();
- }
- var lpString = JsonSerializer.Serialize(profiles);
- File.WriteAllText(Settings.MinecraftForlderPath + "launcher_profiles.json", lpString);
- }
- catch (DirectoryNotFoundException ex)
- {
- Directory.CreateDirectory(Settings.MinecraftForlderPath + "versions");
- return;
- }
-
- }
- public void updateAvailable(object sendingObject, EventArgs e)
- {
- updateAvailable();
- switch (sendingObject)
- {
- case VersionsDownloader:
- ((VersionsDownloader)sendingObject).Closed -= updateAvailable;
- break;
- case SettingsWindow:
- ((SettingsWindow)sendingObject).Closed -= updateAvailable;
- break;
- }
-
- }
- void OpenSettings()
- {
- var settingsWindow = new SettingsWindow { DataContext = new SettingsWindowViewModel() };
- if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- {
- //var versionsDownloaderTask =
- settingsWindow.Closed += updateAvailable;
- settingsWindow.ShowDialog(desktop.MainWindow);
- //versionsDownloaderTask.Wait();
- //updateAvailable();
- }
- }
- public void DownloadUpdate()
- {
- logger.Debug("Started updater.exe");
- Process updater = new Process();
- updater.StartInfo.FileName = "updater.exe";
- updater.Start();
- if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- {
- //var versionsDownloaderTask =
- desktop.MainWindow.Close();
- //versionsDownloaderTask.Wait();
- //updateAvailable();
- }
- }
- private void OnTimedEventMcTfc(Object source, ElapsedEventArgs e)
- {
- McTfcBlock = "McTFC: Offline";
- }
- private void OnTimedEventMcTech(Object source, ElapsedEventArgs e)
- {
- McTechBlock = "McTech: Offline";
- }
- private void OnTimedEventMcVanilla(Object source, ElapsedEventArgs e)
- {
- McVanillaBlock = "McVanilla: Offline";
- }
- }
-
- public class LatestLauncherVersion
- {
- public string latest { get; set; }
- public string url { get; set; }
- }
- public class DownloadedVerion
- {
- public string path;
- public string version;
- public override string ToString()
- {
- return version;
- }
- }
-
- }
|